Skip to content

Commit

Permalink
Fix total entries when query has combinations
Browse files Browse the repository at this point in the history
  • Loading branch information
oo6 authored and cpjolicoeur committed Sep 26, 2024
1 parent d677da2 commit e394a05
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 25 deletions.
39 changes: 14 additions & 25 deletions lib/scrivener/paginater/ecto/query.ex
Original file line number Diff line number Diff line change
Expand Up @@ -47,21 +47,7 @@ defimpl Scrivener.Paginater, for: Ecto.Query do

defp total_entries(query, repo, caller, options) do
prefix = options[:prefix]

total_entries =
query
|> exclude(:preload)
|> exclude(:order_by)
|> aggregate()
|> one(repo, caller, prefix)

total_entries || 0
end

defp aggregate(%{distinct: %{expr: expr}} = query) when expr == true or is_list(expr) do
query
|> exclude(:select)
|> count()
aggregate(query, repo, caller, prefix)
end

defp aggregate(
Expand All @@ -74,24 +60,27 @@ defimpl Scrivener.Paginater, for: Ecto.Query do
}
| _
]
} = query
} = query,
repo,
caller,
prefix
) do
query
|> exclude(:preload)
|> exclude(:order_by)
|> exclude(:select)
|> select([{x, source_index}], struct(x, ^[field]))
|> count()
|> subquery()
|> select(count("*"))
|> one(repo, caller, prefix)
end

defp aggregate(query) do
query
|> exclude(:select)
|> select(count("*"))
defp aggregate(query, repo, caller, nil) do
repo.aggregate(query, :count, caller: caller)
end

defp count(query) do
query
|> subquery
|> select(count("*"))
defp aggregate(query, repo, caller, prefix) do
repo.aggregate(query, :count, caller: caller, prefix: prefix)
end

defp total_pages(0, _), do: 1
Expand Down
12 changes: 12 additions & 0 deletions test/scrivener/paginator/ecto/query_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,18 @@ defmodule Scrivener.Paginator.Ecto.QueryTest do
assert page.total_entries == 2
end

test "can be used with combinations" do
create_posts()

page =
Post
|> Post.published()
|> union(^Post.unpublished(Post))
|> Scrivener.Ecto.Repo.paginate()

assert page.total_entries == 7
end

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

Expand Down

0 comments on commit e394a05

Please sign in to comment.