database - How to catch in trigger what changes caused by foreign key integrity in Postgres PL/PGSQL? -
case example: table "user" has fields id , total, table purchase has user_id (as foreign key "user".id on update cascade , on delete cascade) , cost.
i auto-update total on changes in purchase (so total equal sum of purchases given user). via row trigger after insert or update or delete on purchase. technically possible purchase.user_id changed, , there 2 cases:
- this change caused changing
"user".id1 user another. in case decreasetotalold user , increase new user. - this change caused changing
idin table"user"(andon update cascadechanges correspondinguser_ids inpurchase). in case should nothing own trigger.
how catch second case in trigger? there analogous question catching deletion in purchase caused deletion in "user".
for case of cascading delete there nothing do; updates trigger on purchase nothing matching row in "user" not exist more.
to handle update of "user".id, create trigger before update on "user" sets new.total 0. after trigger on purchase has run, value same before.
Comments
Post a Comment