Recently I came across an interesting problem. Basically I have a database of schools which manages records of teachers, students, parents etc.
Theory:
Now, with every changing school session I want to be able to update the information of (say) student's class while maintaining the old information as well. One solution to this I thought would be to create a new instance of mongodb database thats would be the exact copy of the original one that runs on the same server, so I'll have 2 instances of the same database (one that has data of current school session and one that has the data of last year's session) running on same server.
Now I can query a specific instance based on my needs and get the appropriate data. Any changes would be done on the current school session while the old one would be treated as historical data.
Application:
Now I can't exactly figure out how to do it. I've looked into mongodb database versioning but even that doesn't seems to do it. One thing I know I don't want to do is to create an extra field on each of the collection's schema named version and manipulate it somehow which most of the solutions seems to suggest. I know mongodb has and __v field but I don't think that would be very useful (I could be wrong).
Any help is appreciated, Thanks
I have an scenario on which I am merging an object with a to-many relationship. My privacy policy is mergeByPropertyObjectTrumpMergePolicyType and I have also tried overwriteMergePolicyType. When the object gets merged, instead of taking the value of the relationships of the object in-memory and replacing the previous values, it just adds them to the set.
So far, I've managed to do some manual house-keeping to delete the old objects but this is far from ideal. Is there any way I can replace the set in disk exactly with the the set in memory and not have to clean it manually?
After adding a new Core Data model version to my app, I performed a lightweight migration, apparently successfully. The migrated file loaded fine, but upon the first attempt to access an attribute via a particular relationship, the app crashes with an NSRangeException: '*** -[__NSArrayM objectAtIndex:]: index 4294967295 beyond bounds [0 .. 35]'. This relationship worked fine prior to the migration. I know from other posts here that 4294967295 is really -1, but the only thing I can identify with 36 items in my app/data is that there are 36 total entities in the data model (for reference, the relationship that's being fetched has 58 items in its table).
The question:
My question is: based on the error I'm getting and the troubleshooting I've done below, is there a type of schema change that could pass the lightweight migration, but corrupt the data along the way, leading to the noted exception? I'm going to try breaking down the migration into smaller chunks over several versions to either isolate or avoid the issue, but it would be nice to be able to focus on specific schema changes that might be at fault.
The failure:
The failure occurs with the following code in "myobject":
[[self object2] text];
The object2 relationship is to-one, non-optional both ways and neither the forward nor inverse relationship was changed between data models. The text attribute is likely not relevant because when the error occurs, awakeFromFetch is not reached in object2. If I assign [self object2] to a variable prior to the above statement, the assignment is successful and reports data: <fault>.
The database:
Looking at the database in sqlite3, I notice the following:
The index values for the forward and inverse relationships appear to be correct in each table.
The object2 table has two columns for the inverse relationship instead of the one prior to migration (ZMYOBJECT as before and the additional Z2_MYOBJECT, which is empty for all rows). No other relationship were added to explain this column.
In the Z_PRIMARYKEY table, all entries post-migration show -1 for Z_MAX, whereas prior to migration they showed zero for empty tables and the maximum row number for populated tables. Manually updating Z_MAX to the proper values did not help with the exception. All Z_SUPER values were correct.
I set up a mapping model to see if anything looked awry with the automatic mappings, but everything looked fine.
Overall schema changes:
In the source version of the data model, there were fourteen entities, of which only four had been populated with data (the app is still in development). Seven were top-level entities and seven were sub-entities of three of the top-level entities.
In the target version of the data model, twenty-two entities were added, some top-level and some sub-entities, with dozens of relationships, including some added to existing entities.
Some attributes and relationships were removed from existing entities and others were added. No data types or relationship settings were changed, no attributes or relationships were renamed, and no special mappings were required.
Update (2/25/12): As I started working on a new intermediate model, I remembered that I had changed the class (representedClassName) for a number of entities from NSManagedObject to an NSManagedObject subclass, but hadn't generated the class files. I didn't suspect that would cause an issue and, indeed, creating all of the class files did not help with the exception. I just wanted to note that as another change between models.
Conclusions:
This is a wild guess, but if the 36 entity count is not a coincidence, it seems that when "myobject" attempts to fault in "object2" it does not have a valid reference for the table and is attempting to load table number -1, causing the exception. The fact that a simple assignment of [self object2] is successful, however, doesn't jibe with that conclusion.
Any ideas?
By working through several incremental migrations I was able to determine what is causing the issue, and a solution.
The problem:
One of the existing entities with data has no child entities in the current model. If I create a new model that simply adds a child entity, containing no attributes or relationships, and makes no other changes, the NSRangeException, Z_MAX observation, and doubling of the inverse relationship noted in my question all occur.
The solution:
After observing the failures following a "successful" lightweight migration for the case above, I created a mapping model. Since the only change was one additional entity, all but one of the entity mappings were straightforward. The question was what to do with the single added entity.
By default, the added entity with no attributes or relationships of its own was showing attribute and relationship mappings for all of the parent's properties. All of the mappings had empty value expressions by default, which I assumed meant that it would just skip them during the migration. Not true, apparently. By deleting all of the attribute and relationship mappings within the entity mapping and then turning off inferred mapping, the migration proceeded successfully.
I still have to tackle all of the remaining entities and will be trying this approach to do the rest in bulk, with all planned attributes and relationships intact.
Your posts were helpful when I encountered this problem. Thank you. [Have you reported the bug yet?]
Here are some more experimental results but, alas, not a great solution.
My schema change similarly added an entity subtype that has no additional attributes or relationships. The error message is the same as yours except the bounds are [0 .. 19]. That does correspond to 20 entity types, validating your hypothesis. Like your situation, the error happened when attempting to access an entity property after migration completed.
Adding a dummy attribute and a dummy self-relationship to the new entity type didn't avoid the post-migration crash. (However, I didn't test with that new entity type as the only schema change since I previously pushed that schema change to alpha testers.)
I observe the Z2_MYOBJECT column and Z_PRIMARYKEY.Z_MAX = -1 symptoms after successful migrations for other schema changes, so those may not be problematic at all. The -1 values get replaced lazily by the proper max values. The extra column might be used during migration.
In my case, the new entity's supertype has an ordered to-many relationship. In the very simple case where the entire data store contains just one object instance (an instance of that entity type with no outgoing relationship links), the schema migration succeeds. It does have the extra Z2_MYOBJECT column and Z_PRIMARYKEY.Z_MAX = -1 values and yet the resulting data store works fine when adding objects from there.
I tried creating a mapping model but was unsuccessful in getting Core Data to apply it. Turning off inferred mapping just made Core Data unable to migrate at all. Is there a trick to it? Do I have to write custom migration code to invoke a mapping model? This is Xcode 4.6.2 so the older bug is long gone.
When using git to roll the code & data model backwards or forwards to conduct an experiment, it seems to be necessary to (1) close & reopen the Xcode project and (2) do a clean build. Otherwise Xcode may crash and/or leave confounding state around.
To experimentally roll backwards, you must delete the .momd/ directory or the entire app from the target iOS simulator/device (or deploy the app via iTunes or TestFlight) since redeploying via Xcode won't remove obsolete files (like .mom and .omo data model definitions) which in turn lets the app do lightweight migrations that the actual deployed app can't do.
About the entity mapping to use for the added entity type, note that when Core Data applies a mapping model, it's copying entities from the old data store to a new one. It's not modifying the tables in place. You don't want it to "skip" properties (including inherited properties) unless you want to drop them.
However, since the schema change added an entity type, that entity has no instances to migrate so its custom mapping model rules do not matter.
Thus I wonder if something else caused your crashes to stop, like leftover experimental .mom files or custom migration code. Did your workaround hold up?
After 2 days of experimenting I decided my alpha testers would have to live without data migration this time. Fortunately this happened without production customers. But it doesn't give me confidence in Core Data.
I had the same sort of NSRangeException after adding a core data model version when accessing any instance of a particular entity after automatic lightweight migration. In my case also the range corresponded to the number of entities in my model.
I generated a mapping model with Xcode 4.6 (4H127) using File > New > File... and then selecting Core Data > Mapping Model. This caused the crash to (d)evolve into -[NSSymbolicExpression length]: unrecognized selector sent to instance...
Solution
The issue in my case was that my entity causing the original crash had a relationship named size, which is a reserved word listed in apple's Predicate Programming Guide. An examination of the mapping model revealed that the reserved word had been capitalized in the Value Expression for the relationship:
FUNCTION($manager, "destinationInstancesForEntityMappingNamed:sourceInstances:" , "PNSizeOptionToPNSizeOption", $source.SIZE)
I found the solution in Core Data Model Versioning and Data Migration Programming Guide:
Reserved words in custom value expressions: If you use a custom value
expression, you must escape reserved words such as SIZE, FIRST, and
LAST using a # (for example, $source.#size).
Unfortunately, Xcode's algorithm for generating the mapping model did not recognize the reserved word and I had to change the expression's key path in the Relationship Mapping inspector to $source.#size. This solved the problem. I assume that core data's inferred mapping model ran into a similar problem during lightweight migration.
There may be other causes of this kind crash and so this solution may not apply, but it may be worth checking the property names in your model against the list of reserved words in the Predicate Programming Guide.
So I am following the instructions found here: http://msdn.microsoft.com/en-US/data/jj691402 concerning how to handle multiple result sets from in EF.
I am trying to avoid the second solution as this will involve changing the EDMX by hand, which concerns me as I do not want to have to worry about other members on my team overwriting them.
But the first example still seems to be lacking. It refers to the ObjectContext.Translate<TEntity> method, but no where does it say how the <TEntity> is being created. Any time I create an Entity by hand, I of course get Error 2062, "no mapping between entity set and association set". Is there a step that I am missing? Or does the first solution not work with a DB first approach?
If you have create entity by hand in EF designer without mapping it to existing table or database view you indeed receive an error. Try to create complex type instead.
I've been trying to build a simple load/save system for a game using Core Data.
Saving, loading and creating my UIManagedDocument works fine. Setting and loading values for attributes in my savegame entity works fine as well.
The problem is that these values are lost when my app quits, because I don't know how to access them.
I have about 200 attributes inside my savegame entity, such as (NSNumber *)currentIncome, NSNumber *currentMoney, NSNumber *currentMonth etc. Seems simple, right? If I were to group these into attributes with relationships, I'd probably end up with about 20 attributes. From what I gathered from the Core Data Programming Guide, in order to fill the entity with the values from my saved UIManagedDocument, I need to perform a fetchrequest with a predicate which fills an array of results.
This is where my first question arises: Would I need to perform a fetchrequest for every single attribute? This seems useful if you only have a few attributes or if you have 'to many' relationships. In my case, this would seem incredibly tedious though.
I might be missing something very essential here, but I would need something like load my UIManagedDocument and automatically fill my NSManagedModel with the one that was saved in the document's context and I cannot find it.
That is where my second question comes in: Is CoreData and UIManagedDocument even the right approach for this? 200 variables is too much for NSUserDefaults - I could imagine using NSCoding though. I definately want to incorporate iCloud savegame sharing at a later point, and UIManagedDocument and CoreData just seemed perfect for this.
Solved:
I just rewrote the entire Core Data fetching code (20 lines down to 10 or so).
Performing a fetchrequest for an entity without a predicate apparently returns the entire entity.
If my (NSArray *)fetchedResults turns up nil (database is empty), I insert a new instance of my savegame entity in my managedobjectcontext.
If it turns up non-nil, I just do a (NSManagedObject *)saveGame = [fetchedResults lastObject] and every value gets loaded fine.
From a database perspective it sounds like what you have here is a database with a single table saveGame with 200 columns currentMoney, currentMonth, etc. You then have a single row in your database representing the current game state.
The NSFetchRequest is the equivalent of the database SELECT statement, and as you only have one row you don't really need any predicates WHERE clauses etc, just get everything from this table, which is what your fetch request that only specifies the entity is doing SELECT * FROM saveGame.
So all in all it doesn't sound like you're getting much value out of the core-data framework here. Another alternative might be to look into the iCloud Key-Value storage API, which sounds closer to what you are currently getting from core-data.