The Record Protocols
GRDB defines three main record protocols:FetchableRecord
Decode database rows into Swift types
PersistableRecord
Encode Swift types into database rows
Codable Records
Leverage Swift’s Codable for automatic conformance
Protocol Hierarchy
The record protocols build on each other:FetchableRecord
Types that conform toFetchableRecord can be decoded from database rows:
PersistableRecord & MutablePersistableRecord
Types that conform toPersistableRecord or MutablePersistableRecord can be saved to the database:
Choosing Between Protocols
When to use FetchableRecord only
When to use FetchableRecord only
Use
FetchableRecord alone when you only need to read data from the database:- Read-only views or computed data
- Data from complex queries or joins
- Immutable reference data
When to use MutablePersistableRecord
When to use MutablePersistableRecord
Use
MutablePersistableRecord for struct-based records with auto-incremented primary keys:- Records are value types (structs)
- Need to capture auto-incremented IDs after insertion
- Prefer Swift’s value semantics
When to use PersistableRecord
When to use PersistableRecord
Use
PersistableRecord for class-based records or immutable structs:- Records are reference types (classes)
- No need to mutate on insertion
- Primary keys are set before insertion
When to combine with TableRecord
When to combine with TableRecord
Add
TableRecord conformance to enable query interface methods:Codable Integration
The simplest way to adopt record protocols is through Swift’sCodable:
Codable, GRDB automatically provides implementations for init(row:) and encode(to:). See Codable Records for more details.
Persistence Methods
Records that conform toMutablePersistableRecord or PersistableRecord get persistence methods:
Inserts a new record into the database
Updates an existing record based on its primary key
Inserts or updates depending on whether the record exists
Deletes the record from the database
Best Practices
The Record class is legacy: GRDB historically provided a
Record base class, but this approach is no longer recommended. Prefer protocol conformance with structs instead.Next Steps
FetchableRecord
Learn how to fetch records from the database
PersistableRecord
Learn how to persist records to the database
Codable Records
Use Codable for automatic protocol conformance