-- +goose Up -- Accounts confirm their email address before signing in; existing ones -- count as confirmed. ALTER TABLE users ADD COLUMN email_verified_at timestamptz; UPDATE users SET email_verified_at = created_at; -- One account per mailbox: email_key is the address with +suffixes and, -- for Gmail, dots removed (see emailKey in the api package). Accounts that -- already share a key keep theirs empty; only the oldest holds it. ALTER TABLE users ADD COLUMN email_key text; WITH parts AS ( SELECT id, created_at, split_part(split_part(lower(email::text), '@', 1), '+', 1) AS local, split_part(lower(email::text), '@', 2) AS domain FROM users ), keyed AS ( SELECT id, CASE WHEN domain IN ('gmail.com', 'googlemail.com') THEN replace(local, '.', '') || '@gmail.com' ELSE local || '@' || domain END AS key, row_number() OVER (PARTITION BY CASE WHEN domain IN ('gmail.com', 'googlemail.com') THEN replace(local, '.', '') || '@gmail.com' ELSE local || '@' || domain END ORDER BY created_at) AS n FROM parts ) UPDATE users u SET email_key = keyed.key FROM keyed WHERE keyed.id = u.id AND keyed.n = 1; CREATE UNIQUE INDEX users_email_key_idx ON users (email_key); -- +goose Down DROP INDEX users_email_key_idx; ALTER TABLE users DROP COLUMN email_key; ALTER TABLE users DROP COLUMN email_verified_at;