0

I have two tables: my_table1 and my_table2. a_column in my_table2 should always match the corresponding value in my_table1.

However, the tricky part is that rows in my_table2 may be inserted before or after the corresponding row in my_table1.

I’ve tried to handle this using triggers, but it's not working as expected. Here's what I have so far:

CREATE OR REPLACE FUNCTION trig_get_column_data() RETURNS trigger AS
$$
BEGIN
    SELECT a_column
    FROM my_table1
    WHERE (a, b) = (new.a, new.b)
    INTO new.column;
    RETURN new;
END;
$$ LANGUAGE plpgsql;


CREATE OR REPLACE TRIGGER get_column_data
    BEFORE INSERT OR UPDATE
    ON my_table2
    FOR EACH ROW
    WHEN ( new.a_column ISNULL OR TRIM( BOTH new.a_column ) = '')
EXECUTE PROCEDURE trig_get_column_data();

CREATE OR REPLACE FUNCTION trig_aft_ins() RETURNS trigger AS
$$
BEGIN
    UPDATE my_table2 t
        SET a_column = o.a_column
    FROM new_datas o
    WHERE (t.a, t.b) = (o.a, o.b);
    RETURN new;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trig_aft_ins
    AFTER INSERT
    ON my_table1
    REFERENCING new TABLE AS new_datas
    FOR EACH STATEMENT
EXECUTE PROCEDURE trig_aft_ins( )

The issue I'm facing is that sometimes the a_column in my_table2 doesn't get updated when the corresponding row in my_table1 is inserted later. How can I ensure that a_column in my_table2 always reflects the correct value from my_table1, regardless of which row gets inserted first?

Any help or better approach is appreciated!

9
  • I understand that you have simplified your use case to make it self-contained for Stack Overflow (good thing!), but could you use another name than column which is a reserved keyword, throwing a syntax error on call of your trigger? Commented Apr 9 at 7:48
  • Have you tried bidirectional sync? Commented Apr 9 at 8:03
  • Do you reproduce it in a sequential setup (with or without transactions), or does it occur only on concurrent queries (one web server thread doing inserts to my_table1, another to my_table2)? Commented Apr 9 at 8:07
  • 4
    Why must my_table2 contain this column at all? Can't you just select it from table_1 whenever you need it with a mere join? And if you want it more convenient, you'll create a view on the joined tables. Commented Apr 9 at 10:05
  • This sounds like a bug in your data model. A trigger can't see data from concurrent processes, and that might cause new problems. I would double-check the data model first before even thinking about a trigger. Commented Apr 9 at 15:34

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.