abstract_adapter.rb 10.8 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
      def unprepared_statement
134
        old_prepared_statements, @prepared_statements = @prepared_statements, false
135 136
        yield
      ensure
137
        @prepared_statements = old_prepared_statements
138 139
      end

S
Sebastian Martinez 已提交
140
      # Returns the human-readable name of the adapter. Use mixed case - one
141
      # can always use downcase if needed.
142
      def adapter_name
143 144
        'Abstract'
      end
145

146
      # Does this adapter support migrations?
147 148
      def supports_migrations?
        false
149
      end
150

151
      # Can this adapter determine the primary key for tables not attached
152
      # to an Active Record class, such as join tables?
153 154 155 156
      def supports_primary_key?
        false
      end

S
Sebastian Martinez 已提交
157
      # Does this adapter support DDL rollbacks in transactions? That is, would
158
      # CREATE TABLE or ALTER TABLE get rolled back by a transaction?
159 160 161
      def supports_ddl_transactions?
        false
      end
162

163 164 165 166
      def supports_bulk_alter?
        false
      end

167
      # Does this adapter support savepoints?
168 169 170
      def supports_savepoints?
        false
      end
171

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

179 180 181 182 183
      # Does this adapter support index sort order?
      def supports_index_sort_order?
        false
      end

184 185 186 187 188
      # Does this adapter support partial indices?
      def supports_partial_index?
        false
      end

189
      # Does this adapter support explain?
190 191 192 193
      def supports_explain?
        false
      end

194 195 196 197 198
      # Does this adapter support setting the isolation level for a transaction?
      def supports_transaction_isolation?
        false
      end

199
      # Does this adapter support database extensions?
200 201 202 203
      def supports_extensions?
        false
      end

204
      # Does this adapter support creating indexes in the same statement as
205
      # creating the table?
206 207 208 209
      def supports_indexes_in_create?
        false
      end

210 211 212 213 214 215 216 217
      # 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

218
      # A list of extensions, to be filled in by adapters that support them.
219 220 221 222
      def extensions
        []
      end

223
      # A list of index algorithms, to be filled by adapters that support them.
224 225 226 227
      def index_algorithms
        {}
      end

228 229
      # QUOTING ==================================================

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

236 237
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
238
      # Override to turn off referential integrity while executing <tt>&block</tt>.
239
      def disable_referential_integrity
240 241 242
        yield
      end

243 244
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
245 246 247
      # 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.
248 249 250
      def active?
      end

P
Pratik Naik 已提交
251
      # Disconnects from the database if already connected, and establishes a
252 253
      # new connection with the database. Implementors should call super if they
      # override the default implementation.
254
      def reconnect!
255 256
        clear_cache!
        reset_transaction
257 258
      end

P
Pratik Naik 已提交
259 260
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
261
      def disconnect!
262 263
        clear_cache!
        reset_transaction
264 265
      end

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

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

283
      # Returns true if its required to reload the connection between requests for development mode.
284
      def requires_reloading?
285
        false
286 287
      end

P
Pratik Naik 已提交
288 289 290
      # 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.
291 292
      def verify!(*ignored)
        reconnect! unless active?
293
      end
294

P
Pratik Naik 已提交
295 296 297 298 299 300
      # 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.
301 302 303
      def raw_connection
        @connection
      end
304

305 306 307
      def open_transactions
        @transaction.number
      end
308

309
      def create_savepoint(name = nil)
J
Jonathan Viney 已提交
310
      end
311

312
      def rollback_to_savepoint(name = nil)
J
Jonathan Viney 已提交
313
      end
314

315
      def release_savepoint(name = nil)
J
Jonathan Viney 已提交
316
      end
317

318
      def case_sensitive_modifier(node, table_attribute)
319 320 321
        node
      end

322
      def case_sensitive_comparison(table, attribute, column, value)
323 324 325
        table_attr = table[attribute]
        value = case_sensitive_modifier(value, table_attr) unless value.nil?
        table_attr.eq(value)
326 327
      end

328 329 330 331
      def case_insensitive_comparison(table, attribute, column, value)
        table[attribute].lower.eq(table.lower(value))
      end

J
Jonathan Viney 已提交
332
      def current_savepoint_name
333
        "active_record_#{open_transactions}"
J
Jonathan Viney 已提交
334
      end
335

336 337 338 339 340
      # Check the connection back in to the connection pool
      def close
        pool.checkin self
      end

341
      protected
342

A
Aaron Patterson 已提交
343
      def translate_exception_class(e, sql)
344 345 346 347
        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 已提交
348
        exception
349 350
      end

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

363
      def translate_exception(exception, message)
364
        # override in derived class
365
        ActiveRecord::StatementInvalid.new(message, exception)
366
      end
367 368

      def without_prepared_statement?(binds)
369
        !@prepared_statements || binds.empty?
370
      end
371
    end
D
Initial  
David Heinemeier Hansson 已提交
372
  end
373
end