Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix aggregate for combination queries #100

Closed
wants to merge 7 commits into from
Closed
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
30 changes: 29 additions & 1 deletion lib/scrivener/paginater/ecto/query.ex
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,29 @@ defimpl Scrivener.Paginater, for: Ecto.Query do
|> all(repo, caller, prefix)
end

defp total_entries(%{combinations: [_|_]} = query, repo, caller, options) do
prefix = options[:prefix]

simpler_query =
query
|> exclude(:preload)
|> exclude(:order_by)

{sql_query, params} = Ecto.Adapters.SQL.to_sql(:all, repo, simpler_query)
count_query = "select count(*) from (#{sql_query}) as count_me"
%Postgrex.Result{
columns: ["count"],
command: :select,
num_rows: 1,
rows: [[total_entries]]
}
= Ecto.Adapters.SQL.query!(
repo, "select count(*) from (#{sql_query}) as count_me", params
)

total_entries || 0
end

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

Expand All @@ -60,10 +83,15 @@ defimpl Scrivener.Paginater, for: Ecto.Query do

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

defp aggregate(%{order_bys: %{expr: expr}} = query) do
query
|> exclude(:preload)
|> select(count("*"))
end

defp aggregate(
%{
group_bys: [
Expand Down