Skip to content

Commit

Permalink
Fix naive datetime casting (#3182)
Browse files Browse the repository at this point in the history
For maps with either all date fields or all time fields blank
  • Loading branch information
aptinio authored and josevalim committed Dec 11, 2019
1 parent d2496ee commit b23c177
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/ecto/type.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1018,12 +1018,14 @@ defmodule Ecto.Type do
do: {:ok, nil}

defp cast_naive_datetime(%{} = map) do
with {:ok, date} <- cast_date(map),
{:ok, time} <- cast_time(map) do
with {:ok, date} when not is_nil(date) <- cast_date(map),
{:ok, time} when not is_nil(time) <- cast_time(map) do
case NaiveDateTime.new(date, time) do
{:ok, _} = ok -> ok
{:error, _} -> :error
end
else
_ -> :error
end
end

Expand Down
14 changes: 14 additions & 0 deletions test/ecto/type_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,20 @@ defmodule Ecto.TypeTest do
assert Ecto.Type.cast(:naive_datetime, %{year: 2015, month: 1, day: 23, hour: 23, minute: nil}) ==
:error

assert Ecto.Type.cast(:naive_datetime, %{"year" => "", "month" => "", "day" => "",
"hour" => "23", "minute" => "50", "second" => "07"}) ==
:error

assert Ecto.Type.cast(:naive_datetime, %{year: nil, month: nil, day: nil, hour: 23, minute: 50, second: 07}) ==
:error

assert Ecto.Type.cast(:naive_datetime, %{"year" => "2015", "month" => "1", "day" => "23",
"hour" => "", "minute" => ""}) ==
:error

assert Ecto.Type.cast(:naive_datetime, %{year: 2015, month: 1, day: 23, hour: nil, minute: nil}) ==
:error

assert Ecto.Type.cast(:naive_datetime, DateTime.from_unix!(10, :second)) ==
{:ok, ~N[1970-01-01 00:00:10]}

Expand Down

0 comments on commit b23c177

Please sign in to comment.