From a1a50474bb640fa49afada86cd0e5cc76aea4d0d Mon Sep 17 00:00:00 2001 From: Greg Rychlewski Date: Tue, 8 Oct 2024 14:56:01 -0400 Subject: [PATCH] Raise when empty list is given to `values/2` (#4523) --- lib/ecto/query.ex | 4 ++++ lib/ecto/query/api.ex | 3 ++- test/ecto/query/builder/from_test.exs | 8 ++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/ecto/query.ex b/lib/ecto/query.ex index 4168c49d1c..5af3cd3f4c 100644 --- a/lib/ecto/query.ex +++ b/lib/ecto/query.ex @@ -485,6 +485,10 @@ defmodule Ecto.Query do @moduledoc false defstruct [:types, :num_rows, :params] + def new([], _types) do + raise ArgumentError, "must provide a non-empty list to values/2" + end + def new(values_list, types) do fields = fields(values_list) types = types!(fields, types) diff --git a/lib/ecto/query/api.ex b/lib/ecto/query/api.ex index 0ce9f8bcea..9d2c6ce540 100644 --- a/lib/ecto/query/api.ex +++ b/lib/ecto/query/api.ex @@ -515,7 +515,8 @@ defmodule Ecto.Query.API do and `Ecto.Query.join/5`. The first argument is a list of maps representing the values of the constant table. - Each entry in the list must have exactly the same fields or an error is raised. + An error is raised if the list is empty or if every map does not have exactly the + same fields. The second argument is a map of types corresponding to the fields in the first argument. Each field must be given a type or an error is raised. Any type that can be specified in diff --git a/test/ecto/query/builder/from_test.exs b/test/ecto/query/builder/from_test.exs index b6f4eeac76..8114e587d9 100644 --- a/test/ecto/query/builder/from_test.exs +++ b/test/ecto/query/builder/from_test.exs @@ -27,6 +27,14 @@ defmodule Ecto.Query.Builder.FromTest do types_kw = Enum.map(types, & &1) assert query.from.source == {:values, [], [types_kw, length(values)]} + # Empty values + msg = "must provide a non-empty list to values/2" + + assert_raise ArgumentError, msg, fn -> + from v in values([], %{}) + end + + # Missing type msg = "values/2 must declare the type for every field. The type was not given for field `text`"