33 lines
1.6 KiB
SQL
33 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.
|
|
--
|
|
-- Historical rows have no recorded org. A membership row carries only the
|
|
-- moment it started (no end), so the membership in effect at an event is the
|
|
-- latest one created at or before it. An agent belongs to one org, so its
|
|
-- assignment is the next best answer. A row with neither stays NULL and is
|
|
-- visible only to an instance administrator: attributing it to the system org
|
|
-- would show one org's history to every non-admin member of that org.
|
|
|
|
-- +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 = COALESCE(
|
|
(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 a.org_id FROM org_agents a WHERE a.identity_id = ie.identity_id)
|
|
);
|
|
|
|
-- 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;
|