Skip to content

Instantly share code, notes, and snippets.

@h0lyalg0rithm
Created September 29, 2016 20:53
Show Gist options
  • Save h0lyalg0rithm/54fdfb02fd2cf8e8196b71d832c49b1b to your computer and use it in GitHub Desktop.
Save h0lyalg0rithm/54fdfb02fd2cf8e8196b71d832c49b1b to your computer and use it in GitHub Desktop.
Postgres date range type using ecto
defmodule LocationService.Daterange do
@behaviour Ecto.Type
def type, do: :daterange
def cast([lower, upper]) do
{:ok, [lower, upper]}
end
def cast(_), do: :error
def load(%Postgrex.Range{lower: lower, upper: nil}) do
lower = lower |> to_datetime
{:ok, [lower, nil]}
end
def load(%Postgrex.Range{lower: lower, upper: upper}) do
lower = lower |> to_datetime
upper = upper |> to_datetime
{:ok, [lower, upper]}
end
def dump([lower, upper]) do
{:ok, %Postgrex.Range{lower: lower, upper: upper, upper_inclusive: false}}
end
def dump(_), do: :error
defp to_datetime(value) do
datetime = value |> Ecto.DateTime.load
elem(datetime, 1)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment