App迭代过程中,难免需要对数据库进行更新,有可能是字段的增加,修改或删除,也有可能需要新建一张表,这就涉及到数据库的迁移Migrate,最简单粗暴的方法是在Room的配置项中添加fallbackToDestructiveMigration()
方法,如下
Room.databaseBuilder(context.applicationContext,
AppDatabase::class.java, "exercise.db")
.fallbackToDestructiveMigration() //添加此方法
.build()
为什么说是简单粗暴呢,因为它是直接删除之前的数据库,重新再创建新的数据库,这在大部分情况下绝对是灾难性的做法,所以更好的做法是addMigrations(Migration... migrations)
,具体以下步骤:
一、version升级+1 (我这边是3 -> 4)
@Database(entities = [HistoryEntity::class,CollectEntity::class], version = 4)
abstract class AppDatabase: RoomDatabase() {
//code
}
二、自定义Migration,如下三种情况:
1.增加一个字段update_time
private val MIGRATION_1_2: Migration = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE history ADD COLUMN update_time INTEGER NOT NULL DEFAULT 0")
}
}
2.创建一个新表collect
private val MIGRATION_2_3: Migration = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL(
"CREATE TABLE collect (collect_id INTEGER NOT NULL DEFAULT 0,line_name_collect TEXT NOT NULL DEFAULT '', upper_or_down_collect TEXT NOT NULL DEFAULT '', PRIMARY KEY(collect_id))")
}
}
3.更改一个字段类型
private val MIGRATION_4_3: Migration = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
//创建一个备份的新表
database.execSQL(
"CREATE TABLE collect_new_one (collect_id INTEGER NOT NULL DEFAULT 0,line_name_collect TEXT NOT NULL DEFAULT '', upper_or_down_collect TEXT NOT NULL DEFAULT '', PRIMARY KEY(collect_id))")
// 把旧表的数据拷贝到新表
database.execSQL(
"INSERT INTO collect_new_one (collect_id , line_name_collect, upper_or_down_collect) SELECT collect_id, line_name_collect, upper_or_down_collect FROM collect")
// 删除掉旧表
database.execSQL("DROP TABLE collect")
// 重命名新表(完成谋权篡位)
database.execSQL("ALTER TABLE collect_new_one RENAME TO collect")
}
}
三、将自定义好的Migration加入配置
Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java, "exercise.db"
) .addMigrations(MIGRATION_1_2,MIGRATION_2_3,MIGRATION_3_4)
.build()
这就是完整的Room数据库迁移,但是这当中可能会碰到几个异常报错,比如
Room Database Migration doesnt properly handle ALTER TABLE migration
解决方法可以定位到我第一个例子(增加一个字段)的sql语句,在后面加入INTEGER NOT NULL DEFAULT 0
保证当它为null时赋予0,否则Room会直接抛异常;其他的报错基本能从报错信息理解出来。
顺便晒出AppDatabase
代码
@Database(entities = [HistoryEntity::class, CollectEntity::class], version = 4)
abstract class AppDatabase : RoomDatabase() {
abstract fun historyDao(): HistoryDao
abstract fun collectDao(): CollectionDao
companion object {
@Volatile
private var INSTANCE: AppDatabase? = null
fun getInstance(): AppDatabase =
INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(App.instance).also { INSTANCE = it }
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java, "exercise.db"
).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4)
.build()
private val MIGRATION_1_2: Migration = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE history ADD COLUMN update_time INTEGER NOT NULL DEFAULT 0")
}
}
private val MIGRATION_2_3: Migration = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL(
"CREATE TABLE collect (collect_id INTEGER NOT NULL DEFAULT 0,line_name_collect TEXT NOT NULL DEFAULT '', upper_or_down_collect TEXT NOT NULL DEFAULT '', PRIMARY KEY(collect_id))"
)
}
}
private val MIGRATION_3_4: Migration = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL(
"CREATE TABLE collect_new_one (collect_id INTEGER NOT NULL DEFAULT 0,line_name_collect TEXT NOT NULL DEFAULT '', upper_or_down_collect TEXT NOT NULL DEFAULT '', PRIMARY KEY(collect_id))"
)
database.execSQL(
"INSERT INTO collect_new_one (collect_id , line_name_collect, upper_or_down_collect) SELECT collect_id, line_name_collect, upper_or_down_collect FROM collect"
)
database.execSQL("DROP TABLE collect")
database.execSQL("ALTER TABLE collect_new_one RENAME TO collect")
}
}
}
}
总结
这是我自己练手项目中截取的一个记录,项目里使用到jetpack,后面有时间还会一一记录与分享,对于Room的简单使用上总体感觉还算方便快速,就是这个数据迁移会踩点坑,比较麻烦