Skip to content

Commit

Permalink
chore(ecto_adatper): Update decoding behavior in adapters for Ecto 3.11
Browse files Browse the repository at this point in the history
In Ecto 3.11, adapters now handle decoding with nil values, originating from null values in records.
  • Loading branch information
caleb-acosta committed Dec 5, 2023
1 parent 874cc4d commit 00a8c04
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
7 changes: 7 additions & 0 deletions lib/snowflex/ecto/ecto_adapter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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(decode), 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
Expand All @@ -48,12 +53,14 @@ 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
{val, _} = Float.parse(float)
{:ok, val}
end

defp date_decode(nil), do: {:ok, nil}
defp date_decode(date), do: Date.from_iso8601(date)
end
12 changes: 11 additions & 1 deletion test/snowflex_ecto_adapter_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 00a8c04

Please sign in to comment.