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.
Code
-- 行级 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.HTTP Status Code ExplorerBrowse and explore HTTP status codes with their meanings, categories, and common use cases. Search by code or description to understand 1xx through 5xx responses.
FAQ
- What objects does the SQL involve?
- The references are `of`, `new.status`, `orders`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.