Skip to content

Instantly share code, notes, and snippets.

@jgautsch
Created October 2, 2018 03:32
Show Gist options
  • Save jgautsch/85bda57d53ada9f2d0106b3d4a379472 to your computer and use it in GitHub Desktop.
Save jgautsch/85bda57d53ada9f2d0106b3d4a379472 to your computer and use it in GitHub Desktop.
defmodule Postgrex.Extension.TSTZRange do
@behaviour Ecto.Type
def type, do: :tstzrange
def cast({lower, upper}) do
case apply_func({lower, upper}, &Ecto.Type.cast(:utc_datetime, &1)) do
{:ok, {lower, upper}} -> {:ok, {lower, upper}}
:error -> :error
end
end
def cast(_), do: :error
def load(%Postgrex.Range{lower: lower, upper: upper}) do
apply_func({lower, upper}, &Ecto.Type.load(:utc_datetime, &1))
end
def load(_), do: :error
def dump({lower, upper}) do
case apply_func({lower, upper}, &Ecto.Type.dump(:utc_datetime, &1)) do
{:ok, {lower, upper}} ->
{:ok, %Postgrex.Range{lower: lower, upper: upper, upper_inclusive: false}}
:error ->
:error
end
end
def dump(_), do: :error
def apply_func({lower, upper}, fun) do
lower = do_apply_func(lower, fun)
upper = do_apply_func(upper, fun)
if lower != :error and upper != :error do
{:ok, {lower, upper}}
else
:error
end
end
def do_apply_func(target, fun) do
case fun.(target) do
{:ok, target} -> target
:error -> :error
end
end
end
@jgautsch
Copy link
Author

jgautsch commented Nov 5, 2018

FYI this stops working with ecto 3.0 and postgrex 0.14.0.
Here is a complete example of creating tsrange and tstzrange columns with Ecto 3.0: https://github.com/jgautsch/ecto_time_ranges
^that repo also shows examples of how to query for overlapping ranges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment