20

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

AdamL
  • 11,328
  • 5
  • 49
  • 72
Julien
  • 371
  • 3
  • 9

3 Answers3

15

I know it's an old question but now it has been implemented in version 9.3, or at least partially http://www.postgresql.org/docs/9.3/static/event-trigger-definition.html

Ali
  • 526
  • 6
  • 23
15

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.

gilad905
  • 2,370
  • 2
  • 13
  • 22
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

Ilya
  • 97
  • 3
  • 5
JotaBe
  • 36,481
  • 7
  • 93
  • 114