From cdc78054719f492deca4f4fdb11e72e33f71d482 Mon Sep 17 00:00:00 2001 From: Scott Berrevoets Date: Wed, 11 Aug 2021 23:41:02 -0700 Subject: [PATCH 01/26] Add option for converting snake case This adds an option to convert column names from snake case to camel case, similar to how JSONDecoder works. In fact, the implementation here is largely based on JSONDecoder's implementation. --- GRDB/Record/FetchableRecord+Decodable.swift | 41 ++++---- GRDB/Record/FetchableRecord.swift | 95 +++++++++++++++++++ .../FetchableRecordDecodableTests.swift | 18 ++++ 3 files changed, 136 insertions(+), 18 deletions(-) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index ae96ce03e..e7343d99b 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -14,7 +14,7 @@ class RowDecoder { init() { } func decode(_ type: T.Type = T.self, from row: Row) throws -> T { - let decoder = _RowDecoder(row: row, codingPath: []) + let decoder = _RowDecoder(row: row, codingPath: [], keyDecodingStrategy: T.databaseKeyDecodingStrategy) return try T(from: decoder) } } @@ -25,6 +25,7 @@ class RowDecoder { private struct _RowDecoder: Decoder { var row: Row var codingPath: [CodingKey] + var keyDecodingStrategy: DatabaseKeyDecodingStrategy var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { @@ -98,23 +99,27 @@ private struct _RowDecoder: Decoder { // swiftlint:disable comma // swiftlint:disable line_length - func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: key.stringValue) } - func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } // swiftlint:enable line_length // swiftlint:enable comma - + + private func convertedKey(_ key: String) -> String { + decoder.keyDecodingStrategy.convertedKey(key: key) + } + func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable { let row = decoder.row let keyName = key.stringValue @@ -250,7 +255,7 @@ private struct _RowDecoder: Decoder { // Prefer FetchableRecord decoding over Decodable. return type.init(row: row) as! T } else { - let decoder = _RowDecoder(row: row, codingPath: codingPath) + let decoder = _RowDecoder(row: row, codingPath: codingPath, keyDecodingStrategy: .useDefaultKeys) return try T(from: decoder) } } @@ -319,7 +324,7 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { mutating func decode(_ type: T.Type) throws -> T where T: Decodable { defer { currentIndex += 1 } - let decoder = _RowDecoder(row: rows[currentIndex], codingPath: codingPath) + let decoder = _RowDecoder(row: rows[currentIndex], codingPath: codingPath, keyDecodingStrategy: .useDefaultKeys) return try T(from: decoder) } diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 73213ca42..5b8bdb7e5 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -103,6 +103,20 @@ public protocol FetchableRecord { /// var registrationDate: Date // decoded from epoch timestamp /// } static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } + + /// When the FetchableRecord type also adopts the standard Decodable + /// protocol, this property controls the key decoding strategy. + /// + /// Default value is .useDefaultKeys + /// + /// For example: + /// + /// struct Player: FetchableRecord, Decodable { + /// static let databaseDateDecodingStrategy: DatabaseKeyDecodingStrategy = .convertFromSnakeCase + /// + /// var playerID: String // decoded from player_id + /// } + static var databaseKeyDecodingStrategy: DatabaseKeyDecodingStrategy { get } } extension FetchableRecord { @@ -127,6 +141,10 @@ extension FetchableRecord { public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { .deferredToDate } + + public static var databaseKeyDecodingStrategy: DatabaseKeyDecodingStrategy { + .useDefaultKeys + } } extension FetchableRecord { @@ -614,3 +632,80 @@ public enum DatabaseDateDecodingStrategy { /// error, and react accordingly). case custom((DatabaseValue) -> Date?) } + +// MARK: - DatabaseKeyDecodingStrategy + +/// `DatabaseKeyDecodingStrategy` specifies how `FetchableRecord` types that +/// also adopt the standard `Decodable` protocol decode their keys. +/// +/// For example: +/// +/// struct Player: FetchableRecord, Decodable { +/// static let databaseKeyDecodingStrategy = DatabaseKeyDecodingStrategy.convertFromSnakeCase +/// +/// var playerID: Int // decoded from player_id +/// } +public enum DatabaseKeyDecodingStrategy { + /// Uses the original key without applying any transformations + case useDefaultKeys + /// Converts the key from snake case format, e.g. player_id to playerID + case convertFromSnakeCase + + func convertedKey(key: String) -> String { + switch self { + case .useDefaultKeys: + return key + case .convertFromSnakeCase: + return Self.convertToSnakeCase(key) + } + } + + fileprivate static func convertToSnakeCase(_ stringKey: String) -> String { + guard !stringKey.isEmpty else { return stringKey } + + var words: [Range] = [] + // The general idea of this algorithm is to split words on transition from lower to upper case, then on transition of >1 upper case characters to lowercase + // + // myProperty -> my_property + // myURLProperty -> my_url_property + // + // We assume, per Swift naming conventions, that the first character of the key is lowercase. + var wordStart = stringKey.startIndex + var searchRange = stringKey.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital before the lower case character. + let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) + words.append(upperCaseRange.lowerBound.. Date: Thu, 12 Aug 2021 20:08:45 -0700 Subject: [PATCH 02/26] Add support for encoding as well --- .swiftlint.yml | 3 + GRDB.xcodeproj/project.pbxproj | 8 ++ GRDB/Core/Database.swift | 2 - GRDB/Record/EncodableRecord+Encodable.swift | 3 +- GRDB/Record/EncodableRecord.swift | 101 ++++++++++++++++++ GRDB/Record/FetchableRecord+Decodable.swift | 3 +- GRDB/Record/FetchableRecord.swift | 21 ++-- GRDB/Utils/Inflections+English.swift | 1 - .../DatabaseKeyEncodingStrategyTests.swift | 33 ++++++ 9 files changed, 163 insertions(+), 12 deletions(-) create mode 100644 Tests/GRDBTests/DatabaseKeyEncodingStrategyTests.swift diff --git a/.swiftlint.yml b/.swiftlint.yml index 3d7960402..089f47747 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -61,3 +61,6 @@ opt_in_rules: vertical_whitespace: max_empty_lines: 2 + +line_length: + ignores_urls: true diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 4f2018a56..55958f5b6 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -1217,6 +1217,9 @@ C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; + D263F40A26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D263F40926C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift */; }; + D263F40B26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D263F40926C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift */; }; + D263F40C26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D263F40926C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift */; }; DC2393C81ABE35F8003FF113 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; DC3773F919C8CBB3004FCF85 /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; /* End PBXBuildFile section */ @@ -1625,6 +1628,7 @@ AAA4DCFE230F1E0600C74B15 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; AAA4DDD4230F262000C74B15 /* GRDBtvOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBtvOSTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; C96C0F242084A442006B2981 /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; + D263F40926C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseKeyEncodingStrategyTests.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; DC3773F319C8CBB3004FCF85 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -1773,6 +1777,7 @@ children = ( 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, + D263F40926C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift */, 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, @@ -3343,6 +3348,7 @@ 564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */, + D263F40B26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */, 5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 5657AB3A1D108BA9006283EF /* FoundationDataTests.swift in Sources */, 563363D61C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, @@ -3574,6 +3580,7 @@ 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, + D263F40A26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */, 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */, 56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */, @@ -3938,6 +3945,7 @@ AAA4DD99230F262000C74B15 /* DatabaseRegionObservationTests.swift in Sources */, AAA4DD9A230F262000C74B15 /* AssociationParallelDecodableRecordTests.swift in Sources */, AAA4DD9C230F262000C74B15 /* DatabaseErrorTests.swift in Sources */, + D263F40C26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */, AAA4DD9D230F262000C74B15 /* FoundationDateComponentsTests.swift in Sources */, AAA4DD9E230F262000C74B15 /* FoundationDataTests.swift in Sources */, AAA4DD9F230F262000C74B15 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 9a607d73d..63908a0c3 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -319,7 +319,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // // - DatabaseCursorTests.testIssue583() // - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html - // swiftlint:disable:previous line_length let dbPointer = Unmanaged.passUnretained(self).toOpaque() sqlite3_set_authorizer( sqliteConnection, @@ -1294,7 +1293,6 @@ extension Database { // > options and using sqlcipher_export() to migrate the contents and // > schema of the original db into the new one: // > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/ - // swiftlint:disable:previous line_length let code = passphrase.withUnsafeBytes { sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count)) } diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index e61e57e4e..9c844eaa9 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -16,6 +16,7 @@ private class RecordEncoder: Encoder { var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } private var _persistenceContainer: PersistenceContainer var persistenceContainer: PersistenceContainer { _persistenceContainer } + var keyEncodingStrategy: DatabaseKeyEncodingStrategy { Record.databaseKeyEncodingStrategy } init(persistenceContainer: PersistenceContainer) { _persistenceContainer = persistenceContainer @@ -122,7 +123,7 @@ private class RecordEncoder: Encoder { /// Helper methods @inline(__always) fileprivate func persist(_ value: DatabaseValueConvertible?, forKey key: CodingKey) { - _persistenceContainer[key.stringValue] = value + _persistenceContainer[keyEncodingStrategy.convertedKey(key: key.stringValue)] = value } @inline(__always) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 9195b421a..41e388a07 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -117,6 +117,21 @@ public protocol EncodableRecord { /// var uuid: UUID /// } static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get } + + /// When the EncodableRecord type also adopts the standard Encodable + /// protocol, this property controls the key encoding strategy. + /// + /// Default value is .useDefaultKeys + /// + /// For example: + /// + /// struct Player: PersistableProtocol, Encodable { + /// static let databaseKeyEncodingStrategy: DatabaseUUIDEncodingStrategy = .convertToSnakeCase + /// + /// // encoded as player_id + /// var playerID: String + /// } + static var databaseKeyEncodingStrategy: DatabaseKeyEncodingStrategy { get } } extension EncodableRecord { @@ -144,6 +159,10 @@ extension EncodableRecord { public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { .deferredToUUID } + + public static var databaseKeyEncodingStrategy: DatabaseKeyEncodingStrategy { + .useDefaultKeys + } } extension EncodableRecord { @@ -381,3 +400,85 @@ public enum DatabaseUUIDEncodingStrategy { /// Encodes UUIDs as strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" case string } + +/// `DatabaseKeyEncodingStrategy` specifies how `EncodableRecord` types that +/// also adopt the standard `Encodable` protocol encode their keys. +/// +/// For example: +/// +/// struct Player: EncodableProtocol, Encodable { +/// static let databaseKeyEncodingStrategy = DatabaseKeyEncodingStrategy.convertToSnakeCase +/// +/// // encoded as player_id +/// var playerID: String +/// } + +public enum DatabaseKeyEncodingStrategy { + case useDefaultKeys + case convertToSnakeCase + + func convertedKey(key: String) -> String { + switch self { + case .useDefaultKeys: + return key + case .convertToSnakeCase: + return Self.convertToSnakeCase(key) + } + } + + /// This function is taken directly from Apple's open source JSONEncoder. + /// https://github.com/apple/swift-corelibs-foundation/blob/eec4b26deee34edb7664ddd9c1222492a399d122/Sources/Foundation/JSONEncoder.swift#L127 + private static func convertToSnakeCase(_ stringKey: String) -> String { + guard !stringKey.isEmpty else { return stringKey } + + var words: [Range] = [] + // The general idea of this algorithm is to split words on transition from lower to upper case, then on + // transition of >1 upper case characters to lowercase + // + // myProperty -> my_property + // myURLProperty -> my_url_property + // + // We assume, per Swift naming conventions, that the first character of the key is lowercase. + var wordStart = stringKey.startIndex + var searchRange = stringKey.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital before + // the lower case character. + let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) + words.append(upperCaseRange.lowerBound..(_ type: T.Type) throws -> T where T: Decodable { defer { currentIndex += 1 } - let decoder = _RowDecoder(row: rows[currentIndex], codingPath: codingPath, keyDecodingStrategy: .useDefaultKeys) + let decoder = _RowDecoder(row: rows[currentIndex], codingPath: codingPath, + keyDecodingStrategy: .useDefaultKeys) return try T(from: decoder) } diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 5b8bdb7e5..90dc7aa8b 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -656,15 +656,18 @@ public enum DatabaseKeyDecodingStrategy { case .useDefaultKeys: return key case .convertFromSnakeCase: - return Self.convertToSnakeCase(key) + return Self.convertFromSnakeCase(key) } } - fileprivate static func convertToSnakeCase(_ stringKey: String) -> String { + /// This function is taken directly from Apple's open source JSONDecoder. + /// https://github.com/apple/swift-corelibs-foundation/blob/eec4b26deee34edb7664ddd9c1222492a399d122/Sources/Foundation/JSONDecoder.swift#L103 + private static func convertFromSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } var words: [Range] = [] - // The general idea of this algorithm is to split words on transition from lower to upper case, then on transition of >1 upper case characters to lowercase + // The general idea of this algorithm is to split words on transition from lower to upper case, then + // on transition of >1 upper case characters to lowercase // // myProperty -> my_property // myURLProperty -> my_url_property @@ -674,26 +677,30 @@ public enum DatabaseKeyDecodingStrategy { var searchRange = stringKey.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital before the lower case character. + // There was a range of >1 capital letters. Turn those into a word, stopping at the capital + // before the lower case character. let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) words.append(upperCaseRange.lowerBound.. Date: Sat, 14 Aug 2021 21:45:35 -0700 Subject: [PATCH 03/26] Fix name and convert `Decodable`s as well --- GRDB/Record/FetchableRecord+Decodable.swift | 2 +- Tests/GRDBTests/FetchableRecordDecodableTests.swift | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 21bfe42ed..8c14d8dcf 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -154,7 +154,7 @@ private struct _RowDecoder: Decoder { func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { let row = decoder.row - let keyName = key.stringValue + let keyName = convertedKey(key.stringValue) // Column? if let index = row.index(forColumn: keyName) { diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index 832716e9c..6cef685ff 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -763,21 +763,24 @@ extension FetchableRecordDecodableTests { } } - func testJSONKeyEncodingStrategy() throws { + func testJSONKeyDecodingStrategy() throws { struct Record: FetchableRecord, Decodable { static let databaseKeyDecodingStrategy: DatabaseKeyDecodingStrategy = .convertFromSnakeCase let recordID: Int let recordName: String + let recordDate: Date } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let record = try Record.fetchOne(db, sql: "SELECT ? AS record_id, ? AS record_name", arguments: [ + let record = try Record.fetchOne(db, sql: "SELECT ? AS record_id, ? AS record_name, ? as record_date", arguments: [ 1, "test1", + "1970-01-01 00:02:08.000", ])! XCTAssertEqual(record.recordID, 1) XCTAssertEqual(record.recordName, "test1") + XCTAssertEqual(record.recordDate.timeIntervalSince1970, 128) } } } From 987b8a48e5ac92c050c18d0325fe99a49c157bd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 28 Aug 2021 15:41:12 +0200 Subject: [PATCH 04/26] Key coding strategies transform keys into columns They are not String transformers --- GRDB/Record/EncodableRecord+Encodable.swift | 6 ++-- GRDB/Record/EncodableRecord.swift | 25 +++++++------- GRDB/Record/FetchableRecord+Decodable.swift | 38 ++++++++++----------- GRDB/Record/FetchableRecord.swift | 24 ++++++------- 4 files changed, 46 insertions(+), 47 deletions(-) diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index 9c844eaa9..7b55fc418 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -123,7 +123,7 @@ private class RecordEncoder: Encoder { /// Helper methods @inline(__always) fileprivate func persist(_ value: DatabaseValueConvertible?, forKey key: CodingKey) { - _persistenceContainer[keyEncodingStrategy.convertedKey(key: key.stringValue)] = value + _persistenceContainer[keyEncodingStrategy.column(forKey: key)] = value } @inline(__always) @@ -150,9 +150,9 @@ private class RecordEncoder: Encoder { } catch is JSONRequiredError { // Encode to JSON try autoreleasepool { - + let jsonData = try Record.databaseJSONEncoder(for: key.stringValue).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 diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 41e388a07..62ec57a01 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -117,7 +117,7 @@ public protocol EncodableRecord { /// var uuid: UUID /// } static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get } - + /// When the EncodableRecord type also adopts the standard Encodable /// protocol, this property controls the key encoding strategy. /// @@ -159,7 +159,7 @@ extension EncodableRecord { public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { .deferredToUUID } - + public static var databaseKeyEncodingStrategy: DatabaseKeyEncodingStrategy { .useDefaultKeys } @@ -412,25 +412,24 @@ public enum DatabaseUUIDEncodingStrategy { /// // encoded as player_id /// var playerID: String /// } - public enum DatabaseKeyEncodingStrategy { case useDefaultKeys case convertToSnakeCase - - func convertedKey(key: String) -> String { + + func column(forKey key: CodingKey) -> String { switch self { case .useDefaultKeys: - return key + return key.stringValue case .convertToSnakeCase: - return Self.convertToSnakeCase(key) + return Self.convertToSnakeCase(key.stringValue) } } - + /// This function is taken directly from Apple's open source JSONEncoder. /// https://github.com/apple/swift-corelibs-foundation/blob/eec4b26deee34edb7664ddd9c1222492a399d122/Sources/Foundation/JSONEncoder.swift#L127 private static func convertToSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } - + var words: [Range] = [] // The general idea of this algorithm is to split words on transition from lower to upper case, then on // transition of >1 upper case characters to lowercase @@ -441,13 +440,13 @@ public enum DatabaseKeyEncodingStrategy { // We assume, per Swift naming conventions, that the first character of the key is lowercase. var wordStart = stringKey.startIndex var searchRange = stringKey.index(after: wordStart)..: Decoder { // swiftlint:disable comma // swiftlint:disable line_length - func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } - func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: convertedKey(key.stringValue)) } + func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: column(forKey: key)) } // swiftlint:enable line_length // swiftlint:enable comma - - private func convertedKey(_ key: String) -> String { - decoder.keyDecodingStrategy.convertedKey(key: key) + + private func column(forKey key: Key) -> String { + decoder.keyDecodingStrategy.column(forKey: key) } - + func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable { let row = decoder.row let keyName = key.stringValue @@ -154,7 +154,7 @@ private struct _RowDecoder: Decoder { func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { let row = decoder.row - let keyName = convertedKey(key.stringValue) + let keyName = column(forKey: key) // Column? if let index = row.index(forColumn: keyName) { diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 90dc7aa8b..94d669f90 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -103,7 +103,7 @@ public protocol FetchableRecord { /// var registrationDate: Date // decoded from epoch timestamp /// } static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } - + /// When the FetchableRecord type also adopts the standard Decodable /// protocol, this property controls the key decoding strategy. /// @@ -141,7 +141,7 @@ extension FetchableRecord { public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { .deferredToDate } - + public static var databaseKeyDecodingStrategy: DatabaseKeyDecodingStrategy { .useDefaultKeys } @@ -650,21 +650,21 @@ public enum DatabaseKeyDecodingStrategy { case useDefaultKeys /// Converts the key from snake case format, e.g. player_id to playerID case convertFromSnakeCase - - func convertedKey(key: String) -> String { + + func column(forKey key: CodingKey) -> String { switch self { case .useDefaultKeys: - return key + return key.stringValue case .convertFromSnakeCase: - return Self.convertFromSnakeCase(key) + return Self.convertFromSnakeCase(key.stringValue) } } - + /// This function is taken directly from Apple's open source JSONDecoder. /// https://github.com/apple/swift-corelibs-foundation/blob/eec4b26deee34edb7664ddd9c1222492a399d122/Sources/Foundation/JSONDecoder.swift#L103 private static func convertFromSnakeCase(_ stringKey: String) -> String { guard !stringKey.isEmpty else { return stringKey } - + var words: [Range] = [] // The general idea of this algorithm is to split words on transition from lower to upper case, then // on transition of >1 upper case characters to lowercase @@ -675,13 +675,13 @@ public enum DatabaseKeyDecodingStrategy { // We assume, per Swift naming conventions, that the first character of the key is lowercase. var wordStart = stringKey.startIndex var searchRange = stringKey.index(after: wordStart).. Date: Sat, 28 Aug 2021 15:46:44 +0200 Subject: [PATCH 05/26] Documentation Doc of cases is copied from JSONDecoder.KeyDecodingStrategy and JSONEncoder.KeyEncodingStrategy --- GRDB/Record/EncodableRecord.swift | 8 ++++++-- GRDB/Record/FetchableRecord.swift | 11 +++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 62ec57a01..1c224f982 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -402,18 +402,22 @@ public enum DatabaseUUIDEncodingStrategy { } /// `DatabaseKeyEncodingStrategy` specifies how `EncodableRecord` types that -/// also adopt the standard `Encodable` protocol encode their keys. +/// also adopt the standard `Encodable` protocol encode their coding keys into +/// database columns. /// /// For example: /// /// struct Player: EncodableProtocol, Encodable { /// static let databaseKeyEncodingStrategy = DatabaseKeyEncodingStrategy.convertToSnakeCase /// -/// // encoded as player_id +/// // Encoded in the player_id column /// var playerID: String /// } public enum DatabaseKeyEncodingStrategy { + /// A key encoding strategy that doesn’t change key names during encoding. case useDefaultKeys + + /// A key encoding strategy that converts camel-case keys to snake-case keys. case convertToSnakeCase func column(forKey key: CodingKey) -> String { diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 94d669f90..4fa5eaf8a 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -636,19 +636,22 @@ public enum DatabaseDateDecodingStrategy { // MARK: - DatabaseKeyDecodingStrategy /// `DatabaseKeyDecodingStrategy` specifies how `FetchableRecord` types that -/// also adopt the standard `Decodable` protocol decode their keys. +/// also adopt the standard `Decodable` protocol look for the database colums +/// that match their coding keys. /// /// For example: /// /// struct Player: FetchableRecord, Decodable { /// static let databaseKeyDecodingStrategy = DatabaseKeyDecodingStrategy.convertFromSnakeCase /// -/// var playerID: Int // decoded from player_id +/// // Decoded from the player_id column +/// var playerID: Int /// } public enum DatabaseKeyDecodingStrategy { - /// Uses the original key without applying any transformations + /// A key decoding strategy that doesn’t change key names during decoding. case useDefaultKeys - /// Converts the key from snake case format, e.g. player_id to playerID + + /// A key decoding strategy that converts snake-case keys to camel-case keys. case convertFromSnakeCase func column(forKey key: CodingKey) -> String { From 5f23d9790317f7459dfa9b973a17ee2e3ec2e4b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 28 Aug 2021 15:50:34 +0200 Subject: [PATCH 06/26] Add the custom strategies --- GRDB/Record/EncodableRecord.swift | 5 +++++ GRDB/Record/FetchableRecord.swift | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 1c224f982..bf1f22b0e 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -420,12 +420,17 @@ public enum DatabaseKeyEncodingStrategy { /// A key encoding strategy that converts camel-case keys to snake-case keys. case convertToSnakeCase + /// A key encoding strategy defined by the closure you supply. + case custom((CodingKey) -> String) + func column(forKey key: CodingKey) -> String { switch self { case .useDefaultKeys: return key.stringValue case .convertToSnakeCase: return Self.convertToSnakeCase(key.stringValue) + case let .custom(column): + return column(key) } } diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 4fa5eaf8a..4f15b53c7 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -654,12 +654,17 @@ public enum DatabaseKeyDecodingStrategy { /// A key decoding strategy that converts snake-case keys to camel-case keys. case convertFromSnakeCase + /// A key decoding strategy defined by the closure you supply. + case custom((CodingKey) -> String) + func column(forKey key: CodingKey) -> String { switch self { case .useDefaultKeys: return key.stringValue case .convertFromSnakeCase: return Self.convertFromSnakeCase(key.stringValue) + case let .custom(column): + return column(key) } } From 06763e47d2e57dec4719f216aa2825b11845fcbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 28 Aug 2021 16:05:41 +0200 Subject: [PATCH 07/26] Share convertToSnakeCase() --- GRDB/Record/EncodableRecord.swift | 58 +----------------------------- GRDB/Record/FetchableRecord.swift | 58 +----------------------------- GRDB/Utils/Inflections.swift | 60 +++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 114 deletions(-) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index bf1f22b0e..aa00ffae8 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -428,65 +428,9 @@ public enum DatabaseKeyEncodingStrategy { case .useDefaultKeys: return key.stringValue case .convertToSnakeCase: - return Self.convertToSnakeCase(key.stringValue) + return key.stringValue.convertToSnakeCase() case let .custom(column): return column(key) } } - - /// This function is taken directly from Apple's open source JSONEncoder. - /// https://github.com/apple/swift-corelibs-foundation/blob/eec4b26deee34edb7664ddd9c1222492a399d122/Sources/Foundation/JSONEncoder.swift#L127 - private static func convertToSnakeCase(_ stringKey: String) -> String { - guard !stringKey.isEmpty else { return stringKey } - - var words: [Range] = [] - // The general idea of this algorithm is to split words on transition from lower to upper case, then on - // transition of >1 upper case characters to lowercase - // - // myProperty -> my_property - // myURLProperty -> my_url_property - // - // We assume, per Swift naming conventions, that the first character of the key is lowercase. - var wordStart = stringKey.startIndex - var searchRange = stringKey.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital before - // the lower case character. - let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) - words.append(upperCaseRange.lowerBound.. String { - guard !stringKey.isEmpty else { return stringKey } - - var words: [Range] = [] - // The general idea of this algorithm is to split words on transition from lower to upper case, then - // on transition of >1 upper case characters to lowercase - // - // myProperty -> my_property - // myURLProperty -> my_url_property - // - // We assume, per Swift naming conventions, that the first character of the key is lowercase. - var wordStart = stringKey.startIndex - var searchRange = stringKey.index(after: wordStart)..1 capital letters. Turn those into a word, stopping at the capital - // before the lower case character. - let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) - words.append(upperCaseRange.lowerBound.. String { + guard !isEmpty else { return self } + + var words: [Range] = [] + // The general idea of this algorithm is to split words on transition + // from lower to upper case, then on transition of >1 upper case + // characters to lowercase + // + // myProperty -> my_property + // myURLProperty -> my_url_property + // + // We assume, per Swift naming conventions, that the first character of + // the key is lowercase. + var wordStart = startIndex + var searchRange = index(after: wordStart)..1 capital letters. Turn those into a + // word, stopping at the capital before the lower case character. + let beforeLowerIndex = index(before: lowerCaseRange.lowerBound) + words.append(upperCaseRange.lowerBound.. Date: Sat, 28 Aug 2021 16:24:53 +0200 Subject: [PATCH 08/26] Make it clear that strategies apply to columns only ...and not to row scopes or prefetched records --- GRDB.xcodeproj/project.pbxproj | 16 ++++++++-------- GRDB/Record/EncodableRecord+Encodable.swift | 2 +- GRDB/Record/EncodableRecord.swift | 12 ++++++------ GRDB/Record/FetchableRecord+Decodable.swift | 4 ++-- GRDB/Record/FetchableRecord.swift | 14 +++++++------- ...=> DatabaseColumnEncodingStrategyTests.swift} | 6 +++--- .../FetchableRecordDecodableTests.swift | 2 +- 7 files changed, 28 insertions(+), 28 deletions(-) rename Tests/GRDBTests/{DatabaseKeyEncodingStrategyTests.swift => DatabaseColumnEncodingStrategyTests.swift} (78%) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 55958f5b6..d95347493 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -1217,9 +1217,9 @@ C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; - D263F40A26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D263F40926C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift */; }; - D263F40B26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D263F40926C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift */; }; - D263F40C26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D263F40926C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift */; }; + D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */; }; + D263F40B26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */; }; + D263F40C26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */; }; DC2393C81ABE35F8003FF113 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; DC3773F919C8CBB3004FCF85 /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; /* End PBXBuildFile section */ @@ -1628,7 +1628,7 @@ AAA4DCFE230F1E0600C74B15 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; AAA4DDD4230F262000C74B15 /* GRDBtvOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBtvOSTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; C96C0F242084A442006B2981 /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; - D263F40926C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseKeyEncodingStrategyTests.swift; sourceTree = ""; }; + D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; DC3773F319C8CBB3004FCF85 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -1775,9 +1775,9 @@ 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( + D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */, 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, - D263F40926C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift */, 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */, 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, @@ -3348,7 +3348,7 @@ 564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */, - D263F40B26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */, + D263F40B26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */, 5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 5657AB3A1D108BA9006283EF /* FoundationDataTests.swift in Sources */, 563363D61C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, @@ -3580,7 +3580,7 @@ 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, - D263F40A26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */, + D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */, 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */, 56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */, @@ -3945,7 +3945,7 @@ AAA4DD99230F262000C74B15 /* DatabaseRegionObservationTests.swift in Sources */, AAA4DD9A230F262000C74B15 /* AssociationParallelDecodableRecordTests.swift in Sources */, AAA4DD9C230F262000C74B15 /* DatabaseErrorTests.swift in Sources */, - D263F40C26C613090038B07F /* DatabaseKeyEncodingStrategyTests.swift in Sources */, + D263F40C26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */, AAA4DD9D230F262000C74B15 /* FoundationDateComponentsTests.swift in Sources */, AAA4DD9E230F262000C74B15 /* FoundationDataTests.swift in Sources */, AAA4DD9F230F262000C74B15 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index 7b55fc418..d71a37ff3 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -16,7 +16,7 @@ private class RecordEncoder: Encoder { var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } private var _persistenceContainer: PersistenceContainer var persistenceContainer: PersistenceContainer { _persistenceContainer } - var keyEncodingStrategy: DatabaseKeyEncodingStrategy { Record.databaseKeyEncodingStrategy } + var keyEncodingStrategy: DatabaseColumnEncodingStrategy { Record.databaseColumnEncodingStrategy } init(persistenceContainer: PersistenceContainer) { _persistenceContainer = persistenceContainer diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index aa00ffae8..6d63ce23a 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -126,12 +126,12 @@ public protocol EncodableRecord { /// For example: /// /// struct Player: PersistableProtocol, Encodable { - /// static let databaseKeyEncodingStrategy: DatabaseUUIDEncodingStrategy = .convertToSnakeCase + /// static let databaseColumnEncodingStrategy: DatabaseUUIDEncodingStrategy = .convertToSnakeCase /// /// // encoded as player_id /// var playerID: String /// } - static var databaseKeyEncodingStrategy: DatabaseKeyEncodingStrategy { get } + static var databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy { get } } extension EncodableRecord { @@ -160,7 +160,7 @@ extension EncodableRecord { .deferredToUUID } - public static var databaseKeyEncodingStrategy: DatabaseKeyEncodingStrategy { + public static var databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy { .useDefaultKeys } } @@ -401,19 +401,19 @@ public enum DatabaseUUIDEncodingStrategy { case string } -/// `DatabaseKeyEncodingStrategy` specifies how `EncodableRecord` types that +/// `DatabaseColumnEncodingStrategy` specifies how `EncodableRecord` types that /// also adopt the standard `Encodable` protocol encode their coding keys into /// database columns. /// /// For example: /// /// struct Player: EncodableProtocol, Encodable { -/// static let databaseKeyEncodingStrategy = DatabaseKeyEncodingStrategy.convertToSnakeCase +/// static let databaseColumnEncodingStrategy = DatabaseColumnEncodingStrategy.convertToSnakeCase /// /// // Encoded in the player_id column /// var playerID: String /// } -public enum DatabaseKeyEncodingStrategy { +public enum DatabaseColumnEncodingStrategy { /// A key encoding strategy that doesn’t change key names during encoding. case useDefaultKeys diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index d5788d418..6da23e8eb 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -14,7 +14,7 @@ class RowDecoder { init() { } func decode(_ type: T.Type = T.self, from row: Row) throws -> T { - let decoder = _RowDecoder(row: row, codingPath: [], keyDecodingStrategy: T.databaseKeyDecodingStrategy) + let decoder = _RowDecoder(row: row, codingPath: [], keyDecodingStrategy: T.databaseColumnDecodingStrategy) return try T(from: decoder) } } @@ -25,7 +25,7 @@ class RowDecoder { private struct _RowDecoder: Decoder { var row: Row var codingPath: [CodingKey] - var keyDecodingStrategy: DatabaseKeyDecodingStrategy + var keyDecodingStrategy: DatabaseColumnDecodingStrategy var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 58b922dac..3da5cb5b7 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -112,11 +112,11 @@ public protocol FetchableRecord { /// For example: /// /// struct Player: FetchableRecord, Decodable { - /// static let databaseDateDecodingStrategy: DatabaseKeyDecodingStrategy = .convertFromSnakeCase + /// static let databaseDateDecodingStrategy: DatabaseColumnDecodingStrategy = .convertFromSnakeCase /// /// var playerID: String // decoded from player_id /// } - static var databaseKeyDecodingStrategy: DatabaseKeyDecodingStrategy { get } + static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { get } } extension FetchableRecord { @@ -142,7 +142,7 @@ extension FetchableRecord { .deferredToDate } - public static var databaseKeyDecodingStrategy: DatabaseKeyDecodingStrategy { + public static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { .useDefaultKeys } } @@ -633,21 +633,21 @@ public enum DatabaseDateDecodingStrategy { case custom((DatabaseValue) -> Date?) } -// MARK: - DatabaseKeyDecodingStrategy +// MARK: - DatabaseColumnDecodingStrategy -/// `DatabaseKeyDecodingStrategy` specifies how `FetchableRecord` types that +/// `DatabaseColumnDecodingStrategy` specifies how `FetchableRecord` types that /// also adopt the standard `Decodable` protocol look for the database colums /// that match their coding keys. /// /// For example: /// /// struct Player: FetchableRecord, Decodable { -/// static let databaseKeyDecodingStrategy = DatabaseKeyDecodingStrategy.convertFromSnakeCase +/// static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.convertFromSnakeCase /// /// // Decoded from the player_id column /// var playerID: Int /// } -public enum DatabaseKeyDecodingStrategy { +public enum DatabaseColumnDecodingStrategy { /// A key decoding strategy that doesn’t change key names during decoding. case useDefaultKeys diff --git a/Tests/GRDBTests/DatabaseKeyEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseColumnEncodingStrategyTests.swift similarity index 78% rename from Tests/GRDBTests/DatabaseKeyEncodingStrategyTests.swift rename to Tests/GRDBTests/DatabaseColumnEncodingStrategyTests.swift index 7cc8b3d9b..bc8e8e818 100644 --- a/Tests/GRDBTests/DatabaseKeyEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseColumnEncodingStrategyTests.swift @@ -3,16 +3,16 @@ import Foundation @testable import GRDB private struct UseDefaultKeysRecord: PersistableRecord, Encodable { - static var databaseKeyEncodingStrategy: DatabaseKeyEncodingStrategy { .useDefaultKeys } + static var databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy { .useDefaultKeys } var recordID: String } private struct ConvertToSnakeCaseRecord: PersistableRecord, Encodable { - static var databaseKeyEncodingStrategy: DatabaseKeyEncodingStrategy { .convertToSnakeCase } + static var databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy { .convertToSnakeCase } var recordID: String } -class DatabaseKeyEncodingStrategyTests: GRDBTestCase { +class DatabaseColumnEncodingStrategyTests: GRDBTestCase { func testUseDefaultKeys() { let record = UseDefaultKeysRecord(recordID: "test") diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index 6cef685ff..7c32c5c58 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -765,7 +765,7 @@ extension FetchableRecordDecodableTests { func testJSONKeyDecodingStrategy() throws { struct Record: FetchableRecord, Decodable { - static let databaseKeyDecodingStrategy: DatabaseKeyDecodingStrategy = .convertFromSnakeCase + static let databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy = .convertFromSnakeCase let recordID: Int let recordName: String let recordDate: Date From 0914b56c4170f31f6e97fe9079d455badc395749 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 08:31:36 +0200 Subject: [PATCH 09/26] Add mark --- GRDB/Record/EncodableRecord.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 6d63ce23a..44c61a38c 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -401,6 +401,8 @@ public enum DatabaseUUIDEncodingStrategy { case string } +// MARK: - DatabaseColumnEncodingStrategy + /// `DatabaseColumnEncodingStrategy` specifies how `EncodableRecord` types that /// also adopt the standard `Encodable` protocol encode their coding keys into /// database columns. From 8aa640f84b35e0c7420cc18209ea5e9402f0715e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 08:41:46 +0200 Subject: [PATCH 10/26] Documentation: Column Names Coding Strategies --- README.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/README.md b/README.md index ae8436b04..9247a5968 100644 --- a/README.md +++ b/README.md @@ -3018,6 +3018,7 @@ Codable records encode and decode their properties according to their own implem For more information about Codable records, see: - [JSON Columns] +- [Column Names Coding Strategies] - [Date and UUID Coding Strategies] - [The userInfo Dictionary] - [Tip: Derive Columns from Coding Keys](#tip-derive-columns-from-coding-keys) @@ -3074,6 +3075,25 @@ protocol EncodableRecord { > :bulb: **Tip**: Make sure you set the JSONEncoder `sortedKeys` option, available from iOS 11.0+, macOS 10.13+, tvOS 9.0+ and watchOS 4.0+. This option makes sure that the JSON output is stable. This stability is required for [Record Comparison] to work as expected, and database observation tools such as [ValueObservation] to accurately recognize changed records. +### Column Names Coding Strategies + +By default, [Codable Records] stores their values into database columns that match their coding keys: the `teamID` property is stored into the `teamID` column. + +This behavior can be overridden, so that you can, for example, store the `teamID` property into the `team_id` column: + +```swift +protocol FetchableRecord { + static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { get } +} + +protocol EncodableRecord { + static var databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy { get } +} +``` + +See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.10/Enums/DatabaseColumnDecodingStrategy.html), [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.10/Enums/DatabaseColumnEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.10/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. + + ### Date and UUID Coding Strategies By default, [Codable Records] encode and decode their Date and UUID properties as described in the general [Date and DateComponents](#date-and-datecomponents) and [UUID](#uuid) chapters. @@ -3432,6 +3452,7 @@ GRDB records come with many default behaviors, that are designed to fit most sit [Codable Records] have a few extra options: - [JSON Columns]: control the format of JSON columns. +- [Column Names Coding Strategies]: control how coding keys are turned into column names - [Date and UUID Coding Strategies]: control the format of Date and UUID properties in your Codable records. - [The userInfo Dictionary]: adapt your Codable implementation for the database. @@ -8472,6 +8493,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Common Table Expressions]: Documentation/CommonTableExpressions.md [Conflict Resolution]: #conflict-resolution [Customizing the Persistence Methods]: #customizing-the-persistence-methods +[Column Names Coding Strategies]: #column-names-coding-strategies [Date and UUID Coding Strategies]: #date-and-uuid-coding-strategies [Fetching from Requests]: #fetching-from-requests [Full-Text Search]: Documentation/FullTextSearch.md From 5a04183baf146857e67bd59592843622004fb71d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 08:54:41 +0200 Subject: [PATCH 11/26] Fix test name --- Tests/GRDBTests/FetchableRecordDecodableTests.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index 0380e948f..09eeadcdc 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -762,22 +762,22 @@ extension FetchableRecordDecodableTests { XCTAssertEqual(record.optionalDates[1]!.timeIntervalSince1970, 128) } } - - func testJSONKeyDecodingStrategy() throws { + + func testDatabaseColumnDecodingStrategy() throws { struct Record: FetchableRecord, Decodable { static let databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy = .convertFromSnakeCase let recordID: Int let recordName: String let recordDate: Date } - + let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let record = try Record.fetchOne(db, sql: "SELECT ? AS record_id, ? AS record_name, ? as record_date", arguments: [ 1, "test1", "1970-01-01 00:02:08.000", - ])! + ])! XCTAssertEqual(record.recordID, 1) XCTAssertEqual(record.recordName, "test1") XCTAssertEqual(record.recordDate.timeIntervalSince1970, 128) From d5676309669d587b2c85433f1b4398e25114bc69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 08:55:39 +0200 Subject: [PATCH 12/26] Column decoding strategy only applies to columns --- GRDB/Record/FetchableRecord+Decodable.swift | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 9376987c4..d729b2d54 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -154,10 +154,9 @@ private struct _RowDecoder: Decoder { func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { let row = decoder.row - let keyName = column(forKey: key) // Column? - if let index = row.index(forColumn: keyName) { + if let index = row.index(forColumn: column(forKey: key)) { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { @@ -172,12 +171,12 @@ private struct _RowDecoder: Decoder { } // Scope? - if let scopedRow = row.scopesTree[keyName] { + if let scopedRow = row.scopesTree[key.stringValue] { return try decode(type, fromRow: scopedRow, codingPath: codingPath + [key]) } // Prefetched Rows? - if let prefetchedRows = row.prefetchedRows[keyName] { + if let prefetchedRows = row.prefetchedRows[key.stringValue] { let decoder = PrefetchedRowsDecoder(rows: prefetchedRows, codingPath: codingPath) return try T(from: decoder) } From 8846ea3c25dc0c9e1fbf08b29644fafa42aea322 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 09:40:16 +0200 Subject: [PATCH 13/26] Failing test --- ...ciationBelongsToFetchableRecordTests.swift | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift index 17fbc3373..00eafb027 100644 --- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -111,4 +111,86 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase { XCTAssertNil(players[1].teamId) XCTAssertEqual(players[1].name, "Barbara") } + + func testIncludingRequired_ColumnDecodingStrategy() throws { + struct XTeam: Decodable, FetchableRecord, TableRecord { + static let databaseTableName = "teams" + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { key in + String(key.stringValue.dropFirst()) + } + var xid: Int64 + var xname: String + } + + struct XPlayer: Decodable, FetchableRecord, TableRecord { + static let databaseTableName = "players" + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { key in + String(key.stringValue.dropFirst()) + } + static let xteam = belongsTo(XTeam.self, key: "xteam") + var xid: Int64 + var xteamId: Int64? + var xname: String + } + + struct XPlayerWithRequiredTeam: Decodable, FetchableRecord { + var xplayer: XPlayer + var xteam: XTeam + } + + let dbQueue = try makeDatabaseQueue() + let request = XPlayer + .including(required: XPlayer.xteam) + .asRequest(of: XPlayerWithRequiredTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records[0].xplayer.xid, 1) + XCTAssertEqual(records[0].xplayer.xteamId, 1) + XCTAssertEqual(records[0].xplayer.xname, "Arthur") + XCTAssertEqual(records[0].xteam.xid, 1) + XCTAssertEqual(records[0].xteam.xname, "Reds") + } + + func testIncludingOptional_ColumnDecodingStrategy() throws { + struct XTeam: Decodable, FetchableRecord, TableRecord { + static let databaseTableName = "teams" + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { key in + String(key.stringValue.dropFirst()) + } + var xid: Int64 + var xname: String + } + + struct XPlayer: Decodable, FetchableRecord, TableRecord { + static let databaseTableName = "players" + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { key in + String(key.stringValue.dropFirst()) + } + static let xteam = belongsTo(XTeam.self, key: "xteam") + var xid: Int64 + var xteamId: Int64? + var xname: String + } + + struct XPlayerWithOptionalTeam: Decodable, FetchableRecord { + var xplayer: XPlayer + var xteam: XTeam? + } + + let dbQueue = try makeDatabaseQueue() + let request = XPlayer + .including(optional: XPlayer.xteam) + .asRequest(of: XPlayerWithOptionalTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].xplayer.xid, 1) + XCTAssertEqual(records[0].xplayer.xteamId, 1) + XCTAssertEqual(records[0].xplayer.xname, "Arthur") + XCTAssertEqual(records[0].xteam!.xid, 1) + XCTAssertEqual(records[0].xteam!.xname, "Reds") + XCTAssertEqual(records[1].xplayer.xid, 2) + XCTAssertNil(records[1].xplayer.xteamId) + XCTAssertEqual(records[1].xplayer.xname, "Barbara") + XCTAssertNil(records[1].xteam) + } } From e60a31f401a7c2d4a436b908db0ec119a133896e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 09:40:32 +0200 Subject: [PATCH 14/26] Fix failing test --- GRDB/Record/FetchableRecord+Decodable.swift | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index d729b2d54..dc19f97be 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -85,7 +85,7 @@ private struct _RowDecoder: Decoder { func contains(_ key: Key) -> Bool { let row = decoder.row - return row.hasColumn(key.stringValue) + return row.hasColumn(column(forKey: key)) || (row.scopesTree[key.stringValue] != nil) || (row.prefetchedRows[key.stringValue] != nil) } @@ -94,7 +94,7 @@ private struct _RowDecoder: Decoder { // Nil is only possible for columns and scopes (optional // associations), not for prefetched rows. let row = decoder.row - return row[key.stringValue] == nil && (row.scopesTree[key.stringValue] == nil) + return row[column(forKey: key)] == nil && (row.scopesTree[key.stringValue] == nil) } // swiftlint:disable comma @@ -122,10 +122,9 @@ private struct _RowDecoder: Decoder { func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable { let row = decoder.row - let keyName = key.stringValue // Column? - if let index = row.index(forColumn: keyName) { + if let index = row.index(forColumn: column(forKey: key)) { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { @@ -144,7 +143,7 @@ private struct _RowDecoder: Decoder { } // Scope? (beware left joins: check if scoped row contains non-null values) - if let scopedRow = row.scopesTree[keyName], scopedRow.containsNonNullValue { + if let scopedRow = row.scopesTree[key.stringValue], scopedRow.containsNonNullValue { return try decode(type, fromRow: scopedRow, codingPath: codingPath + [key]) } @@ -321,8 +320,10 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { mutating func decode(_ type: T.Type) throws -> T where T: Decodable { defer { currentIndex += 1 } - let decoder = _RowDecoder(row: rows[currentIndex], codingPath: codingPath, - keyDecodingStrategy: .useDefaultKeys) + let decoder = _RowDecoder( + row: rows[currentIndex], + codingPath: codingPath, + keyDecodingStrategy: .useDefaultKeys) return try T(from: decoder) } From 76f8b5547fc2e4372b124331a408cff47588253c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 09:51:24 +0200 Subject: [PATCH 15/26] Failing test --- ...ciationPrefetchingCodableRecordTests.swift | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index 3c800ccd0..b74e2f660 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -1223,4 +1223,59 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { ]) } } + + func testIncludingAllHasMany_ColumnDecodingStrategy() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + do { + struct XA: TableRecord, FetchableRecord, Decodable, Equatable { + static let databaseTableName = "a" + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { key in + String(key.stringValue.dropFirst()) + } + var xcola1: Int64 + var xcola2: String + } + + struct XB: TableRecord, FetchableRecord, Decodable, Equatable, Hashable { + static let databaseTableName = "b" + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { key in + String(key.stringValue.dropFirst()) + } + var xcolb1: Int64 + var xcolb2: Int64? + var xcolb3: String + } + + struct XRecord: FetchableRecord, Decodable, Equatable { + var xa: XA + var xbs: [XB] + } + + let request = XA + .including(all: XA + .hasMany(XB.self, key: "xbs") + .orderByPrimaryKey()) + .orderByPrimaryKey() + + let records = try XRecord.fetchAll(db, request) + XCTAssertEqual(records, [ + XRecord( + xa: XA(row: ["cola1": 1, "cola2": "a1"]), + xbs: [ + XB(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + XB(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ]), + XRecord( + xa: XA(row: ["cola1": 2, "cola2": "a2"]), + xbs: [ + XB(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + XRecord( + xa: XA(row: ["cola1": 3, "cola2": "a3"]), + xbs: []), + ]) + } + } + } } From 6f024373b3f8af5e6aa4548c6e474a7e1f885403 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 09:51:31 +0200 Subject: [PATCH 16/26] Fix failing test --- GRDB/Record/FetchableRecord+Decodable.swift | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index dc19f97be..59f1b799a 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -320,10 +320,16 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { mutating func decode(_ type: T.Type) throws -> T where T: Decodable { defer { currentIndex += 1 } + let keyDecodingStrategy: DatabaseColumnDecodingStrategy + if let type = T.self as? FetchableRecord.Type { + keyDecodingStrategy = type.databaseColumnDecodingStrategy + } else { + keyDecodingStrategy = .useDefaultKeys + } let decoder = _RowDecoder( row: rows[currentIndex], codingPath: codingPath, - keyDecodingStrategy: .useDefaultKeys) + keyDecodingStrategy: keyDecodingStrategy) return try T(from: decoder) } From 427a00582f41e159c79b6eed79bc1361c8de6d49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 09:55:06 +0200 Subject: [PATCH 17/26] Rename keyDecodingStrategy to columnDecodingStrategy --- GRDB/Record/FetchableRecord+Decodable.swift | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 59f1b799a..3e72c3db7 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -14,7 +14,7 @@ class RowDecoder { init() { } func decode(_ type: T.Type = T.self, from row: Row) throws -> T { - let decoder = _RowDecoder(row: row, codingPath: [], keyDecodingStrategy: T.databaseColumnDecodingStrategy) + let decoder = _RowDecoder(row: row, codingPath: [], columnDecodingStrategy: T.databaseColumnDecodingStrategy) return try T(from: decoder) } } @@ -25,7 +25,7 @@ class RowDecoder { private struct _RowDecoder: Decoder { var row: Row var codingPath: [CodingKey] - var keyDecodingStrategy: DatabaseColumnDecodingStrategy + var columnDecodingStrategy: DatabaseColumnDecodingStrategy var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { @@ -117,7 +117,7 @@ private struct _RowDecoder: Decoder { // swiftlint:enable comma private func column(forKey key: Key) -> String { - decoder.keyDecodingStrategy.column(forKey: key) + decoder.columnDecodingStrategy.column(forKey: key) } func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable { @@ -252,7 +252,7 @@ private struct _RowDecoder: Decoder { // Prefer FetchableRecord decoding over Decodable. return type.init(row: row) as! T } else { - let decoder = _RowDecoder(row: row, codingPath: codingPath, keyDecodingStrategy: .useDefaultKeys) + let decoder = _RowDecoder(row: row, codingPath: codingPath, columnDecodingStrategy: .useDefaultKeys) return try T(from: decoder) } } @@ -320,16 +320,18 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { mutating func decode(_ type: T.Type) throws -> T where T: Decodable { defer { currentIndex += 1 } - let keyDecodingStrategy: DatabaseColumnDecodingStrategy + + let columnDecodingStrategy: DatabaseColumnDecodingStrategy if let type = T.self as? FetchableRecord.Type { - keyDecodingStrategy = type.databaseColumnDecodingStrategy + columnDecodingStrategy = type.databaseColumnDecodingStrategy } else { - keyDecodingStrategy = .useDefaultKeys + columnDecodingStrategy = .useDefaultKeys } + let decoder = _RowDecoder( row: rows[currentIndex], codingPath: codingPath, - keyDecodingStrategy: keyDecodingStrategy) + columnDecodingStrategy: columnDecodingStrategy) return try T(from: decoder) } From c36aa2bfda6ac8ab057231b810a7b6989708593d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 09:59:49 +0200 Subject: [PATCH 18/26] Fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9247a5968..d4ef263fd 100644 --- a/README.md +++ b/README.md @@ -3077,7 +3077,7 @@ protocol EncodableRecord { ### Column Names Coding Strategies -By default, [Codable Records] stores their values into database columns that match their coding keys: the `teamID` property is stored into the `teamID` column. +By default, [Codable Records] store their values into database columns that match their coding keys: the `teamID` property is stored into the `teamID` column. This behavior can be overridden, so that you can, for example, store the `teamID` property into the `team_id` column: From 86e4adf860aa029f9eb6a663e993d2b2fa430b90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 10:08:08 +0200 Subject: [PATCH 19/26] Spot a design flaw --- GRDB/Record/FetchableRecord+Decodable.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 3e72c3db7..ad6d632d9 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -76,6 +76,7 @@ private struct _RowDecoder: Decoder { } lazy var allKeys: [Key] = { + #warning("TODO: the columns are not decoded with decoder.columnDecodingStrategy") let row = decoder.row return Set(row.columnNames) .union(row.scopesTree.names) From e6e2536f6b5ad7792b99af83e97860478b73063a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 13:52:36 +0200 Subject: [PATCH 20/26] Reverse DatabaseColumnDecodingStrategy It does not convert coding keys to columns, but columns to CodingKeys, exactly as JSONDecoder.KeyDecodingStrategy --- GRDB/Record/EncodableRecord.swift | 67 ++++++++- GRDB/Record/FetchableRecord+Decodable.swift | 135 ++++++++++++++---- GRDB/Record/FetchableRecord.swift | 62 +++++++- GRDB/Utils/Inflections.swift | 60 -------- ...ciationBelongsToFetchableRecordTests.swift | 30 ++-- ...ciationPrefetchingCodableRecordTests.swift | 15 +- 6 files changed, 261 insertions(+), 108 deletions(-) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 082e479e1..ddb84bad3 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -428,9 +428,74 @@ public enum DatabaseColumnEncodingStrategy { case .useDefaultKeys: return key.stringValue case .convertToSnakeCase: - return key.stringValue.convertToSnakeCase() + return Self._convertToSnakeCase(key.stringValue) case let .custom(column): return column(key) } } + + // Copied straight from + // https://github.com/apple/swift-corelibs-foundation/blob/8d6398d76eaf886a214e0bb2bd7549d968f7b40e/Sources/Foundation/JSONEncoder.swift#L127 + static func _convertToSnakeCase(_ stringKey: String) -> String { + guard !stringKey.isEmpty else { return stringKey } + + var words: [Range] = [] + // The general idea of this algorithm is to split words on transition + // from lower to upper case, then on transition of >1 upper case + // characters to lowercase + // + // myProperty -> my_property + // myURLProperty -> my_url_property + // + // We assume, per Swift naming conventions, that the first character of + // the key is lowercase. + var wordStart = stringKey.startIndex + var searchRange = stringKey.index(after: wordStart)..1 capital letters. Turn those into a + // word, stopping at the capital before the lower case character. + let beforeLowerIndex = stringKey.index(before: lowerCaseRange.lowerBound) + words.append(upperCaseRange.lowerBound..: Decoder { } class KeyedContainer: KeyedDecodingContainerProtocol { - let decoder: _RowDecoder + private let decoder: _RowDecoder var codingPath: [CodingKey] { decoder.codingPath } - var decodedRootKey: CodingKey? + private var decodedRootKey: CodingKey? + // Not nil iff decoder has a columnDecodingStrategy + private let _columnForKey: [String: String]? init(decoder: _RowDecoder) { self.decoder = decoder + switch decoder.columnDecodingStrategy { + case .useDefaultKeys: + _columnForKey = nil + default: + var columnForKey: [String: String] = [:] + for column in decoder.row.columnNames { + if let key: Key = decoder.columnDecodingStrategy.key(forColumn: column) { + columnForKey[key.stringValue] = column + } + } + _columnForKey = columnForKey + } } lazy var allKeys: [Key] = { - #warning("TODO: the columns are not decoded with decoder.columnDecodingStrategy") let row = decoder.row - return Set(row.columnNames) - .union(row.scopesTree.names) - .union(row.prefetchedRows.keys) - .compactMap(Key.init(stringValue:)) + var keys = _columnForKey.map { Set($0.keys) } ?? Set(row.columnNames) + keys.formUnion(row.scopesTree.names) + keys.formUnion(row.prefetchedRows.keys) + return keys.compactMap(Key.init(stringValue:)) }() func contains(_ key: Key) -> Bool { let row = decoder.row - return row.hasColumn(column(forKey: key)) - || (row.scopesTree[key.stringValue] != nil) - || (row.prefetchedRows[key.stringValue] != nil) + if let _columnForKey = _columnForKey { + if let column = _columnForKey[key.stringValue] { + assert(row.hasColumn(column)) + return true + } + } else if row.hasColumn(key.stringValue) { + return true + } + if row.scopesTree[key.stringValue] != nil { + return true + } + if row.prefetchedRows[key.stringValue] != nil { + return true + } + return false } func decodeNil(forKey key: Key) throws -> Bool { // Nil is only possible for columns and scopes (optional // associations), not for prefetched rows. let row = decoder.row - return row[column(forKey: key)] == nil && (row.scopesTree[key.stringValue] == nil) + if let column = try? decodeColumn(forKey: key), row[column] != nil { + return false + } + if row.scopesTree[key.stringValue] != nil { + return false + } + return true } // swiftlint:disable comma // swiftlint:disable line_length - func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: column(forKey: key)) } - func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: column(forKey: key)) } + func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } + func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: decodeColumn(forKey: key)) } // swiftlint:enable line_length // swiftlint:enable comma - private func column(forKey key: Key) -> String { - decoder.columnDecodingStrategy.column(forKey: key) + private func decodeColumn(forKey key: Key) throws -> String { + guard let _columnForKey = _columnForKey else { + return key.stringValue + } + + guard let column = _columnForKey[key.stringValue] else { + let errorDescription: String + switch decoder.columnDecodingStrategy { + case .convertFromSnakeCase: + // In this case we can attempt to recover the original value + // by reversing the transform + let original = key.stringValue + let converted = DatabaseColumnEncodingStrategy._convertToSnakeCase(original) + let roundtrip = DatabaseColumnDecodingStrategy._convertFromSnakeCase(converted) + if converted == original { + errorDescription = "\(key) (\"\(original)\")" + } else if roundtrip == original { + errorDescription = """ + \(key) (\"\(original)\"), \ + converted to \(converted) + """ + } else { + errorDescription = """ + \(key) (\"\(original)\"), \ + with divergent representation \(roundtrip), \ + converted to \(converted) + """ + } + default: + // Otherwise, just report the converted string + errorDescription = "\(key) (\"\(key.stringValue)\")" + } + + // TODO: this is not quite correct: key IS NOT a column name. + // So we shouldn't use RowKey.columnName. Yet this only impacts + // internal types, so the damage is limited. + throw RowDecodingError.keyNotFound( + .columnName(key.stringValue), // <- See above TODO + RowDecodingError.Context( + decodingContext: RowDecodingContext(row: decoder.row), + debugDescription: "key not found: \(errorDescription)")) + } + + return column } func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable { let row = decoder.row // Column? - if let index = row.index(forColumn: column(forKey: key)) { + if let column = try? decodeColumn(forKey: key), + let index = row.index(forColumn: column) + { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { @@ -156,7 +231,9 @@ private struct _RowDecoder: Decoder { let row = decoder.row // Column? - if let index = row.index(forColumn: column(forKey: key)) { + if let column = try? decodeColumn(forKey: key), + let index = row.index(forColumn: column) + { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 771eec939..6f075c03c 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -654,16 +654,66 @@ public enum DatabaseColumnDecodingStrategy { case convertFromSnakeCase /// A key decoding strategy defined by the closure you supply. - case custom((CodingKey) -> String) + case custom((String) -> CodingKey) - func column(forKey key: CodingKey) -> String { + func key(forColumn column: String) -> K? { switch self { case .useDefaultKeys: - return key.stringValue + return K(stringValue: column) case .convertFromSnakeCase: - return key.stringValue.convertToSnakeCase() - case let .custom(column): - return column(key) + return K(stringValue: Self._convertFromSnakeCase(column)) + case let .custom(key): + return K(stringValue: key(column).stringValue) } } + + // Copied straight from + // https://github.com/apple/swift-corelibs-foundation/blob/8d6398d76eaf886a214e0bb2bd7549d968f7b40e/Sources/Foundation/JSONDecoder.swift#L103 + static func _convertFromSnakeCase(_ stringKey: String) -> String { + guard !stringKey.isEmpty else { return stringKey } + + // Find the first non-underscore character + guard let firstNonUnderscore = stringKey.firstIndex(where: { $0 != "_" }) else { + // Reached the end without finding an _ + return stringKey + } + + // Find the last non-underscore character + var lastNonUnderscore = stringKey.index(before: stringKey.endIndex) + while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" { + stringKey.formIndex(before: &lastNonUnderscore) + } + + let keyRange = firstNonUnderscore...lastNonUnderscore + let leadingUnderscoreRange = stringKey.startIndex.. String { - guard !isEmpty else { return self } - - var words: [Range] = [] - // The general idea of this algorithm is to split words on transition - // from lower to upper case, then on transition of >1 upper case - // characters to lowercase - // - // myProperty -> my_property - // myURLProperty -> my_url_property - // - // We assume, per Swift naming conventions, that the first character of - // the key is lowercase. - var wordStart = startIndex - var searchRange = index(after: wordStart)..1 capital letters. Turn those into a - // word, stopping at the capital before the lower case character. - let beforeLowerIndex = index(before: lowerCaseRange.lowerBound) - words.append(upperCaseRange.lowerBound.. Date: Sun, 29 Aug 2021 13:53:22 +0200 Subject: [PATCH 21/26] Thourough testing of DatabaseColumnDecodingStrategy --- .../FetchableRecordDecodableTests.swift | 316 +++++++++++++++++- 1 file changed, 300 insertions(+), 16 deletions(-) diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index 09eeadcdc..36c6c76ab 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -763,24 +763,308 @@ extension FetchableRecordDecodableTests { } } - func testDatabaseColumnDecodingStrategy() throws { - struct Record: FetchableRecord, Decodable { - static let databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy = .convertFromSnakeCase - let recordID: Int - let recordName: String - let recordDate: Date + // MARK: - DatabaseColumnDecodingStrategy + + func testDatabaseColumnDecodingStrategy_useDefaultKeys() throws { + struct Record: FetchableRecord, Decodable, Equatable { + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.useDefaultKeys + let requiredId: Int + let optionalName: String? + let requiredDates: [Date] + let optionalDates: [Date?] + let optionalDates2: [Date]? } - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let record = try Record.fetchOne(db, sql: "SELECT ? AS record_id, ? AS record_name, ? as record_date", arguments: [ - 1, - "test1", - "1970-01-01 00:02:08.000", - ])! - XCTAssertEqual(record.recordID, 1) - XCTAssertEqual(record.recordName, "test1") - XCTAssertEqual(record.recordDate.timeIntervalSince1970, 128) + do { + let record = try RowDecoder().decode(Record.self, from: [ + "requiredId": 1, + "optionalName": "test1", + "requiredDates": "[128000]", + "optionalDates": "[null, 128000]", + "optionalDates2": "[128000]", + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: "test1", + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: [Date(timeIntervalSince1970: 128)])) + } + + do { + let record = try RowDecoder().decode(Record.self, from: [ + "REQUIREDID": 1, + "OPTIONALNAME": "test1", + "REQUIREDDATES": "[128000]", + "OPTIONALDATES": "[null, 128000]", + "OPTIONALDATES2": "[128000]", + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: "test1", + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: [Date(timeIntervalSince1970: 128)])) + } + + do { + let record = try RowDecoder().decode(Record.self, from: [ + "requiredId": 1, + "optionalName": nil, + "requiredDates": "[128000]", + "optionalDates": "[null, 128000]", + "optionalDates2": nil, + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: nil, + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: nil)) + } + + do { + let record = try RowDecoder().decode(Record.self, from: [ + "requiredId": 1, + "requiredDates": "[128000]", + "optionalDates": "[null, 128000]", + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: nil, + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: nil)) + } + + do { + _ = try RowDecoder().decode(Record.self, from: [ + "required_id": 1, + "optionalName": "test1", + "requiredDates": "[128000]", + "optionalDates": "[null, 128000]", + "optionalDates2": "[128000]", + ]) + XCTFail("Expected error") + } catch let RowDecodingError.keyNotFound(.columnName(column), context) { + XCTAssertEqual(column, "requiredId") + XCTAssertEqual(context.debugDescription, "column not found: \"requiredId\"") + } + } + + func testDatabaseColumnDecodingStrategy_convertFromSnakeCase() throws { + struct Record: FetchableRecord, Decodable, Equatable { + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.convertFromSnakeCase + let requiredId: Int + let optionalName: String? + let requiredDates: [Date] + let optionalDates: [Date?] + let optionalDates2: [Date]? + } + + struct IncorrectRecord: FetchableRecord, Decodable, Equatable { + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.convertFromSnakeCase + let requiredID: Int // incorrect: should be requiredId + let optionalName: String? + let requiredDates: [Date] + let optionalDates: [Date?] + let optionalDates2: [Date]? + } + + do { + let record = try RowDecoder().decode(Record.self, from: [ + "required_id": 1, + "optional_name": "test1", + "required_dates": "[128000]", + "optional_dates": "[null, 128000]", + "optional_dates2": "[128000]", + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: "test1", + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: [Date(timeIntervalSince1970: 128)])) + } + + do { + let record = try RowDecoder().decode(Record.self, from: [ + "REQUIRED_ID": 1, + "OPTIONAL_NAME": "test1", + "REQUIRED_DATES": "[128000]", + "OPTIONAL_DATES": "[null, 128000]", + "OPTIONAL_DATES2": "[128000]", + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: "test1", + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: [Date(timeIntervalSince1970: 128)])) + } + + do { + let record = try RowDecoder().decode(Record.self, from: [ + "required_id": 1, + "optional_name": nil, + "required_dates": "[128000]", + "optional_dates": "[null, 128000]", + "optional_dates2": nil, + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: nil, + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: nil)) + } + + do { + let record = try RowDecoder().decode(Record.self, from: [ + "required_id": 1, + "required_dates": "[128000]", + "optional_dates": "[null, 128000]", + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: nil, + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: nil)) + } + + do { + // Matches JSONDecoder.KeyDecodingStrategy.convertFromSnakeCase behavior + let record = try RowDecoder().decode(Record.self, from: [ + "requiredId": 1, + "optionalName": "test1", + "requiredDates": "[128000]", + "optionalDates": "[null, 128000]", + "optionalDates2": "[128000]", + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: "test1", + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: [Date(timeIntervalSince1970: 128)])) + } + + do { + _ = try RowDecoder().decode(Record.self, from: [ + "required_idx": 1, + "optional_name": "test1", + "required_dates": "[128000]", + "optional_dates": "[null, 128000]", + "optional_dates2": "[128000]", + ]) + XCTFail("Expected error") + } catch let RowDecodingError.keyNotFound(.columnName(column), context) { + XCTAssertEqual(column, "requiredId") + XCTAssertEqual(context.debugDescription, """ + key not found: CodingKeys(stringValue: "requiredId", intValue: nil) ("requiredId"), \ + converted to required_id + """) + } + + do { + _ = try RowDecoder().decode(IncorrectRecord.self, from: [ + "required_id": 1, + "optional_name": "test1", + "required_dates": "[128000]", + "optional_dates": "[null, 128000]", + "optional_dates2": "[128000]", + ]) + XCTFail("Expected error") + } catch let RowDecodingError.keyNotFound(.columnName(column), context) { + XCTAssertEqual(column, "requiredID") + XCTAssertEqual(context.debugDescription, """ + key not found: CodingKeys(stringValue: "requiredID", intValue: nil) ("requiredID"), \ + with divergent representation requiredId, \ + converted to required_id + """) + } + } + + func testDatabaseColumnDecodingStrategy_custom() throws { + struct AnyKey: CodingKey { + var stringValue: String + var intValue: Int? { nil } + init(stringValue: String) { self.stringValue = stringValue } + init?(intValue: Int) { nil } + } + + struct Record: FetchableRecord, Decodable, Equatable { + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { column in + AnyKey(stringValue: String(column.dropFirst())) + } + let requiredId: Int + let optionalName: String? + let requiredDates: [Date] + let optionalDates: [Date?] + let optionalDates2: [Date]? + } + + do { + let record = try RowDecoder().decode(Record.self, from: [ + "_requiredId": 1, + "_optionalName": "test1", + "_requiredDates": "[128000]", + "_optionalDates": "[null, 128000]", + "_optionalDates2": "[128000]", + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: "test1", + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: [Date(timeIntervalSince1970: 128)])) + } + + do { + let record = try RowDecoder().decode(Record.self, from: [ + "_requiredId": 1, + "_optionalName": nil, + "_requiredDates": "[128000]", + "_optionalDates": "[null, 128000]", + "_optionalDates2": nil, + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: nil, + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: nil)) + } + + do { + let record = try RowDecoder().decode(Record.self, from: [ + "_requiredId": 1, + "_requiredDates": "[128000]", + "_optionalDates": "[null, 128000]", + ]) + XCTAssertEqual(record, Record( + requiredId: 1, + optionalName: nil, + requiredDates: [Date(timeIntervalSince1970: 128)], + optionalDates: [nil, Date(timeIntervalSince1970: 128)], + optionalDates2: nil)) + } + + do { + _ = try RowDecoder().decode(Record.self, from: [ + "requiredId": 1, + "_optionalName": "test1", + "_requiredDates": "[128000]", + "_optionalDates": "[null, 128000]", + "_optionalDates2": "[128000]", + ]) + XCTFail("Expected error") + } catch let RowDecodingError.keyNotFound(.columnName(column), context) { + XCTAssertEqual(column, "requiredId") + XCTAssertEqual(context.debugDescription, """ + key not found: CodingKeys(stringValue: "requiredId", intValue: nil) ("requiredId") + """) } } } From c23d97775929bda11cc20603e9520b2bc0fd375f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 14:08:17 +0200 Subject: [PATCH 22/26] Thorough testing of DatabaseColumnDecodingStrategy with including(optional:) and including(required:) We make sure strategies are correctly applied for each involved record type. --- ...ciationBelongsToFetchableRecordTests.swift | 162 ++++++++++++++---- 1 file changed, 126 insertions(+), 36 deletions(-) diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift index 26de5facc..ebbabc3cc 100644 --- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -128,34 +128,75 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase { var xid: Int64 var xname: String } - + struct XPlayer: Decodable, FetchableRecord, TableRecord { static let databaseTableName = "players" static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { column in AnyKey(stringValue: "x\(column)") } + static let team = belongsTo(Team.self, key: "team") static let xteam = belongsTo(XTeam.self, key: "xteam") var xid: Int64 var xteamId: Int64? var xname: String } - - struct XPlayerWithRequiredTeam: Decodable, FetchableRecord { - var xplayer: XPlayer - var xteam: XTeam + + do { + struct XPlayerWithRequiredXTeam: Decodable, FetchableRecord { + var xplayer: XPlayer + var xteam: XTeam + } + + let dbQueue = try makeDatabaseQueue() + let request = XPlayer + .including(required: XPlayer.xteam) + .asRequest(of: XPlayerWithRequiredXTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records[0].xplayer.xid, 1) + XCTAssertEqual(records[0].xplayer.xteamId, 1) + XCTAssertEqual(records[0].xplayer.xname, "Arthur") + XCTAssertEqual(records[0].xteam.xid, 1) + XCTAssertEqual(records[0].xteam.xname, "Reds") } - let dbQueue = try makeDatabaseQueue() - let request = XPlayer - .including(required: XPlayer.xteam) - .asRequest(of: XPlayerWithRequiredTeam.self) - let records = try dbQueue.inDatabase { try request.fetchAll($0) } - XCTAssertEqual(records.count, 1) - XCTAssertEqual(records[0].xplayer.xid, 1) - XCTAssertEqual(records[0].xplayer.xteamId, 1) - XCTAssertEqual(records[0].xplayer.xname, "Arthur") - XCTAssertEqual(records[0].xteam.xid, 1) - XCTAssertEqual(records[0].xteam.xname, "Reds") + do { + struct XPlayerWithRequiredTeam: Decodable, FetchableRecord { + var xplayer: XPlayer + var team: Team + } + + let dbQueue = try makeDatabaseQueue() + let request = XPlayer + .including(required: XPlayer.team) + .asRequest(of: XPlayerWithRequiredTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records[0].xplayer.xid, 1) + XCTAssertEqual(records[0].xplayer.xteamId, 1) + XCTAssertEqual(records[0].xplayer.xname, "Arthur") + XCTAssertEqual(records[0].team.id, 1) + XCTAssertEqual(records[0].team.name, "Reds") + } + + do { + struct PlayerWithRequiredXTeam: Decodable, FetchableRecord { + var player: Player + var xteam: XTeam + } + + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(required: Player.belongsTo(XTeam.self, key: "xteam")) + .asRequest(of: PlayerWithRequiredXTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].xteam.xid, 1) + XCTAssertEqual(records[0].xteam.xname, "Reds") + } } func testIncludingOptional_ColumnDecodingStrategy() throws { @@ -174,37 +215,86 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase { var xid: Int64 var xname: String } - + struct XPlayer: Decodable, FetchableRecord, TableRecord { static let databaseTableName = "players" static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { column in AnyKey(stringValue: "x\(column)") } + static let team = belongsTo(Team.self, key: "team") static let xteam = belongsTo(XTeam.self, key: "xteam") var xid: Int64 var xteamId: Int64? var xname: String } - - struct XPlayerWithOptionalTeam: Decodable, FetchableRecord { - var xplayer: XPlayer - var xteam: XTeam? + + do { + struct XPlayerWithOptionalXTeam: Decodable, FetchableRecord { + var xplayer: XPlayer + var xteam: XTeam? + } + + let dbQueue = try makeDatabaseQueue() + let request = XPlayer + .including(optional: XPlayer.xteam) + .asRequest(of: XPlayerWithOptionalXTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].xplayer.xid, 1) + XCTAssertEqual(records[0].xplayer.xteamId, 1) + XCTAssertEqual(records[0].xplayer.xname, "Arthur") + XCTAssertEqual(records[0].xteam!.xid, 1) + XCTAssertEqual(records[0].xteam!.xname, "Reds") + XCTAssertEqual(records[1].xplayer.xid, 2) + XCTAssertNil(records[1].xplayer.xteamId) + XCTAssertEqual(records[1].xplayer.xname, "Barbara") + XCTAssertNil(records[1].xteam) } - let dbQueue = try makeDatabaseQueue() - let request = XPlayer - .including(optional: XPlayer.xteam) - .asRequest(of: XPlayerWithOptionalTeam.self) - let records = try dbQueue.inDatabase { try request.fetchAll($0) } - XCTAssertEqual(records.count, 2) - XCTAssertEqual(records[0].xplayer.xid, 1) - XCTAssertEqual(records[0].xplayer.xteamId, 1) - XCTAssertEqual(records[0].xplayer.xname, "Arthur") - XCTAssertEqual(records[0].xteam!.xid, 1) - XCTAssertEqual(records[0].xteam!.xname, "Reds") - XCTAssertEqual(records[1].xplayer.xid, 2) - XCTAssertNil(records[1].xplayer.xteamId) - XCTAssertEqual(records[1].xplayer.xname, "Barbara") - XCTAssertNil(records[1].xteam) + do { + struct XPlayerWithOptionalTeam: Decodable, FetchableRecord { + var xplayer: XPlayer + var team: Team? + } + + let dbQueue = try makeDatabaseQueue() + let request = XPlayer + .including(optional: XPlayer.team) + .asRequest(of: XPlayerWithOptionalTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].xplayer.xid, 1) + XCTAssertEqual(records[0].xplayer.xteamId, 1) + XCTAssertEqual(records[0].xplayer.xname, "Arthur") + XCTAssertEqual(records[0].team!.id, 1) + XCTAssertEqual(records[0].team!.name, "Reds") + XCTAssertEqual(records[1].xplayer.xid, 2) + XCTAssertNil(records[1].xplayer.xteamId) + XCTAssertEqual(records[1].xplayer.xname, "Barbara") + XCTAssertNil(records[1].team) + } + + do { + struct PlayerWithOptionalXTeam: Decodable, FetchableRecord { + var player: Player + var xteam: XTeam? + } + + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(optional: Player.belongsTo(XTeam.self, key: "xteam")) + .asRequest(of: PlayerWithOptionalXTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].xteam!.xid, 1) + XCTAssertEqual(records[0].xteam!.xname, "Reds") + XCTAssertEqual(records[1].player.id, 2) + XCTAssertNil(records[1].player.teamId) + XCTAssertEqual(records[1].player.name, "Barbara") + XCTAssertNil(records[1].xteam) + } } } From d2e7485b0284810fde4fb3ffbc5a5b10681d3b56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Aug 2021 14:11:58 +0200 Subject: [PATCH 23/26] Thorough testing of DatabaseColumnDecodingStrategy with including(all:) We make sure strategies are correctly applied for each involved record type. --- ...ciationPrefetchingCodableRecordTests.swift | 114 ++++++++++++++---- 1 file changed, 88 insertions(+), 26 deletions(-) diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index 5fb98b189..04fa5c549 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -1225,35 +1225,35 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { } func testIncludingAllHasMany_ColumnDecodingStrategy() throws { + struct AnyKey: CodingKey { + var stringValue: String + var intValue: Int? { nil } + init(stringValue: String) { self.stringValue = stringValue } + init?(intValue: Int) { nil } + } + + struct XA: TableRecord, FetchableRecord, Decodable, Equatable { + static let databaseTableName = "a" + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { column in + AnyKey(stringValue: "x\(column)") + } + var xcola1: Int64 + var xcola2: String + } + + struct XB: TableRecord, FetchableRecord, Decodable, Equatable, Hashable { + static let databaseTableName = "b" + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { column in + AnyKey(stringValue: "x\(column)") + } + var xcolb1: Int64 + var xcolb2: Int64? + var xcolb3: String + } + let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in do { - struct AnyKey: CodingKey { - var stringValue: String - var intValue: Int? { nil } - init(stringValue: String) { self.stringValue = stringValue } - init?(intValue: Int) { nil } - } - - struct XA: TableRecord, FetchableRecord, Decodable, Equatable { - static let databaseTableName = "a" - static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { column in - AnyKey(stringValue: "x\(column)") - } - var xcola1: Int64 - var xcola2: String - } - - struct XB: TableRecord, FetchableRecord, Decodable, Equatable, Hashable { - static let databaseTableName = "b" - static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { column in - AnyKey(stringValue: "x\(column)") - } - var xcolb1: Int64 - var xcolb2: Int64? - var xcolb3: String - } - struct XRecord: FetchableRecord, Decodable, Equatable { var xa: XA var xbs: [XB] @@ -1283,6 +1283,68 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { xbs: []), ]) } + + do { + struct XRecord: FetchableRecord, Decodable, Equatable { + var xa: XA + var bs: [B] + } + + let request = XA + .including(all: XA + .hasMany(B.self) + .orderByPrimaryKey()) + .orderByPrimaryKey() + + let records = try XRecord.fetchAll(db, request) + XCTAssertEqual(records, [ + XRecord( + xa: XA(row: ["cola1": 1, "cola2": "a1"]), + bs: [ + B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + B(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ]), + XRecord( + xa: XA(row: ["cola1": 2, "cola2": "a2"]), + bs: [ + B(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + XRecord( + xa: XA(row: ["cola1": 3, "cola2": "a3"]), + bs: []), + ]) + } + + do { + struct XRecord: FetchableRecord, Decodable, Equatable { + var a: A + var xbs: [XB] + } + + let request = A + .including(all: A + .hasMany(XB.self, key: "xbs") + .orderByPrimaryKey()) + .orderByPrimaryKey() + + let records = try XRecord.fetchAll(db, request) + XCTAssertEqual(records, [ + XRecord( + a: A(row: ["cola1": 1, "cola2": "a1"]), + xbs: [ + XB(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]), + XB(row: ["colb1": 5, "colb2": 1, "colb3": "b2"]), + ]), + XRecord( + a: A(row: ["cola1": 2, "cola2": "a2"]), + xbs: [ + XB(row: ["colb1": 6, "colb2": 2, "colb3": "b3"]), + ]), + XRecord( + a: A(row: ["cola1": 3, "cola2": "a3"]), + xbs: []), + ]) + } } } } From 87e9a0d0e0db2d088b9be06541c6160ae6f7172a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Aug 2021 19:21:37 +0200 Subject: [PATCH 24/26] Add license --- GRDB/Record/EncodableRecord.swift | 11 +++++++++++ GRDB/Record/FetchableRecord.swift | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index ddb84bad3..3e8d2c903 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -437,6 +437,17 @@ public enum DatabaseColumnEncodingStrategy { // Copied straight from // https://github.com/apple/swift-corelibs-foundation/blob/8d6398d76eaf886a214e0bb2bd7549d968f7b40e/Sources/Foundation/JSONEncoder.swift#L127 static func _convertToSnakeCase(_ stringKey: String) -> String { + //===----------------------------------------------------------------------===// + // + // This function is part of the Swift.org open source project + // + // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors + // Licensed under Apache License v2.0 with Runtime Library Exception + // + // See https://swift.org/LICENSE.txt for license information + // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors + // + //===----------------------------------------------------------------------===// guard !stringKey.isEmpty else { return stringKey } var words: [Range] = [] diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 6f075c03c..24333e25b 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -670,6 +670,17 @@ public enum DatabaseColumnDecodingStrategy { // Copied straight from // https://github.com/apple/swift-corelibs-foundation/blob/8d6398d76eaf886a214e0bb2bd7549d968f7b40e/Sources/Foundation/JSONDecoder.swift#L103 static func _convertFromSnakeCase(_ stringKey: String) -> String { + //===----------------------------------------------------------------------===// + // + // This function is part of the Swift.org open source project + // + // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors + // Licensed under Apache License v2.0 with Runtime Library Exception + // + // See https://swift.org/LICENSE.txt for license information + // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors + // + //===----------------------------------------------------------------------===// guard !stringKey.isEmpty else { return stringKey } // Find the first non-underscore character From c7e05caf86f34e06defd4874465ba2593c7bf623 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 3 Sep 2021 14:50:53 +0200 Subject: [PATCH 25/26] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c7682f7a..52d6896fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,6 +81,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Fixed**: Version 5.10.0, when embedded as an Xcode project, would enable the FTS5 full-text engine on system versions that do not provide it. - **New**: [#1046](https://github.com/groue/GRDB.swift/pull/1046) by [@groue](https://github.com/groue): Improve performance of by-index row decoding +- **New**: [#1029](https://github.com/groue/GRDB.swift/pull/1029) by [@sberrevoets](https://github.com/sberrevoets), [@groue](https://github.com/groue): Column coding strategies for Codable records ## 5.10.0 From cc2326389765818e9cdbd19051cb6f494385b391 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 3 Sep 2021 14:51:01 +0200 Subject: [PATCH 26/26] Update thank you notice --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d4ef263fd..cd3a22437 100644 --- a/README.md +++ b/README.md @@ -8425,7 +8425,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](http://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@layoutSubviews](https://github.com/layoutSubviews), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@mattgallagher](https://github.com/mattgallagher), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@pp5x](https://github.com/pp5x), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@tternes](https://github.com/tternes), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), [@ZevEisenberg](https://github.com/ZevEisenberg), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. +- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](http://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@layoutSubviews](https://github.com/layoutSubviews), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@mattgallagher](https://github.com/mattgallagher), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@pp5x](https://github.com/pp5x), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@sberrevoets](https://github.com/sberrevoets), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@tternes](https://github.com/tternes), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), [@ZevEisenberg](https://github.com/ZevEisenberg), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency.