abstract_adapter.rb 10.9 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'
D
Initial  
David Heinemeier Hansson 已提交
9 10 11

module ActiveRecord
  module ConnectionAdapters # :nodoc:
12 13 14
    extend ActiveSupport::Autoload

    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 22
      autoload :TableDefinition
      autoload :Table
23
      autoload :AlterTable
24 25 26 27 28 29
    end

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

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

    autoload_at 'active_record/connection_adapters/abstract/transaction' do
      autoload :ClosedTransaction
      autoload :RealTransaction
      autoload :SavepointTransaction
45
      autoload :TransactionState
46 47
    end

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

69 70
      SIMPLE_INT = /\A\d+\z/

71
      define_callbacks :checkout, :checkin
72

73
      attr_accessor :visitor, :pool
74 75
      attr_reader :schema_cache, :owner, :logger
      alias :in_use? :owner
76

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
      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

93 94
      attr_reader :prepared_statements

95
      def initialize(connection, logger = nil, pool = nil) #:nodoc:
96 97
        super()

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

108 109 110 111
      def valid_type?(type)
        true
      end

112 113 114 115
      def schema_creation
        SchemaCreation.new self
      end

116 117
      def lease
        synchronize do
118 119
          unless in_use?
            @owner = Thread.current
120
          end
121
        end
122 123
      end

124 125 126 127 128
      def schema_cache=(cache)
        cache.connection = self
        @schema_cache = cache
      end

A
Aaron Patterson 已提交
129
      def expire
130
        @owner = nil
A
Aaron Patterson 已提交
131 132
      end

133 134 135 136 137
      def unprepared_visitor
        self.class::BindSubstitution.new self
      end

      def unprepared_statement
138 139
        old_prepared_statements, @prepared_statements = @prepared_statements, false
        old_visitor, @visitor = @visitor, unprepared_visitor
140 141
        yield
      ensure
142
        @visitor, @prepared_statements = old_visitor, old_prepared_statements
143 144
      end

S
Sebastian Martinez 已提交
145
      # Returns the human-readable name of the adapter. Use mixed case - one
146
      # can always use downcase if needed.
147
      def adapter_name
148 149
        'Abstract'
      end
150

151
      # Does this adapter support migrations?
152 153
      def supports_migrations?
        false
154
      end
155

156
      # Can this adapter determine the primary key for tables not attached
157
      # to an Active Record class, such as join tables?
158 159 160 161
      def supports_primary_key?
        false
      end

S
Sebastian Martinez 已提交
162
      # Does this adapter support DDL rollbacks in transactions? That is, would
163
      # CREATE TABLE or ALTER TABLE get rolled back by a transaction?
164 165 166
      def supports_ddl_transactions?
        false
      end
167

168 169 170 171
      def supports_bulk_alter?
        false
      end

172
      # Does this adapter support savepoints?
173 174 175
      def supports_savepoints?
        false
      end
176

177
      # Should primary key values be selected from their corresponding
S
Sebastian Martinez 已提交
178
      # sequence before the insert statement? If true, next_sequence_value
179
      # is called before each insert to set the record's primary key.
180
      def prefetch_primary_key?(table_name = nil)
181 182 183
        false
      end

184 185 186 187 188
      # Does this adapter support index sort order?
      def supports_index_sort_order?
        false
      end

189 190 191 192 193
      # Does this adapter support partial indices?
      def supports_partial_index?
        false
      end

194
      # Does this adapter support explain?
195 196 197 198
      def supports_explain?
        false
      end

199 200 201 202 203
      # Does this adapter support setting the isolation level for a transaction?
      def supports_transaction_isolation?
        false
      end

204
      # Does this adapter support database extensions?
205 206 207 208
      def supports_extensions?
        false
      end

209
      # Does this adapter support creating indexes in the same statement as
210
      # creating the table?
211 212 213 214
      def supports_indexes_in_create?
        false
      end

215 216 217 218 219 220 221 222
      # 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

223
      # A list of extensions, to be filled in by adapters that support them.
224 225 226 227
      def extensions
        []
      end

228
      # A list of index algorithms, to be filled by adapters that support them.
229 230 231 232
      def index_algorithms
        {}
      end

233 234
      # QUOTING ==================================================

235 236
      # Returns a bind substitution value given a bind +index+ and +column+
      # NOTE: The column param is currently being used by the sqlserver-adapter
237
      def substitute_at(column, index)
238
        Arel::Nodes::BindParam.new '?'
A
Aaron Patterson 已提交
239 240
      end

241 242
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
243
      # Override to turn off referential integrity while executing <tt>&block</tt>.
244
      def disable_referential_integrity
245 246 247
        yield
      end

248 249
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
250 251 252
      # 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.
253 254 255
      def active?
      end

P
Pratik Naik 已提交
256
      # Disconnects from the database if already connected, and establishes a
257 258
      # new connection with the database. Implementors should call super if they
      # override the default implementation.
259
      def reconnect!
260 261
        clear_cache!
        reset_transaction
262 263
      end

P
Pratik Naik 已提交
264 265
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
266
      def disconnect!
267 268
        clear_cache!
        reset_transaction
269 270
      end

271 272
      # Reset the state of this connection, directing the DBMS to clear
      # transactions and other connection-related server-side state. Usually a
P
Pratik Naik 已提交
273 274 275 276
      # database-dependent operation.
      #
      # The default implementation does nothing; the implementation should be
      # overridden by concrete adapters.
277
      def reset!
278
        # this should be overridden by concrete adapters
279 280
      end

A
Aaron Patterson 已提交
281 282
      ###
      # Clear any caching the database adapter may be doing, for example
S
Sebastian Martinez 已提交
283
      # clearing the prepared statement cache. This is database specific.
A
Aaron Patterson 已提交
284 285 286 287
      def clear_cache!
        # this should be overridden by concrete adapters
      end

288
      # Returns true if its required to reload the connection between requests for development mode.
289
      def requires_reloading?
290
        false
291 292
      end

P
Pratik Naik 已提交
293 294 295
      # 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.
296 297
      def verify!(*ignored)
        reconnect! unless active?
298
      end
299

P
Pratik Naik 已提交
300 301 302 303 304 305
      # 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.
306 307 308
      def raw_connection
        @connection
      end
309

310 311 312
      def open_transactions
        @transaction.number
      end
313

314
      def create_savepoint(name = nil)
J
Jonathan Viney 已提交
315
      end
316

317
      def rollback_to_savepoint(name = nil)
J
Jonathan Viney 已提交
318
      end
319

320
      def release_savepoint(name = nil)
J
Jonathan Viney 已提交
321
      end
322

323
      def case_sensitive_modifier(node, table_attribute)
324 325 326
        node
      end

327
      def case_sensitive_comparison(table, attribute, column, value)
328 329 330
        table_attr = table[attribute]
        value = case_sensitive_modifier(value, table_attr) unless value.nil?
        table_attr.eq(value)
331 332
      end

333 334 335 336
      def case_insensitive_comparison(table, attribute, column, value)
        table[attribute].lower.eq(table.lower(value))
      end

J
Jonathan Viney 已提交
337
      def current_savepoint_name
338
        "active_record_#{open_transactions}"
J
Jonathan Viney 已提交
339
      end
340

341 342 343 344 345
      # Check the connection back in to the connection pool
      def close
        pool.checkin self
      end

346
      protected
347

A
Aaron Patterson 已提交
348
      def translate_exception_class(e, sql)
349 350 351 352
        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 已提交
353
        exception
354 355
      end

356
      def log(sql, name = "SQL", binds = [], statement_name = nil)
357 358
        @instrumenter.instrument(
          "sql.active_record",
359 360 361 362 363
          :sql            => sql,
          :name           => name,
          :connection_id  => object_id,
          :statement_name => statement_name,
          :binds          => binds) { yield }
364
      rescue => e
A
Aaron Patterson 已提交
365
        raise translate_exception_class(e, sql)
366 367
      end

368
      def translate_exception(exception, message)
369
        # override in derived class
370
        ActiveRecord::StatementInvalid.new(message, exception)
371
      end
372 373

      def without_prepared_statement?(binds)
374
        !@prepared_statements || binds.empty?
375
      end
376
    end
D
Initial  
David Heinemeier Hansson 已提交
377
  end
378
end