Automatic migrations to Room

Until now, any changes to the database structure had to be written manually in the Migration class, telling Room what exactly has changed. In most cases, this entailed writing complex SQL queries.





Starting with version 2.4.0-alpha01 , the migration of the database structure to Room has been greatly simplified - there are automatic migrations (auto-migration).





In simple cases (for example, adding or removing a column, creating a new table), you just specify which version you want to migrate from, and Room will do all the dirty work for you and automatically generate migrations.





In more complex (and ambiguous) cases, Room will need help: you will need to indicate which column or table has been renamed or deleted. Based on this data, Room will automatically generate and run the migration.





Let's take a look at a few examples to get a better understanding of how this works.





Turn on automatic migrations

Suppose we add a new column to the table (moving from version 1 to version 2). As a result, we will have to update the annotation @Database



by increasing the version number and writing specific versions in AutoMigration



:





, , , AutoMigration



:





Room ? , . :





  • ,





  • , ,





  • ..





: . , , exportSchema



true



. : Cannot create auto-migrations when export schema is OFF.





?

, Room' . , .





: Room , ( ) . , Room AutoMigrationSpec, .





AutoMigrationSpec :





  • @DeleteTable(tableName)



    β€” , ,





  • @RenameTable(fromTableName, toTableName)



    β€” , ,





  • @DeleteColumn(tableName, columnName)



    β€” , ,





  • @RenameColumn(tableName, fromColumnName, toColumnName)



    β€” , , .





, Doggos



GoodDoggos



. Room :





  • GoodGoggos



    , , , (Doggos



    ) ,





  • Doggos



    , .





:





vs.

1.0, Room Migration . , .





, . Room , . , , .





Migration



, databaseBuilder()



addMigrations()



:





Room . , 1 2 Migration



, 2 3 β€” ..





, , .





?

: Migration



, .





, Room , , @Database



. , Room .





MigrationTestHelper



helper.runMigrationsAndValidate()



, Migration.





.





. β€” autoMigrations



@Database



( exportSchema = true



).





Room can handle simple cases automatically, but in more complex and ambiguous situations, we need to describe the essence of the changes made. In all other cases, use regular migrations.





The functionality of automatic migrations is in alpha status . Help us make it better by leaving feedback in the bug tracker .





useful links

  1. Documentation on @AutoMigration.





  2. List of commits that were included in version 2.4.0-alpha01.








All Articles