Last active
August 9, 2024 12:22
-
-
Save mpellegrini/eecd0459c2b21288da042f584aa30d34 to your computer and use it in GitHub Desktop.
Postgres Function and Trigger to Update Audit Metadata Fields
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 public.update_audit_metadata() | |
RETURNS trigger | |
LANGUAGE 'plpgsql' | |
AS | |
$function$ | |
BEGIN | |
NEW.created_at := OLD.created_at; | |
NEW.created_by := OLD.created_by; | |
NEW.version := OLD.version; | |
IF row (NEW.*) IS DISTINCT FROM row (OLD.*) THEN | |
NEW.updated_at := now(); | |
NEW.version := OLD.version + 1; | |
RETURN NEW; | |
ELSE | |
RETURN OLD; | |
END IF; | |
END; | |
$function$ |
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 TRIGGER bu_{tablename}_update_audit_metadata | |
BEFORE UPDATE | |
ON "schema"."tablename" | |
FOR EACH ROW | |
EXECUTE PROCEDURE update_audit_metadata(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment