class ActiveRecord::ConnectionAdapters::SQLServerAdapter

Constants

ADAPTER_NAME

Attributes

spid[R]

Public Class Methods

new(connection, logger, pool, config) click to toggle source
Calls superclass method
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 50
def initialize(connection, logger, pool, config)
  super(connection, logger, pool)
  # AbstractAdapter Responsibility
  @schema_cache = SQLServer::SchemaCache.new self
  @visitor = Arel::Visitors::SQLServer.new self
  @prepared_statements = true
  # Our Responsibility
  @connection_options = config
  connect
  @sqlserver_azure = !!(select_value('SELECT @@version', 'SCHEMA') =~ /Azure/i)
  initialize_dateformatter
  use_database
end

Public Instance Methods

active?() click to toggle source

Abstract Adapter (Connection Management) ================== #

# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 132
def active?
  return false unless @connection
  raw_connection_do 'SELECT 1'
  true
rescue *connection_errors
  false
end
adapter_name() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 74
def adapter_name
  ADAPTER_NAME
end
database_prefix() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 203
def database_prefix
  @connection_options[:database_prefix]
end
database_prefix_remote_server?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 197
def database_prefix_remote_server?
  return false if database_prefix.blank?
  name = SQLServer::Utils.extract_identifiers(database_prefix)
  name.fully_qualified? && name.object.blank?
end
disable_referential_integrity() { || ... } click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 122
def disable_referential_integrity
  tables = tables_with_referential_integrity
  tables.each { |t| do_execute "ALTER TABLE #{t} NOCHECK CONSTRAINT ALL" }
  yield
ensure
  tables.each { |t| do_execute "ALTER TABLE #{t} CHECK CONSTRAINT ALL" }
end
disconnect!() click to toggle source
Calls superclass method
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 146
def disconnect!
  super
  @spid = nil
  case @connection_options[:mode]
  when :dblib
    @connection.close rescue nil
  when :odbc
    @connection.disconnect rescue nil
  end
  @connection = nil
end
inspect() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 211
def inspect
  "#<#{self.class} version: #{version}, mode: #{@connection_options[:mode]}, azure: #{sqlserver_azure?.inspect}>"
end
pk_and_sequence_for(table_name) click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 178
def pk_and_sequence_for(table_name)
  pk = primary_key(table_name)
  pk ? [pk, nil] : nil
end
primary_key(table_name) click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 183
def primary_key(table_name)
  schema_cache.columns(table_name).find(&:is_primary?).try(:name) || identity_column(table_name).try(:name)
end
reconnect!() click to toggle source
Calls superclass method
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 140
def reconnect!
  super
  disconnect!
  connect
end
reset!() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 158
def reset!
  reset_transaction
  do_execute 'IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION'
end
schema_creation() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 70
def schema_creation
  SQLServer::SchemaCreation.new self
end
sqlserver?() click to toggle source

SQLServer Specific (DB Reflection) ======================== #

# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 189
def sqlserver?
  true
end
sqlserver_azure?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 193
def sqlserver_azure?
  @sqlserver_azure
end
supports_bulk_alter?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 94
def supports_bulk_alter?
  false
end
supports_count_distinct?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 86
def supports_count_distinct?
  true
end
supports_ddl_transactions?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 90
def supports_ddl_transactions?
  true
end
supports_explain?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 106
def supports_explain?
  true
end
supports_foreign_keys?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 118
def supports_foreign_keys?
  true
end
supports_index_sort_order?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 98
def supports_index_sort_order?
  true
end
supports_migrations?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 78
def supports_migrations?
  true
end
supports_partial_index?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 102
def supports_partial_index?
  true
end
supports_primary_key?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 82
def supports_primary_key?
  true
end
supports_transaction_isolation?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 110
def supports_transaction_isolation?
  true
end
supports_views?() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 114
def supports_views?
  true
end
tables_with_referential_integrity() click to toggle source

Abstract Adapter (Misc Support) =========================== #

# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 165
      def tables_with_referential_integrity
        schemas_and_tables = select_rows <<-SQL.strip_heredoc
          SELECT s.name, o.name
          FROM sys.foreign_keys i
          INNER JOIN sys.objects o ON i.parent_object_id = o.OBJECT_ID
          INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
        SQL
        schemas_and_tables.map do |schema_table|
          schema, table = schema_table
          "#{SQLServer::Utils.quoted_raw(schema)}.#{SQLServer::Utils.quoted_raw(table)}"
        end
      end
valid_type?(type) click to toggle source

Abstract Adapter ========================================== #

# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 66
def valid_type?(type)
  !native_database_types[type].nil?
end
version() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 207
def version
  self.class::VERSION
end

Protected Instance Methods

config_appname(config) click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 369
def config_appname(config)
  config[:appname] || configure_application_name || Rails.application.class.name.split('::').first rescue nil
end
config_encoding(config) click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 381
def config_encoding(config)
  config[:encoding].present? ? config[:encoding] : nil
end
config_login_timeout(config) click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 373
def config_login_timeout(config)
  config[:login_timeout].present? ? config[:login_timeout].to_i : nil
end
config_timeout(config) click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 377
def config_timeout(config)
  config[:timeout].present? ? config[:timeout].to_i / 1000 : nil
end
configure_application_name() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 387
def configure_application_name ; end
configure_connection() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 385
def configure_connection ; end
connect() click to toggle source

SQLServer Specific (Connection Management) ================ #

# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 298
def connect
  config = @connection_options
  @connection = case config[:mode]
                when :dblib
                  dblib_connect(config)
                when :odbc
                  odbc_connect(config)
                end
  @spid = _raw_select('SELECT @@SPID', fetch: :rows).first.first
  configure_connection
end
connection_errors() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 310
def connection_errors
  @connection_errors ||= [].tap do |errors|
    errors << TinyTds::Error if defined?(TinyTds::Error)
    errors << ODBC::Error if defined?(ODBC::Error)
  end
end
dblib_connect(config) click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 317
def dblib_connect(config)
  TinyTds::Client.new(
    dataserver: config[:dataserver],
    host: config[:host],
    port: config[:port],
    username: config[:username],
    password: config[:password],
    database: config[:database],
    tds_version: config[:tds_version],
    appname: config_appname(config),
    login_timeout: config_login_timeout(config),
    timeout: config_timeout(config),
    encoding:  config_encoding(config),
    azure: config[:azure]
  ).tap do |client|
    if config[:azure]
      client.execute('SET ANSI_NULLS ON').do
      client.execute('SET CURSOR_CLOSE_ON_COMMIT OFF').do
      client.execute('SET ANSI_NULL_DFLT_ON ON').do
      client.execute('SET IMPLICIT_TRANSACTIONS OFF').do
      client.execute('SET ANSI_PADDING ON').do
      client.execute('SET QUOTED_IDENTIFIER ON').do
      client.execute('SET ANSI_WARNINGS ON').do
    else
      client.execute('SET ANSI_DEFAULTS ON').do
      client.execute('SET CURSOR_CLOSE_ON_COMMIT OFF').do
      client.execute('SET IMPLICIT_TRANSACTIONS OFF').do
    end
    client.execute('SET TEXTSIZE 2147483647').do
    client.execute('SET CONCAT_NULL_YIELDS_NULL ON').do
  end
end
initialize_dateformatter() click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 389
def initialize_dateformatter
  @database_dateformat = user_options_dateformat
  a, b, c = @database_dateformat.each_char.to_a
  [a, b, c].each { |f| f.upcase! if f == 'y' }
  dateformat = "%#{a}-%#{b}-%#{c}"
  ::Date::DATE_FORMATS[:_sqlserver_dateformat]     = dateformat
  ::Time::DATE_FORMATS[:_sqlserver_dateformat]     = dateformat
  ::Time::DATE_FORMATS[:_sqlserver_time]           = '%H:%M:%S'
  ::Time::DATE_FORMATS[:_sqlserver_datetime]       = "#{dateformat} %H:%M:%S"
  ::Time::DATE_FORMATS[:_sqlserver_datetimeoffset] = lambda { |time|
    time.strftime "#{dateformat} %H:%M:%S.%9N #{time.formatted_offset}"
  }
end
initialize_type_map(m) click to toggle source

Abstract Adapter (Misc Support) =========================== #

# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 220
def initialize_type_map(m)
  m.register_type              %r{.*},            SQLServer::Type::UnicodeString.new
  # Exact Numerics
  register_class_with_limit m, 'bigint(8)',         SQLServer::Type::BigInteger
  m.alias_type                 'bigint',            'bigint(8)'
  register_class_with_limit m, 'int(4)',            SQLServer::Type::Integer
  m.alias_type                 'integer',           'int(4)'
  m.alias_type                 'int',               'int(4)'
  register_class_with_limit m, 'smallint(2)',       SQLServer::Type::SmallInteger
  m.alias_type                 'smallint',          'smallint(2)'
  register_class_with_limit m, 'tinyint(1)',        SQLServer::Type::TinyInteger
  m.alias_type                 'tinyint',           'tinyint(1)'
  m.register_type              'bit',               SQLServer::Type::Boolean.new
  m.register_type              %r{\Adecimal}i do |sql_type|
    scale = extract_scale(sql_type)
    precision = extract_precision(sql_type)
    SQLServer::Type::Decimal.new precision: precision, scale: scale
  end
  m.alias_type                 %r{\Anumeric}i,      'decimal'
  m.register_type              'money',             SQLServer::Type::Money.new
  m.register_type              'smallmoney',        SQLServer::Type::SmallMoney.new
  # Approximate Numerics
  m.register_type              'float',             SQLServer::Type::Float.new
  m.register_type              'real',              SQLServer::Type::Real.new
  # Date and Time
  m.register_type              'date',              SQLServer::Type::Date.new
  m.register_type              'datetime',          SQLServer::Type::DateTime.new
  m.register_type              %r{\Adatetime2}i do |sql_type|
    precision = extract_precision(sql_type)
    SQLServer::Type::DateTime2.new precision: precision
  end
  m.register_type              %r{\Adatetimeoffset}i do |sql_type|
    precision = extract_precision(sql_type)
    SQLServer::Type::DateTimeOffset.new precision: precision
  end
  m.register_type              'smalldatetime',     SQLServer::Type::SmallDateTime.new
  m.register_type              %r{\Atime}i do |sql_type|
    scale = extract_scale(sql_type)
    precision = extract_precision(sql_type)
    SQLServer::Type::Time.new precision: precision
  end
  # Character Strings
  register_class_with_limit m, %r{\Achar}i,         SQLServer::Type::Char
  register_class_with_limit m, %r{\Avarchar}i,      SQLServer::Type::Varchar
  m.register_type              'varchar(max)',      SQLServer::Type::VarcharMax.new
  m.register_type              'text',              SQLServer::Type::Text.new
  # Unicode Character Strings
  register_class_with_limit m, %r{\Anchar}i,        SQLServer::Type::UnicodeChar
  register_class_with_limit m, %r{\Anvarchar}i,     SQLServer::Type::UnicodeVarchar
  m.alias_type                 'string',            'nvarchar(4000)'
  m.register_type              'nvarchar(max)',     SQLServer::Type::UnicodeVarcharMax.new
  m.register_type              'ntext',             SQLServer::Type::UnicodeText.new
  # Binary Strings
  register_class_with_limit m, %r{\Abinary}i,       SQLServer::Type::Binary
  register_class_with_limit m, %r{\Avarbinary}i,    SQLServer::Type::Varbinary
  m.register_type              'varbinary(max)',    SQLServer::Type::VarbinaryMax.new
  # Other Data Types
  m.register_type              'uniqueidentifier',  SQLServer::Type::Uuid.new
  m.register_type              'timestamp',         SQLServer::Type::Timestamp.new
end
odbc_connect(config) click to toggle source
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 350
def odbc_connect(config)
  if config[:dsn].include?(';')
    driver = ODBC::Driver.new.tap do |d|
      d.name = config[:dsn_name] || 'Driver1'
      d.attrs = config[:dsn].split(';').map { |atr| atr.split('=') }.reject { |kv| kv.size != 2 }.reduce({}) { |a, e| k, v = e ; a[k] = v ; a }
    end
    ODBC::Database.new.drvconnect(driver)
  else
    ODBC.connect config[:dsn], config[:username], config[:password]
  end.tap do |c|
    begin
      c.use_time = true
      c.use_utc = ActiveRecord::Base.default_timezone == :utc
    rescue Exception
      warn 'Ruby ODBC v0.99992 or higher is required.'
    end
  end
end
translate_exception(e, message) click to toggle source
Calls superclass method
# File lib/active_record/connection_adapters/sqlserver_adapter.rb, line 281
def translate_exception(e, message)
  case message
  when /(cannot insert duplicate key .* with unique index) | (violation of unique key constraint)/i
    RecordNotUnique.new(message, e)
  when /conflicted with the foreign key constraint/i
    InvalidForeignKey.new(message, e)
  when /has been chosen as the deadlock victim/i
    DeadlockVictim.new(message, e)
  when /database .* does not exist/i
    NoDatabaseError.new(message, e)
  else
    super
  end
end