Skip to content

Commit

Permalink
PostgresQuery full test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
fabianfett committed Feb 20, 2022
1 parent 10bda2d commit 426f6a3
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Sources/PostgresNIO/New/PostgresQuery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ extension PostgresQuery {
self.sql.append(contentsOf: "$\(self.binds.count)")
}

mutating func appendInterpolation<Value: PSQLEncodable & Encodable, JSONEncoder: PostgresJSONEncoder>(
mutating func appendInterpolation<Value: PSQLEncodable, JSONEncoder: PostgresJSONEncoder>(
_ value: Value,
context: PSQLEncodingContext<JSONEncoder>
) throws {
Expand Down
52 changes: 51 additions & 1 deletion Tests/PostgresNIOTests/New/PostgresQueryTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import XCTest

final class PostgresQueryTests: XCTestCase {

func testStringInterpolation() throws {
func testStringInterpolationWithOptional() throws {
let string = "Hello World"
let null: UUID? = nil
let uuid: UUID? = UUID()
Expand All @@ -29,4 +29,54 @@ final class PostgresQueryTests: XCTestCase {

XCTAssertEqual(query.binds.bytes, expected)
}

func testStringInterpolationWithCustomJSONEncoder() throws {
struct Foo: Codable, PSQLCodable {
var helloWorld: String
}

let jsonEncoder = JSONEncoder()
jsonEncoder.keyEncodingStrategy = .convertToSnakeCase

let query: PostgresQuery = try """
INSERT INTO test (foo) SET (\(Foo(helloWorld: "bar"), context: .init(jsonEncoder: jsonEncoder)));
"""

XCTAssertEqual(query.sql, "INSERT INTO test (foo) SET ($1);")

let expectedJSON = #"{"hello_world":"bar"}"#

var expected = ByteBuffer()
expected.writeInteger(Int32(expectedJSON.utf8.count + 1))
expected.writeInteger(UInt8(0x01))
expected.writeString(expectedJSON)

XCTAssertEqual(query.binds.bytes, expected)
}

func testAllowUsersToGenerateLotsOfRows() throws {
struct Foo: Codable, PSQLCodable {
var helloWorld: String
}

let jsonEncoder = JSONEncoder()
jsonEncoder.keyEncodingStrategy = .convertToSnakeCase

let sql = "INSERT INTO test (id) SET (\((1...5).map({"$\($0)"}).joined(separator: ", ")));"

var query = PostgresQuery(unsafeSQL: sql, binds: .init(capacity: 5))
for value in 1...5 {
XCTAssertNoThrow(try query.appendBinding(Int(value), context: .default))
}

XCTAssertEqual(query.sql, "INSERT INTO test (id) SET ($1, $2, $3, $4, $5);")

var expected = ByteBuffer()
for value in 1...5 {
expected.writeInteger(UInt32(8))
expected.writeInteger(value)
}

XCTAssertEqual(query.binds.bytes, expected)
}
}

0 comments on commit 426f6a3

Please sign in to comment.