abstract_adapter.rb 11.5 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/abstract/schema_dumper'
7
require 'active_record/connection_adapters/abstract/schema_creation'
8
require 'monitor'
9 10
require 'arel/collectors/bind'
require 'arel/collectors/sql_string'
D
Initial  
David Heinemeier Hansson 已提交
11 12 13

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

    autoload :Column
17
    autoload :ConnectionSpecification
18

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

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

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

    autoload_at 'active_record/connection_adapters/abstract/transaction' do
      autoload :ClosedTransaction
      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
      include Quoting, DatabaseStatements, SchemaStatements
65
      include DatabaseLimits
66
      include QueryCache
67
      include ActiveSupport::Callbacks
68
      include MonitorMixin
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 122 123 124 125 126 127 128 129
      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
        if @prepared_statements
          SQLString.new
        else
          BindCollector.new
        end
      end

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

134 135 136 137
      def schema_creation
        SchemaCreation.new self
      end

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

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

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

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

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

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

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

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

185 186 187 188
      def supports_bulk_alter?
        false
      end

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

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

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

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

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

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

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

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

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

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

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

250 251
      # QUOTING ==================================================

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

258 259
      # REFERENTIAL INTEGRITY ====================================

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

265 266
      # CONNECTION MANAGEMENT ====================================

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

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

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

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

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

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

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

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

327 328 329
      def open_transactions
        @transaction.number
      end
330

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

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

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

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

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

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

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

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

363
      protected
364

A
Aaron Patterson 已提交
365
      def translate_exception_class(e, sql)
366 367 368 369
        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 已提交
370
        exception
371 372
      end

373
      def log(sql, name = "SQL", binds = [], statement_name = nil)
374 375
        @instrumenter.instrument(
          "sql.active_record",
376 377 378 379 380
          :sql            => sql,
          :name           => name,
          :connection_id  => object_id,
          :statement_name => statement_name,
          :binds          => binds) { yield }
381
      rescue => e
A
Aaron Patterson 已提交
382
        raise translate_exception_class(e, sql)
383 384
      end

385
      def translate_exception(exception, message)
386
        # override in derived class
387
        ActiveRecord::StatementInvalid.new(message, exception)
388
      end
389 390

      def without_prepared_statement?(binds)
391
        !@prepared_statements || binds.empty?
392
      end
393 394

      def column_for(table_name, column_name) # :nodoc:
395 396
        column_name = column_name.to_s
        unless column = columns(table_name).detect { |c| c.name == column_name }
397 398 399 400
          raise ActiveRecordError, "No such column: #{table_name}.#{column_name}"
        end
        column
      end
401
    end
D
Initial  
David Heinemeier Hansson 已提交
402
  end
403
end