把 SQLite DB 變成 App 專用資料格式

Jack Yu
2 min readApr 2, 2022

--

SQLite DB 的檔案一般來說就是個 “資料庫” 檔案。最近發現 SQLite 有幾個 PRAGMA 可以修改檔案標頭,讓這個檔案變成你的 App 的專用檔案。雖然沒看過有人這樣做過,但還是紀錄一下…

設定 Application ID

PRAGMA schema.application_id;
PRAGMA
schema.application_id = integer ;

The application_id PRAGMA is used to query or set the 32-bit signed big-endian “Application ID” integer located at offset 68 into the database header. Applications that use SQLite as their application file-format should set the Application ID integer to a unique integer so that utilities such as file(1) can determine the specific file type rather than just reporting “SQLite3 Database”. A list of assigned application IDs can be seen by consulting the magic.txt file in the SQLite source repository.

從清單來看,應該是沒人在用或沒人在維護

設定版本

PRAGMA schema.user_version;
PRAGMA
schema.user_version = integer ;

The user_version pragma will to get or set the value of the user-version integer at offset 60 in the database header. The user-version is an integer that is available to applications to use however they want. SQLite makes no use of the user-version itself.

這個欄位做為 DB schema 版本或是 App 版本,用來管相容性滿好用的,不用自己存一個 table 放這個資訊

(加映)SQLite 也會自動維護 schema 版本

PRAGMA schema.schema_version;
PRAGMA
schema.schema_version = integer ;

The schema_version pragma will get or set the value of the schema-version integer at offset 40 in the database header.

SQLite automatically increments the schema-version whenever the schema changes. As each SQL statement runs, the schema version is checked to ensure that the schema has not changed since the SQL statement was prepared. Subverting this mechanism by using “PRAGMA schema_version” may cause SQL statement to run using an obsolete schema, which can lead to incorrect answers and/or database corruption.

這個欄位是 SQLite 自己會維護的,但寫 DB migration/update 還是用 user_version 或自己維護吧,這個就參考用

Reference

--

--

Jack Yu
Jack Yu

No responses yet