How Room Applies Migrations
When you create your
RoomDatabase instance via the
Builder, Room will use
SQLiteOpenHelper semantics to see if the schema version in the existing database is older than the schema version that you declared in your
@Database annotation. If it is, Room will try to find a suitable
Migration to use, falling back to dropping all of your tables and rebuilding them from scratch, as happens during ordinary development.
Much of the time, the schema will jump from one version to the next. If you are using a simple numbering scheme starting at 1, the schema will then move to 2, then 3, then 4, and so on, for a given device. Hence, your primary
Migration objects will be ones that implement these incremental migrations.
However, some user might have skipped some app updates, so you need to skip a schema version as part of an upgrade (e.g., go from schema version 1 to schema version 3). Room is smart enough to find a chain of
Migration objects to use, and so if you have
Migration objects for each incremental schema change, Room can handle any combination of changes. For example, to go from 1 to 3, Room might first use your
(1,2) migration, then the
Sometimes, though, this can lead to unnecessary work. Suppose in schema version 2, you created a bunch of new tables and stuff… then reverted those changes in schema version 3. By using the incremental migrations, Room will create those tables and then turn around and drop them right away.
However, all else being equal, Room will try to use the shortest possible chain. Hence, you can create additional
Migration objects where appropriate to streamline particular upgrades. You could create a
(1,3) migration that bypasses the obsolete schema version 2, for example. This is optional but may prove useful from time to time.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.