More on Triggers
Getting Internal Information
CREATE OR REPLACE FUNCTION fn_trigger_variables_display()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS
$$
BEGIN
RAISE NOTICE 'TG_NAME: %', TG_NAME;
RAISE NOTICE 'TG_RELNAME: %', TG_RELNAME;
RAISE NOTICE 'TG_TABLE_SCHEMA: %', TG_TABLE_SCHEMA;
RAISE NOTICE 'TG_WHEN: %', TG_WHEN;
RAISE NOTICE 'TG_LEVEL: %', TG_LEVEL;
RAISE NOTICE 'TG_OP: %', TG_OP;
RAISE NOTICE 'TG_NARGS: %', TG_NARGS;
RAISE NOTICE 'TG_ARGV: %', TG_NAME;
RETURN NEW;
END;
$$
CREATE TRIGGER trg_trigger_variables_display
AFTER INSERT
ON t_temperature_log
FOR EACH ROW
EXECUTE PROCEDURE fn_trigger_variables_display();
INSERT INTO t_temperature_log ( add_date, temperature ) values ('2020-02-02', -40);Disallow DELETE on table
Disallow truncating
Creating Audit Trigger
To log data changes to tables in a consistent and transparent manner.
Please not that new OLD are not null for DELETE and INSERT triggers.
Creating Conditional Triggers
Created by using generic WHEN clause.
With a WHEN clause, you can write some conditions except a subquery
Disallow updating Primary Key of table
Event Triggers
Event triggers are data-specific and not bind or attached to a table
Unlike regular triggers they capture system level DLL events
Event triggers can be BEFORE or AFTER triggers
Trigger function can be written in any language except SQL
Event triggers are disabled in the single user mode and can only be created by a superuser
Syntax :
CREATE EVENT TRIGGER trg_nameBefore creating an event trigger, we must have a function that the trigger will execute
The function must return a specifi type called
EVENT_TRIGGERThis function need not (and may not) return a valuel the return type serivces merely as s signal that the function is to be invoked as an event trigger.
Can we create conditional event trigger ? Yes, using the when clause
Event trigger cannot be executed in an aborted transaction
Event trigger events
ddl_command_start
This event occurs jsut BEFORE a CREATE, ALTER, or DROP DLL command is executed
ddl_command_end
This event occurs just AFTER a create, alter, or drop command has finished executing
table_rewrite
This event occurs just before a table is re written by some action of the commands ALTER TABLE and ALTER TYPE.
sql_drop
This evetn occurs just before the ddl_command_end eevent for the commands that frop database objects
Event trigger variables
TG_TAG: this variable contains the 'TAG' or the command for which the trigger is executed.TG_EVENT: This variable contains the event name, which can be ddl_command_start, ddl_comman_end, and sql_drop.
Creating an auditing event trigger
Dont allow anyone to create table between time
Dropping event trigger
Last updated
Was this helpful?