execute a trigger when I create a table
Asked Answered
S

3

25

I would like to know if a trigger on a system table of PostgreSQL can be executed when I create a table

I need to add 2 functions on each table of my database and I would like to do it dynamically

Thanks

Selfimmolation answered 23/3, 2012 at 13:6 Comment(0)
H
20

This can be done with an event trigger:

CREATE OR REPLACE FUNCTION on_create_table_func()
RETURNS event_trigger AS $$
BEGIN
    -- your code here
END
$$
LANGUAGE plpgsql;

CREATE EVENT TRIGGER
on_create_table ON ddl_command_end
WHEN TAG IN ('CREATE TABLE')
EXECUTE PROCEDURE on_create_table_func();

Note that there is no way to directly execute any query on the newly created table, or even get its name. I don't know what you mean by "add 2 functions on each table" since functions don't belong to a specific table, but if you need to perform an operation specific for the new tables, this might not be for you.

Hallucinosis answered 6/6, 2017 at 11:4 Comment(0)
H
16

it has been implemented since version 9.3 https://www.postgresql.org/docs/current/event-trigger-definition.html

Homemade answered 11/10, 2013 at 10:14 Comment(0)
B
1

You're looking for "DDL Triggers". They're not implemented in PostgreSQL. Neither you can add triggers to system tables. Look at this forum entry:

Adding ddl audit trigger

Bub answered 23/3, 2012 at 13:13 Comment(2)
@Bub deadlinkCadent
There are event triggers now. postgresql.org/docs/13/event-triggers.htmlRipplet

© 2022 - 2024 — McMap. All rights reserved.