diff --git a/lib/snowflex/ecto/ecto_adapter.ex b/lib/snowflex/ecto/ecto_adapter.ex index 2328793..e102f56 100644 --- a/lib/snowflex/ecto/ecto_adapter.ex +++ b/lib/snowflex/ecto/ecto_adapter.ex @@ -31,14 +31,19 @@ defmodule Snowflex.EctoAdapter do defp binary_encode(raw), do: {:ok, Base.encode16(raw)} + def decimal_decode(nil), do: {:ok, nil} def decimal_decode(dec) when is_binary(dec), do: {:ok, Decimal.new(dec)} def decimal_decode(dec) when is_float(dec), do: {:ok, Decimal.from_float(dec)} + defp int_decode(nil), do: {:ok, nil} defp int_decode(int) when is_binary(int), do: {:ok, String.to_integer(int)} defp int_decode(int), do: {:ok, int} + defp time_decode(nil), do: {:ok, nil} defp time_decode(time), do: Time.from_iso8601(time) + defp datetime_decode(nil), do: {:ok, nil} + defp datetime_decode({date, time}) do with {:ok, date} <- Date.from_erl(date), {:ok, time} <- Time.from_erl(time) do @@ -48,6 +53,7 @@ defmodule Snowflex.EctoAdapter do end end + defp float_decode(nil), do: {:ok, nil} defp float_decode(float) when is_float(float), do: float defp float_decode(float) do @@ -55,5 +61,6 @@ defmodule Snowflex.EctoAdapter do {:ok, val} end + defp date_decode(nil), do: {:ok, nil} defp date_decode(date), do: Date.from_iso8601(date) end diff --git a/test/snowflex_ecto_adapter_test.exs b/test/snowflex_ecto_adapter_test.exs index 7ebbb71..2147cda 100644 --- a/test/snowflex_ecto_adapter_test.exs +++ b/test/snowflex_ecto_adapter_test.exs @@ -2,8 +2,18 @@ defmodule SnowflexEctoAdapterTest do use ExUnit.Case test "handles casting maybe date type to date" do - assert [date_decode, {:maybe, :date}] = Snowflex.EctoAdapter.loaders({:maybe, :date}, {:maybe, :date}) + assert [date_decode, {:maybe, :date}] = + Snowflex.EctoAdapter.loaders({:maybe, :date}, {:maybe, :date}) + assert is_function(date_decode, 1) assert {:ok, ~D[2023-10-23]} = date_decode.("2023-10-23") end + + test "handles nil values" do + [:integer, :utc_datetime, :naive_datetime, :decimal, :float, :date, :id, :time] + |> Enum.each(fn type -> + [decode_fn | _] = Snowflex.EctoAdapter.loaders(type, nil) + assert {:ok, nil} == decode_fn.(nil) + end) + end end