How to safely handle related database operations with Ecto Multi

Sometimes you need to do some database operations at once. A simple example: User-A transfers money to User-B. Updating just one balance at the time creates a risk of data desynchronization. What if the first DB operation goes well but updating the second user’s data fails? Sounds like a hard to catch vulnerability.

Fortunately, the IT environment knows the solution. Transaction processing divides the problem into smaller chunks. Every operation is considered separately, but all of them must succeed to apply changes. In that case, User-A won't lose money if the operation of updating User-B balance fails.

Let’s take a look at the code:

Ecto.Multi.new()
|>Ecto.Multi.update(:payer, payer_changeset)
|>Ecto.Multi.update(:reciever, reciever_changeset)
|>Repo.transaction()

Atom argument - in update function - is just the name of the operation. It could be anything that is unique among these actions.

Of course, it would be also nice to handle result:

  • In case of success there will be returned tuple with :ok atom and instead of the updated structure as the second variable, you can expect the map with all updated structures.

  • Failure brings some helpful information too – like which operation failed (returns its unique atom), what is the failed value, and what has been changed so far (however not applied).

More about Ecto.Multi: https://hexdocs.pm/ecto/Ecto.Multi.html

A girl receiving new message

Sign to our Newsletter

We're committed to your privacy. Curiosum uses the information you provide to us to contact you about our relevant content. You may unsubscribe from these communications at any time. For more information, check out our privacy policy.

Oskar Legner
Oskar Legner

Read more
on #curiosum blog

Phoenix LiveView Tutorial: Adding Phoenix PubSub and Pow Authentication to Messenger
  • Elixir

Phoenix LiveView Tutorial: Adding Phoenix PubSub and Pow Authentication to Messenger

We've already bootstrapped our Phoenix LiveView-based Messenger app's database structure and a first LiveView page.

This time, we're going to improve real-time communication between the app's users using Phoenix PubSub, and use the Pow library to add secure user authentication.

As of November 2020, the latest Phoenix LiveView version is 0.14.8 - and the series has been updated to match it!

5 top-tier companies that use Elixir
  • Elixir

5 top-tier companies that use Elixir

Elixir is a pretty capable language - and it consistently ranks near the top of most loved and wanted languages rankings. It has a large following and some very persuasive preachers as well. But that would not be enough to make me like it – what I need as real proof of its strengths is real businesses that strive with Elixir.

That’s what this list is all about – a bunch of stories from top companies that chose Elixir and never looked back. Let us show you how its power and versatility shows in practice.