zhulinpinyu / zhulinpinyu.github.io

Blog
http://blog.zhulinpinyu.com
Apache License 2.0
2 stars 0 forks source link

Repo.transaction Ecto.Multi Example #23

Open zhulinpinyu opened 2 years ago

zhulinpinyu commented 2 years ago

Handling results Once you call Repo.transaction/1, you can pattern-match the result tuple.

In the case of success, you will receive all {:ok, result} with result being a map; operations and their successful results will be in the result map, under the unique key you have chosen.

In the case of an error, all database operations will be rolled back, and you will be given {:error, failed_operation, failed_value, changes_so_far} which allows you to handle errors from specific operations individually and inspect them. Note that changes_so_far simply means “operations that went well until this one failed” and no data is actually left in the database.

Ecto.Multi.new()
|> Ecto.Multi.insert(:team, team_changeset)
|> Ecto.Multi.update(:user, user_changeset)
|> Ecto.Multi.delete(:foo, foo_changeset)
|> Repo.transaction
|> case do
  {:ok, %{user: user, team: team, foo: foo}} ->
    # Yay, success!
  {:error, :foo, value, _} ->
    # It seems that :foo failed!
  {:error, op, res, others} ->
    # One of the others failed!
end

https://elixirschool.com/blog/ecto-multi/