Skip to content

Commit

Permalink
Merge pull request #17 from vapor/null-encode
Browse files Browse the repository at this point in the history
null data encode
  • Loading branch information
tanner0101 authored Feb 14, 2018
2 parents 82c7e14 + b3ef0f6 commit 2c9333d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,22 @@ fileprivate final class _PostgreSQLMessageKeyedEncoder<K>: KeyedEncodingContaine
func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer { return encoder.unkeyedContainer() }
func superEncoder() -> Encoder { return encoder }
func superEncoder(forKey key: K) -> Encoder { return encoder }

func encodeIfPresent<T>(_ value: T?, forKey key: K) throws where T : Encodable {
if T.self == Data.self {
if let data = value {
try encoder.encode(data)
} else {
try encoder.encode(Int32(-1)) // indicate nil data
}
} else {
if let value = value {
try encoder.encode(value)
} else {
try encoder.encodeNil()
}
}
}
}

/// MARK: Unkeyed
Expand Down
17 changes: 16 additions & 1 deletion Tests/PostgreSQLTests/PostgreSQLConnectionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class PostgreSQLConnectionTests: XCTestCase {
func testVersion() throws {
let (client, eventLoop) = try PostgreSQLConnection.makeTest()
let results = try client.simpleQuery("SELECT version();").await(on: eventLoop)
try XCTAssert(results[0]["version"]?.decode(String.self).contains("10.1") == true)
try XCTAssert(results[0]["version"]?.decode(String.self).contains("10.") == true)
}

func testSelectTypes() throws {
Expand Down Expand Up @@ -270,13 +270,28 @@ class PostgreSQLConnectionTests: XCTestCase {
}
}

func testNull() throws {
let (client, eventLoop) = try PostgreSQLConnection.makeTest()
_ = try client.query("drop table if exists nulltest;").await(on: eventLoop)
let createResult = try client.query("create table nulltest (i integer not null, d timestamp);").await(on: eventLoop)
XCTAssertEqual(createResult.count, 0)
let insertResult = try! client.query("insert into nulltest (i, d) VALUES ($1, $2)", [
PostgreSQLData(type: .int2, format: .binary, data: Data([0x00, 0x01])),
PostgreSQLData(type: .timestamp, format: .binary, data: nil),
]).await(on: eventLoop)
XCTAssertEqual(insertResult.count, 0)
let parameterizedResult = try! client.query("select * from nulltest").await(on: eventLoop)
XCTAssertEqual(parameterizedResult.count, 1)
}

static var allTests = [
("testVersion", testVersion),
("testSelectTypes", testSelectTypes),
("testParse", testParse),
("testTypes", testTypes),
("testParameterizedTypes", testParameterizedTypes),
("testStruct", testStruct),
("testNull", testNull),
]
}

Expand Down

0 comments on commit 2c9333d

Please sign in to comment.