Created
August 26, 2022 17:37
-
-
Save MarshalOfficial/7078a98724e88e0214f99cedb4b9ae77 to your computer and use it in GitHub Desktop.
postgresql table changes log history
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 SCHEMA logging; | |
| CREATE TABLE logging.table_history ( | |
| id serial, | |
| tstamp timestamp DEFAULT now(), | |
| schemaname text, | |
| tabname text, | |
| operation text, | |
| who text DEFAULT current_user, | |
| new_val json, | |
| old_val json | |
| ); | |
| -- | |
| CREATE OR REPLACE FUNCTION public.change_trigger() | |
| RETURNS trigger | |
| LANGUAGE 'plpgsql' | |
| COST 100 | |
| VOLATILE NOT LEAKPROOF SECURITY DEFINER | |
| AS $BODY$ | |
| BEGIN | |
| IF TG_OP = 'INSERT' | |
| THEN INSERT INTO logging.table_history ( | |
| tabname, schemaname, operation, new_val | |
| ) VALUES ( | |
| TG_RELNAME, TG_TABLE_SCHEMA, TG_OP, row_to_json(NEW) | |
| ); | |
| RETURN NEW; | |
| ELSIF TG_OP = 'UPDATE' | |
| THEN | |
| INSERT INTO logging.table_history ( | |
| tabname, schemaname, operation, new_val, old_val | |
| ) | |
| VALUES (TG_RELNAME, TG_TABLE_SCHEMA, TG_OP, row_to_json(NEW), row_to_json(OLD)); | |
| RETURN NEW; | |
| ELSIF TG_OP = 'DELETE' | |
| THEN | |
| INSERT INTO logging.table_history | |
| (tabname, schemaname, operation, old_val) | |
| VALUES ( | |
| TG_RELNAME, TG_TABLE_SCHEMA, TG_OP, row_to_json(OLD) | |
| ); | |
| RETURN OLD; | |
| END IF; | |
| END; | |
| $BODY$; | |
| ALTER FUNCTION public.change_trigger() | |
| OWNER TO postgres; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment