Module: TSqlMethods

Included in:
JdbcSpec::CacheDB, JdbcSpec::MsSQL
Defined in:
lib/jdbc_adapter/tsql_helper.rb

Overview

Common methods for handling TSQL databases.

Instance Method Summary collapse

Instance Method Details

#add_limit_offset!(sql, options) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/jdbc_adapter/tsql_helper.rb', line 26

def add_limit_offset!(sql, options)
  if options[:limit] and options[:offset]
    total_query = sql.gsub(/\bSELECT(\s+DISTINCT)?\b/i, "SELECT\\1 TOP 1000000000")
    if options[:order] && sql =~ /DISTINCT/
      # SELECT DISTINCT cannot have order by unless order by appears in select,
      # You also cannot do a select distinct/order by in a subselect, so we need to
      # just chop the order by to prevent an error generating TotalRows
      total_query.gsub!(/ORDER BY #{options[:order]}/, '')
      sql.gsub!(/\bSELECT\s+(.*)\s+FROM\b/i, "SELECT \\1,#{options[:order].split.first} FROM")
    end
    total_rows = select_all("SELECT count(*) as TotalRows from (#{total_query}) tally")[0]["TotalRows"].to_i
    if (options[:limit] + options[:offset]) >= total_rows
      options[:limit] = (total_rows - options[:offset] >= 0) ? (total_rows - options[:offset]) : 0
    end
    sql.sub!(/^\s*SELECT(\s+DISTINCT)?/i, "SELECT * FROM (SELECT TOP #{options[:limit]} * FROM (SELECT\\1 TOP #{options[:limit] + options[:offset]} ")
    sql << ") AS tmp1"
    if options[:order]
      options[:order] = options[:order].split(',').map do |field|
        parts = field.split(" ")
        if options[:order] && sql =~ /DISTINCT/
          tc = parts[1]
        else
          tc = parts[0]
        end
        if sql =~ /\.\[/ and tc =~ /\./ # if column quoting used in query
          tc.gsub!(/\./, '\\.\\[')
          tc << '\\]'
        end
        if sql =~ /#{tc} AS (t\d_r\d\d?)/
          parts[0] = $1
        end
        parts.join(' ')
      end.join(', ')
      sql << " ) AS tmp2"
    else
      sql << " ) AS tmp2"
    end
  elsif sql !~ /^\s*SELECT (@@|COUNT\()/i
    sql.sub!(/^\s*SELECT(\s+DISTINCT)?/i) do
      "SELECT#{$1} TOP #{options[:limit]}"
    end unless options[:limit].nil?
  end
end

#modify_types(tp) ⇒ Object

:nodoc:



4
5
6
7
8
9
10
# File 'lib/jdbc_adapter/tsql_helper.rb', line 4

def modify_types(tp) #:nodoc:
  tp[:primary_key] = "int NOT NULL IDENTITY(1, 1) PRIMARY KEY"
  tp[:integer][:limit] = nil
  tp[:boolean] = {:name => "bit"}
  tp[:binary] = { :name => "image"}
  tp
end

#type_to_sql(type, limit = nil, precision = nil, scale = nil) ⇒ Object

:nodoc:



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/jdbc_adapter/tsql_helper.rb', line 12

def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
  return super unless type.to_s == 'integer'
  
  if limit.nil? || limit == 4
    'int'
  elsif limit == 2
    'smallint'
  elsif limit == 1
    'tinyint'
  else
    'bigint'
  end
end