Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update rows on room migrations

Is it possible to write migrations to update all previous data of some table?
I'm developing enrypition for my room data and would be nice if I could enrypt all rows after migration

like image 313
Shermano Avatar asked Oct 20 '25 06:10

Shermano


1 Answers

Well, when defining a migration you have access to SupportSQLiteDatabase, through which you can execute an SQL query. You can use SQL queries to update previous data using the update statement.

You can get access to the old data with the query method which returns a Cursor. The Cursor can be used to get info like the id and password of the user. The final code could look something like this.

val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        val cursor = database.query("SELECT * FROM user")
        while(cursor.moveToNext()) {
            val id = cursor.getLong(cursor.getColumnIndex("_id"))
            val password = cursor.getString(cursor.getColumnIndex("password"))
            //-- Hash your password --//
            database.execSQL("UPDATE user
                              SET password = hashedPassword
                              WHERE _id = id;")
        }
    }
}

Don't forget to update the database version.

like image 165
Khaled Emara Avatar answered Oct 22 '25 19:10

Khaled Emara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!