abstract_adapter.rb 11.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
      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 valid_type?(type)
        true
      end

111 112 113 114
      def schema_creation
        SchemaCreation.new self
      end

115 116
      def lease
        synchronize do
117 118 119 120
          unless in_use
            @in_use   = true
            @last_use = Time.now
          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 130 131 132
      def expire
        @in_use = false
      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

S
Sebastian Martinez 已提交
151
      # Does this adapter support migrations? Backend specific, as the
152
      # abstract adapter always returns +false+.
153 154
      def supports_migrations?
        false
155
      end
156

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

S
Sebastian Martinez 已提交
164
      # Does this adapter support using DISTINCT within COUNT? This is +true+
165 166 167 168
      # for all adapters except sqlite.
      def supports_count_distinct?
        true
      end
169

S
Sebastian Martinez 已提交
170 171 172
      # 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.
173 174 175
      def supports_ddl_transactions?
        false
      end
176

177 178 179 180
      def supports_bulk_alter?
        false
      end

181 182
      # Does this adapter support savepoints? PostgreSQL and MySQL do,
      # SQLite < 3.6.8 does not.
183 184 185
      def supports_savepoints?
        false
      end
186

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

195 196 197 198 199
      # Does this adapter support index sort order?
      def supports_index_sort_order?
        false
      end

200 201 202 203 204
      # Does this adapter support partial indices?
      def supports_partial_index?
        false
      end

205 206 207 208 209 210
      # Does this adapter support explain? As of this writing sqlite3,
      # mysql2, and postgresql are the only ones that do.
      def supports_explain?
        false
      end

211 212 213 214 215
      # Does this adapter support setting the isolation level for a transaction?
      def supports_transaction_isolation?
        false
      end

X
Xavier Noria 已提交
216 217
      # Does this adapter support database extensions? As of this writing only
      # postgresql does.
218 219 220 221
      def supports_extensions?
        false
      end

222 223 224 225 226 227 228 229
      # 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 已提交
230 231
      # A list of extensions, to be filled in by adapters that support them. At
      # the moment only postgresql does.
232 233 234 235
      def extensions
        []
      end

236 237
      # A list of index algorithms, to be filled by adapters that support them.
      # MySQL and PostgreSQL have support for them right now.
238 239 240 241
      def index_algorithms
        {}
      end

242 243
      # QUOTING ==================================================

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

250 251
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
252
      # Override to turn off referential integrity while executing <tt>&block</tt>.
253
      def disable_referential_integrity
254 255 256
        yield
      end

257 258
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
259 260 261
      # 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.
262 263 264
      def active?
      end

265 266 267 268 269 270
      # Adapter should redefine this if it needs a threadsafe way to approximate
      # if the connection is active
      def active_threadsafe?
        active?
      end

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

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

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

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

303 304
      # 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.
305
      def requires_reloading?
306
        false
307 308
      end

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

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

326 327 328
      def open_transactions
        @transaction.number
      end
329

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

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

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

339 340 341 342
      def case_sensitive_modifier(node)
        node
      end

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

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

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

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

361
      protected
362

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

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

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

      def without_prepared_statement?(binds)
389
        !@prepared_statements || binds.empty?
390
      end
391
    end
D
Initial  
David Heinemeier Hansson 已提交
392
  end
393
end