Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Repo.transaction Ecto.Multi Example #23

Open
zhulinpinyu opened this issue Feb 7, 2022 · 0 comments
Open

Repo.transaction Ecto.Multi Example #23

zhulinpinyu opened this issue Feb 7, 2022 · 0 comments
Labels

Comments

@zhulinpinyu
Copy link
Owner

zhulinpinyu commented Feb 7, 2022

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant