50 lines
2.1 KiB
SQL
50 lines
2.1 KiB
SQL
-- sys_audit is the field-level trail for settings resources and access
|
|
-- policies. It had no org column: the org lived inside record_key, in a shape
|
|
-- that differed per writer, so no caller could read one org's trail without
|
|
-- knowing every writer's key grammar. org_id makes the org a first-class
|
|
-- column and the indexes make an org-scoped, time-ordered page cheap.
|
|
|
|
-- +goose Up
|
|
ALTER TABLE sys_audit ADD COLUMN org_id text NOT NULL DEFAULT 'org-sys';
|
|
ALTER TABLE sys_audit ADD CONSTRAINT sys_audit_org_nonempty CHECK (org_id <> '');
|
|
|
|
-- Backfill from the two key grammars written before this migration.
|
|
-- resources: bare kind for org-sys, <org>/<kind> otherwise.
|
|
-- access_policies: <level>/<org>/<workspace>/<objectKind>/<objectID>/<policyID>;
|
|
-- instance-level policies carry no org; reset rows are reset/instance or
|
|
-- reset/org/<org>.
|
|
UPDATE sys_audit SET org_id =
|
|
CASE table_name
|
|
WHEN 'resources' THEN
|
|
CASE
|
|
WHEN position('/' IN record_key) > 0 THEN split_part(record_key, '/', 1)
|
|
ELSE 'org-sys'
|
|
END
|
|
WHEN 'access_policies' THEN
|
|
CASE
|
|
WHEN record_key LIKE 'reset/org/%' THEN split_part(record_key, '/', 3)
|
|
WHEN record_key LIKE 'reset/%' THEN 'org-sys'
|
|
WHEN split_part(record_key, '/', 1) = 'instance' THEN 'org-sys'
|
|
ELSE COALESCE(NULLIF(split_part(record_key, '/', 2), ''), 'org-sys')
|
|
END
|
|
ELSE 'org-sys'
|
|
END;
|
|
|
|
CREATE INDEX idx_sys_audit_org_at ON sys_audit (org_id, at DESC, id DESC);
|
|
CREATE INDEX idx_sys_audit_org_record ON sys_audit (org_id, table_name, record_key, at DESC, id DESC);
|
|
|
|
CREATE INDEX idx_events_org_at ON events (org_id, at DESC, id DESC);
|
|
CREATE INDEX idx_identity_events_at ON identity_events (at DESC, id DESC);
|
|
CREATE INDEX idx_access_denials_org_minute ON access_denials (org_id, minute_at DESC, id DESC);
|
|
CREATE INDEX idx_access_denials_minute ON access_denials (minute_at, id);
|
|
|
|
-- +goose Down
|
|
DROP INDEX idx_access_denials_minute;
|
|
DROP INDEX idx_access_denials_org_minute;
|
|
DROP INDEX idx_identity_events_at;
|
|
DROP INDEX idx_events_org_at;
|
|
DROP INDEX idx_sys_audit_org_record;
|
|
DROP INDEX idx_sys_audit_org_at;
|
|
ALTER TABLE sys_audit DROP CONSTRAINT sys_audit_org_nonempty;
|
|
ALTER TABLE sys_audit DROP COLUMN org_id;
|