Skip to content

Instantly share code, notes, and snippets.

@rodo
Created December 9, 2021 09:51
Show Gist options
  • Select an option

  • Save rodo/320499c515e5c215e9b580a7ee28d564 to your computer and use it in GitHub Desktop.

Select an option

Save rodo/320499c515e5c215e9b580a7ee28d564 to your computer and use it in GitHub Desktop.
PostgreSQL trigger to historize data
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