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

module ActiveRecord
  module ConnectionAdapters # :nodoc:
16 17
    extend ActiveSupport::Autoload

18
    autoload :Column
19
    autoload :ConnectionSpecification
20

21 22 23
    autoload_at 'active_record/connection_adapters/abstract/schema_definitions' do
      autoload :IndexDefinition
      autoload :ColumnDefinition
24
      autoload :ChangeColumnDefinition
25
      autoload :ForeignKeyDefinition
26 27
      autoload :TableDefinition
      autoload :Table
28
      autoload :AlterTable
29 30 31 32 33 34
    end

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

36
    autoload_under 'abstract' do
37 38 39 40 41 42
      autoload :SchemaStatements
      autoload :DatabaseStatements
      autoload :DatabaseLimits
      autoload :Quoting
      autoload :ConnectionPool
      autoload :QueryCache
43
      autoload :Savepoints
J
Jon Leighton 已提交
44 45 46
    end

    autoload_at 'active_record/connection_adapters/abstract/transaction' do
A
Arthur Neves 已提交
47
      autoload :TransactionManager
48
      autoload :NullTransaction
J
Jon Leighton 已提交
49 50
      autoload :RealTransaction
      autoload :SavepointTransaction
51
      autoload :TransactionState
52 53
    end

54
    # Active Record supports multiple database systems. AbstractAdapter and
P
Pratik Naik 已提交
55 56 57 58 59 60
    # 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 已提交
61
    # All the concrete database adapters follow the interface laid down in this class.
P
Pratik Naik 已提交
62 63
    # ActiveRecord::Base.connection returns an AbstractAdapter object, which
    # you can use.
64
    #
P
Pratik Naik 已提交
65 66
    # 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 已提交
67
    class AbstractAdapter
68
      ADAPTER_NAME = 'Abstract'.freeze
69
      include Quoting, DatabaseStatements, SchemaStatements
70
      include DatabaseLimits
71
      include QueryCache
72
      include ActiveSupport::Callbacks
73
      include MonitorMixin
74
      include ColumnDumper
75

76 77
      SIMPLE_INT = /\A\d+\z/

78
      define_callbacks :checkout, :checkin
79

80
      attr_accessor :visitor, :pool
81 82
      attr_reader :schema_cache, :owner, :logger
      alias :in_use? :owner
83

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
      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

100 101
      attr_reader :prepared_statements

102
      def initialize(connection, logger = nil, pool = nil) #:nodoc:
103 104
        super()

105
        @connection          = connection
106
        @owner               = nil
107 108 109 110 111
        @instrumenter        = ActiveSupport::Notifications.instrumenter
        @logger              = logger
        @pool                = pool
        @schema_cache        = SchemaCache.new self
        @visitor             = nil
112
        @prepared_statements = false
113 114
      end

115 116
      class BindCollector < Arel::Collectors::Bind
        def compile(bvs, conn)
117
          casted_binds = conn.prepare_binds_for_database(bvs)
S
Sean Griffin 已提交
118
          super(casted_binds.map { |value| conn.quote(value) })
119 120 121 122 123 124 125 126 127 128
        end
      end

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

      def collector
129
        if prepared_statements
130 131 132 133 134 135
          SQLString.new
        else
          BindCollector.new
        end
      end

136 137 138 139
      def valid_type?(type)
        true
      end

140 141 142 143
      def schema_creation
        SchemaCreation.new self
      end

144 145
      def lease
        synchronize do
146 147
          unless in_use?
            @owner = Thread.current
148
          end
149
        end
150 151
      end

152 153 154 155 156
      def schema_cache=(cache)
        cache.connection = self
        @schema_cache = cache
      end

A
Aaron Patterson 已提交
157
      def expire
158
        @owner = nil
A
Aaron Patterson 已提交
159 160
      end

161
      def unprepared_statement
162
        old_prepared_statements, @prepared_statements = @prepared_statements, false
163 164
        yield
      ensure
165
        @prepared_statements = old_prepared_statements
166 167
      end

S
Sebastian Martinez 已提交
168
      # Returns the human-readable name of the adapter. Use mixed case - one
169
      # can always use downcase if needed.
170
      def adapter_name
171
        self.class::ADAPTER_NAME
172
      end
173

174
      # Does this adapter support migrations?
175 176
      def supports_migrations?
        false
177
      end
178

179
      # Can this adapter determine the primary key for tables not attached
180
      # to an Active Record class, such as join tables?
181 182 183 184
      def supports_primary_key?
        false
      end

S
Sebastian Martinez 已提交
185
      # Does this adapter support DDL rollbacks in transactions? That is, would
186
      # CREATE TABLE or ALTER TABLE get rolled back by a transaction?
187 188 189
      def supports_ddl_transactions?
        false
      end
190

191 192 193 194
      def supports_bulk_alter?
        false
      end

195
      # Does this adapter support savepoints?
196 197 198
      def supports_savepoints?
        false
      end
199

200
      # Should primary key values be selected from their corresponding
S
Sebastian Martinez 已提交
201
      # sequence before the insert statement? If true, next_sequence_value
202
      # is called before each insert to set the record's primary key.
203
      def prefetch_primary_key?(table_name = nil)
204 205 206
        false
      end

207 208 209 210 211
      # Does this adapter support index sort order?
      def supports_index_sort_order?
        false
      end

212 213 214 215 216
      # Does this adapter support partial indices?
      def supports_partial_index?
        false
      end

217
      # Does this adapter support explain?
218 219 220 221
      def supports_explain?
        false
      end

222 223 224 225 226
      # Does this adapter support setting the isolation level for a transaction?
      def supports_transaction_isolation?
        false
      end

227
      # Does this adapter support database extensions?
228 229 230 231
      def supports_extensions?
        false
      end

232
      # Does this adapter support creating indexes in the same statement as
233
      # creating the table?
234 235 236 237
      def supports_indexes_in_create?
        false
      end

238 239 240 241 242
      # Does this adapter support creating foreign key constraints?
      def supports_foreign_keys?
        false
      end

243 244 245 246 247
      # Does this adapter support views?
      def supports_views?
        false
      end

248 249 250 251 252
      # Does this adapter support datetime with precision?
      def supports_datetime_with_precision?
        false
      end

253 254 255 256 257 258 259 260
      # 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

261
      # A list of extensions, to be filled in by adapters that support them.
262 263 264 265
      def extensions
        []
      end

266
      # A list of index algorithms, to be filled by adapters that support them.
267 268 269 270
      def index_algorithms
        {}
      end

271
      # Returns a bind substitution value given a bind +column+
272
      # NOTE: The column param is currently being used by the sqlserver-adapter
273
      def substitute_at(column, _unused = 0)
S
Sean Griffin 已提交
274
        Arel::Nodes::BindParam.new
A
Aaron Patterson 已提交
275 276
      end

277 278
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
279
      # Override to turn off referential integrity while executing <tt>&block</tt>.
280
      def disable_referential_integrity
281 282 283
        yield
      end

284 285
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
286 287 288
      # 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.
289 290 291
      def active?
      end

P
Pratik Naik 已提交
292
      # Disconnects from the database if already connected, and establishes a
293 294
      # new connection with the database. Implementors should call super if they
      # override the default implementation.
295
      def reconnect!
296 297
        clear_cache!
        reset_transaction
298 299
      end

P
Pratik Naik 已提交
300 301
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
302
      def disconnect!
303 304
        clear_cache!
        reset_transaction
305 306
      end

307 308
      # Reset the state of this connection, directing the DBMS to clear
      # transactions and other connection-related server-side state. Usually a
P
Pratik Naik 已提交
309 310 311 312
      # database-dependent operation.
      #
      # The default implementation does nothing; the implementation should be
      # overridden by concrete adapters.
313
      def reset!
314
        # this should be overridden by concrete adapters
315 316
      end

A
Aaron Patterson 已提交
317 318
      ###
      # Clear any caching the database adapter may be doing, for example
S
Sebastian Martinez 已提交
319
      # clearing the prepared statement cache. This is database specific.
A
Aaron Patterson 已提交
320 321 322 323
      def clear_cache!
        # this should be overridden by concrete adapters
      end

324
      # Returns true if its required to reload the connection between requests for development mode.
325
      def requires_reloading?
326
        false
327 328
      end

P
Pratik Naik 已提交
329 330 331
      # 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.
332 333
      def verify!(*ignored)
        reconnect! unless active?
334
      end
335

P
Pratik Naik 已提交
336 337 338 339 340 341
      # 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.
342 343 344
      def raw_connection
        @connection
      end
345

346
      def create_savepoint(name = nil)
J
Jonathan Viney 已提交
347
      end
348

349
      def release_savepoint(name = nil)
J
Jonathan Viney 已提交
350
      end
351

352
      def case_sensitive_modifier(node, table_attribute)
353 354 355
        node
      end

356
      def case_sensitive_comparison(table, attribute, column, value)
357 358 359
        table_attr = table[attribute]
        value = case_sensitive_modifier(value, table_attr) unless value.nil?
        table_attr.eq(value)
360 361
      end

362
      def case_insensitive_comparison(table, attribute, column, value)
S
Sean Griffin 已提交
363 364 365 366 367 368 369 370 371
        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
372
      end
S
Sean Griffin 已提交
373
      private :can_perform_case_insensitive_comparison_for?
374

J
Jonathan Viney 已提交
375
      def current_savepoint_name
376
        current_transaction.savepoint_name
J
Jonathan Viney 已提交
377
      end
378

379 380 381 382 383
      # Check the connection back in to the connection pool
      def close
        pool.checkin self
      end

384 385 386 387 388 389
      def type_map # :nodoc:
        @type_map ||= Type::TypeMap.new.tap do |mapping|
          initialize_type_map(mapping)
        end
      end

390 391
      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)
392 393
      end

394
      def lookup_cast_type(sql_type) # :nodoc:
395 396 397
        type_map.lookup(sql_type)
      end

398
      def column_name_for_operation(operation, node) # :nodoc:
399
        visitor.accept(node, collector).value
400 401
      end

402 403
      protected

404
      def initialize_type_map(m) # :nodoc:
405 406 407 408 409 410 411 412 413
        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 已提交
414 415 416 417 418 419 420 421

        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'

422
        m.register_type(%r(decimal)i) do |sql_type|
S
Sean Griffin 已提交
423
          scale = extract_scale(sql_type)
S
Sean Griffin 已提交
424
          precision = extract_precision(sql_type)
S
Sean Griffin 已提交
425 426

          if scale == 0
427
            # FIXME: Remove this class as well
428
            Type::DecimalWithoutScale.new(precision: precision)
429
          else
S
Sean Griffin 已提交
430
            Type::Decimal.new(precision: precision, scale: scale)
431 432 433 434 435 436 437
          end
        end
      end

      def reload_type_map # :nodoc:
        type_map.clear
        initialize_type_map(type_map)
438 439
      end

S
Sean Griffin 已提交
440 441 442 443 444 445 446
      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

447 448 449 450 451 452 453
      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 已提交
454 455 456 457 458 459 460
      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 已提交
461 462 463 464
      def extract_precision(sql_type) # :nodoc:
        $1.to_i if sql_type =~ /\((\d+)(,\d+)?\)/
      end

S
Sean Griffin 已提交
465
      def extract_limit(sql_type) # :nodoc:
466 467 468 469 470 471
        case sql_type
        when /^bigint/i
          8
        when /\((.*)\)/
          $1.to_i
        end
S
Sean Griffin 已提交
472 473
      end

A
Aaron Patterson 已提交
474
      def translate_exception_class(e, sql)
475 476 477 478 479 480
        begin
          message = "#{e.class.name}: #{e.message}: #{sql}"
        rescue Encoding::CompatibilityError
          message = "#{e.class.name}: #{e.message.force_encoding sql.encoding}: #{sql}"
        end

481 482
        exception = translate_exception(e, message)
        exception.set_backtrace e.backtrace
A
Aaron Patterson 已提交
483
        exception
484 485
      end

486
      def log(sql, name = "SQL", binds = [], statement_name = nil)
487 488
        @instrumenter.instrument(
          "sql.active_record",
489 490 491 492 493
          :sql            => sql,
          :name           => name,
          :connection_id  => object_id,
          :statement_name => statement_name,
          :binds          => binds) { yield }
494
      rescue => e
A
Aaron Patterson 已提交
495
        raise translate_exception_class(e, sql)
496 497
      end

498
      def translate_exception(exception, message)
499
        # override in derived class
500
        ActiveRecord::StatementInvalid.new(message, exception)
501
      end
502 503

      def without_prepared_statement?(binds)
504
        !prepared_statements || binds.empty?
505
      end
506 507

      def column_for(table_name, column_name) # :nodoc:
508
        column_name = column_name.to_s
509 510
        columns(table_name).detect { |c| c.name == column_name } ||
          raise(ActiveRecordError, "No such column: #{table_name}.#{column_name}")
511
      end
512
    end
D
Initial  
David Heinemeier Hansson 已提交
513
  end
514
end