Ecto v2.2.8 Ecto.Multi View Source

Ecto.Multi is a data structure for grouping multiple Repo operations.

Ecto.Multi makes it possible to pack operations that should be performed in a single database transaction and gives a way to introspect the queued operations without actually performing them. Each operation is given a name that is unique and will identify its result in case of success or failure.

All operations will be executed in the order they were added.

The Ecto.Multi structure should be considered opaque. You can use %Ecto.Multi{} to pattern match the type, but accessing fields or directly modifying them is not advised.

Ecto.Multi.to_list/1 returns a canonical representation of the structure that can be used for introspection.

Changesets

If multi contains operations that accept changesets (like insert/4, update/4 or delete/4) they will be checked before starting the transaction. If any changeset has errors, the transaction won’t even be started and the error will be immediately returned.

Run

Multi allows you to run arbitrary functions as part of your transaction via run/3 and run/5. This is very useful when an operation depends on the value of a previous operation. For this reason, the function given as callback to run/3 and run/5 will receive all changes performed by the multi so far as a map in the first argument.

The function given to run must return {:ok, value} or {:error, value} as its result. Returning an error will abort any further operations and make the whole multi fail.

Example

Let’s look at an example definition and usage. The use case we’ll be looking into is resetting a password. We need to update the account with proper information, log the request and remove all current sessions:

defmodule PasswordManager do
  alias Ecto.Multi

  def reset(account, params) do
    Multi.new
    |> Multi.update(:account, Account.password_reset_changeset(account, params))
    |> Multi.insert(:log, Log.password_reset_changeset(account, params))
    |> Multi.delete_all(:sessions, Ecto.assoc(account, :sessions))
  end
end

We can later execute it in the integration layer using Repo:

Repo.transaction(PasswordManager.reset(account, params))

By pattern matching on the result we can differentiate different conditions:

case result do
  {:ok, %{account: account, log: log, sessions: sessions}} ->
    # Operation was successful, we can access results (exactly the same
    # we would get from running corresponding Repo functions) under keys
    # we used for naming the operations.
  {:error, failed_operation, failed_value, changes_so_far} ->
    # One of the operations failed. We can access the operation's failure
    # value (like changeset for operations on changesets) to prepare a
    # proper response. We also get access to the results of any operations
    # that succeeded before the indicated operation failed. However, any
    # successful operations would have been rolled back.
end

We can also easily unit test our transaction without actually running it. Since changesets can use in-memory-data, we can use an account that is constructed in memory as well (without persisting it to the database):

test "dry run password reset" do
  account = %Account{password: "letmein"}
  multi = PasswordManager.reset(account, params)

  assert [
    {:account, {:update, account_changeset, []}},
    {:log, {:insert, log_changeset, []}},
    {:sessions, {:delete_all, query, []}}
  ] = Ecto.Multi.to_list(multi)

  # We can introspect changesets and query to see if everything
  # is as expected, for example:
  assert account_changeset.valid?
  assert log_changeset.valid?
  assert inspect(query) == "#Ecto.Query<from a in Session>"
end

Link to this section Summary

Functions

Appends the second multi to the first one

Adds a delete operation to the multi

Adds a delete_all operation to the multi

Causes the multi to fail with the given value

Adds an insert operation to the multi

Adds an insert_all operation to the multi

Inserts or updates a changeset depending on whether the changeset was persisted or not

Merges a multi returned dynamically by an anonymous function

Merges a multi returned dynamically by calling module and function with args

Returns an empty Ecto.Multi struct

Prepends the second multi to the first one

Adds a function to run as part of the multi

Adds a function to run as part of the multi

Returns the list of operations stored in multi

Adds an update operation to the multi

Adds an update_all operation to the multi

Link to this section Types

Link to this type merge() View Source
merge() :: (map() -> t()) | {module(), atom(), [any()]}
Link to this type name() View Source
name() :: any()
Link to this type run() View Source
run() :: (t() -> {:ok | :error, any()}) | {module(), atom(), [any()]}

Link to this section Functions

Link to this function append(lhs, rhs) View Source
append(t(), t()) :: t()

Appends the second multi to the first one.

All names must be unique between both structures.

Example

iex> lhs = Ecto.Multi.new |> Ecto.Multi.run(:left, &{:ok, &1})
iex> rhs = Ecto.Multi.new |> Ecto.Multi.run(:right, &{:error, &1})
iex> Ecto.Multi.append(lhs, rhs) |> Ecto.Multi.to_list |> Keyword.keys
[:left, :right]
Link to this function delete(multi, name, changeset_or_struct, opts \\ []) View Source
delete(t(), name(), Ecto.Changeset.t() | Ecto.Schema.t(), Keyword.t()) :: t()

Adds a delete operation to the multi.

Accepts the same arguments and options as Ecto.Repo.delete/2 does.

Link to this function delete_all(multi, name, queryable, opts \\ []) View Source
delete_all(t(), name(), Ecto.Queryable.t(), Keyword.t()) :: t()

Adds a delete_all operation to the multi.

Accepts the same arguments and options as Ecto.Repo.delete_all/2 does.

Link to this function error(multi, name, value) View Source
error(t(), name(), error :: term()) :: t()

Causes the multi to fail with the given value.

Running the multi in a transaction will execute all previous steps until this operation which halt with the given value.

Link to this function insert(multi, name, changeset_or_struct, opts \\ []) View Source
insert(t(), name(), Ecto.Changeset.t() | Ecto.Schema.t(), Keyword.t()) :: t()

Adds an insert operation to the multi.

Accepts the same arguments and options as Ecto.Repo.insert/2 does.

Link to this function insert_all(multi, name, schema_or_source, entries, opts \\ []) View Source
insert_all(t(), name(), schema_or_source(), [entry], Keyword.t()) :: t() when entry: map() | Keyword.t()

Adds an insert_all operation to the multi.

Accepts the same arguments and options as Ecto.Repo.insert_all/3 does.

Link to this function insert_or_update(multi, name, changeset, opts \\ []) View Source
insert_or_update(t(), name(), Ecto.Changeset.t(), Keyword.t()) :: t()

Inserts or updates a changeset depending on whether the changeset was persisted or not.

Accepts the same arguments and options as Ecto.Repo.insert_or_update/2 does.

Link to this function merge(multi, merge) View Source
merge(t(), (map() -> t())) :: t()

Merges a multi returned dynamically by an anonymous function.

This function is useful when the multi to be merged requires information from the original multi. Hence the second argument is an anonymous function that receives the multi changes so far. The anonymous function must return another multi.

If you would prefer to simply merge two multis together, see append/2 or prepend/2.

Duplicated operations are not allowed.

Link to this function merge(multi, mod, fun, args) View Source
merge(t(), module(), function, args) :: t() when function: atom(), args: [any()]

Merges a multi returned dynamically by calling module and function with args.

Similar to merge/2, but allows to pass module name, function and arguments. The function should return an Ecto.Multi, and receives changes so far as the first argument (prepended to those passed in the call to the function).

Duplicated operations are not allowed.

Returns an empty Ecto.Multi struct.

Example

iex> Ecto.Multi.new |> Ecto.Multi.to_list
[]
Link to this function prepend(lhs, rhs) View Source
prepend(t(), t()) :: t()

Prepends the second multi to the first one.

All names must be unique between both structures.

Example

iex> lhs = Ecto.Multi.new |> Ecto.Multi.run(:left, &{:ok, &1})
iex> rhs = Ecto.Multi.new |> Ecto.Multi.run(:right, &{:error, &1})
iex> Ecto.Multi.prepend(lhs, rhs) |> Ecto.Multi.to_list |> Keyword.keys
[:right, :left]
Link to this function run(multi, name, run) View Source
run(t(), name(), (t() -> {:ok | :error, any()})) :: t()

Adds a function to run as part of the multi.

The function should return either {:ok, value} or {:error, value}, and receives changes so far as an argument.

Link to this function run(multi, name, mod, fun, args) View Source
run(t(), name(), module(), function, args) :: t() when function: atom(), args: [any()]

Adds a function to run as part of the multi.

Similar to run/3, but allows to pass module name, function and arguments. The function should return either {:ok, value} or {:error, value}, and will receive changes so far as the first argument (prepended to those passed in the call to the function).

Link to this function to_list(multi) View Source
to_list(t()) :: [{name(), term()}]

Returns the list of operations stored in multi.

Always use this function when you need to access the operations you have defined in Ecto.Multi. Inspecting the Ecto.Multi struct internals directly is discouraged.

Link to this function update(multi, name, changeset, opts \\ []) View Source
update(t(), name(), Ecto.Changeset.t(), Keyword.t()) :: t()

Adds an update operation to the multi.

Accepts the same arguments and options as Ecto.Repo.update/2 does.

Link to this function update_all(multi, name, queryable, updates, opts \\ []) View Source
update_all(t(), name(), Ecto.Queryable.t(), Keyword.t(), Keyword.t()) :: t()

Adds an update_all operation to the multi.

Accepts the same arguments and options as Ecto.Repo.update_all/3 does.