1、schemas数据结构:
{
"formatVersion": 1,
"database": {
"version": 3,
"identityHash": "2d05b9491a3bd2b17de229846df033e2",
"entities": [
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2d05b9491a3bd2b17de229846df033e2')"
]
}
}
其中identifyHash决定数据库的完整性校验。
如果查看db文件会发现room会有额外的一个表,用来记录这个identifyHash:
当数据库open的时候,会首先检测identify:
public void onOpen(SupportSQLiteDatabase db) {
super.onOpen(db);
checkIdentity(db);
mDelegate.onOpen(db);
// there might be too many configurations etc, just clear it.
mConfiguration = null;
}
private void checkIdentity(SupportSQLiteDatabase db) {
if (hasRoomMasterTable(db)) {
//读取数据库identify
String identityHash = null;
Cursor cursor = db.query(new SimpleSQLiteQuery(RoomMasterTable.READ_QUERY));
//noinspection TryFinallyCanBeTryWithResources
try {
if (cursor.moveToFirst()) {
identityHash = cursor.getString(0);
}
} finally {
cursor.close();
}
//与代码中的identify进行对比
if (!mIdentityHash.equals(identityHash) && !mLegacyHash.equals(identityHash)) {
//校验失败抛出room无法校验完整性异常
throw new IllegalStateException("Room cannot verify the data integrity. Looks like"
+ " you've changed schema but forgot to update the version number. You can"
+ " simply fix this by increasing the version number.");
}
} else {
// No room_master_table, this might an a pre-populated DB, we must validate to see if its suitable for usage.
ValidationResult result = mDelegate.onValidateSchema(db);
if (!result.isValid) {
//预填充数据库有一个无效的结构
throw new IllegalStateException("Pre-packaged database has an invalid schema: "
+ result.expectedFoundMsg);
}
mDelegate.onPostMigrate(db);
updateIdentity(db);
}
}