fireproofsocks

fireproofsocks

A fairly simple use-case: a user has one or more email addresses, stored in the database in 2 separate tables (users, emails) such that the emails table has a foreign key for user_id. (In reality, my use case is more complex, but this illustrates the problem).

Ecto.Multi lets us create a single transaction for adding both the user record and an email record, and we can rollback if either one of those operations fail. I’m looking at the docs for the run/3 and run/5 functions Ecto.Multi — Ecto v3.14.0 but I can’t figure out how these are supposed to be used. From the docs, I’m not at all clear on what value the run function is supposed to return or how that gets ingested by the next operation.

I know I could (sometimes) do this with a single insert operation by leveraging the relationships defined in the schema, but I’m more interested in the principle of the thing.

Thanks as always!

Showing Posts 1 to 10

abitdodgy

abitdodgy

Edit: I’d use @idi527’s example as it’s much more idiomatic.


Here’s a contrived example that should give you the general idea.

Ecto.Multi.new
|> Ecto.Multi.run(:user, fn _ ->
  create_user(user_params)
end)
|> Ecto.Multi.run(:email, fn %{user: user} ->
  create_email(user, email_params)
end)
|> Repo.transaction()

When you use Multi.run, you tag the operation using the second argument. For example, the |> Ecto.Multi.run(:user ... makes the result of create_user available under the :user key in the next the function.

idi527

idi527

:waving_hand:

create_user!(user_params) and create_email!(user, email_params) would need to return {:ok, resource} or {:error, reason}, so these are unlikely to be “bang” operations.

And the last |> Repo.insert() would need to be replaced with Repo.transaction().


@fireproofsocks note that Multi.runs are not automatically rolled back on errors, I’d probably use inserts instead. Modifying @abitdodgy’s example:

alias Ecto.Multi

Multi.new()
|> Multi.insert(:user, User.changeset(%User{}, user_params) end)
|> Multi.insert(:email, fn %{user: %User{id: user_id}} ->
  Email.changeset(%Email{author_id: user_id}, email_params)
end)
|> Repo.transaction()
14
Post #2
abitdodgy

abitdodgy

Good catch. I just cooked that example up!

LostKobrakai

LostKobrakai

Are you sure? A Multi is executed in a transaction and for as long as the command in a Multi.run does only cause side effects to the db and nothing else it should just be rolled back like any other db operation, which happened in that transaction. I‘ve even some places in my projects, where Multis are effectively nested, as the inner multis are executed in named functions which a outer multi composes.

OvermindDL1

OvermindDL1

Precisely, DB actions are rolled back because of a transaction, but run/3,5 is often used to perform non-db actions that need to be run only if the DB succeeds, however there is not version of run/? that allows you to pass both a ‘do’ and an ‘undo’ function, which would be a huge help personally. as right now you have to check it ‘after’ running Repo.transaction, thus meaning the actions of the multi have to ‘leak’ out of where they are defined. We could really use a run/4;8 as well to support both a do and undo…

LostKobrakai

LostKobrakai

How would you ensure that the cleanup doesn’t fail? For the database part it’s a guarantee of the database, but for other side effects ecto cannot do that. Ecto.Multi.run exist because before ecto 3 you could only pass a callback to Ecto.Multi.run and it’s the only way to compose function which do their own database operations.

OvermindDL1

OvermindDL1

That would be on the onus of the one writing their own cleanup function. Some things are just not undoable of course, thus keep using the currently existing functions for those. :slight_smile:

LostKobrakai

LostKobrakai

That’s exactly why Ecto.Multi is not the tool to use imo. You’re no longer orchestrating database operations within a transaction, but arbitrary operations. This is a different requirement, which should be handled by a more appropriate tool like sage.

OvermindDL1

OvermindDL1

Well in my case I’m orchestrating things that need to stay in sync between 2 different databases and an LDAP system, where if any of them fail I can and do need to roll them all back. It’s still a database transaction, just spread across 3 databases (one of which is not transactional, LDAP, so have to roll it back manually)… ^.^;

What is this sage thing and most curiously how would it handle this?

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews