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".id
1 user another. in case decreasetotal
old user , increase new user. - this change caused changing
id
in table"user"
(andon update cascade
changes correspondinguser_id
s 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; update
s 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