From 426f6a384844c284c836d75f738fa9f0d03be7ca Mon Sep 17 00:00:00 2001 From: Fabian Fett Date: Sun, 20 Feb 2022 12:29:49 +0100 Subject: [PATCH] PostgresQuery full test coverage --- Sources/PostgresNIO/New/PostgresQuery.swift | 2 +- .../New/PostgresQueryTests.swift | 52 ++++++++++++++++++- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/Sources/PostgresNIO/New/PostgresQuery.swift b/Sources/PostgresNIO/New/PostgresQuery.swift index 279bfbe3..7c748e83 100644 --- a/Sources/PostgresNIO/New/PostgresQuery.swift +++ b/Sources/PostgresNIO/New/PostgresQuery.swift @@ -57,7 +57,7 @@ extension PostgresQuery { self.sql.append(contentsOf: "$\(self.binds.count)") } - mutating func appendInterpolation( + mutating func appendInterpolation( _ value: Value, context: PSQLEncodingContext ) throws { diff --git a/Tests/PostgresNIOTests/New/PostgresQueryTests.swift b/Tests/PostgresNIOTests/New/PostgresQueryTests.swift index 3e534d41..24123a54 100644 --- a/Tests/PostgresNIOTests/New/PostgresQueryTests.swift +++ b/Tests/PostgresNIOTests/New/PostgresQueryTests.swift @@ -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() @@ -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) + } }