SwiftData uses SQLite as its underlying storage engine. Sometimes, you may want to inspect or interact with the SQLite database directly for debugging or migration purposes.

Locating the SQLite Database

The SQLite file is typically stored in your app’s sandboxed documents directory. You can find its location by printing the URL in your code:

if let container = try? ModelContainer(for: YourModel.self) {
  print(container.configurations.first?.url ?? "No URL found")
}

This will output a path similar to:

/Users/william/Library/Containers/uk.co.domainname.appname/Data/Library/Application Support/default.store

You can also find the database file in the Xcode Organizer under the “Devices and Simulators” section, where you can download the app’s container.

Inspecting the Database

You can use tools like DB Browser for SQLite to open and inspect the database file.

or use command-line tools:

sqlite3 '/Users/william/Library/Containers/uk.co.domainname.appname/Data/Library/Application Support/default.store'

To see the tables in the database, you can run:

.tables

You’ll see that the table names aren’t exactly the same as your SwiftData model names. They are prefixed with Z so they look like ZYourModelName. This is a convention used by SwiftData to manage its internal structure.

To view the schema of a specific table, use:

.schema YourTableName

To view the contents of a specific table, you can run:

SELECT * FROM YourTableName;

To exit the SQLite command line, type:

.quit

Notes

  • Directly modifying the database is not recommended.
  • Always back up your data before making changes.

References: