Trigger Guard Status Transitions

Encode the state machine as a BEFORE UPDATE trigger that raises a real error for illegal status transitions, whichever client submits the UPDATE.

SqlData Integrity

Code

snippet
-- 行级 BEFORE 触发器把状态机写进数据库:非法迁移直接报错,
-- 任何客户端、任何 ORM 都绕不过去
CREATE TABLE orders (
    order_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    status   text NOT NULL DEFAULT 'draft'
);

CREATE FUNCTION enforce_status_transition() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
    -- 允许的路径:draft -> submitted -> approved -> shipped
    IF NOT (
        (OLD.status = 'draft'     AND NEW.status = 'submitted') OR
        (OLD.status = 'submitted' AND NEW.status = 'approved')  OR
        (OLD.status = 'approved'  AND NEW.status = 'shipped')
    ) THEN
        RAISE EXCEPTION 'illegal status transition: % -> %', OLD.status, NEW.status
            USING ERRCODE = 'check_violation';
    END IF;
    RETURN NEW;
END;
$$;

CREATE TRIGGER orders_status_guard
BEFORE UPDATE OF status ON orders
FOR EACH ROW
WHEN (OLD.status IS DISTINCT FROM NEW.status)
EXECUTE FUNCTION enforce_status_transition();

INSERT INTO orders DEFAULT VALUES;               -- 进入 draft

UPDATE orders SET status = 'submitted';           -- 合法迁移
UPDATE orders SET status = 'shipped';             -- ERROR: illegal status transition
UPDATE orders SET status = 'draft';               -- 回退同样被拦

How the snippet works

What runs here is INSERT / UPDATE / CREATE — of, new.status and orders are the objects involved.

Mechanically, the statements are built from: a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Point it at the of table.

Statements that matter

CREATE TRIGGER orders_status_guard
BEFORE UPDATE OF status ON orders
FOR EACH ROW
WHEN (OLD.status IS DISTINCT FROM NEW.status)
EXECUTE FUNCTION enforce_status_transition();
CREATE TABLE orders (
    order_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    status   text NOT NULL DEFAULT 'draft'
);
UPDATE orders SET status = 'shipped';             -- ERROR: illegal status transition

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `of`, `new.status`, `orders`.