abstract_adapter.rb 11.0 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 bind_substitution_visitor
        @bind_sub_visitor ||= visitor.dup.extend(Arel::Visitors::BindVisitor)
      end

112 113 114 115
      def valid_type?(type)
        true
      end

116 117 118 119
      def schema_creation
        SchemaCreation.new self
      end

120 121
      def lease
        synchronize do
122 123
          unless in_use?
            @owner = Thread.current
124
          end
125
        end
126 127
      end

128 129 130 131 132
      def schema_cache=(cache)
        cache.connection = self
        @schema_cache = cache
      end

A
Aaron Patterson 已提交
133
      def expire
134
        @owner = nil
A
Aaron Patterson 已提交
135 136
      end

137 138 139 140 141
      def unprepared_visitor
        self.class::BindSubstitution.new self
      end

      def unprepared_statement
142 143
        old_prepared_statements, @prepared_statements = @prepared_statements, false
        old_visitor, @visitor = @visitor, unprepared_visitor
144 145
        yield
      ensure
146
        @visitor, @prepared_statements = old_visitor, old_prepared_statements
147 148
      end

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

155
      # Does this adapter support migrations?
156 157
      def supports_migrations?
        false
158
      end
159

160
      # Can this adapter determine the primary key for tables not attached
161
      # to an Active Record class, such as join tables?
162 163 164 165
      def supports_primary_key?
        false
      end

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

172 173 174 175
      def supports_bulk_alter?
        false
      end

176
      # Does this adapter support savepoints?
177 178 179
      def supports_savepoints?
        false
      end
180

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

188 189 190 191 192
      # Does this adapter support index sort order?
      def supports_index_sort_order?
        false
      end

193 194 195 196 197
      # Does this adapter support partial indices?
      def supports_partial_index?
        false
      end

198
      # Does this adapter support explain?
199 200 201 202
      def supports_explain?
        false
      end

203 204 205 206 207
      # Does this adapter support setting the isolation level for a transaction?
      def supports_transaction_isolation?
        false
      end

208
      # Does this adapter support database extensions?
209 210 211 212
      def supports_extensions?
        false
      end

213
      # Does this adapter support creating indexes in the same statement as
214
      # creating the table?
215 216 217 218
      def supports_indexes_in_create?
        false
      end

219 220 221 222 223 224 225 226
      # 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

227
      # A list of extensions, to be filled in by adapters that support them.
228 229 230 231
      def extensions
        []
      end

232
      # A list of index algorithms, to be filled by adapters that support them.
233 234 235 236
      def index_algorithms
        {}
      end

237 238
      # QUOTING ==================================================

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

245 246
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
247
      # Override to turn off referential integrity while executing <tt>&block</tt>.
248
      def disable_referential_integrity
249 250 251
        yield
      end

252 253
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
254 255 256
      # 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.
257 258 259
      def active?
      end

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

P
Pratik Naik 已提交
268 269
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
270
      def disconnect!
271 272
        clear_cache!
        reset_transaction
273 274
      end

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

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

292
      # Returns true if its required to reload the connection between requests for development mode.
293
      def requires_reloading?
294
        false
295 296
      end

P
Pratik Naik 已提交
297 298 299
      # 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.
300 301
      def verify!(*ignored)
        reconnect! unless active?
302
      end
303

P
Pratik Naik 已提交
304 305 306 307 308 309
      # 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.
310 311 312
      def raw_connection
        @connection
      end
313

314 315 316
      def open_transactions
        @transaction.number
      end
317

318
      def create_savepoint(name = nil)
J
Jonathan Viney 已提交
319
      end
320

321
      def rollback_to_savepoint(name = nil)
J
Jonathan Viney 已提交
322
      end
323

324
      def release_savepoint(name = nil)
J
Jonathan Viney 已提交
325
      end
326

327 328 329 330
      def case_sensitive_modifier(node)
        node
      end

331 332 333 334 335
      def case_sensitive_comparison(table, attribute, column, value)
        value = case_sensitive_modifier(value) unless value.nil?
        table[attribute].eq(value)
      end

336 337 338 339
      def case_insensitive_comparison(table, attribute, column, value)
        table[attribute].lower.eq(table.lower(value))
      end

J
Jonathan Viney 已提交
340
      def current_savepoint_name
341
        "active_record_#{open_transactions}"
J
Jonathan Viney 已提交
342
      end
343

344 345 346 347 348
      # Check the connection back in to the connection pool
      def close
        pool.checkin self
      end

349
      protected
350

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

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

371
      def translate_exception(exception, message)
372
        # override in derived class
373
        ActiveRecord::StatementInvalid.new(message, exception)
374
      end
375 376

      def without_prepared_statement?(binds)
377
        !@prepared_statements || binds.empty?
378
      end
379
    end
D
Initial  
David Heinemeier Hansson 已提交
380
  end
381
end