• 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. }

  • 相关阅读:
    PyTorch深度解析:Tensor——神经网络的核心构建块
    Vue学习:Hello小案例
    log4j2同步日志引发的性能问题
    MySql优化
    稳定好用的短连接生成平台,支持API批量生成
    HTML做一个简单的页面(纯html代码)地球专题学习网站
    这位00后经历人生重大变故后,选择了智能家居,选择了Aqara绿米
    mysql中json类型字段用法
    JVM 虚拟机系列:架构(二)一图看懂虚拟机架构:JNI
    C++教程(2)
  • 原文地址:https://blog.csdn.net/u010123949/article/details/127809284