Search code examples
postgresqltriggersinsertsynchronizationpostgresql-9.3

sync two tables after insert


I am using postgresql. I have two schemas main and sec containing only one table datastore with the same structure (this is only an extract) I am trying unsucessfully to create a trigger for keep sync both tables when insert occurs in one of them. The problem is some kind of circular or recursive reference.

Can you create some example for solve this?

I am working on this, I'll post my solution later. You can use this code as reference for creating schemas and tables

    CREATE SCHEMA main;
    CREATE SCHEMA sec;
    SET search_path = main, pg_catalog;
    CREATE TABLE datastore (
        fullname character varying,
        age integer
    );
    SET search_path = sec, pg_catalog;
    CREATE TABLE datastore (
        fullname character varying,
        age integer
    );

Solution

  • An updatable view is the best solution and is as simple as (Postgres 9.3+):

    drop table sec.datastore;
    create view sec.datastore
    as select * from main.datastore;
    

    However, if you cannot do it for some inscrutable reasons, use pg_trigger_depth() function (Postgres 9.2+) to ensure that the trigger function is not executed during replication. The trigger on main.datastore may look like this:

    create or replace function main.datastore_insert_trigger()
    returns trigger language plpgsql as $$
    begin
        insert into sec.datastore
        select new.fullname, new.age;
        return new;
    end $$;
    
    create trigger datastore_insert_trigger
    before insert on main.datastore
    for each row when (pg_trigger_depth() = 0)
    execute procedure main.datastore_insert_trigger();
    

    The trigger on sec.datastore should be defined analogously.