close search bar

Sorry, not available in this language yet

close language selection

A Quick Guide to the Complex: Ecto.Multi

Synopsys Editorial Team

Sep 05, 2018 / 2 min read

Table of Contents

Ecto.Multi, a data structure added in Ecto 2.0, is an extremely useful tool for creating and executing complex, atomic transactions. This very brief guide will cover a few of the most useful methods associated with Ecto.Multi and when to use them.

Common Uses

insert(multi, name, changeset_or_struct, opts \\ [])

The most straightforward way to use Ecto.Multi is to chain individual changesets together. insert, update, and delete functions are available and all behave as you might expect them to, with all operations are executed in the order in which they are added. You can imagine a transaction dealing with a user signing up via an invitation email might look something like this:

Common Uses

What might have been be two separate database transactions has been condensed into a single, atomic transaction, with Ecto.Multi handling rollbacks when necessary. But what about when one operation relies on the results of a previous one?

Run

run(multi, name, fun)

Run is an extremely versatile method that adds a function to the Ecto.Multi transaction.

The function must return a tuple in the for of {:ok, value} or {:error, value}, and,

importantly, is passed a map of the operations processed so far in the Multi struct. This means we can key into the changes created by previous operations, and use the those values while executing any code we like. The transaction creating and sending the invitation mentioned above could look something like this:

Run

Append

append(lhs, rhs)

append is a handy way to combine two Ecto.Multi structs into a single atomic transaction. One potential pattern is to compose multiple functions that return Ecto.Multi structs, and combine them as needed. As noted above, operations are executed in order, so if you want the appended struct to be executed first, you’ll want to use prepend instead.

Append

Merge

merge(multi, fun)

Similar to run, merge will execute a given function and any arbitrary code associated with that function. Unlike run, this function is expected to return a multi struct whose operations will be merged into the multi struct passed to it as the first parameter.

Merge

Continue Reading

Explore Topics