I am using a trigger to log all the UPDATE and INSERT OPERATION, but my table has many columns, and I would like to log which column did I updated or inserted and their new and old values. The following is a demonstration of what I am trying to achieve:
big table
-------------------------
id |feild_1 | field_2| field_3 .....
-----------------------------------------------
usr1 |old_value1|
usr2 |old_value2|
suppose I change value in usr1 filed_1 to 'new_value1'. I would like to see in my change history :
change history
-------------------------
id |field_changed | old_value | new_value |
-----------------------------------------------------------
usr1 |field_1 |old_value_1|new_value_1|
The difficulty lies in achieving the name of the column I modified. The current trigger function I used is modified from https://stackoverflow.com/a/49872254/5749562. It looks like the following:
CREATE FUNCTION change_trigger() RETURNS trigger AS $$
BEGIN
IF TG_OP = 'INSERT'
THEN INSERT INTO change_history (
id, old_value, new_value
) VALUES (
OLD.id, row_to_json(OLD), row_to_json(NEW)
);
RETURN NEW;
ELSIF TG_OP = 'UPDATE'
THEN
INSERT INTO change_history (
id, old_value, new_value
)
VALUES (OLD.id, row_to_json(OLD), row_to_json(NEW));
RETURN NEW;
END IF;
END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER;
As you can see all the columns are recorded during the change, which is not so informative for big table. How I can modify my trigger function?