Sub topic 19
Event triggers for DDL commands
This chapter assumes you can write a PL/pgSQL trigger function and attach it with CREATE TRIGGER. It also assumes you know that PostgreSQL DDL is transactional. Table triggers react to changes in row data. Event triggers react to schema changes: CREATE, ALTER, DROP and similar commands.
How event triggers differ from table triggers
An event trigger belongs to a database, not to a table. It has no NEW or OLD and no row-level or statement-level choice, and it takes no timing keyword like BEFORE or AFTER. The event name carries the timing. The function takes no arguments and is declared RETURNS event_trigger.
| Aspect | Table trigger | Event trigger |
|---|---|---|
| Fires on | INSERT, UPDATE, DELETE, TRUNCATE | DDL commands |
| Scope | One table or view | The whole database |
| Function returns | `trigger` | `event_trigger` |
| Return value used | Yes, in BEFORE row triggers | No |
| Context variables | `NEW`, `OLD`, `TG_OP`, and others | `TG_EVENT`, `TG_TAG` |
| Who can create it | Table owner with `TRIGGER` privilege | Superuser only |
Event triggers run in the same transaction as the command. If the function raises an exception, the DDL command is rolled back with everything else in that transaction.
The events
| Event | When it fires |
|---|---|
| `ddl_command_start` | Before the command runs. The object does not exist yet or has not changed yet. |
| `ddl_command_end` | After the command finishes, still inside the same transaction. |
| `sql_drop` | Just before `ddl_command_end`, for commands that dropped objects. |
| `table_rewrite` | Before a command such as `ALTER TABLE ... ALTER COLUMN TYPE` rewrites a table. |
| `login` | When a user connects (PostgreSQL 17 and later). |
A first event trigger
This function reports every DDL command that finishes. TG_TAG holds the command tag, such as CREATE TABLE.
CREATE FUNCTION log_ddl() RETURNS event_trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'DDL command finished: %', TG_TAG;
END;
$$;
CREATE EVENT TRIGGER log_ddl_trg
ON ddl_command_end
EXECUTE FUNCTION log_ddl();Run any CREATE TABLE afterwards and psql prints the notice. TG_EVENT holds the event name, for example ddl_command_end.
Finding out what changed
TG_TAG tells you the command but not which object it touched. In a ddl_command_end trigger, call the set-returning function pg_event_trigger_ddl_commands(). It returns one row per affected object, with columns such as command_tag, object_type, schema_name and object_identity. This example writes a permanent DDL log.
CREATE TABLE ddl_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
logged_at timestamptz NOT NULL DEFAULT now(),
username text NOT NULL DEFAULT current_user,
command_tag text NOT NULL,
object_type text,
object_identity text
);
CREATE FUNCTION record_ddl() RETURNS event_trigger
LANGUAGE plpgsql AS $$
DECLARE
r record;
BEGIN
FOR r IN
SELECT command_tag, object_type, object_identity
FROM pg_event_trigger_ddl_commands()
LOOP
INSERT INTO ddl_log (command_tag, object_type, object_identity)
VALUES (r.command_tag, r.object_type, r.object_identity);
END LOOP;
END;
$$;
CREATE EVENT TRIGGER record_ddl_trg
ON ddl_command_end
EXECUTE FUNCTION record_ddl();A single command can produce several rows. CREATE TABLE with a PRIMARY KEY reports the table and its index. Looping over the function's output handles this.
pg_event_trigger_ddl_commands() only works in ddl_command_end triggers. In a sql_drop trigger, use pg_event_trigger_dropped_objects() instead. It returns object_type, schema_name, object_name, object_identity and flags such as original and is_temporary. The objects are already gone from the system catalogs by then, so use the returned values and do not look the objects up.
Filtering with WHEN TAG
Without a filter, the function runs for every supported command. A WHEN TAG IN (...) clause limits it to the commands you name. Filtering also avoids needless function calls.
CREATE FUNCTION block_drop_table() RETURNS event_trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION 'command % is disabled in this database', TG_TAG;
END;
$$;
CREATE EVENT TRIGGER no_drop_table
ON ddl_command_start
WHEN TAG IN ('DROP TABLE')
EXECUTE FUNCTION block_drop_table();WHEN supports only TAG. Tags are written as in the SQL command, in uppercase. Raising the exception in ddl_command_start stops the command before it does anything.
Managing event triggers
Event triggers have their own commands and catalog.
-- List event triggers
SELECT evtname, evtevent, evtenabled FROM pg_event_trigger;
-- Disable and re-enable
ALTER EVENT TRIGGER no_drop_table DISABLE;
ALTER EVENT TRIGGER no_drop_table ENABLE;
-- Remove
DROP EVENT TRIGGER IF EXISTS no_drop_table;A broken event trigger can block every DDL command, including the commands you would use to fix it. Superusers can still run ALTER EVENT TRIGGER ... DISABLE or DROP EVENT TRIGGER. In PostgreSQL 17 and later, setting event_triggers = off also skips event triggers for the session. Only superusers can change that setting. Always test a new event trigger on a scratch database first.
Limits and gotchas
- Only supported commands fire. Event triggers do not fire for shared objects such as databases, roles and tablespaces, or for commands on event triggers themselves.
- Errors abort the DDL. An exception in a
ddl_command_endtrigger rolls back the command that just succeeded. A logging bug can therefore block schema changes. Keep the function simple. - Everything is per database. An event trigger created in one database does not affect others in the same cluster.
- Superuser to create. Because the function runs with the privileges of whoever issues the DDL, a malicious function would be dangerous. This is why creation is restricted.
- Logged rows can be rolled back. The log insert is part of the same transaction. If the user rolls back the DDL, the log row disappears too. This is correct for "what is in the schema" but is not a durable record of attempts.
When to use them
Good uses include schema change logging, blocking dangerous commands in production (such as DROP TABLE), enforcing naming conventions, and warning about slow table rewrites with table_rewrite. For row data, use ordinary table triggers or constraints.
Exercise
You create an event trigger on ddlcommandend that inserts a row into ddllog. A developer runs BEGIN; CREATE TABLE t (id int); ROLLBACK; Will ddllog contain a row for this command? Why? Also, which function would you call to get the dropped table's name inside a sql_drop trigger?
Show answer
No. The event trigger runs inside the developer's transaction, so the log insert is rolled back together with the CREATE TABLE. In a sqldrop trigger, call pgeventtriggerdroppedobjects() and read objectname or object_identity.