From 8c8f1489d0894ffa67364a6c6c5b10340b7776e5 Mon Sep 17 00:00:00 2001 From: Alex Castillo Date: Thu, 19 Nov 2026 06:13:24 -0400 Subject: [PATCH] fix(db): collapse segment memberships per merge group in normalize_contact_emails migration The dedupe DELETE only removed a duplicate's membership when the survivor already held one, so two duplicates sharing a segment the survivor was not in both got rewritten to the same (contactId, segmentId) and hit the primary key, aborting the upgrade. It also kept an exited survivor row over active duplicate rows, silently dropping the merged contact from the segment. Keep one row per (survivor, segment) across the whole group, preferring an active membership. --- .../migration.sql | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/packages/db/prisma/migrations/20260615120000_normalize_contact_emails/migration.sql b/packages/db/prisma/migrations/20260615120000_normalize_contact_emails/migration.sql index 6a9e18479..36b30be8b 100644 --- a/packages/db/prisma/migrations/20260615120000_normalize_contact_emails/migration.sql +++ b/packages/db/prisma/migrations/20260615120000_normalize_contact_emails/migration.sql @@ -75,17 +75,28 @@ SET "contactId" = m.survivor_id FROM _contact_merge_map m WHERE ev."contactId" = m.dup_id; --- segment_memberships has a composite PK (contactId, segmentId). Drop any --- duplicate membership the survivor already holds for the same segment, then --- reassign the rest. -DELETE FROM segment_memberships dsm -USING _contact_merge_map m -WHERE dsm."contactId" = m.dup_id - AND EXISTS ( - SELECT 1 FROM segment_memberships ssm - WHERE ssm."contactId" = m.survivor_id - AND ssm."segmentId" = dsm."segmentId" - ); +-- segment_memberships has a composite PK (contactId, segmentId). Collapse the +-- memberships of the whole merge group (survivor included) down to one row per +-- (survivor, segment) so the reassignment below cannot collide. An active +-- membership (exitedAt IS NULL) wins, mirroring "a single unsubscribe wins" +-- above: if any source contact is still in the segment, the merged contact +-- stays in it. +WITH grp AS ( + SELECT sm.ctid AS row_id, + ROW_NUMBER() OVER ( + PARTITION BY m.survivor_id, sm."segmentId" + ORDER BY (sm."exitedAt" IS NOT NULL), sm."enteredAt", sm."contactId" + ) AS rn + FROM segment_memberships sm + JOIN ( + SELECT dup_id AS cid, survivor_id FROM _contact_merge_map + UNION + SELECT survivor_id, survivor_id FROM _contact_merge_map + ) m ON m.cid = sm."contactId" +) +DELETE FROM segment_memberships sm +USING grp +WHERE sm.ctid = grp.row_id AND grp.rn > 1; UPDATE segment_memberships dsm SET "contactId" = m.survivor_id