From c6764a77700c17a134cb945e4e2288173064ae31 Mon Sep 17 00:00:00 2001 From: Maksim Sitnikov Date: Mon, 26 Feb 2024 14:29:18 +0300 Subject: [PATCH] Add foreign key (entry_id, tenant_id) for favorites (#79) --- ...ites_add_entry_id_tenant_id_foreign_key.ts | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/db/migrations/20240224171740_favorites_add_entry_id_tenant_id_foreign_key.ts diff --git a/src/db/migrations/20240224171740_favorites_add_entry_id_tenant_id_foreign_key.ts b/src/db/migrations/20240224171740_favorites_add_entry_id_tenant_id_foreign_key.ts new file mode 100644 index 00000000..002175b1 --- /dev/null +++ b/src/db/migrations/20240224171740_favorites_add_entry_id_tenant_id_foreign_key.ts @@ -0,0 +1,33 @@ +import {Knex} from 'knex'; + +export async function up(knex: Knex): Promise { + return knex.raw(` + ALTER TABLE favorites DROP CONSTRAINT favorites_entries_id; + + ALTER TABLE favorites DROP CONSTRAINT favorites_tenant_id_ref; + + ALTER TABLE entries + ADD CONSTRAINT entries_uniq_entry_id_tenant_id_constraint UNIQUE(entry_id, tenant_id); + + ALTER TABLE favorites + ADD CONSTRAINT favorites_entry_id_tenant_id_ref FOREIGN KEY (entry_id, tenant_id) + REFERENCES entries(entry_id, tenant_id) ON DELETE CASCADE ON UPDATE CASCADE; + `); +} + +export async function down(knex: Knex): Promise { + return knex.raw(` + ALTER TABLE favorites DROP CONSTRAINT favorites_entry_id_tenant_id_ref; + + ALTER TABLE entries DROP CONSTRAINT entries_uniq_entry_id_tenant_id_constraint; + + ALTER TABLE favorites + ADD CONSTRAINT favorites_tenant_id_ref FOREIGN KEY (tenant_id) + REFERENCES tenants(tenant_id) ON UPDATE CASCADE ON DELETE CASCADE; + + ALTER TABLE favorites + ADD CONSTRAINT favorites_entries_id FOREIGN KEY (entry_id) + REFERENCES entries(entry_id) + ON DELETE CASCADE; + `); +}