2020년 7월 19일 일요일

Room migrations in Kotlin

To test you need two class 

//===============================================================
// AppDatabase class
Database(entities = [Song::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
        companion object {
        @Volatile private var INSTANCE: AppDatabase? = null
        fun getInstance(context: Context): AppDatabase =
            INSTANCE ?: synchronized(this) {                
         INSTANCE ?: buildDatabase(context).also {INSTANCE = it }}
        private fun buildDatabase(context: Context) =              
        Room.databaseBuilder(context.applicationContext,                  
        AppDatabase::class.java, "test.db").build()
        fun destroyInstance() {
            INSTANCE = null        
        }
    }
}

//===============================================================
// Entity class
// when the version was 1
@Entitydata class Song(
    @PrimaryKey val id: Long,    val title: String
)
//===============================================================


When you run an app with the database version 1
after then you modified the Song class added 'tag' entity.
@Entitydata class Song(
    @PrimaryKey    val id: Long,    
    val title: String,    
    val tag: String // Added in version 2.
)
you should change the version number of AppDatabase class like below from 1 to 2
Database(entities = [Song::class], version = 2, exportSchema = false)

you also have to edit database builder like this

private fun buildDatabase(context: Context) =
     Room.databaseBuilder(context.applicationContext, 
          AppDatabase::class.java, "terry.db")
          .addMigrations(MIGRATION_1_2).build()

and add migration code or edit it in the Song class
// Migration from 1 to 2, Room 2.1.0val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL(
            "ALTER TABLE Song ADD COLUMN tag TEXT NOT NULL DEFAULT ''")
    }
}

That's all! :)


댓글 없음:

댓글 쓰기