DBConnection.transaction
transaction
, go back to DBConnection module for more information.
Specs
transaction(conn(), (t() -> result), opts :: Keyword.t()) :: {:ok, result} | {:error, reason :: any()} when result: var
Acquire a lock on a connection and run a series of requests inside a
transaction. The result of the transaction fun is return inside an :ok
tuple: {:ok, result}
.
To use the locked connection call the request with the connection
reference passed as the single argument to the fun
. If the
connection disconnects all future calls using that connection
reference will fail.
run/3
and transaction/3
can be nested multiple times. If a transaction is
rolled back or a nested transaction fun
raises the transaction is marked as
failed. All calls except run/3
, transaction/3
, rollback/2
, close/3
and
close!/3
will raise an exception inside a failed transaction until the outer
transaction call returns. All transaction/3
calls will return
{:error, :rollback}
if the transaction failed or connection closed and
rollback/2
is not called for that transaction/3
.
Options
:queue
- Whether to block waiting in an internal queue for the connection's state (boolean, default:true
). See "Queue config" instart_link/2
docs:timeout
- The maximum time that the caller is allowed to perform this operation (default:15_000
):deadline
- If set, overrides:timeout
option and specifies absolute monotonic time in milliseconds by which caller must perform operation. SeeSystem
module documentation for more information on monotonic time (default:nil
):log
- A function to log information about begin, commit and rollback calls made as part of the transaction, either a 1-arity fun,{module, function, args}
withDBConnection.LogEntry.t/0
prepended toargs
ornil
. SeeDBConnection.LogEntry
(default:nil
)
The pool and connection module may support other options. All options
are passed to handle_begin/2
, handle_commit/2
and
handle_rollback/2
.
Example
{:ok, res} = DBConnection.transaction(conn, fn conn ->
DBConnection.execute!(conn, query, [])
end)