Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Fix paginate_by_sql for MSSQL adapter #289

Open
wants to merge 2 commits into from

3 participants

@denniskis

paginate_by_sql adds LIMIT option which is not working with MSSQL.

denniskis added some commits
@denniskis denniskis Fix paginate_by_sql for MSSQL adapter
LIMIT option is not working with MSSQL.
e6e9414
@denniskis denniskis MSSQL support
Fix mssql support for paginate_by_sql
c220911
@viegasfh

Same holds true for Firebird SQL. I modifed active_record.rb as follows:

      oracle = self.connection.adapter_name =~ /^(oracle|oci$)/i
      firebird = self.connection.adapter_name == 'Rubyfb'

      # add limit, offset
      if oracle
        query = <<-SQL
          SELECT * FROM (
            SELECT rownum rnum, a.* FROM (#{query}) a
            WHERE rownum <= #{pager.offset + pager.per_page}
          ) WHERE rnum >= #{pager.offset}
        SQL
      elsif firebird
        query << " ROWS #{pager.offset+1} TO #{pager.per_page+pager.offset}"
      else
        query << " LIMIT #{pager.per_page} OFFSET #{pager.offset}"
      end

This will work with Rubyfb driver or Firebird, and it only supports Firebird 2.0+

@tflanitzer

The problem reported by denniskis still exists after 2 years. Merging this into a near future release would be highly appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Feb 4, 2013
  1. @denniskis

    Fix paginate_by_sql for MSSQL adapter

    denniskis authored
    LIMIT option is not working with MSSQL.
Commits on Apr 10, 2013
  1. @denniskis

    MSSQL support

    denniskis authored
    Fix mssql support for paginate_by_sql
This page is out of date. Refresh to see the latest.
Showing with 11 additions and 0 deletions.
  1. +11 −0 lib/will_paginate/active_record.rb
View
11 lib/will_paginate/active_record.rb
@@ -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
@@ -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
Something went wrong with that request. Please try again.