Search code examples
realmrealm-migration

Realm migrated schema even though the schema version was never changed


When updating my realm schema, i reconfigured the RealmMigration to add the new class/fields , however I forgot to update the schema version. When I updated the app, I experienced no issues, but then realized I forgot to update the schema version, which was confusing because I now realized that realm updated my schema without me specifying that the version changed.

So when I updated it, I got the class already exists exception which was even more confusing because now I didn't know what to set my schema version too -- i changed the schema, but the changes were already made by the RealmMigration object, so I didn't know if I should have left it at the old version number, causing no class already exists exception, or change it to the correct version number, causing the exception.

Is it possible that realm can execute a migration with the given RealmMigration object if it experiences a realm migration exception; even if the schema version was never updated?


Solution

  • Let me assume your migration code is:

    RealmMigration migration = new RealmMigration() {
        @Override
        public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
            RealmSchema schema = realm.getSchema();
            if (oldVersion == 0) {
                schema.create("Person")
                   .addField("name", String.class)
                   .addField("age", int.class);
                // forgot: oldVersion++;
            }
        }
    }
    

    You cannot use the version to determine if you should add the Person class or bump the version. But you can use that you know if Person exists, you will need to bump the version.

    RealmMigration migration = new RealmMigration() {
        @Override
        public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
            RealmSchema schema = realm.getSchema();
            if (oldVersion == 0) {
                if (schema.contains("Person)) {
                    oldVersion++;
                } else {
                    schema.create("Person")
                       .addField("name", String.class)
                       .addField("age", int.class);
                    oldVersion++;
                }
            }
        }
    }