【问题标题】:How to merge multiple Room databases during migration如何在迁移过程中合并多个 Room 数据库
【发布时间】:2023-02-23 18:21:18
【问题描述】:
问题我有两个数据库,mainDb 和secondDb,我需要在数据库升级(迁移)期间将它们合并到一个数据库中。
尝试我已经查看了允许从数据库导入数据的createFromAsset(),但是这个启用了fallbackToDestructiveMigration()的only seems to work会在加载createFromAsset(secondDb)时清除我的mainDb。
【问题讨论】:
标签:
android-room
android-room-migration
【解决方案1】:
我将尝试以下操作(仍有待测试):
@Database(...) abstract class MainDatabase : RoomDatabase() {
// Default Singleton pattern code
companion object {
@Volatile private var INSTANCE: Database? = null
fun getDatabase(context: Context): Database {
return INSTANCE ?: synchronized(this) {
// Located here to have access to `Context`
val MIGRATION_17_18 = object : Migration(17, 18) {
override fun migrate(database: SupportSQLiteDatabase) {
// Check if `secondDb` exists
val file = context.getDatabasePath(SecondDatabase.DATABASE_NAME)
if (file.exists()) {
// Using a build method which includes all migation steps for `secondDb`
val secondDb = SecondDatabase.build(context)
// TODO: add handling for different `secondDb` versions
// Insert the data from the `secondDb`
secondDb.locationDao().all.forEach {
database.execSQL(
"INSERT INTO `Location` (`id`, ...)"
+ " VALUES ('" + it.uid + "', ...)"
)
}
// Drop `secondDb`
Validate.isTrue(file.delete())
}
}
}
// Default building code for Singleton Pattern
val instance = Room.databaseBuilder(
context.applicationContext,
Database::class.java,
"mainDb"
)
.enableMultiInstanceInvalidation()
.addMigrations(MIGRATION_17_18)
.build()
INSTANCE = instance
return instance
}
}
}
}
我正在按照here的建议使用单例模式