Instance Method
withTransaction(logger:file:line:isolation:_:)
closure’s lifetime.func withTransaction<Result>(logger: Logger, file: String = #file, line: Int = #line, isolation: isolated (any Actor)? = #isolation, _ closure: nonisolated(nonsending) (PostgresConnection) async throws -> sending Result) async throws -> sending Result
Parameters
loggerThe
Loggerto log into for the transaction.fileThe file the transaction was started in. Used for better error reporting.
lineThe line the transaction was started in. Used for better error reporting.
isolationThe actor isolation to use for the transaction.
closureThe user provided code to modify the database. Use the provided connection to run queries. The connection must stay in the transaction mode. Otherwise this method will throw!
Return Value
The closure’s return value.
Discussion
The function leases a connection from the underlying connection pool and starts a transaction by running a BEGIN query on the leased connection against the database. It then lends the connection to the user provided closure. The user can then modify the database as they wish. If the user provided closure returns successfully, the function will attempt to commit the changes by running a COMMIT query against the database. If the user provided closure throws an error, the function will attempt to rollback the changes made within the closure.