In Room, how do you write and register a Migration, and which migrations run for a user still on schema version 4?
answer
- start and end version
- builder registration
- stored version vs declared version
- furthest step that does not overshoot
basics
~20 sSubclass Migration(startVersion, endVersion), run the schema SQL in migrate() and register it with addMigrations(). On open, Room reads the stored version and chains migrations up to the @Database version, taking the furthest step that does not overshoot.
solid answer
~40 sA `Migration(6, 7)` overrides `migrate()` and runs raw SQL: in Room 2.x on a `SupportSQLiteDatabase` with `db.execSQL(...)`, in Room 3.0 as a suspend function on a `SQLiteConnection`. You raise `version` in `@Database` and register every step with `addMigrations(MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7)` on the builder. When the database is first opened, Room compares SQLite's `user_version` with the declared version. For a user on 4 it walks 4 to 5 to 6 to 7, but if a `Migration(4, 7)` is also registered it takes that single step, because at each version it picks the migration that reaches furthest without passing the target. The chain runs inside a transaction, and Room then validates the tables against the entities. `migrate()` must not use DAOs: they describe the latest schema, not the one being migrated.
code
kotlin · 24 linesval MIGRATION_4_5 = object : Migration(4, 5) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE workouts ADD COLUMN calories INTEGER")
}
}
val MIGRATION_5_6 = object : Migration(5, 6) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"CREATE TABLE IF NOT EXISTS heart_rate_samples (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"workout_id INTEGER NOT NULL, bpm INTEGER NOT NULL)"
)
}
}
// No schema change in 7, but the version moved, so a step is still required.
val MIGRATION_6_7 = object : Migration(6, 7) {
override fun migrate(db: SupportSQLiteDatabase) = Unit
}
val db = Room.databaseBuilder(context, FitnessDatabase::class.java, "fitness.db")
.addMigrations(MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7)
.build()go deeper
Recall the shape: a Migration with a start and end version, SQL in migrate(), registration through addMigrations(), and a raised @Database version.
Explain how Room reads user_version, picks the furthest step that does not overshoot at each version, runs the chain in a transaction and then validates the tables.
Show you know the edges: shortcuts win, the search never backtracks, empty steps are still required, and migrate() must use raw SQL rather than DAOs.
Talk about keeping every shipped migration, naming them per release, and when a shortcut migration is worth its extra test surface.
## What a Room migration is Room keeps two numbers apart. The **version your code expects** is the `version` in `@Database(version = 7, ...)`. The **version of the file on the device** is stored in SQLite's `PRAGMA user_version`, which Room writes after it creates or upgrades the database. When the two differ at open time, the file has the shape of an older release and must be transformed before any query runs. A **`Migration`** is one such transformation. Its constructor takes a **`startVersion`** and an **`endVersion`**, and its `migrate()` function runs the SQL that turns the first shape into the second: - In **Room 2.x** you override `migrate(db: SupportSQLiteDatabase)` and call `db.execSQL(...)`. - In **Room 3.0** you override the abstract `suspend fun migrate(connection: SQLiteConnection)` instead, because Room 3.0 removed the `SupportSQLite` types. - Both majors also offer a factory function, `Migration(6, 7) { ... }`, for short migrations written as a lambda. ## Registering migrations A migration object does nothing until the database builder knows about it. You pass every object to `addMigrations(...)` and raise the `@Database` version in the same change. Forgetting to register one is the same as never writing it: a user whose file needs that step has no path, and Room throws an `IllegalStateException` when it opens the database. The Migration KDoc adds a rule people miss: **even a release with no schema change between two versions still needs a Migration object** (an empty `migrate()` body is fine) once the version number moved. ## How Room chooses the path For the fitness app shipping version 7 to users on 4, 5 and 6, Room builds the path at open time: 1. Read the file's version (say 4) and the declared version (7). 2. Among the registered migrations that start at the current version, take the one with the **highest `endVersion` that does not pass 7**. 3. Move to that end version and repeat until the target is reached. 4. If at some version no migration fits, there is **no path**. Room throws `IllegalStateException` ("A migration from 4 to 7 was required but not found"), unless a destructive fallback was configured on the builder. Two consequences follow from that algorithm: - **A shortcut wins.** With `Migration(4, 5)`, `(5, 6)`, `(6, 7)` and `(4, 7)` all registered, a user on 4 runs only `Migration(4, 7)`; users on 5 and 6 still use the single steps. - **Room does not backtrack.** If you register `(4, 6)`, `(4, 5)` and `(5, 7)` but no `(6, 7)`, a user on 4 takes the longer jump to 6, finds nothing onward and gets "no path", even though 4 to 5 to 7 existed. The same search runs downward when a newer file meets an older build, so a downgrade needs an explicit `Migration(7, 6)` or one of the fallback options. ## What happens around migrate() | Stage | What Room does | |---|---| | Open | Reads `user_version`; a fresh install (version 0) creates the tables directly and runs no migrations | | Migrate | Runs the chosen chain inside a transaction, possibly one composite transaction for all steps | | Validate | Compares every table with what the entities expect: columns, affinity, `NOT NULL`, primary key, foreign keys, indices | | Commit | Writes the new `user_version` and the schema identity hash | If any step throws, or validation fails, nothing is committed and the file stays at the old version. Validation failure surfaces as `IllegalStateException` with "Migration didn't properly handle" followed by the expected and found table description. ## Writing migrate() safely - **Raw SQL only.** The KDoc states that `migrate()` cannot access any generated DAO; the DAOs' queries and mappings describe version 7, while the tables still have the older shape. - **Write the full SQL text in the migration.** The Room documentation warns against referencing constants for the queries: a constant shared with today's code can change later and silently rewrite an old step. - **Move data with SQL**, for example `INSERT INTO new_table SELECT ... FROM old_table`; what SQLite's `ALTER TABLE` can and cannot change is a SQLite question, not a Room one. - **Keep every shipped migration** for as long as users may still be on its start version; deleting `MIGRATION_4_5` strands everyone on 4. - Prefer one migration per release, named after its versions (`MIGRATION_6_7`), and add a shortcut only when it is clearly faster than the chain.
- You registered Migration(4, 6), Migration(4, 5) and Migration(5, 7), but no Migration(6, 7). What happens to a user on version 4?Room takes the step that reaches furthest without passing 7, so it runs 4 to 6, then finds no migration starting at 6. It does not go back to try 4 to 5 to 7, so it reports no path and throws `IllegalStateException`, unless a destructive fallback is set. Add `Migration(6, 7)` or remove the dead-end shortcut.
- Why can't migrate() call the app's WorkoutDao to copy rows into a new table?The generated DAO is compiled against the latest entities, so its SQL and row mapping assume version 7 while the tables still have the older shape, and the database is still in the middle of being opened. The KDoc states that a migration cannot access generated DAOs; copy rows with SQL on the object `migrate()` receives, such as `INSERT INTO ... SELECT`.
- Your release has no entity changes but you bumped the @Database version anyway. Is a migration still needed?Yes. Room compares the stored `user_version` with the declared version, not the schemas, so a gap with no registered step is a missing path. Register an empty `Migration(6, 7)` (or an `@AutoMigration(from = 6, to = 7)`), otherwise users on 6 crash on open.
Room's path search is like taking a lift in a building where some lifts skip floors: from your floor you always board the lift that goes highest without passing your destination, and you never walk back down to try another route.
- Room always runs migrations one version at a time, ignoring shortcuts
- A release with no schema change needs no Migration after a version bump
- Calling DAOs inside migrate() is fine for copying data
- Room reads the current schema version from the exported JSON files
- If one step of the chain fails, the earlier steps stay committed
Code assumes Room 2.8.5, where migrate() takes a SupportSQLiteDatabase; in Room 3.0 migrate() is a suspend function on a SQLiteConnection and path selection is unchanged.