Question

is is possible in postgres to have a trigger on CREATE TABLE that will create triggers for the newly created table?

for example,

CREATE TABLE base_abc(
   ...
) inherits( base );

I would like to automatically add triggers to the newly create table base_abc that would, for example, that would calculate a column value based on column names.

likewise, is it possible to trigger on ALTER TABLE so that the triggers can be dropped and recreated?

for context, see what is best way to extend postgresql to index json objects?

Was it helpful?

Solution

Don't think there's a way to implement such "triggers" using PostgreSQL built-in functions, but you can definitely write a stored function that will do what you want - i.e. create a derived table and then a trigger on that table.

You can also write one for ALTERing tables.

OTHER TIPS

Found this question when googling and since things have changed decided to add contemporary answer. As of 9.3 we have event triggers. Read online docs for more info.

What you ask can be done similar to:

event_tg_example=# CREATE OR REPLACE FUNCTION add_tg_fn()
        RETURNS event_trigger LANGUAGE plpgsql AS $f$
DECLARE
    obj record;
BEGIN
  FOR obj IN SELECT * FROM pg_event_trigger_ddl_commands()
  LOOP
  execute format('create function %I() returns trigger as $tgf$ begin raise info %L, $i$here$i$; return old; end $tgf$ language $l$plpgsql$l$', 'blah_'||obj.objid::regclass,'%');
  execute format ('CREATE TRIGGER tg_blah BEFORE DELETE ON %I FOR EACH ROW EXECUTE PROCEDURE %I();', obj.objid::regclass, 'blah_'||obj.objid::regclass);

  END LOOP;
END
$f$
;
CREATE FUNCTION
event_tg_example=# CREATE EVENT TRIGGER add_tg_tg
   ON ddl_command_end
WHEN TAG IN ('CREATE TABLE')
   EXECUTE PROCEDURE add_tg_fn()
;
CREATE EVENT TRIGGER
event_tg_example=# create table t(i int);
CREATE TABLE
event_tg_example=# insert into t values (1);
INSERT 0 1
event_tg_example=# delete from t where i = 1;
INFO:  here
DELETE 1
event_tg_example=#

Mind this is just a working example, don't copy/paste it blindly

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top