Room Auto Migration showing compile time error

Viewed 3844

I am using Room 2.4.0-alpha01

but it show me this error

Schemas required for migration are not found at path: \app\schemascom.pigeon.mangaer.AppDB/2.json. Cannot generate auto migrations.

here is my code:

@Database(
    exportSchema = true,
    version = 3,
    entities = [Pigeon::class,PairEntity::class],
    autoMigrations = [
        AutoMigration(from = 2,to = 3)
                     ]
   )
abstract class AppDB:RoomDatabase() {
    abstract  fun  pigeonDao():PigeonDao
    abstract fun  pairDao():PairDao
}
4 Answers

Room Auto-migration requires you to export your database schema, so it can know how your database was in the previous version, in order to generate the auto-migration. This was stated at a post on Medium by Florina Muntenescu:

⚠️Note: Under the hood, Room auto-migrations rely on the generated database schema, so make sure that the exportSchema option in @Database is true while using autoMigrations. Otherwise it leads to an error: Cannot create auto-migrations when export schema is OFF.

This answer shows how to add the option exportSchema correctly to your project.

In my case I changed the database version after making the changes and compiling. This modified the generated schema for the old version (2.json), so the new version would still compare to the wrong old version.

Spent some time until I noticed this, so rolling back the changes on the old schema fixed it. This is assuming you use some sort of version control. Without it, you should first build the app without the changes made in the data model. Then bump up the database version and apply the changes (adding/removing columns, etc).

My mistake was I remembered to add the Auto migration, but forgot to change the version. I added the migration:

AutoMigration(from = 9, to = 10),

but forgot to change the version:

version = 9

So changing the version to 10:

version = 10

fixed the problem.

In case this helps anyone. The accepted answer is correct. However, you should add

exportSchema = true

then rebuild your app, and then add the migration block:

autoMigrations = [
    AutoMigration(from = 2,to = 3)
]

This way the compiler will generate the schema for the old version, which it needs for the migration. If you change exportSchema to true at the same time, the compiler will complain that the schema json file is missing. Took me a while to figure that one out.

Related