Skip to content

Commit

Permalink
index/3 raises if given multiple where: clauses
Browse files Browse the repository at this point in the history
Because multiple `where:` keywords are supported by Ecto.Query, users
may provide multiple `where:` keywords when declaring a partial index.
However, this is not supported.

Previously, this would fail in a surprising way: the final `where:`
would be used and the other discarded. Now we raise an error, explaining
that these clauses should be combined into a single string.

Fixes #2690
  • Loading branch information
nathanl committed Sep 21, 2018
1 parent 92e8a5f commit 72feaae
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/ecto/migration.ex
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 582,7 @@ defmodule Ecto.Migration do
end

def index(table, columns, opts) when is_binary(table) and is_list(columns) and is_list(opts) do
validate_index_opts!(opts)
index = struct(%Index{table: table, columns: columns}, opts)
%{index | name: index.name || default_index_name(index)}
end
Expand Down Expand Up @@ -956,6 957,17 @@ defmodule Ecto.Migration do
reference
end

defp validate_index_opts!(opts) when is_list(opts) do
case Keyword.get_values(opts, :where) do
[_, _ | _] ->
raise ArgumentError, message:
"only one 'where' keyword is supported when declaring a partial index. To specify multiple conditions, write a single WHERE clause using AND between them."
_ -> :ok
end
end

defp validate_index_opts!(opts), do: opts

@doc false
def __prefix__(%{prefix: prefix} = index_or_table) do
runner_prefix = Runner.prefix()
Expand Down
6 changes: 6 additions & 0 deletions test/ecto/migration_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 64,12 @@ defmodule Ecto.MigrationTest do
%Index{table: "table_one__table_two", unique: true, name: :table_one__table_two_title_index, columns: [:title]}
end

test "raises if given multiple 'where' clauses for an index" do
assert_raise(ArgumentError, fn ->
index(:posts, [:title], where: "status = 'published'", where: "deleted = 'false'")
end)
end

test "creates a reference" do
assert references(:posts) ==
%Reference{table: "posts", column: :id, type: :bigserial}
Expand Down

0 comments on commit 72feaae

Please sign in to comment.