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

feat(transaction): Adding withTransaction #519

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
22 changes: 22 additions & 0 deletions Sources/PostgresNIO/Pool/PostgresClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,28 @@ public final class PostgresClient: Sendable, ServiceLifecycle.Service {

return try await closure(connection)
}

/// Lease a connection for the provided `closure`'s lifetime.
/// A transation starts with call to withConnection
/// A transaction should end with a call to COMMIT or ROLLBACK
/// COMMIT is called upon successful completion and ROLLBACK is called should any steps fail
///
/// - Parameter closure: A closure that uses the passed `PostgresConnection`. The closure **must not** capture
/// the provided `PostgresConnection`.
/// - Returns: The closure's return value.
public func withTransaction<Result>(logger: Logger, _ process: (PostgresConnection) async throws -> Result) async throws -> Result {
try await withConnection { connection in
do {
try await connection.query("BEGIN;", logger: logger)
thoven87 marked this conversation as resolved.
Show resolved Hide resolved
let value = try await process(connection)
try await connection.query("COMMIT;", logger: logger)
return value
} catch {
try await connection.query("ROLLBACK;", logger: logger)
throw error
}
}
}

/// Run a query on the Postgres server the client is connected to.
///
Expand Down
35 changes: 35 additions & 0 deletions Tests/IntegrationTests/PostgresClientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,41 @@ final class PostgresClientTests: XCTestCase {
taskGroup.cancelAll()
}
}

func testTransaction() async throws {
var mlogger = Logger(label: "test")
mlogger.logLevel = .debug
let logger = mlogger
let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 8)
self.addTeardownBlock {
try await eventLoopGroup.shutdownGracefully()
}

let clientConfig = PostgresClient.Configuration.makeTestConfiguration()
let client = PostgresClient(configuration: clientConfig, eventLoopGroup: eventLoopGroup, backgroundLogger: logger)

await withThrowingTaskGroup(of: Void.self) { taskGroup in
taskGroup.addTask {
await client.run()
}

let iterations = 1000

for _ in 0..<iterations {
taskGroup.addTask {
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think we should create a throwaway table here and insert some data. then we should check if a commit commits and if a rollback rolls back.

Copy link
Author

@thoven87 thoven87 Oct 21, 2024

Choose a reason for hiding this comment

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

I think we should create a throwaway table here and insert some data. then we should check if a commit commits and if a rollback rolls back.

I added tests in the latest commit. Thanks!

try await client.withTransaction(logger: logger) { connection in
_ = try await connection.query("SELECT 1", logger: logger)
}
}
}

for _ in 0..<iterations {
_ = await taskGroup.nextResult()!
}

taskGroup.cancelAll()
}
}

func testQueryDirectly() async throws {
var mlogger = Logger(label: "test")
Expand Down