Introduction
Once we define the databases and run our application, we cannot make any changes to the database without crashing the application. To make sure it runs on the devices the application is already installed on, we need to define a proper migration guide for the app database to be updated.
Thankfully, we have an auto-migration feature available in the Room Database to update the tables easily without having to write queries as part of the migrations. Let us go over the steps to do it quickly –
Implementation
First Step
We need to make sure that we are on 2.4.0-alpha01 or higher version of Room.
Second Step
Room auto-migration works on the exported database schema which is auto-generated when we specify – ‘exportSchema = true’ under the ‘@Database’ annotation. This step is quite important because if only when we export the initial version schema, Room will be able to make the differences between the different versions and run the migrations.
Once done, compile the code and you can see the database schema being exported to app/schemas/{package_name}/{version}.json file. We can also change the directory where the schemas are stored we can do it by adding this block of code in the defaultConfig section of build.gradle (module-level) –
Third Step
So now when we are done making the changes to the database models, we will define the auto-migration specs to run the migrations of the already installed applications on the devices. We will now increment the version number to 2 or the next higher number. We will also add a ‘autoMigrations’ key and specify the AutoMigration from version 1 to 2.
Most of the part is now done. But we may need to add AutoMigrationSpec if we have –
- Deleted / Renamed a Table.
- Deleted / Renamed a Column.
We will quickly go over it. Let’s say we have renamed a Column called ‘quizQues’ to ‘quizQuestion’. We will define a class, annotate it with ‘@RenameColumn’, specify the tableName, fromColumnName, toColumnName and extend it to AutoMigrationSpec. We will also add a property ‘spec’ in the ‘@AutoMigration’ we defined earlier.
Similarly, if we had done either of the other three operations, we can do it as –
And that’s it! Now when we run our application, we can see the migration has run and it is evident from the ‘Database Inspector’ tab which helps us look through the values of our app database.
Conclusion
Most of the cases would be satisfied with the new AutoMigrationSpec but if we have complex changes (splitting a table into two) etc, we will have to go with the Manual Migration way of writing queries and running the migration on it. More on it here.
With this simple 3 step guide, we can now upgrade our Room DB using Auto Migrations in a hassle-free way.