In Room, what does @AutoMigration need in order to generate a migration, and when must you supply an AutoMigrationSpec with @RenameColumn or @DeleteColumn?
answer
- two exported schemas
- schemaDirectory in the Gradle plugin
- rename looks like delete plus add
- spec annotations and onPostMigrate
basics
~20 s@AutoMigration(from, to) diffs the exported schema JSON of both versions, so exportSchema must stay on with a schema directory set. Additions usually migrate on their own; a renamed or deleted table or column needs an AutoMigrationSpec carrying @RenameColumn, @DeleteColumn, @RenameTable or @DeleteTable.
solid answer
~50 sAn `@AutoMigration(from = 6, to = 7)` listed in `@Database(autoMigrations = [...])` makes the Room compiler diff the exported schema JSON of version 6 against the schema it is compiling for 7 and generate the `Migration`. That only works when `exportSchema` is true (the default) and a schema location is set, usually with the Room Gradle plugin's `schemaDirectory`, and the older JSON files are committed. New tables, columns and indices usually need no help. A rename or a delete is ambiguous, since a renamed column looks like one dropped and one added, so the build fails until you point `spec` at a class implementing `AutoMigrationSpec` and annotated with `@RenameColumn`, `@DeleteColumn`, `@RenameTable` or `@DeleteTable`. Its `onPostMigrate` runs after the generated SQL. Splitting a table or transforming data still needs a hand-written `Migration`, which wins if both cover the same versions.
code
kotlin · 15 lines@Database(
entities = [Workout::class, HeartRateSample::class],
version = 7,
autoMigrations = [
AutoMigration(from = 5, to = 6),
AutoMigration(from = 6, to = 7, spec = FitnessDatabase.Spec6To7::class),
],
)
abstract class FitnessDatabase : RoomDatabase() {
@RenameColumn(tableName = "workouts", fromColumnName = "duration", toColumnName = "duration_seconds")
@DeleteColumn(tableName = "workouts", columnName = "legacy_notes")
class Spec6To7 : AutoMigrationSpec
abstract fun workoutDao(): WorkoutDao
}go deeper
Know that @AutoMigration lives in @Database's autoMigrations and relies on the exported schema JSON files.
Explain which changes Room infers on its own and which need a spec annotation, and where the schema directory is configured.
Handle the ambiguous cases with the right spec annotations, use onPostMigrate for small fix-ups, and know that a manual migration overrides an auto one.
Decide where the line sits between auto and hand-written migrations, and make the schema directory a reviewed, versioned artefact.
## What an auto-migration is Since Room 2.4.0, you can declare a migration instead of writing it. Listing `AutoMigration(from = 6, to = 7)` in the `autoMigrations` array of `@Database` tells the Room compiler to **generate** a `Migration(6, 7)` by comparing two schemas: the one exported when version 6 was built, and the one it is compiling now for version 7. The generated object is registered automatically; you do not pass it to `addMigrations()`. ## What it depends on: exported schemas Room writes the schema of every database version as JSON at compile time: one `<version>.json` per version, in a folder named after the database's fully qualified class name. Each file records the `version`, an `identityHash` and every entity's `tableName`, `createSql`, `fields`, `primaryKey`, `indices` and `foreignKeys`. Auto-migrations need these files, which brings three requirements: - **`exportSchema` stays `true`.** It is the default in `@Database`; the annotation's KDoc states it must be true when an auto-migration is defined. - **A schema location is configured.** With the **Room Gradle plugin** (2.6.0 and later) you apply `androidx.room` and set `schemaDirectory("$projectDir/schemas")` in the `room` extension; Room 3.0's plugin is `androidx.room3` with a `room3` extension. Without the plugin, the location is the `room.schemaLocation` compiler option. - **The old JSON is in version control.** The documentation says auto-migrations rely on the generated schema of both the lower and the higher version, and fail when `exportSchema` is false; the version-6 file must therefore still exist when version 7 compiles. ## Changes Room can and cannot infer | Change between versions | Auto-migration | What you add | |---|---|---| | New table, new column, new index | Generated for most such changes | Usually nothing | | Column or table renamed | Ambiguous | `@RenameColumn` or `@RenameTable` on a spec | | Column or table deleted | Ambiguous | `@DeleteColumn` or `@DeleteTable` on a spec | | Data transformed, table split, values computed | Not expressible | A hand-written `Migration` | A rename is ambiguous because, from two schemas alone, `duration` disappearing and `duration_seconds` appearing could be a rename (keep the data) or a delete plus an add (drop it). Room refuses to guess and **fails the build** with an error asking for an `AutoMigrationSpec`. ## Writing the spec 1. Declare a class that implements `AutoMigrationSpec`, often nested in the database class. 2. Annotate it with the changes: `@RenameColumn(tableName, fromColumnName, toColumnName)`, `@DeleteColumn(tableName, columnName)`, `@RenameTable(fromTableName, toTableName)`, `@DeleteTable(tableName)`. 3. Reference it: `AutoMigration(from = 6, to = 7, spec = FitnessDatabase.Spec6To7::class)`. 4. Optionally override `onPostMigrate` to run SQL after the generated statements, such as back-filling a new column; Room 2.x passes a `SupportSQLiteDatabase` (or, since 2.7.0, a `SQLiteConnection`), Room 3.0 a `SQLiteConnection` to a suspend function. The documentation notes that in Kotlin several annotations of the same type are written through their container, such as `@RenameColumn.Entries(...)`. A spec that needs dependencies can be annotated `@ProvidedAutoMigrationSpec` and passed at runtime with `addAutoMigrationSpec()`. ## Mixing auto and manual migrations - One database can use auto-migrations for some versions and hand-written ones for others; Room's path search treats them alike. - If both cover the same `from` and `to`, **the manual `Migration` wins**. - Auto-migrations are validated like any other: after the generated SQL runs, Room compares the tables with the entities. - `MigrationTestHelper` picks up the declared auto-migrations when it is built with the database class, so they are tested the same way. ## A worked example For the fitness app moving from 5 to 7: 1. Version 6 adds a `heart_rate_samples` table, so `AutoMigration(from = 5, to = 6)` needs no spec. 2. Version 7 renames `workouts.duration` to `duration_seconds` and drops `legacy_notes`, so `AutoMigration(from = 6, to = 7, spec = Spec6To7::class)` points at a spec carrying `@RenameColumn` and `@DeleteColumn`. 3. Building writes `7.json`, diffs it against `6.json`, and generates both migrations; a user on 5 runs them in one transaction, then Room validates the tables. 4. Commit `7.json` with the change and add migration tests from 5 and from 6. ## Common mistakes - Declaring `AutoMigration(from = 6, to = 7)` in a project that never exported version 6. - Treating a `.gitignore`d schema folder as build output; it is history, and history cannot be regenerated. - Renaming a field's column name while expecting Room to notice it is a rename. - Reaching for an auto-migration when the change moves data between tables.
- The 6-to-7 change renames a column and also needs every existing row's new column filled from another table. Auto or manual?The rename alone fits an `AutoMigrationSpec` with `@RenameColumn`, and a simple back-fill can go in the spec's `onPostMigrate`. If the data work is substantial, such as joining tables or splitting one into two, write a manual `Migration(6, 7)`: it is plain SQL you control, and if both exist the manual one wins.
- What happens if a developer deletes the schemas folder because it 'looks like build output'?The next build that declares an `@AutoMigration` from an old version cannot find that version's JSON and the auto-migration fails, and `MigrationTestHelper` can no longer create old-version databases for tests. Those files are the only record of shipped schemas; restore them from version control and keep them there.
- Room detects a column rename automatically from the two schemas
- Auto-migrations work with exportSchema set to false
- The schemas folder is build output and can be gitignored
- An auto-migration always takes precedence over a manual Migration
- Auto-migrations can split one table into two without extra code
Auto-migrations exist since Room 2.4.0 and work the same in Room 3.0; the Gradle plugin is androidx.room with a room extension from 2.6.0, and androidx.room3 with a room3 extension in 3.0.