CREATE TABLE sc_catalogue_meta(policy text PRIMARY KEY, composition text NOT NULL, source_hash char(64) NOT NULL); CREATE TABLE sc_catalogue_versions( id bigserial PRIMARY KEY, tenant_id bigint NOT NULL, company_id bigint NOT NULL, unit_id bigint NOT NULL, record_key uuid NOT NULL, version bigint NOT NULL CHECK(version>0), previous_id bigint UNIQUE REFERENCES sc_catalogue_versions(id), action text NOT NULL CHECK(action IN('prepare','review')), state text NOT NULL CHECK(state IN('prepared','approved','refused')), prepared_host_id bigint NOT NULL, prepared_native_id bigint NOT NULL REFERENCES users(id), host_actor_id bigint NOT NULL, actor_id bigint NOT NULL REFERENCES users(id), stock_item_id bigint REFERENCES stock_items(id), data jsonb NOT NULL CHECK(jsonb_typeof(data)='object'), reason text NOT NULL CHECK(length(reason)>=10), created_at timestamptz NOT NULL, UNIQUE(tenant_id,company_id,unit_id,record_key,version), CHECK((action='prepare' AND state='prepared') OR (action='review' AND state IN('approved','refused'))), CHECK(action<>'review' OR (host_actor_id<>prepared_host_id AND actor_id<>prepared_native_id)) ); CREATE TABLE sc_catalogue_commands( id bigserial PRIMARY KEY, tenant_id bigint NOT NULL, company_id bigint NOT NULL, unit_id bigint NOT NULL, host_actor_id bigint NOT NULL, actor_id bigint NOT NULL REFERENCES users(id), command_key uuid NOT NULL, request_hash char(64) NOT NULL, binding_hash char(64) NOT NULL, input jsonb NOT NULL, result jsonb NOT NULL, created_at timestamptz NOT NULL, UNIQUE(tenant_id,company_id,unit_id,host_actor_id,command_key) ); CREATE FUNCTION sc_catalogue_append_only() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'SGF_CATALOGUE_APPEND_ONLY'; END; $$; CREATE TRIGGER sc_catalogue_versions_immutable BEFORE UPDATE OR DELETE ON sc_catalogue_versions FOR EACH ROW EXECUTE FUNCTION sc_catalogue_append_only(); CREATE TRIGGER sc_catalogue_commands_immutable BEFORE UPDATE OR DELETE ON sc_catalogue_commands FOR EACH ROW EXECUTE FUNCTION sc_catalogue_append_only(); CREATE TRIGGER sc_catalogue_meta_immutable BEFORE UPDATE OR DELETE ON sc_catalogue_meta FOR EACH ROW EXECUTE FUNCTION sc_catalogue_append_only();