Android 房间持久性库。在迁移中更改数据库视图

Android Room persistence library. Alter Database View in migration

我在 android 项目中使用 Room 持久性库。我有一个数据库视图,我想在我的应用程序的新版本中向它添加一列。正确的迁移代码是什么?

database.execSQL("????")

PS:我想更改视图,而不是 Table 我试过这个:

database.execSQL("ALTER TABLE table_name ADD COLUMN column_name data_type")

我收到此错误:无法将列添加到视图(代码 1 SQLITE_ERROR)

更新:我的观点是旧版本:

@Data
@DatabaseView("SELECT site.name AS address, group_site.name AS groupName, group_site.member_id AS memberId " +
        "FROM site, group_site " +
        "INNER JOIN groupsite_join_site " +
        "ON site.id = groupsite_join_site.site_id AND group_site.id = groupsite_join_site.group_site_id " 
)
public class SiteDetail {
    long memberId;
    String address;
    String groupName;
}

新版本:

@Data
@DatabaseView("SELECT site.id as id, site.name AS address, group_site.name AS groupName, group_site.member_id AS memberId " +
        "FROM site, group_site " +
        "INNER JOIN groupsite_join_site " +
        "ON site.id = groupsite_join_site.site_id AND group_site.id = groupsite_join_site.group_site_id " 
)
public class SiteDetail {
    long id;
    long memberId;
    String address;
    String groupName;
}

可以看出,我想将 id 列添加到我的数据库视图中。

您可以使用 alter query 添加新列,如

database.execSQL("ALTER TABLE table_name ADD column_name datatype")

首先创建迁移对象如下

val MigrationFrom1To2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("ALTER TABLE your_table_name ADD COLUMN your_column_name data_type")
    }
}

在此之后,在您的数据库配置中添加以上对象

Room.databaseBuilder(
    applicationContext, 
    MyAppDatabase::class.java, 
    "your_database_name"
).addMigrations(MigrationFrom1To2)
.build()

SQLite 的 3.25.0 版本之前(Android API 30 以下的任何内容)视图未根据 table 更改进行更改,根据

Compatibility Note: The behavior of ALTER TABLE when renaming a table was enhanced in versions 3.25.0 (2018-09-15) and 3.26.0 (2018-12-01) in order to carry the rename operation forward into triggers and views that reference the renamed table.

If any views refer to table X in a way that is affected by the schema change, then drop those views using DROP VIEW and recreate them with whatever changes are necessary to accommodate the schema change using CREATE VIEW.

在您的迁移中,您需要删除视图(在 ALTER TABLE 之前)然后创建视图 (创建视图的 SQL 可以从编译项目成功后生成Java,如果API小于30(或无关)。