Last active
November 16, 2020 22:12
-
-
Save Breefield/2729fbe6e86b286e8b86c65c6fa19d33 to your computer and use it in GitHub Desktop.
This file contains 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 OR REPLACE FUNCTION | |
record_inventory_change() | |
RETURNS TRIGGER LANGUAGE plpgsql AS $$ | |
DECLARE | |
columns text; | |
entity RECORD := NEW; | |
_deleted VARCHAR(5) := 'false'; | |
BEGIN | |
SELECT string_agg(column_name, ',') INTO columns from information_schema.columns where table_name = 'inventory'; | |
IF TG_OP = 'DELETE' THEN | |
entity := OLD; | |
_deleted := 'true'; | |
END IF; | |
EXECUTE format('INSERT INTO inventory_audit (%1$s,_deleted) SELECT %1$s, %2$s AS _deleted FROM inventory WHERE id=%3$s;', | |
columns, _deleted, entity.id | |
); | |
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; | |
RETURN NULL; | |
END; | |
$$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment