Skip to content

Commit

Permalink
Same as pageinate_by_sql by uses Postgres window function to run the …
Browse files Browse the repository at this point in the history
…count and query in 1 query instead of 2.
  • Loading branch information
jdwyah committed Mar 8, 2011
1 parent f169dcc commit e1906b3
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/will_paginate/finder.rb
Expand Up @@ -150,6 +150,24 @@ def paginate_by_sql(sql, options)
end end
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: def respond_to?(method, include_priv = false) #:nodoc:
case method.to_sym case method.to_sym
when :paginate, :paginate_by_sql when :paginate, :paginate_by_sql
Expand Down

0 comments on commit e1906b3

Please sign in to comment.