0Pricing
Elixir & Phoenix: Scalable Backend Development · レッスン

トランザクションとEcto.Multi

Repoのトランザクションと、組み合わせて使えるEcto.Multi構造体を利用して、複数のデータベース操作をアトミックな単位にまとめます。

「トランザクションとEcto.Multi」はCoddyKit上の無料Elixir & Phoenix: Scalable Backend Developmentレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはElixir & Phoenix: Scalable Backend Development学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Elixir & Phoenix: Scalable Backend Developmentコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

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

よくある質問

「トランザクションとEcto.Multi」レッスンは無料ですか?

はい。「トランザクションとEcto.Multi」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Elixir & Phoenix: Scalable Backend Developmentコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Elixir & Phoenix: Scalable Backend Developmentコースには全4レッスンが含まれています。

「トランザクションとEcto.Multi」で何を学びますか?

Repoのトランザクションと、組み合わせて使えるEcto.Multi構造体を利用して、複数のデータベース操作をアトミックな単位にまとめます。 ブラウザで直接実行するハンズオンコードでElixir & Phoenix: Scalable Backend Developmentを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Elixir & Phoenix: Scalable Backend Developmentを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのElixir & Phoenix: Scalable Backend Developmentは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「トランザクションとEcto.Multi」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このElixir & Phoenix: Scalable Backend Developmentレッスンでコードを書いて実行できますか?

はい。すべてのElixir & Phoenix: Scalable Backend Developmentレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. Ectoスキーマとデータベースマイグレーション
  2. Repo、Changeset、クエリ
  3. アソシエーションと埋め込みスキーマ
  4. トランザクションとEcto.Multi
← Elixir & Phoenix: Scalable Backend Developmentに戻る