Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(ecto_adatper): Update decoding behavior in adapters for Ecto 3.11 #79

Merged
merged 1 commit into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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(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
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