Android Room Database Migration (Upgrade Version) - Kotlin

October 9, 2018
Add New Column To Table

Add new field/column to Entity.

@Entity(tableName = "pin")
class Pin (
        // old fields
        @PrimaryKey
        @ColumnInfo(name = "id") var id: String = "",
        @ColumnInfo(name = "name") var name: String = "",
        @ColumnInfo(name = "lat") var lat: Double? = null,
        @ColumnInfo(name = "lng") var lat: Double? = null,
        
        // new field
        @ColumnInfo(name = "is_location_accurate") var isLocationAccurate: Boolean = false
        ) {

        }

Create file DatabaseMigration.kt to handle database migration from Version 1 -> 2.

val MIGRATION_1_2: Migration = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        // https://developer.android.com/reference/android/arch/persistence/room/ColumnInfo
        /*
        database.execSQL("ALTER TABLE pin "
                + " ADD COLUMN is_location_accurate INTEGER")
         */
        database.execSQL("ALTER TABLE pin "
                + " ADD COLUMN is_location_accurate INTEGER NOT NULL DEFAULT 0")
        database.execSQL("UPDATE pin "
                + " SET is_location_accurate = 0 WHERE lat IS NULL")
        database.execSQL("UPDATE pin "
                + " SET is_location_accurate = 1 WHERE lat IS NOT NULL")
    }
}

Add addMigrations to Room.databaseBuilder.

val database = Room.databaseBuilder(app, AppDatabase::class.java, "PixPin.db")
        // addMigrations(MIGRATION_1_2, MIGRATION_2_3)
        .addMigrations(MIGRATION_1_2)
        .build()

Change Database version.

@Database(entities = [(Pin::class), (PinGroup::class), (Image::class), Test::class], version = 2, exportSchema = false)
@TypeConverters(RoomConverters::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun pinDao(): PinDao
    abstract fun imageDao(): ImageDao
}

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.