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

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

    autoload :Column
18
    autoload :ConnectionSpecification
19

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

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

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

    autoload_at 'active_record/connection_adapters/abstract/transaction' do
      autoload :ClosedTransaction
      autoload :RealTransaction
      autoload :SavepointTransaction
48
      autoload :TransactionState
49 50
    end

51
    # Active Record supports multiple database systems. AbstractAdapter and
P
Pratik Naik 已提交
52 53 54 55 56 57
    # 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 已提交
58
    # All the concrete database adapters follow the interface laid down in this class.
P
Pratik Naik 已提交
59 60
    # ActiveRecord::Base.connection returns an AbstractAdapter object, which
    # you can use.
61
    #
P
Pratik Naik 已提交
62 63
    # 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 已提交
64
    class AbstractAdapter
65
      include Quoting, DatabaseStatements, SchemaStatements
66
      include DatabaseLimits
67
      include QueryCache
68
      include ActiveSupport::Callbacks
69
      include MonitorMixin
70
      include ColumnDumper
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, pool = nil) #:nodoc:
99 100
        super()

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

111 112 113 114 115 116 117 118 119 120 121 122 123
      class BindCollector < Arel::Collectors::Bind
        def compile(bvs, conn)
          super(bvs.map { |bv| conn.quote(*bv.reverse) })
        end
      end

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

      def collector
124
        if prepared_statements
125 126 127 128 129 130
          SQLString.new
        else
          BindCollector.new
        end
      end

131 132 133 134
      def valid_type?(type)
        true
      end

135 136 137 138
      def schema_creation
        SchemaCreation.new self
      end

139 140
      def lease
        synchronize do
141 142
          unless in_use?
            @owner = Thread.current
143
          end
144
        end
145 146
      end

147 148 149 150 151
      def schema_cache=(cache)
        cache.connection = self
        @schema_cache = cache
      end

A
Aaron Patterson 已提交
152
      def expire
153
        @owner = nil
A
Aaron Patterson 已提交
154 155
      end

156
      def unprepared_statement
157
        old_prepared_statements, @prepared_statements = @prepared_statements, false
158 159
        yield
      ensure
160
        @prepared_statements = old_prepared_statements
161 162
      end

S
Sebastian Martinez 已提交
163
      # Returns the human-readable name of the adapter. Use mixed case - one
164
      # can always use downcase if needed.
165
      def adapter_name
166 167
        'Abstract'
      end
168

169
      # Does this adapter support migrations?
170 171
      def supports_migrations?
        false
172
      end
173

174
      # Can this adapter determine the primary key for tables not attached
175
      # to an Active Record class, such as join tables?
176 177 178 179
      def supports_primary_key?
        false
      end

S
Sebastian Martinez 已提交
180
      # Does this adapter support DDL rollbacks in transactions? That is, would
181
      # CREATE TABLE or ALTER TABLE get rolled back by a transaction?
182 183 184
      def supports_ddl_transactions?
        false
      end
185

186 187 188 189
      def supports_bulk_alter?
        false
      end

190
      # Does this adapter support savepoints?
191 192 193
      def supports_savepoints?
        false
      end
194

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

202 203 204 205 206
      # Does this adapter support index sort order?
      def supports_index_sort_order?
        false
      end

207 208 209 210 211
      # Does this adapter support partial indices?
      def supports_partial_index?
        false
      end

212
      # Does this adapter support explain?
213 214 215 216
      def supports_explain?
        false
      end

217 218 219 220 221
      # Does this adapter support setting the isolation level for a transaction?
      def supports_transaction_isolation?
        false
      end

222
      # Does this adapter support database extensions?
223 224 225 226
      def supports_extensions?
        false
      end

227
      # Does this adapter support creating indexes in the same statement as
228
      # creating the table?
229 230 231 232
      def supports_indexes_in_create?
        false
      end

233 234 235 236 237 238 239 240
      # 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

241
      # A list of extensions, to be filled in by adapters that support them.
242 243 244 245
      def extensions
        []
      end

246
      # A list of index algorithms, to be filled by adapters that support them.
247 248 249 250
      def index_algorithms
        {}
      end

251 252
      # QUOTING ==================================================

253 254
      # Returns a bind substitution value given a bind +index+ and +column+
      # NOTE: The column param is currently being used by the sqlserver-adapter
255
      def substitute_at(column, index)
256
        Arel::Nodes::BindParam.new '?'
A
Aaron Patterson 已提交
257 258
      end

259 260
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
261
      # Override to turn off referential integrity while executing <tt>&block</tt>.
262
      def disable_referential_integrity
263 264 265
        yield
      end

266 267
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
268 269 270
      # 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.
271 272 273
      def active?
      end

P
Pratik Naik 已提交
274
      # Disconnects from the database if already connected, and establishes a
275 276
      # new connection with the database. Implementors should call super if they
      # override the default implementation.
277
      def reconnect!
278 279
        clear_cache!
        reset_transaction
280 281
      end

P
Pratik Naik 已提交
282 283
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
284
      def disconnect!
285 286
        clear_cache!
        reset_transaction
287 288
      end

289 290
      # Reset the state of this connection, directing the DBMS to clear
      # transactions and other connection-related server-side state. Usually a
P
Pratik Naik 已提交
291 292 293 294
      # database-dependent operation.
      #
      # The default implementation does nothing; the implementation should be
      # overridden by concrete adapters.
295
      def reset!
296
        # this should be overridden by concrete adapters
297 298
      end

A
Aaron Patterson 已提交
299 300
      ###
      # Clear any caching the database adapter may be doing, for example
S
Sebastian Martinez 已提交
301
      # clearing the prepared statement cache. This is database specific.
A
Aaron Patterson 已提交
302 303 304 305
      def clear_cache!
        # this should be overridden by concrete adapters
      end

306
      # Returns true if its required to reload the connection between requests for development mode.
307
      def requires_reloading?
308
        false
309 310
      end

P
Pratik Naik 已提交
311 312 313
      # 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.
314 315
      def verify!(*ignored)
        reconnect! unless active?
316
      end
317

P
Pratik Naik 已提交
318 319 320 321 322 323
      # 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.
324 325 326
      def raw_connection
        @connection
      end
327

328 329 330
      def open_transactions
        @transaction.number
      end
331

332
      def create_savepoint(name = nil)
J
Jonathan Viney 已提交
333
      end
334

335
      def rollback_to_savepoint(name = nil)
J
Jonathan Viney 已提交
336
      end
337

338
      def release_savepoint(name = nil)
J
Jonathan Viney 已提交
339
      end
340

341
      def case_sensitive_modifier(node, table_attribute)
342 343 344
        node
      end

345
      def case_sensitive_comparison(table, attribute, column, value)
346 347 348
        table_attr = table[attribute]
        value = case_sensitive_modifier(value, table_attr) unless value.nil?
        table_attr.eq(value)
349 350
      end

351 352 353 354
      def case_insensitive_comparison(table, attribute, column, value)
        table[attribute].lower.eq(table.lower(value))
      end

J
Jonathan Viney 已提交
355
      def current_savepoint_name
356
        "active_record_#{open_transactions}"
J
Jonathan Viney 已提交
357
      end
358

359 360 361 362 363
      # Check the connection back in to the connection pool
      def close
        pool.checkin self
      end

364 365 366 367 368 369
      def type_map # :nodoc:
        @type_map ||= Type::TypeMap.new.tap do |mapping|
          initialize_type_map(mapping)
        end
      end

370
      protected
371

372
      def lookup_cast_type(sql_type) # :nodoc:
373 374 375 376
        type_map.lookup(sql_type)
      end

      def initialize_type_map(m) # :nodoc:
S
Sean Griffin 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
        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_limit m, %r(date)i,      Type::Date
        register_class_with_limit m, %r(time)i,      Type::Time
        register_class_with_limit 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

        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'

394
        m.register_type(%r(decimal)i) do |sql_type|
S
Sean Griffin 已提交
395
          scale = extract_scale(sql_type)
S
Sean Griffin 已提交
396
          precision = extract_precision(sql_type)
S
Sean Griffin 已提交
397 398

          if scale == 0
399
            Type::DecimalWithoutScale.new(precision: precision)
400
          else
S
Sean Griffin 已提交
401
            Type::Decimal.new(precision: precision, scale: scale)
402 403 404 405 406 407 408
          end
        end
      end

      def reload_type_map # :nodoc:
        type_map.clear
        initialize_type_map(type_map)
409 410
      end

S
Sean Griffin 已提交
411 412 413 414 415 416 417
      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

S
Sean Griffin 已提交
418 419 420 421 422 423 424
      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 已提交
425 426 427 428
      def extract_precision(sql_type) # :nodoc:
        $1.to_i if sql_type =~ /\((\d+)(,\d+)?\)/
      end

S
Sean Griffin 已提交
429 430 431 432
      def extract_limit(sql_type) # :nodoc:
        $1.to_i if sql_type =~ /\((.*)\)/
      end

A
Aaron Patterson 已提交
433
      def translate_exception_class(e, sql)
434 435 436 437
        message = "#{e.class.name}: #{e.message}: #{sql}"
        @logger.error message if @logger
        exception = translate_exception(e, message)
        exception.set_backtrace e.backtrace
A
Aaron Patterson 已提交
438
        exception
439 440
      end

441
      def log(sql, name = "SQL", binds = [], statement_name = nil)
442 443
        @instrumenter.instrument(
          "sql.active_record",
444 445 446 447 448
          :sql            => sql,
          :name           => name,
          :connection_id  => object_id,
          :statement_name => statement_name,
          :binds          => binds) { yield }
449
      rescue => e
A
Aaron Patterson 已提交
450
        raise translate_exception_class(e, sql)
451 452
      end

453
      def translate_exception(exception, message)
454
        # override in derived class
455
        ActiveRecord::StatementInvalid.new(message, exception)
456
      end
457 458

      def without_prepared_statement?(binds)
459
        !prepared_statements || binds.empty?
460
      end
461 462

      def column_for(table_name, column_name) # :nodoc:
463
        column_name = column_name.to_s
464 465
        columns(table_name).detect { |c| c.name == column_name } ||
          raise(ActiveRecordError, "No such column: #{table_name}.#{column_name}")
466
      end
467
    end
D
Initial  
David Heinemeier Hansson 已提交
468
  end
469
end