diff --git a/changelogs/drizzle-kit/0.32.3.md b/changelogs/drizzle-kit/0.32.3.md new file mode 100644 index 0000000000..d81a448616 --- /dev/null +++ b/changelogs/drizzle-kit/0.32.3.md @@ -0,0 +1,3 @@ +### PostgreSQL bug fix + +Foreign-key removals now use `DROP CONSTRAINT IF EXISTS`. This prevents generated migrations from failing when an earlier `DROP TABLE ... CASCADE` already removed the same constraint. diff --git a/drizzle-kit/package.json b/drizzle-kit/package.json index 9e24f04927..975d9926f4 100644 --- a/drizzle-kit/package.json +++ b/drizzle-kit/package.json @@ -1,6 +1,6 @@ { "name": "@drizzle-team/drizzle-kit", - "version": "0.32.1", + "version": "0.32.3", "homepage": "https://orm.drizzle.team", "keywords": [ "drizzle", diff --git a/drizzle-kit/src/sqlgenerator.ts b/drizzle-kit/src/sqlgenerator.ts index 3b88cde67a..c63981ad8a 100644 --- a/drizzle-kit/src/sqlgenerator.ts +++ b/drizzle-kit/src/sqlgenerator.ts @@ -3476,7 +3476,7 @@ class PgDeleteForeignKeyConvertor extends Convertor { ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`; - return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${name}";\n`; + return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT IF EXISTS "${name}";\n`; } } diff --git a/drizzle-kit/tests/pg-tables.test.ts b/drizzle-kit/tests/pg-tables.test.ts index 4ca01f1fe7..a9c47eea62 100644 --- a/drizzle-kit/tests/pg-tables.test.ts +++ b/drizzle-kit/tests/pg-tables.test.ts @@ -753,6 +753,28 @@ test('alter composite primary key', async () => { ]); }); +test('drop foreign key constraint idempotently', async () => { + const users = pgTable('users', { + id: integer('id').primaryKey(), + }); + const postsFrom = pgTable('posts', { + userId: integer('user_id').references(() => users.id), + }); + const postsTo = pgTable('posts', { + userId: integer('user_id'), + }); + + const { sqlStatements } = await diffTestSchemas( + { users, posts: postsFrom }, + { users, posts: postsTo }, + [], + ); + + expect(sqlStatements).toStrictEqual([ + 'ALTER TABLE "posts" DROP CONSTRAINT IF EXISTS "posts_user_id_users_id_fk";\n', + ]); +}); + test('add index with op', async () => { const from = { users: pgTable('users', {