Skip to content

Commit

Permalink
Handle NULLs when decoding arrays (#142)
Browse files Browse the repository at this point in the history
* Add crashing test for decoding an array with NULL values

* Fix crash on NULL values inside arrays
  • Loading branch information
vzsg authored Sep 8, 2019
1 parent 41cec28 commit 561fa79
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Sources/PostgreSQL/Codable/PostgreSQLDataDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,13 @@ struct PostgreSQLDataDecoder {
let _ = value.extract(Int32.self).bigEndian
for _ in 0..<count {
let count = Int(value.extract(Int32.self).bigEndian)

// Postgres sends -1 to distinguish an empty byte sequence from NULLs
guard count != -1 else {
array.append(.null)
continue
}

let subValue = value.extract(count: count)
let psqlData = PostgreSQLData(type, binary: subValue)
array.append(psqlData)
Expand Down
16 changes: 16 additions & 0 deletions Tests/PostgreSQLTests/ConnectionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,22 @@ class ConnectionTests: XCTestCase {
XCTAssertEqual(polygon.polygon.points[3].y, 200)
}.wait()
}

func testGH141() throws {
let conn = try PostgreSQLConnection.makeTest()
defer { conn.close() }

struct Test: Decodable {
let arr: [String?]
}

let result = try conn.raw("SELECT ARRAY[NULL, 'foo', NULL, 'bar'] AS arr")
.all(decoding: Test.self)
.wait()

XCTAssertEqual(1, result.count)
XCTAssertEqual([nil, "foo", nil, "bar"], result[0].arr)
}
}

extension PostgreSQLConnection {
Expand Down
1 change: 1 addition & 0 deletions Tests/PostgreSQLTests/XCTestManifests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ extension ConnectionTests {
("testDataDecoder", testDataDecoder),
("testEmptyArray", testEmptyArray),
("testGH125", testGH125),
("testGH141", testGH141),
("testGH24", testGH24),
("testGH46", testGH46),
("testInvalidDate", testInvalidDate),
Expand Down

0 comments on commit 561fa79

Please sign in to comment.