abstract_adapter.rb 14.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'
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
    extend ActiveSupport::Autoload

17
    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
    end

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

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

74 75
      SIMPLE_INT = /\A\d+\z/

76
      define_callbacks :checkout, :checkin
77

78
      attr_accessor :visitor, :pool
79 80
      attr_reader :schema_cache, :owner, :logger
      alias :in_use? :owner
81

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

98 99
      attr_reader :prepared_statements

100
      def initialize(connection, logger = nil, pool = nil) #:nodoc:
101 102
        super()

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

113 114 115 116 117 118 119 120 121 122 123 124 125
      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
126
        if prepared_statements
127 128 129 130 131 132
          SQLString.new
        else
          BindCollector.new
        end
      end

133 134 135 136
      def valid_type?(type)
        true
      end

137 138 139 140
      def schema_creation
        SchemaCreation.new self
      end

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

149 150 151 152 153
      def schema_cache=(cache)
        cache.connection = self
        @schema_cache = cache
      end

A
Aaron Patterson 已提交
154
      def expire
155
        @owner = nil
A
Aaron Patterson 已提交
156 157
      end

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

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

171
      # Does this adapter support migrations?
172 173
      def supports_migrations?
        false
174
      end
175

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

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

188 189 190 191
      def supports_bulk_alter?
        false
      end

192
      # Does this adapter support savepoints?
193 194 195
      def supports_savepoints?
        false
      end
196

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

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

209 210 211 212 213
      # Does this adapter support partial indices?
      def supports_partial_index?
        false
      end

214
      # Does this adapter support explain?
215 216 217 218
      def supports_explain?
        false
      end

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

224
      # Does this adapter support database extensions?
225 226 227 228
      def supports_extensions?
        false
      end

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

235 236 237 238 239
      # Does this adapter support creating foreign key constraints?
      def supports_foreign_keys?
        false
      end

240 241 242 243 244
      # Does this adapter support views?
      def supports_views?
        false
      end

245 246 247 248 249 250 251 252
      # 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

253
      # A list of extensions, to be filled in by adapters that support them.
254 255 256 257
      def extensions
        []
      end

258
      # A list of index algorithms, to be filled by adapters that support them.
259 260 261 262
      def index_algorithms
        {}
      end

263 264
      # QUOTING ==================================================

265 266
      # Returns a bind substitution value given a bind +index+ and +column+
      # NOTE: The column param is currently being used by the sqlserver-adapter
267
      def substitute_at(column, index = 0)
268
        Arel::Nodes::BindParam.new '?'
A
Aaron Patterson 已提交
269 270
      end

271 272
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
273
      # Override to turn off referential integrity while executing <tt>&block</tt>.
274
      def disable_referential_integrity
275 276 277
        yield
      end

278 279
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
280 281 282
      # 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.
283 284 285
      def active?
      end

P
Pratik Naik 已提交
286
      # Disconnects from the database if already connected, and establishes a
287 288
      # new connection with the database. Implementors should call super if they
      # override the default implementation.
289
      def reconnect!
290 291
        clear_cache!
        reset_transaction
292 293
      end

P
Pratik Naik 已提交
294 295
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
296
      def disconnect!
297 298
        clear_cache!
        reset_transaction
299 300
      end

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

A
Aaron Patterson 已提交
311 312
      ###
      # Clear any caching the database adapter may be doing, for example
S
Sebastian Martinez 已提交
313
      # clearing the prepared statement cache. This is database specific.
A
Aaron Patterson 已提交
314 315 316 317
      def clear_cache!
        # this should be overridden by concrete adapters
      end

318
      # Returns true if its required to reload the connection between requests for development mode.
319
      def requires_reloading?
320
        false
321 322
      end

P
Pratik Naik 已提交
323 324 325
      # 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.
326 327
      def verify!(*ignored)
        reconnect! unless active?
328
      end
329

P
Pratik Naik 已提交
330 331 332 333 334 335
      # 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.
336 337 338
      def raw_connection
        @connection
      end
339

340
      def create_savepoint(name = nil)
J
Jonathan Viney 已提交
341
      end
342

343
      def rollback_to_savepoint(name = nil)
J
Jonathan Viney 已提交
344
      end
345

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

349
      def case_sensitive_modifier(node, table_attribute)
350 351 352
        node
      end

353
      def case_sensitive_comparison(table, attribute, column, value)
354 355 356
        table_attr = table[attribute]
        value = case_sensitive_modifier(value, table_attr) unless value.nil?
        table_attr.eq(value)
357 358
      end

359 360 361 362
      def case_insensitive_comparison(table, attribute, column, value)
        table[attribute].lower.eq(table.lower(value))
      end

J
Jonathan Viney 已提交
363
      def current_savepoint_name
364
        current_transaction.savepoint_name
J
Jonathan Viney 已提交
365
      end
366

367 368 369 370 371
      # Check the connection back in to the connection pool
      def close
        pool.checkin self
      end

372 373 374 375 376 377
      def type_map # :nodoc:
        @type_map ||= Type::TypeMap.new.tap do |mapping|
          initialize_type_map(mapping)
        end
      end

378 379 380 381
      def new_column(name, default, cast_type, sql_type = nil, null = true)
        Column.new(name, default, cast_type, sql_type, null)
      end

382
      def lookup_cast_type(sql_type) # :nodoc:
383 384 385
        type_map.lookup(sql_type)
      end

386 387 388 389
      def column_name_for_operation(operation, node) # :nodoc:
        node.to_sql
      end

390 391
      protected

392
      def initialize_type_map(m) # :nodoc:
S
Sean Griffin 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
        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'

410
        m.register_type(%r(decimal)i) do |sql_type|
S
Sean Griffin 已提交
411
          scale = extract_scale(sql_type)
S
Sean Griffin 已提交
412
          precision = extract_precision(sql_type)
S
Sean Griffin 已提交
413 414

          if scale == 0
415
            # FIXME: Remove this class as well
416
            Type::DecimalWithoutScale.new(precision: precision)
417
          else
S
Sean Griffin 已提交
418
            Type::Decimal.new(precision: precision, scale: scale)
419 420 421 422 423 424 425
          end
        end
      end

      def reload_type_map # :nodoc:
        type_map.clear
        initialize_type_map(type_map)
426 427
      end

S
Sean Griffin 已提交
428 429 430 431 432 433 434
      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 已提交
435 436 437 438 439 440 441
      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 已提交
442 443 444 445
      def extract_precision(sql_type) # :nodoc:
        $1.to_i if sql_type =~ /\((\d+)(,\d+)?\)/
      end

S
Sean Griffin 已提交
446 447 448 449
      def extract_limit(sql_type) # :nodoc:
        $1.to_i if sql_type =~ /\((.*)\)/
      end

A
Aaron Patterson 已提交
450
      def translate_exception_class(e, sql)
451 452 453 454
        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 已提交
455
        exception
456 457
      end

458
      def log(sql, name = "SQL", binds = [], statement_name = nil)
459 460
        @instrumenter.instrument(
          "sql.active_record",
461 462 463 464 465
          :sql            => sql,
          :name           => name,
          :connection_id  => object_id,
          :statement_name => statement_name,
          :binds          => binds) { yield }
466
      rescue => e
A
Aaron Patterson 已提交
467
        raise translate_exception_class(e, sql)
468 469
      end

470
      def translate_exception(exception, message)
471
        # override in derived class
472
        ActiveRecord::StatementInvalid.new(message, exception)
473
      end
474 475

      def without_prepared_statement?(binds)
476
        !prepared_statements || binds.empty?
477
      end
478 479

      def column_for(table_name, column_name) # :nodoc:
480
        column_name = column_name.to_s
481 482
        columns(table_name).detect { |c| c.name == column_name } ||
          raise(ActiveRecordError, "No such column: #{table_name}.#{column_name}")
483
      end
484
    end
D
Initial  
David Heinemeier Hansson 已提交
485
  end
486
end