views:

997

answers:

2

How to prevent recursive execution of trigger? Let's say i want to construct a "tree-able" description on chart of account. So what I do is when a new record is inserted/updated, I update the the parent record's down_qty, so this would trigger the update trigger recursively

Right now, my code is ok, i do this:

I put this on UPDATE trigger's first line:

-- prevents recursive trigger
if new.track_recursive_trigger <> old.track_recursive_trigger then
    return new;
end if;

And this is the sample code from my trigger when I need to update the parent record's qty:

update account_category set 

 track_recursive_trigger = track_recursive_trigger + 1, -- i put this line to prevent recursive trigger

 down_qty = down_qty - (old.down_qty + 1)

where account_category_id = m_parent_account;


I'm thinking if there's a way in PostgreSQL to detect recursive trigger without introducing a new field, something analogous to MSSQL's trigger_nestlevel

[EDIT]

i loop inside the tree, i need to bubble up the down_qty of each account_category back to its root. example, i insert a new account category, it needs to increment the down_qty of its parent account_category, likewise when i change the account category's parent account_category, i need to decrement the down_qty of account_category's previous parent account_category. though i think it can, i'm not letting postgres do the recursive trigger. i used mssql before where the trigger recursive depth level is limited only up to 16 levels

+1  A: 

In pg, it's up to you to track trigger recursion.

If a trigger function executes SQL commands then these commands might fire triggers again. This is known as cascading triggers. There is no direct limitation on the number of cascade levels. It is possible for cascades to cause a recursive invocation of the same trigger; for example, an INSERT trigger might execute a command that inserts an additional row into the same table, causing the INSERT trigger to be fired again. It is the trigger programmer's responsibility to avoid infinite recursion in such scenarios.

http://www.postgresql.org/docs/8.3/static/trigger-definition.html

tpdi
A: 

At the beggining of the definition of the trigger you can disable triggers on that particular table, and reenable them at the end (and make sure an exception doesn't terminate the execution before expected!). This has many deep holes, but may work for some light implementations. Notice that for this implementation, you will also need priviliges to disable triggers.

diegom_ch