Skip to content

Instantly share code, notes, and snippets.

@jukkatupamaki
Last active January 18, 2022 21:43
Show Gist options
  • Save jukkatupamaki/45317518687d9fb20b86ccfe6a170614 to your computer and use it in GitHub Desktop.
Save jukkatupamaki/45317518687d9fb20b86ccfe6a170614 to your computer and use it in GitHub Desktop.
How to use check constraints with Knex.js and Postgres

How to use check constraints with Knex.js and Postgres

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
`)
@Epicnessism
Copy link

Epicnessism commented Nov 19, 2021

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:

exports.up = async function(knex) {
    await knex.schema.createTable('table_name', table => {
        table.increments('id');
     ....rest of table code here
    })
    return knex.schema.raw('
        ALTER TABLE
        tournaments
        ADD CONSTRAINT
          constraint_name
        CHECK
          your_check_operator_here = true
      ')
      };
  
  exports.down = function(knex) {
    return knex.schema.dropTable('table_name');
  };

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment