abstract_adapter.rb 18.3 KB
Newer Older
1
require 'active_record/type'
2
require 'active_record/connection_adapters/determine_if_preparable_visitor'
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
      autoload :ReferenceDefinition
26 27 28 29 30
    end

    autoload_at 'active_record/connection_adapters/abstract/connection_pool' do
      autoload :ConnectionHandler
    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
    # 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
54 55
    # a connection, escaping values, building the right SQL fragments for +:offset+
    # and +:limit+ options, etc.
P
Pratik Naik 已提交
56
    #
D
Initial  
David Heinemeier Hansson 已提交
57
    # All the concrete database adapters follow the interface laid down in this class.
58
    # {ActiveRecord::Base.connection}[rdoc-ref:ConnectionHandling#connection] returns an AbstractAdapter object, which
P
Pratik Naik 已提交
59
    # you can use.
60
    #
P
Pratik Naik 已提交
61
    # Most of the methods in the adapter are useful during migrations. Most
62
    # notably, the instance methods provided by SchemaStatements 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
      include Savepoints
71

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

74
      define_callbacks :checkout, :checkin
75

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

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
      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

96 97
      attr_reader :prepared_statements

98
      def initialize(connection, logger = nil, config = {}) # :nodoc:
99 100
        super()

101
        @connection          = connection
102
        @owner               = nil
103 104
        @instrumenter        = ActiveSupport::Notifications.instrumenter
        @logger              = logger
105 106
        @config              = config
        @pool                = nil
107
        @schema_cache        = SchemaCache.new self
108
        @quoted_column_names, @quoted_table_names = {}, {}
109 110 111 112 113 114 115 116
        @visitor             = arel_visitor

        if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
          @prepared_statements = true
          @visitor.extend(DetermineIfPreparableVisitor)
        else
          @prepared_statements = false
        end
117 118
      end

119 120 121 122 123 124 125 126 127 128 129 130
      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

131 132
      class BindCollector < Arel::Collectors::Bind
        def compile(bvs, conn)
133
          casted_binds = bvs.map(&:value_for_database)
S
Sean Griffin 已提交
134
          super(casted_binds.map { |value| conn.quote(value) })
135 136 137 138 139 140 141 142 143 144
        end
      end

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

      def collector
145
        if prepared_statements
146 147 148 149 150 151
          SQLString.new
        else
          BindCollector.new
        end
      end

152
      def arel_visitor # :nodoc:
153
        Arel::Visitors::ToSql.new(self)
154 155
      end

156
      def valid_type?(type)
157
        false
158 159
      end

160 161 162 163
      def schema_creation
        SchemaCreation.new self
      end

164
      # this method must only be called while holding connection pool's mutex
165
      def lease
166 167 168 169 170 171 172
        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}."
173
          end
174
          raise ActiveRecordError, msg
175
        end
176 177

        @owner = Thread.current
178 179
      end

180 181 182 183 184
      def schema_cache=(cache)
        cache.connection = self
        @schema_cache = cache
      end

185
      # this method must only be called while holding connection pool's mutex
A
Aaron Patterson 已提交
186
      def expire
187
        if in_use?
188
          if @owner != Thread.current
189 190 191 192 193 194 195 196 197
            raise ActiveRecordError, "Cannot expire connection, " <<
              "it is owned by a different thread: #{@owner}. " <<
              "Current thread: #{Thread.current}."
          end

          @owner = nil
        else
          raise ActiveRecordError, 'Cannot expire connection, it is not currently leased.'
        end
A
Aaron Patterson 已提交
198 199
      end

200 201 202 203 204 205 206 207 208 209 210 211 212
      # this method must only be called while holding connection pool's mutex (and a desire for segfaults)
      def steal! # :nodoc:
        if in_use?
          if @owner != Thread.current
            pool.send :remove_connection_from_thread_cache, self, @owner

            @owner = Thread.current
          end
        else
          raise ActiveRecordError, 'Cannot steal connection, it is not currently leased.'
        end
      end

213
      def unprepared_statement
214
        old_prepared_statements, @prepared_statements = @prepared_statements, false
215 216
        yield
      ensure
217
        @prepared_statements = old_prepared_statements
218 219
      end

S
Sebastian Martinez 已提交
220
      # Returns the human-readable name of the adapter. Use mixed case - one
221
      # can always use downcase if needed.
222
      def adapter_name
223
        self.class::ADAPTER_NAME
224
      end
225

226
      # Does this adapter support migrations?
227 228
      def supports_migrations?
        false
229
      end
230

231
      # Can this adapter determine the primary key for tables not attached
232
      # to an Active Record class, such as join tables?
233 234 235 236
      def supports_primary_key?
        false
      end

S
Sebastian Martinez 已提交
237
      # Does this adapter support DDL rollbacks in transactions? That is, would
238
      # CREATE TABLE or ALTER TABLE get rolled back by a transaction?
239 240 241
      def supports_ddl_transactions?
        false
      end
242

243 244 245 246
      def supports_bulk_alter?
        false
      end

247
      # Does this adapter support savepoints?
248 249 250
      def supports_savepoints?
        false
      end
251

252 253 254 255 256
      # Does this adapter support application-enforced advisory locking?
      def supports_advisory_locks?
        false
      end

257
      # Should primary key values be selected from their corresponding
S
Sebastian Martinez 已提交
258
      # sequence before the insert statement? If true, next_sequence_value
259
      # is called before each insert to set the record's primary key.
260
      def prefetch_primary_key?(table_name = nil)
261 262 263
        false
      end

264 265 266 267 268
      # Does this adapter support index sort order?
      def supports_index_sort_order?
        false
      end

269 270 271 272 273
      # Does this adapter support partial indices?
      def supports_partial_index?
        false
      end

274 275 276 277 278
      # Does this adapter support expression indices?
      def supports_expression_index?
        false
      end

279
      # Does this adapter support explain?
280 281 282 283
      def supports_explain?
        false
      end

284 285 286 287 288
      # Does this adapter support setting the isolation level for a transaction?
      def supports_transaction_isolation?
        false
      end

289
      # Does this adapter support database extensions?
290 291 292 293
      def supports_extensions?
        false
      end

294
      # Does this adapter support creating indexes in the same statement as
295
      # creating the table?
296 297 298 299
      def supports_indexes_in_create?
        false
      end

300 301 302 303 304
      # Does this adapter support creating foreign key constraints?
      def supports_foreign_keys?
        false
      end

305 306 307 308 309
      # Does this adapter support views?
      def supports_views?
        false
      end

310 311 312 313 314
      # Does this adapter support datetime with precision?
      def supports_datetime_with_precision?
        false
      end

315 316 317 318 319
      # Does this adapter support json data type?
      def supports_json?
        false
      end

320
      # Does this adapter support metadata comments on database objects (tables, columns, indexes)?
321 322 323 324 325 326 327 328 329
      def supports_comments?
        false
      end

      # Can comments for tables, columns, and indexes be specified in create/alter table statements?
      def supports_comments_in_create?
        false
      end

330
      # Does this adapter support multi-value insert?
331 332 333 334
      def supports_multi_insert?
        true
      end

335 336 337 338 339 340 341 342
      # 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

343 344 345 346
      # This is meant to be implemented by the adapters that support advisory
      # locks
      #
      # Return true if we got the lock, otherwise false
347
      def get_advisory_lock(lock_id) # :nodoc:
348 349 350 351 352 353
      end

      # This is meant to be implemented by the adapters that support advisory
      # locks.
      #
      # Return true if we released the lock, otherwise false
354
      def release_advisory_lock(lock_id) # :nodoc:
355 356
      end

357
      # A list of extensions, to be filled in by adapters that support them.
358 359 360 361
      def extensions
        []
      end

362
      # A list of index algorithms, to be filled by adapters that support them.
363 364 365 366
      def index_algorithms
        {}
      end

367 368
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
369
      # Override to turn off referential integrity while executing <tt>&block</tt>.
370
      def disable_referential_integrity
371 372 373
        yield
      end

374 375
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
376 377 378
      # 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.
379 380 381
      def active?
      end

P
Pratik Naik 已提交
382
      # Disconnects from the database if already connected, and establishes a
383 384
      # new connection with the database. Implementors should call super if they
      # override the default implementation.
385
      def reconnect!
386 387
        clear_cache!
        reset_transaction
388 389
      end

P
Pratik Naik 已提交
390 391
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
392
      def disconnect!
393 394
        clear_cache!
        reset_transaction
395 396
      end

397 398
      # Reset the state of this connection, directing the DBMS to clear
      # transactions and other connection-related server-side state. Usually a
P
Pratik Naik 已提交
399 400 401 402
      # database-dependent operation.
      #
      # The default implementation does nothing; the implementation should be
      # overridden by concrete adapters.
403
      def reset!
404
        # this should be overridden by concrete adapters
405 406
      end

A
Aaron Patterson 已提交
407 408
      ###
      # Clear any caching the database adapter may be doing, for example
S
Sebastian Martinez 已提交
409
      # clearing the prepared statement cache. This is database specific.
A
Aaron Patterson 已提交
410 411 412 413
      def clear_cache!
        # this should be overridden by concrete adapters
      end

414
      # Returns true if its required to reload the connection between requests for development mode.
415
      def requires_reloading?
416
        false
417 418
      end

P
Pratik Naik 已提交
419
      # Checks whether the connection to the database is still active (i.e. not stale).
420
      # This is done under the hood by calling #active?. If the connection
P
Pratik Naik 已提交
421
      # is no longer active, then this method will reconnect to the database.
422 423
      def verify!(*ignored)
        reconnect! unless active?
424
      end
425

P
Pratik Naik 已提交
426
      # Provides access to the underlying database driver for this adapter. For
R
Ryuta Kamizono 已提交
427
      # example, this method returns a Mysql2::Client object in case of Mysql2Adapter,
P
Pratik Naik 已提交
428 429 430 431
      # 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.
432 433 434
      def raw_connection
        @connection
      end
435

436
      def case_sensitive_comparison(table, attribute, column, value)
437 438 439 440 441
        if value.nil?
          table[attribute].eq(value)
        else
          table[attribute].eq(Arel::Nodes::BindParam.new)
        end
442 443
      end

444
      def case_insensitive_comparison(table, attribute, column, value)
S
Sean Griffin 已提交
445
        if can_perform_case_insensitive_comparison_for?(column)
446
          table[attribute].lower.eq(table.lower(Arel::Nodes::BindParam.new))
S
Sean Griffin 已提交
447
        else
448
          table[attribute].eq(Arel::Nodes::BindParam.new)
S
Sean Griffin 已提交
449 450 451 452 453
        end
      end

      def can_perform_case_insensitive_comparison_for?(column)
        true
454
      end
S
Sean Griffin 已提交
455
      private :can_perform_case_insensitive_comparison_for?
456

457 458 459 460 461
      # Check the connection back in to the connection pool
      def close
        pool.checkin self
      end

462 463 464 465 466 467
      def type_map # :nodoc:
        @type_map ||= Type::TypeMap.new.tap do |mapping|
          initialize_type_map(mapping)
        end
      end

468 469
      def new_column(name, default, sql_type_metadata, null, table_name, default_function = nil, collation = nil) # :nodoc:
        Column.new(name, default, sql_type_metadata, null, table_name, default_function, collation)
470 471
      end

472
      def lookup_cast_type(sql_type) # :nodoc:
473 474 475
        type_map.lookup(sql_type)
      end

476
      def column_name_for_operation(operation, node) # :nodoc:
477
        visitor.accept(node, collector).value
478 479
      end

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
      def combine_bind_parameters(
        from_clause: [],
        join_clause: [],
        where_clause: [],
        having_clause: [],
        limit: nil,
        offset: nil
      ) # :nodoc:
        result = from_clause + join_clause + where_clause + having_clause
        if limit
          result << limit
        end
        if offset
          result << offset
        end
        result
      end

498 499
      protected

500
      def initialize_type_map(m) # :nodoc:
501 502 503 504 505 506 507 508 509
        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 已提交
510 511 512 513 514 515 516 517

        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'

518
        m.register_type(%r(decimal)i) do |sql_type|
S
Sean Griffin 已提交
519
          scale = extract_scale(sql_type)
S
Sean Griffin 已提交
520
          precision = extract_precision(sql_type)
S
Sean Griffin 已提交
521 522

          if scale == 0
523
            # FIXME: Remove this class as well
524
            Type::DecimalWithoutScale.new(precision: precision)
525
          else
S
Sean Griffin 已提交
526
            Type::Decimal.new(precision: precision, scale: scale)
527 528 529 530 531 532 533
          end
        end
      end

      def reload_type_map # :nodoc:
        type_map.clear
        initialize_type_map(type_map)
534 535
      end

S
Sean Griffin 已提交
536 537 538 539 540 541 542
      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

543 544 545 546 547 548 549
      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 已提交
550 551 552 553 554 555 556
      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 已提交
557 558 559 560
      def extract_precision(sql_type) # :nodoc:
        $1.to_i if sql_type =~ /\((\d+)(,\d+)?\)/
      end

S
Sean Griffin 已提交
561
      def extract_limit(sql_type) # :nodoc:
562 563 564 565 566 567
        case sql_type
        when /^bigint/i
          8
        when /\((.*)\)/
          $1.to_i
        end
S
Sean Griffin 已提交
568 569
      end

A
Aaron Patterson 已提交
570
      def translate_exception_class(e, sql)
571 572 573 574 575 576
        begin
          message = "#{e.class.name}: #{e.message}: #{sql}"
        rescue Encoding::CompatibilityError
          message = "#{e.class.name}: #{e.message.force_encoding sql.encoding}: #{sql}"
        end

577 578
        exception = translate_exception(e, message)
        exception.set_backtrace e.backtrace
A
Aaron Patterson 已提交
579
        exception
580 581
      end

582
      def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil)
583 584
        @instrumenter.instrument(
          "sql.active_record",
585 586 587 588 589 590
          sql:               sql,
          name:              name,
          binds:             binds,
          type_casted_binds: type_casted_binds,
          statement_name:    statement_name,
          connection_id:     object_id) { yield }
591
      rescue => e
A
Aaron Patterson 已提交
592
        raise translate_exception_class(e, sql)
593 594
      end

595
      def translate_exception(exception, message)
596
        # override in derived class
597
        ActiveRecord::StatementInvalid.new(message)
598
      end
599 600

      def without_prepared_statement?(binds)
601
        !prepared_statements || binds.empty?
602
      end
603 604

      def column_for(table_name, column_name) # :nodoc:
605
        column_name = column_name.to_s
606 607
        columns(table_name).detect { |c| c.name == column_name } ||
          raise(ActiveRecordError, "No such column: #{table_name}.#{column_name}")
608
      end
609
    end
D
Initial  
David Heinemeier Hansson 已提交
610
  end
611
end