Reputation: 1256
I'm using Knex.js. I'd like to create a unique index for my table with WHERE clause:
db.schema.createTable('newTable', function(t) {
t.increments()
t.string('col1').defaultTo(null)
t.string('col2').notNullable()
t.integer('col3').notNullable()
t.unique(['col1', 'col2', 'col3']).whereNotNull('col1')
t.unique(['col2', 'col3']).whereNull('col1')
})
I try to create two partial indexes for the table. However, whereNotNull
is not chainable with unique
function. How to create a unique index with 'where' clause?
Upvotes: 3
Views: 7428
Reputation: 176
With this merged, now in order create unique index in knex we can do
db.schema.createTable('newTable', function(t) {
t.increments()
t.string('col1').defaultTo(null)
t.string('col2').notNullable()
t.integer('col3').notNullable()
t.unique(['col1', 'col2', 'col3'], {
useConstraint: false,
predicate: knex.whereNotNull('col1')
})
t.unique(['col2', 'col3'], {
useConstraint: false,
predicate: knex.whereNull('col1')
})
})
Upvotes: 0
Reputation: 1177
one can use below syntax to create index with conditions
knex.table('users', function (table)
{
table.index(['name', 'last_name'], 'idx_name_last_name', {
indexType: 'FULLTEXT',
storageEngineIndexType: 'hash',
predicate: knex.whereNotNull('email'),
});
});
or
knex.table('users', function (table)
{
table.index(['name', 'last_name'], 'idx_name_last_name', {
indexType: 'unique',
storageEngineIndexType: 'hash',
predicate: knex.whereRaw('email=false'),
});
});
extra example
Upvotes: 0
Reputation: 225
Try this:
knex.schema.raw(
`CREATE UNIQUE INDEX "unique_partial_newTable_col1_col2_col3" ON "newTable" ("col1", "col2", "col3") WHERE "col1" IS NOT NULL`
);
knex.schema.raw(
`CREATE UNIQUE INDEX "unique_partial_newTable_col2_col3" ON "newTable" ("col2", "col3") WHERE "col1" IS NULL`
);
Upvotes: 8
Reputation: 19718
Partial index is not yet supported. There is PR which is not ready yet though https://github.com/tgriesser/knex/pull/2401.
For now one has to use knex.schema.raw for it.
Upvotes: 6