Module: ArJdbc::MsSQL::LimitHelpers::SqlServer2000ReplaceLimitOffset

Included in:
Arel::Visitors::SQLServer2000
Defined in:
lib/arjdbc/mssql/limit_helpers.rb

Class Method Summary collapse

Class Method Details

.replace_limit_offset!(sql, limit, offset, order) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/arjdbc/mssql/limit_helpers.rb', line 17

def replace_limit_offset!(sql, limit, offset, order)
  if limit
    offset ||= 0
    start_row = offset + 1
    end_row = offset + limit.to_i
    find_select = /\b(SELECT(?:\s+DISTINCT)?)\b(.*)/im
    whole, select, rest_of_query = find_select.match(sql).to_a
    if (start_row == 1) && (end_row ==1)
      new_sql = "#{select} TOP 1 #{rest_of_query}"
      sql.replace(new_sql)
    else
      #UGLY
      #KLUDGY?
      #removing out stuff before the FROM...
      rest = rest_of_query[/FROM/i=~ rest_of_query.. -1]
      #need the table name for avoiding amiguity
      table_name = LimitHelpers.get_table_name(sql)
      #I am not sure this will cover all bases.  but all the tests pass
      new_order = "ORDER BY #{order}, #{table_name}.id" if order.index("#{table_name}.id").nil?
      new_order ||= order

      if (rest_of_query.match(/WHERE/).nil?)
        new_sql = "#{select} TOP #{limit} #{rest_of_query} WHERE #{table_name}.id NOT IN (#{select} TOP #{offset} #{table_name}.id #{rest} #{new_order}) #{order} "
      else
        new_sql = "#{select} TOP #{limit} #{rest_of_query} AND #{table_name}.id NOT IN (#{select} TOP #{offset} #{table_name}.id #{rest} #{new_order}) #{order} "
      end

      sql.replace(new_sql)
    end
  end
  sql
end