0Pricing
Elixir & Phoenix: Scalable Backend Development · Lezione

Transazioni ed Ecto.Multi

Raggruppi più operazioni sul database in unità atomiche usando le transazioni di Repo e la struct componibile Ecto.Multi.

Transazioni ed Ecto.Multi è una lezione Elixir & Phoenix: Scalable Backend Development gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Elixir & Phoenix: Scalable Backend Development, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Why Transactions?

A transaction bundles several operations so they all succeed or all roll back together, keeping data consistent.

Repo.transaction with a Function

The simplest form runs a function; if it returns normally the transaction commits, if it raises it rolls back.

Repo.transaction(fn ->
  Repo.insert!(%Account{balance: 100})
  Repo.insert!(%Log{action: "created"})
end)

Manual Rollback

Inside the function you can abort explicitly with Repo.rollback/1, which returns {:error, reason}.

Repo.transaction(fn ->
  case withdraw(account, 50) do
    {:ok, acc} -> acc
    {:error, r} -> Repo.rollback(r)
  end
end)

The Problem with Nested Functions

Function-based transactions get hard to read and reuse when steps depend on earlier results. Ecto.Multi solves this declaratively.

Building an Ecto.Multi

Ecto.Multi is a struct that accumulates named operations without touching the database until run.

alias Ecto.Multi
multi =
  Multi.new()
  |> Multi.insert(:user, %User{name: "Ada"})

Chaining Operations

Each operation gets a unique name, letting you reference earlier results and inspect them later.

Multi.new()
|> Multi.insert(:user, user_changeset)
|> Multi.insert(:profile, profile_changeset)

Depending on Earlier Steps

Pass a function to use the results of previous steps. It receives the repo and a map of completed operations.

Multi.new()
|> Multi.insert(:user, user_changeset)
|> Multi.run(:welcome, fn _repo, %{user: user} ->
  send_welcome(user)
end)

Running the Multi

Repo.transaction/1 executes the whole Multi atomically and returns {:ok, results} or an error tuple.

case Repo.transaction(multi) do
  {:ok, %{user: user}} -> {:ok, user}
  {:error, step, reason, _} -> {:error, step, reason}
end

Pinpointing Failures

On failure the error tuple names exactly which step failed and gives the changes made so far (which were rolled back).

{:error, :profile, changeset, _changes_so_far}

Other Multi Operations

Multi supports update, delete, update_all, and delete_all, mirroring Repo functions.

Multi.new()
|> Multi.update(:acc, changeset)
|> Multi.delete_all(:logs, old_logs_query)

Composability Wins

Because a Multi is just data, you can build it in pieces across functions and append more steps before running it, improving testability.

def base_multi, do: Multi.new() |> Multi.insert(:user, cs)
# elsewhere
base_multi() |> Multi.insert(:audit, audit_cs) |> Repo.transaction()

Quick Check

Test your transaction knowledge.

Recap

You made database changes atomic:

  • Repo.transaction with a function commits or rolls back together
  • Repo.rollback aborts explicitly
  • Ecto.Multi composes named steps as data
  • Failures return the failing step name and roll back everything

Domande Frequenti

La lezione «Transazioni ed Ecto.Multi» è gratuita?

Sì — il testo completo di «Transazioni ed Ecto.Multi» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Elixir & Phoenix: Scalable Backend Development, passa a CoddyKit PRO. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.

Cosa imparerò in «Transazioni ed Ecto.Multi»?

Raggruppi più operazioni sul database in unità atomiche usando le transazioni di Repo e la struct componibile Ecto.Multi. Eserciti Elixir & Phoenix: Scalable Backend Development con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Elixir & Phoenix: Scalable Backend Development?

Non è richiesta alcuna esperienza precedente. Elixir & Phoenix: Scalable Backend Development su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Transazioni ed Ecto.Multi»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Elixir & Phoenix: Scalable Backend Development?

Sì. Ogni lezione Elixir & Phoenix: Scalable Backend Development include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Schema Ecto e migrazioni del database
  2. Repo, changeset e query
  3. Associazioni e schemi incorporati
  4. Transazioni ed Ecto.Multi
← Torna a Elixir & Phoenix: Scalable Backend Development