Home > Software engineering >  Handling Room Database update by reacreating from asset except for few columns I need to persist - A
Handling Room Database update by reacreating from asset except for few columns I need to persist - A

Time:04-01

My database has game configuration data and dynamic user data. Every time I update the app, I change the configuration data a lot (records are updated and new records are added), and it easy to just delete the database and recreate from asset. All is updated except the user data which needs to persist and is not impacted by the game configuration update.

So what I would like to do to avoid lengthy migration code:

  1. Read User data from Db (2 columns) store them somewhere temporarily
  2. Delete Entire database and recreate from the asset I updated
  3. Write back the user data into those 2 columns.

From a technical point of view I'm always fidning it difficult to achieve this, and I'm wondering if someone knows if it's possible or has done it before?

CodePudding user response:

If there are just two columns I suggest you to remove it from db and store it somewhere else. For example in SharedPreferences. Or this is not what you can do?

I am missing details of your implementation.

If you are using Room, it would be a great opportunity to try out Destructive migrations. When building the db, just enable destructive migrations and the work is done automatically when db version is updated.

Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")
    .createFromAsset("database/myapp.db")
    .fallbackToDestructiveMigration()
    .build()

CodePudding user response:

and it easy to just delete the database and recreate from asset.

Instead of deleting the database rename it, thus it is then still available.

Use the prePackedDatabase callback to apply the data from the renamed version (when the callback is called the prepackaged database has been copied) and then delete the renamed database.

You may find this useful How do I use Room's prepackagedDatabaseCallback?

  • Related