在 Room 迁移中管理大型数据库操作是否可以接受?

Is it acceptable to manage large DB manipulations inside Room migration?

更新数据库时,是否接受 table 到 运行 大代码以使数据库符合我的要求。 例如,我需要更改 table 并更改列名。然后我需要在数据库中获取我的所有数据并检查是否找到文件而不是相应地更新数据库。当用户将应用程序更新到此 Room 版本时,我只需要它发生一次。

        val MIGRATION_8_9 = object : Migration(8, 9) {
        override fun migrate(database: SupportSQLiteDatabase) {
            database.execSQL("ALTER TABLE RideEntity RENAME videoPresent TO videoState")

            GlobalScope.launch(Dispatchers.IO) {
                val rides = DataBaseHelper.getAllPartsFromDB() //get all data
                rides.forEach {
                    val path = MyApp.appContext.getExternalFilesDir(null)!!.path + "/" + it.name + "/"

                    val file = File(path + VIDEO_FILE).exists()

                    if (file) {
                        it.videoState = 1
                        DataBaseHelper.updateData(it) //set the data
                    }
                }
            }

        }
    }

其中:

suspend fun getAllPartsFromDB() = withContext(Dispatchers.IO) {
    val parts = db.rideDao().getAllParts()
    parts
}

函数:

@Query("SELECT * FROM rideentity ORDER BY time DESC")
fun getAllParts(): List<Parts>

所以我的问题是,尽管这可行,但这种方式是否可以接受table?并且如果当应用程序数据库从版本 X 更新到 Y

时仅调用一次迁移函数

Is it acceptable to manage large DB manipulations inside Room migration?

是的。但是,您可能希望将更新循环放在事务中。

And if the migrate function called only once when the app DB updated from version X to Y

是的,它只被调用过一次。 Migration(8,9) 确定只有当存储在数据库 header 中的版本为 8 并且版本号设置为 9 时才会调用 Migration。