Dev/Android

Room DB 마이그레이션

healthyryu 2022. 7. 14. 15:42

안드로이드 공식 페이지 - Room 데이터베이스 이전

 

기존 Room DB 구성

더보기
@Database(
    entities = [Alarm::class, MedicationHistory::class],
    version = 1
)
abstract class AppDatabase : RoomDatabase() {

    abstract fun alarmDao(): AlarmDao
    abstract fun medicationHistoryDoa(): MedicationHistoryDao

    companion object {
        @Volatile
        private var instance: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase =
            instance ?: synchronized(this) {
                instance ?: buildDatabase(context).also {
                    instance = it
                }
            }

        private fun buildDatabase(appContext: Context) =
            Room.databaseBuilder(appContext, AppDatabase::class.java, "app_db")
                .build()
    }

}

 

기존 Room 마이그레이션 방법

@Database(
    version = AppDatabase.LATEST_VERSION,
    entities = [Alarm::class]
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun alarmDao(): AlarmDao

    companion object {
        @Volatile
        private var instance: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase =
            instance ?: synchronized(this) {
                instance ?: buildDatabase(context).also {
                    instance = it
                }
            }

        private fun buildDatabase(appContext: Context) =
			Room.databaseBuilder(appContext, AppDatabase::class.java, "app_db")
                .addMigrations(MIGRATION_1_2)
                .build()

        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("DROP TABLE 테이블이름")
            }
        }

        const val LATEST_VERSION = 2
    }
}

 

AutoMigration 사용하는 마이그레이션 방법

@Database(
    version = AppDatabase.LATEST_VERSION,
    entities = [Alarm::class],
    autoMigrations = [
        AutoMigration(
            from = 1,
            to = 2,
            spec = AppDatabase.IhpMigration::class
        )
    ],
    exportSchema = true
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun alarmDao(): AlarmDao

    @DeleteTable(tableName = "테이블이름")
    class IhpMigration : AutoMigrationSpec {}

    companion object {
        @Volatile
        private var instance: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase =
            instance ?: synchronized(this) {
                instance ?: buildDatabase(context).also {
                    instance = it
                }
            }

        private fun buildDatabase(appContext: Context) =
            Room.databaseBuilder(appContext, AppDatabase::class.java, "inhandplus")
                .build()

        const val LATEST_VERSION = 2
    }
}
반응형