Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql trigger for all tables that include create date

I have 54 tables in my postgresql databse. And most of tables includes date of creation time the data. I want to create a global trigger for all tables which include CreatedDate column. And this trigger will update the column when a record inserted.

like image 223
barteloma Avatar asked Apr 08 '26 20:04

barteloma


2 Answers

Every table needs its own trigger, but you can use a single trigger function:

CREATE FUNCTION set_created_date() RETURNS trigger AS $$
BEGIN
  NEW.createddate := CURRENT_TIME;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

For each table you should have a trigger like this:

CREATE TRIGGER set_createddate
BEFORE INSERT ON <table name>
FOR EACH ROW EXECUTE PROCEDURE set_created_date();

You can set the trigger for all 54 tables with this code (first create the trigger function):

DO $$
DECLARE
    t record;
BEGIN
    FOR t IN 
        SELECT * FROM information_schema.columns
        WHERE column_name = 'createddate'
    LOOP
        EXECUTE format('CREATE TRIGGER set_createddate
                        BEFORE INSERT ON %I.%I
                        FOR EACH ROW EXECUTE PROCEDURE set_created_date()',
                        t.table_schema, t.table_name);
    END LOOP;
END;
$$ LANGUAGE plpgsql;

This obviously assumes that there are no other tables with a column named createddate. This you can check easily by querying the information_schema.columns table.

like image 112
Patrick Avatar answered Apr 11 '26 02:04

Patrick


For those who have some problems with Patrick's solution. Here the same code with some improvement :

DO $$
DECLARE
    t text;
BEGIN
    FOR t IN 
        SELECT table_name FROM information_schema.columns
        WHERE column_name = 'createddate'
    LOOP
        EXECUTE format('CREATE TRIGGER set_createddate
                        BEFORE INSERT ON %I
                        FOR EACH ROW EXECUTE PROCEDURE set_created_date()',
                        t);
    END LOOP;
END;
$$ LANGUAGE plpgsql;
like image 36
Gnoocki Avatar answered Apr 11 '26 01:04

Gnoocki