Postgrex.transaction

You're seeing just the function transaction, go back to Postgrex module for more information.
Link to this function

transaction(conn, fun, opts \\ [])

View Source

Specs

transaction(conn(), (DBConnection.t() -> result), [option()]) ::
  {:ok, result} | {:error, 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.

rollback/2 rolls back the transaction and causes the function to return {:error, reason}.

transaction/3 can be nested multiple times if the connection reference is used to start a nested transaction. The top level transaction function is the actual transaction.

Options

  • :queue - Whether to wait for connection in a queue (default: true);
  • :timeout - Transaction timeout (default: 15000);
  • :mode - Set to :savepoint to use savepoints instead of an SQL transaction, otherwise set to :transaction (default: :transaction);

The :timeout is for the duration of the transaction and all nested transactions and requests. This timeout overrides timeouts set by internal transactions and requests. The :mode will be used for all requests inside the transaction function.

Example

{:ok, res} = Postgrex.transaction(pid, fn(conn) ->
  Postgrex.query!(conn, "SELECT title FROM posts", [])
end)