abstract_adapter.rb 15.8 KB
Newer Older
1
require 'active_record/type'
2
require 'active_support/core_ext/benchmark'
3
require 'active_record/connection_adapters/schema_cache'
S
Sean Griffin 已提交
4
require 'active_record/connection_adapters/sql_type_metadata'
5
require 'active_record/connection_adapters/abstract/schema_dumper'
6
require 'active_record/connection_adapters/abstract/schema_creation'
7 8
require 'arel/collectors/bind'
require 'arel/collectors/sql_string'
D
Initial  
David Heinemeier Hansson 已提交
9 10 11

module ActiveRecord
  module ConnectionAdapters # :nodoc:
12 13
    extend ActiveSupport::Autoload

14
    autoload :Column
15
    autoload :ConnectionSpecification
16

17 18 19
    autoload_at 'active_record/connection_adapters/abstract/schema_definitions' do
      autoload :IndexDefinition
      autoload :ColumnDefinition
20
      autoload :ChangeColumnDefinition
21
      autoload :ForeignKeyDefinition
22 23
      autoload :TableDefinition
      autoload :Table
24
      autoload :AlterTable
25 26 27 28 29 30
    end

    autoload_at 'active_record/connection_adapters/abstract/connection_pool' do
      autoload :ConnectionHandler
      autoload :ConnectionManagement
    end
31

32
    autoload_under 'abstract' do
33 34 35 36 37 38
      autoload :SchemaStatements
      autoload :DatabaseStatements
      autoload :DatabaseLimits
      autoload :Quoting
      autoload :ConnectionPool
      autoload :QueryCache
39
      autoload :Savepoints
J
Jon Leighton 已提交
40 41 42
    end

    autoload_at 'active_record/connection_adapters/abstract/transaction' do
A
Arthur Neves 已提交
43
      autoload :TransactionManager
44
      autoload :NullTransaction
J
Jon Leighton 已提交
45 46
      autoload :RealTransaction
      autoload :SavepointTransaction
47
      autoload :TransactionState
48 49
    end

50
    # Active Record supports multiple database systems. AbstractAdapter and
P
Pratik Naik 已提交
51 52 53 54 55 56
    # related classes form the abstraction layer which makes this possible.
    # An AbstractAdapter represents a connection to a database, and provides an
    # abstract interface for database-specific functionality such as establishing
    # a connection, escaping values, building the right SQL fragments for ':offset'
    # and ':limit' options, etc.
    #
D
Initial  
David Heinemeier Hansson 已提交
57
    # All the concrete database adapters follow the interface laid down in this class.
P
Pratik Naik 已提交
58 59
    # ActiveRecord::Base.connection returns an AbstractAdapter object, which
    # you can use.
60
    #
P
Pratik Naik 已提交
61 62
    # Most of the methods in the adapter are useful during migrations. Most
    # notably, the instance methods provided by SchemaStatement are very useful.
D
Initial  
David Heinemeier Hansson 已提交
63
    class AbstractAdapter
64
      ADAPTER_NAME = 'Abstract'.freeze
65
      include Quoting, DatabaseStatements, SchemaStatements
66
      include DatabaseLimits
67
      include QueryCache
68
      include ActiveSupport::Callbacks
69
      include ColumnDumper
70

71 72
      SIMPLE_INT = /\A\d+\z/

73
      define_callbacks :checkout, :checkin
74

75
      attr_accessor :visitor, :pool
76 77
      attr_reader :schema_cache, :owner, :logger
      alias :in_use? :owner
78

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
      def self.type_cast_config_to_integer(config)
        if config =~ SIMPLE_INT
          config.to_i
        else
          config
        end
      end

      def self.type_cast_config_to_boolean(config)
        if config == "false"
          false
        else
          config
        end
      end

95 96
      attr_reader :prepared_statements

97
      def initialize(connection, logger = nil, pool = nil) #:nodoc:
98 99
        super()

100
        @connection          = connection
101
        @owner               = nil
102 103 104 105 106
        @instrumenter        = ActiveSupport::Notifications.instrumenter
        @logger              = logger
        @pool                = pool
        @schema_cache        = SchemaCache.new self
        @visitor             = nil
107
        @prepared_statements = false
108 109
      end

110 111 112 113 114 115 116 117 118 119 120 121
      class Version
        include Comparable

        def initialize(version_string)
          @version = version_string.split('.').map(&:to_i)
        end

        def <=>(version_string)
          @version <=> version_string.split('.').map(&:to_i)
        end
      end

122 123
      class BindCollector < Arel::Collectors::Bind
        def compile(bvs, conn)
124
          casted_binds = conn.prepare_binds_for_database(bvs)
S
Sean Griffin 已提交
125
          super(casted_binds.map { |value| conn.quote(value) })
126 127 128 129 130 131 132 133 134 135
        end
      end

      class SQLString < Arel::Collectors::SQLString
        def compile(bvs, conn)
          super(bvs)
        end
      end

      def collector
136
        if prepared_statements
137 138 139 140 141 142
          SQLString.new
        else
          BindCollector.new
        end
      end

143 144 145 146
      def valid_type?(type)
        true
      end

147 148 149 150
      def schema_creation
        SchemaCreation.new self
      end

151
      # this method must only be called while holding connection pool's mutex
152
      def lease
153 154 155 156 157 158 159
        if in_use?
          msg = 'Cannot lease connection, '
          if @owner == Thread.current
            msg << 'it is already leased by the current thread.'
          else
            msg << "it is already in use by a different thread: #{@owner}. " <<
                   "Current thread: #{Thread.current}."
160
          end
161
          raise ActiveRecordError, msg
162
        end
163 164

        @owner = Thread.current
165 166
      end

167 168 169 170 171
      def schema_cache=(cache)
        cache.connection = self
        @schema_cache = cache
      end

172
      # this method must only be called while holding connection pool's mutex
A
Aaron Patterson 已提交
173
      def expire
174
        @owner = nil
A
Aaron Patterson 已提交
175 176
      end

177
      def unprepared_statement
178
        old_prepared_statements, @prepared_statements = @prepared_statements, false
179 180
        yield
      ensure
181
        @prepared_statements = old_prepared_statements
182 183
      end

S
Sebastian Martinez 已提交
184
      # Returns the human-readable name of the adapter. Use mixed case - one
185
      # can always use downcase if needed.
186
      def adapter_name
187
        self.class::ADAPTER_NAME
188
      end
189

190
      # Does this adapter support migrations?
191 192
      def supports_migrations?
        false
193
      end
194

195
      # Can this adapter determine the primary key for tables not attached
196
      # to an Active Record class, such as join tables?
197 198 199 200
      def supports_primary_key?
        false
      end

S
Sebastian Martinez 已提交
201
      # Does this adapter support DDL rollbacks in transactions? That is, would
202
      # CREATE TABLE or ALTER TABLE get rolled back by a transaction?
203 204 205
      def supports_ddl_transactions?
        false
      end
206

207 208 209 210
      def supports_bulk_alter?
        false
      end

211
      # Does this adapter support savepoints?
212 213 214
      def supports_savepoints?
        false
      end
215

216
      # Should primary key values be selected from their corresponding
S
Sebastian Martinez 已提交
217
      # sequence before the insert statement? If true, next_sequence_value
218
      # is called before each insert to set the record's primary key.
219
      def prefetch_primary_key?(table_name = nil)
220 221 222
        false
      end

223 224 225 226 227
      # Does this adapter support index sort order?
      def supports_index_sort_order?
        false
      end

228 229 230 231 232
      # Does this adapter support partial indices?
      def supports_partial_index?
        false
      end

233
      # Does this adapter support explain?
234 235 236 237
      def supports_explain?
        false
      end

238 239 240 241 242
      # Does this adapter support setting the isolation level for a transaction?
      def supports_transaction_isolation?
        false
      end

243
      # Does this adapter support database extensions?
244 245 246 247
      def supports_extensions?
        false
      end

248
      # Does this adapter support creating indexes in the same statement as
249
      # creating the table?
250 251 252 253
      def supports_indexes_in_create?
        false
      end

254 255 256 257 258
      # Does this adapter support creating foreign key constraints?
      def supports_foreign_keys?
        false
      end

259 260 261 262 263
      # Does this adapter support views?
      def supports_views?
        false
      end

264 265 266 267 268
      # Does this adapter support datetime with precision?
      def supports_datetime_with_precision?
        false
      end

269 270 271 272 273 274 275 276
      # This is meant to be implemented by the adapters that support extensions
      def disable_extension(name)
      end

      # This is meant to be implemented by the adapters that support extensions
      def enable_extension(name)
      end

277
      # A list of extensions, to be filled in by adapters that support them.
278 279 280 281
      def extensions
        []
      end

282
      # A list of index algorithms, to be filled by adapters that support them.
283 284 285 286
      def index_algorithms
        {}
      end

287
      # Returns a bind substitution value given a bind +column+
288
      # NOTE: The column param is currently being used by the sqlserver-adapter
289
      def substitute_at(column, _unused = 0)
S
Sean Griffin 已提交
290
        Arel::Nodes::BindParam.new
A
Aaron Patterson 已提交
291 292
      end

293 294
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
295
      # Override to turn off referential integrity while executing <tt>&block</tt>.
296
      def disable_referential_integrity
297 298 299
        yield
      end

300 301
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
302 303 304
      # Checks whether the connection to the database is still active. This includes
      # checking whether the database is actually capable of responding, i.e. whether
      # the connection isn't stale.
305 306 307
      def active?
      end

P
Pratik Naik 已提交
308
      # Disconnects from the database if already connected, and establishes a
309 310
      # new connection with the database. Implementors should call super if they
      # override the default implementation.
311
      def reconnect!
312 313
        clear_cache!
        reset_transaction
314 315
      end

P
Pratik Naik 已提交
316 317
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
318
      def disconnect!
319 320
        clear_cache!
        reset_transaction
321 322
      end

323 324
      # Reset the state of this connection, directing the DBMS to clear
      # transactions and other connection-related server-side state. Usually a
P
Pratik Naik 已提交
325 326 327 328
      # database-dependent operation.
      #
      # The default implementation does nothing; the implementation should be
      # overridden by concrete adapters.
329
      def reset!
330
        # this should be overridden by concrete adapters
331 332
      end

A
Aaron Patterson 已提交
333 334
      ###
      # Clear any caching the database adapter may be doing, for example
S
Sebastian Martinez 已提交
335
      # clearing the prepared statement cache. This is database specific.
A
Aaron Patterson 已提交
336 337 338 339
      def clear_cache!
        # this should be overridden by concrete adapters
      end

340
      # Returns true if its required to reload the connection between requests for development mode.
341
      def requires_reloading?
342
        false
343 344
      end

P
Pratik Naik 已提交
345 346 347
      # Checks whether the connection to the database is still active (i.e. not stale).
      # This is done under the hood by calling <tt>active?</tt>. If the connection
      # is no longer active, then this method will reconnect to the database.
348 349
      def verify!(*ignored)
        reconnect! unless active?
350
      end
351

P
Pratik Naik 已提交
352 353 354 355 356 357
      # Provides access to the underlying database driver for this adapter. For
      # example, this method returns a Mysql object in case of MysqlAdapter,
      # and a PGconn object in case of PostgreSQLAdapter.
      #
      # This is useful for when you need to call a proprietary method such as
      # PostgreSQL's lo_* methods.
358 359 360
      def raw_connection
        @connection
      end
361

362
      def create_savepoint(name = nil)
J
Jonathan Viney 已提交
363
      end
364

365
      def release_savepoint(name = nil)
J
Jonathan Viney 已提交
366
      end
367

368
      def case_sensitive_modifier(node, table_attribute)
369 370 371
        node
      end

372
      def case_sensitive_comparison(table, attribute, column, value)
373 374 375
        table_attr = table[attribute]
        value = case_sensitive_modifier(value, table_attr) unless value.nil?
        table_attr.eq(value)
376 377
      end

378
      def case_insensitive_comparison(table, attribute, column, value)
S
Sean Griffin 已提交
379 380 381 382 383 384 385 386 387
        if can_perform_case_insensitive_comparison_for?(column)
          table[attribute].lower.eq(table.lower(value))
        else
          case_sensitive_comparison(table, attribute, column, value)
        end
      end

      def can_perform_case_insensitive_comparison_for?(column)
        true
388
      end
S
Sean Griffin 已提交
389
      private :can_perform_case_insensitive_comparison_for?
390

J
Jonathan Viney 已提交
391
      def current_savepoint_name
392
        current_transaction.savepoint_name
J
Jonathan Viney 已提交
393
      end
394

395 396 397 398 399
      # Check the connection back in to the connection pool
      def close
        pool.checkin self
      end

400 401 402 403 404 405
      def type_map # :nodoc:
        @type_map ||= Type::TypeMap.new.tap do |mapping|
          initialize_type_map(mapping)
        end
      end

406 407
      def new_column(name, default, sql_type_metadata = nil, null = true, default_function = nil, collation = nil)
        Column.new(name, default, sql_type_metadata, null, default_function, collation)
408 409
      end

410
      def lookup_cast_type(sql_type) # :nodoc:
411 412 413
        type_map.lookup(sql_type)
      end

414
      def column_name_for_operation(operation, node) # :nodoc:
415
        visitor.accept(node, collector).value
416 417
      end

418 419
      protected

420
      def initialize_type_map(m) # :nodoc:
421 422 423 424 425 426 427 428 429
        register_class_with_limit m, %r(boolean)i,       Type::Boolean
        register_class_with_limit m, %r(char)i,          Type::String
        register_class_with_limit m, %r(binary)i,        Type::Binary
        register_class_with_limit m, %r(text)i,          Type::Text
        register_class_with_precision m, %r(date)i,      Type::Date
        register_class_with_precision m, %r(time)i,      Type::Time
        register_class_with_precision m, %r(datetime)i,  Type::DateTime
        register_class_with_limit m, %r(float)i,         Type::Float
        register_class_with_limit m, %r(int)i,           Type::Integer
S
Sean Griffin 已提交
430 431 432 433 434 435 436 437

        m.alias_type %r(blob)i,      'binary'
        m.alias_type %r(clob)i,      'text'
        m.alias_type %r(timestamp)i, 'datetime'
        m.alias_type %r(numeric)i,   'decimal'
        m.alias_type %r(number)i,    'decimal'
        m.alias_type %r(double)i,    'float'

438
        m.register_type(%r(decimal)i) do |sql_type|
S
Sean Griffin 已提交
439
          scale = extract_scale(sql_type)
S
Sean Griffin 已提交
440
          precision = extract_precision(sql_type)
S
Sean Griffin 已提交
441 442

          if scale == 0
443
            # FIXME: Remove this class as well
444
            Type::DecimalWithoutScale.new(precision: precision)
445
          else
S
Sean Griffin 已提交
446
            Type::Decimal.new(precision: precision, scale: scale)
447 448 449 450 451 452 453
          end
        end
      end

      def reload_type_map # :nodoc:
        type_map.clear
        initialize_type_map(type_map)
454 455
      end

S
Sean Griffin 已提交
456 457 458 459 460 461 462
      def register_class_with_limit(mapping, key, klass) # :nodoc:
        mapping.register_type(key) do |*args|
          limit = extract_limit(args.last)
          klass.new(limit: limit)
        end
      end

463 464 465 466 467 468 469
      def register_class_with_precision(mapping, key, klass) # :nodoc:
        mapping.register_type(key) do |*args|
          precision = extract_precision(args.last)
          klass.new(precision: precision)
        end
      end

S
Sean Griffin 已提交
470 471 472 473 474 475 476
      def extract_scale(sql_type) # :nodoc:
        case sql_type
          when /\((\d+)\)/ then 0
          when /\((\d+)(,(\d+))\)/ then $3.to_i
        end
      end

S
Sean Griffin 已提交
477 478 479 480
      def extract_precision(sql_type) # :nodoc:
        $1.to_i if sql_type =~ /\((\d+)(,\d+)?\)/
      end

S
Sean Griffin 已提交
481
      def extract_limit(sql_type) # :nodoc:
482 483 484 485 486 487
        case sql_type
        when /^bigint/i
          8
        when /\((.*)\)/
          $1.to_i
        end
S
Sean Griffin 已提交
488 489
      end

A
Aaron Patterson 已提交
490
      def translate_exception_class(e, sql)
491 492 493 494 495 496
        begin
          message = "#{e.class.name}: #{e.message}: #{sql}"
        rescue Encoding::CompatibilityError
          message = "#{e.class.name}: #{e.message.force_encoding sql.encoding}: #{sql}"
        end

497 498
        exception = translate_exception(e, message)
        exception.set_backtrace e.backtrace
A
Aaron Patterson 已提交
499
        exception
500 501
      end

502
      def log(sql, name = "SQL", binds = [], statement_name = nil)
503 504
        @instrumenter.instrument(
          "sql.active_record",
505 506 507 508 509
          :sql            => sql,
          :name           => name,
          :connection_id  => object_id,
          :statement_name => statement_name,
          :binds          => binds) { yield }
510
      rescue => e
A
Aaron Patterson 已提交
511
        raise translate_exception_class(e, sql)
512 513
      end

514
      def translate_exception(exception, message)
515
        # override in derived class
516
        ActiveRecord::StatementInvalid.new(message, exception)
517
      end
518 519

      def without_prepared_statement?(binds)
520
        !prepared_statements || binds.empty?
521
      end
522 523

      def column_for(table_name, column_name) # :nodoc:
524
        column_name = column_name.to_s
525 526
        columns(table_name).detect { |c| c.name == column_name } ||
          raise(ActiveRecordError, "No such column: #{table_name}.#{column_name}")
527
      end
528
    end
D
Initial  
David Heinemeier Hansson 已提交
529
  end
530
end