204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
|
# File 'lib/jdbc_adapter/jdbc_mssql.rb', line 204
def add_limit_offset!(sql, options)
limit = options[:limit]
if limit
offset = (options[:offset] || 0).to_i
start_row = offset + 1
end_row = offset + limit.to_i
order = (options[:order] || determine_order_clause(sql))
sql.sub!(/ ORDER BY.*$/i, '')
find_select = /\b(SELECT(?:\s+DISTINCT)?)\b(.*)/i
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
rest = rest_of_query[/FROM/i=~ rest_of_query.. -1]
table_name = get_table_name(sql)
new_order = "#{order}, #{table_name}.id" if order.index("#{table_name}.id").nil?
new_order ||= order
new_sql = "#{select} TOP #{limit} #{rest_of_query} WHERE #{table_name}.id NOT IN (#{select} TOP #{offset} #{table_name}.id #{rest} ORDER BY #{new_order}) ORDER BY #{order} "
sql.replace(new_sql)
end
end
end
|