3

I've implemented the Logical replication in PostgreSQL 10 within 2 db in 2 different server and I'm aware that the sequences are not sync so I created a trigger function like this in both database:

CREATE FUNCTION update_ogc_fid()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE NOT LEAKPROOF 
AS $BODY$
Declare 
iInt integer;
BEGIN
execute 'Select nextval('|| chr(39) || 'address_ogc_fid_seq' || chr(39) ||');' into iInt;
NEW.ogc_fid = iInt;
RETURN NEW;
END;
$BODY$;

CREATE TRIGGER update_ogc_fid_address
    BEFORE INSERT 
    ON address
    FOR EACH ROW
    EXECUTE PROCEDURE update_ogc_fid();

A part from the fact that is actually using just odd ID in the DB1 and even in DB2 why is the function not triggered in the second database?

If I insert a record in the DB1 i have ID 3, it do the replication and in the DB2 i have the same record with the same ID, I'm going to check the sequence in the DB2 and is still 1 instead of be 3.

Now I'm going to insert a record in the DB2 and I have ID 2 and then 4.

For what I want to achieve that is a master master system, in case that one is down I can write in the second one I don't really care too much but thinking in case of a disaster when I'm going to restore the DB in the server that is down (maybe with a pg-dump backup) I need to update all the sequences to start writing from where was before.

2 Answers 2

8

Triggers are by default not executed on logical standby servers, because the parameter session_replication_role is set to replica when the changes are applied.

You can change a trigger so that it fires even during replication:

ALTER TABLE mytab
   ENABLE ALWAYS TRIGGER atrigger;
4
  • 1
    This will make the trigger fire, but if the goal is to keep sequences in sync across a multi-master setup, I don't think this trigger is going to do it... Commented Jun 19, 2019 at 16:12
  • I've used this tutorial, I'm using wal_level = logical digitalocean.com/community/tutorials/…
    – DevWizard
    Commented Jun 19, 2019 at 19:12
  • 1
    @NickBarnes I agree. I just tried to explain why the triggers don't fire. Commented Jun 19, 2019 at 19:23
  • I'll give it a try and see what happens
    – DevWizard
    Commented Jun 20, 2019 at 7:01
1
CREATE  TRIGGER yours_trigger_name
AFTER INSERT OR UPDATE ON yours_table_name
FOR EACH ROW
EXECUTE PROCEDURE yours_trigger_procedure_name();

alter table yours_table_name enable always trigger yours_trigger_name;
alter table yours_table_name enable replica trigger yours_trigger_name;

This construction works in replication, but if you want to use UPDATE OF yours_field_name instead of just UPDATE it doesn't work. I don't know why)))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.