40 lines
1.8 KiB
SQL
40 lines
1.8 KiB
SQL
-- Identity lifecycle events were instance-level: the feed joined live
|
|
-- memberships to decide which org could see them, so removing a member erased
|
|
-- their earlier lifecycle rows from that org's timeline. org_id on the event
|
|
-- makes the org a first-class, immutable fact recorded when the event happens.
|
|
--
|
|
-- Historical rows have no recorded org. A membership row carries only the
|
|
-- moment it started (no end), so the memberships in effect at an event are
|
|
-- those created at or before it. Memberships and agent assignments are counted
|
|
-- together, matching the writer's union: an event is attributed only when
|
|
-- exactly one distinct org qualifies. A person in two or more orgs at the time
|
|
-- is deliberately left NULL, because picking one would hide the event from the
|
|
-- other org's feed. A row with no qualifying org stays NULL and is visible
|
|
-- only to an instance administrator, so rows written before and after the
|
|
-- upgrade agree.
|
|
|
|
-- +goose Up
|
|
ALTER TABLE identity_events ADD COLUMN org_id text;
|
|
ALTER TABLE identity_events ADD CONSTRAINT identity_events_org_nonempty
|
|
CHECK (org_id IS NULL OR org_id <> '');
|
|
|
|
UPDATE identity_events ie SET org_id = (
|
|
SELECT min(b.org_id) FROM (
|
|
SELECT m.org_id FROM memberships m
|
|
WHERE m.identity_id = ie.identity_id AND m.created_at <= ie.at
|
|
UNION
|
|
SELECT a.org_id FROM org_agents a
|
|
WHERE a.identity_id = ie.identity_id AND a.created_at <= ie.at
|
|
) b
|
|
HAVING count(DISTINCT b.org_id) = 1
|
|
);
|
|
|
|
-- Keep the instance-admin read ordered by time as well: its predicate has no
|
|
-- org equality, so the org-leading index alone would not serve it.
|
|
CREATE INDEX idx_identity_events_org_at ON identity_events (org_id, at DESC, id DESC);
|
|
|
|
-- +goose Down
|
|
DROP INDEX idx_identity_events_org_at;
|
|
ALTER TABLE identity_events DROP CONSTRAINT identity_events_org_nonempty;
|
|
ALTER TABLE identity_events DROP COLUMN org_id;
|