CoreData lightweight migration possibility

Situation:

  1. Sometimes between releases we change CoreData model and changes can be either supported by automatic lightweight migration or not.
  2. We are checking if current model in app's bundle compatible with persisted data by NSManagedObjectModel.isConfiguration(withName:compatibleWithStoreMetadata:).
  3. If it's not supported we are good to drop the database (because it's mainly used for caching purposes), but the problem that method returns false even if lightweight migration is possible so cache could be potentially preserved without manual migrations.

Thoughts: Documentation states that:

To perform automatic lightweight migration, Core Data needs to be able to find the source and destination managed object models at runtime.

So we can manually check if lightweight migration possible by calling NSMappingModel.inferredMappingModel(forSourceModel:destinationModel:) But where to obtain this source model?

I know that I can keep all model versions in the bundle and create a new one for each change, but in fact I can just add new property to any entity in model (without creation a new model version) and lightweight migration works perfectly.

So what should be forSourceModel parameter in this case? In case model changes in between releases without preserving the old one? Or may be there are other ways to check if lightweight migration is going to take place during .loadPersistentStores call?

Accepted Answer

So I've found that it's only possible via manual querying of Z_MODELCACHE -> Z_CONTENT data from SQLite file, decompressing it via zlib and decoding via NSKeyedUnarchiever. This is how CoreData internally works.

Submitted feedback to make this logic public in FB10972098.

CoreData lightweight migration possibility
 
 
Q