Enhanced DocC for DatabaseValueConvertible

Also:
- Redirect the "Custom Value Types" README chapter to DatabaseValueConvertible documentation.
- Document how to support Tagged https://github.com/pointfreeco/swift-tagged
This commit is contained in:
Gwendal Roué committed 2023-03-04 14:51:46 +01:00
1 parent 441823d5f4
commit cc8ed5ccb5
2 files changed
+202 -47

No files matched your search

+192 -4
View File
@@ -1,12 +1,200 @@
/// A type that can convert itself into and out of a database value.
///
/// ## Overview
///
/// A `DatabaseValueConvertible` type supports conversion to and from
/// database values (null, integers, doubles, strings, and blobs).
/// `DatabaseValueConvertible` is adopted by `Bool`, `Int`, `String`,
/// `Date`, etc.
///
/// To conform to `DatabaseValueConvertible`, provide custom implementations
/// for ``fromDatabaseValue(_:)-21zzv`` and ``databaseValue-1ob9k``. These
/// implementations are ready-made for `RawRepresentable` types whose
/// `RawValue` is `StatementColumnConvertible`, and for `Codable` types.
/// > Note: Types that converts to and from multiple columns in a database
/// > row must not conform to the `DatabaseValueConvertible` protocol. Those
/// > types are called **record types**, and should conform to record
/// > protocols instead. See <doc:QueryInterface>.
///
/// ## Conforming to the DatabaseValueConvertible Protocol
///
/// To conform to `DatabaseValueConvertible`, implement the two requirements
/// ``fromDatabaseValue(_:)-21zzv`` and ``databaseValue-1ob9k``. Do not
/// customize the ``fromMissingColumn()-7iamp`` requirement. Do not
/// customize the conformance of `Optional`: it is built-in when the wrapped
/// type is itself `DatabaseValueConvertible`.
///
/// It is important that the implementation of `fromDatabaseValue` returns
/// nil if the type can not be decoded from the raw database value. This
/// nil value will have GRDB throw a decoding error accordingly.
///
/// For example:
///
/// ```swift
/// struct EvenInteger {
/// let value: Int // Guaranteed even
///
/// init?(_ value: Int) {
/// guard value.isMultiple(of: 2) else {
/// return nil // Not an even number
/// }
/// self.value = value
/// }
/// }
///
/// extension EvenInteger: DatabaseValueConvertible {
/// var databaseValue: DatabaseValue {
/// value.databaseValue
/// }
///
/// static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
/// guard let value = Int.fromDatabaseValue(dbValue) else {
/// return nil // Not an integer
/// }
/// return EvenInteger(value) // Nil if not even
/// }
/// }
/// ```
///
/// ### Built-in RawRepresentable support
///
/// `DatabaseValueConvertible` implementation is ready-made for
/// `RawRepresentable` types whose raw value is itself
/// `DatabaseValueConvertible`, such as enums:
///
/// ```swift
/// enum Grape: String {
/// case chardonnay, merlot, riesling
/// }
///
/// // Empty DatabaseValueConvertible adoption is enough
/// extension Grape: DatabaseValueConvertible { }
/// ```
///
/// ### Built-in Codable support
///
/// `DatabaseValueConvertible` is also ready-made for `Codable` types, which
/// are automatically coded and decoded from JSON arrays and objects:
///
/// ```swift
/// struct Color: Codable {
/// var r: Double
/// var g: Double
/// var b: Double
/// }
///
/// // Encodes and decodes `Color` as a JSON object in the database:
/// extension Color: DatabaseValueConvertible { }
/// ```
///
/// By default, such codable value types are encoded and decoded with the
/// standard [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder)
/// and [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder).
/// `Data` values are handled with the `.base64` strategy, `Date` with the
/// `.millisecondsSince1970` strategy, and non conforming floats with the
/// `.throw` strategy.
///
/// In order to customize the JSON format, provide a custom implementation
/// of the `DatabaseValueConvertible` requirements.
///
/// ### Adding support for the Tagged library
///
/// [Tagged](https://github.com/pointfreeco/swift-tagged) is a popular
/// library that makes it possible to enhance the type-safety of our
/// programs with dedicated wrappers around basic types. For example:
///
/// ```swift
/// import Tagged
///
/// struct Player: Identifiable {
/// // Player.ID can not be mismatched with Team.ID or Award.ID, even
/// // though they all wrap strings.
/// typealias ID = Tagged<Player, String>
/// var id: ID
/// var name: String
/// var score: Int
/// }
/// ```
///
/// Applications that use both Tagged and GRDB will want to add those lines
/// somewhere:
///
/// ```swift
/// import GRDB
/// import Tagged
///
/// extension Tagged: SQLExpressible where RawValue: SQLExpressible { }
/// extension Tagged: StatementBinding where RawValue: StatementBinding { }
/// extension Tagged: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
/// ```
///
/// This makes it possible to use `Tagged` in all the expected places:
///
/// ```swift
/// let id: Player.ID = ...
/// let player = try Player.find(db, id: id)
/// ```
///
/// ## Optimized Values
///
/// For extra performance, custom value types can conform to both
/// `DatabaseValueConvertible` and ``StatementColumnConvertible``. This
/// extra protocol grants raw access to the [low-level C SQLite
/// interface](https://www.sqlite.org/c3ref/column_blob.html) when
/// decoding values.
///
/// For example:
///
/// ```swift
/// extension EvenInteger: StatementColumnConvertible {
/// init?(sqliteStatement: SQLiteStatement, index: CInt) {
/// let int64 = sqlite3_column_int64(sqliteStatement, index)
/// guard let value = Int(exactly: int64) else {
/// return nil // Does not fit Int (probably a 32-bit architecture)
/// }
/// self.init(value) // Nil if not even
/// }
/// }
/// ```
///
/// > Note: Standard collections `Array`, `Set`, and `Dictionary` do not
/// > conform to `DatabaseValueConvertible`, on purpose. You won't be able
/// > to directly fetch or store arrays, sets, or dictionaries as JSON
/// > database values.
/// >
/// > Standard collections get free JSON support when they are embedded as
/// > properties of `Codable` record types, though: see <doc:QueryInterface>.
/// >
/// > It is not advised to consider the absence of those conformances as a
/// > lack, and add `DatabaseValueConvertible` conformance to those
/// > collection types in your application. This would litter JSON values in
/// > unexpected places, and foster misuse. For example, it is better when
/// > the code below *does not compile*:
/// >
/// > ```swift
/// > // MISUSE: if Array would conform to DatabaseValueConvertible, this
/// > // code would compile, and run the incorrect SQLite query
/// > // `SELECT ... WHERE id IN ('[1,2,3]')`, instead of the expected
/// > // `SELECT ... WHERE id IN (1, 2, 3)`.
/// > let ids = [1, 2, 3]
/// > let players = try Player.fetchAll(db, sql: """
/// > SELECT * FROM player WHERE id IN (?)
/// > """, arguments: [ids])
/// > ```
/// >
/// > Correct and fostered versions of the code above are:
/// >
/// > ```swift
/// > // CORRECT (explicit SQLite arguments):
/// > let ids = [1, 2, 3]
/// > let questionMarks = databaseQuestionMarks(count: ids.count) // "?,?,?"
/// > let players = try Player.fetchAll(db, sql: """
/// > SELECT * FROM player WHERE id IN (\(questionMarks))
/// > """, arguments: StatementArguments(ids))
/// >
/// > // CORRECT (SQL interpolation):
/// > let ids = [1, 2, 3]
/// > let request: SQLRequest<Player> = """
/// > SELECT * FROM player WHERE id IN \(ids)
/// > """
/// > let players = try request.fetchAll(db)
/// > ```
///
/// ## Topics
///
+10 -43
View File
@@ -460,7 +460,7 @@ SQLite API
- [Date and DateComponents](#date-and-datecomponents)
- [NSNumber, NSDecimalNumber, and Decimal](#nsnumber-nsdecimalnumber-and-decimal)
- [Swift enums](#swift-enums)
- [Custom Value Types](#custom-value-types)
- [DatabaseValueConvertible]: the protocol for custom value types
- [Transactions and Savepoints]
- [SQL Interpolation]
@@ -989,7 +989,7 @@ case .blob(let data): print("Data: \(data)")
}
```
You can extract regular [values](#values) (Bool, Int, String, Date, Swift enums, etc.) from DatabaseValue with the [DatabaseValueConvertible.fromDatabaseValue()](#custom-value-types) method:
You can extract regular [values](#values) (Bool, Int, String, Date, Swift enums, etc.) from DatabaseValue with the [DatabaseValueConvertible.fromDatabaseValue()](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible/fromdatabasevalue(_:)-21zzv) method:
```swift
let dbValue: DatabaseValue = row["bookCount"]
@@ -1142,7 +1142,7 @@ GRDB ships with built-in support for the following value types:
- **Full-Text Patterns**: [FTS3Pattern](Documentation/FullTextSearch.md#fts3pattern) and [FTS5Pattern](Documentation/FullTextSearch.md#fts5pattern).
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
- Generally speaking, all types that adopt the [DatabaseValueConvertible] protocol.
Values can be used as [statement arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
@@ -1301,7 +1301,7 @@ if let row = try Row.fetchOne(db, ...) {
}
```
See also [Codable Records] for more date customization options, and [DatabaseValueConvertible](#custom-value-types) if you want to define a Date-wrapping type with customized database representation.
See also [Codable Records] for more date customization options, and [DatabaseValueConvertible] if you want to define a Date-wrapping type with customized database representation.
#### DateComponents
@@ -1453,44 +1453,6 @@ if dbValue.isNull {
```
### Custom Value Types
Conversion to and from the database is based on the `DatabaseValueConvertible` protocol:
```swift
protocol DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from dbValue, if possible.
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
}
```
All types that adopt this protocol can be used like all other [values](#values) (Bool, Int, String, Date, Swift enums, etc.)
The `databaseValue` property returns [DatabaseValue](#databasevalue), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc. Conversion to DatabaseValue *must not* fail.
The `fromDatabaseValue()` factory method returns an instance of your custom type if the database value contains a suitable value. If the database value does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
Value types that adopt both `DatabaseValueConvertible` and an archival protocol ([Codable, Encodable or Decodable](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types)) are automatically coded and decoded from JSON arrays and objects:
```swift
// Encoded as a JSON object in the database:
struct Color: Codable, DatabaseValueConvertible {
var r: Double
var g: Double
var b: Double
}
```
For such codable value types, GRDB uses the standard [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder) and [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) from Foundation. By default, Data values are handled with the `.base64` strategy, Date with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy.
In order to customize the JSON format, provide a custom implementation of the `DatabaseValueConvertible` requirements.
> **Note**: standard sequences such as `Array`, `Set`, or `Dictionary` do not conform to `DatabaseValueConvertible`, even conditionally. You won't be able to directly fetch or store arrays, sets, or dictionaries as JSON database values. You can get free JSON support from these standard types when they are embedded as properties of [Codable Records], though.
## Prepared Statements
**Prepared Statements** let you prepare an SQL query and execute it later, several times if you need, with different arguments.
@@ -2958,7 +2920,7 @@ try dbQueue.write { db in
Codable records encode and decode their properties according to their own implementation of the Encodable and Decodable protocols. Yet databases have specific requirements:
- Properties are always coded according to their preferred database representation, when they have one (all [values](#values) that adopt the [DatabaseValueConvertible](#custom-value-types) protocol).
- Properties are always coded according to their preferred database representation, when they have one (all [values](#values) that adopt the [DatabaseValueConvertible] protocol).
- You can customize the encoding and decoding of dates and uuids.
- Complex properties (arrays, dictionaries, nested structs, etc.) are stored as JSON.
@@ -6899,6 +6861,10 @@ This chapter has been renamed [Record Comparison].
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
#### Custom Value Types
Custom Value Types conform to the [DatabaseValueConvertible] protocol.
#### Customized Decoding of Database Rows
This chapter has been renamed [Beyond FetchableRecord].
@@ -7057,3 +7023,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
[Database queues]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue
[`DatabasePool`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
[database pools]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
[DatabaseValueConvertible]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible