Skip to content

Commit 3023a1f

Browse files
committed
Add optional support for decoding
1 parent d34f63a commit 3023a1f

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Sources/SQLite/Typed/Coding.swift

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,54 @@ 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 decode<T>(_ type: T.Type, forKey key: Key) throws -> T? where T: Swift.Decodable {
499+
switch type {
500+
case is Data.Type:
501+
let data = try row.get(Expression<Data>(key.stringValue))
502+
return data as? T
503+
case is Date.Type:
504+
let date = try row.get(Expression<Date>(key.stringValue))
505+
return date as? T
506+
case is UUID.Type:
507+
let uuid = try row.get(Expression<UUID>(key.stringValue))
508+
return uuid as? T
509+
default:
510+
guard let JSONString = try row.get(Expression<String?>(key.stringValue)) else {
511+
throw DecodingError.typeMismatch(type, DecodingError.Context(codingPath: codingPath,
512+
debugDescription: "an unsupported type was found"))
513+
}
514+
guard let data = JSONString.data(using: .utf8) else {
515+
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
516+
debugDescription: "invalid utf8 data found"))
517+
}
518+
return try JSONDecoder().decode(type, from: data)
519+
}
520+
}
521+
474522
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws
475523
-> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
476524
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,

0 commit comments

Comments
 (0)