Room Database Migration in Kotlin

How to Rename a Column

@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

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

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

--

--

--

19 Years Old | Pursing Android Development

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Cheat Sheet for Ballerina Commands associated with Module Management

Installing Google Cloud SDK to Use Python from Anaconda

Quick Basic Deploy Flask App with Pipenv & Python Pt. 2 — Now with SQL server

Shortcuts and Working Copy

Working with MongoDB

Daily Native Dev: Windows and OpenSSL

Progressive Web Apps vs Native Apps

Observer Design Pattern

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
Alexander Portillo

Alexander Portillo

19 Years Old | Pursing Android Development

More from Medium

Null Safety in Kotlin

Coroutine Adventure Part.3

Extension Functions in Kotlin

Kotlin ⚡️: Null Safety | Erselan Khan