[CoreData] Migrating To A New Model With An Extra Entity

As I mentioned in the previous post, I ran into an annoying problem with CoreData very recently:

Problem: We needed to have an evolution of the model, which in its simplest form meant adding an entity.

Naive solution: Well, duh. Lightweight migration will work just fine. If not, just make a mapping model, and you’ll be fine.

Well, no. Every automatic migration ended up into a “Error: table ZRandomNumber_*WhateverRandomEntityFromYourModel* already exists”

After a lot of digging around, annoying any and every contact who remotely knew anything about CoreData, I managed to extract the actual SQL commands it was trying to execute on the SQLite database.

Guess what? it was trying to recreate some of the tables based on relationships (rightly assuming that some of them had changed or had been added, since I added an Entity). But one of them was getting mangled, because it incorrectly assumed none of the relationships preexisted.

Naive solution v2: Well duh, export the database to an agnostic format, then reimport it in the new model.

Yep. That actually works. But I have 140 entities, and close to 300000 rows. After 4h of crunching, I decided to stop the test.

Naive (and I mean REALLY naive) solution that actually works: Find a way to add your new entity at the end of the alphabetical list. That way it creates the missing relationships after having made everything was kosher. I’m not even kidding, I added ZZ in front, and everything just worked. Try it before you loose your own hair.


Leave a Reply