Skip to content

Commit ce924be

Browse files
chris-kobrzakSAMIBETTAYEB
authored andcommitted
Defensively drop constraints during migrations
When `PostgreSQL.prototype.getDropForeignKeys` gets called with duplicated foreign keys, an invalid `ALTER TABLE` statement gets created. This is because the duplicates are mapped to multiple `DROP CONSTRAINT fk_key` SQL actions, e.g.: ```sql -- This will throw an error ALTER TABLE "public"."foo" DROP CONSTRAINT "fk_duplicatedKey", DROP CONSTRAINT "fk_duplicatedKey", DROP CONSTRAINT "fk_duplicatedKey", DROP CONSTRAINT "fk_otherKey" ``` As the `DROP CONSTRAINT` actions are run sequentially, when the first action gets executed by PostgreSQL, the next one (for the same, but already dropped key) will not cause an SQL error thanks to the added IF EXISTS check: ```sql -- This is valid SQL ALTER TABLE "public"."foo" DROP CONSTRAINT IF EXISTS "fk_duplicatedKey", DROP CONSTRAINT IF EXISTS "fk_duplicatedKey", DROP CONSTRAINT IF EXISTS "fk_duplicatedKey", DROP CONSTRAINT IF EXISTS "fk_otherKey" ``` Please note, this is really a hack and we still need to understand why the method in question gets called with duplicated foreign keys in certain conditions. Signed-off-by: Chris Kobrzak <[email protected]> Signed-off-by: SAMI BETTAYEB <[email protected]>
1 parent bf6067e commit ce924be

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

lib/migration.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -586,7 +586,7 @@ function mixinMigration(PostgreSQL) {
586586
}
587587

588588
if (needsToDrop) {
589-
sql.push('DROP CONSTRAINT ' + self.escapeName(fk.fkName));
589+
sql.push('DROP CONSTRAINT IF EXISTS ' + self.escapeName(fk.fkName));
590590
removedFks.push(fk); // keep track that we removed these
591591
}
592592

0 commit comments

Comments
 (0)