Interested in speaking at MongoDB World 2022? Click here to become a speaker.
HomeLearnHow-toHow to Update Realm SDK Database Schema for Android

How to Update Realm SDK Database Schema for Android

Updated: Nov 01, 2021 |

Published: Oct 21, 2021

  • Realm
  • Mobile
  • Kotlin
  • ...

By Mohit Sharma

Rate this article

This is a follow-up article in the Getting Started Series. In this article, we learn how to modify/migrate Realm local database schema.

#Introduction

As you add and change application features, you need to modify database schema, and the need for migrations arises, which is very important for a seamless user experience.

By the end of this article, you will learn:

  1. How to update database schema post-production release on play store.
  2. How to migrate user data from one schema to another.

Before we get down to business, let's quickly recap how we set Realm in our application.

1const val REALM_SCHEMA_VERSION: Long = 1
2const val REALM_DB_NAME = "rMigrationSample.db"
3
4fun setupRealm(context: Context) {
5 Realm.init(context)
6
7 val config = RealmConfiguration.Builder()
8 .name(REALM_DB_NAME)
9 .schemaVersion(REALM_SCHEMA_VERSION)
10 .build()
11
12 Realm.setDefaultConfiguration(config)
13}

Doing migration in Realm is very straightforward and simple. The high-level steps for the successful migration of any database are:

  1. Update the database version.
  2. Make changes to the database schema.
  3. Migrate user data from old schema to new.

#Update the Database Version

This is the simplest step, which can be done by incrementing the version of REALM_SCHEMA_VERSION, which notifies Relam about database changes. This, in turn, runs triggers migration, if provided.

To add migration, we use the migration function available in RealmConfiguration.Builder, which takes an argument of RealmMigration, which we will review in the next step.

1val config = RealmConfiguration.Builder()
2 .name(REALM_DB_NAME)
3 .schemaVersion(REALM_SCHEMA_VERSION)
4 .migration(DBMigrationHelper())
5 .build()

#Make Changes to the Database Schema

In Realm, all the migration-related operation has to be performed within the scope of RealmMigration.

1class DBMigrationHelper : RealmMigration {
2
3 override fun migrate(realm: DynamicRealm, oldVersion: Long, newVersion: Long) {
4 migration1to2(realm.schema)
5 migration2to3(realm.schema)
6 migration3to4(realm.schema)
7 }
8
9 private fun migration3to4(schema: RealmSchema?) {
10 TODO("Not yet implemented")
11 }
12
13 private fun migration2to3(schema: RealmSchema?) {
14 TODO("Not yet implemented")
15 }
16
17 private fun migration1to2(schema: RealmSchema) {
18 TODO("Not yet implemented")
19 }
20}

To add/update/rename any field:

1private fun migration1to2(schema: RealmSchema) {
2 val userSchema = schema.get(UserInfo::class.java.simpleName)
3 userSchema?.run {
4 addField("phoneNumber", String::class.java, FieldAttribute.REQUIRED)
5 renameField("phoneNumber", "phoneNo")
6 removeField("phoneNo")
7 }
8}

#Migrate User Data from Old Schema to New

All the data transformation during migration can be done with transform function with the help of set and get methods.

1private fun migration2to3(schema: RealmSchema) {
2 val userSchema = schema.get(UserInfo::class.java.simpleName)
3 userSchema?.run {
4 addField("fullName", String::class.java, FieldAttribute.REQUIRED)
5 transform {
6 it.set("fullName", it.get<String>("firstName") + it.get<String>("lastName"))
7 }
8 }
9}

In the above snippet, we are setting the default value of fullName by extracting the value from old data, like firstName and lastName.

We can also use transform to update the data type.

1val personSchema = schema!!["Person"]
2
3// Change type from String to int
4schema["Pet"]?.run {
5 addField("type_tmp", Int::class.java)
6 transform { obj ->
7 val oldType = obj.getString("type")
8 if (oldType == "dog") {
9 obj.setLong("type_tmp", 1)
10 } else if (oldType == "cat") {
11 obj.setInt("type_tmp", 2)
12 } else if (oldType == "hamster") {
13 obj.setInt("type_tmp", 3)
14 }
15 }
16 removeField("type")
17 renameField("type_tmp", "type")
18}

In case you want to delete the complete Realm, you can use deleteRealmIfMigrationNeeded with RealmConfiguration.Builder, but that should be considered as the last resort.

Thank you for reading! If you have any queries or comments, you can share them on the MongoDB Realm forum or tweet me @codeWithMohit.

In the next article, we will discuss how to migrate the Realm database with sync.

If you have an iOS app, do check out the iOS tutorial on Realm iOS Migration.

Rate this article
MongoDB logo
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.