问题描述
我的应用崩溃了,因为我没有正确处理迁移. 我正在寻找一种解决方案来迁移表中1列的名称.
My app is crashing because I am not handling migration properly. I'm looking for a solution to migrate the name of 1 column in my table.
在我的项目中,我有一个名为" content "的房间表,该房间表带有 Double 属性" archivedCount ".在最新版本的应用程序中,属性 archivedCount 属性仍重命名为 dismissCount ,仍为 Double.
In my project I a have a room table named 'content' with a Double attribute 'archivedCount'. In the latest version of the app the attribute archivedCount attribute is re-named to dismissCount, still as type Double.
原始内容模型
@Entity(tableName = "content")
data class Content(@PrimaryKey var id: String, var archiveCount: Double) : Parcelable {...}
新内容模型
@Entity(tableName = "content")
data class Content(@PrimaryKey var id: String, var dismissCount: Double) : Parcelable {...}
尝试的解决方案
在阅读Google Developer Advocate的说明了解Room的迁移后,我尝试了在帖子的具有复杂模式更改的迁移部分中概述的解决方案,该方法需要制作原始表的副本,删除旧表,然后重命名新创建的表.
Attempted Solution
After reading a Google Developer Advocate's explanation Understanding migrations with Room, I attempted her solution outlined in the post's section Migrations with complex schema changes which entails making a copy of the original table, deleting the old table, then renaming the newly created table.
使用下面的以下方法,在此行上出现运行时错误:database.execSQL("INSERT INTO content_new (id, dismissCount) SELECT id, archiveCount FROM users");
,因为我已经清除了应用程序的缓存,所以旧表不再存在.
With the following approach below there is a runtime error on this line: database.execSQL("INSERT INTO content_new (id, dismissCount) SELECT id, archiveCount FROM users");
because I already cleared my app's cache so the old table no longer exists.
是否可以在不重新创建整个表的情况下更新单个列?
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
// Create the new table
database.execSQL(
"CREATE TABLE content_new (id TEXT, dismissCount REAL, PRIMARY KEY(id))");
// Copy the data
database.execSQL("INSERT INTO content_new (id, dismissCount) SELECT id, archiveCount FROM users");
// Remove the old table
database.execSQL("DROP TABLE content");
// Change the table name to the correct one
database.execSQL("ALTER TABLE content_new RENAME TO content");
}
};
推荐答案
解决方案
借助@TimBiegeleisen的指导,我们发现 Android的实现用于 API 27 和 28 的SQLite 3.19 尚未升级到版本 3.25 的SQLite,该版本允许 StackOverflow帖子.
Solution
Thanks to the guidance from @TimBiegeleisen we discovered that the Android implementation of SQLite 3.19 for API 27 and 28 has not yet upgraded to the version 3.25 SQLite which allows this feature outlined in this StackOverflow post.
一旦Android升级了诸如此类的命令以更改表列,便可以:database.execSQL("ALTER TABLE content RENAME COLUMN archiveCount TO dismissCount")
Once Android upgrades a command such as this to alter a table column will be possible: database.execSQL("ALTER TABLE content RENAME COLUMN archiveCount TO dismissCount")
这篇关于Android Room:如何迁移列重命名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!