Dynamically pull out NEW in a postgres trigger

NEW is really just a ROW structure so you can turn it into JSON and
dynamically pull out the values however you wish.

CREATE OR REPLACE FUNCTION test_trigger()
RETURNS TRIGGER AS $$
DECLARE
  pk_column VARCHAR;
  pk_val    INT;
BEGIN
    pk_column := TG_ARGV[0];
    pk_val := row_to_json(NEW)->>pk_column;



    INSERT INTO bar (baz) VALUES (pk_val);



    RETURN NEW;
END;
$$
LANGUAGE plpgsql;

https://www.postgresql.org/message-id/CAB_5SRfwgWNatbmarwzrSEFhXU3gVsRazt-96ijS1dXPGJ5uPA%40mail.gmail.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s