-- +goose Up CREATE TABLE monitor_groups ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE, parent_id uuid, name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), UNIQUE (id, org_id), CHECK (parent_id IS DISTINCT FROM id), -- Composite keys keep parents and members in the same organization; -- removing a group detaches what referenced it instead of failing. FOREIGN KEY (parent_id, org_id) REFERENCES monitor_groups (id, org_id) ON DELETE SET NULL (parent_id) ); CREATE INDEX monitor_groups_parent_idx ON monitor_groups (parent_id); ALTER TABLE monitors ADD COLUMN group_id uuid; ALTER TABLE monitors ADD FOREIGN KEY (group_id, org_id) REFERENCES monitor_groups (id, org_id) ON DELETE SET NULL (group_id); CREATE INDEX monitors_group_idx ON monitors (group_id); -- +goose StatementBegin -- Rejects cycles and nesting deeper than eight levels. CREATE FUNCTION monitor_groups_tree_check() RETURNS trigger LANGUAGE plpgsql AS $$ DECLARE depth integer; BEGIN IF NEW.parent_id IS NULL THEN RETURN NEW; END IF; WITH RECURSIVE up AS ( SELECT id, parent_id, 1 AS depth FROM monitor_groups WHERE id = NEW.parent_id UNION ALL SELECT g.id, g.parent_id, up.depth + 1 FROM monitor_groups g JOIN up ON g.id = up.parent_id WHERE up.depth < 20 ) SELECT max(up.depth) INTO depth FROM up; IF EXISTS ( WITH RECURSIVE up AS ( SELECT id, parent_id FROM monitor_groups WHERE id = NEW.parent_id UNION SELECT g.id, g.parent_id FROM monitor_groups g JOIN up ON g.id = up.parent_id ) SELECT 1 FROM up WHERE id = NEW.id ) THEN RAISE EXCEPTION 'monitor group cycle' USING ERRCODE = 'check_violation', CONSTRAINT = 'monitor_groups_cycle'; END IF; IF depth >= 8 THEN RAISE EXCEPTION 'monitor groups nested too deeply' USING ERRCODE = 'check_violation', CONSTRAINT = 'monitor_groups_depth'; END IF; RETURN NEW; END $$; -- +goose StatementEnd CREATE TRIGGER monitor_groups_tree BEFORE INSERT OR UPDATE OF parent_id ON monitor_groups FOR EACH ROW EXECUTE FUNCTION monitor_groups_tree_check(); ALTER TABLE monitor_groups ENABLE ROW LEVEL SECURITY; ALTER TABLE monitor_groups FORCE ROW LEVEL SECURITY; CREATE POLICY monitor_groups_tenant ON monitor_groups FOR ALL USING (app_scope_system() OR org_id = app_org_id()) WITH CHECK (app_scope_system() OR org_id = app_org_id()); -- +goose Down ALTER TABLE monitors DROP COLUMN group_id; DROP TABLE monitor_groups; DROP FUNCTION monitor_groups_tree_check();