51 lines
2.2 KiB
SQL
51 lines
2.2 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. An event is attributed only when exactly one
|
|
-- 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.
|
|
-- The agent-assignment fallback follows the same exactly-one rule. A row with
|
|
-- no qualifying org stays NULL and is visible only to an instance
|
|
-- administrator. The write path resolves an identity's orgs with the same
|
|
-- definition, so a new multi-org event is NULL by design too.
|
|
|
|
-- +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 = CASE
|
|
WHEN (
|
|
SELECT count(DISTINCT m.org_id) FROM memberships m
|
|
WHERE m.identity_id = ie.identity_id AND m.created_at <= ie.at
|
|
) = 1 THEN (
|
|
SELECT min(m.org_id) FROM memberships m
|
|
WHERE m.identity_id = ie.identity_id AND m.created_at <= ie.at
|
|
)
|
|
WHEN (
|
|
SELECT count(DISTINCT m.org_id) FROM memberships m
|
|
WHERE m.identity_id = ie.identity_id AND m.created_at <= ie.at
|
|
) = 0
|
|
AND (
|
|
SELECT count(DISTINCT a.org_id) FROM org_agents a
|
|
WHERE a.identity_id = ie.identity_id AND a.created_at <= ie.at
|
|
) = 1 THEN (
|
|
SELECT min(a.org_id) FROM org_agents a
|
|
WHERE a.identity_id = ie.identity_id AND a.created_at <= ie.at
|
|
)
|
|
ELSE NULL
|
|
END;
|
|
|
|
-- 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;
|