0

Imagine I deliver a prepopulated database with my application version 1. The prepopulated database includes a table "my_items" with the column item:

item
------
apple

For application version 2 I deliver an updated prepopulated database, so table "my_items" includes

item
------
apple
milk

How would one make sure that the new prepopulated data is transfered to the database of the app in a non-destructive way? (user is allowed to insert new items to "my_items" by himself and I need to keep his input). I read the Room migrations documentation, but it seems like the prepopulated data is only read on a destructive migration, which is not what I want, as the items entered by the user himself shall remain available.

stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270
  • Anyone looking for another solution, take a look at my answer here: https://stackoverflow.com/a/73887645/14609192 – AaronC Sep 28 '22 at 21:07

1 Answers1

0

Room's built in migration processing does not support the merging of existing data into a new prepopulated database.

An approach that should work is to give the prepackaged database file for each app version a unique name, e.g. my_items1.db, my_items2.db, etc. In app version 2, create the main database from prepackaged database file my_items2.db. Then open the database for the previous version as a separate Room database instance, query it to find the items added by the user, and insert those into the new main database with appropriate default values for new fields. This merge processing could be triggered by the onCreate() callback for the main database. The merge processing should be done in a transaction. If it completes successfully, you can close and delete the database for the previous version. In the event of failure, you'll need to notify the user and implement some sort of mitigation processing.

Bob Snyder
  • 37,759
  • 6
  • 111
  • 158