Skip to content

Commit 561fa79

Browse files
authored
Handle NULLs when decoding arrays (vapor#142)
* Add crashing test for decoding an array with NULL values * Fix crash on NULL values inside arrays
1 parent 41cec28 commit 561fa79

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

Sources/PostgreSQL/Codable/PostgreSQLDataDecoder.swift

+7
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,13 @@ struct PostgreSQLDataDecoder {
6363
let _ = value.extract(Int32.self).bigEndian
6464
for _ in 0..<count {
6565
let count = Int(value.extract(Int32.self).bigEndian)
66+
67+
// Postgres sends -1 to distinguish an empty byte sequence from NULLs
68+
guard count != -1 else {
69+
array.append(.null)
70+
continue
71+
}
72+
6673
let subValue = value.extract(count: count)
6774
let psqlData = PostgreSQLData(type, binary: subValue)
6875
array.append(psqlData)

Tests/PostgreSQLTests/ConnectionTests.swift

+16
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,22 @@ class ConnectionTests: XCTestCase {
670670
XCTAssertEqual(polygon.polygon.points[3].y, 200)
671671
}.wait()
672672
}
673+
674+
func testGH141() throws {
675+
let conn = try PostgreSQLConnection.makeTest()
676+
defer { conn.close() }
677+
678+
struct Test: Decodable {
679+
let arr: [String?]
680+
}
681+
682+
let result = try conn.raw("SELECT ARRAY[NULL, 'foo', NULL, 'bar'] AS arr")
683+
.all(decoding: Test.self)
684+
.wait()
685+
686+
XCTAssertEqual(1, result.count)
687+
XCTAssertEqual([nil, "foo", nil, "bar"], result[0].arr)
688+
}
673689
}
674690

675691
extension PostgreSQLConnection {

Tests/PostgreSQLTests/XCTestManifests.swift

+1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ extension ConnectionTests {
1111
("testDataDecoder", testDataDecoder),
1212
("testEmptyArray", testEmptyArray),
1313
("testGH125", testGH125),
14+
("testGH141", testGH141),
1415
("testGH24", testGH24),
1516
("testGH46", testGH46),
1617
("testInvalidDate", testInvalidDate),

0 commit comments

Comments
 (0)