Schema changes are scary. If you add a column to a Room database without a proper migration strategy, your app will crash for every existing user the moment they update. Here is how I handle it professionally.
The AutoMigration (API 2.1+)
For simple changes like adding a new column, Room can now handle migrations automatically. Just increment your version and add the migration to your database declaration.
@Database(
entities = [User::class],
version = 2,
autoMigrations = [
AutoMigration(from = 1, to = 2)
]
)
Manual Migrations
When you're doing something complex—like renaming a column or splitting a table—you need a manual migration. This requires writing SQL, but it gives you total control.
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE User ADD COLUMN age INTEGER NOT NULL DEFAULT 0")
}
}
The Golden Rule
Always test your migrations using a physical device with the old version installed. Never assume the SQL is perfect. A broken migration is the fastest way to lose users.
Summary
Level up your Room game with AutoMigrations for the simple stuff and manual SQL for the complex shifts. Keep your user data safe!