Migrating the Room database, with only a new table added

One line answer

  1. Write SQL that creates the new table in AppDatabase.java
  2. Call the add-migration in DB initialization

The code

// @Database...
public abstract class AppDatabase extends RoomDatabase {
public static final String DB_NAME = "Nhviewer";
// public abstract ComicBookmarkDao comicBookmarkDao();
// ...
public static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
// create comic bookmark table
database.execSQL("CREATE TABLE IF NOT EXISTS `ComicBookmark` (`page` INTEGER NOT NULL, `id` INTEGER NOT NULL, `dateOfCreate` TEXT, PRIMARY KEY(`id`, `page`))");
}
};
}
// ...
private static AppDatabase appDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
appDatabase = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, AppDatabase.DB_NAME)
.addMigrations(AppDatabase.MIGRATION_1_2).build();
}
// ...


The problem

In my comic app project (NHViewer), I wanted to add a "bookmark" function to show the last seen page for each comic. 

So I need to create a new table for the Room database while keeping the original tables and data in the device. 

After some searching, I wrote the above code according to the AppDatabase's schema


Coda

During my searching, the Room database migration seems improved in the version 2.2.0 (androidx.room:room-*:2.2.0)
This note did not cover that part though 🙁


References

留言