mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-26 04:07:50 +00:00
Merge branch 'dev/codable-database-value' into development
This commit is contained in:
commit
e19de4e42e
11 files changed
+500
-124
No files matched your search
@@ -91,7 +91,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
```
|
||||
|
||||
- **New**: [#993](https://github.com/groue/GRDB.swift/pull/993) by [@groue](https://github.com/groue): QueryInterfaceRequest builder with dynamic table/view name
|
||||
- **New**: Types that adopt both `DatabaseValueConvertible` and `Codable` now profit from automatic JSON encoding and decoding.
|
||||
- **Documentation Update**: The [Requests](README.md#requests) chapter was updated for the new `Table` type that can build requests without any record type.
|
||||
- **Documentation Update**: The [Custom Value Types](README.md#custom-value-types) chapter was extended about the new support for codable value types encoded as JSON arrays or objects.
|
||||
|
||||
|
||||
## 5.8.0
|
||||
|
||||
@@ -478,6 +478,10 @@
|
||||
566BE7212342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
|
||||
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
56713FDE2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
56713FDF2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
56713FE02691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; };
|
||||
56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */; };
|
||||
56717272261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */; };
|
||||
@@ -1431,6 +1435,7 @@
|
||||
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = "<group>"; };
|
||||
566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = "<group>"; };
|
||||
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = "<group>"; };
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = "<group>"; };
|
||||
56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CaseInsensitiveIdentifier.swift; sourceTree = "<group>"; };
|
||||
@@ -1734,6 +1739,7 @@
|
||||
5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */,
|
||||
5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */,
|
||||
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */,
|
||||
56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */,
|
||||
5605F1581C672E4000235C62 /* StandardLibrary.swift */,
|
||||
);
|
||||
path = StandardLibrary;
|
||||
@@ -2974,6 +2980,7 @@
|
||||
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
56F5ABD91D814330001F60CB /* Data.swift in Sources */,
|
||||
565490D41D5AE252005622CB /* (null) in Sources */,
|
||||
56713FDF2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
565490B61D5AE236005622CB /* Configuration.swift in Sources */,
|
||||
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */,
|
||||
@@ -3031,6 +3038,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECAA025D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56713FDE2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
@@ -3625,6 +3633,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECAA225D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56713FE02691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */,
|
||||
AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */,
|
||||
AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */,
|
||||
@@ -3988,6 +3997,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
|
||||
let dbValue: DatabaseValue
|
||||
let codingPath: [CodingKey]
|
||||
@@ -155,15 +157,13 @@ private struct DatabaseValueDecoder: Decoder {
|
||||
var userInfo: [CodingUserInfoKey: Any] { [:] }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
throw DecodingError.typeMismatch(
|
||||
type,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "keyed decoding is not supported"))
|
||||
// We need to switch to JSON decoding
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
// We need to switch to JSON decoding
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
@@ -173,7 +173,20 @@ private struct DatabaseValueDecoder: Decoder {
|
||||
|
||||
extension DatabaseValueConvertible where Self: Decodable {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
|
||||
do {
|
||||
return try self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
|
||||
} catch is JSONRequiredError {
|
||||
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)
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
|
||||
@@ -40,13 +42,18 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode(dbValueConvertible.databaseValue)
|
||||
} else {
|
||||
try value.encode(to: DatabaseValueEncoder(encode: encode))
|
||||
try DatabaseValueEncoder(encode: encode).encode(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DatabaseValueEncoder: Encoder {
|
||||
private class DatabaseValueEncoder: Encoder {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
var requiresJSON = false
|
||||
|
||||
init(encode: @escaping (DatabaseValue) -> Void) {
|
||||
self.encode = encode
|
||||
}
|
||||
|
||||
/// The path of coding keys taken to get to this point in encoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
@@ -63,7 +70,14 @@ private struct DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
|
||||
fatalError("keyed encoding is not supported")
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
// Unfortunately (bis), we can't throw right from here, so let's
|
||||
// return a JSONRequiredEncoder that will throw as soon as possible.
|
||||
requiresJSON = true
|
||||
let container = JSONRequiredEncoder.KeyedContainer<Key>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding multiple unkeyed values.
|
||||
@@ -73,7 +87,13 @@ private struct DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
fatalError("unkeyed encoding is not supported")
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
// Unfortunately (bis), we can't throw right from here, so let's
|
||||
// return a JSONRequiredEncoder that will throw as soon as possible.
|
||||
requiresJSON = true
|
||||
return JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding a single primitive value.
|
||||
@@ -86,13 +106,41 @@ private struct DatabaseValueEncoder: Encoder {
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
DatabaseValueEncodingContainer(encode: encode)
|
||||
}
|
||||
|
||||
func encode<T: Encodable>(_ value: T) throws {
|
||||
do {
|
||||
try value.encode(to: self)
|
||||
if requiresJSON {
|
||||
// Here we handle empty arrays and dictionaries.
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
} catch is JSONRequiredError {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
encoder.dateEncodingStrategy = .millisecondsSince1970
|
||||
encoder.nonConformingFloatEncodingStrategy = .throw
|
||||
if #available(watchOS 4.0, OSX 10.13, iOS 11.0, tvOS 11.0, *) {
|
||||
// guarantee some stability in order to ease value comparison
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
}
|
||||
let jsonData = try encoder.encode(value)
|
||||
|
||||
// Store JSON String in the database for easier debugging and
|
||||
// database inspection. Thanks to SQLite weak typing, we won't
|
||||
// have any trouble decoding this string into data when we
|
||||
// eventually perform JSON decoding.
|
||||
// TODO: possible optimization: avoid this conversion to string,
|
||||
// and store raw data bytes as an SQLite string
|
||||
let jsonString = String(data: jsonData, encoding: .utf8)!
|
||||
try jsonString.encode(to: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible where Self: Encodable {
|
||||
public var databaseValue: DatabaseValue {
|
||||
var dbValue: DatabaseValue! = nil
|
||||
let encoder = DatabaseValueEncoder(encode: { dbValue = $0 })
|
||||
try! self.encode(to: encoder)
|
||||
try! DatabaseValueEncoder(encode: { dbValue = $0 }).encode(self)
|
||||
return dbValue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
struct JSONRequiredError: Error { }
|
||||
|
||||
/// The encoder that always ends up with a JSONRequiredError
|
||||
struct JSONRequiredEncoder: Encoder {
|
||||
var codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
|
||||
let container = KeyedContainer<Key>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
|
||||
struct KeyedContainer<KeyType: CodingKey>: KeyedEncodingContainerProtocol {
|
||||
var codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
// swiftlint:disable comma
|
||||
func encodeNil(forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Bool, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int8, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int16, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int32, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int64, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt8, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt16, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt32, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt64, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode<T>(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() }
|
||||
// swiftlint:enable comma
|
||||
|
||||
func nestedContainer<NestedKey>(
|
||||
keyedBy keyType: NestedKey.Type,
|
||||
forKey key: KeyType)
|
||||
-> KeyedEncodingContainer<NestedKey>
|
||||
where NestedKey: CodingKey
|
||||
{
|
||||
let container = KeyedContainer<NestedKey>(codingPath: codingPath + [key])
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder() -> Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder(forKey key: KeyType) -> Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension JSONRequiredEncoder: SingleValueEncodingContainer {
|
||||
func encodeNil() throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Bool ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int8 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int16 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int32 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int64 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt8 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt16) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt32) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt64) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Float ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Double) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: String) throws { throw JSONRequiredError() }
|
||||
func encode<T>(_ value: T) throws where T: Encodable { throw JSONRequiredError() }
|
||||
}
|
||||
|
||||
extension JSONRequiredEncoder: UnkeyedEncodingContainer {
|
||||
var count: Int { 0 }
|
||||
|
||||
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type)
|
||||
-> KeyedEncodingContainer<NestedKey>
|
||||
where NestedKey: CodingKey
|
||||
{
|
||||
let container = KeyedContainer<NestedKey>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
|
||||
mutating func superEncoder() -> Encoder { self }
|
||||
}
|
||||
@@ -88,7 +88,7 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
|
||||
func encodeIfPresent(_ value: Float?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
|
||||
func encodeIfPresent(_ value: Double?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
|
||||
func encodeIfPresent(_ value: String?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
|
||||
// swiftlint:disable comma
|
||||
// swiftlint:enable comma
|
||||
|
||||
func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T: Encodable {
|
||||
if let value = value {
|
||||
@@ -182,20 +182,24 @@ private class ColumnEncoder<Record: EncodableRecord>: Encoder {
|
||||
}
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
|
||||
// Keyed values require JSON encoding: we need to throw
|
||||
// JSONRequiredError. Since we can't throw right from here, let's
|
||||
// delegate the job to a dedicated container.
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
// Unfortunately (bis), we can't throw right from here, so let's
|
||||
// return a JSONRequiredEncoder that will throw as soon as possible.
|
||||
requiresJSON = true
|
||||
let container = JSONRequiredEncoder<Record>.KeyedContainer<Key>(codingPath: codingPath)
|
||||
let container = JSONRequiredEncoder.KeyedContainer<Key>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
// Keyed values require JSON encoding: we need to throw
|
||||
// JSONRequiredError. Since we can't throw right from here, let's
|
||||
// delegate the job to a dedicated container.
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
// Unfortunately (bis), we can't throw right from here, so let's
|
||||
// return a JSONRequiredEncoder that will throw as soon as possible.
|
||||
requiresJSON = true
|
||||
return JSONRequiredEncoder<Record>(codingPath: codingPath)
|
||||
return JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
@@ -224,105 +228,6 @@ extension ColumnEncoder: SingleValueEncodingContainer {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - JSONRequiredEncoder
|
||||
|
||||
/// The error that triggers JSON encoding
|
||||
private struct JSONRequiredError: Error { }
|
||||
|
||||
/// The encoder that always ends up with a JSONRequiredError
|
||||
private struct JSONRequiredEncoder<Record: EncodableRecord>: Encoder {
|
||||
var codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
|
||||
let container = KeyedContainer<Key>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
|
||||
struct KeyedContainer<KeyType: CodingKey>: KeyedEncodingContainerProtocol {
|
||||
var codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
func encodeNil(forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Bool, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int8, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int16, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int32, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int64, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt8, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt16, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt32, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt64, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode<T>(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() }
|
||||
|
||||
func nestedContainer<NestedKey>(
|
||||
keyedBy keyType: NestedKey.Type,
|
||||
forKey key: KeyType)
|
||||
-> KeyedEncodingContainer<NestedKey>
|
||||
where NestedKey: CodingKey
|
||||
{
|
||||
let container = KeyedContainer<NestedKey>(codingPath: codingPath + [key])
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder() -> Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder(forKey key: KeyType) -> Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension JSONRequiredEncoder: SingleValueEncodingContainer {
|
||||
func encodeNil() throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Bool ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int8 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int16 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int32 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int64 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt8 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt16) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt32) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt64) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Float ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Double) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: String) throws { throw JSONRequiredError() }
|
||||
func encode<T>(_ value: T) throws where T: Encodable { throw JSONRequiredError() }
|
||||
}
|
||||
|
||||
extension JSONRequiredEncoder: UnkeyedEncodingContainer {
|
||||
var count: Int { 0 }
|
||||
|
||||
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type)
|
||||
-> KeyedEncodingContainer<NestedKey>
|
||||
where NestedKey: CodingKey
|
||||
{
|
||||
let container = KeyedContainer<NestedKey>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
|
||||
mutating func superEncoder() -> Encoder { self }
|
||||
}
|
||||
|
||||
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
|
||||
private var iso8601Formatter: ISO8601DateFormatter = {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
|
||||
@@ -396,9 +396,6 @@ extension ColumnDecoder: SingleValueDecodingContainer {
|
||||
}
|
||||
}
|
||||
|
||||
/// The error that triggers JSON decoding
|
||||
private struct JSONRequiredError: Error { }
|
||||
|
||||
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
|
||||
private var iso8601Formatter: ISO8601DateFormatter = {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
|
||||
@@ -324,6 +324,8 @@
|
||||
5670329C212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; };
|
||||
567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; };
|
||||
56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
56713FE42691F487006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
|
||||
5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
|
||||
56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; };
|
||||
@@ -955,6 +957,7 @@
|
||||
566BE7132342541F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = "<group>"; };
|
||||
56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = "<group>"; };
|
||||
56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = "<group>"; };
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = "<group>"; };
|
||||
5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3TokenizerDescriptor.swift; sourceTree = "<group>"; };
|
||||
@@ -1215,6 +1218,7 @@
|
||||
5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */,
|
||||
5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */,
|
||||
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */,
|
||||
56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */,
|
||||
5605F1581C672E4000235C62 /* StandardLibrary.swift */,
|
||||
);
|
||||
path = StandardLibrary;
|
||||
@@ -2271,6 +2275,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5656A8722295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
56713FE42691F487006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */,
|
||||
563B8FBE24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
@@ -2634,6 +2639,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */,
|
||||
563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
|
||||
@@ -1552,6 +1552,23 @@ The `databaseValue` property returns [DatabaseValue](#databasevalue), a type tha
|
||||
|
||||
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.
|
||||
|
||||
> :point_up: **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.
|
||||
|
||||
|
||||
## Transactions and Savepoints
|
||||
|
||||
|
||||
@@ -129,6 +129,169 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromDecodable4() throws {
|
||||
struct Value: Decodable, DatabaseValueConvertible {
|
||||
let strings: [String]
|
||||
|
||||
var databaseValue: DatabaseValue {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// Success from DatabaseValue
|
||||
let value = Value.fromDatabaseValue(#"{ "strings": ["foo", "bar"] }"#.databaseValue)!
|
||||
XCTAssertEqual(value.strings, ["foo", "bar"])
|
||||
}
|
||||
do {
|
||||
// Success from database
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let value = try Value.fetchOne(db, sql: #"SELECT '{ "strings": ["foo", "bar"] }'"#)!
|
||||
XCTAssertEqual(value.strings, ["foo", "bar"])
|
||||
}
|
||||
}
|
||||
do {
|
||||
// Failure from DatabaseValue
|
||||
let value = Value.fromDatabaseValue(1.databaseValue)
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromDecodable5() throws {
|
||||
struct Value: Decodable, DatabaseValueConvertible {
|
||||
let dictionary: [String: Int]
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
dictionary = try .init(from: decoder)
|
||||
}
|
||||
|
||||
var databaseValue: DatabaseValue {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// Success from DatabaseValue
|
||||
let value = Value.fromDatabaseValue(#"{"foo": 1}"#.databaseValue)!
|
||||
XCTAssertEqual(value.dictionary, ["foo": 1])
|
||||
}
|
||||
do {
|
||||
// Success from database
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let value = try Value.fetchOne(db, sql: #"SELECT '{"foo": 1}'"#)!
|
||||
XCTAssertEqual(value.dictionary, ["foo": 1])
|
||||
}
|
||||
}
|
||||
do {
|
||||
// Failure from DatabaseValue
|
||||
let value = Value.fromDatabaseValue(1.databaseValue)
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromDecodable6() throws {
|
||||
struct Value: Decodable, DatabaseValueConvertible {
|
||||
let strings: [String]
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
strings = try .init(from: decoder)
|
||||
}
|
||||
|
||||
var databaseValue: DatabaseValue {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// Success from DatabaseValue
|
||||
let value = Value.fromDatabaseValue(#"["foo", "bar"]"#.databaseValue)!
|
||||
XCTAssertEqual(value.strings, ["foo", "bar"])
|
||||
}
|
||||
do {
|
||||
// Success from database
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let value = try Value.fetchOne(db, sql: #"SELECT '["foo", "bar"]'"#)!
|
||||
XCTAssertEqual(value.strings, ["foo", "bar"])
|
||||
}
|
||||
}
|
||||
do {
|
||||
// Failure from DatabaseValue
|
||||
let value = Value.fromDatabaseValue(1.databaseValue)
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromDecodable7() throws {
|
||||
struct Value: Decodable, DatabaseValueConvertible {
|
||||
let dictionary: [String: Int]
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
dictionary = try container.decode([String: Int].self)
|
||||
}
|
||||
|
||||
var databaseValue: DatabaseValue {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// Success from DatabaseValue
|
||||
let value = Value.fromDatabaseValue(#"{"foo": 1}"#.databaseValue)!
|
||||
XCTAssertEqual(value.dictionary, ["foo": 1])
|
||||
}
|
||||
do {
|
||||
// Success from database
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let value = try Value.fetchOne(db, sql: #"SELECT '{"foo": 1}'"#)!
|
||||
XCTAssertEqual(value.dictionary, ["foo": 1])
|
||||
}
|
||||
}
|
||||
do {
|
||||
// Failure from DatabaseValue
|
||||
let value = Value.fromDatabaseValue(1.databaseValue)
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromDecodable8() throws {
|
||||
struct Value: Decodable, DatabaseValueConvertible {
|
||||
let strings: [String]
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
strings = try container.decode([String].self)
|
||||
}
|
||||
|
||||
var databaseValue: DatabaseValue {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
// Success from DatabaseValue
|
||||
let value = Value.fromDatabaseValue(#"["foo", "bar"]"#.databaseValue)!
|
||||
XCTAssertEqual(value.strings, ["foo", "bar"])
|
||||
}
|
||||
do {
|
||||
// Success from database
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let value = try Value.fetchOne(db, sql: #"SELECT '["foo", "bar"]'"#)!
|
||||
XCTAssertEqual(value.strings, ["foo", "bar"])
|
||||
}
|
||||
}
|
||||
do {
|
||||
// Failure from DatabaseValue
|
||||
let value = Value.fromDatabaseValue(1.databaseValue)
|
||||
XCTAssertNil(value)
|
||||
}
|
||||
}
|
||||
|
||||
func testCustomDatabaseValueConvertible() throws {
|
||||
struct Value : Decodable, DatabaseValueConvertible {
|
||||
let string: String
|
||||
|
||||
@@ -87,6 +87,124 @@ class DatabaseValueConvertibleEncodableTests: GRDBTestCase {
|
||||
XCTAssertEqual(dbValue.storage.value as! String, "foo")
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromEncodable4() throws {
|
||||
struct Value: Encodable, DatabaseValueConvertible {
|
||||
let strings: [String]
|
||||
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = Value(strings: ["foo", "bar"]).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"{"strings":["foo","bar"]}"#)
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = Value(strings: []).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"{"strings":[]}"#)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromEncodable5() throws {
|
||||
struct Value: Encodable, DatabaseValueConvertible {
|
||||
let dictionary: [String: Int]
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
try dictionary.encode(to: encoder)
|
||||
}
|
||||
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = Value(dictionary: ["foo": 1]).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"{"foo":1}"#)
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = Value(dictionary: [:]).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"{}"#)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromEncodable6() throws {
|
||||
struct Value: Encodable, DatabaseValueConvertible {
|
||||
let strings: [String]
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
try strings.encode(to: encoder)
|
||||
}
|
||||
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = Value(strings: ["foo", "bar"]).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"["foo","bar"]"#)
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = Value(strings: []).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"[]"#)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromEncodable7() throws {
|
||||
struct Value: Encodable, DatabaseValueConvertible {
|
||||
let dictionary: [String: Int]
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(dictionary)
|
||||
}
|
||||
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = Value(dictionary: ["foo": 1]).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"{"foo":1}"#)
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = Value(dictionary: [:]).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"{}"#)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseValueConvertibleImplementationDerivedFromEncodable8() throws {
|
||||
struct Value: Encodable, DatabaseValueConvertible {
|
||||
let strings: [String]
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(strings)
|
||||
}
|
||||
|
||||
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? {
|
||||
preconditionFailure("not tested")
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = Value(strings: ["foo", "bar"]).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"["foo","bar"]"#)
|
||||
}
|
||||
|
||||
do {
|
||||
let dbValue = Value(strings: []).databaseValue
|
||||
XCTAssertEqual(dbValue.storage.value as! String, #"[]"#)
|
||||
}
|
||||
}
|
||||
|
||||
func testEncodableRawRepresentable() {
|
||||
// Test that the rawValue is encoded with DatabaseValueConvertible, not with Encodable
|
||||
struct Value : RawRepresentable, Encodable, DatabaseValueConvertible {
|
||||
|
||||
Reference in new issue
Block a user