事务与 Ecto.Multi
使用 Repo 事务将多个数据库操作组合为原子单元,并利用可组合的 Ecto.Multi 结构进行处理。
事务与 Ecto.Multi 是 CoddyKit 上的免费 Elixir & Phoenix: Scalable Backend Development 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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}
endPinpointing 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.transactionwith a function commits or rolls back togetherRepo.rollbackaborts explicitlyEcto.Multicomposes named steps as data- Failures return the failing step name and roll back everything
常见问题解答
「事务与 Ecto.Multi」课时是免费的吗?
是的 — 「事务与 Ecto.Multi」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Elixir & Phoenix: Scalable Backend Development 课程的其余内容,请升级到 CoddyKit PRO。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。
「事务与 Ecto.Multi」这节课中我会学到什么?
使用 Repo 事务将多个数据库操作组合为原子单元,并利用可组合的 Ecto.Multi 结构进行处理。 你通过在浏览器中直接运行的动手代码来练习 Elixir & Phoenix: Scalable Backend Development,全天候 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 反馈 — 无需本地设置。
此课程中的所有课时
- Ecto 模式与数据库迁移
- Repo、Changesets 与查询
- 关联与嵌入式模式
- 事务与 Ecto.Multi