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'
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
      attr_reader :schema_cache, :last_use, :in_use, :logger
75
      alias :in_use? :in_use
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
      def initialize(connection, logger = nil, pool = nil) #:nodoc:
94 95
        super()

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

107 108 109 110
      def bind_substitution_visitor
        @bind_sub_visitor ||= visitor.dup.extend(Arel::Visitors::BindVisitor)
      end

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

115 116 117 118
      def schema_creation
        SchemaCreation.new self
      end

119 120
      def lease
        synchronize do
121 122 123 124
          unless in_use
            @in_use   = true
            @last_use = Time.now
          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 134 135 136
      def expire
        @in_use = false
      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

S
Sebastian Martinez 已提交
155
      # Does this adapter support migrations? Backend specific, as the
156
      # abstract adapter always returns +false+.
157 158
      def supports_migrations?
        false
159
      end
160

161
      # Can this adapter determine the primary key for tables not attached
S
Sebastian Martinez 已提交
162
      # to an Active Record class, such as join tables? Backend specific, as
163 164 165 166 167
      # the abstract adapter always returns +false+.
      def supports_primary_key?
        false
      end

S
Sebastian Martinez 已提交
168
      # Does this adapter support using DISTINCT within COUNT? This is +true+
169 170 171 172
      # for all adapters except sqlite.
      def supports_count_distinct?
        true
      end
173

S
Sebastian Martinez 已提交
174 175 176
      # Does this adapter support DDL rollbacks in transactions? That is, would
      # CREATE TABLE or ALTER TABLE get rolled back by a transaction? PostgreSQL,
      # SQL Server, and others support this. MySQL and others do not.
177 178 179
      def supports_ddl_transactions?
        false
      end
180

181 182 183 184
      def supports_bulk_alter?
        false
      end

185 186
      # Does this adapter support savepoints? PostgreSQL and MySQL do,
      # SQLite < 3.6.8 does not.
187 188 189
      def supports_savepoints?
        false
      end
190

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

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

204 205 206 207 208
      # Does this adapter support partial indices?
      def supports_partial_index?
        false
      end

209 210 211 212 213 214
      # Does this adapter support explain? As of this writing sqlite3,
      # mysql2, and postgresql are the only ones that do.
      def supports_explain?
        false
      end

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

X
Xavier Noria 已提交
220 221
      # Does this adapter support database extensions? As of this writing only
      # postgresql does.
222 223 224 225
      def supports_extensions?
        false
      end

226 227 228 229 230 231 232 233
      # 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

X
Xavier Noria 已提交
234 235
      # A list of extensions, to be filled in by adapters that support them. At
      # the moment only postgresql does.
236 237 238 239
      def extensions
        []
      end

240 241
      # A list of index algorithms, to be filled by adapters that support them.
      # MySQL and PostgreSQL have support for them right now.
242 243 244 245
      def index_algorithms
        {}
      end

246 247
      # QUOTING ==================================================

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

254 255
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
256
      # Override to turn off referential integrity while executing <tt>&block</tt>.
257
      def disable_referential_integrity
258 259 260
        yield
      end

261 262
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
263 264 265
      # 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.
266 267 268
      def active?
      end

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

P
Pratik Naik 已提交
277 278
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
279
      def disconnect!
280 281
        clear_cache!
        reset_transaction
282 283
      end

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

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

301 302
      # Returns true if its required to reload the connection between requests for development mode.
      # This is not the case for Ruby/MySQL and it's not necessary for any adapters except SQLite.
303
      def requires_reloading?
304
        false
305 306
      end

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

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

324 325 326
      def open_transactions
        @transaction.number
      end
327

328
      def create_savepoint(name = nil)
J
Jonathan Viney 已提交
329
      end
330

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

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

337 338 339 340
      def case_sensitive_modifier(node)
        node
      end

341 342 343 344
      def case_insensitive_comparison(table, attribute, column, value)
        table[attribute].lower.eq(table.lower(value))
      end

J
Jonathan Viney 已提交
345
      def current_savepoint_name
346
        "active_record_#{open_transactions}"
J
Jonathan Viney 已提交
347
      end
348

349 350 351 352 353
      # Check the connection back in to the connection pool
      def close
        pool.checkin self
      end

354
      protected
355

356 357 358 359 360 361 362
      def translate_exception(e, sql)
        message = "#{e.class.name}: #{e.message}: #{sql}"
        @logger.error message if @logger
        exception = translate_exception(e, message)
        exception.set_backtrace e.backtrace
      end

363
      def log(sql, name = "SQL", binds = [], statement_name = nil)
364 365
        @instrumenter.instrument(
          "sql.active_record",
366 367 368 369 370
          :sql            => sql,
          :name           => name,
          :connection_id  => object_id,
          :statement_name => statement_name,
          :binds          => binds) { yield }
371
      rescue => e
372
        raise translate_exception(e, sql)
373 374
      end

375
      def translate_exception(exception, message)
376
        # override in derived class
377
        ActiveRecord::StatementInvalid.new(message, exception)
378
      end
379 380

      def without_prepared_statement?(binds)
381
        !@prepared_statements || binds.empty?
382
      end
383
    end
D
Initial  
David Heinemeier Hansson 已提交
384
  end
385
end