elixirdrops / kerosene

Pagination for Ecto and Pheonix.
https://github.com/elixirdrops/kerosene
MIT License
231 stars 39 forks source link

Add limit to row_count function #61

Closed alli5723 closed 2 years ago

alli5723 commented 2 years ago

I have a query that took ~ 6 seconds to resolve because of the time it takes for the library to resolve the following line of code.

Since we are only expecting 1 row of result, I noticed adding limit(1) brings the result time 652ms instead.

defp total_count(query = %{group_bys: [_|_]}), do: total_row_count(query)
  defp total_count(query = %{from: %{source: {_, nil}}}), do: total_row_count(query)

  defp total_count(query) do
    primary_key = get_primary_key(query)
    query
    |> exclude(:select)
    |> select([i], count(field(i, ^primary_key), :distinct))
+    |> limit(1)
  end

  defp total_row_count(query) do
    query
    |> subquery()
    |> select(count("*"))
+    |> limit(1)
  end