Skip to content

Commit

Permalink
Limit integers to less than 32 digits
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Jul 7, 2023
1 parent cf37968 commit 41f6f91
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
4 changes: 3 additions & 1 deletion lib/ecto/changeset.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1314,7 +1314,9 @@ defmodule Ecto.Changeset do
end
end

defp key_as_int({key, val}) when is_binary(key) do
# We check for the byte size to avoid creating unecessary large integers
# which would never map to a database key (u64 is 20 digits only).
defp key_as_int({key, val}) when is_binary(key) and byte_size(key) < 32 do
case Integer.parse(key) do
{key, ""} -> {key, val}
_ -> {key, val}
Expand Down
12 changes: 7 additions & 5 deletions lib/ecto/type.ex
Original file line number Diff line number Diff line change
Expand Up @@ -824,7 +824,9 @@ defmodule Ecto.Type do
end
end

defp cast_integer(term) when is_binary(term) do
# We check for the byte size to avoid creating unecessary large integers
# which would never map to a database key (u64 is 20 digits only).
defp cast_integer(term) when is_binary(term) and byte_size(term) < 32 do
case Integer.parse(term) do
{integer, ""} -> {:ok, integer}
_ -> :error
Expand Down Expand Up @@ -1410,16 +1412,16 @@ defmodule Ecto.Type do
{:ok, acc}
end

defp to_i(nil), do: nil
defp to_i(int) when is_integer(int), do: int

defp to_i(bin) when is_binary(bin) do
defp to_i(bin) when is_binary(bin) and byte_size(bin) < 32 do
case Integer.parse(bin) do
{int, ""} -> int
_ -> nil
end
end

defp to_i(int) when is_integer(int), do: int
defp to_i(_), do: nil

defp maybe_truncate_usec({:ok, struct}), do: {:ok, truncate_usec(struct)}
defp maybe_truncate_usec(:error), do: :error

Expand Down
4 changes: 4 additions & 0 deletions test/ecto/type_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,10 @@ defmodule Ecto.TypeTest do
refute match?(:string, {:param, :any_datetime})
end

test "integer" do
assert cast(:integer, String.duplicate("1", 64)) == :error
end

test "decimal" do
assert cast(:decimal, "1.0") == {:ok, Decimal.new("1.0")}
assert cast(:decimal, 1.0) == {:ok, Decimal.new("1.0")}
Expand Down

0 comments on commit 41f6f91

Please sign in to comment.