I have several tables that are periodically updated from the server (Benefit
, Branch
, Coupon
) and two more tables that are only local (FavoriteBenefit
, UsedCoupon
). ER diagram looks like this:
Whenever a Benefit
is deleted on the server, I also want to delete an appropriate entity from FavoriteBenefit
. For that, I can use onDelete = ForeignKey.CASCADE
and whenever parent Benefit
no longer exists in the database, FavoriteBenefit
gets deleted as well. Sounds good.
A problem arises whenever I use
@Insert(onConflict = OnConflictStrategy.REPLACE)
to update benefits in the database. REPLACE
actually performs a DELETE
and INSERT
but DELETE
internally triggers onDelete
of FavoriteBenefit
and as a result, all data in that table gets deleted as well.
(A similar problem occurs with Coupon
and UsedCoupon
tables.)
I am looking for a way to temporarily disable Foreign Key constraints until the end of the transaction. That is, do not validate Foreign Keys during the transaction but only at the end of the transaction. I still want Room to automatically delete entities that do not have a valid parent.
It seems that marking foreign key as defferred by setting deferred = true
on the @ForeignKey
definition should do exactly what I am trying to achieve.
boolean deferred ()
A foreign key constraint can be deferred until the transaction is complete. This is useful if you are doing bulk inserts into the database in a single transaction. By default, foreign key constraints are immediate but you can change it by setting this field to true.
But even when I set the deferred
flag it seems to have no effect because FavoriteBenefit
is still being deleted every time.
Am I understanding the deferred
flag incorrectly?