Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use NSBatchDeleteRequest on entities with relationships that have delete rules?

Tags:

core-data

I'm attempting to use NSBatchDeleteRequest to delete a pile of entities, many of these entities have delete cascade and/or nullify rules.

My first attempt to delete anything fails and the NSError I get back includes the string "Delete rule is not supported for batch deletes". I had thought it was fine to delete such things but i was responsible for making sure all the constraints are satisfied before I do a save.

Should I be able to batch delete these managed objects? (I want to keep the delete rules, other delete paths don't have an easy way to know what set of objects to delete) Do some kinds of batch deletes work in this case, but others not? (say predicates fail, but a list of object IDs work?)

like image 307
Stripes Avatar asked Jan 08 '23 10:01

Stripes


1 Answers

Batch delete is problematic with relationships.

It goes directly to the database and deletes the records suspending all object graph rules, including the delete rules. You have correctly identified the requirement that you need to do all the constraint checking yourself again. (That by itself could be a deal-breaker.)

Even if you manage to delete the entities and all the necessary related entities correctly, you will still be left with lots of entries in the (opaque) join table Core Data creates in the background. There is no obvious safe way to delete the entries in the join tables and they have been reported to interfere with managing relationships in future operations.

IMO , the solution in this case is to still use the object graph rather than batch delete and optimize for performance. There are many good answers on SOF on how to do this, but most of it can be summarized with these points:

  • find the right batch size for saving (typically 500 entities for creation, about 2000 for deletion, but this could vary according to object size and relationship complexity - you have to experiment).
  • if you have memory constraints, use autoreleasepools.
  • use a background context to free the UI for interaction. I prefer to do the saving to the database in the background after updating the UI.
like image 107
Mundi Avatar answered May 07 '23 14:05

Mundi