How to Update Realm SDK Database Schema for Android
Rate this tutorial
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:
- How to update database schema post-production release on play store.
- How to migrate user data from one schema to another.
Before we get down to business, let's quickly recap how we set
Realmin our application.
Doing migration in Realm is very straightforward and simple. The high-level steps for the successful migration of any database are:
- Update the database version.
- Make changes to the database schema.
- Migrate user data from old schema to new.
This is the simplest step, which can be done by incrementing the version of
REALM_SCHEMA_VERSION, which notifies
Relamabout database changes. This, in turn, runs triggers migration, if provided.
To add migration, we use the
migrationfunction available in
RealmConfiguration.Builder, which takes an argument of
RealmMigration, which we will review in the next step.
Realm, all the migration-related operation has to be performed within the scope of
To add/update/rename any field:
All the data transformation during migration can be done with
transformfunction with the help of
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
transformto update the data type.
In case you want to delete the complete
Realm, you can use
RealmConfiguration.Builder, but that should be considered as the last resort.
In the next article, we will discuss how to migrate the Realm database with sync.