Big_Chair
Big_Chair

Reputation: 3229

Room Migration with prepopulated DB - Is fallbackToDestructiveMigration() my only option?

I have several tables in my DB of which some contain prepopulated content that the user cannot change and others that are only filled by the user. Now I want to update the prepopulated, static content but keep the user generated content.

This Android developer guide says the following concerning my question:

Because there is an implemented migration path from version 2 to version 3, Room runs the defined migrate() method to update the database instance on the device to version 3, preserving the data that is already in the database. Room does not use the prepackaged database file, because Room uses prepackaged database files only in the case of a fallback migration.

So this means I have no possibility to, for example: from 3 columns X, Y & Z - drop columns X and Z and recreate them with new content from the updated DB file, while keeping column Y as it was?

Below is an illustration of the issue.

Visualization of the question for better understanding


Is it correct that I only have 2 options now:

  1. Drop tables completely and make user lose their generated content, so they can have the updated prepopulated content
  2. Write migrations for the new structure, but end up with empty columns X.2 and Z.2 because Room will ignore my prepopulated DB 2.0

Upvotes: 1

Views: 1002

Answers (1)

ueen
ueen

Reputation: 692

Take a look at this library, maybe it helps you solve this
https://github.com/ueen/RoomAssetHelper

You can name tables and columns that should be preserved and then rename the existing db, copy the new one and transfer the specified columns.

Example from the GitHub page:

val db = RoomAssetHelper.databaseBuilder(applicationContext,
                       AppDatabase::class.java, 
                       "chinook.db",
                       1,
                       preserve = arrayOf(TablePreserve(table = "yourTable",
                                        preserveColumns = arrayOf("yourColumn"),
                                        matchByColumns = arrayOf("id"))))
                .build()

Upvotes: 1

Related Questions