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 但我不是。