mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-26 04:07:50 +00:00
Merge pull request #1429 from JhonnyBillM/dev/1428-EXTEND-VALUE-CONVERTIBLE-JSON-FORMAT-CUSTOMIZATION
Extend `DatabaseValueConvertible` JSON parsing format customization
This commit is contained in:
7 files changed
+167
-18
No files matched your search
+1
-1
@@ -61,7 +61,7 @@ How you can Contribute
|
||||
- Get familiar with the [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
|
||||
- Spaces, not tabs.
|
||||
- Whitespace-only lines are not trimmed.
|
||||
- Documentation comments are hard-wrapped at column 80 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 80).
|
||||
- Documentation comments are hard-wrapped at column 76 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 76).
|
||||
- No Swiftlint warning after a build.
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
// Standard collections `Array`, `Set`, and `Dictionary` do not conform to
|
||||
// `DatabaseValueConvertible`, on purpose.
|
||||
//
|
||||
@@ -59,6 +61,18 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
|
||||
///
|
||||
/// - returns: A decoded value, or, if decoding is impossible, nil.
|
||||
static func fromMissingColumn() -> Self?
|
||||
|
||||
/// Returns the `JSONDecoder` that decodes the value.
|
||||
///
|
||||
/// This method is dedicated to ``DatabaseValueConvertible`` types that
|
||||
/// also conform to the standard `Decodable` protocol.
|
||||
static func databaseJSONDecoder() -> JSONDecoder
|
||||
|
||||
/// Returns the `JSONEncoder` that encodes the value.
|
||||
///
|
||||
/// This method is dedicated to ``DatabaseValueConvertible`` types that
|
||||
/// also conform to the standard `Encodable` protocol.
|
||||
static func databaseJSONEncoder() -> JSONEncoder
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
@@ -75,6 +89,41 @@ extension DatabaseValueConvertible {
|
||||
public static func fromMissingColumn() -> Self? {
|
||||
nil // failure.
|
||||
}
|
||||
|
||||
/// Returns the `JSONDecoder` that decodes the value.
|
||||
///
|
||||
/// The default implementation returns a `JSONDecoder` with the
|
||||
/// following properties:
|
||||
///
|
||||
/// - `dataDecodingStrategy`: `.base64`
|
||||
/// - `dateDecodingStrategy`: `.millisecondsSince1970`
|
||||
/// - `nonConformingFloatDecodingStrategy`: `.throw`
|
||||
public static func databaseJSONDecoder() -> JSONDecoder {
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dataDecodingStrategy = .base64
|
||||
decoder.dateDecodingStrategy = .millisecondsSince1970
|
||||
decoder.nonConformingFloatDecodingStrategy = .throw
|
||||
return decoder
|
||||
}
|
||||
|
||||
/// Returns the `JSONEncoder` that encodes the value.
|
||||
///
|
||||
/// The default implementation returns a `JSONEncoder` with the
|
||||
/// following properties:
|
||||
///
|
||||
/// - `dataEncodingStrategy`: `.base64`
|
||||
/// - `dateEncodingStrategy`: `.millisecondsSince1970`
|
||||
/// - `nonConformingFloatEncodingStrategy`: `.throw`
|
||||
/// - `outputFormatting`: `.sortedKeys`
|
||||
public static func databaseJSONEncoder() -> JSONEncoder {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
encoder.dateEncodingStrategy = .millisecondsSince1970
|
||||
encoder.nonConformingFloatEncodingStrategy = .throw
|
||||
// guarantee some stability in order to ease value comparison
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
return encoder
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
|
||||
@@ -179,11 +179,7 @@ extension DatabaseValueConvertible where Self: Decodable {
|
||||
guard let data = Data.fromDatabaseValue(databaseValue) else {
|
||||
return nil
|
||||
}
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dataDecodingStrategy = .base64
|
||||
decoder.dateDecodingStrategy = .millisecondsSince1970
|
||||
decoder.nonConformingFloatDecodingStrategy = .throw
|
||||
return try? decoder.decode(Self.self, from: data)
|
||||
return try? databaseJSONDecoder().decode(Self.self, from: data)
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import Foundation
|
||||
|
||||
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
let jsonEncoder: JSONEncoder
|
||||
|
||||
var codingPath: [any CodingKey] { [] }
|
||||
|
||||
@@ -42,16 +43,21 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode(dbValueConvertible.databaseValue)
|
||||
} else {
|
||||
try DatabaseValueEncoder(encode: encode).encode(value)
|
||||
try DatabaseValueEncoder(jsonEncoder: jsonEncoder, encode: encode).encode(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class DatabaseValueEncoder: Encoder {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
let jsonEncoder: JSONEncoder
|
||||
var requiresJSON = false
|
||||
|
||||
init(encode: @escaping (DatabaseValue) -> Void) {
|
||||
init(
|
||||
jsonEncoder: JSONEncoder,
|
||||
encode: @escaping (DatabaseValue) -> Void
|
||||
) {
|
||||
self.jsonEncoder = jsonEncoder
|
||||
self.encode = encode
|
||||
}
|
||||
|
||||
@@ -104,7 +110,7 @@ private class DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
DatabaseValueEncodingContainer(encode: encode)
|
||||
DatabaseValueEncodingContainer(encode: encode, jsonEncoder: jsonEncoder)
|
||||
}
|
||||
|
||||
func encode<T: Encodable>(_ value: T) throws {
|
||||
@@ -115,13 +121,7 @@ private class DatabaseValueEncoder: Encoder {
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
} catch is JSONRequiredError {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
encoder.dateEncodingStrategy = .millisecondsSince1970
|
||||
encoder.nonConformingFloatEncodingStrategy = .throw
|
||||
// guarantee some stability in order to ease value comparison
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
let jsonData = try encoder.encode(value)
|
||||
let jsonData = try jsonEncoder.encode(value)
|
||||
|
||||
// Store JSON String in the database for easier debugging and
|
||||
// database inspection. Thanks to SQLite weak typing, we won't
|
||||
@@ -138,7 +138,11 @@ private class DatabaseValueEncoder: Encoder {
|
||||
extension DatabaseValueConvertible where Self: Encodable {
|
||||
public var databaseValue: DatabaseValue {
|
||||
var dbValue: DatabaseValue! = nil
|
||||
try! DatabaseValueEncoder(encode: { dbValue = $0 }).encode(self)
|
||||
try! DatabaseValueEncoder(
|
||||
jsonEncoder: Self.databaseJSONEncoder(),
|
||||
encode: { dbValue = $0 }
|
||||
)
|
||||
.encode(self)
|
||||
return dbValue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,7 +74,14 @@ extension Color: DatabaseValueConvertible { }
|
||||
|
||||
By default, such codable value types are encoded and decoded with the standard [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) and [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder). `Data` values are handled with the `.base64` strategy, `Date` with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy.
|
||||
|
||||
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements.
|
||||
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements, or implement these two methods:
|
||||
|
||||
```swift
|
||||
protocol DatabaseValueConvertible {
|
||||
static func databaseJSONDecoder() -> JSONDecoder
|
||||
static func databaseJSONEncoder() -> JSONEncoder
|
||||
}
|
||||
```
|
||||
|
||||
### Adding support for the Tagged library
|
||||
|
||||
@@ -144,6 +151,11 @@ This extra conformance is not required: only aim at the low-level C interface if
|
||||
|
||||
- ``databaseValue-1ob9k``
|
||||
|
||||
### Configuring the JSON format for the standard Decodable protocol
|
||||
|
||||
- ``databaseJSONDecoder()-7zou9``
|
||||
- ``databaseJSONEncoder()-37sff``
|
||||
|
||||
### Fetching Values from Raw SQL
|
||||
|
||||
- ``fetchCursor(_:sql:arguments:adapter:)-6elcz``
|
||||
|
||||
@@ -326,4 +326,57 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase {
|
||||
XCTAssertEqual(value, .foo)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromDecodableWithCustomJsonDecoder() throws {
|
||||
struct Value: Decodable, DatabaseValueConvertible {
|
||||
let duration: Double
|
||||
|
||||
var databaseValue: DatabaseValue {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
|
||||
public static func databaseJSONDecoder() -> JSONDecoder {
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dataDecodingStrategy = .base64
|
||||
decoder.dateDecodingStrategy = .millisecondsSince1970
|
||||
decoder.nonConformingFloatDecodingStrategy = .convertFromString(
|
||||
positiveInfinity: "+InF",
|
||||
negativeInfinity: "-InF",
|
||||
nan: "NaN"
|
||||
)
|
||||
return decoder
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// Success from DatabaseValue
|
||||
let value = Value.fromDatabaseValue(#"{ "duration": "+InF" }"#.databaseValue)!
|
||||
XCTAssertEqual(value.duration, Double.infinity)
|
||||
|
||||
let value2 = Value.fromDatabaseValue(#"{ "duration": "-InF" }"#.databaseValue)!
|
||||
XCTAssertEqual(value2.duration, -Double.infinity)
|
||||
|
||||
let value3 = Value.fromDatabaseValue(#"{ "duration": "NaN" }"#.databaseValue)!
|
||||
XCTAssertTrue(value3.duration.isNaN)
|
||||
}
|
||||
do {
|
||||
// Success from database
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let value = try Value.fetchOne(db, sql: #"SELECT '{ "duration": "+InF" }'"#)!
|
||||
XCTAssertEqual(value.duration, Double.infinity)
|
||||
|
||||
let value2 = try Value.fetchOne(db, sql: #"SELECT '{ "duration": "-InF" }'"#)!
|
||||
XCTAssertEqual(value2.duration, -Double.infinity)
|
||||
|
||||
let value3 = try Value.fetchOne(db, sql: #"SELECT '{ "duration": "NaN" }'"#)!
|
||||
XCTAssertTrue(value3.duration.isNaN)
|
||||
}
|
||||
}
|
||||
do {
|
||||
// Failure from DatabaseValue
|
||||
let value = Value.fromDatabaseValue("infinity".databaseValue)
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -304,4 +304,39 @@ extension DatabaseValueConvertibleEncodableTests {
|
||||
let encodedUUID = UUID.fromDatabaseValue(dbValue)!
|
||||
XCTAssertEqual(encodedUUID, value.uuid)
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromEncodableWithCustomJsonEncoder() throws {
|
||||
struct Value: Encodable, DatabaseValueConvertible {
|
||||
let duration: Double
|
||||
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
|
||||
public static func databaseJSONEncoder() -> JSONEncoder {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
encoder.dateEncodingStrategy = .millisecondsSince1970
|
||||
encoder.nonConformingFloatEncodingStrategy = .convertToString(
|
||||
positiveInfinity: "+InF",
|
||||
negativeInfinity: "-InF",
|
||||
nan: "NaN"
|
||||
)
|
||||
// guarantee some stability in order to ease value comparison
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
return encoder
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = Value(duration: .infinity).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"{"duration":"+InF"}"#)
|
||||
|
||||
let dbValue2 = Value(duration: -Double.infinity).databaseValue
|
||||
XCTAssertEqual(dbValue2.storage.value as! String, #"{"duration":"-InF"}"#)
|
||||
|
||||
let dbValue3 = Value(duration: .nan).databaseValue
|
||||
XCTAssertEqual(dbValue3.storage.value as! String, #"{"duration":"NaN"}"#)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user