Sub topic 2
Writing a trigger function
This chapter assumes you can write basic SQL (CREATE TABLE, INSERT, UPDATE) and use psql. It also assumes you know what a transaction is. Simple PL/pgSQL syntax (DECLARE, BEGIN, IF, RAISE) helps but isn't required. The previous chapter covered what triggers are. This one covers the function a trigger runs, and the next chapter covers CREATE TRIGGER.
What makes a function a trigger function
A trigger function is an ordinary function with three fixed properties:
- It is declared with
RETURNS trigger. - It takes no declared arguments.
CREATE FUNCTION f(x int) RETURNS triggerfails with an error. - It can only be called by the trigger machinery. Calling it from a query is an error.
PL/pgSQL is the usual language. PL/Python, PL/Perl, PL/Tcl and C can also write trigger functions. This tutorial uses PL/pgSQL.
The function is created separately from the trigger. One function can serve many triggers on many tables, which is why trigger functions are often written generically.
A first trigger function
The following function reports which event called it. The demo table is widgets.
CREATE TABLE widgets (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
CREATE FUNCTION describe_event() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'trigger=% when=% level=% op=% table=%.%',
TG_NAME, TG_WHEN, TG_LEVEL, TG_OP, TG_TABLE_SCHEMA, TG_TABLE_NAME;
IF TG_OP = 'DELETE' THEN
RETURN OLD;
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER widgets_describe
BEFORE INSERT OR UPDATE OR DELETE ON widgets
FOR EACH ROW
EXECUTE FUNCTION describe_event();
INSERT INTO widgets (name) VALUES ('gear');The insert prints a notice like this:
NOTICE: trigger=widgets_describe when=BEFORE level=ROW op=INSERT table=public.widgetsThe function does two things. It reads TG_* variables that PostgreSQL creates automatically in every trigger function. It also ends with a RETURN, because the return value is part of the trigger's contract.
The variables PostgreSQL provides
These are the variables you will use most.
| Variable | Contents |
|---|---|
| `NEW` | The row being inserted or the new version of an updated row. Null in `DELETE` triggers and in statement-level triggers. |
| `OLD` | The row being deleted or the old version of an updated row. Null in `INSERT` triggers and in statement-level triggers. |
| `TG_OP` | `INSERT`, `UPDATE`, `DELETE` or `TRUNCATE`. |
| `TG_WHEN` | `BEFORE`, `AFTER` or `INSTEAD OF`. |
| `TG_LEVEL` | `ROW` or `STATEMENT`. |
| `TG_NAME` | The trigger's name. |
| `TG_TABLE_NAME`, `TG_TABLE_SCHEMA` | The table that fired the trigger and its schema. |
| `TG_NARGS`, `TG_ARGV` | The count and the text array of arguments given in `CREATE TRIGGER`. |
Because NEW and OLD are null in some situations, a function shared by several events must check TG_OP before touching them. Reading OLD.id in an insert trigger raises an error.
Passing arguments through TG_ARGV
The function itself declares no parameters. Arguments go on the CREATE TRIGGER command and arrive as text in TG_ARGV, indexed from 0. This lets one function work with different column names.
ALTER TABLE widgets ADD COLUMN modified_at timestamptz;
CREATE FUNCTION stamp_column() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_NARGS <> 1 THEN
RAISE EXCEPTION 'stamp_column expects 1 argument, got %', TG_NARGS;
END IF;
NEW := jsonb_populate_record(NEW, jsonb_build_object(TG_ARGV[0], now()));
RETURN NEW;
END;
$$;
CREATE TRIGGER widgets_stamp
BEFORE INSERT OR UPDATE ON widgets
FOR EACH ROW
EXECUTE FUNCTION stamp_column('modified_at');
UPDATE widgets SET name = 'cog' WHERE name = 'gear';
SELECT name, modified_at FROM widgets;jsonb_populate_record copies the values of NEW and overrides the key named in the argument. The function then assigns the result back to NEW.
What the function must return
The return value depends on the trigger's timing and level.
| Trigger | Return value | Effect |
|---|---|---|
| `BEFORE` row | A row (usually `NEW`) | That row is inserted or updated. Changes made to `NEW` are kept. |
| `BEFORE` row | `NULL` | The operation is skipped for this row. No error is raised. |
| `BEFORE` row, `DELETE` | `OLD` | The delete proceeds. Returning `NEW` there is useless because it is null, so the delete would be skipped. |
| `AFTER` row | Anything | Ignored. `RETURN NULL` is the convention. |
| Statement level | Anything | Ignored. `RETURN NULL` is the convention. |
| `INSTEAD OF` row | A non-null row | Reports the operation as handled. `NULL` reports that nothing was done. |
The DELETE case is a frequent mistake. If a BEFORE DELETE function ends with RETURN NEW, NEW is null, the delete is silently skipped, and no error appears. This is why describe_event returns OLD for deletes.
A function that reaches the end of its body without a RETURN fails at run time with control reached end of trigger procedure without RETURN.
Raising errors
RAISE EXCEPTION aborts the current statement. The whole transaction is marked failed unless the caller catches the error with a savepoint or an EXCEPTION block. Triggers that enforce rules rely on this. Use USING ERRCODE to pick a meaningful SQLSTATE so that applications can tell your errors apart. Later chapters build validation on this.
Calling and permissions
Calling the function directly fails:
SELECT describe_event();
-- ERROR: trigger functions can only be called as triggersPermissions follow two rules:
- To create a trigger, a user needs the
TRIGGERprivilege on the table andEXECUTEon the function. - When the trigger fires, the function runs with the privileges of the user who ran the statement.
SECURITY DEFINERchanges that to the function's owner. Use it only deliberately, for example when the trigger must write to an audit table that ordinary users cannot touch. If you use it, also setsearch_pathon the function.
Replacing a function
CREATE OR REPLACE FUNCTION changes the body without dropping the triggers that use it. The new version applies to the next firing. You cannot change the return type this way, but it stays trigger anyway.
Exercise
A BEFORE DELETE row trigger function ends with RETURN NEW. You run DELETE FROM widgets WHERE id = 1 and it reports DELETE 0, although the row exists. Why, and what is the fix?
Show answer
In a DELETE trigger NEW is null, so RETURN NEW returns NULL. In a BEFORE row trigger, NULL means "skip this row", so the delete is silently cancelled. Change the function to RETURN OLD, or branch on TG_OP and return OLD for deletes and NEW otherwise.