Repository navigation
Return :error when casting malformed datetimes without seconds - #4802
Merged
josevalim merged 1 commit intoOct 17, 2026
Merged
Conversation
Strings such as "2015-01-23 ab:50" matched the YYYY-MM-DD HH:MM clause of the :naive_datetime and :utc_datetime casts, and the nil parts produced by to_i/1 were passed to NaiveDateTime.new/6, which raised a FunctionClauseError instead of returning :error. Build the date and time through the guarded cast_date/3 and cast_time/4 helpers instead.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Ecto.Type.cast/2for:naive_datetimeand:utc_datetime(and the_usecvariants) raisesFunctionClauseErroron any malformed string shaped likeYYYY-MM-DD HH:MM. It should return:error. Strings like"2015-01-23 ab:50"or"abcd-01-23 23:50"match the clause for datetimes without seconds.to_i/1turns the bad parts intonil, and thosenils go straight intoNaiveDateTime.new/6, which fails its guards inCalendar.ISO.valid_date?/3/valid_time?/4.So a form param can crash
Ecto.Changeset.cast/4where it should add a validation error:The fix builds the date and time with the existing guarded
cast_date/3andcast_time/4helpers, the same way the map clause ofcast_naive_datetime/1already does. Valid inputs give the same results as before.Checks run:
mix test test/ecto/type_test.exs: before the fix, 2 failures (naive_datetime casting naive datetime,utc_datetime cast), bothFunctionClauseError. After the fix, 99 passed.mix test: 1611 passed (97 doctests, 1514 tests)mix compile --force --warnings-as-errors: cleanmix format --check-formatted lib/ecto/type.ex test/ecto/type_test.exs: clean"abcd-01-23 23:50"rows, which go from raising to:error.Not run: the earthly integration matrix, and Elixir versions other than 1.20.4 / OTP 29.