Skip to content

Instantly share code, notes, and snippets.

@Breefield
Last active November 16, 2020 22:12
Show Gist options
  • Save Breefield/2729fbe6e86b286e8b86c65c6fa19d33 to your computer and use it in GitHub Desktop.
Save Breefield/2729fbe6e86b286e8b86c65c6fa19d33 to your computer and use it in GitHub Desktop.
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