好吧,我正在尝试测试数据库迁移。不幸的是,看起来有些错误。
@RunWith(AndroidJUnit4ClassRunner.class)
public class MigrationTest {
private static final String TEST_DB = "migration-test";
@Rule
public MigrationTestHelper helper;
public MigrationTest() {
helper = new MigrationTestHelper(InstrumentationRegistry.getInstrumentation(),
AppDatabase.class.getCanonicalName(),
new FrameworkSQLiteOpenHelperFactory());
}
@Test
public void migrateAll() throws IOException {
// Create earliest version of the database.
SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 1);
db.close();
// Open latest version of the database. Room will validate the schema
// once all migrations execute.
AppDatabase appDb = Room.databaseBuilder(
InstrumentationRegistry.getInstrumentation().getTargetContext(),
AppDatabase.class,
TEST_DB)
.addMigrations(ALL_MIGRATIONS).build();
appDb.getOpenHelper().getWritableDatabase();
appDb.close();
}
// Array of all migrations
private static final Migration[] ALL_MIGRATIONS = new Migration[]{MIGRATION_1_2};
}
迁移代码。
public static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE mytable ADD COLUMN reference_code TEXT");
}
};
在进行真正的迁移时,一切正常,但在junit测试用例中,出现以下错误。
E/SQLiteLog: (1) duplicate column name: reference_code
E/TestRunner: failed: migrateAll(com.apps.MigrationTest)
E/TestRunner: ----- begin exception -----
E/TestRunner: android.database.sqlite.SQLiteException: duplicate column name: reference_code (code 1 SQLITE_ERROR): , while compiling: ALTER TABLE mytable ADD COLUMN reference_code TEXT
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
at a
据我了解,好像SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 1);
正在创建数据库的架构V2(而不是版本1)。
结果,新列被标记为重复列。
要解决此问题,我必须将我的version = 1
回滚到@Database
类,然后再次开始进行junit测试。
有人可以帮我吗?
我在这里遵循Google指南:https://developer.android.com/training/data-storage/room/migrating-db-versions.html
答案 0 :(得分:0)
好吧,我终于找到了。看来我的资产文件夹中生成了错误的模式。
要解决此问题,这是我所做的。
这是我的Java对象与数据库版本1和2之间的区别
char* str = malloc(sizeof(char) * (strlen(tribe_name) + 1));
希望这会有所帮助。