Room migrations
Why it matters
- Every schema change (new column, renamed column, new table, new index) needs a version bump and a migration path. Without one, every user upgrading from the old version crashes the first time the database opens.
- A destructive fallback drops the tables and recreates them empty. Nothing crashes, so your crash dashboard stays green while user data disappears.
- Interviewers at mid and senior level ask you to write a
Migration, explain what auto-migration can and cannot do, and describe how you test migrations before release. - Migration bugs only show up on upgrade, never on a fresh install, so they slip past manual QA unless you test them on purpose.
The simple explanation
- You are renovating a house while people live in it.
- A migration is the renovation plan for one step: version 4 to version 5.
- Auto-migration is a contractor who compares the old and new floor plans and does the work. For ambiguous changes (did you rename that room, or knock it down and build a new one?) the contractor refuses to start until you leave a note: an
AutoMigrationSpec. - A manual Migration is you writing the exact steps, for jobs the contractor cannot infer, such as moving furniture between rooms (copying and transforming data).
- Destructive fallback is demolishing the house and rebuilding it empty because no plan was found.
- MigrationTestHelper is a rehearsal on a copy of the old house before you touch the real one.
Room stores the schema version in the database file. When the database is first opened and the file's version is lower than @Database(version = N), Room looks for a path of migrations from the old version to N. It runs them in a transaction, then checks that the resulting schema matches what your entities expect. If no path exists, opening the database throws IllegalStateException ("A migration from 4 to 5 was required but not found"), unless a destructive fallback allows it. If a migration runs but leaves the wrong schema, Room throws IllegalStateException ("Migration didn't properly handle ...").
Schema files. exportSchema is true by default. With the Room Gradle plugin's schemaDirectory set, Room writes one JSON file per version (schemas/<db class>/<version>.json) describing every table, column, default, index and foreign key. Commit them. Auto-migrations are generated by comparing two of these files, and MigrationTestHelper creates old-version databases from them.
| Approach | When to use | Limitation |
|---|---|---|
AutoMigration(from, to) | Adding tables, columns (with a defaultValue for NOT NULL), indices; Room can also handle many type and nullability changes by recreating the table | Needs both schema files; ambiguous changes need a spec |
AutoMigration(from, to, spec = ...) | Renaming or deleting a table or column (@RenameColumn, @DeleteColumn, @RenameTable, @DeleteTable) | Data fixes only through onPostMigrate |
object : Migration(from, to) | Data transforms: backfilling, splitting or merging columns or tables | You write and test the SQL yourself |
fallbackToDestructiveMigration(dropAllTables = true) | Data that is purely a re-downloadable cache, or local development | Drops the data whenever no migration path exists |
Manual migrations are registered with .addMigrations(MIGRATION_1_2, MIGRATION_2_3) on the builder; auto-migrations are listed in @Database(autoMigrations = [...]). You can mix them. Room picks a path through all available steps and prefers a manual migration when both cover the same step.
Notes
- Bump
@Database(version)for every released schema change. Room compares a hash of the schema, so changing an entity without bumping the version fails when an existing install opens the database. - A missing path throws
IllegalStateExceptionthe first time the database is opened (the first query), not whenbuild()is called. - Room runs each migration in a transaction and then validates the schema. A migration that leaves a column type, nullability or default different from the entity fails validation.
- When you add a NOT NULL column, SQLite requires a non-null
DEFAULTinALTER TABLE ... ADD COLUMN. Put the same default on the entity with@ColumnInfo(defaultValue = "..."), or validation reports a mismatch. - Auto-migrations need the exported JSON for both versions. Renames and deletions are ambiguous, so without a spec the build fails and asks for one.
AutoMigrationSpec.onPostMigrateruns after the generated SQL, which is the place for a small data fix within an auto-migration.- In a manual
Migration,db.execSQL(...)runs DDL and updates, anddb.query(...)reads rows when you need to transform them in Kotlin. - If SQLite cannot alter a table the way you need, the manual pattern is: create
table_new,INSERT INTO table_new SELECT ... FROM table, drop the old table, rename the new one. Copy theCREATE TABLEstatement from the exported JSON so it matches exactly. - The no-argument
fallbackToDestructiveMigration()is deprecated; current builders takedropAllTables(truedrops every table in the file,falseonly the tables Room knows).fallbackToDestructiveMigrationOnDowngrade(...)andfallbackToDestructiveMigrationFrom(..., versions)limit it to downgrades or specific old versions. MigrationTestHelperlives inroom-testing. On Android it is usually run as an instrumented test, so the migration runs on a real device's SQLite.
Code example
This database is at version 3. Version 2 added a displayName column and backfilled it from name (a manual migration, because auto-migration cannot copy data). Version 3 renamed name to fullName (an auto-migration with a spec). The test creates a version 1 database from the exported schema and migrates it.
import android.content.Context
import androidx.room.AutoMigration
import androidx.room.ColumnInfo
import androidx.room.Database
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.RenameColumn
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.AutoMigrationSpec
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
@Entity(tableName = "users")
data class User(
@PrimaryKey val id: Long,
val fullName: String, // was "name" before version 3
@ColumnInfo(defaultValue = "") val displayName: String, // added in version 2
)
@Database(
entities = [User::class],
version = 3,
autoMigrations = [AutoMigration(from = 2, to = 3, spec = AppDatabase.RenameNameSpec::class)],
)
abstract class AppDatabase : RoomDatabase() {
@RenameColumn(tableName = "users", fromColumnName = "name", toColumnName = "fullName")
class RenameNameSpec : AutoMigrationSpec
}
// Manual: auto-migration could add the column, but not fill it from another column
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(db: SupportSQLiteDatabase) {
// Same default as @ColumnInfo(defaultValue = ""), or schema validation fails
db.execSQL("ALTER TABLE users ADD COLUMN displayName TEXT NOT NULL DEFAULT ''")
db.execSQL("UPDATE users SET displayName = name")
}
}
fun buildDatabase(context: Context): AppDatabase =
Room.databaseBuilder(context, AppDatabase::class.java, "app.db")
.addMigrations(MIGRATION_1_2) // the 2 -> 3 auto-migration is picked up from @Database
.build()import androidx.room.testing.MigrationTestHelper
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MigrationTest {
@get:Rule
val helper = MigrationTestHelper(
InstrumentationRegistry.getInstrumentation(),
AppDatabase::class.java,
)
@Test
fun migrate1To3_keepsAndBackfillsData() {
// Build a version 1 database from schemas/.../1.json
helper.createDatabase(TEST_DB, 1).apply {
execSQL("INSERT INTO users (id, name) VALUES (1, 'Alice')")
close()
}
// Runs MIGRATION_1_2, then the 2 -> 3 auto-migration, then validates against 3.json
val db = helper.runMigrationsAndValidate(TEST_DB, 3, true, MIGRATION_1_2)
db.query("SELECT fullName, displayName FROM users WHERE id = 1").use { cursor ->
assertTrue(cursor.moveToFirst())
assertEquals("Alice", cursor.getString(0))
assertEquals("Alice", cursor.getString(1))
}
}
private companion object {
const val TEST_DB = "migration-test"
}
}@ColumnInfo(defaultValue = "")andDEFAULT ''in the SQL describe the same default. If they differ,runMigrationsAndValidate(and Room at runtime) throws "Migration didn't properly handle".- The rename is a spec, not a manual migration: Room generates the SQL from
2.jsonand3.json, and the annotation tells it the column was renamed, not dropped and re-added. runMigrationsAndValidatepicks a path the way Room does, so auto-migrations in@Databaserun without being passed in.- With the Room Gradle plugin, the exported schemas are added to the instrumentation test assets, which is where the helper reads them.
Run the idea in plain Kotlin
A tiny model of what Room does on open: look for a complete path of migrations from the stored version to the target before running anything, then either run every step, throw, or fall back destructively.
class Migration(val from: Int, val to: Int, val run: (MutableMap<String, MutableList<String>>) -> Unit)
class FakeDatabase(var version: Int, val tables: MutableMap<String, MutableList<String>>)
fun open(db: FakeDatabase, target: Int, migrations: List<Migration>, destructiveFallback: Boolean) {
// Like Room, find the whole path first, preferring the step that jumps furthest
val path = mutableListOf<Migration>()
var v = db.version
while (v < target) {
val step = migrations.filter { it.from == v && it.to <= target }.maxByOrNull { it.to } ?: break
path.add(step)
v = step.to
}
if (v < target) {
if (!destructiveFallback) {
throw IllegalStateException("A migration from " + db.version + " to " + target + " was required but not found")
}
db.tables.clear() // tables recreated empty: the user's rows are gone
db.tables["users"] = mutableListOf()
db.version = target
println("destructive fallback: rows left = " + db.tables.getValue("users").size)
return
}
for (step in path) {
step.run(db.tables)
db.version = step.to
println("ran " + step.from + " -> " + step.to)
}
}
fun main() {
val m12 = Migration(1, 2) { t -> t.getValue("users").replaceAll { it + "|displayName=" + it.substringAfter("name=") } }
val m23 = Migration(2, 3) { t -> t.getValue("users").replaceAll { it.replaceFirst("name=", "fullName=") } }
val upgraded = FakeDatabase(1, mutableMapOf("users" to mutableListOf("name=Alice")))
open(upgraded, target = 3, migrations = listOf(m12, m23), destructiveFallback = false)
println("version " + upgraded.version + ": " + upgraded.tables.getValue("users"))
val missingStep = FakeDatabase(1, mutableMapOf("users" to mutableListOf("name=Bob")))
try {
open(missingStep, target = 3, migrations = listOf(m12), destructiveFallback = false)
} catch (e: IllegalStateException) {
println("crash: " + e.message)
}
val wiped = FakeDatabase(1, mutableMapOf("users" to mutableListOf("name=Carol")))
open(wiped, target = 3, migrations = listOf(m12), destructiveFallback = true)
}Expected output:
ran 1 -> 2
ran 2 -> 3
version 3: [fullName=Alice|displayName=Alice]
crash: A migration from 1 to 3 was required but not found
destructive fallback: rows left = 0
In production
- The team added a column, bumped the version from 4 to 5 and forgot the migration.
- The production builder still had
fallbackToDestructiveMigration(), added "temporarily" during early development. - On upgrade Room found no path from 4 to 5, dropped the tables and recreated them empty: drafts and offline history vanished.
- The crash dashboard showed nothing, because the fallback does not throw; one-star reviews and support tickets did.
- Reproduced it by installing the previous release, adding data, then installing the new build over it.
- Removed the fallback from the production builder and added
AutoMigration(from = 4, to = 5)with@ColumnInfo(defaultValue = ...)on the new column, plus aMigrationTestHelpertest that seeds version 4 rows and asserts they survive. - Kept destructive fallback only on a separate cache database whose contents can be downloaded again, and added a
RoomDatabase.Callback.onDestructiveMigrationlog there so any wipe is visible in analytics.
- A developer added a new entity and bumped the version from 7 to 8 without adding a migration.
- Fresh installs worked, so QA passed. Every upgrading user crashed with "A migration from 7 to 8 was required but not found" the first time the app touched the database.
- The crash rate jumped within hours of the staged rollout reaching real users.
- Halted the rollout and shipped a build with
AutoMigration(from = 7, to = 8); adding a table needs no spec. - Added a CI test that creates the database at each shipped version with
MigrationTestHelper.createDatabaseand migrates it to the current version withrunMigrationsAndValidate. - Added a review rule: a change under
schemas/must come with a migration entry and a test for it.
Common mistakes
- Shipping a destructive fallback for user data. It drops the tables whenever a migration path is missing, with no exception. Keep it off databases that hold anything the user created.
- Not committing the schema JSON files. Without the old version's file, Room cannot generate an auto-migration and
MigrationTestHelpercannot create the old database. ConfigureschemaDirectoryfrom version 1 and commit every file. - Adding a NOT NULL column without matching defaults. SQLite rejects
ADD COLUMN ... NOT NULLwithout a non-null default, and aDEFAULTin SQL without the same@ColumnInfo(defaultValue)fails Room's schema validation. - Renaming a property and expecting auto-migration to guess. A rename looks like a drop plus an add. Without
@RenameColumnin a spec, the build fails, and if you "fix" it with@DeleteColumnthe data is gone. - Changing an entity without bumping the version. Existing installs then fail Room's schema hash check when they open the database.
- Testing only fresh installs. Migrations only run on upgrade. Test every shipped version to the current one with
MigrationTestHelper.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What happens when you bump the @Database version but do not provide a migration?”
“Explain the difference between auto-migration and a manual Migration.”
“Why is fallbackToDestructiveMigration dangerous, and when is it acceptable?”
“How do you test a Room migration?”
Quiz
What are the exported Room schema JSON files used for?
A builder has fallbackToDestructiveMigration(dropAllTables = true) and no migration from 4 to 5. A user upgrades. What happens?
You renamed the property name to fullName in an entity and want an auto-migration. What else do you need?
The database version goes from 3 to 5 and only Migration(3, 4) is registered. When do upgrading users notice?
0 of 4 answered
Mini task
Hands-on: Add a column and migrate
Goal: add a createdAt column to an existing Note entity, migrate it, and verify it with MigrationTestHelper.
- Make sure
room { schemaDirectory("$projectDir/schemas") }is set and the JSON for your current version N is committed. - Add
@ColumnInfo(name = "created_at", defaultValue = "0") val createdAt: LongtoNoteand bumpversionto N+1. - Add
AutoMigration(from = N, to = N + 1)to@Database(autoMigrations = [...])and build. Check thatN+1.jsonappears. - Write an instrumented test with a
@get:RuleMigrationTestHelper(InstrumentationRegistry.getInstrumentation(), YourDatabase::class.java):createDatabase(TEST_DB, N), insert one note with the old columns, thenclose().runMigrationsAndValidate(TEST_DB, N + 1, true).- Query
created_atfor that row and assert it is0.
- Search the code for
fallbackToDestructiveMigrationand remove it from any database that holds user data.
Done condition: the test passes, N+1.json is committed, and no database with user data uses a destructive fallback.