Ecto, working with time intervals
Hi, I using Ecto to query a table named “events” that has a mandatory start datetime and an optional end datetime.
I want to select events that last less (more resp.) than thirty days.
I came up with this code which is working that use Fragments (meh) :
defp events_for_longevents(query, args) do
longevents = Map.get(args, :longevents)
threshold = "30 days" # * 24 * 60 * 60 # 30 days in seconds
case longevents do
nil -> query
true ->
where(
query,
[q],
not is_nil(q.ends_on) and fragment("(? - ?) > '30 days'::interval", q.ends_on, q.begins_on) #, ^threshold)
)
false ->
where(
query,
[q],
is_nil(q.ends_on) or fragment("(? - ?) <= '30 days'::interval", q.ends_on, q.begins_on) #(q.ends_on - q.begins_on) <= ^threshold
)
end
end
But I’m not convinced that there is not a more idiomatic way to write it.
Any suggestion ?
Thanks