1 require 'jdbc_adapter/tsql_helper'
5 # After setting large objects to empty, write data back with a helper method
7 def write_lobs() #:nodoc:
8 if connection.is_a?(JdbcSpec::MsSQL)
9 self.class.columns.select { |c| c.sql_type =~ /image/i }.each { |c|
11 value = value.to_yaml if unserializable_attribute?(c.name, c)
12 next if value.nil? || (value == '')
14 connection.write_large_object(c.type == :binary, c.name, self.class.table_name, self.class.primary_key, quote_value(id), value)
26 def self.column_selector
27 [/sqlserver|tds/i, lambda {|cfg,col| col.extend(::JdbcSpec::MsSQL::Column)}]
30 def self.adapter_selector
31 [/sqlserver|tds/i, lambda {|cfg,adapt| adapt.extend(::JdbcSpec::MsSQL)}]
35 attr_accessor :identity, :is_special
37 def simplified_type(field_type)
39 when /int|bigint|smallint|tinyint/i then :integer
40 when /numeric/i then (@scale.nil? || @scale == 0) ? :integer : :decimal
41 when /float|double|decimal|money|real|smallmoney/i then :decimal
42 when /datetime|smalldatetime/i then :datetime
43 when /timestamp/i then :timestamp
44 when /time/i then :time
45 when /text|ntext/i then :text
46 when /binary|image|varbinary/i then :binary
47 when /char|nchar|nvarchar|string|varchar/i then :string
48 when /bit/i then :boolean
49 when /uniqueidentifier/i then :string
54 return nil if value.nil? || value == "(null)" || value == "(NULL)"
56 when :string then unquote_string value
57 when :integer then unquote(value).to_i rescue value ? 1 : 0
58 when :primary_key then value == true || value == false ? value == true ? 1 : 0 : value.to_i
59 when :decimal then self.class.value_to_decimal(unquote(value))
60 when :datetime then cast_to_datetime(value)
61 when :timestamp then cast_to_time(value)
62 when :time then cast_to_time(value)
63 when :date then cast_to_datetime(value)
64 when :boolean then value == true or (value =~ /^t(rue)?$/i) == 0 or unquote(value)=="1"
65 when :binary then unquote value
70 # JRUBY-2011: Match balanced quotes and parenthesis - 'text',('text') or (text)
71 def unquote_string(value)
72 value.sub(/^\((.*)\)$/,'\1').sub(/^'(.*)'$/,'\1')
76 value.to_s.sub(/\A\([\(\']?/, "").sub(/[\'\)]?\)\Z/, "")
79 def cast_to_time(value)
80 return value if value.is_a?(Time)
81 time_array = ParseDate.parsedate(value)
82 time_array[0] ||= 2000
85 Time.send(ActiveRecord::Base.default_timezone, *time_array) rescue nil
88 def cast_to_datetime(value)
90 if value.year != 0 and value.month != 0 and value.day != 0
93 return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil
96 return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil
100 # These methods will only allow the adapter to insert binary data with a length of 7K or less
101 # because of a SQL Server statement length policy.
102 def self.string_to_binary(value)
107 def quote(value, column = nil)
108 return value.quoted_id if value.respond_to?(:quoted_id)
111 when String, ActiveSupport::Multibyte::Chars
113 if column && column.type == :binary
114 "'#{quote_string(JdbcSpec::MsSQL::Column.string_to_binary(value))}'" # ' (for ruby-mode)
115 elsif column && [:integer, :float].include?(column.type)
116 value = column.type == :integer ? value.to_i : value.to_f
119 "'#{quote_string(value)}'" # ' (for ruby-mode)
121 when TrueClass then '1'
122 when FalseClass then '0'
123 when Time, DateTime then "'#{value.strftime("%Y%m%d %H:%M:%S")}'"
124 when Date then "'#{value.strftime("%Y%m%d")}'"
129 def quote_string(string)
130 string.gsub(/\'/, "''")
133 def quote_table_name(name)
137 def quote_column_name(name)
141 def change_order_direction(order)
142 order.split(",").collect {|fragment|
144 when /\bDESC\b/i then fragment.gsub(/\bDESC\b/i, "ASC")
145 when /\bASC\b/i then fragment.gsub(/\bASC\b/i, "DESC")
146 else String.new(fragment).split(',').join(' DESC,') + ' DESC'
151 def recreate_database(name)
153 create_database(name)
156 def drop_database(name)
157 execute "DROP DATABASE #{name}"
160 def create_database(name)
161 execute "CREATE DATABASE #{name}"
164 def rename_table(name, new_name)
165 execute "EXEC sp_rename '#{name}', '#{new_name}'"
168 # Adds a new column to the named table.
169 # See TableDefinition#column for details of the options you can use.
170 def add_column(table_name, column_name, type, options = {})
171 add_column_sql = "ALTER TABLE #{table_name} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
172 add_column_options!(add_column_sql, options)
173 # TODO: Add support to mimic date columns, using constraints to mark them as such in the database
174 # 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
175 execute(add_column_sql)
178 def rename_column(table, column, new_column_name)
179 execute "EXEC sp_rename '#{table}.#{column}', '#{new_column_name}'"
182 def change_column(table_name, column_name, type, options = {}) #:nodoc:
183 sql_commands = ["ALTER TABLE #{table_name} ALTER COLUMN #{column_name} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"]
184 if options_include_default?(options)
185 remove_default_constraint(table_name, column_name)
186 sql_commands << "ALTER TABLE #{table_name} ADD CONSTRAINT DF_#{table_name}_#{column_name} DEFAULT #{quote(options[:default], options[:column])} FOR #{column_name}"
188 sql_commands.each {|c|
192 def change_column_default(table_name, column_name, default) #:nodoc:
193 remove_default_constraint(table_name, column_name)
194 execute "ALTER TABLE #{table_name} ADD CONSTRAINT DF_#{table_name}_#{column_name} DEFAULT #{quote(default, column_name)} FOR #{column_name}"
196 def remove_column(table_name, column_name)
197 remove_check_constraints(table_name, column_name)
198 remove_default_constraint(table_name, column_name)
199 execute "ALTER TABLE #{table_name} DROP COLUMN [#{column_name}]"
202 def remove_default_constraint(table_name, column_name)
203 defaults = 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"
204 defaults.each {|constraint|
205 execute "ALTER TABLE #{table_name} DROP CONSTRAINT #{constraint["name"]}"
209 def remove_check_constraints(table_name, column_name)
210 # TODO remove all constraints in single method
211 constraints = select "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '#{table_name}' and COLUMN_NAME = '#{column_name}'"
212 constraints.each do |constraint|
213 execute "ALTER TABLE #{table_name} DROP CONSTRAINT #{constraint["CONSTRAINT_NAME"]}"
217 def remove_index(table_name, options = {})
218 execute "DROP INDEX #{table_name}.#{index_name(table_name, options)}"
222 def columns(table_name, name = nil)
223 return [] if table_name =~ /^information_schema\./i
226 col.identity = true if col.sql_type =~ /identity/i
227 col.is_special = true if col.sql_type =~ /text|ntext|image/i
232 def _execute(sql, name = nil)
233 if sql.lstrip =~ /^insert/i
234 if query_requires_identity_insert?(sql)
235 table_name = get_table_name(sql)
236 with_identity_insert_enabled(table_name) do
237 id = @connection.execute_insert(sql)
240 @connection.execute_insert(sql)
242 elsif sql.lstrip =~ /^\(?\s*(select|show)/i
243 repair_special_columns(sql)
244 @connection.execute_query(sql)
246 @connection.execute_update(sql)
252 # Turns IDENTITY_INSERT ON for table during execution of the block
253 # N.B. This sets the state of IDENTITY_INSERT to OFF after the
254 # block has been executed without regard to its previous state
256 def with_identity_insert_enabled(table_name, &block)
257 set_identity_insert(table_name, true)
260 set_identity_insert(table_name, false)
263 def set_identity_insert(table_name, enable = true)
264 execute "SET IDENTITY_INSERT #{table_name} #{enable ? 'ON' : 'OFF'}"
265 rescue Exception => e
266 raise ActiveRecord::ActiveRecordError, "IDENTITY_INSERT could not be turned #{enable ? 'ON' : 'OFF'} for table #{table_name}"
269 def get_table_name(sql)
270 if sql =~ /^\s*insert\s+into\s+([^\(\s,]+)\s*|^\s*update\s+([^\(\s,]+)\s*/i
272 elsif sql =~ /from\s+([^\(\s,]+)\s*/i
279 def identity_column(table_name)
280 @table_columns = {} unless @table_columns
281 @table_columns[table_name] = columns(table_name) if @table_columns[table_name] == nil
282 @table_columns[table_name].each do |col|
283 return col.name if col.identity
289 def query_requires_identity_insert?(sql)
290 table_name = get_table_name(sql)
291 id_column = identity_column(table_name)
292 sql =~ /\[#{id_column}\]/ ? table_name : nil
295 def get_special_columns(table_name)
297 @table_columns ||= {}
298 @table_columns[table_name] ||= columns(table_name)
299 @table_columns[table_name].each do |col|
300 special << col.name if col.is_special
305 def repair_special_columns(sql)
306 special_cols = get_special_columns(get_table_name(sql))
307 for col in special_cols.to_a
308 sql.gsub!(Regexp.new(" #{col.to_s} = "), " #{col.to_s} LIKE ")
309 sql.gsub!(/ORDER BY #{col.to_s}/i, '')