1
|
require 'active_record/connection_adapters/abstract_adapter'
|
2
|
|
3
|
require 'bigdecimal'
|
4
|
require 'bigdecimal/util'
|
5
|
|
6
|
# sqlserver_adapter.rb -- ActiveRecord adapter for Microsoft SQL Server
|
7
|
#
|
8
|
# Author: Joey Gibson <joey@joeygibson.com>
|
9
|
# Date: 10/14/2004
|
10
|
#
|
11
|
# Modifications: DeLynn Berry <delynnb@megastarfinancial.com>
|
12
|
# Date: 3/22/2005
|
13
|
#
|
14
|
# Modifications (ODBC): Mark Imbriaco <mark.imbriaco@pobox.com>
|
15
|
# Date: 6/26/2005
|
16
|
|
17
|
# Modifications (Migrations): Tom Ward <tom@popdog.net>
|
18
|
# Date: 27/10/2005
|
19
|
#
|
20
|
# Modifications (Numerous fixes as maintainer): Ryan Tomayko <rtomayko@gmail.com>
|
21
|
# Date: Up to July 2006
|
22
|
|
23
|
# Current maintainer: Tom Ward <tom@popdog.net>
|
24
|
|
25
|
module ActiveRecord
|
26
|
class Base
|
27
|
def self.sqlserver_connection(config) #:nodoc:
|
28
|
require_library_or_gem 'dbi' unless self.class.const_defined?(:DBI)
|
29
|
|
30
|
config = config.symbolize_keys
|
31
|
|
32
|
mode = config[:mode] ? config[:mode].to_s.upcase : 'ADO'
|
33
|
username = config[:username] ? config[:username].to_s : 'sa'
|
34
|
password = config[:password] ? config[:password].to_s : ''
|
35
|
autocommit = config.key?(:autocommit) ? config[:autocommit] : true
|
36
|
if mode == "ODBC"
|
37
|
raise ArgumentError, "Missing DSN. Argument ':dsn' must be set in order for this adapter to work." unless config.has_key?(:dsn)
|
38
|
dsn = config[:dsn]
|
39
|
driver_url = "DBI:ODBC:#{dsn}"
|
40
|
else
|
41
|
raise ArgumentError, "Missing Database. Argument ':database' must be set in order for this adapter to work." unless config.has_key?(:database)
|
42
|
database = config[:database]
|
43
|
host = config[:host] ? config[:host].to_s : 'localhost'
|
44
|
unless config[:trusted_connection]
|
45
|
driver_url = "DBI:ADO:Provider=SQLOLEDB;Data Source=#{host};Initial Catalog=#{database};User Id=#{username};Password=#{password};"
|
46
|
else
|
47
|
driver_url = "DBI:ADO:Provider=SQLOLEDB;Data Source=#{host};Initial Catalog=#{database};Trusted_Connection=Yes;"
|
48
|
end
|
49
|
end
|
50
|
conn = DBI.connect(driver_url, username, password)
|
51
|
conn["AutoCommit"] = autocommit
|
52
|
ConnectionAdapters::SQLServerAdapter.new(conn, logger, [driver_url, username, password])
|
53
|
end
|
54
|
end # class Base
|
55
|
|
56
|
module ConnectionAdapters
|
57
|
class SQLServerColumn < Column# :nodoc:
|
58
|
attr_reader :identity, :is_special
|
59
|
|
60
|
def initialize(name, default, sql_type = nil, identity = false, null = true) # TODO: check ok to remove scale_value = 0
|
61
|
super(name, default, sql_type, null)
|
62
|
@identity = identity
|
63
|
@is_special = sql_type =~ /text|ntext|image/i
|
64
|
# TODO: check ok to remove @scale = scale_value
|
65
|
# SQL Server only supports limits on *char and float types
|
66
|
@limit = nil unless @type == :string
|
67
|
end
|
68
|
|
69
|
def simplified_type(field_type)
|
70
|
case field_type
|
71
|
when /money/i then :decimal
|
72
|
when /image/i then :binary
|
73
|
when /bit/i then :boolean
|
74
|
when /uniqueidentifier/i then :string
|
75
|
else super
|
76
|
end
|
77
|
end
|
78
|
|
79
|
def type_cast(value)
|
80
|
return nil if value.nil?
|
81
|
case type
|
82
|
when :datetime then cast_to_datetime(value)
|
83
|
when :timestamp then cast_to_time(value)
|
84
|
when :time then cast_to_time(value)
|
85
|
when :date then cast_to_datetime(value)
|
86
|
when :boolean then value == true or (value =~ /^t(rue)?$/i) == 0 or value.to_s == '1'
|
87
|
else super
|
88
|
end
|
89
|
end
|
90
|
|
91
|
def cast_to_time(value)
|
92
|
return value if value.is_a?(Time)
|
93
|
time_array = ParseDate.parsedate(value)
|
94
|
Time.send(Base.default_timezone, *time_array) rescue nil
|
95
|
end
|
96
|
|
97
|
def cast_to_datetime(value)
|
98
|
return value.to_time if value.is_a?(DBI::Timestamp)
|
99
|
|
100
|
if value.is_a?(Time)
|
101
|
if value.year != 0 and value.month != 0 and value.day != 0
|
102
|
return value
|
103
|
else
|
104
|
return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil
|
105
|
end
|
106
|
end
|
107
|
|
108
|
if value.is_a?(DateTime)
|
109
|
return Time.mktime(value.year, value.mon, value.day, value.hour, value.min, value.sec)
|
110
|
end
|
111
|
|
112
|
return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil
|
113
|
value
|
114
|
end
|
115
|
|
116
|
# TODO: Find less hack way to convert DateTime objects into Times
|
117
|
|
118
|
def self.string_to_time(value)
|
119
|
if value.is_a?(DateTime)
|
120
|
return Time.mktime(value.year, value.mon, value.day, value.hour, value.min, value.sec)
|
121
|
else
|
122
|
super
|
123
|
end
|
124
|
end
|
125
|
|
126
|
# These methods will only allow the adapter to insert binary data with a length of 7K or less
|
127
|
# because of a SQL Server statement length policy.
|
128
|
def self.string_to_binary(value)
|
129
|
value.gsub(/(\r|\n|\0|\x1a)/) do
|
130
|
case $1
|
131
|
when "\r" then "%00"
|
132
|
when "\n" then "%01"
|
133
|
when "\0" then "%02"
|
134
|
when "\x1a" then "%03"
|
135
|
end
|
136
|
end
|
137
|
end
|
138
|
|
139
|
def self.binary_to_string(value)
|
140
|
value.gsub(/(%00|%01|%02|%03)/) do
|
141
|
case $1
|
142
|
when "%00" then "\r"
|
143
|
when "%01" then "\n"
|
144
|
when "%02\0" then "\0"
|
145
|
when "%03" then "\x1a"
|
146
|
end
|
147
|
end
|
148
|
end
|
149
|
end
|
150
|
|
151
|
# In ADO mode, this adapter will ONLY work on Windows systems,
|
152
|
# since it relies on Win32OLE, which, to my knowledge, is only
|
153
|
# available on Windows.
|
154
|
#
|
155
|
# This mode also relies on the ADO support in the DBI module. If you are using the
|
156
|
# one-click installer of Ruby, then you already have DBI installed, but
|
157
|
# the ADO module is *NOT* installed. You will need to get the latest
|
158
|
# source distribution of Ruby-DBI from http://ruby-dbi.sourceforge.net/
|
159
|
# unzip it, and copy the file
|
160
|
# <tt>src/lib/dbd_ado/ADO.rb</tt>
|
161
|
# to
|
162
|
# <tt>X:/Ruby/lib/ruby/site_ruby/1.8/DBD/ADO/ADO.rb</tt>
|
163
|
# (you will more than likely need to create the ADO directory).
|
164
|
# Once you've installed that file, you are ready to go.
|
165
|
#
|
166
|
# In ODBC mode, the adapter requires the ODBC support in the DBI module which requires
|
167
|
# the Ruby ODBC module. Ruby ODBC 0.996 was used in development and testing,
|
168
|
# and it is available at http://www.ch-werner.de/rubyodbc/
|
169
|
#
|
170
|
# Options:
|
171
|
#
|
172
|
# * <tt>:mode</tt> -- ADO or ODBC. Defaults to ADO.
|
173
|
# * <tt>:username</tt> -- Defaults to sa.
|
174
|
# * <tt>:password</tt> -- Defaults to empty string.
|
175
|
#
|
176
|
# ADO specific options:
|
177
|
#
|
178
|
# * <tt>:host</tt> -- Defaults to localhost.
|
179
|
# * <tt>:database</tt> -- The name of the database. No default, must be provided.
|
180
|
#
|
181
|
# ODBC specific options:
|
182
|
#
|
183
|
# * <tt>:dsn</tt> -- Defaults to nothing.
|
184
|
#
|
185
|
# ADO code tested on Windows 2000 and higher systems,
|
186
|
# running ruby 1.8.2 (2004-07-29) [i386-mswin32], and SQL Server 2000 SP3.
|
187
|
#
|
188
|
# ODBC code tested on a Fedora Core 4 system, running FreeTDS 0.63,
|
189
|
# unixODBC 2.2.11, Ruby ODBC 0.996, Ruby DBI 0.0.23 and Ruby 1.8.2.
|
190
|
# [Linux strongmad 2.6.11-1.1369_FC4 #1 Thu Jun 2 22:55:56 EDT 2005 i686 i686 i386 GNU/Linux]
|
191
|
class SQLServerAdapter < AbstractAdapter
|
192
|
|
193
|
def initialize(connection, logger, connection_options=nil)
|
194
|
super(connection, logger)
|
195
|
@connection_options = connection_options
|
196
|
end
|
197
|
|
198
|
def native_database_types
|
199
|
{
|
200
|
:primary_key => "int NOT NULL IDENTITY(1, 1) PRIMARY KEY",
|
201
|
:string => { :name => "varchar", :limit => 255 },
|
202
|
:text => { :name => "text" },
|
203
|
:integer => { :name => "int" },
|
204
|
:float => { :name => "float" },
|
205
|
:decimal => { :name => "decimal" },
|
206
|
:datetime => { :name => "datetime" },
|
207
|
:timestamp => { :name => "datetime" },
|
208
|
:time => { :name => "datetime" },
|
209
|
:date => { :name => "datetime" },
|
210
|
:binary => { :name => "image"},
|
211
|
:boolean => { :name => "bit"}
|
212
|
}
|
213
|
end
|
214
|
|
215
|
def adapter_name
|
216
|
'SQLServer'
|
217
|
end
|
218
|
|
219
|
def supports_migrations? #:nodoc:
|
220
|
true
|
221
|
end
|
222
|
|
223
|
def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
|
224
|
return super unless type.to_s == 'integer'
|
225
|
|
226
|
if limit.nil? || limit == 4
|
227
|
'integer'
|
228
|
elsif limit < 4
|
229
|
'smallint'
|
230
|
else
|
231
|
'bigint'
|
232
|
end
|
233
|
end
|
234
|
|
235
|
# CONNECTION MANAGEMENT ====================================#
|
236
|
|
237
|
# Returns true if the connection is active.
|
238
|
def active?
|
239
|
@connection.execute("SELECT 1").finish
|
240
|
true
|
241
|
rescue DBI::DatabaseError, DBI::InterfaceError
|
242
|
false
|
243
|
end
|
244
|
|
245
|
# Reconnects to the database, returns false if no connection could be made.
|
246
|
def reconnect!
|
247
|
disconnect!
|
248
|
@connection = DBI.connect(*@connection_options)
|
249
|
rescue DBI::DatabaseError => e
|
250
|
@logger.warn "#{adapter_name} reconnection failed: #{e.message}" if @logger
|
251
|
false
|
252
|
end
|
253
|
|
254
|
# Disconnects from the database
|
255
|
|
256
|
def disconnect!
|
257
|
@connection.disconnect rescue nil
|
258
|
end
|
259
|
|
260
|
def columns(table_name, name = nil)
|
261
|
return [] if table_name.blank?
|
262
|
table_name = table_name.to_s if table_name.is_a?(Symbol)
|
263
|
table_name = table_name.split('.')[-1] unless table_name.nil?
|
264
|
table_name = table_name.gsub(/[\[\]]/, '')
|
265
|
sql = %Q{
|
266
|
SELECT
|
267
|
cols.COLUMN_NAME as ColName,
|
268
|
cols.COLUMN_DEFAULT as DefaultValue,
|
269
|
cols.NUMERIC_SCALE as numeric_scale,
|
270
|
cols.NUMERIC_PRECISION as numeric_precision,
|
271
|
cols.DATA_TYPE as ColType,
|
272
|
cols.IS_NULLABLE As IsNullable,
|
273
|
COL_LENGTH(cols.TABLE_NAME, cols.COLUMN_NAME) as Length,
|
274
|
COLUMNPROPERTY(OBJECT_ID(cols.TABLE_NAME), cols.COLUMN_NAME, 'IsIdentity') as IsIdentity,
|
275
|
cols.NUMERIC_SCALE as Scale
|
276
|
FROM INFORMATION_SCHEMA.COLUMNS cols
|
277
|
WHERE cols.TABLE_NAME = '#{table_name}'
|
278
|
}
|
279
|
# Comment out if you want to have the Columns select statment logged.
|
280
|
# Personally, I think it adds unnecessary bloat to the log.
|
281
|
# If you do comment it out, make sure to un-comment the "result" line that follows
|
282
|
result = log(sql, name) { @connection.select_all(sql) }
|
283
|
#result = @connection.select_all(sql)
|
284
|
columns = []
|
285
|
result.each do |field|
|
286
|
default = field[:DefaultValue].to_s.gsub!(/[()\']/,"") =~ /null|NULL/ ? nil : field[:DefaultValue]
|
287
|
if field[:ColType] =~ /numeric|decimal/i
|
288
|
type = "#{field[:ColType]}(#{field[:numeric_precision]},#{field[:numeric_scale]})"
|
289
|
else
|
290
|
type = "#{field[:ColType]}(#{field[:Length]})"
|
291
|
end
|
292
|
is_identity = field[:IsIdentity] == 1
|
293
|
is_nullable = field[:IsNullable] == 'YES'
|
294
|
columns << SQLServerColumn.new(field[:ColName], default, type, is_identity, is_nullable)
|
295
|
end
|
296
|
columns
|
297
|
end
|
298
|
|
299
|
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
|
300
|
execute(sql, name)
|
301
|
id_value || select_one("SELECT @@IDENTITY AS Ident")["Ident"]
|
302
|
end
|
303
|
|
304
|
def update(sql, name = nil)
|
305
|
execute(sql, name) do |handle|
|
306
|
handle.rows
|
307
|
end || select_one("SELECT @@ROWCOUNT AS AffectedRows")["AffectedRows"]
|
308
|
end
|
309
|
|
310
|
alias_method :delete, :update
|
311
|
|
312
|
def execute(sql, name = nil)
|
313
|
if sql =~ /^\s*INSERT/i && (table_name = query_requires_identity_insert?(sql))
|
314
|
log(sql, name) do
|
315
|
with_identity_insert_enabled(table_name) do
|
316
|
@connection.execute(sql) do |handle|
|
317
|
yield(handle) if block_given?
|
318
|
end
|
319
|
end
|
320
|
end
|
321
|
else
|
322
|
log(sql, name) do
|
323
|
@connection.execute(sql) do |handle|
|
324
|
yield(handle) if block_given?
|
325
|
end
|
326
|
end
|
327
|
end
|
328
|
end
|
329
|
|
330
|
def begin_db_transaction
|
331
|
@connection["AutoCommit"] = false
|
332
|
rescue Exception => e
|
333
|
@connection["AutoCommit"] = true
|
334
|
end
|
335
|
|
336
|
def commit_db_transaction
|
337
|
@connection.commit
|
338
|
ensure
|
339
|
@connection["AutoCommit"] = true
|
340
|
end
|
341
|
|
342
|
def rollback_db_transaction
|
343
|
@connection.rollback
|
344
|
ensure
|
345
|
@connection["AutoCommit"] = true
|
346
|
end
|
347
|
|
348
|
def quote(value, column = nil)
|
349
|
return value.quoted_id if value.respond_to?(:quoted_id)
|
350
|
|
351
|
case value
|
352
|
when TrueClass then '1'
|
353
|
when FalseClass then '0'
|
354
|
when Time, DateTime then "'#{value.strftime("%Y%m%d %H:%M:%S")}'"
|
355
|
when Date then "'#{value.strftime("%Y%m%d")}'"
|
356
|
else super
|
357
|
end
|
358
|
end
|
359
|
|
360
|
def quote_string(string)
|
361
|
string.gsub(/\'/, "''")
|
362
|
end
|
363
|
|
364
|
def quoted_true
|
365
|
"1"
|
366
|
end
|
367
|
|
368
|
def quoted_false
|
369
|
"0"
|
370
|
end
|
371
|
|
372
|
def quote_column_name(name)
|
373
|
"[#{name}]"
|
374
|
end
|
375
|
|
376
|
def add_limit_offset!(sql, options)
|
377
|
if options[:limit] and options[:offset]
|
378
|
total_rows = @connection.select_all("SELECT count(*) as TotalRows from (#{sql.gsub(/\bSELECT(\s+DISTINCT)?\b/i, "SELECT#{$1} TOP 1000000000")}) tally")[0][:TotalRows].to_i
|
379
|
if (options[:limit] + options[:offset]) >= total_rows
|
380
|
options[:limit] = (total_rows - options[:offset] >= 0) ? (total_rows - options[:offset]) : 0
|
381
|
end
|
382
|
sql.sub!(/^\s*SELECT(\s+DISTINCT)?/i, "SELECT * FROM (SELECT TOP #{options[:limit]} * FROM (SELECT#{$1} TOP #{options[:limit] + options[:offset]} ")
|
383
|
sql << ") AS tmp1"
|
384
|
if options[:order]
|
385
|
order1 = options[:order].split(',').map do |field|
|
386
|
parts = field.split(" ")
|
387
|
tc = parts[0]
|
388
|
if sql =~ /\.\[/ and tc =~ /\./ # if column quoting used in query
|
389
|
tc.gsub!(/\./, '\\.\\[')
|
390
|
tc << '\\]'
|
391
|
end
|
392
|
if sql =~ /#{tc} AS (t\d_r\d\d?)/
|
393
|
parts[0] = $1
|
394
|
elsif parts[0] =~ /\w+\.(\w+)/
|
395
|
parts[0] = 'tmp1.' + $1
|
396
|
end
|
397
|
parts.join(' ')
|
398
|
end.join(', ')
|
399
|
|
400
|
order2 = order1.gsub(/tmp1/, 'tmp2')
|
401
|
# order2 = options[:order].split(',').map do |field|
|
402
|
# parts = field.split(" ")
|
403
|
# tc = parts[0]
|
404
|
# if sql =~ /\.\[/ and tc =~ /\./ # if column quoting used in query
|
405
|
# tc.gsub!(/\./, '\\.\\[')
|
406
|
# tc << '\\]'
|
407
|
# end
|
408
|
# if sql =~ /#{tc} AS (t\d_r\d\d?)/
|
409
|
# parts[0] = $1
|
410
|
# elsif parts[0] =~ /\w+\.(\w+)/
|
411
|
# parts[0] = 'tmp2.' + $1
|
412
|
# end
|
413
|
# parts.join(' ')
|
414
|
# end.join(', ')
|
415
|
sql << " ORDER BY #{change_order_direction(order1)}) AS tmp2 ORDER BY #{order2}"
|
416
|
else
|
417
|
sql << " ) AS tmp2"
|
418
|
end
|
419
|
elsif sql !~ /^\s*SELECT (@@|COUNT\()/i
|
420
|
sql.sub!(/^\s*SELECT(\s+DISTINCT)?/i) do
|
421
|
"SELECT#{$1} TOP #{options[:limit]}"
|
422
|
end unless options[:limit].nil?
|
423
|
end
|
424
|
end
|
425
|
|
426
|
def recreate_database(name)
|
427
|
drop_database(name)
|
428
|
create_database(name)
|
429
|
end
|
430
|
|
431
|
def drop_database(name)
|
432
|
execute "DROP DATABASE #{name}"
|
433
|
end
|
434
|
|
435
|
def create_database(name)
|
436
|
execute "CREATE DATABASE #{name}"
|
437
|
end
|
438
|
|
439
|
def current_database
|
440
|
@connection.select_one("select DB_NAME()")[0]
|
441
|
end
|
442
|
|
443
|
def tables(name = nil)
|
444
|
execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'", name) do |sth|
|
445
|
sth.inject([]) do |tables, field|
|
446
|
table_name = field[0]
|
447
|
tables << table_name unless table_name == 'dtproperties'
|
448
|
tables
|
449
|
end
|
450
|
end
|
451
|
end
|
452
|
|
453
|
def indexes(table_name, name = nil)
|
454
|
ActiveRecord::Base.connection.instance_variable_get("@connection")["AutoCommit"] = false
|
455
|
indexes = []
|
456
|
execute("EXEC sp_helpindex '#{table_name}'", name) do |sth|
|
457
|
sth.each do |index|
|
458
|
unique = index[1] =~ /unique/
|
459
|
primary = index[1] =~ /primary key/
|
460
|
if !primary
|
461
|
indexes << IndexDefinition.new(table_name, index[0], unique, index[2].split(", "))
|
462
|
end
|
463
|
end
|
464
|
end
|
465
|
indexes
|
466
|
ensure
|
467
|
ActiveRecord::Base.connection.instance_variable_get("@connection")["AutoCommit"] = true
|
468
|
end
|
469
|
|
470
|
def add_order_by_for_association_limiting!(sql, options)
|
471
|
# Just skip ORDER BY clause. I dont know better solution for DISTINCT plus ORDER BY.
|
472
|
# And this doesnt cause to much problem..
|
473
|
return sql
|
474
|
end
|
475
|
|
476
|
def rename_table(name, new_name)
|
477
|
execute "EXEC sp_rename '#{name}', '#{new_name}'"
|
478
|
end
|
479
|
|
480
|
# Adds a new column to the named table.
|
481
|
# See TableDefinition#column for details of the options you can use.
|
482
|
def add_column(table_name, column_name, type, options = {})
|
483
|
add_column_sql = "ALTER TABLE #{table_name} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
|
484
|
add_column_options!(add_column_sql, options)
|
485
|
# TODO: Add support to mimic date columns, using constraints to mark them as such in the database
|
486
|
# add_column_sql << " CONSTRAINT ck__#{table_name}__#{column_name}__date_only CHECK ( CONVERT(CHAR(12), #{quote_column_name(column_name)}, 14)='00:00:00:000' )" if type == :date
|
487
|
execute(add_column_sql)
|
488
|
end
|
489
|
|
490
|
def rename_column(table, column, new_column_name)
|
491
|
execute "EXEC sp_rename '#{table}.#{column}', '#{new_column_name}'"
|
492
|
end
|
493
|
|
494
|
def change_column(table_name, column_name, type, options = {}) #:nodoc:
|
495
|
sql_commands = ["ALTER TABLE #{table_name} ALTER COLUMN #{column_name} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"]
|
496
|
if options_include_default?(options)
|
497
|
remove_default_constraint(table_name, column_name)
|
498
|
sql_commands << "ALTER TABLE #{table_name} ADD CONSTRAINT DF_#{table_name}_#{column_name} DEFAULT #{quote(options[:default], options[:column])} FOR #{column_name}"
|
499
|
end
|
500
|
sql_commands.each {|c|
|
501
|
execute(c)
|
502
|
}
|
503
|
end
|
504
|
|
505
|
def remove_column(table_name, column_name)
|
506
|
remove_check_constraints(table_name, column_name)
|
507
|
remove_default_constraint(table_name, column_name)
|
508
|
execute "ALTER TABLE [#{table_name}] DROP COLUMN [#{column_name}]"
|
509
|
end
|
510
|
|
511
|
def remove_default_constraint(table_name, column_name)
|
512
|
constraints = select "select def.name from sysobjects def, syscolumns col, sysobjects tab where col.cdefault = def.id and col.name = '#{column_name}' and tab.name = '#{table_name}' and col.id = tab.id"
|
513
|
|
514
|
constraints.each do |constraint|
|
515
|
execute "ALTER TABLE #{table_name} DROP CONSTRAINT #{constraint["name"]}"
|
516
|
end
|
517
|
end
|
518
|
|
519
|
def remove_check_constraints(table_name, column_name)
|
520
|
# TODO remove all constraints in single method
|
521
|
constraints = select "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '#{table_name}' and COLUMN_NAME = '#{column_name}'"
|
522
|
constraints.each do |constraint|
|
523
|
execute "ALTER TABLE #{table_name} DROP CONSTRAINT #{constraint["CONSTRAINT_NAME"]}"
|
524
|
end
|
525
|
end
|
526
|
|
527
|
def remove_index(table_name, options = {})
|
528
|
execute "DROP INDEX #{table_name}.#{quote_column_name(index_name(table_name, options))}"
|
529
|
end
|
530
|
|
531
|
private
|
532
|
def select(sql, name = nil)
|
533
|
repair_special_columns(sql)
|
534
|
|
535
|
result = []
|
536
|
execute(sql) do |handle|
|
537
|
handle.each do |row|
|
538
|
row_hash = {}
|
539
|
row.each_with_index do |value, i|
|
540
|
if value.is_a? DBI::Timestamp
|
541
|
value = DateTime.new(value.year, value.month, value.day, value.hour, value.minute, value.sec)
|
542
|
end
|
543
|
row_hash[handle.column_names[i]] = value
|
544
|
end
|
545
|
result << row_hash
|
546
|
end
|
547
|
end
|
548
|
result
|
549
|
end
|
550
|
|
551
|
# Turns IDENTITY_INSERT ON for table during execution of the block
|
552
|
# N.B. This sets the state of IDENTITY_INSERT to OFF after the
|
553
|
# block has been executed without regard to its previous state
|
554
|
|
555
|
def with_identity_insert_enabled(table_name, &block)
|
556
|
set_identity_insert(table_name, true)
|
557
|
yield
|
558
|
ensure
|
559
|
set_identity_insert(table_name, false)
|
560
|
end
|
561
|
|
562
|
def set_identity_insert(table_name, enable = true)
|
563
|
execute "SET IDENTITY_INSERT #{table_name} #{enable ? 'ON' : 'OFF'}"
|
564
|
rescue Exception => e
|
565
|
raise ActiveRecordError, "IDENTITY_INSERT could not be turned #{enable ? 'ON' : 'OFF'} for table #{table_name}"
|
566
|
end
|
567
|
|
568
|
def get_table_name(sql)
|
569
|
if sql =~ /^\s*insert\s+into\s+([^\(\s]+)\s*|^\s*update\s+([^\(\s]+)\s*/i
|
570
|
$1
|
571
|
elsif sql =~ /from\s+([^\(\s]+)\s*/i
|
572
|
$1
|
573
|
else
|
574
|
nil
|
575
|
end
|
576
|
end
|
577
|
|
578
|
def identity_column(table_name)
|
579
|
@table_columns = {} unless @table_columns
|
580
|
@table_columns[table_name] = columns(table_name) if @table_columns[table_name] == nil
|
581
|
@table_columns[table_name].each do |col|
|
582
|
return col.name if col.identity
|
583
|
end
|
584
|
|
585
|
return nil
|
586
|
end
|
587
|
|
588
|
def query_requires_identity_insert?(sql)
|
589
|
table_name = get_table_name(sql)
|
590
|
id_column = identity_column(table_name)
|
591
|
sql =~ /\[#{id_column}\]/ ? table_name : nil
|
592
|
end
|
593
|
|
594
|
def change_order_direction(order)
|
595
|
order.split(",").collect {|fragment|
|
596
|
case fragment
|
597
|
when /\bDESC\b/i then fragment.gsub(/\bDESC\b/i, "ASC")
|
598
|
when /\bASC\b/i then fragment.gsub(/\bASC\b/i, "DESC")
|
599
|
else String.new(fragment).split(',').join(' DESC,') + ' DESC'
|
600
|
end
|
601
|
}.join(",")
|
602
|
end
|
603
|
|
604
|
def get_special_columns(table_name)
|
605
|
special = []
|
606
|
@table_columns ||= {}
|
607
|
@table_columns[table_name] ||= columns(table_name)
|
608
|
@table_columns[table_name].each do |col|
|
609
|
special << col.name if col.is_special
|
610
|
end
|
611
|
special
|
612
|
end
|
613
|
|
614
|
def repair_special_columns(sql)
|
615
|
special_cols = get_special_columns(get_table_name(sql))
|
616
|
for col in special_cols.to_a
|
617
|
sql.gsub!(Regexp.new(" #{col.to_s} = "), " #{col.to_s} LIKE ")
|
618
|
sql.gsub!(/ORDER BY #{col.to_s}/i, '')
|
619
|
end
|
620
|
sql
|
621
|
end
|
622
|
|
623
|
end #class SQLServerAdapter < AbstractAdapter
|
624
|
end #module ConnectionAdapters
|
625
|
end #module ActiveRecord
|