From 620eb6f21cdd0593f2064f5f8feaa2eed3b19567 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 4 Jul 2021 17:34:31 +0200 Subject: [PATCH 1/4] Default DatabaseValueConvertible+Codable implementation uses the JSON format --- GRDB.xcodeproj/project.pbxproj | 10 ++ .../DatabaseValueConvertible+Decodable.swift | 25 ++- .../DatabaseValueConvertible+Encodable.swift | 58 ++++++- .../StandardLibrary/JSONRequiredEncoder.swift | 97 +++++++++++ GRDB/Record/EncodableRecord+Encodable.swift | 121 ++----------- GRDB/Record/FetchableRecord+Decodable.swift | 3 - GRDBCustom.xcodeproj/project.pbxproj | 6 + ...tabaseValueConvertibleDecodableTests.swift | 163 ++++++++++++++++++ ...tabaseValueConvertibleEncodableTests.swift | 118 +++++++++++++ 9 files changed, 477 insertions(+), 124 deletions(-) create mode 100644 GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index a9a61a52d..4f2018a56 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -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 = ""; }; 566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; }; 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; + 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CaseInsensitiveIdentifier.swift; sourceTree = ""; }; @@ -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 */, diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift index e9ed49e80..b25c456bf 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift @@ -155,15 +155,13 @@ private struct DatabaseValueDecoder: Decoder { var userInfo: [CodingUserInfoKey: Any] { [:] } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { - 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 +171,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 + } } } diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index 42d73482c..0c9ec1518 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -40,13 +40,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 +68,14 @@ private struct DatabaseValueEncoder: Encoder { /// - precondition: May not be called after a value has been encoded through /// a previous `self.singleValueContainer()` call. func container(keyedBy type: Key.Type) -> KeyedEncodingContainer { - 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(codingPath: codingPath) + return KeyedEncodingContainer(container) } /// Returns an encoding container appropriate for holding multiple unkeyed values. @@ -73,7 +85,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 +104,41 @@ private struct DatabaseValueEncoder: Encoder { func singleValueContainer() -> SingleValueEncodingContainer { DatabaseValueEncodingContainer(encode: encode) } + + func encode(_ 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 } } diff --git a/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift b/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift new file mode 100644 index 000000000..8ab622a19 --- /dev/null +++ b/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift @@ -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(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { + let container = KeyedContainer(codingPath: codingPath) + return KeyedEncodingContainer(container) + } + + func unkeyedContainer() -> UnkeyedEncodingContainer { self } + + func singleValueContainer() -> SingleValueEncodingContainer { self } + + struct KeyedContainer: 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(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() } + // swiftlint:enable comma + + func nestedContainer( + keyedBy keyType: NestedKey.Type, + forKey key: KeyType) + -> KeyedEncodingContainer + where NestedKey: CodingKey + { + let container = KeyedContainer(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(_ value: T) throws where T: Encodable { throw JSONRequiredError() } +} + +extension JSONRequiredEncoder: UnkeyedEncodingContainer { + var count: Int { 0 } + + mutating func nestedContainer(keyedBy keyType: NestedKey.Type) + -> KeyedEncodingContainer + where NestedKey: CodingKey + { + let container = KeyedContainer(codingPath: codingPath) + return KeyedEncodingContainer(container) + } + + mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self } + + mutating func superEncoder() -> Encoder { self } +} diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index 0e511bc40..e61e57e4e 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -88,7 +88,7 @@ private class RecordEncoder: 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(_ value: T?, forKey key: Key) throws where T: Encodable { if let value = value { @@ -182,20 +182,24 @@ private class ColumnEncoder: Encoder { } func container(keyedBy type: Key.Type) -> KeyedEncodingContainer 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.KeyedContainer(codingPath: codingPath) + let container = JSONRequiredEncoder.KeyedContainer(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(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: Encoder { - var codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } - - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { - let container = KeyedContainer(codingPath: codingPath) - return KeyedEncodingContainer(container) - } - - func unkeyedContainer() -> UnkeyedEncodingContainer { self } - - func singleValueContainer() -> SingleValueEncodingContainer { self } - - struct KeyedContainer: 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(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() } - - func nestedContainer( - keyedBy keyType: NestedKey.Type, - forKey key: KeyType) - -> KeyedEncodingContainer - where NestedKey: CodingKey - { - let container = KeyedContainer(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(_ value: T) throws where T: Encodable { throw JSONRequiredError() } -} - -extension JSONRequiredEncoder: UnkeyedEncodingContainer { - var count: Int { 0 } - - mutating func nestedContainer(keyedBy keyType: NestedKey.Type) - -> KeyedEncodingContainer - where NestedKey: CodingKey - { - let container = KeyedContainer(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() diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 68a4d84b9..ae96ce03e 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -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() diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index aa2cde0e0..d224c905a 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -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 = ""; }; 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; + 56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3TokenizerDescriptor.swift; sourceTree = ""; }; @@ -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 */, diff --git a/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift index 3d9e19470..4b75c9e9f 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleDecodableTests.swift @@ -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 diff --git a/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift index 81efa85be..c155d344c 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleEncodableTests.swift @@ -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 { From ad48aa6eec153ba8d6654ce7155c9f6dfd0bc0ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 4 Jul 2021 18:36:56 +0200 Subject: [PATCH 2/4] Document the default DatabaseValueConvertible+Codable implementation --- README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/README.md b/README.md index 409799a83..ac1045007 100644 --- a/README.md +++ b/README.md @@ -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 From d772e8da3a0f76f4246dad621db03802b9218848 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 4 Jul 2021 18:37:44 +0200 Subject: [PATCH 3/4] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index dea94add5..a9b62adb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 From 57cf9b45b659e9ac70ddc23d4a09f7ef07d7e82b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 4 Jul 2021 19:28:27 +0200 Subject: [PATCH 4/4] Add missing Foundation import for SPM --- .../StandardLibrary/DatabaseValueConvertible+Decodable.swift | 2 ++ .../StandardLibrary/DatabaseValueConvertible+Encodable.swift | 2 ++ 2 files changed, 4 insertions(+) diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift index b25c456bf..b65e64a34 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift @@ -1,3 +1,5 @@ +import Foundation + private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { let dbValue: DatabaseValue let codingPath: [CodingKey] diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index 0c9ec1518..5682ca7c9 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -1,3 +1,5 @@ +import Foundation + private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { let encode: (DatabaseValue) -> Void