Is there a way to get the JSON of the only modified fields?
Now I use the following trigger but the entire line is printed in the changelog.
Example tables:
TABLE tbl_changelog (
tbl TEXT,
op TEXT,
new JSON,
old JSON
);
TABLE tbl_items (
f1 TEXT,
f2 TEXT
);
Trigger:
CREATE OR REPLACE FUNCTION changelog_procedure() RETURNS trigger AS $$
BEGIN
INSERT INTO tbl_changelog(tbl, op, new, old)
VALUES (TG_TABLE_NAME, TG_OP, row_to_json(NEW), row_to_json(OLD));
RETURN NULL;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER changelog_items
AFTER INSERT OR UPDATE OR DELETE ON tbl_items
FOR EACH ROW EXECUTE PROCEDURE changelog_procedure();
After inserting and uploaded f2 and f1 the changelog is the following:
tbl_changelog
------------------------------------------------------------------
tbl | op | new | old
------------------------------------------------------------------
tbl_items | INSERT | {f1: "aa", f2: "bb"} |
------------------------------------------------------------------
tbl_items | UPDATE | {f1: "aa", f2: "cc"} | {f1: "aa", f2: "bb"}
------------------------------------------------------------------
tbl_items | UPDATE | {f1: "dd", f2: "cc"} | {f1: "aa", f2: "cc"}
------------------------------------------------------------------
I would like to record only the changes, that is:
tbl_changelog
------------------------------------------------------------------
tbl | op | new | old
------------------------------------------------------------------
tbl_items | INSERT | {f1: "aa", f2: "bb"} |
------------------------------------------------------------------
tbl_items | UPDATE | {f2: "cc"} | {f2: "bb"}
------------------------------------------------------------------
tbl_items | UPDATE | {f1: "dd"} | {f1: "aa"}
------------------------------------------------------------------