Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Actually use additional parameters #473

Merged
merged 8 commits into from
May 9, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Sources/PostgresNIO/New/PostgresChannelHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,8 @@ final class PostgresChannelHandler: ChannelDuplexHandler {
let authContext = AuthContext(
username: username,
password: self.configuration.password,
database: self.configuration.database
database: self.configuration.database,
additionalParameters: self.configuration.options.additionalStartupParameters
MahdiBM marked this conversation as resolved.
Show resolved Hide resolved
)
let action = self.state.provideAuthenticationContext(authContext)
return self.run(action, with: context)
Expand Down
33 changes: 32 additions & 1 deletion Tests/IntegrationTests/AsyncTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,36 @@ final class AsyncPostgresConnectionTests: XCTestCase {
}
}

func testAdditionalParametersTakeEffect() async throws {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer { XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully()) }
let eventLoop = eventLoopGroup.next()

let query: PostgresQuery = """
SELECT
current_setting('application_name');
"""

let applicationName = "postgres-nio-test"
var options = PostgresConnection.Configuration.Options()
options.additionalStartupParameters = [
("application_name", applicationName)
]

try await withTestConnection(on: eventLoop, options: options) { connection in
let rows = try await connection.query(query, logger: .psqlTest)
var counter = 0

for try await element in rows.decode(String.self) {
XCTAssertEqual(element, applicationName)

counter += 1
}

XCTAssertGreaterThanOrEqual(counter, 1)
}
}

func testSelectTimeoutWhileLongRunningQuery() async throws {
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer { XCTAssertNoThrow(try eventLoopGroup.syncShutdownGracefully()) }
Expand Down Expand Up @@ -452,11 +482,12 @@ extension XCTestCase {

func withTestConnection<Result>(
on eventLoop: EventLoop,
options: PostgresConnection.Configuration.Options? = nil,
file: StaticString = #filePath,
line: UInt = #line,
_ closure: (PostgresConnection) async throws -> Result
) async throws -> Result {
let connection = try await PostgresConnection.test(on: eventLoop).get()
let connection = try await PostgresConnection.test(on: eventLoop, options: options).get()

do {
let result = try await closure(connection)
Expand Down
21 changes: 12 additions & 9 deletions Tests/IntegrationTests/Utilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ extension PostgresConnection {
static func address() throws -> SocketAddress {
try .makeAddressResolvingHost(env("POSTGRES_HOSTNAME") ?? "localhost", port: env("POSTGRES_PORT").flatMap(Int.init(_:)) ?? 5432)
}

MahdiBM marked this conversation as resolved.
Show resolved Hide resolved
@available(*, deprecated, message: "Test deprecated functionality")
static func testUnauthenticated(on eventLoop: EventLoop, logLevel: Logger.Level = .info) -> EventLoopFuture<PostgresConnection> {
var logger = Logger(label: "postgres.connection.test")
Expand All @@ -24,20 +24,23 @@ extension PostgresConnection {
}
}

static func test(on eventLoop: EventLoop) -> EventLoopFuture<PostgresConnection> {
static func test(on eventLoop: EventLoop, options: Configuration.Options? = nil) -> EventLoopFuture<PostgresConnection> {
let logger = Logger(label: "postgres.connection.test")
let config = PostgresConnection.Configuration(
var config = PostgresConnection.Configuration(
host: env("POSTGRES_HOSTNAME") ?? "localhost",
port: env("POSTGRES_PORT").flatMap(Int.init(_:)) ?? 5432,
username: env("POSTGRES_USER") ?? "test_username",
password: env("POSTGRES_PASSWORD") ?? "test_password",
database: env("POSTGRES_DB") ?? "test_database",
tls: .disable
)
if let options {
config.options = options
}

return PostgresConnection.connect(on: eventLoop, configuration: config, id: 0, logger: logger)
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just my Xcode settings ... not sure what to do?

static func testUDS(on eventLoop: EventLoop) -> EventLoopFuture<PostgresConnection> {
let logger = Logger(label: "postgres.connection.test")
let config = PostgresConnection.Configuration(
Expand All @@ -46,10 +49,10 @@ extension PostgresConnection {
password: env("POSTGRES_PASSWORD") ?? "test_password",
database: env("POSTGRES_DB") ?? "test_database"
)

return PostgresConnection.connect(on: eventLoop, configuration: config, id: 0, logger: logger)
}

static func testChannel(_ channel: Channel, on eventLoop: EventLoop) -> EventLoopFuture<PostgresConnection> {
let logger = Logger(label: "postgres.connection.test")
let config = PostgresConnection.Configuration(
Expand All @@ -58,7 +61,7 @@ extension PostgresConnection {
password: env("POSTGRES_PASSWORD") ?? "test_password",
database: env("POSTGRES_DB") ?? "test_database"
)

return PostgresConnection.connect(on: eventLoop, configuration: config, id: 0, logger: logger)
}
}
Expand All @@ -74,7 +77,7 @@ func env(_ name: String) -> String? {
}

extension XCTestCase {

public static var shouldRunLongRunningTests: Bool {
// The env var must be set and have the value `"true"`, `"1"`, or `"yes"` (case-insensitive).
// For the sake of sheer annoying pedantry, values like `"2"` are treated as false.
Expand All @@ -83,7 +86,7 @@ extension XCTestCase {
if let intValue = Int(rawValue) { return intValue == 1 }
return rawValue.lowercased() == "yes"
}

public static var shouldRunPerformanceTests: Bool {
// Same semantics as above. Any present non-truthy value will explicitly disable performance
// tests even if they would've overwise run in the current configuration.
Expand Down
42 changes: 42 additions & 0 deletions Tests/PostgresNIOTests/New/PostgresConnectionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,48 @@ class PostgresConnectionTests: XCTestCase {
}
}

func testOptionsAreSentOnTheWire() async throws {
let eventLoop = NIOAsyncTestingEventLoop()
let channel = await NIOAsyncTestingChannel(handlers: [
ReverseByteToMessageHandler(PSQLFrontendMessageDecoder()),
ReverseMessageToByteHandler(PSQLBackendMessageEncoder()),
], loop: eventLoop)
try await channel.connect(to: .makeAddressResolvingHost("localhost", port: 5432))

let configuration = {
var config = PostgresConnection.Configuration(
establishedChannel: channel,
username: "username",
password: "postgres",
database: "database"
)
config.options.additionalStartupParameters = [
("DateStyle", "ISO, MDY"),
("application_name", "postgres-nio-test"),
("server_encoding", "UTF8"),
("integer_datetimes", "on"),
("client_encoding", "UTF8"),
("TimeZone", "Etc/UTC"),
("is_superuser", "on"),
("server_version", "13.1 (Debian 13.1-1.pgdg100+1)"),
("session_authorization", "postgres"),
("IntervalStyle", "postgres"),
("standard_conforming_strings", "on")
]
return config
}()

async let connectionPromise = PostgresConnection.connect(on: eventLoop, configuration: configuration, id: 1, logger: .psqlTest)
let message = try await channel.waitForOutboundWrite(as: PostgresFrontendMessage.self)
XCTAssertEqual(message, .startup(.versionThree(parameters: .init(user: "username", database: "database", options: configuration.options.additionalStartupParameters, replication: .false)))) // put in the options here. This will validate the options have hit the wire
MahdiBM marked this conversation as resolved.
Show resolved Hide resolved
try await channel.writeInbound(PostgresBackendMessage.authentication(.ok))
try await channel.writeInbound(PostgresBackendMessage.backendKeyData(.init(processID: 1234, secretKey: 5678)))
try await channel.writeInbound(PostgresBackendMessage.readyForQuery(.idle))

let connection = try await connectionPromise
try await connection.close()
}

func testSimpleListen() async throws {
let (connection, channel) = try await self.makeTestConnectionWithAsyncTestingChannel()

Expand Down
Loading