【发布时间】:2018-11-11 10:48:54
【问题描述】:
我需要更新SQLite-Database,所以我创建了一个迁移。
在逐步调试此迁移时,没有错误,但正如我所见,仅更新了“日志文件”。
更改从未提交给数据库,我真的不明白我做错了什么,所以也许有人可以提供建议。?
我有一个名为“图像”的表,我需要创建一个名为“附件”的表。之后,我需要将所有数据从“图像”移动到“附件”,处理/转换一些数据,最后删除表“图像”。
这是我的实现:
1.我将库添加到我的项目中
implementation android.arch.persistence.room:runtime:1.0.0
implementation android.arch.persistence.room:compiler:1.0.0
2。创建迁移
val MIGRATION_2_3: Migration = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
// create table 'attachment'
database.execSQL("CREATE TABLE attachment (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, extenal_id INTEGER NOT NULL, userId TEXT, createdDateTime TEXT, displayFileName TEXT, fileExtension TEXT NOT NULL, noData INTEGER, identifier TEXT, commentText TEXT, localBaseFileName TEXT, dirty INTEGER NOT NULL, task_id TEXT NOT NULL, attachmentType INTEGER NOT NULL)")
// migrate data from table 'image' to 'attachment'
val cursor = database.query("SELECT * FROM image")
cursor.moveToFirst()
while (!cursor.isAfterLast) {
// get stored values
val image_id = cursor.getInt(0)
val externalId = cursor.getLong(1)
val customIdentifier = cursor.getString(2)
val createdAt = cursor.getString(3)
val imageType = cursor.getString(4)
val commentText = cursor.getString(5)
val createdBy = cursor.getString(6)
// cursor.getString(7)/ / not used anymore
val imageName = cursor.getString(8)
val dirty = cursor.getInt(9)
val task_id = cursor.getString(10)
// cursor.getString(11) // not used anymore
// create migration only for availably images
if (!imageName.isNullOrEmpty()) {
// get file extension or 'unknown' if not known
val fileExtension = MimeTypeMap.getSingleton().getExtensionFromMimeType(imageType) ?: "unknown"
val contentValues = ContentValues()
contentValues.put("id", image_id)
contentValues.put("external_id", externalId)
contentValues.put("userId", createdBy)
contentValues.put("createdDateTime", createdAt)
contentValues.put("displayFileName", imageName)
contentValues.put"fileExtension", fileExtension)
contentValues.put"noData", false)
contentValues.put("identifier", customIdentifier)
contentValues.put("commentText", commentText)
contentValues.put("localBaseFileName", imageName.split("_")[0])
contentValues.put("dirty", dirty)
contentValues.put("task_id", task_id)
contentValues.put("attachmentType", DatabaseManager.ATTACHMENT_TYPE_IMAGE)
// insert new data
database.insert("attachment", SQLiteDatabase.CONFLICT_REPLACE, contentValues)
}
// load next entry
cursor.moveToNext()
}
cursor.close()
// delete old table 'image'
// database.execSQL("DROP TABLE image")
}
}
3.添加了迁移到我的数据库实现
Room
.databaseBuilder(context, Database::class.java, "my_db.db")
.fallbackToDestructiveMigration()
.addMigrations(MIGRATION_2_3)
.build()
当我运行代码时,将调用迁移而没有任何错误。但是迁移后,只更新了'journal'-file,而不是数据库本身!?
我在这里缺少什么吗?没看懂。。。¯\_(ツ)_/¯
【问题讨论】:
标签: android database-migration android-room