Introduction to GRDB.swift
Learning intentions
In this lesson, you will learn how to bridge the gap between Swift objects and database tables using GRDB.swift.
- Explain what an ORM-like layer is and why GRDB.swift is used in Swift development.
- Manage external dependencies by editing
Package.swift. - Define database schemas using migrations.
- Map Swift models to database rows using GRDB protocols.
What is GRDB.swift?
GRDB.swift is a SQLite toolkit for Swift. It gives you two ways to work with data:
- SQL-first: write SQL directly when you want full control.
- Record-based: map rows to Swift types for safer, cleaner code.
You can still use SQL when you need it, but GRDB gives you strong Swift typing and helpful conventions for day-to-day app code.
Setting up the dependency
To use GRDB.swift, you must tell Swift Package Manager (SPM) to download it. This is done in your Package.swift file.
1. Add the package
Add the GRDB.swift repository to your dependencies array:
let package = Package(
name: "SwiftPlayground",
dependencies: [
.package(url: "https://github.com/groue/GRDB.swift", exact: "7.10.0")
],
2. Add to target
Add "GRDB" to the dependencies array of your specific target:
targets: [
.executableTarget(
name: "SwiftPlayground",
dependencies: [
.product(name: "GRDB", package: "grdb.swift")
]
),
]
)
Once you save this file, your IDE (like Xcode or VS Code) will automatically download the library.
Complete example of Package.swift
Connecting to a .db file
GRDB works with SQLite database files that end in .db. You connect by creating a DatabaseQueue (single-threaded) or a DatabasePool (multi-threaded). For learning, DatabaseQueue is a good default.
Handling throwing functions
Most GRDB APIs are marked throws because database work can fail (missing files, bad SQL, locked database, and so on). In Swift, you handle this with do/catch, try?, or by propagating the error.
Modeling data with GRDB
GRDB uses lightweight protocols to map rows to Swift types. A typical model uses:
FetchableRecordto load rows from the database.PersistableRecordto insert and update rows.Codableto map columns to Swift properties.
GRDB does not rely on property wrappers. Instead, it uses Swift protocols and CodingKeys to map between properties and database columns.
Task A: Dependency Management
- Open your
Package.swiftfile. - Add the
GRDB.swiftpackage to your dependencies. - Add the
GRDBproduct to your main target. - Verify that the packages resolve (download) successfully.
Task B: Creating a Model
You have been given an existing database with a Purchaser table.
- Create a struct called
Purchaserthat conforms toCodable,FetchableRecord, andPersistableRecord. - Set the table name to
"Purchaser". - Add a primary key property
purchaserIDof typeInt64. - Add properties for
name(String),count(Int), andreservedTable(String). - Use
CodingKeysso the database columns (PurchaserID,Name,Count,ReservedTable) map to your Swift properties.
Task C: Expanding the Schema
Create models for the remaining tables in the schema.
ItemwithitemID(Int64),name(String),price(Double).OrderwithorderID(Int64),purchaserID(Int64),amount(Double).OrderLinewithorderID(Int64),itemID(Int64),quantity(Int).- Use
CodingKeysso the database columns (ItemID,OrderID,PurchaserID) map to your Swift properties.
Task D: Using the Model
Summary
GRDB.swift gives you a clean way to work with SQLite using either SQL or Swift models.
- SQLite toolkit with SQL-first and record-based options.
Package.swiftmanages the library download.FetchableRecord/PersistableRecordmap rows to Swift types.CodingKeyscontrol how Swift properties map to column names.
Review
Use these prompts to check your understanding.
- Why might you still write SQL even when using GRDB.swift?
- What does
databaseTableNamedo? - When would you use
CodingKeysin a GRDB model? - What is the benefit of an in-memory
DatabaseQueueduring testing?
Extension challenge for Super Players!
- Research
DatabaseMigratorin GRDB.swift. - Add
created_atandupdated_atcolumns to yourbookstable. - Explain in a comment how these timestamps help a developer track data changes.