AutoMigration With Room Database In Android To Alter Table
In this post I shared how to use AutoMigration with Room in Android to delete a column.

This post will focus on how to use AutoMigration with Room Database to alter table in Android. This will be a small snippet of code and a brief explanation.

The issue I had was that I needed to change the SQLite table I used in the current project. The action I needed to perform was to ALTER the table to drop a column, in my case it was the password field. There are two methods that this can be done.

  1. Create a backup table similar to existing, then transfer all current items over. Create new table with current needed structure. Then copy all items back over to new. Delete the backup table.
  2. Utilize the Room AutoMigration feature

I decided to implement AutoMigration With Room Database. I ran into a small issue at first which I will explain then it worked no problem.

The issue I had was I flagged the database as

exportSchema = false

The AutoMigration needs to have the schema exported in order to migrate from old to new.

Android Room AutoMigration

Steps

Ensure the schema is set to true in the DatabaseHelper object. Basically this means the database schema is written into a JSON file at runtime to check versions and structure history.

@Database(
    entities = [UserEntryTable::class],
    version = 1,
    exportSchema = true
)

abstract class UserRoomDatabase : RoomDatabase(){

....

}

Add the schema location in the module build.gradle file. I am using the project root as the location but you can choose your own location. I'm using KSP as annotation processor for this project.

android {
    ....

    defaultConfig {
    ....
    
        ksp {
            arg("room.schemaLocation", "$projectDir/schemas")
        }
    }

Finally build the app. It will then create the JSON schema file it needs. In this case it would create 1.json for version 1 of the database.

Now we can add the AutoMigration implementation. This will be added to the root database object.

@Database(
    entities = [UserEntryTable::class],
    version = 2,
    exportSchema = true,
    autoMigrations = [
        AutoMigration (
            from = 1,
            to = 2,
            spec = UserRoomDatabase.MyAutoMigration::class
        )
    ]
)

abstract class UserRoomDatabase : RoomDatabase(){
    @DeleteColumn(tableName = "user_table",  columnName = "password")
    class MyAutoMigration : AutoMigrationSpec

All done.

It should work now after you update the rest of your DB calls ( INSERT, UPDATE, etc ) to account for new table structure.