2

I have 2 DB , 1st is master db and 2nd is replica db (just some tables of master DB). I try to add the trigger on replica table to catching when it is replicated from master db tables.

I using the trigger for catching insert, delete and update action but it seem not work. that trigger only work for some table that change from sql statement. Not work for replica tables.

Is there any way to catching the replica tables changes? I using go lang and follow guide of this post https://coussej.github.io/2015/09/15/Listening-to-generic-JSON-notifications-from-PostgreSQL-in-Go/

i did these step :

-- create function
CREATE OR REPLACE FUNCTION notify_event() RETURNS TRIGGER AS $$
DECLARE
data json;
notification json;
BEGIN
IF (TG_OP = 'DELETE') THEN
data = row_to_json(OLD);
ELSE
data = row_to_json(NEW);
END IF;
notification = json_build_object(
'table',TG_TABLE_NAME,
'action', TG_OP,
'data', data);
PERFORM pg_notify('events',notification::text);
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- create trigger
CREATE TRIGGER user_warehouse_notify_event
AFTER INSERT OR UPDATE OR DELETE ON users_warehouse_rel
FOR EACH ROW EXECUTE PROCEDURE notify_event();

-- enable replica trigger 
ALTER TABLE users_warehouse_rel ENABLE REPLICA TRIGGER user_warehouse_notify_event

it's still not work

1 Answer 1

4

When logical replication applies its changes, session_replication_role is set to replica so that normal triggers are not triggered.

To change that for your trigger, use

ALTER TABLE atable ENABLE ALWAYS TRIGGER trigger_name;

Think twice before using this – badly defined triggers can break replication.

2
  • OP, I would add that if you tried a trigger on master and found out that it generates too much noise or load, and you are now trying to do triggering on replica instead in order not to mess up your master, this would not work and will with a high probability backfire.
    – ADEpt
    Commented Oct 16, 2019 at 12:57
  • What do you mean? What do you get for \d table_name? Commented Oct 17, 2019 at 5:57

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.