4

I'm doing my first Realm migration and started thinking about the version number. On what is this version number based?

Because if it is based on what is on your phone, how do I handle it if a new person installs the app and gets a migration? Because it will also update the fields which where already set because of a fresh install.

Kevin van Mierlo
  • 9,554
  • 5
  • 44
  • 76

2 Answers2

7

Christian from Realm here. The migration API is still in a very experimental state and kinda ugly, so right now the version number always start with 0, and the only way for changing that is through a migration.

This means that if you want a fresh install with a different version other than 0, you will have to do something like:

   // Pseudo code
    public class RealmHelper() {

        private static SharedPreferences prefs;

        public static Realm getInstance() {
            if (!prefs.getBoolean("versionSet", false)) {
                String path = new File(context.getFilesDir(), Realm.DEFAULT_REALM_NAME).getAbsolutePath();
                Realm.migrateRealmAtPath(path, new RealmMigration() {
                            @Override
                            public long execute(Realm realm, long version) {
                                return 42; // Set version numbers
                            }
                        })
                prefs.edit().putBoolean("versionSet", true).apply();
            }

            return Realm.getInstance();
        }
    }

This is going to be a lot better soon though: https://github.com/realm/realm-java/pull/929

blizzard
  • 5,275
  • 2
  • 34
  • 48
Christian Melchior
  • 19,978
  • 5
  • 62
  • 53
  • 1
    I like how the new api is going to look! I didn't have much problem with the migration, except for the version ;). It's a great database btw! :) – Kevin van Mierlo Apr 30 '15 at 07:05
2

Realm migrations in 0.84.2 are changed quite a bit (see Christian's hint on the new API), the key points on making a realm (0.84.2) migration work for me were understanding that:

  • The schemaVersion is always 0 when your app has a realm db without specifying the schemaVersion. Which is true in most cases since you probably start using the schemaVersion in the configuration once you need migrations & are already running a live release of your app.

  • The schemaVersion is automatically stored and when a fresh install of your app occurs and you are already on schemaVersion 3, realm automatically checks if there are exceptions, if not it sets the schemaVersion to 3 so your migrations aren't run when not needed. This also meens you don't have to store anything anymore in SharedPreferences.

  • In the migration you have to set all values of new columns when the type is not nullable, current version of realm, ...

  • Empty Strings can be inserted but only when setting convertColumnToNullable on the column

Jordy
  • 1,764
  • 1
  • 22
  • 32