Skip to content

Commit

Permalink
Merge pull request mojotech#39 from BKStephens/master
Browse files Browse the repository at this point in the history
Fix total entries errors for queries with group by clause
  • Loading branch information
drewolson authored Aug 17, 2017
2 parents 175aa2f + f9ec225 commit 8ec0a6a
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
26 changes: 25 additions & 1 deletion lib/scrivener/paginater/ecto/query.ex
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,39 @@ defimpl Scrivener.Paginater, for: Ecto.Query do
total_entries =
query
|> exclude(:preload)
|> exclude(:select)
|> exclude(:order_by)
|> prepare_select
|> subquery
|> select(count("*"))
|> repo.one(caller: caller)

total_entries || 0
end

defp prepare_select(query) do
try do
query
|> subquery
|> select(count("*"))
|> Ecto.Query.Planner.prepare_sources(_adapter = nil)

query
rescue
e in Ecto.SubQueryError ->
case e do
%{
exception: %{
message: "subquery must select a source (t), a field (t.field) or a map" <> _rest
}
} ->
query
|> exclude(:select)
_ ->
raise e
end
end
end

defp total_pages(0, _), do: 1

defp total_pages(total_entries, page_size) do
Expand Down
25 changes: 25 additions & 0 deletions test/scrivener/paginator/ecto/query_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,31 @@ defmodule Scrivener.Paginator.Ecto.QueryTest do
assert page.total_entries == 7
end

test "can be used with a group by clause on field other than id" do
create_posts()

page =
Post
|> group_by([p], p.body)
|> select([p], (p.body))
|> Scrivener.Ecto.Repo.paginate

assert page.total_entries == 7
end

test "can be used with a group by clause on field on joined table" do
create_posts()

page =
Post
|> join(:inner, [p], c in assoc(p, :comments))
|> group_by([p, c], c.body)
|> select([p, c], (c.body))
|> Scrivener.Ecto.Repo.paginate

assert page.total_entries == 2
end

test "can be provided a Scrivener.Config directly" do
posts = create_posts()

Expand Down

0 comments on commit 8ec0a6a

Please sign in to comment.