Permalink
Browse files

Create a select statement helper that does the task of merging source…

…/froms with a lock.
  • Loading branch information...
1 parent cabad3d commit 67e28d452f898ae4b056eca7b64511cf0d6a950b @metaskills metaskills committed Jan 17, 2011
Showing with 16 additions and 9 deletions.
  1. +15 −8 lib/arel/visitors/sqlserver.rb
  2. +1 −1 test/cases/offset_and_limit_test_sqlserver.rb
View
23 lib/arel/visitors/sqlserver.rb
@@ -143,10 +143,7 @@ def visit_Arel_Nodes_SelectStatementWithOutOffset(o, windowed=false)
[ ("SELECT" if !windowed),
(visit(o.limit) if o.limit && !windowed),
(projections.map{ |x| visit(x) }.join(', ')),
- # TODO: [ARel 2.2] Use #from/#source vs. #froms
- # visit(core.source),
- ("FROM #{visit core.froms}" if core.froms),
- (visit(o.lock) if o.lock),
+ (source_with_lock_for_select_statement(o)),
("WHERE #{core.wheres.map{ |x| visit(x) }.join ' AND ' }" unless core.wheres.empty?),
("GROUP BY #{groups.map { |x| visit x }.join ', ' }" unless groups.empty?),
(visit(core.having) if core.having),
@@ -177,10 +174,7 @@ def visit_Arel_Nodes_SelectStatementForComplexCount(o)
(visit(o.limit) if o.limit),
"ROW_NUMBER() OVER (ORDER BY #{orders.map{ |x| visit(x) }.join(', ')}) AS [__rn],",
"1 AS [count]",
- # TODO: [ARel 2.2] Use #from/#source vs. #froms
- # visit(core.source),
- ("FROM #{visit core.froms}" if core.froms),
- (visit(o.lock) if o.lock),
+ (source_with_lock_for_select_statement(o)),
("WHERE #{core.wheres.map{ |x| visit(x) }.join ' AND ' }" unless core.wheres.empty?),
("GROUP BY #{core.groups.map { |x| visit x }.join ', ' }" unless core.groups.empty?),
(visit(core.having) if core.having),
@@ -193,6 +187,19 @@ def visit_Arel_Nodes_SelectStatementForComplexCount(o)
# SQLServer Helpers
+ def source_with_lock_for_select_statement(o)
+ # TODO: [ARel 2.2] Use #from/#source vs. #froms
+ core = o.cores.first
+ source = "FROM #{visit core.froms}" if core.froms
+ if source && o.lock
+ lock = visit o.lock
+ index = source.match(/FROM [\w\[\]\.]+/)[0].length
+ source.insert index, " #{lock}"
+ else
+ source
+ end
+ end
+
def table_from_select_statement(o)
core = o.cores.first
# TODO: [ARel 2.2] Use #from/#source vs. #froms
View
2 test/cases/offset_and_limit_test_sqlserver.rb
@@ -41,7 +41,7 @@ class OffsetAndLimitTestSqlserver < ActiveRecord::TestCase
end
should 'alter SQL to limit number of records returned offset by specified amount' do
- sql = %|SELECT TOP (3) [__rnt].* FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [books].[id] ASC) AS [__rn], [books].* FROM [books] ) AS [__rnt] WHERE [__rnt].[__rn] > 5|
+ sql = %|SELECT TOP (3) [__rnt].* FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [books].[id] ASC) AS [__rn], [books].* FROM [books] ) AS [__rnt] WHERE [__rnt].[__rn] > 5|
assert_sql(sql) { Book.limit(3).offset(5).all }
end

0 comments on commit 67e28d4

Please sign in to comment.