Skip to content

Commit

Permalink
feat: expose knex query builder instance in schema classes
Browse files Browse the repository at this point in the history
Schema builder queries are directly handled by Knex and therefore schema
properties that needs access to the query builder should use the knex
query builder

Closes: #832
  • Loading branch information
thetutlage committed May 8, 2022
1 parent 1b6001d commit dff3f84
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions adonis-typings/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ declare module '@ioc:Adonis/Lucid/Schema' {
db: QueryClientContract
schema: Knex.SchemaBuilder
now(precision?: number): Knex.Raw
knex(): Knex.QueryBuilder
raw(sql: string, bindings?: RawQueryBindings): Knex.Raw
defer: (cb: DeferCallback) => void
up(): Promise<void> | void
Expand Down
7 changes: 7 additions & 0 deletions src/Schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,13 @@ export class Schema implements SchemaContract {
return this.db.knexRawQuery(query, bindings)
}

/**
* Get access to the underlying knex query builder
*/
public knex() {
return this.db.knexQuery()
}

/**
* Wrapping database calls inside defer ensures that they run
* in the right order and also they won't be executed when
Expand Down
32 changes: 32 additions & 0 deletions test/migrations/schema.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,4 +350,36 @@ test.group('Schema', (group) => {
await db.connection().schema.dropTable('schema_accounts')
await db.connection().schema.dropTable('schema_users')
})

test('define index predicate as knex query', async ({ assert }) => {
class UsersSchema extends getBaseSchema() {
public up() {
this.schema.createTable('users', (table) => {
table.increments('id')
table.index(['name', 'last_name'], 'idx_name_last_name', {
indexType: 'FULLTEXT',
storageEngineIndexType: 'hash',
predicate: this.knex().whereNotNull('email'),
})
})
}
}

const schema = new UsersSchema(db.connection(), 'users.ts', true)
const queries = await schema.execUp()

const knexSchema = db
.connection()
.schema.createTable('users', (table) => {
table.increments('id')
table.index(['name', 'last_name'], 'idx_name_last_name', {
indexType: 'FULLTEXT',
storageEngineIndexType: 'hash',
predicate: db.connection().knexQuery().whereNotNull('email'),
})
})
.toQuery()

assert.deepEqual(queries, [knexSchema])
})
})

0 comments on commit dff3f84

Please sign in to comment.