Sergeevme
Sergeevme

Reputation: 113

Do I need to keep old autoMigrations lines in Room Database?

Today I saw an error: A migration from [n] to [n+2] was required but not found

Question: should I keep the lines with automigrations when I have already switched to new versions. Are json files with database schemas packaged in apk and/or aab?

Is it enough to write like this?

@Database(
    entities = [Setting::class, ProfileModel::class, EventsClicks::class],
    version = 5,
    autoMigrations = [
        AutoMigration(from = 4, to = 5)
    ]
)

Or should I write like this all the time?

@Database(
    entities = [Setting::class, ProfileModel::class, EventsClicks::class],
    version = 5,
    autoMigrations = [
        AutoMigration(from = 1, to = 2),
        AutoMigration(from = 2, to = 3, spec = AppDatabase.MyAutoMigration::class),
        AutoMigration(from = 3, to = 4),
        AutoMigration(from = 4, to = 5)
    ]
)

There is no such information on https://developer.android.com/training/data-storage/room/migrating-db-versions and many other guides don't either. Could you help me understand, please?

Upvotes: 1

Views: 169

Answers (2)

Kiryl Tkach
Kiryl Tkach

Reputation: 3644

Generally you should keep all previous migrations. Consider the users who didn't update to the version of your app which has database version 4. After installing the update they will see empty database (if you have set fallbackToDestructiveMigration) or even crash. So if you have a lot of users on the database version < 4 you should keep those migrations, otherwise you can consider setting flag fallbackToDestructiveMigration and remove them.

Upvotes: 1

JustSightseeing
JustSightseeing

Reputation: 3025

That depends, if you will have an user that has the db with version 1 (didn't update the app for a long time) and no migration schema will be present from version 1 to 5, the app won't work, so keeping them might be a good idea

also, room is capable of skiping versions during migrations, as mentioned in this article, so you may shorten up the automigrations

Upvotes: 1

Related Questions