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/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 diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 4f2018a56..d95347493 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 /* 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 */ @@ -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 /* 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 = ""; }; @@ -1771,6 +1775,7 @@ 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( + D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */, 5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */, 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */, 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */, @@ -3343,6 +3348,7 @@ 564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */, + D263F40B26C613090038B07F /* DatabaseColumnEncodingStrategyTests.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 /* DatabaseColumnEncodingStrategyTests.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 /* DatabaseColumnEncodingStrategyTests.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 6554aecd4..b1c16a1ff 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -318,7 +318,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, @@ -1293,7 +1292,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 6fb63e83c..e7b296a41 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: DatabaseColumnEncodingStrategy { Record.databaseColumnEncodingStrategy } init(persistenceContainer: PersistenceContainer) { _persistenceContainer = persistenceContainer @@ -121,7 +122,7 @@ private class RecordEncoder: Encoder { /// Helper methods fileprivate func persist(_ value: DatabaseValueConvertible?, forKey key: CodingKey) { - _persistenceContainer[key.stringValue] = value + _persistenceContainer[keyEncodingStrategy.column(forKey: key)] = value } fileprivate func encode(_ value: T, forKey key: CodingKey) throws where T: Encodable { @@ -147,9 +148,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 a4926569a..3e8d2c903 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 databaseColumnEncodingStrategy: DatabaseUUIDEncodingStrategy = .convertToSnakeCase + /// + /// // encoded as player_id + /// var playerID: String + /// } + static var databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy { get } } extension EncodableRecord { @@ -144,6 +159,10 @@ extension EncodableRecord { public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { .deferredToUUID } + + public static var databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy { + .useDefaultKeys + } } extension EncodableRecord { @@ -379,3 +398,115 @@ public enum DatabaseUUIDEncodingStrategy { /// Encodes UUIDs as strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" case string } + +// MARK: - DatabaseColumnEncodingStrategy + +/// `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 databaseColumnEncodingStrategy = DatabaseColumnEncodingStrategy.convertToSnakeCase +/// +/// // Encoded in the player_id column +/// var playerID: String +/// } +public enum DatabaseColumnEncodingStrategy { + /// 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 + + /// 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) + } + } + + // 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] = [] + // 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 = T.self, from row: Row) throws -> T { - let decoder = _RowDecoder(row: row, codingPath: []) + let decoder = _RowDecoder(row: row, codingPath: [], columnDecodingStrategy: T.databaseColumnDecodingStrategy) return try T(from: decoder) } } @@ -25,6 +25,7 @@ class RowDecoder { private struct _RowDecoder: Decoder { var row: Row var codingPath: [CodingKey] + var columnDecodingStrategy: DatabaseColumnDecodingStrategy var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { @@ -66,61 +67,140 @@ private struct _RowDecoder: 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] = { 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(key.stringValue) - || (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[key.stringValue] == 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: 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: 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 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 - let keyName = key.stringValue // Column? - if let index = row.index(forColumn: keyName) { + 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 { @@ -139,7 +219,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]) } @@ -149,10 +229,11 @@ 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 // Column? - if let index = row.index(forColumn: keyName) { + 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 { @@ -167,12 +248,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) } @@ -249,7 +330,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, columnDecodingStrategy: .useDefaultKeys) return try T(from: decoder) } } @@ -317,7 +398,18 @@ 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 columnDecodingStrategy: DatabaseColumnDecodingStrategy + if let type = T.self as? FetchableRecord.Type { + columnDecodingStrategy = type.databaseColumnDecodingStrategy + } else { + columnDecodingStrategy = .useDefaultKeys + } + + let decoder = _RowDecoder( + row: rows[currentIndex], + codingPath: codingPath, + columnDecodingStrategy: columnDecodingStrategy) return try T(from: decoder) } diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 0861bd382..24333e25b 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: DatabaseColumnDecodingStrategy = .convertFromSnakeCase + /// + /// var playerID: String // decoded from player_id + /// } + static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { get } } extension FetchableRecord { @@ -127,6 +141,10 @@ extension FetchableRecord { public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { .deferredToDate } + + public static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { + .useDefaultKeys + } } extension FetchableRecord { @@ -613,3 +631,100 @@ public enum DatabaseDateDecodingStrategy { /// error, and react accordingly). case custom((DatabaseValue) -> Date?) } + +// MARK: - DatabaseColumnDecodingStrategy + +/// `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 databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.convertFromSnakeCase +/// +/// // Decoded from the player_id column +/// var playerID: Int +/// } +public enum DatabaseColumnDecodingStrategy { + /// A key decoding strategy that doesn’t change key names during decoding. + case useDefaultKeys + + /// 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((String) -> CodingKey) + + func key(forColumn column: String) -> K? { + switch self { + case .useDefaultKeys: + return K(stringValue: column) + case .convertFromSnakeCase: + 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 { + //===----------------------------------------------------------------------===// + // + // 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 + 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.. :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] 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: + +```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. @@ -8404,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. @@ -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 diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift index 17fbc3373..ebbabc3cc 100644 --- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -111,4 +111,190 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase { XCTAssertNil(players[1].teamId) XCTAssertEqual(players[1].name, "Barbara") } + + func testIncludingRequired_ColumnDecodingStrategy() throws { + struct AnyKey: CodingKey { + var stringValue: String + var intValue: Int? { nil } + init(stringValue: String) { self.stringValue = stringValue } + init?(intValue: Int) { nil } + } + + struct XTeam: Decodable, FetchableRecord, TableRecord { + static let databaseTableName = "teams" + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { column in + AnyKey(stringValue: "x\(column)") + } + 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 + } + + 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") + } + + 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 { + struct AnyKey: CodingKey { + var stringValue: String + var intValue: Int? { nil } + init(stringValue: String) { self.stringValue = stringValue } + init?(intValue: Int) { nil } + } + + struct XTeam: Decodable, FetchableRecord, TableRecord { + static let databaseTableName = "teams" + static let databaseColumnDecodingStrategy = DatabaseColumnDecodingStrategy.custom { column in + AnyKey(stringValue: "x\(column)") + } + 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 + } + + 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) + } + + 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) + } + } } diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index 3c800ccd0..04fa5c549 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -1223,4 +1223,128 @@ 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 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: []), + ]) + } + + 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: []), + ]) + } + } + } } diff --git a/Tests/GRDBTests/DatabaseColumnEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseColumnEncodingStrategyTests.swift new file mode 100644 index 000000000..bc8e8e818 --- /dev/null +++ b/Tests/GRDBTests/DatabaseColumnEncodingStrategyTests.swift @@ -0,0 +1,33 @@ +import XCTest +import Foundation +@testable import GRDB + +private struct UseDefaultKeysRecord: PersistableRecord, Encodable { + static var databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy { .useDefaultKeys } + var recordID: String +} + +private struct ConvertToSnakeCaseRecord: PersistableRecord, Encodable { + static var databaseColumnEncodingStrategy: DatabaseColumnEncodingStrategy { .convertToSnakeCase } + var recordID: String +} + +class DatabaseColumnEncodingStrategyTests: GRDBTestCase { + func testUseDefaultKeys() { + let record = UseDefaultKeysRecord(recordID: "test") + + var container = PersistenceContainer() + record.encode(to: &container) + XCTAssertNil(container["record_id"]?.databaseValue.storage) + XCTAssertEqual(container["recordID"]?.databaseValue.storage, "test".databaseValue.storage) + } + + func testConvertToSnakeCase() { + let record = ConvertToSnakeCaseRecord(recordID: "test") + + var container = PersistenceContainer() + record.encode(to: &container) + XCTAssertNil(container["recordID"]?.databaseValue.storage) + XCTAssertEqual(container["record_id"]?.databaseValue.storage, "test".databaseValue.storage) + } +} diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index 4a304aa6e..36c6c76ab 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -762,6 +762,311 @@ extension FetchableRecordDecodableTests { XCTAssertEqual(record.optionalDates[1]!.timeIntervalSince1970, 128) } } + + // 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]? + } + + 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") + """) + } + } } // MARK: - User Infos & Coding Keys