Junior — Middle
What steps should be taken to ensure the correct operation of an application when changing a field type from int to string in the Room database?
sobes.tech AI
Answer from AI
When changing a field type from int to string in a Room database, a migration must be performed to preserve data and avoid errors.
Main steps:
- Create a new version of the database with an updated schema where the field is changed to String.
- Implement a Migration object, describing the logic to convert data from int to string. For example, create a new temporary table with the required schema, copy and convert data, delete the old table, and rename the temporary one.
- Register the migration in RoomDatabase.Builder via the
.addMigrations()method.
Migration example:
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE new_table (id INTEGER PRIMARY KEY NOT NULL, field TEXT)")
database.execSQL("INSERT INTO new_table (id, field) SELECT id, CAST(field AS TEXT) FROM old_table")
database.execSQL("DROP TABLE old_table")
database.execSQL("ALTER TABLE new_table RENAME TO old_table")
}
}
- Update the database version in the @Database annotation.
Thus, the application will be able to work correctly with the changed field type without data loss.