【SwiftData】 データストアファイルを SQLite コマンドで見てみる

そもそものきっかけは、

「Preview と シュミレーター の保存データは違うのか」

という素朴な疑問から。

 

📂 データファイルはどこにあるのか

xcrun で調べたみたが、パスが深くて長いし、

デバイスやアプリのIDがあれこれ違うので面倒すぎる。

コード内から吐かすのが楽ちん。


FileManager
  .default
  .urls(for: .applicationSupportDirectory, in: .userDomainMask)
  .last!
  .path(percentEncoded: false)

👉 Where does SwiftData store the data? | Apple Developer Forums hatena-bookmark

とか、いや、


URL.applicationSupportDirectory
  .path(percentEncoded: false)

で取得できるので print() などで出力。


// Playground
/Users/{USER_NAME}/Library/
  Application Support/

// Preview
/Users/{USER_NAME}/Library/Developer/
  Xcode/UserData/Previews/
  Simulator Devices/{DEVICE_ID}/
  data/Containers/Data/Application/{APP_ID}/Library/
  Application Support/

// Simulator
/Users/{USER_NAME}/Library/Developer/
  CoreSimulator/
  Devices/{DEVICE_ID}/
  data/Containers/Data/Application/{APP_ID}/Library/
  Application Support/

見づらいので改行しています。

実行環境で違うのか。

それぞれの「Application Support」 ディレクトリ以下に該当ファイルがある。


default.store
default.store-shm
default.store-wal

 

📂 SQLite コマンドで見てみる

👉 sqlite — Homebrew Formulae hatena-bookmark

せっかくなので覗く。


$ sqlite default.store

SQLite version 3.43.2 2023-10-10 13:08:14
Enter ".help" for usage hints.

sqlite> .tables
ACHANGE             ATRANSACTIONSTRING  ZTODO               Z_MODELCACHE
ATRANSACTION        Z_METADATA          Z_PRIMARYKEY

sqlite> .schema ZTODO
CREATE TABLE ZTODO ( Z_PK INTEGER PRIMARY KEY, Z_ENT INTEGER, Z_OPT INTEGER, ZTIME TIMESTAMP, ZTEXT VARCHAR );

sqlite> .headers on
sqlite> .mode column

sqlite> select * from ZTODO;
Z_PK  Z_ENT  Z_OPT  ZTIME             ZTEXT
----  -----  -----  ----------------  -----------------------------------------------------------
11    2      1      727759392.308872  2. Do, or do not. There is no try.
12    2      1      727759392.914907  3. Most things look better when you put them in a circle.
13    2      1      727759393.191901  4. Could not get advice.
14    2      1      727760485.069984  0. You're not that important; it's what you do that counts.
15    2      1      727760485.781123  1. Most things done in secrecy are better left undone.
16    2      1      727760486.503812  2. When in doubt, just take the next small step.
17    2      1      727760487.112024  3. Have a firm handshake.

よくできてるなあ、SwiftData って。