Sub topic 11
Example: an audit trail
This chapter builds an audit trail with one trigger. Every insert, update, and delete on accounts leaves a permanent record of who changed what, and when. It assumes you know the pieces from earlier chapters: trigger functions, CREATE TRIGGER, NEW and OLD, TG_OP, and the effect of AFTER timing.
What an audit trail records
An audit trail is an append-only table. Each row describes one change to another table. A useful row answers four questions:
- Which row changed? This is the primary key.
- What happened? This is the operation: INSERT, UPDATE, or DELETE.
- What was the data before and after the change?
- Who made the change, and when?
Storing the old and new row as jsonb keeps the audit table independent of the source table's columns. If you add a column to accounts later, the audit table needs no change.
Why an AFTER row-level trigger
An audit trigger should record what actually happened, so it fires AFTER the change. A BEFORE trigger runs ahead of other BEFORE triggers and constraint checks. It could log a row that a later step then changes or rejects. An AFTER trigger sees the final stored row.
It must be row-level because it needs OLD and NEW for each affected row. The return value of an AFTER row trigger is ignored, so the function returns NULL.
The audit insert runs in the same transaction as the change. If the transaction rolls back, the audit row disappears with it. That is the right behavior: the audit trail describes committed changes only.
The audit table and trigger
This block is complete and runnable on its own. It creates a minimal accounts table, the audit table, the function, and the trigger.
CREATE TABLE accounts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
balance numeric(12,2) NOT NULL DEFAULT 0,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE accounts_audit (
audit_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
account_id bigint NOT NULL,
operation text NOT NULL,
old_row jsonb,
new_row jsonb,
changed_at timestamptz NOT NULL DEFAULT now(),
changed_by text NOT NULL DEFAULT current_user
);
CREATE FUNCTION audit_accounts() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
INSERT INTO accounts_audit (account_id, operation, new_row)
VALUES (NEW.id, TG_OP, to_jsonb(NEW));
ELSIF TG_OP = 'UPDATE' THEN
INSERT INTO accounts_audit (account_id, operation, old_row, new_row)
VALUES (NEW.id, TG_OP, to_jsonb(OLD), to_jsonb(NEW));
ELSIF TG_OP = 'DELETE' THEN
INSERT INTO accounts_audit (account_id, operation, old_row)
VALUES (OLD.id, TG_OP, to_jsonb(OLD));
END IF;
RETURN NULL;
END;
$$;
CREATE TRIGGER accounts_audit_trg
AFTER INSERT OR UPDATE OR DELETE ON accounts
FOR EACH ROW
EXECUTE FUNCTION audit_accounts();Three details matter here:
TG_OPholds the event name as text. One function serves all three events.NEWdoes not exist for DELETE, andOLDdoes not exist for INSERT. Reading the missing record raises an error, so each branch touches only the record that exists.to_jsonb(NEW)converts the whole row to a JSON object keyed by column name.
Trying it
On a fresh accounts table, run a change of each kind and read the log:
INSERT INTO accounts (email, balance) VALUES ('[email protected]', 100);
UPDATE accounts SET balance = 150 WHERE id = 1;
DELETE FROM accounts WHERE id = 1;
SELECT operation, account_id,
old_row->>'balance' AS old_balance,
new_row->>'balance' AS new_balance
FROM accounts_audit
ORDER BY audit_id; operation | account_id | old_balance | new_balance
-----------+------------+-------------+-------------
INSERT | 1 | | 100.00
UPDATE | 1 | 100.00 | 150.00
DELETE | 1 | 150.00 |To see only the columns an update changed, compare the two JSON objects key by key:
SELECT a.audit_id, k AS column_name,
a.old_row->k AS old_value,
a.new_row->k AS new_value
FROM accounts_audit a,
jsonb_object_keys(a.new_row) AS k
WHERE a.operation = 'UPDATE'
AND a.old_row->k IS DISTINCT FROM a.new_row->k;Skipping updates that change nothing
An UPDATE accounts SET balance = balance writes a new row version even though no value changed, and the audit trigger logs it. You would normally use a WHEN (OLD.* IS DISTINCT FROM NEW.*) condition to skip such updates. But PostgreSQL rejects a WHEN condition that references OLD on an INSERT trigger, and rejects one that references NEW on a DELETE trigger. So a trigger declared for all three events cannot use it. Split the trigger in two:
DROP TRIGGER accounts_audit_trg ON accounts;
CREATE TRIGGER accounts_audit_ins_del
AFTER INSERT OR DELETE ON accounts
FOR EACH ROW
EXECUTE FUNCTION audit_accounts();
CREATE TRIGGER accounts_audit_upd
AFTER UPDATE ON accounts
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE FUNCTION audit_accounts();Both triggers call the same function. Each one is now valid for its events, and the update trigger skips no-op updates before the function is even called.
Gotchas
- TRUNCATE is not logged. Row-level triggers never fire for
TRUNCATE. To record it, add a separateFOR EACH STATEMENTtrigger onTRUNCATE. current_usercan mislead. It is the role the session is currently acting as. If the trigger function isSECURITY DEFINER,current_userinside it is the function owner, not the person who ran the statement. Usesession_userin the column default, or take the application's user from a setting you control.- Protect the log. An audit table that its subjects can edit proves little. Revoke write access from ordinary roles and let only the trigger write to it.
- Do not audit the audit table. A trigger on
accounts_auditthat writes toaccounts_auditfires itself again and recurses until it hits the stack depth limit. - Each audited write costs an extra insert. Bulk loads into an audited table roughly double their write work. Consider disabling the trigger for a controlled data load, and record that you did so.
REVOKE UPDATE, DELETE, TRUNCATE ON accounts_audit FROM PUBLIC;Row snapshots versus change records
Full-row snapshots are simple and make point-in-time questions easy. They cost storage, because a one-column update writes two complete copies of the row. If rows are wide and updates are frequent, store only the changed keys instead. The trade-off is a more complex function and harder reads.
Exercise
A teammate changes accounts_audit_trg so it is BEFORE INSERT OR UPDATE OR DELETE and returns NULL from the function. What happens to the changes made to accounts, and why is AFTER a better choice for an audit trigger anyway?
Show answer
In a BEFORE row-level trigger, returning NULL tells PostgreSQL to skip the operation for that row, so every insert, update, and delete on accounts would silently do nothing, while audit rows would still be written. AFTER is better because the trigger then sees the final stored row, after other BEFORE triggers and constraint checks have run, and its return value is ignored. The audit trigger therefore cannot change or cancel the operation by accident.
Exercise
Why does CREATE TRIGGER ... AFTER INSERT OR UPDATE OR DELETE ON accounts FOR EACH ROW WHEN (OLD.* IS DISTINCT FROM NEW.*) ... fail, and how do you fix it?
Show answer
PostgreSQL does not allow a WHEN condition to reference OLD in an INSERT trigger, or NEW in a DELETE trigger, because those records do not exist for those events. Fix it by splitting the trigger. Use one trigger for AFTER INSERT OR DELETE with no WHEN condition, and one for AFTER UPDATE with the WHEN condition. Both can call the same function.