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.
This commit is contained in:
Scott Berrevoets committed 2021-08-12 20:11:54 -07:00
1 parent 97221c7bd6
commit cdc7805471
3 files changed
+136 -18

No files matched your search

+23 -18
View File
@@ -14,7 +14,7 @@ class RowDecoder {
init() { }
func decode<T: FetchableRecord & Decodable>(_ type: T.Type = T.self, from row: Row) throws -> T {
let decoder = _RowDecoder<T>(row: row, codingPath: [])
let decoder = _RowDecoder<T>(row: row, codingPath: [], keyDecodingStrategy: T.databaseKeyDecodingStrategy)
return try T(from: decoder)
}
}
@@ -25,6 +25,7 @@ class RowDecoder {
private struct _RowDecoder<R: FetchableRecord>: Decoder {
var row: Row
var codingPath: [CodingKey]
var keyDecodingStrategy: DatabaseKeyDecodingStrategy
var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
@@ -98,23 +99,27 @@ private struct _RowDecoder<R: FetchableRecord>: 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<T>(_ 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<R: FetchableRecord>: 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<T>(_ type: T.Type) throws -> T where T: Decodable {
defer { currentIndex += 1 }
let decoder = _RowDecoder<R>(row: rows[currentIndex], codingPath: codingPath)
let decoder = _RowDecoder<R>(row: rows[currentIndex], codingPath: codingPath, keyDecodingStrategy: .useDefaultKeys)
return try T(from: decoder)
}
+95
View File
@@ -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<String.Index>] = []
// 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)..<stringKey.endIndex
// Find next uppercase character
while let upperCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.uppercaseLetters, options: [], range: searchRange) {
let untilUpperCase = wordStart..<upperCaseRange.lowerBound
words.append(untilUpperCase)
// Find next lowercase character
searchRange = upperCaseRange.lowerBound..<searchRange.upperBound
guard let lowerCaseRange = stringKey.rangeOfCharacter(from: CharacterSet.lowercaseLetters, options: [], range: searchRange) else {
// There are no more lower case letters. Just end here.
wordStart = searchRange.lowerBound
break
}
// Is the next lowercase letter more than 1 after the uppercase? If so, we encountered a group of uppercase letters that we should treat as its own word
let nextCharacterAfterCapital = stringKey.index(after: upperCaseRange.lowerBound)
if lowerCaseRange.lowerBound == nextCharacterAfterCapital {
// The next character after capital is a lower case character and therefore not a word boundary.
// Continue searching for the next upper case for the boundary.
wordStart = upperCaseRange.lowerBound
} else {
// 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..<beforeLowerIndex)
// Next word starts at the capital before the lowercase we just found
wordStart = beforeLowerIndex
}
searchRange = lowerCaseRange.upperBound..<searchRange.upperBound
}
words.append(wordStart..<searchRange.upperBound)
let result = words.map({ (range) in
return stringKey[range].lowercased()
}).joined(separator: "_")
return result
}
}
@@ -762,6 +762,24 @@ extension FetchableRecordDecodableTests {
XCTAssertEqual(record.optionalDates[1]!.timeIntervalSince1970, 128)
}
}
func testJSONKeyEncodingStrategy() throws {
struct Record: FetchableRecord, Decodable {
static let databaseKeyDecodingStrategy: DatabaseKeyDecodingStrategy = .convertFromSnakeCase
let recordID: Int
let recordName: String
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = try Record.fetchOne(db, sql: "SELECT ? AS record_id, ? AS record_name", arguments: [
1,
"test1",
])!
XCTAssertEqual(record.recordID, 1)
XCTAssertEqual(record.recordName, "test1")
}
}
}
// MARK: - User Infos & Coding Keys