问题
I want to write the following query in a phoenix application using Ecto fragments:
select *
from (
select id,
inserted_at + interval '1 day' * expiry as deadline
from friend_referral_code
) t
where localtimestamp at time zone 'UTC' > deadline
The value of expiry is an integer value that represents number of days. What I've got so far is something like this:
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()
end
but it throws the following error:
** (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)>)
回答1:
You are after Ecto.Query.API.ago/2 and Ecto.Query.API.from_now/2 for querying interval and Ecto.Query.subquery/2 for inner select
.
Also, Repo.all/2 expects a query as a first argument, while you pass FriendReferralCode
as the first argument in the call to Repo.all/2
, where it expects a query, and query
as a second one, where it expects a keyword list of options.
Do just query |> Repo.all()
instead.
来源:https://stackoverflow.com/questions/65183075/add-interval-to-timestamp-using-ecto-fragments