Ecto, working with time intervals

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

I’ve done interval stuff with fragments too. I don’t have a problem using fragments when needed.

You could pattern match longevents in the function head do you have three small functions

You can use this to add time:
https://hexdocs.pm/ecto/Ecto.Query.API.html#datetime_add/3

1 Like