manicanldes-backend/prisma/migrations/20261008130000_order_expiry.../migration.sql

25 lines
2.0 KiB
PL/PgSQL

CREATE TABLE order_expiry_runs (
id UUID NOT NULL, organization_id UUID NOT NULL, actor_id UUID NOT NULL,
idempotency_key UUID NOT NULL, request_hash CHAR(64) NOT NULL, "limit" INTEGER NOT NULL,
as_of TIMESTAMPTZ(3) NOT NULL, completed_at TIMESTAMPTZ(3) NOT NULL, processed_order_ids UUID[] NOT NULL,
CONSTRAINT order_expiry_runs_pkey PRIMARY KEY (id),
CONSTRAINT order_expiry_runs_actor_id_organization_id_fkey FOREIGN KEY (actor_id, organization_id) REFERENCES users(id, organization_id) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT expiry_run_valid CHECK ("limit" BETWEEN 1 AND 25 AND cardinality(processed_order_ids) <= "limit" AND completed_at >= as_of AND request_hash ~ '^[a-f0-9]{64}$')
);
CREATE INDEX orders_organization_id_status_expires_at_id_idx ON orders (organization_id, status, expires_at, id);
CREATE UNIQUE INDEX order_expiry_runs_organization_id_idempotency_key_key ON order_expiry_runs (organization_id, idempotency_key);
CREATE INDEX order_expiry_runs_organization_id_completed_at_id_idx ON order_expiry_runs (organization_id, completed_at, id);
CREATE FUNCTION guard_order_expiry_run() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'Order expiry run history is immutable'; END IF;
IF (SELECT COUNT(DISTINCT id) FROM unnest(NEW.processed_order_ids) AS ids(id)) <> cardinality(NEW.processed_order_ids)
OR EXISTS (SELECT 1 FROM unnest(NEW.processed_order_ids) AS ids(id) LEFT JOIN orders o ON o.id = ids.id AND o.organization_id = NEW.organization_id
WHERE o.id IS NULL OR o.status <> 'CANCELLED' OR o.expires_at > NEW.as_of)
THEN RAISE EXCEPTION 'Expiry run contains invalid order evidence'; END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER order_expiry_run_guard BEFORE INSERT OR UPDATE OR DELETE ON order_expiry_runs FOR EACH ROW EXECUTE FUNCTION guard_order_expiry_run();
UPDATE roles SET permissions = ARRAY(SELECT DISTINCT unnest(permissions || ARRAY['workflows.read', 'workflows.run']))
WHERE is_system = true AND name = 'Owner';