From a45267441ab3184f7fef751214b3f5d08535633b Mon Sep 17 00:00:00 2001 From: Zach Daniel Date: Fri, 3 Mar 2023 11:59:15 -0500 Subject: [PATCH] chore: more fluent datetime type casting --- lib/ash/type/utc_datetime.ex | 12 ++++++++++++ lib/ash/type/utc_datetime_usec.ex | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/lib/ash/type/utc_datetime.ex b/lib/ash/type/utc_datetime.ex index a59846e1..b9551236 100644 --- a/lib/ash/type/utc_datetime.ex +++ b/lib/ash/type/utc_datetime.ex @@ -6,6 +6,8 @@ defmodule Ash.Type.UtcDatetime do """ use Ash.Type + @beginning_of_day Time.new!(0, 0, 0) + @impl true def storage_type, do: :utc_datetime @@ -17,6 +19,16 @@ defmodule Ash.Type.UtcDatetime do end @impl true + def cast_input(%Date{} = date, constraints) do + case DateTime.new(date, @beginning_of_day) do + {:ok, value} -> + cast_input(value, constraints) + + _ -> + {:error, "Date could not be converted to datetime"} + end + end + def cast_input(value, _) do Ecto.Type.cast(:utc_datetime, value) end diff --git a/lib/ash/type/utc_datetime_usec.ex b/lib/ash/type/utc_datetime_usec.ex index d4cea5a1..12807d17 100644 --- a/lib/ash/type/utc_datetime_usec.ex +++ b/lib/ash/type/utc_datetime_usec.ex @@ -6,6 +6,8 @@ defmodule Ash.Type.UtcDatetimeUsec do """ use Ash.Type + @beginning_of_day Time.new!(0, 0, 0) + @impl true def storage_type, do: :utc_datetime_usec @@ -17,6 +19,16 @@ defmodule Ash.Type.UtcDatetimeUsec do end @impl true + def cast_input(%Date{} = date, constraints) do + case DateTime.new(date, @beginning_of_day) do + {:ok, value} -> + cast_input(value, constraints) + + _ -> + {:error, "Date could not be converted to datetime"} + end + end + def cast_input(value, _) do Ecto.Type.cast(:utc_datetime_usec, value) end