Skip to content

Instantly share code, notes, and snippets.

@mpellegrini
Last active August 9, 2024 12:22
Show Gist options
  • Save mpellegrini/eecd0459c2b21288da042f584aa30d34 to your computer and use it in GitHub Desktop.
Save mpellegrini/eecd0459c2b21288da042f584aa30d34 to your computer and use it in GitHub Desktop.
Postgres Function and Trigger to Update Audit Metadata Fields
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$
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