Created
December 9, 2021 09:51
-
-
Save rodo/320499c515e5c215e9b580a7ee28d564 to your computer and use it in GitHub Desktop.
PostgreSQL trigger to historize data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| CREATE FUNCTION {{table_name}}_historization_update_trg() | |
| RETURNS trigger LANGUAGE plpgsql AS $$ | |
| BEGIN | |
| -- we increment the version number | |
| NEW.version = OLD.version + 1; | |
| INSERT INTO {{schema}}.{{table_name}}_log (id, version, data) | |
| VALUES (NEW.id, NEW.version, to_json(NEW)); | |
| RETURN NEW; | |
| END; | |
| $$; | |
| -- | |
| -- Do not log when rows are identical | |
| -- | |
| CREATE TRIGGER {{table_name}}_historization_trg | |
| BEFORE UPDATE ON {{table_name}} | |
| FOR EACH ROW | |
| WHEN (NEW <> OLD) | |
| EXECUTE PROCEDURE {{table_name}}_historization_update_trg(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment