Skip to content

Commit c361380

Browse files
authored
Merge pull request #1248 from Chris-Stockbridge/master
Fix #1247 support nil case when decoding optionals
2 parents f0bbfaa + bad16cb commit c361380

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

Sources/SQLite/Typed/Coding.swift

+2-3
Original file line numberDiff line numberDiff line change
@@ -504,9 +504,8 @@ private class SQLiteDecoder: Decoder {
504504
case is UUID.Type:
505505
return try? row.get(Expression<UUID>(key.stringValue)) as? T
506506
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"))
507+
guard let JSONString = try row.get(Expression<String?>(key.stringValue)) else {
508+
return nil
510509
}
511510
guard let data = JSONString.data(using: .utf8) else {
512511
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,

Tests/SQLiteTests/Typed/QueryIntegrationTests.swift

+27
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,33 @@ class QueryIntegrationTests: SQLiteTestCase {
152152
XCTAssertEqual(values.count, 2)
153153
}
154154

155+
func test_insert_custom_encodable_type() throws {
156+
struct TestTypeWithOptionalArray: Codable {
157+
var myInt: Int
158+
var myString: String
159+
var myOptionalArray: [Int]?
160+
}
161+
162+
let table = Table("custom_codable")
163+
try db.run(table.create { builder in
164+
builder.column(Expression<Int?>("myInt"))
165+
builder.column(Expression<String?>("myString"))
166+
builder.column(Expression<String?>("myOptionalArray"))
167+
})
168+
169+
let customType = TestTypeWithOptionalArray(myInt: 13, myString: "foo", myOptionalArray: [1, 2, 3])
170+
try db.run(table.insert(customType))
171+
let rows = try db.prepare(table)
172+
let values: [TestTypeWithOptionalArray] = try rows.map({ try $0.decode() })
173+
XCTAssertEqual(values.count, 1, "return one optional custom type")
174+
175+
let customTypeWithNil = TestTypeWithOptionalArray(myInt: 123, myString: "String", myOptionalArray: nil)
176+
try db.run(table.insert(customTypeWithNil))
177+
let rowsNil = try db.prepare(table)
178+
let valuesNil: [TestTypeWithOptionalArray] = try rowsNil.map({ try $0.decode() })
179+
XCTAssertEqual(valuesNil.count, 2, "return two custom objects, including one that contains a nil optional")
180+
}
181+
155182
func test_upsert() throws {
156183
try XCTSkipUnless(db.satisfiesMinimumVersion(minor: 24))
157184
let fetchAge = { () throws -> Int? in

0 commit comments

Comments
 (0)