Dim
Dim

Reputation: 4807

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

When updading DB is it acceptable to run large code to align the DB to my requirements. For example, I need to alter the table and change column names. Then I need to get all my data in the DB and check if file is located than update the DB accordingly. I need it happen only once when user updates the app to this Room version.

        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
                    }
                }
            }

        }
    }

Where:

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

Function:

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

So my question, despite this works, is this way acceptable? And if the migrate function called only once when the app DB updated from version X to Y

Upvotes: 0

Views: 108

Answers (1)

MikeT
MikeT

Reputation: 56943

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

Yes. However you may wish to put the update loop inside a transaction.

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

Yes it is only called the one time. The Migration(8,9) determines this that is the Migration will only be invoked when the version, as stored in the database header, is 8 and then the version number is set to 9.

Upvotes: 2

Related Questions