Room Database Migration in Kotlin

How to Rename a Column

When you are deleting or renaming a table or column, you will have to implement an AutoMigrationSpec. There are 4 annotations, @DeleteTable, @RenameTable, @DeleteColumn, and @RenameColumn. Since we want to rename the column, we use the @RenameColumn annotation. This is what the database class should look like.

@Database(
version = 2,
entities = [user::class],
autoMigrations = [
AutoMigration (
from = 1,
to = 2,
spec = UserDatabase.MyAutoMigration::class
)
]
)
abstract class UserDatabase : RoomDatabase() {
@RenameColumn(fromTableName = "User", toTableName = "UserInfo")
class UserAutoMigration : AutoMigrationSpec { }

}

How to Migrate Manually

Here I will be showing you what your code should look like if you need to migrate manually. First, you would want to create a migration path. This is how your code should look.

val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
// this is where you would write your migration
}
}
Room.databaseBuilder(
applicationContext,
UserDatabase::class.java,
"User-Database"
)
.addMigrations(MIGRATION_1_2)
.build()
@Database(entities = [User::class], version = 2)
abstract class UserDatabase : RoomDatabase() {
...
}

What To Add Inside The Migrate Method

I will be showing you different changes to your database that would require a migration change.

database.execSQL("DROP TABLE <name of entity>")
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("DROP TABLE user")
}
}
database.execSQL("CREATE TABLE User(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, firstName TEXT NOT NULL)")
database.execSQL("CREATE TABLE temp_user(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, firstName TEXT NOT NULL, lastName TEXT NOT NULL)")
database.execSQL("INSERT INTO temp_user (id, firstName, lastName) SELECT id, firstName, lastName FROM Student")
database.execSQL("DROP TABLE User")
database.execSQL("ALTER TABLE temp_user RENAME TO user")

Wrap Up

I hope this article helped you understand a bit more about Room database migrations. Thanks for reading!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store