Home > Mobile >  Optimize Room database migrations
Optimize Room database migrations

Time:09-04

In migration (3,4), I delete table TableA and create two new tables TableB and `TableC.

static final Migration MIGRATION_3_4 = new Migration(3, 4) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("DROP TABLE IF EXISTS `TableA`");

        database.execSQL("CREATE TABLE IF NOT EXISTS "  
                "`TableB` (`id` INTEGER NOT NULL, "  
                "PRIMARY KEY(`id`))");

        database.execSQL("CREATE TABLE IF NOT EXISTS "  
                "`TableB` (`id` INTEGER NOT NULL, "  
                "PRIMARY KEY(`id`))");

        // bulky method
        databaseWriteExecutor.execute(AppDatabase::populateProblem);
    }
};

In migration (4, 5), I want to remove TableB and TableC:

static final Migration MIGRATION_4_5 = new Migration(4, 5) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("DROP TABLE IF EXISTS `TableB`");
        database.execSQL("DROP TABLE IF EXISTS `TableC`");
    }
};

As you can see, migration (4, 5) is the opposite of migration (3, 4). Now suppose a user wants to migrate from 3 to 5, as far as I know Room will run two successive migrations in this case 3 to 4 then 4 to 5, creating two tables and then dropping them is a waste of time, so to optimize this I add a new migration (3, 5):

static final Migration MIGRATION_3_5 = new Migration(3, 5) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        database.execSQL("DROP TABLE IF EXISTS `TableA`");
    }
};

Question: Can I safely remove migration(3, 4) from the source code? because I think it is no longer used. In this migration I am calling the populateProblem() method which is a very big method, removing the migration will reduce the size of the apk.

CodePudding user response:

Yes, you can drop the intermediate migrations. You only need to keep migrations from every previous version to the latest version. So, if you latest DB version is 5, and assuming that you had versions 1 - 4 in production, you only need the following migrations:

Migration(1, 5)
Migration(2, 5)
Migration(3, 5)
Migration(4, 5)
  • Related