fix(state): resolve identity audit org in one statement

This commit is contained in:
sam committed 2026-10-25 21:37:50 +11:00
1 parent 274acfe6f5
commit 6c095e5ac6
3 files changed
+19 -51

No files matched your search

@@ -111,9 +111,12 @@ FROM (
UNION
SELECT a.org_id FROM org_agents a WHERE a.identity_id = $1
) belonging
HAVING count(DISTINCT org_id) = 1
`
// The identity's org, read only when IdentityAuditOrgCount returns one.
// The identity's org only when it belongs to exactly one, across memberships
// and agent assignments; no row otherwise. One statement, so a concurrent
// membership add cannot make the count and the org disagree.
func (q *Queries) IdentityAuditOrg(ctx context.Context, identityID string) (string, error) {
row := q.db.QueryRow(ctx, identityAuditOrg, identityID)
var org_id string
@@ -121,25 +124,6 @@ func (q *Queries) IdentityAuditOrg(ctx context.Context, identityID string) (stri
return org_id, err
}
const identityAuditOrgCount = `-- name: IdentityAuditOrgCount :one
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
`
// 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.
func (q *Queries) IdentityAuditOrgCount(ctx context.Context, identityID string) (int32, error) {
row := q.db.QueryRow(ctx, identityAuditOrgCount, identityID)
var org_count int32
err := row.Scan(&org_count)
return org_count, err
}
const insertIdentity = `-- name: InsertIdentity :exec
INSERT INTO identities (id, kind, display_name, lifecycle, version, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)