Description:
- I am running
postgresql 13
- I have two tables under different schemas,
t1
andt2
. t2
is derivative oft1
in the sense that they share all the same columns and data, butt2
is always downstream oft1
as far as validity.- The rows in both tables share the same primary key, which is what I assume would be used as the link between them.
The ask:
- I would like to create a trigger that reflects any changes in
t1
and syncst2
to be the same. - I started with
INSERT
orUPDATE
, but ifDELETE
is easily added, I would like to implement that as well.
Trigger Code:
-- Trigger for t1 to t2 --
CREATE OR REPLACE FUNCTION t1_schema.sync_trigger()
RETURNS TRIGGER AS
$$
BEGIN
INSERT INTO t2_schema.t2 (col1, col2, col3)
VALUES (NEW.col1, NEW.col2, NEW.col3);
RETURN NEW;
END
$$ LANGUAGE plpgsql;
CREATE TRIGGER t1t2_test_sync
AFTER INSERT OR UPDATE ON t1_schema.t1
FOR EACH ROW
EXECUTE PROCEDURE t1_schema.sync_trigger()
When I execute this code and do a test UPDATE
on t1
, the same row on t2
does not reflect the changes or give me any errors.
I have tried:
- Discretely labeling all rows as updated with
NEW.
format, but run into the problem of primary key column not being editable int2
. - Adding a
WHERE
clause after theVALUES
clause, something likeWHERE primary_key=NEW.primary_key
, but I get an error. - Another option I have seen is adding an
IF
statement before theINSERT
, or adding aWHEN
clause in the trigger, but neither have worked.