From cdc78054719f492deca4f4fdb11e72e33f71d482 Mon Sep 17 00:00:00 2001 From: Scott Berrevoets Date: Wed, 11 Aug 2021 23:41:02 -0700 Subject: [PATCH] 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..