Room源码分析

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);
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值