Skip to content

Commit

Permalink
DRY DB2 limit/offset code
Browse files Browse the repository at this point in the history
  • Loading branch information
nicksieger committed Nov 29, 2010
1 parent 8128419 commit 13986d8
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 13 deletions.
13 changes: 1 addition & 12 deletions lib/arel/visitors/db2.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,7 @@ def visit_Arel_Nodes_SelectStatement o
end

def add_limit_offset(sql, o)
limit, offset = o.limit, o.offset
if limit && !offset
if limit == 1
sql << " FETCH FIRST ROW ONLY"
else
sql << " FETCH FIRST #{limit} ROWS ONLY"
end
elsif limit && offset
sql.gsub!(/SELECT/i, 'SELECT B.* FROM (SELECT A.*, row_number() over () AS internal$rownum FROM (SELECT')
sql << ") A ) B WHERE B.internal$rownum > #{offset} AND B.internal$rownum <= #{limit + offset}"
end
sql
@connection.replace_limit_offset! sql, o.limit, o.offset
end
end
end
Expand Down
6 changes: 5 additions & 1 deletion lib/arjdbc/db2/adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,10 @@ def arel2_visitors
end

def add_limit_offset!(sql, options)
limit, offset = options[:limit], options[:offset]
replace_limit_offset!(sql, options[:limit], options[:offset])
end

def replace_limit_offset!(sql, limit, offset)
if limit && !offset
if limit == 1
sql << " FETCH FIRST ROW ONLY"
Expand All @@ -160,6 +163,7 @@ def add_limit_offset!(sql, options)
sql.gsub!(/SELECT/i, 'SELECT B.* FROM (SELECT A.*, row_number() over () AS internal$rownum FROM (SELECT')
sql << ") A ) B WHERE B.internal$rownum > #{offset} AND B.internal$rownum <= #{sanitize_limit(limit) + offset}"
end
sql
end

def pk_and_sequence_for(table)
Expand Down

0 comments on commit 13986d8

Please sign in to comment.