Skip to content

Instantly share code, notes, and snippets.

@Wigny
Last active May 29, 2024 03:52
Show Gist options
  • Save Wigny/3f1b32f729632d5a7417c3d3c31cfbcd to your computer and use it in GitHub Desktop.
Save Wigny/3f1b32f729632d5a7417c3d3c31cfbcd to your computer and use it in GitHub Desktop.
defmodule MyApp.Type.Duration do
use Ecto.Type
alias Postgrex.Interval
defguardp is_duration(value) when is_struct(value, Duration)
defguardp is_interval(value) when is_struct(value, Interval)
@impl true
def type, do: :interval
@impl true
def cast(value) when is_interval(value), do: {:ok, from_interval(value)}
def cast(value) when is_duration(value), do: {:ok, value}
def cast(_value), do: :error
@impl true
def load(value) when is_interval(value), do: {:ok, from_interval(value)}
@impl true
def dump(value) when is_duration(value), do: {:ok, to_interval(value)}
def dump(_value), do: :error
defp from_interval(interval) do
Duration.new!(month: interval.months, day: interval.days, second: interval.secs, microsecond: {interval.microsecs, 6})
end
defp to_interval(duration) do
milliseconds = to_timeout(duration)
%Interval{microsecs: milliseconds * 1_000}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment