Sub topic 18
Event Triggers for DDL Commands and Testing Triggers
Prerequisites
This chapter assumes basic SQL, PostgreSQL transactions, and simple PL/pgSQL statements such as BEGIN, IF, and RAISE. A regular trigger reacts to changes in table data. An event trigger reacts to data definition language (DDL) commands, such as CREATE TABLE, ALTER TABLE, and DROP TABLE.
Event triggers run at database level. They can help record schema changes, enforce DDL policies, or notify administrators. They do not replace regular table triggers.
Creating an Event Trigger
An event trigger function returns the special type event_trigger. PostgreSQL provides event-trigger variables such as:
TG_TAG: the DDL command tag, such asCREATE TABLETG_EVENT: the event namepg_event_trigger_ddl_commands(): rows describing completed DDL commands
The following trigger reports every DDL command that finishes successfully:
CREATE FUNCTION report_ddl() RETURNS event_trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'DDL command finished: %', TG_TAG;
END;
$$;
CREATE EVENT TRIGGER report_ddl_trigger
ON ddl_command_end
EXECUTE FUNCTION report_ddl();
SET client_min_messages = notice;
CREATE TABLE ddl_probe (
id integer PRIMARY KEY
);
DROP TABLE ddl_probe;ddl_command_end fires after the DDL command completes. Other event points include ddl_command_start, sql_drop, and table_rewrite. The available event-trigger variables and helper functions depend on the event point.
Creating an event trigger requires superuser privileges. This restriction matters because an event trigger can affect schema changes made by many users.
Diagram: DDL Event Flow
Testing and Debugging Triggers
Test triggers inside a transaction while developing. You can inspect notices and undo the test without keeping its changes:
BEGIN;
SET LOCAL client_min_messages = notice;
CREATE TABLE trigger_test (
id integer
);
ALTER TABLE trigger_test ADD COLUMN label text;
ROLLBACK;A RAISE NOTICE statement shows useful values without stopping the transaction. Use RAISE WARNING for a more visible message. Use RAISE EXCEPTION when the condition must abort the statement.
Inspect regular triggers through pg_trigger:
SELECT tgname, tgenabled
FROM pg_trigger
WHERE tgrelid = 'accounts'::regclass
AND NOT tgisinternal;Inspect event triggers through pg_event_trigger:
SELECT evtname, evtevent, evtenabled
FROM pg_event_trigger
ORDER BY evtname;When debugging, check whether the trigger is enabled, whether its event point matches the command, and whether an exception caused the transaction to abort. In psql, inspect the complete error message and use \d accounts to review table triggers. Test both the expected path and failure path, including a transaction rollback.
Exercise
Why would you use an event trigger instead of a regular AFTER INSERT trigger?
Show answer
An event trigger reacts to database DDL commands such as CREATE TABLE or ALTER TABLE, while a regular table trigger reacts to data changes in a table.