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