Sub topic 20
Testing and debugging triggers
This chapter assumes you can write a trigger function and attach it with CREATE TRIGGER. It also assumes you know how BEFORE, AFTER, NEW, OLD and return values work, and that you can run scripts in psql. The examples use the accounts table, the set_updated_at, forbid_negative_balance and audit_accounts triggers, and the accounts_audit table from earlier chapters.
Triggers run implicitly, so a bug in one shows up as a strange result of an ordinary statement. A trigger can also change data without any visible call. This chapter covers how to test triggers in isolation, how to see what they are doing, and how to recognize the usual failures.
Test inside a transaction you roll back
Run each test in a transaction and finish with ROLLBACK. The trigger fires for real, and no test data stays behind.
BEGIN;
INSERT INTO accounts (email) VALUES ('[email protected]');
-- Try to force an old timestamp. The BEFORE trigger should overwrite it.
UPDATE accounts SET updated_at = '2000-01-01' WHERE email = '[email protected]';
SELECT updated_at = now() AS trigger_ran
FROM accounts
WHERE email = '[email protected]';
ROLLBACK;The query should return t. The comparison with now() is deliberate. now() returns the start time of the current transaction, so it is the same value on every call inside the transaction. If you compared updated_at before and after two updates in one transaction, you would see no change, even though the trigger worked. To observe time passing, use separate transactions or clock_timestamp().
Assert rejections and side effects
A rule that rejects data is tested by expecting an error. A DO block with an EXCEPTION clause does this. It runs in a subtransaction, so the failed insert is undone.
DO $$
BEGIN
INSERT INTO accounts (email, balance) VALUES ('[email protected]', -5);
RAISE EXCEPTION 'trigger did not reject the negative balance';
EXCEPTION
WHEN check_violation THEN
RAISE NOTICE 'ok: negative balance rejected';
END;
$$;The trigger raises with the check_violation error code, so the handler catches it. If the trigger is missing, the insert succeeds and the second RAISE EXCEPTION fires. That one uses the default code, so the handler does not catch it, and the script fails loudly.
For side effects such as audit rows, use ASSERT. A failed assertion raises an error and stops the script.
BEGIN;
DO $$
DECLARE
n int;
BEGIN
INSERT INTO accounts (email) VALUES ('[email protected]');
UPDATE accounts SET balance = 5 WHERE email = '[email protected]';
SELECT count(*) INTO n
FROM accounts_audit a
JOIN accounts c ON c.id = a.account_id
WHERE c.email = '[email protected]';
ASSERT n = 2, format('expected 2 audit rows, got %s', n);
END;
$$;
ROLLBACK;Cover both sides of every trigger. Test a case where it should act, a case where it should stay quiet (for example, a WHEN condition that is false), and the edge cases: a multi-row statement, a DELETE, and a NULL in a compared column. For a larger suite, the pgTAP extension provides assertion functions and a test runner, but plain SQL scripts like these work well for small projects.
Trace what fires
When you do not know which triggers run, or in what order, add a temporary tracing trigger. It reports its own name, timing, event, level and nesting depth.
CREATE FUNCTION trace_trigger() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'fired % (% % on %, level %, depth %)',
TG_NAME, TG_WHEN, TG_OP, TG_TABLE_NAME, TG_LEVEL, pg_trigger_depth();
IF TG_OP = 'DELETE' THEN
RETURN OLD;
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER accounts_a_trace
BEFORE INSERT OR UPDATE OR DELETE ON accounts
FOR EACH ROW
EXECUTE FUNCTION trace_trigger();pg_trigger_depth() returns how many triggers are currently nested. A value above 1 means one trigger's action fired another. A depth that keeps growing is the first sign of recursion.
The name accounts_a_trace is chosen on purpose. Triggers with the same timing and event fire in alphabetical order by name, so this one runs before the others. Remove it when you are done:
DROP TRIGGER accounts_a_trace ON accounts;
DROP FUNCTION trace_trigger();Inspect what is installed
Check the catalog before assuming a trigger exists, is enabled, or has the definition you wrote.
SELECT tgname, tgenabled, pg_get_triggerdef(oid) AS definition
FROM pg_trigger
WHERE tgrelid = 'accounts'::regclass
AND NOT tgisinternal
ORDER BY tgname;tgenabled is O for a normal enabled trigger and D for a disabled one. The ORDER BY tgname shows the firing order within each timing and event. Also look at what the function does, using \sf set_updated_at in psql.
Common failures and their causes
| Symptom | Likely cause |
|---|---|
| `UPDATE 0` although matching rows exist | A `BEFORE` row trigger returned `NULL`, which skips the row silently. |
| `control reached end of trigger procedure without RETURN` | The function has a code path with no `RETURN`. |
| Change made to `NEW` has no effect | The trigger is `AFTER`, or a `BEFORE` trigger did not return `NEW`. |
| Trigger never fires | `UPDATE OF` names a column the statement does not set, or `WHEN` is false. |
| Another trigger sees unexpected values | An earlier trigger, by name order, already changed `NEW`. |
| `stack depth limit exceeded` | The trigger's own statement fires the trigger again. |
| Error mentions `NEW` or `OLD` in a statement-level trigger | Statement-level triggers have no row. Use a transition table instead. |
For recursion, a common guard is IF pg_trigger_depth() > 1 THEN RETURN NEW; END IF;. Use it with care, because it also skips legitimate work when another trigger caused the nesting. A narrower WHEN condition is usually the better fix.
Read errors with context
An error raised inside a trigger reports the function and line number in its CONTEXT line, for example PL/pgSQL function forbid_negative_balance() line 4 at RAISE. In psql, \set VERBOSITY verbose also shows the error code and source location. Use these to find the failing statement, then reproduce it by running the same INSERT or UPDATE by hand in a rolled-back transaction.
Exercise
A BEFORE UPDATE row trigger on accounts contains IF NEW.balance < 0 THEN RETURN NULL; END IF; RETURN NEW;. A user runs UPDATE accounts SET balance = -1 WHERE id = 7; and psql prints UPDATE 0 with no error. Why, and how would you change the trigger so the user sees a failure?
Show answer
Returning NULL from a BEFORE row-level trigger tells PostgreSQL to skip that row's operation without raising an error, so zero rows are updated. Replace RETURN NULL with RAISE EXCEPTION 'balance cannot be negative: %', NEW.balance USING ERRCODE = 'check_violation';. The statement then aborts with an error, and you can test it with an EXCEPTION block that catches check_violation.