1 # Common methods for handling TSQL databases.
4 def modify_types(tp) #:nodoc:
5 tp[:primary_key] = "int NOT NULL IDENTITY(1, 1) PRIMARY KEY"
6 tp[:integer][:limit] = nil
7 tp[:boolean] = {:name => "bit"}
8 tp[:binary] = { :name => "image"}
12 def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
13 limit = nil if %w(text binary).include? type.to_s
14 return 'uniqueidentifier' if (type.to_s == 'uniqueidentifier')
15 return super unless type.to_s == 'integer'
17 if limit.nil? || limit == 4
28 def add_limit_offset!(sql, options)
29 if options[:limit] and options[:offset]
30 total_rows = select_all("SELECT count(*) as TotalRows from (#{sql.gsub(/\bSELECT(\s+DISTINCT)?\b/i, "SELECT\\1 TOP 1000000000")}) tally")[0]["TotalRows"].to_i
31 if (options[:limit] + options[:offset]) >= total_rows
32 options[:limit] = (total_rows - options[:offset] >= 0) ? (total_rows - options[:offset]) : 0
34 sql.sub!(/^\s*SELECT(\s+DISTINCT)?/i, "SELECT * FROM (SELECT TOP #{options[:limit]} * FROM (SELECT\\1 TOP #{options[:limit] + options[:offset]} ")
37 options[:order] = options[:order].split(',').map do |field|
38 parts = field.split(" ")
40 if sql =~ /\.\[/ and tc =~ /\./ # if column quoting used in query
41 tc.gsub!(/\./, '\\.\\[')
44 if sql =~ /#{tc} AS (t\d_r\d\d?)/
46 elsif parts[0] =~ /\w+\.(\w+)/
51 sql << " ORDER BY #{change_order_direction(options[:order])}) AS tmp2 ORDER BY #{options[:order]}"
55 elsif sql !~ /^\s*SELECT (@@|COUNT\()/i
56 sql.sub!(/^\s*SELECT(\s+DISTINCT)?/i) do
57 "SELECT#{$1} TOP #{options[:limit]}"
58 end unless options[:limit].nil?