Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Room verify data integrity? Where are the db versions/hashes stored?

My goal is to use Room's new createFromAsset api to load a pre-loaded database from the apps assets. However, I noticed that if my pre-loaded database does not have a organic (generated by Room) id and identity hash in the room_master_table, I get a "IllegalStateException: Room cannot verify the data integrity." exception thrown.

I have tried using an exact db file generated by Room as a pre-loaded db that it copies over and this works, but I am not sure why. It seems like these database version/id/hashes are saved somewhere and Room validates it against these versions. But I have tried deleting the local db and uninstalling the app as well but still get the same exception thrown.

I'd like to know how room generates a specific id and hash in room_master_table and how does it validate them?

like image 869
Dan Avatar asked Aug 18 '19 18:08

Dan


1 Answers

Room Persistence Library generates unique identity_hash for every version of database. And it is stored at room_master_table.

Every time you compile your application room generates mIdentityHash reflecting your current database schema. And whenever you run application and call database for the first time Room compares it to the mLegacyHash which is already stored in database. So if these two hashes are different, Room throws IlligalStateException.

All of these processes done with Annotation Processing Library that you add into your build.gradle file with

kapt "androidx.room:room-compiler:$room_version"
// annotationProcessing androidx.room:room-compiler:$room_version in case you use Java

You can check Room source code for detailed verification. Take a look at RoomOpenHelper.java class which has checkIdentity() function where they check identity_hash and throw exception if two identity hashes don't match.

If you are looking for how exactly identity_key is generated take a look at SchemaIdentityKey.kt

I hope it was helpful.

like image 109
musooff Avatar answered Nov 01 '22 01:11

musooff