Codable Support
SQLite.swift integrates with Swift's Codable protocols (introduced in Swift 4) to allow for easy serialization and deserialization of your custom types to and from the database.
Inserting Codable Types
You can directly insert any Encodable object into a table. SQLite.swift will map the object's properties to columns with matching names.
struct User: Codable {
let id: Int64
let name: String
let email: String
}
let users = Table("users")
let alice = User(id: 1, name: "Alice", email: "alice@example.com")
try db.run(users.insert(alice))
// INSERT INTO "users" ("id", "name", "email") VALUES (1, 'Alice', 'alice@example.com')
The insert method for Encodable types also supports OnConflict resolution and additional setters.
Updating Codable Types
Similarly, you can update a database row by passing a Codable object to the update method. This is typically used with a filter.
let updatedAlice = User(id: 1, name: "Alice L.", email: "alice.l@example.com")
try db.run(users.filter(id == 1).update(updatedAlice))
// UPDATE "users" SET "id" = 1, "name" = 'Alice L.', "email" = 'alice.l@example.com'
// WHERE ("id" = 1)
Calling update with a Codable object on an unfiltered query will update all rows in the table.
Retrieving Codable Types
To decode a database row back into your custom Decodable type, use the decode() method on a Row object. This is often used with map on a query result.
let query = users.filter(id == 1)
let userArray: [User] = try db.prepare(query).map { row in
return try row.decode()
}
if let alice = userArray.first {
print(alice.name) // "Alice L."
}
Restrictions and Advanced Usage
- Supported Property Types: The default
Codableimplementation supports basic types (Int,Bool,String,Double,Date,Data,UUID) and their optional variants. - Nested Objects: Nested
Codableobjects will be encoded as a JSON string into a singleTEXTcolumn. - Relationships: The default implementation does not handle database relationships (e.g., foreign keys). To support this, you must write a custom
Codableimplementation that manually encodes/decodes the relevant IDs. - Limitations: The implementation does not support nested containers, single-value containers, or super decoders/encoders from the
CodableAPI.