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 paginate_by_sql for MSSQL adapter #289

Closed
wants to merge 2 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
11 changes: 11 additions & 0 deletions lib/will_paginate/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ def paginate_by_sql(sql, options)
query = sanitize_sql(sql.dup)
original_query = query.dup
oracle = self.connection.adapter_name =~ /^(oracle|oci$)/i
adapter = self.connection.adapter_name

# add limit, offset
if oracle
Expand All @@ -211,6 +212,16 @@ def paginate_by_sql(sql, options)
WHERE rownum <= #{pager.offset + pager.per_page}
) WHERE rnum >= #{pager.offset}
SQL
elsif adapter == "SQLServer"
options_limit = pager.per_page ? "TOP #{pager.per_page}" : ""
options[:order] ||= if order_by = query.match(/ORDER BY(.*$)/i)
order_by[1]
else
query.match('FROM (.+?)\b')[1] + '.id'
end
query.sub!(/ORDER BY.*$/i, '')
query.sub!(/SELECT/i, "SELECT #{options_limit} * FROM ( SELECT ROW_NUMBER() OVER( ORDER BY #{options[:order] } ) AS row_num, ")
query << ") AS t WHERE row_num > #{pager.offset}"
else
query << " LIMIT #{pager.per_page} OFFSET #{pager.offset}"
end
Expand Down