Sub topic 11
Example: an Audit Trail with PostgreSQL Triggers
Assume you know INSERT, UPDATE, DELETE, basic transactions, and simple PL/pgSQL. An audit trail is a history of changes to data. It can answer questions such as who changed an account, which operation occurred, and what the row contained before and after the change.
A trigger is useful here because it runs inside the same transaction as the data change. If the change rolls back, its audit record rolls back too.
Design the audit table
Store the operation, the affected row's key, and snapshots of the old and new row values. The jsonb type keeps the audit table flexible if the source table later gains columns.
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
);old_row is useful for UPDATE and DELETE. new_row is useful for INSERT and UPDATE. The unused column remains NULL.
Write the trigger function
A trigger function must return the special trigger type. PostgreSQL provides TG_OP, OLD, and NEW inside the function:
TG_OPcontainsINSERT,UPDATE, orDELETE.OLDcontains the row before the change.NEWcontains the row after the change.
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;
$$;The to_jsonb function converts a row record into a JSONB value. The function returns NULL because this is an AFTER trigger. PostgreSQL ignores the return value from an AFTER row-level trigger.
Attach it to the table
CREATE TRIGGER accounts_audit_trg
AFTER INSERT OR UPDATE OR DELETE ON accounts
FOR EACH ROW
EXECUTE FUNCTION audit_accounts();FOR EACH ROW means one audit row is created for every affected account. An UPDATE that changes 100 accounts calls the function 100 times.
sequenceDiagram
participant Client
participant Accounts
participant Trigger
participant Audit
Client->>Accounts: UPDATE account
Accounts->>Trigger: AFTER row event
Trigger->>Audit: INSERT old and new values
Audit-->>Client: Transaction completescaption: How an account update creates an audit record alt: A sequence showing an update reaching an AFTER trigger, which inserts old and new values into the audit table.
Exercise
Why does the audit function use OLD for DELETE and NEW for INSERT?
Show answer
A deleted row has no NEW version, and an inserted row has no OLD version. Each variable represents the version that exists for that event.