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.

Table of contents

    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.update(:payer, payer_changeset)
    |>Ecto.Multi.update(:reciever, reciever_changeset)

    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:

    Download our ebook
    Oskar Legner
    Oskar Legner Elixir & React Developer

    Read more
    on #curiosum blog

    The little story of Elixir programming language

    The Elixir language, operating on an Erlang machine, is constantly gaining more and more followers. Where can these languages be used? How was Elixir created and what does it have in common with Erlang?

    Top Elixir Learning Media & Resources in 2022

    Regardless of whether you've only just heard of the Elixir programming language and would like to learn it, or if you're a seasoned developer with years of experience, you need adequate learning resources to ensure steady progress in your career - and just equally as important is the need to be up to date with what's new & trending in the functional