Android Alter Room Database Table With AutoMigration

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 the Room AutoMigration feature. 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.

Steps

Change the schema to be exported in the DatabaseHelper object

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

abstract class UserRoomDatabase : RoomDatabase(){

....

}

Add the schema location in the module build.gradle file. Im using KSP as annotation processor.

android {
    ....

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

Then build app. It will then create the 1.json schema file it needs.

Now we can add the AutoMigration implementation

@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

Thats it. It should work now after you update rest of your DB calls, ie INSERT, UPDATE.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *