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:

  1. this change caused changing "user".id 1 user another. in case decrease total old user , increase new user.
  2. this change caused changing id in table "user" (and on update cascade changes corresponding user_ids in purchase). 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

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -