如何解决Ecto.Multi.run/3
遵循本教程 https://curiosum.dev/blog/elixir-ecto-database-transactions
alias Ecto.Multi
alias ElixirRest.Account
import Ecto.Query,only: [from: 2]
require Logger
def transfer_money(acc1_id,acc2_id,amount) do
Multi.new()
|> Multi.run(:retrieve_accounts_step,retrieve_accounts(acc1_id,acc2_id))
|> Multi.run(:verify_balances_step,verify_balances(amount))
|> Multi.run(:subtract_from_a_step,&subtract_from_a/2)
|> Multi.run(:add_to_b_step,&add_to_b/2)
end
defp retrieve_accounts(acc1_id,acc2_id) do
fn repo,_ ->
case from(acc in Account,where: acc.id in [^acc1_id,^acc2_id]) |> repo.all() do
[acc_a,acc_b] -> {:ok,{acc_a,acc_b}}
_ -> {:error,:account_not_found}
end
end
end
defp verify_balances(transfer_amount) do
fn _repo,%{retrieve_accounts_step: {acc_a,acc_b}} ->
if acc_a.balance < transfer_amount,do: {:error,:balance_too_low},else: {:ok,acc_b,transfer_amount}}
end
end
defp subtract_from_a(repo,%{verify_balances_step: {acc_a,_,verified_amount}}) do
acc_a
|> Account.changeset(%{balance: acc_a.balance - verified_amount})
|> repo.update()
end
defp add_to_b(repo,%{verify_balances_step: {_,verified_amount}}) do
acc_b
|> Account.changeset(%{balance: acc_b.balance + verified_amount})
|> repo.update()
end
end
这样调用:ElixirRest.Account.Batches.transfer_money(input.from_account,input.to_account,input.sum) |> ElixirRest.Repo.transaction()
错误信息:
[error] #PID<0.459.0> running ElixirRestWeb.Endpoint (cowboy_protocol) terminated
Server: localhost:8081 (http)
Request: POST /api/graphiql
** (exit) an exception was raised:
** (FunctionClauseError) no function clause matching in Ecto.Multi.run/3
(ecto 2.2.12) lib/ecto/multi.ex:309: Ecto.Multi.run(%Ecto.Multi{names: #MapSet<[]>,operations: []},:retrieve_accounts_step,#Function<0.17156638/2 in ElixirRest.Account.Batches.retrieve_accounts/2>)
(elixir_rest 0.0.1) lib/elixir_rest_web/resolvers/transaction_resolver.ex:17: ElixirRestWeb.Resolvers.TransactionResolver.create_transaction/3
(absinthe 1.4.16) lib/absinthe/resolution.ex:209: Absinthe.Resolution.call/2
(absinthe 1.4.16) lib/absinthe/phase/document/execution/resolution.ex:209: Absinthe.Phase.Document.Execution.Resolution.reduce_resolution/1
(absinthe 1.4.16) lib/absinthe/phase/document/execution/resolution.ex:168: Absinthe.Phase.Document.Execution.Resolution.do_resolve_field/4
(absinthe 1.4.16) lib/absinthe/phase/document/execution/resolution.ex:153:
是什么导致了这个问题? 是什么导致了这个问题? 是什么导致了这个问题? 是什么导致了这个问题? 是什么导致了这个问题? 是什么导致了这个问题? 是什么导致了这个问题?
解决方法
我使用的是过时版本的 ecto,(2.2)
我以为我在 3 但我不是。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。