Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Same as pageinate_by_sql by uses Postgres window function to run the …

…count and query in 1 query instead of 2.
  • Loading branch information...
commit e1906b36a4b69fdfd4f1c73cab46effd5d3fddf1 1 parent f169dcc
Jeff Dwyer authored
Showing with 18 additions and 0 deletions.
  1. +18 −0 lib/will_paginate/finder.rb
18 lib/will_paginate/finder.rb
View
@@ -150,6 +150,24 @@ def paginate_by_sql(sql, options)
end
end
+ # Same as pageinate_by_sql by uses Postgres window function to run the count and query in 1 query
+ # instead of 2.
+ #
+ def self.paginate_by_one_hit_sql(sql, options)
+ WillPaginate::Collection.create(*wp_parse_options(options)) do |pager|
+ query = sanitize_sql(sql.dup)
+ # add limit, offset
+ add_limit! query, :offset => pager.offset, :limit => pager.per_page
+ #add a CTE so we can perform the count in a window function
+ query = "WITH sql_query as(#{query})
+ select count(*) OVER () as total_entries, * from sql_query"
+ # perfom the find
+ pager.replace find_by_sql(query)
+ #populate total_entries
+ pager.total_entries = pager.any? ? pager.first.total_entries : 0
+ end
+ end
+
def respond_to?(method, include_priv = false) #:nodoc:
case method.to_sym
when :paginate, :paginate_by_sql
Please sign in to comment.
Something went wrong with that request. Please try again.