In PostgreSQL 9.3.5, I'm trying to prevent a trigger from executing again due to an update or insert within the current trigger or another trigger that executes upon update or insert. So I want to know what the source of the update is so I can prevent recursive triggering.
Unless I missed it, I looked here and didn't read anything about this in the manual:
https://www.postgresql.org/docs/9.3/static/plpgsql-trigger.html
I don't think this would work because I am thinking it will always return the trigger I am currently in, not the source (trigger or not) of the udpate or insert:
TG_NAME
Data type name; variable that contains the name of the trigger actually fired
Currently I am doing a lot of old.col_nm <> new.col_nm
etc. to try and determine via the values that change if it was one of my triggers or not. It would be nice if I could just say "if an update or insert came from a trigger return new;
" and skip the bulk of the trigger.
Best Answer
There are several ways for determining if the trigger is recursing. Checking the trigger depth (
pg_trigger_depth()
) is not one of them, because you don't know if the trigger itself is recursing or is being fired from another trigger.The only direct way to know analysing the execution stack during an exception:
Exception handling is costly, but so are the other options, which require leaving a session marker for avoiding recursion, either using a temporary table, or a session variable:
or using a session variable:
All of the options above have a significant performance impact. A possibly better performing option could involve a table for this purpose:
which can be used like: