Skip to content

Commit 3d25271

Browse files
authored
Merge pull request stephencelis#1224 from JacobHearst/master
Add optional support for decoding
2 parents d34f63a + 1c6bf76 commit 3d25271

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Sources/SQLite/Typed/Coding.swift

+45
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,51 @@ private class SQLiteDecoder: Decoder {
471471
}
472472
}
473473

474+
func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool? {
475+
try? row.get(Expression(key.stringValue))
476+
}
477+
478+
func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int? {
479+
try? row.get(Expression(key.stringValue))
480+
}
481+
482+
func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64? {
483+
try? row.get(Expression(key.stringValue))
484+
}
485+
486+
func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float? {
487+
try? Float(row.get(Expression<Double>(key.stringValue)))
488+
}
489+
490+
func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double? {
491+
try? row.get(Expression(key.stringValue))
492+
}
493+
494+
func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String? {
495+
try? row.get(Expression(key.stringValue))
496+
}
497+
498+
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key) throws -> T? where T: Swift.Decodable {
499+
switch type {
500+
case is Data.Type:
501+
return try? row.get(Expression<Data>(key.stringValue)) as? T
502+
case is Date.Type:
503+
return try? row.get(Expression<Date>(key.stringValue)) as? T
504+
case is UUID.Type:
505+
return try? row.get(Expression<UUID>(key.stringValue)) as? T
506+
default:
507+
guard let JSONString = try? row.get(Expression<String?>(key.stringValue)) else {
508+
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath,
509+
debugDescription: "an unsupported type was found"))
510+
}
511+
guard let data = JSONString.data(using: .utf8) else {
512+
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
513+
debugDescription: "invalid utf8 data found"))
514+
}
515+
return try JSONDecoder().decode(type, from: data)
516+
}
517+
}
518+
474519
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws
475520
-> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
476521
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,

0 commit comments

Comments
 (0)