Audit Trigger Captures Row JSONB
An AFTER row trigger serializes each inserted, updated, or deleted row with to_jsonb, tagging TG_OP and table name so replay never depends on column lists.
Code
-- audit trigger: land a full-row jsonb snapshot of every insert, update, and delete into the audit table
-- to_jsonb(NEW)/to_jsonb(OLD) serialize against the current column layout automatically, so added columns need no trigger change
CREATE TEMP TABLE account_changes (
account_id integer PRIMARY KEY,
balance numeric NOT NULL
);
CREATE TEMP TABLE audit_log (
id bigint GENERATED ALWAYS AS IDENTITY,
table_name text NOT NULL,
op text NOT NULL,
row_data jsonb NOT NULL,
at timestamptz NOT NULL DEFAULT now()
);
CREATE OR REPLACE FUNCTION audit_row_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO audit_log (table_name, op, row_data)
VALUES (
TG_TABLE_NAME,
TG_OP,
CASE WHEN TG_OP = 'DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END
);
RETURN NULL;
END;
$$;
CREATE TRIGGER audit_account_changes
AFTER INSERT OR UPDATE OR DELETE ON account_changes
FOR EACH ROW EXECUTE FUNCTION audit_row_change();
INSERT INTO account_changes VALUES (1, 100), (2, 50);
UPDATE account_changes SET balance = 80 WHERE account_id = 1;
DELETE FROM account_changes WHERE account_id = 2;
SELECT op, row_data FROM audit_log ORDER BY id;What the code does
The file runs SELECT / INSERT / UPDATE / DELETE / CREATE statements, touching audit_log, or and account_changes.
account_changes and audit_log are created in this same file as session-local temp tables — nothing needs to exist beforehand, and they go away at session end.
Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; 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.
Using it
The file sets up its own scratch surface: it builds the session-local tables it works with (account_changes, audit_log), so one full run against a throwaway database is enough.
Key statements
CREATE TRIGGER audit_account_changes
AFTER INSERT OR UPDATE OR DELETE ON account_changes
FOR EACH ROW EXECUTE FUNCTION audit_row_change();
CREATE OR REPLACE FUNCTION audit_row_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO audit_log (table_name, op, row_data)
VALUES (
TG_TABLE_NAME,
TG_OP,
CASE WHEN TG_OP = 'DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END
);
RETURN NULL;
END;
$$;
UPDATE account_changes SET balance = 80 WHERE account_id = 1;
Interactive Tools for This Topic
FAQ
- Which tables appear in this script?
- `audit_log`, `or`, `account_changes` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.