簡體   English   中英

遷移在 Room 中未正確處理

[英]Migration not handled properly in Room

我有一個數據庫表 class ,其中我確實更改了與索引相關的內容。 以前的索引是這樣的:

@Entity(indices = {@Index(value = {"jobNumber", "jobId"},
        unique = true)})

但我把它改成了

@Entity(indices = {
        @Index(value = "jobNumber", unique = true), @Index(value = "jobId", unique = true)
})

但是當我嘗試遷移時,它給了我這樣的問題:

caused by: java.lang.IllegalStateException: Migration didn't properly handle Job

我只需要第二種格式的 go 。 我嘗試添加遷移,但似乎不起作用。 這是我的代碼:

 public static final Migration MIGRATION_4_5 = new Migration(4, 5) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        migrateJobTableForIndices(database);
    }
};

private static void migrateJobTableForIndices(SupportSQLiteDatabase database) {
    //create new table
    database.execSQL(
            "CREATE TABLE Job_new (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, jobId INTEGER NOT NULL, " +
                    "jobNumber TEXT)");

    database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_Job_new_jobNumber_jobId ON Job_new (jobNumber, jobId)");
    // Copy the data
    database.execSQL(
            "INSERT INTO Job_new (id, jobId, jobNumber) " +
                    "SELECT id, jobId, jobNumber " +
                    "FROM Job");
    // Remove the old table
    database.execSQL("DROP TABLE Job");
    // Change the table name to the correct one
    database.execSQL("ALTER TABLE Job_new RENAME TO Job");
}

有沒有辦法為更新的索引格式添加遷移。 任何參考都非常感謝

As Room生成索引名稱。 您可以導出該方案以查看發生了什么。 通過將以下內容添加到您的 build.gradle:

android {
    ...
    javaCompileOptions {
        annotationProcessorOptions {
            arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
        }
    }

    ...
}

現在進行遷移。

事先你必須關閉foreign_keys

database.execSQL("PRAGMA foreign_keys=OFF;")

您必須刪除現有索引。 例如:

database.execSQL("DROP INDEX IF EXISTS `index_Job_jobNumber_jobId`")

然后我建議重命名表。

ALTER TABLE Job RENAME TO Job_old

創建Job

然后創建索引,您將在導出的架構位置找到該索引。 在此示例中,它位於您的$projectDir/schemas中。 從那里的文件中,您可以看到並復制Room如何創建索引並在創建表后添加這些索引的創建。

遷移數據。

放下桌子。

打開foreign_keys

database.execSQL("PRAGMA foreign_keys=ON;")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM