Skip to content
Open
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
19 changes: 18 additions & 1 deletion lib/scrivener/paginater/ecto/query.ex
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,30 @@ defimpl Scrivener.Paginater, for: Ecto.Query do
|> exclude(:order_by)
|> exclude(:select)
|> select([{x, source_index}], struct(x, ^[field]))
|> maybe_limit_by_max_total_entries(options)
|> subquery()
|> select(count("*"))
|> repo.one(options)
end

defp aggregate(query, repo, options) do
repo.aggregate(query, :count, options)
query
|> maybe_limit_by_max_total_entries(options)
|> repo.aggregate(:count, options)
end

defp maybe_limit_by_max_total_entries(query, options) do
case Keyword.get(options, :max_total_entries) do
nil ->
query

max_total_entries when is_integer(max_total_entries) and max_total_entries > 0 ->
limit(query, ^max_total_entries)

otherwise ->
raise ArgumentError,
"max_total_entries must be a positive integer, got: #{inspect(otherwise)}"
end
end

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

test "will respect max_total_entries passed to paginate" do
create_posts()

page =
Post
|> Post.published()
|> Scrivener.Ecto.Repo.paginate(options: [max_total_entries: 4])

assert length(page.entries) == 5
assert page.total_entries == 4
end

test "will respect max_total_entries passed to paginate 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, count("*")})
|> Scrivener.Ecto.Repo.paginate(options: [max_total_entries: 1])

assert length(page.entries) == 2
assert page.total_entries == 1
end

test "will use total_pages if page_numer is too large" do
posts = create_posts()

Expand Down