javaandroidrealmrealm-migration

Realm migration with new schema


I have an app which already taken use of a realm database. I now want to add a new RealmObject to the schema (say I want to add Person as my new RealmObject class). From the documentation it looks like I need to do the following to make this work:

RealmConfiguration config = new RealmConfiguration.Builder()
.schemaVersion(1) // Must be bumped when the schema changes
.migration(new MyMigration()) // Migration to run instead of throwing an exception
.build()




// Example migration adding a new class
class MyMigration extends RealmMigration {

  @Override
  public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
       // DynamicRealm exposes an editable schema
       RealmSchema schema = realm.getSchema();

       // Migrate to version 1: Add a new class.
       // Example:
       // public Person extends RealmObject {
       //     private String name;
       //     private int age;
       //     // getters and setters left out for brevity
       // }
       if (oldVersion == 0) {
          schema.create("Person")
              .addField("name", String.class)
              .addField("age", int.class);
          oldVersion++;
       }
       etc.... 

My question here: do we really need to create the Person schema "by hand" (i.e. add the fields, with their type) here? Or is there a way to use the Person RealmObject since we have already defined what fields should belong to the new class there


Solution

  • My question here: do we really need to create the Person schema "by hand" (i.e. add the fields, with their type) here?

    Yes.

    Or is there a way to use the Person RealmObject since we have already defined what fields should belong to the new class there

    I actually talked about this with Christian Melchior here, but the problem with using the currently existing RealmModel classes for defining what fields you need to add and what you fields you need to remove is:

    If you had a complex migration (involving renameField() and transform() operations), then there is no guarantee that your operations you defined from V5 of the object to V6 of the object are still possible to do, if you base your migration on the realm models you have in schema version V8 later.

    This essentially means that considering RealmModels are subject to change, just "updating to the latest model" could even result in loss of data, you'd be referencing fields that won't exist, and so on.

    Basically, using the current version of your Realm models for defining your schema modifying operations is not future-proof.