postgresql_16:6.6.10.2 Triggers on Events
PostgreSQL 16 > Server Programming > PL/pgSQL — SQL Procedural Language > Trigger Functions > Triggers on Events
PL/pgSQL can be used to define event triggers (see postgresql_16:6.3). PostgreSQL requires that a function that is to be called as an event trigger must be declared as a function with no arguments and a return type of event_trigger.
When a PL/pgSQL function is called as an event trigger, several special variables are created automatically in the top-level block. They are: TG_EVENT text event the trigger is fired for. TG_TAG text command tag for which the trigger is fired.
(see plpgsql-event-trigger-example) shows an example of an event trigger function in PL/pgSQL.
A PL/pgSQL Event Trigger Function
This example trigger simply raises a NOTICE message each time a supported command is executed.
CREATE OR REPLACE FUNCTION snitch() RETURNS event_trigger AS $$
BEGIN
RAISE NOTICE 'snitch: % %', tg_event, tg_tag;
END;
$$ LANGUAGE plpgsql;
CREATE EVENT TRIGGER snitch ON ddl_command_start EXECUTE FUNCTION snitch();