Sub topic 18
Constraint triggers and deferred checks
This chapter assumes you can write a PL/pgSQL trigger function, attach it with CREATE TRIGGER, and read NEW and OLD. It also assumes you know what a transaction and COMMIT are. The chapter covers a special kind of trigger that can wait until the end of the transaction before it runs.
The problem with checking too early
Some rules cannot be true after every statement, only after the last one. For example, "every invoice has at least one line" is false in the moment between inserting the invoice and inserting its first line.
A normal AFTER trigger fires at the end of its statement. A trigger that checks this rule there would reject the invoice insert immediately. You need a check that runs at commit, when the transaction is complete.
PostgreSQL provides this with the constraint trigger. It is a trigger that behaves like a constraint: it can be deferred, and SET CONSTRAINTS controls it.
CREATE CONSTRAINT TRIGGER
The syntax is close to CREATE TRIGGER, with a few additions and restrictions:
CREATE CONSTRAINT TRIGGER name
AFTER event [OR ...] ON table_name
[ NOT DEFERRABLE | [ DEFERRABLE ] [ INITIALLY IMMEDIATE | INITIALLY DEFERRED ] ]
FOR EACH ROW
[ WHEN ( condition ) ]
EXECUTE FUNCTION function_name();The rules:
- It must be
AFTER.BEFOREandINSTEAD OFare not allowed. - It must be
FOR EACH ROW. Statement-level constraint triggers do not exist. - The trigger function must return
trigger, as usual. Because the trigger isAFTER ... FOR EACH ROW, the return value is ignored. DEFERRABLEmeans the check may be postponed.INITIALLY DEFERREDpostpones it by default.INITIALLY IMMEDIATEruns it at the end of each statement unless you ask to defer it.- The default is
NOT DEFERRABLE, which behaves like an ordinaryAFTERrow trigger.
Ordinary triggers cannot be deferred at all. Deferral is the main reason to use a constraint trigger.
Example: an invoice needs at least one line
CREATE TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL
);
CREATE TABLE invoice_lines (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
invoice_id bigint NOT NULL REFERENCES invoices (id) ON DELETE CASCADE,
amount numeric(12,2) NOT NULL
);
CREATE FUNCTION require_invoice_line() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
inv_id bigint;
BEGIN
IF TG_TABLE_NAME = 'invoices' THEN
inv_id := NEW.id;
ELSE
inv_id := OLD.invoice_id;
END IF;
IF EXISTS (SELECT 1 FROM invoices WHERE id = inv_id)
AND NOT EXISTS (SELECT 1 FROM invoice_lines WHERE invoice_id = inv_id)
THEN
RAISE EXCEPTION 'invoice % must have at least one line', inv_id
USING ERRCODE = 'check_violation';
END IF;
RETURN NULL;
END;
$$;
CREATE CONSTRAINT TRIGGER invoices_need_line
AFTER INSERT ON invoices
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW
EXECUTE FUNCTION require_invoice_line();
CREATE CONSTRAINT TRIGGER lines_keep_invoice_valid
AFTER DELETE OR UPDATE OF invoice_id ON invoice_lines
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW
EXECUTE FUNCTION require_invoice_line();One function serves two triggers, and TG_TABLE_NAME selects which row to read. The rule can be broken from two sides. A new invoice may arrive with no lines. A delete or move of a line may leave its old invoice empty.
The function queries the tables instead of trusting NEW or OLD. The reason is explained in the next section.
Now run a transaction that is valid at commit time but not in the middle:
BEGIN;
INSERT INTO invoices (customer) VALUES ('Acme');
INSERT INTO invoice_lines (invoice_id, amount)
VALUES (currval(pg_get_serial_sequence('invoices', 'id')), 50.00);
COMMIT;The commit succeeds. If you leave out the second INSERT, COMMIT fails with the error invoice N must have at least one line and the whole transaction rolls back.
How deferral works
When a row change matches a deferred constraint trigger, PostgreSQL does not run the function. It records an event with the row's values at that moment. At commit, it runs the function for each recorded event.
This has two consequences:
NEWandOLDare snapshots from when the event happened. By commit time the row may have changed again or been deleted. Query the tables for the current state, as the example does.- Events queue up. Inserting 10,000 invoices in one transaction means 10,000 function calls at commit, and the queue uses memory.
If the function raises an exception at commit, the commit fails and the transaction is rolled back.
Controlling timing with SET CONSTRAINTS
SET CONSTRAINTS changes timing for the current transaction:
BEGIN;
SET CONSTRAINTS invoices_need_line IMMEDIATE;
INSERT INTO invoices (customer) VALUES ('Globex');
-- the check runs at the end of the INSERT statement and raises an error
ROLLBACK;You can also write SET CONSTRAINTS ALL DEFERRED, which affects every deferrable constraint and constraint trigger. Switching a trigger to IMMEDIATE runs any events already queued for it at that moment. This is useful when you want an early error at a known point in a long transaction.
SET CONSTRAINTS accepts the constraint trigger's name, so the names you choose matter. It has no effect on triggers that are NOT DEFERRABLE.
Constraint triggers compared with other tools
| Tool | Can be deferred | Level | Best for |
|---|---|---|---|
| `CHECK` constraint | No | Single row | Rules using only that row's columns |
| `UNIQUE`, `FOREIGN KEY` | Yes (if declared `DEFERRABLE`) | Row and table | Uniqueness and references |
| Ordinary trigger | No | Row or statement | Side effects, derived values, immediate checks |
| Constraint trigger | Yes | Row only | Cross-row or cross-table rules checked at commit |
Use the built-in constraints when they can express the rule. Use a constraint trigger only when a rule needs a query across rows or tables and can be false mid-transaction.
Pitfalls
Other things to watch for:
- Stale
NEWandOLD. Do not use them to decide whether the rule holds. Use them only to find which row to re-check. - Rows deleted before commit. In the example, the
EXISTStest oninvoicesstops the cascade delete of an invoice from raising a false error, because the line-delete events still arrive at commit. - Late errors. The error appears at
COMMIT, far from the statement that caused it. Put the offending key in the message, as the example does. - Cost. The queue grows with the number of changed rows. Use
WHENconditions orUPDATE OFcolumn lists to keep the queue small.
Inspecting constraint triggers
Constraint triggers are listed in pg_trigger with a nonzero tgconstraint:
SELECT tgname, tgdeferrable, tginitdeferred
FROM pg_trigger
WHERE tgrelid = 'invoices'::regclass
AND tgconstraint <> 0
AND NOT tgisinternal;Foreign keys also appear in pg_trigger as internal triggers, which is why the query filters on tgisinternal. Drop a constraint trigger with DROP TRIGGER name ON table, the same as any other trigger.
Exercise
A constraint trigger is declared AFTER UPDATE ON accounts DEFERRABLE INITIALLY DEFERRED FOR EACH ROW. Inside one transaction you update the same account three times, then commit. What does the trigger function see in NEW on each call, and why should the function re-query the table to check a rule?
Show answer
The function runs at commit, once for each queued event, so three times. Each call gets the NEW row as it was after its own update, not the final row. A later update may have changed the row again, so NEW can be stale. The function should query the table to read the current committed-in-transaction state before deciding whether the rule holds.