nidus-sync/db/migrations/00153_comms_phone_log_contact.sql
Eli Ribble f957dc6982
Migrate contact_email and contact_phone to allow dupes
The key item here is that comms.phone and comms.email are meant to
represent a real global namespace, but comms.contact is meant to
represent an organization-specific namespace. This means the mapping,
comms.contact_phone and comms.contact_email can't key off the global
namespace. Otherwise the contact namespace would implicitly be global.
2026-05-22 15:13:03 +00:00

65 lines
2 KiB
SQL

-- +goose Up
-- We need to make it possible to have multiple relationships relating phone numbers, a global asset,
-- to cantacts, an organization-specific asset.
-- Step 1: Drop the existing primary key constraint on e164
ALTER TABLE comms.contact_phone
DROP CONSTRAINT contact_phone_pkey;
-- Step 2: Add new ID column with SERIAL type (auto-generates sequence)
ALTER TABLE comms.contact_phone
ADD COLUMN id SERIAL;
-- Step 3: Set the new ID column as the primary key
ALTER TABLE comms.contact_phone
ADD PRIMARY KEY (id);
-- Step 4: Add foreign key constraint on e164 referencing comms.phone
ALTER TABLE comms.contact_phone
ADD CONSTRAINT contact_phone_e164_fkey
FOREIGN KEY (e164) REFERENCES comms.phone(e164);
-- Step 5 (Optional but recommended): Add an index on e164 for query performance
CREATE INDEX idx_contact_phone_e164 ON comms.contact_phone(e164);
CREATE TABLE comms.email (
address TEXT NOT NULL,
is_subscribed BOOLEAN NOT NULL,
PRIMARY KEY(address)
);
INSERT INTO comms.email (
address,
is_subscribed
) SELECT
address,
FALSE
FROM comms.contact_email;
INSERT INTO comms.email (
address,
is_subscribed
) SELECT
source,
FALSE
FROM comms.email_log
ON CONFLICT (address) DO NOTHING;
-- Do the same thing to email, for exactly the same reasons
-- Step 1: Drop the existing primary key constraint on address
ALTER TABLE comms.contact_email
DROP CONSTRAINT contact_email_pkey;
-- Step 2: Add new ID column with SERIAL type (auto-generates sequence)
ALTER TABLE comms.contact_email
ADD COLUMN id SERIAL;
-- Step 3: Set the new ID column as the primary key
ALTER TABLE comms.contact_email
ADD PRIMARY KEY (id);
-- Step 4: Add foreign key constraint on address referencing comms.email
ALTER TABLE comms.contact_email
ADD CONSTRAINT contact_email_address_fkey
FOREIGN KEY (address) REFERENCES comms.email(address);
-- Step 5 (Optional but recommended): Add an index on address for query performance
CREATE INDEX idx_contact_email_address ON comms.contact_email(address);