Migrations Room doesn't handle

Android Sep 23, 2022

Room has AutoMigration Annotation to help with migrations for developers, But It doesn't handle some migrations that we need. Let's learn what these Unsupported migrations are and how to manage them.

List of changes that SQLite doesn't support:

  • Column Type(nullability, data type)
  • Add/Remove/Rename Column
  • Add/Remove Constraints

So what is the solution? Unfortunately, It's sucks, but fortunately, you can test It 😁. Let's Add, Remove and Rename a column from a table.

Solution

For any change in table columns, You need to make another table with those columns and the changes you need. Then copy the content of the old table into the new table, remove the old table and finally rename the new table. So let's see all of these in code.

Assume we have table Members with these columns:

  • id
  • fname
  • lname
  • age(nullable)
  • phoneNumber

we want to rename fname, lname to firstName, lastName, remove phoneNumber and make age nullable. So:

Let's test It with Room testing library. First, we need to add this library:

// Room test library
androidTestImplementation "androidx.room:room-testing:$room_version"

Second, Make a class in androidTest section in the project tree:

Migrations Room doesn't handle - Writing tests

After creating our Test class, we have to initialize Room MigrationTestHelper class to:

Now, we can write our test:

So what have we done here? First, we need to create a database for our test with the version that we want to start the migration. Then confirm that the table is created, and the size of the columns is equal to the size of our columns.

After that, we need to run our migration to check and write our tests if the changes Are applied or not. As we remove the phoneNumber there will be Four columns. Then we check if fname, lname is exists or not, and the expectation is not.

Then we check if firstName, lastName is exists, and our expectation is True. And the final test is the existence of phoneNumber as we removed it. Of course, We can do more tests but I believe you get the idea.

That's it. We made it.

Tags

Benyamin Eskandari

Curious, Experienced Android Developer Also in love with Rust, DevOps, and System Programming Trying to read a lot of books and learn a lot of things, I will write posts about my path on this journey.