]> source.dussan.org Git - sonarqube.git/blob
7562132ab53dbbe7578a391deab473c7d2879992
[sonarqube.git] /
1 require 'arel/visitors/compat'
2
3 module Arel
4   module Visitors
5     class SQLServer < Arel::Visitors::ToSql
6       include ArJdbc::MsSQL::LimitHelpers::SqlServerReplaceLimitOffset
7
8       def select_count? o
9         sel = o.cores.length == 1 && o.cores.first
10         projections = sel && sel.projections.length == 1 && sel.projections
11         projections && Arel::Nodes::Count === projections.first
12       end
13
14       # Need to mimic the subquery logic in ARel 1.x for select count with limit
15       # See arel/engines/sql/compilers/mssql_compiler.rb for details
16       def visit_Arel_Nodes_SelectStatement o
17         order = "ORDER BY #{o.orders.map { |x| visit x }.join(', ')}" unless o.orders.empty?
18         if o.limit
19           if select_count?(o)
20             subquery = true
21             sql = o.cores.map do |x|
22               x = x.dup
23               x.projections = [Arel::Nodes::SqlLiteral.new("*")]
24               visit_Arel_Nodes_SelectCore x
25             end.join
26           else
27             sql = o.cores.map { |x| visit_Arel_Nodes_SelectCore x }.join
28           end
29
30           order ||= "ORDER BY #{@connection.determine_order_clause(sql)}"
31           replace_limit_offset!(sql, limit_for(o.limit).to_i, o.offset && o.offset.value.to_i, order)
32           sql = "SELECT COUNT(*) AS count_id FROM (#{sql}) AS subquery" if subquery
33         else
34           sql = super
35         end
36         sql
37       end
38     end
39
40     class SQLServer2000 < SQLServer
41       include ArJdbc::MsSQL::LimitHelpers::SqlServer2000ReplaceLimitOffset
42     end
43   end
44 end