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

Fix naive datetime casting #3182

Merged
merged 1 commit into from
Dec 11, 2019
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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