34 lines
1.6 KiB
SQL
34 lines
1.6 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.
|
|
|
|
-- +goose Up
|
|
ALTER TABLE identity_events ADD COLUMN org_id text NOT NULL DEFAULT 'org-sys';
|
|
ALTER TABLE identity_events ADD CONSTRAINT identity_events_org_nonempty CHECK (org_id <> '');
|
|
|
|
-- An agent belongs to exactly one org, so its assignment is authoritative.
|
|
-- For a person, use the membership that was already in place when the event
|
|
-- happened; a create writes the membership first, so its event resolves. A
|
|
-- membership that predates the event is the best remaining answer; a person
|
|
-- with none belongs to the system org.
|
|
UPDATE identity_events ie SET org_id = COALESCE(
|
|
(SELECT a.org_id FROM org_agents a WHERE a.identity_id = ie.identity_id),
|
|
(SELECT m.org_id FROM memberships m
|
|
WHERE m.identity_id = ie.identity_id AND m.created_at <= ie.at
|
|
ORDER BY m.created_at DESC LIMIT 1),
|
|
(SELECT m.org_id FROM memberships m
|
|
WHERE m.identity_id = ie.identity_id
|
|
ORDER BY m.created_at ASC LIMIT 1),
|
|
'org-sys'
|
|
);
|
|
|
|
DROP INDEX idx_identity_events_at;
|
|
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;
|
|
CREATE INDEX idx_identity_events_at ON identity_events (at DESC, id DESC);
|
|
ALTER TABLE identity_events DROP CONSTRAINT identity_events_org_nonempty;
|
|
ALTER TABLE identity_events DROP COLUMN org_id;
|