0

I have a PostgreSQL trigger that is not firing sometimes, even though the status is always shown as "enabled".

My trigger code is as follows:

CREATE OR REPLACE FUNCTION audit_src_exhibit() RETURNS trigger AS $BODY$
BEGIN
  IF TG_OP = 'INSERT' then
        if new.audit_created_date is null  THEN
        new.audit_created_date := current_timestamp;
        new.audit_created_by := session_user::text;
    end if;
    else
        if new.audit_modified_date is null  THEN
        new.audit_modified_date := current_timestamp;
        new.audit_modified_by := session_user::text;
    end if;
END IF;
  RETURN NEW;
END; $BODY$ LANGUAGE plpgsql VOLATILE;

CREATE TRIGGER audit_src_exhibit_tr
BEFORE INSERT OR UPDATE ON <table>
FOR EACH ROW EXECUTE PROCEDURE audit_src_exhibit();


Is there any specific reason for this behaviour?
Does my code show any signs of known issues which would result in triggers not firing?

I am getting the audit columns as empty even though some insert and update happened todayenter image description here

4
  • That trigger will fire for every row that is inserted or updated. What leads you to believe it doesn't fire? Please describe the symptoms in detail, ideally with example data. Commented Feb 7, 2023 at 8:56
  • @LaurenzAlbe Yes I find the column "audit_created_date " is not populated where some insert and update happened even though trigger status is showing as "enabled"
    – Arun
    Commented Feb 7, 2023 at 9:06
  • With your code, audit_created_date can be NULL if the operation is an UPDATE. Commented Feb 7, 2023 at 9:32
  • but today all statements was insert event only no update happened
    – Arun
    Commented Feb 7, 2023 at 9:37

1 Answer 1

0

The NULL values for audit_created_date could be explained if the operation was an UPDATE, because your trigger doesn't modify audit_created_date in that case.

If those were INSERTs, then the only possible explanations would be

  1. The trigger was not defined or disabled at the time the statements happened. To preempt the follow-up question: no, PostgreSQL doesn't disable triggers on its own.

  2. session_replication_role was set to replica when the statements were executed. That will prevent firing of all except replica triggers. You can change that for a trigger with

    ALTER TABLE "<table>" ENABLE ALWAYS TRIGGER audit_src_exhibit_tr;
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.