Created
September 29, 2016 20:53
-
-
Save h0lyalg0rithm/54fdfb02fd2cf8e8196b71d832c49b1b to your computer and use it in GitHub Desktop.
Postgres date range type using ecto
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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