Sobes.tech
Junior — Middle

Does Room provide built-in support for automatic database updates when the schema changes?

sobes.tech AI

Answer from AI

Room does not provide automatic database migration when the schema changes. If you modify the database structure (for example, adding or removing columns), you need to explicitly define migrations using the Migration object. Without this, the application will encounter an error when starting with a new schema and an old database version.

Migration example:

val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("ALTER TABLE users ADD COLUMN age INTEGER DEFAULT 0 NOT NULL")
    }
}

val db = Room.databaseBuilder(context, AppDatabase::class.java, "db-name")
    .addMigrations(MIGRATION_1_2)
    .build()

Thus, the developer is responsible for creating and applying migrations when the schema changes.