Android Room Version Migration

passΒ·2023λ…„ 10μ›” 17일
0

Android

λͺ©λ‘ 보기
35/41

πŸ”₯ Android Room μ—μ„œ version Migration 이 ν•„μš”ν•  λ•Œμ™€ μ‚¬μš©λ²•μ„ μ•Œμ•„λ³΄μž.


μ΄λ²ˆμ— google play 에 μ—…λ‘œλ“œν•œ μ–΄ν”Œλ¦¬μΌ€μ΄μ…˜μ„ μ—…λ°μ΄νŠΈν•˜κ²Œ λ˜μ—ˆλŠ”λ°, μ½”λ“œ μˆ˜μ • 쀑, DataBase 의 ꡬ쑰가 λ³€κ²½λ˜λŠ” 일이 λ°œμƒν•˜μ˜€λ‹€.

개발 μ€‘μ΄μ—ˆλ‹€λ©΄, μ•„λž˜ κΈ€μ—μ„œ μž‘μ„±ν–ˆλ˜ κ²ƒμ²˜λŸΌ μΊμ‹œ νŒŒμΌμ„ μ‚­μ œν•˜λ˜κ°€ μ•± 자체λ₯Ό μ‚­μ œν•˜κ³ , google λ“œλΌμ΄λΈŒ μΊμ‹œμ— 값이 μ €μž₯λ˜μ§€ μ•Šλ„λ‘ μ„€μ •ν•˜μ˜€μ„ 것이닀.
https://velog.io/@pass/Android-Room-cannot-verify-the-data-integrity

ν•˜μ§€λ§Œ, Google Play μ—μ„œ 이미 λ‹€μš΄λ‘œλ“œ 받은 μ‚¬μš©μžκ°€ μ—…λ°μ΄νŠΈ 후에 λ°”λ‘œ μ‚¬μš©μ΄ κ°€λŠ₯ν•΄μ•Ό ν•˜λ―€λ‘œ Database 의 version 을 올리기둜 ν•˜μ˜€λ‹€.
μ•„λž˜λŠ” μ˜ˆμ‹œμ½”λ“œμ΄λ©°, version 을 2μ—μ„œ 3으둜 migration ν•œ μ˜ˆμ œμ΄λ‹€.
onOff 속성 νƒ€μž…λ§Œ λ³€κ²½λ˜μ—ˆμœΌλ©°, μƒˆλ‘œμš΄ ν…Œμ΄λΈ”μ„ μƒμ„±ν•˜μ—¬ λŒ€μ²΄ν•˜λŠ” λ°©λ²•μœΌλ‘œ μˆ˜ν–‰ν•˜μ˜€λ‹€.


@Database(entities = [Alarm::class], version = 3)
abstract class AlarmDataBase : RoomDatabase() {
    abstract fun alarmDao(): AlarmDao

    companion object {
        @Volatile
        private var INSTANCE: AlarmDataBase? = null

        fun getInstance(context: Context): AlarmDataBase =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
            }

        private fun buildDatabase(context: Context) =
            Room.databaseBuilder(
                context.applicationContext,
                AlarmDataBase::class.java, Constants.ALARM_DB
            )
            .addMigrations(MIGRATION_2_3)
            .build()

        private val MIGRATION_2_3: Migration = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                // Create the new table
                database.execSQL("""
            CREATE TABLE Alarm_new (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                alarmHour TEXT NOT NULL,
                alarmMinute TEXT NOT NULL,
                onOff INTEGER NOT NULL DEFAULT 0,
                playlistId INTEGER NOT NULL,
                playlistName TEXT NOT NULL
            )
        """)

                // Copy the data
                database.execSQL("""
            INSERT INTO Alarm_new (id, alarmHour, alarmMinute, onOff, playlistId, playlistName)
            SELECT id, alarmHour, alarmMinute,CASE WHEN onOff > 0 THEN 1 ELSE 0 END AS onOff ,playlistId ,playlistName FROM Alarm
        """)

                // Remove the old table
                database.execSQL("DROP TABLE Alarm")

                // Change the table name to the correct one
                database.execSQL("ALTER TABLE Alarm_new RENAME TO Alarm")
            }
        }
    }
}
profile
μ•ˆλ“œλ‘œμ΄λ“œ 개발자 지망생

0개의 λŒ“κΈ€