Check constraints are useful for validating INSERT and UPDATE queries. With Knex.js, you have to use raw
calls to add or drop constraints.
Add a constraint to check that my_column
in my_table
is at least 0:
knex.schema.raw(`
ALTER TABLE
my_table
ADD CONSTRAINT
my_column_is_at_least_0
CHECK
(my_column >= 0)
`)
Drop the above constraint (e.g. in a "down" migration):
knex.schema.raw(`
ALTER TABLE my_table
DROP CONSTRAINT my_column_is_at_least_0
`)
for anyone who got stuck trying to figure out how to integrate this with a migration file like me, if you have a migration file structured like so:
This worked for me, although I ended up not needing it. Idk if this is the best or correct way, but it seemed to work. I was able to test an insert and get a constraint failed error.