Skip to content

Commit

Permalink
feat(Ecto.Repo): allow aggregating over *
Browse files Browse the repository at this point in the history
This is done to provide similar API to `Ecto.Query.API.count/0` as
counting over `*` is faster in some DB than counting over column, even
when column is `NOT NULL` and indexed.

Close elixir-ecto#3175
  • Loading branch information
hauleth committed Dec 2, 2019
1 parent b17168d commit 37f03bc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/ecto/repo/queryable.ex
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,26 @@ defmodule Ecto.Repo.Queryable do
Query.where(queryable, [], ^Enum.to_list(clauses))
end

defp query_for_aggregate(queryable, aggregate, :*) do
query = %{Queryable.to_query(queryable) | preloads: [], assocs: []}
query =
case query do
%{group_bys: [_ | _]} ->
raise Ecto.QueryError, message: "cannot aggregate on query with group_by", query: query

%{distinct: nil, limit: nil, offset: nil} ->
%{query | order_bys: []}

_ ->
query
|> Query.subquery()
|> Queryable.Ecto.SubQuery.to_query()
end

select = %SelectExpr{expr: {aggregate, [], []}, file: __ENV__.file, line: __ENV__.line}
%{query | select: select}
end

defp query_for_aggregate(queryable, aggregate, field) do
query = %{Queryable.to_query(queryable) | preloads: [], assocs: []}
ast = field(0, field)
Expand Down
4 changes: 4 additions & 0 deletions test/ecto/repo_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,10 @@ defmodule Ecto.RepoTest do
TestRepo.aggregate(MySchema, :count, :id)
assert_received {:all, query}
assert inspect(query) == "#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, select: count(m0.id)>"

TestRepo.aggregate(MySchema, :count, :*)
assert_received {:all, query}
assert inspect(query) == "#Ecto.Query<from m0 in Ecto.RepoTest.MySchema, select: count()>"
end

test "aggregates handle a prefix option" do
Expand Down

0 comments on commit 37f03bc

Please sign in to comment.