Skip to content

Instance Method

withTransaction(logger:file:line:isolation:_:)

Puts the connection into an open transaction state, for the provided closure’s lifetime.
func withTransaction<Result>(logger: Logger, file: String = #file, line: Int = #line, isolation: isolated (any Actor)? = #isolation, _ process: nonisolated(nonsending) (PostgresConnection) async throws -> sending Result) async throws -> sending Result

Parameters

logger

The Logger to log into for the transaction.

file

The file the transaction was started in. Used for better error reporting.

line

The line the transaction was started in. Used for better error reporting.

isolation

The actor isolation to use for the transaction.

process

The 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 starts a transaction by running a BEGIN query on the 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.