Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #1160: sqlserver_adapter.rb

File sqlserver_adapter.rb, 12.2 kB (added by wayne_hearn@dell.com, 4 years ago)

sqlserver_adapter

Line 
1 require 'active_record/connection_adapters/abstract_adapter'
2
3 # sqlserver_adapter.rb -- ActiveRecord adapter for Microsoft SQL Server
4 #
5 # Author: Joey Gibson <joey@joeygibson.com>
6 # Date:   10/14/2004
7 #
8 # Modifications: DeLynn Berry <delynnb@megastarfinancial.com>
9 # Date: 3/22/2005
10 #
11 # This adapter will ONLY work on Windows systems, since it relies on Win32OLE, which,
12 # to my knowledge, is only available on Window.
13 #
14 # It relies on the ADO support in the DBI module. If you are using the
15 # one-click installer of Ruby, then you already have DBI installed, but
16 # the ADO module is *NOT* installed. You will need to get the latest
17 # source distribution of Ruby-DBI from http://ruby-dbi.sourceforge.net/
18 # unzip it, and copy the file <tt>src/lib/dbd_ado/ADO.rb</tt> to
19 # <tt>X:/Ruby/lib/ruby/site_ruby/1.8/DBD/ADO/ADO.rb</tt> (you will need to create
20 # the ADO directory). Once you've installed that file, you are ready to go.
21 #
22 # Options:
23 #
24 # * <tt>:host</tt> -- Defaults to localhost
25 # * <tt>:username</tt> -- Defaults to sa
26 # * <tt>:password</tt> -- Defaults to nothing
27 # * <tt>:database</tt> -- The name of the database. No default, must be provided.
28 #
29 # I have tested this code on a WindowsXP Pro SP1 system,
30 # ruby 1.8.2 (2004-07-29) [i386-mswin32], SQL Server 2000.
31 #
32 module ActiveRecord
33   class Base
34     def self.sqlserver_connection(config) #:nodoc:
35       require_library_or_gem 'dbi' unless self.class.const_defined?(:DBI)
36      
37       symbolize_strings_in_hash(config)
38
39       host     = config[:host]
40       username = config[:username] ? config[:username].to_s : 'sa'
41       password = config[:password].to_s
42
43       if config.has_key?(:database)
44         database = config[:database]
45       else
46         raise ArgumentError, "No database specified. Missing argument: database."
47       end
48
49       conn = DBI.connect("DBI:ADO:Provider=SQLOLEDB;Data Source=#{host};Initial Catalog=#{database};User Id=#{username};Password=#{password};")
50       conn["AutoCommit"] = true
51
52       ConnectionAdapters::SQLServerAdapter.new(conn, logger)
53     end
54   end
55
56   module ConnectionAdapters
57     class ColumnWithIdentity < Column# :nodoc:
58       attr_reader :identity, :scale
59
60       def initialize(name, default, sql_type = nil, is_identity = false, scale_value = 0)
61         super(name, default, sql_type)
62         @scale = scale_value
63         @identity = is_identity
64       end
65
66       def simplified_type(field_type)
67         case field_type
68           when /int|bigint|smallint|tinyint/i                        : :integer
69           when /float|double|decimal|money|numeric|real|smallmoney/i : @scale == 0 ? :integer : :float
70           when /datetime|smalldatetime/i                             : :datetime
71           when /timestamp/i                                          : :timestamp
72           when /time/i                                               : :time
73           when /text|ntext/i                                         : :text
74           when /binary|image|varbinary/i                             : :binary
75           when /char|nchar|nvarchar|string|varchar/i                 : :string
76           when /bit/i                                                : :boolean
77         end
78       end
79
80       def type_cast(value)
81         return nil if value.nil? || value =~ /^\s*null\s*$/i
82         case type
83         when :string    then value
84         when :integer   then value == true || value == false ? value == true ? '1' : '0' : value.to_i
85         when :float     then value.to_f
86         when :datetime  then cast_to_date_or_time(value)
87         when :timestamp then cast_to_time(value)
88         when :time      then cast_to_time(value)
89         else value
90         end
91       end
92
93       def cast_to_date_or_time(value)
94         return value if value.is_a?(Date)
95         guess_date_or_time (value.is_a?(Time)) ? value : cast_to_time(value)
96       end
97
98       def cast_to_time(value)
99         return value if value.is_a?(Time)
100         time_array = ParseDate.parsedate value
101         time_array[0] ||= 2000; time_array[1] ||= 1; time_array[2] ||= 1;
102         Time.send Base.default_timezone, *time_array
103       end
104
105       def guess_date_or_time(value)
106         (value.hour == 0 and value.min == 0 and value.sec == 0) ?
107           Date.new(value.year, value.month, value.day) : value
108       end
109
110       # These methods will only allow the adapter to insert binary data with a length of 7K or less
111       # because of a SQL Server statement length policy.
112       def string_to_binary(value)
113         value.gsub(/(\r|\n|\0|\x1a)/) do
114           case $1
115             when "\r"
116               "%00"
117             when "\n"
118               "%01"
119             when "\0"
120               "%02"
121             when "\x1a"
122               "%03"
123           end
124         end
125       end
126
127       def binary_to_string(value)
128         value.gsub(/(%00|%01|%02|%03)/) do
129           case $1
130             when "%00"
131               "\r"
132             when "%01"
133               "\n"
134             when "%02\0"
135               "\0"
136             when "%03"
137               "\x1a"
138           end
139         end
140       end
141
142     end
143
144     class SQLServerAdapter < AbstractAdapter
145
146       def native_database_types
147         {
148           :primary_key => "int NOT NULL IDENTITY(1, 1) PRIMARY KEY",
149           :string      => { :name => "varchar(255)" },
150           :text        => { :name => "text(16)" },
151           :integer     => { :name => "int(4)", :limit => 11 },
152           :float       => { :name => "float(8)" },
153           :datetime    => { :name => "datetime(8)" },
154           :timestamp   => { :name => "datetime(8)" },
155           :time        => { :name => "datetime(8)" },
156           :date        => { :name => "datetime(8)" },
157           :binary      => { :name => "image(16)" },
158           :boolean     => { :name => "bit(1)" }
159         }
160       end
161
162       def adapter_name
163         'SQLServer'
164       end
165
166       def select_all(sql, name = nil)
167         add_limit!(sql, nil)
168         select(sql, name)
169       end
170
171       def select_one(sql, name = nil)
172         add_limit!(sql, nil)
173         result = select(sql, name)
174         result.nil? ? nil : result.first
175       end
176
177       def columns(table_name, name = nil)
178         sql = "SELECT COLUMN_NAME as ColName, COLUMN_DEFAULT as DefaultValue, DATA_TYPE as ColType, COL_LENGTH('#{table_name}', COLUMN_NAME) as Length, COLUMNPROPERTY(OBJECT_ID('#{table_name}'), COLUMN_NAME, 'IsIdentity') as IsIdentity, NUMERIC_SCALE as Scale FROM INFORMATION_SCHEMA.columns WHERE TABLE_NAME = '#{table_name}'"
179         result = nil
180         # Uncomment if you want to have the Columns select statment logged.
181         # Personnally, I think it adds unneccessary bloat to the log.
182         # If you do uncomment, make sure to comment the "result" line that follows
183         log(sql, name, @connection) { |conn| result = conn.select_all(sql) }
184         #result = @connection.select_all(sql)
185         columns = []
186         result.each { |field| columns << ColumnWithIdentity.new(field[:ColName], field[:DefaultValue].to_s.gsub!(/[()\']/,"") =~ /null/ ? nil : field[:DefaultValue], "#{field[:ColType]}(#{field[:Length]})", field[:IsIdentity] == 1 ? true : false, field[:Scale]) }
187         columns
188       end
189
190       def insert(sql, name = nil, pk = nil, id_value = nil)
191         begin
192           table_name = get_table_name(sql)
193           col = get_identity_column(table_name)
194           ii_enabled = false
195
196           if col != nil
197             if query_contains_identity_column(sql, col)
198               begin
199                 execute enable_identity_insert(table_name, true)
200                 ii_enabled = true
201               rescue Exception => e
202                 # Coulnd't turn on IDENTITY_INSERT
203               end
204             end
205           end
206           log(sql, name, @connection) do |conn|
207             conn.execute(sql)
208             select_one("SELECT @@IDENTITY AS Ident")["Ident"]
209           end
210         ensure
211           if ii_enabled
212             begin
213               execute enable_identity_insert(table_name, false)
214             rescue Exception => e
215               # Couldn't turn off IDENTITY_INSERT
216             end
217           end
218         end
219       end
220
221       def execute(sql, name = nil)
222         if sql =~ /^INSERT/i
223           insert(sql, name)
224         elsif sql =~ /^UPDATE|DELETE/i
225           log(sql, name, @connection) do |conn|
226             conn.execute(sql)
227             retVal = select_one("SELECT @@ROWCOUNT AS AffectedRows")["AffectedRows"]
228           end
229         else
230           log(sql, name, @connection) do |conn|
231             conn.execute(sql)
232           end
233         end
234       end
235
236       def update(sql, name = nil)
237         execute(sql, name)
238       end
239       alias_method :delete, :update
240
241       def begin_db_transaction
242         begin
243           @connection["AutoCommit"] = false
244         rescue Exception => e
245           @connection["AutoCommit"] = true
246         end
247       end
248
249       def commit_db_transaction
250         begin
251           @connection.commit
252         ensure
253           @connection["AutoCommit"] = true
254         end
255       end
256
257       def rollback_db_transaction
258         begin
259           @connection.rollback
260         ensure
261           @connection["AutoCommit"] = true
262         end
263       end
264
265       def quote(value, column = nil)
266         case value
267           when String               
268             if column && column.type == :binary
269               "'#{quote_string(column.string_to_binary(value))}'"
270             else
271               "'#{quote_string(value)}'"
272             end
273           when NilClass              then "NULL"
274           when TrueClass             then '1'
275           when FalseClass            then '0'
276           when Float, Fixnum, Bignum then value.to_s
277           when Date                  then "'#{value.to_s}'"
278           when Time, DateTime        then "'#{value.strftime("%Y-%m-%d %H:%M:%S")}'"
279           else                            "'#{quote_string(value.to_yaml)}'"
280         end
281       end
282
283       def quote_string(s)
284         s.gsub(/\'/, "''")
285       end
286
287       def quote_column_name(name)
288         "[#{name}]"
289       end
290
291       def add_limit_with_offset!(sql, limit, offset)
292                 order_by = sql.include?("ORDER BY") ? get_order_by(sql.sub(/.*ORDER\sBY./, "")) : nil
293                 sqlString = "SELECT * FROM ( SELECT TOP #{limit} * FROM ( SELECT TOP #{limit + offset}"
294                 if order_by.nil?
295                         sql.gsub!(/SELECT/i, "#{sqlString}")<<" ) AS tmp1 ) AS tmp2"
296                 else
297                         sql.gsub!(/SELECT/i, "#{sqlString}")<<" ) AS tmp1 ORDER BY #{order_by[1]} ) AS tmp2 ORDER BY #{order_by[0]}"
298                 end
299       end
300
301       def add_limit_without_offset!(sql, limit)
302         limit.nil? ? sql : sql.gsub!(/SELECT/i, "SELECT TOP #{limit}")
303       end
304
305       def recreate_database(name)
306         drop_database(name)
307         create_database(name)
308       end
309
310       def drop_database(name)
311         execute "DROP DATABASE #{name}"
312       end
313
314       def create_database(name)
315         execute "CREATE DATABASE #{name}"
316       end
317
318       private
319         def select(sql, name = nil)
320           rows = []
321           log(sql, name, @connection) do |conn|
322             conn.select_all(sql) do |row|
323               record = {}
324               row.column_names.each do |col|
325                 record[col] = row[col]
326               end
327               rows << record
328             end
329           end
330           rows
331         end
332
333         def enable_identity_insert(table_name, enable = true)
334           if has_identity_column(table_name)
335             "SET IDENTITY_INSERT #{table_name} #{enable ? 'ON' : 'OFF'}"
336           end
337         end
338
339         def get_table_name(sql)
340           if sql =~ /into\s*([^\s]+)\s*/i or
341               sql =~ /update\s*([^\s]+)\s*/i
342             $1
343           else
344             nil
345           end
346         end
347
348         def has_identity_column(table_name)
349           return get_identity_column(table_name) != nil
350         end
351
352         def get_identity_column(table_name)
353           if not @table_columns
354             @table_columns = {}
355           end
356
357           if @table_columns[table_name] == nil
358             @table_columns[table_name] = columns(table_name)
359           end
360
361           @table_columns[table_name].each do |col|
362             return col.name if col.identity
363           end
364
365           return nil
366         end
367
368         def query_contains_identity_column(sql, col)
369           return sql =~ /[\[.,]\s*#{col}/
370         end
371
372         def get_order_by(sql)
373           return sql, sql.gsub(/\s*DESC\s*/, "").gsub(/\s*ASC\s*/, " DESC")
374         end
375
376         def get_offset_amount(limit)
377           limit = limit.gsub!(/.OFFSET./i, ",").split(',')
378           return limit[0].to_i, limit[0].to_i+limit[1].to_i
379         end
380     end
381   end
382 end