1

So I want to drop a constraint using Knex.js, but I need to check if the constraint is present before I do this. I haven't found a way yet. Anyone have an idea?

Here's my function:

async alterTable_dropConstraint(tableName, constraintDropped) {
    return await knex.schema.raw(`ALTER TABLE ${tableName} DROP CONSTRAINT ${constraintDropped}`);
}

Answer (or the code that worked for me): Add 'IF EXISTS'

async alterTable_dropConstraint(tableName, constraintDropped) {
    return await knex.schema.raw(`ALTER TABLE ${tableName} DROP CONSTRAINT IF EXISTS ${constraintDropped}`);
}
Huckleberry Carignan
  • 2,002
  • 4
  • 17
  • 33
  • Is this helps? https://stackoverflow.com/questions/2499332/how-to-check-if-a-constraint-exists-in-sql-server – felixmosh Apr 14 '20 at 21:58
  • After reading that link, I tried adding: a chec: knex.schema.raw(`SELECT 1 FROM ${tableName} WHERE CONSTRAINT_TYPE='UNIQUE' AND CONSTRAINT = ${constraintDropped}`) - but that didn't help. It finds it when it is not available. – Huckleberry Carignan Apr 15 '20 at 15:48

0 Answers0