使用 Ecto Fragments 将时间间隔添加到时间戳

Add interval to timestamp using Ecto Fragments

我想使用 Ecto 片段在 phoenix 应用程序中编写以下查询:

select *
from (
  select id, 
  inserted_at + interval '1 day' * expiry as deadline
  from friend_referral_code
) t
where localtimestamp at time zone 'UTC' > deadline

expiry的值是一个整数值,表示天数。到目前为止我得到的是这样的:

query = from frc in FriendReferralCode,
  where: fragment("localtimestamp at time zone 'UTC'") > fragment("? + INTERVAL '1' * ?", frc.inserted_at, frc.expiry)

FriendReferralCode
|> Repo.all(query)
|> Enum.each(fn frc -> update_friend_referral_code_users(get_friend_referral_code_users_by(receiver_id: frc.id), %{status: false}) end)
|> IO.puts()

结束

但它抛出以下错误:

** (EXIT) an exception was raised:
        ** (FunctionClauseError) no function clause matching in Keyword.merge/2
            (elixir 1.11.2) lib/keyword.ex:764: Keyword.merge([], #Ecto.Query<from f0 in Stakester.Accounts.FriendReferralCode, where: fragment("localtimestamp at time zone 'UTC'") > fragment("? + INTERVAL '1 day' * ?", f0.inserted_at, f0.expiry)>)

您在 Ecto.Query.API.ago/2 and Ecto.Query.API.from_now/2 for querying interval and Ecto.Query.subquery/2 之后寻找内部 select


此外,Repo.all/2 期望查询作为第一个参数,而您将 FriendReferralCode 作为调用 Repo.all/2 的第一个参数传递,它期望查询,并且 query作为第二个,它需要一个关键字选项列表。

只做 query |> Repo.all()