Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass NEW/OLD to procedures called from trigger functions in PostgreSQL?

Let's suppose I have a trigger function, but its code is so complex that it would be handy to split it to more procedures. I want to operate with the NEW (or OLD for UPDATE/DELETE triggers) variable in all of them. Is there any alternative to sending it as a function parameter to every procedure called from the original trigger function?

like image 750
Pavel V. Avatar asked Jan 28 '26 19:01

Pavel V.


1 Answers

If you really need to pass them around, I'm quite sure you can do so as appropriately typed records (e.g. newrow tablename%ROWTYPE).

http://www.postgresql.org/docs/current/static/plpgsql-declarations.html

That said, unless you run giant queries whose results you use throughout the trigger function, breaking the trigger into smaller parts is usually a cleaner than calling subfunctions imho. Note that you can conditionally execute the triggers, e.g.:

create trigger "01_do_stuff_upd" on update after tablename
  for each row
  when (old.field <> new.field and ...)
execute procedure do_stuff_upd_part_01();

The thing to have in mind when doing the above, is that in Postgres (and contrary to the sql spec), the triggers are executed in alphabetical order rather than in the order they're created.

like image 156
Denis de Bernardy Avatar answered Jan 30 '26 17:01

Denis de Bernardy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!