Record the problems encountered during the migration of the Room database. To migrate the Room database, you only need to implement androidx.room.migration.Migration .
Three situations are recorded below
- Modify the structure of the table
object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
// 创建新的临时表
database.execSQL("CREATE TABLE publish_post_bean_new (uid TEXT NOT NULL DEFAULT '' ,value TEXT NOT NULL DEFAULT '' ,time INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(time))")
// 复制数据
database.execSQL("INSERT INTO publish_post_bean_new (uid, value,time) SELECT uid, value ,strftime('%s','now')*1000 FROM publish_post_bean")
// 删除表结构
database.execSQL("DROP TABLE publish_post_bean")
// 临时表名称更改
database.execSQL("ALTER TABLE publish_post_bean_new RENAME TO publish_post_bean")
}
}
Description: publish_post_bean
adds a time
field, and a modified type of the primary key, create a temporary table, and then copy the data, by which the replication process strftime('%s','now')
to get the current time.
- Just add fields
object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE publish_post_bean ADD COLUMN article TEXT NOT NULL DEFAULT '' ")
database.execSQL("ALTER TABLE publish_post_bean ADD COLUMN type INTEGER NOT NULL DEFAULT 0 ")
}
}
- Create new table
object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("CREATE TABLE tag_history_bean (tagId TEXT NOT NULL DEFAULT '' ,uid TEXT NOT NULL DEFAULT '' ,value TEXT NOT NULL DEFAULT '' ,time INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(time))")
}
}
The above note is that when a field is needed, whether the field is null or not has a default value, such as:, NOT NULL DEFAULT ''
consistent with the bean type defined by yourself. At the same time, you can set to fallbackToDestructiveMigrationOnDowngrade
roll back an error occurred during database upgrade.