Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 7 additions & 10 deletions lib/ecto/repo/queryable.ex
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,12 @@ defmodule Ecto.Repo.Queryable do

def exists?(name, queryable, opts) do
queryable =
Query.exclude(queryable, :select)
|> Query.exclude(:preload)
Query.exclude(queryable, :preload)
|> rewrite_combinations()
|> Query.exclude(:select)
|> Query.exclude(:distinct)
|> Query.select(1)
|> Query.limit(1)
|> rewrite_combinations()

case all(name, queryable, opts) do
[1] -> true
Expand All @@ -155,13 +155,10 @@ defmodule Ecto.Repo.Queryable do

defp rewrite_combinations(%{combinations: []} = query), do: query

defp rewrite_combinations(%{combinations: combinations} = query) do
combinations =
Enum.map(combinations, fn {type, query} ->
{type, query |> Query.exclude(:select) |> Query.select(1)}
end)

%{query | combinations: combinations}
defp rewrite_combinations(query) do
query
|> Query.subquery()
|> Queryable.Ecto.SubQuery.to_query()
end

def one(name, queryable, tuplet) do
Expand Down
21 changes: 16 additions & 5 deletions test/ecto/repo_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -565,18 +565,29 @@ defmodule Ecto.RepoTest do
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, order_by: [asc: m0.id], limit: 1, select: 1>"
end

test "overrides any select" do
test "overrides any select without combinations" do
from(MySchema, select: true) |> TestRepo.exists?()
assert_received {:all, query}

assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, limit: 1, select: 1>"
end

from(MySchema, union: ^from(MySchema, select: true)) |> TestRepo.exists?()
assert_received {:all, query}
test "wraps combinations in a subquery before overriding the select" do
query = from(m in MySchema, select: m.id, distinct: true)
combination = from(m in MySchema, select: m.id)

assert inspect(query) ==
"#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, union: (from m0 in Ecto.RepoTest.MySchema,\n select: 1), limit: 1, select: 1>"
for type <- [:union, :union_all, :except, :except_all, :intersect, :intersect_all] do
TestRepo.exists?(%{query | combinations: [{type, combination}]})
assert_received {:all, exists_query}

assert %{from: %{source: %Ecto.SubQuery{query: inner_query}}, combinations: []} = exists_query
assert %{select: %{expr: 1}, limit: %{expr: 1}, distinct: nil} = exists_query
assert [{^type, inner_combination}] = inner_query.combinations
assert inner_query.select.expr != 1
assert inner_query.distinct != nil
assert inner_combination.select.expr != 1
end
end
end

Expand Down
Loading