• Room源码分析


    1、schemas数据结构:

    1. {
    2. "formatVersion": 1,
    3. "database": {
    4. "version": 3,
    5. "identityHash": "2d05b9491a3bd2b17de229846df033e2",
    6. "entities": [
    7. ],
    8. "views": [],
    9. "setupQueries": [
    10. "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
    11. "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2d05b9491a3bd2b17de229846df033e2')"
    12. ]
    13. }
    14. }

    其中identifyHash决定数据库的完整性校验。

    如果查看db文件会发现room会有额外的一个表,用来记录这个identifyHash:

     当数据库open的时候,会首先检测identify:

    1. public void onOpen(SupportSQLiteDatabase db) {
    2. super.onOpen(db);
    3. checkIdentity(db);
    4. mDelegate.onOpen(db);
    5. // there might be too many configurations etc, just clear it.
    6. mConfiguration = null;
    7. }
    1. private void checkIdentity(SupportSQLiteDatabase db) {
    2. if (hasRoomMasterTable(db)) {
    3. //读取数据库identify
    4. String identityHash = null;
    5. Cursor cursor = db.query(new SimpleSQLiteQuery(RoomMasterTable.READ_QUERY));
    6. //noinspection TryFinallyCanBeTryWithResources
    7. try {
    8. if (cursor.moveToFirst()) {
    9. identityHash = cursor.getString(0);
    10. }
    11. } finally {
    12. cursor.close();
    13. }
    14. //与代码中的identify进行对比
    15. if (!mIdentityHash.equals(identityHash) && !mLegacyHash.equals(identityHash)) {
    16. //校验失败抛出room无法校验完整性异常
    17. throw new IllegalStateException("Room cannot verify the data integrity. Looks like"
    18. + " you've changed schema but forgot to update the version number. You can"
    19. + " simply fix this by increasing the version number.");
    20. }
    21. } else {
    22. // No room_master_table, this might an a pre-populated DB, we must validate to see if its suitable for usage.
    23. ValidationResult result = mDelegate.onValidateSchema(db);
    24. if (!result.isValid) {
    25. //预填充数据库有一个无效的结构
    26. throw new IllegalStateException("Pre-packaged database has an invalid schema: "
    27. + result.expectedFoundMsg);
    28. }
    29. mDelegate.onPostMigrate(db);
    30. updateIdentity(db);
    31. }
    32. }

  • 相关阅读:
    云原生之旅 - 8)云原生时代的网关 Ingress Nginx
    服务器连接校园网
    全基因组重测序揭示了野生大豆的局部适应和分化的特征
    py split 用法
    创新实战|高转化网站首页设计的10大关键要素
    Network 之十 BIOS + MBR、UEFI + GPT、GRUB、BOOTMGR、SYSLINUX、Option ROM
    华为云Nginx配置
    性能测试的时间间隔获取方法
    GBase 8s 执行计划查询分析
    文件上传漏洞
  • 原文地址:https://blog.csdn.net/u010123949/article/details/127809284