fix(state): attribute identity events to the subject's single org

This commit is contained in:
sam committed 2026-10-25 21:35:19 +11:00
1 parent e2a268aef1
commit daa7ccb249
5 files changed
+137 -22

No files matched your search

@@ -44,6 +44,26 @@ INSERT INTO identity_aliases (alias, identity_id) VALUES ($1, $2) ON CONFLICT DO
INSERT INTO identity_events (identity_id, event_type, from_lifecycle, to_lifecycle, display_name, actor_id, source, request_id, at, org_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);
-- name: IdentityAuditOrgCount :one
-- How many distinct orgs one identity belongs to, across memberships and agent
-- assignments. Exactly one makes its events attributable to that org; two or
-- more mean an event is not attributable to a single org.
SELECT count(DISTINCT org_id)::int AS org_count
FROM (
SELECT m.org_id FROM memberships m WHERE m.identity_id = $1
UNION
SELECT a.org_id FROM org_agents a WHERE a.identity_id = $1
) belonging;
-- name: IdentityAuditOrg :one
-- The identity's org, read only when IdentityAuditOrgCount returns one.
SELECT min(org_id)::text AS org_id
FROM (
SELECT m.org_id FROM memberships m WHERE m.identity_id = $1
UNION
SELECT a.org_id FROM org_agents a WHERE a.identity_id = $1
) belonging;
-- name: UpdateIdentity :execrows
UPDATE identities SET display_name = $2, lifecycle = $3, version = $4, updated_at = $5
WHERE id = $1 AND version = $6;