Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room Database migration

How many methods will I have to make for Room migration if I have db version 10?

I looked into the following example Google Persistence Migration Sample

and I found Migration varargs based on probable scenarios for database version 4.

public static UsersDatabase getInstance(Context context) {
    synchronized (sLock) {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                    UsersDatabase.class, "Sample.db") 
                    .addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_1_4)
                    .build(); 
        } 
        return INSTANCE;
    } 
} 

My question is, Suppose I am using Room from the db v1 and by time my app reaches to db v10, how many migration methods will I have to write?

In sqlite, we get current db version of installed app in onUpgrade and we just fall through switch case without break statements so that it satisfies all db upgrades.

However, I am not sure, but afaik, we cannot get current db version of installed app in room, we write all possible methods for migration.

But it feels so inconvenient, inappropriate to write total 45 methods if I have db v10!

Is there any better solution?

like image 576
Sagar Patel Avatar asked Sep 08 '18 13:09

Sagar Patel


1 Answers

Suppose I am using Room from the db v1 and by time my app reaches to db v10, how many migration methods will I have to write?

9.

One approach is: 1->2, 2->3, 3->4, 4->5, 5->6, 6->7, 7->8, 8->9, and 9->10.

Another approach is: 1->10, 2->10, 3->10, ..., 9->10.

My guess is that the first approach is more popular, as it is easier to develop. For each new database release, you just create one additional object.

In sqlite, we get current db version of installed app in onUpgrade and we just fall through switch case without break statements so that it satisfies all db upgrades.

That will be about the same number of lines of code, give or take, as what you would do in Room. Each one of your case statements gets turned into a Migration object, handling an incremental upgrade (e.g., 3->4).

But it feels so inconvenient, inappropriate to write total 45 methods if I have db v10!

Room knows how to "stitch together" individual migrations as needed to reach a target version. So, in the first approach that I outlined, if an app needs to be migrated from 3 to 10, Room can use 3->4, 4->5, 5->6, ..., 9->10 to get there.

like image 149
CommonsWare Avatar answered Oct 11 '22 01:10

CommonsWare