From 49828a926e245181f79eb6b25b434b4708a3e706 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Dubigny?= Date: Thu, 17 Oct 2024 02:37:06 +0200 Subject: [PATCH] refactor: remove duplicated non verified email domains --- ...add-null-not-distinct-to-email-domains.cjs | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 migrations/1729121498808_add-null-not-distinct-to-email-domains.cjs diff --git a/migrations/1729121498808_add-null-not-distinct-to-email-domains.cjs b/migrations/1729121498808_add-null-not-distinct-to-email-domains.cjs new file mode 100644 index 00000000..6ea6f527 --- /dev/null +++ b/migrations/1729121498808_add-null-not-distinct-to-email-domains.cjs @@ -0,0 +1,40 @@ +exports.shorthands = undefined; + +exports.up = async (pgm) => { + await pgm.db.query(` + WITH cte AS ( + SELECT id, + ROW_NUMBER() + OVER (PARTITION BY organization_id, domain, verification_type ORDER BY updated_at DESC) AS rn + FROM email_domains + ) + DELETE + FROM email_domains + WHERE id IN ( + SELECT id + FROM cte + WHERE rn > 1 + ); + `); + await pgm.db.query(` + ALTER TABLE email_domains + DROP CONSTRAINT unique_organization_domain; + `); + await pgm.db.query(` + ALTER TABLE email_domains + ADD CONSTRAINT unique_organization_domain + UNIQUE NULLS NOT DISTINCT (organization_id, domain, verification_type); + `); +}; + +exports.down = async (pgm) => { + await pgm.db.query(` + ALTER TABLE email_domains + DROP CONSTRAINT unique_organization_domain; + `); + await pgm.db.query(` + ALTER TABLE email_domains + ADD CONSTRAINT unique_organization_domain + UNIQUE (organization_id, domain, verification_type); + `); +};