Thursday 26 November 2020

Migration to insert new rows of data into Room DB

I'm making a new release of my app with new functionality that requires more rows of data in a Settings table in the Room DB. Even though structurally my DB has not changed (no new tables, no column changes etc) I was thinking of running a new migration (DB v2 -> v3) on the Room DB just to add these new rows of data to an existing table. Is that overkill?

DB_INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            MyDatabase.class, Constants.DB_NAME)
                            .addMigrations(new Migration_1_2(context, 1, 2), new Migration_2_3(2, 3))
                            .build();

I know I can add data in an onCreate() / onOpen() callback in my RoomDatabase. E.g.

private static RoomDatabase.Callback rdc = new RoomDatabase.Callback() {
            public void onCreate (SupportSQLiteDatabase db) {
                // do something after database has been created
            }
            public void onOpen (SupportSQLiteDatabase db) {
                // do something every time database is open
            }
        };

But I'm not sure either of these are appropriate?

onCreate() - for existing app users this won't be called as they'll already have the DB from the previous app release.

onOpen() - would run every single time they start the app - which seems a lot of overhead.

At least with a new migration this would only run once for users. Is this the right method?



from Migration to insert new rows of data into Room DB

No comments:

Post a Comment