abstract_adapter.rb 7.7 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'
D
Initial  
David Heinemeier Hansson 已提交
5

J
Joshua Peek 已提交
6
# TODO: Autoload these files
7
require 'active_record/connection_adapters/column'
8 9 10 11
require 'active_record/connection_adapters/abstract/schema_definitions'
require 'active_record/connection_adapters/abstract/schema_statements'
require 'active_record/connection_adapters/abstract/database_statements'
require 'active_record/connection_adapters/abstract/quoting'
N
Nick 已提交
12
require 'active_record/connection_adapters/abstract/connection_pool'
13
require 'active_record/connection_adapters/abstract/connection_specification'
14
require 'active_record/connection_adapters/abstract/query_cache'
15
require 'active_record/connection_adapters/abstract/database_limits'
A
Aaron Patterson 已提交
16
require 'active_record/result'
17

D
Initial  
David Heinemeier Hansson 已提交
18 19
module ActiveRecord
  module ConnectionAdapters # :nodoc:
20
    # Active Record supports multiple database systems. AbstractAdapter and
P
Pratik Naik 已提交
21 22 23 24 25 26
    # 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 已提交
27
    # All the concrete database adapters follow the interface laid down in this class.
P
Pratik Naik 已提交
28 29
    # ActiveRecord::Base.connection returns an AbstractAdapter object, which
    # you can use.
30
    #
P
Pratik Naik 已提交
31 32
    # 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 已提交
33
    class AbstractAdapter
34
      include Quoting, DatabaseStatements, SchemaStatements
35
      include DatabaseLimits
36
      include QueryCache
37
      include ActiveSupport::Callbacks
38

39
      define_callbacks :checkout, :checkin
40

41
      def initialize(connection, logger = nil) #:nodoc:
42
        @active = nil
D
Initial  
David Heinemeier Hansson 已提交
43
        @connection, @logger = connection, logger
44
        @query_cache_enabled = false
A
Aaron Patterson 已提交
45
        @query_cache = Hash.new { |h,sql| h[sql] = {} }
46
        @instrumenter = ActiveSupport::Notifications.instrumenter
D
Initial  
David Heinemeier Hansson 已提交
47 48
      end

49 50
      # Returns the human-readable name of the adapter.  Use mixed case - one
      # can always use downcase if needed.
51
      def adapter_name
52 53
        'Abstract'
      end
54

55
      # Does this adapter support migrations?  Backend specific, as the
56
      # abstract adapter always returns +false+.
57 58
      def supports_migrations?
        false
59
      end
60

61
      # Can this adapter determine the primary key for tables not attached
62
      # to an Active Record class, such as join tables?  Backend specific, as
63 64 65 66 67
      # the abstract adapter always returns +false+.
      def supports_primary_key?
        false
      end

68 69 70 71 72
      # Does this adapter support using DISTINCT within COUNT?  This is +true+
      # for all adapters except sqlite.
      def supports_count_distinct?
        true
      end
73

74 75 76 77 78 79
      # 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.
      def supports_ddl_transactions?
        false
      end
80

81 82 83 84
      def supports_bulk_alter?
        false
      end

85 86
      # Does this adapter support savepoints? PostgreSQL and MySQL do,
      # SQLite < 3.6.8 does not.
87 88 89
      def supports_savepoints?
        false
      end
90

91 92 93 94
      # Should primary key values be selected from their corresponding
      # sequence before the insert statement?  If true, next_sequence_value
      # is called before each insert to set the record's primary key.
      # This is false for all adapters but Firebird.
95
      def prefetch_primary_key?(table_name = nil)
96 97 98
        false
      end

99 100
      # QUOTING ==================================================

101 102 103 104 105
      # Override to return the quoted table name. Defaults to column quoting.
      def quote_table_name(name)
        quote_column_name(name)
      end

A
Aaron Patterson 已提交
106
      # Returns a bind substitution value given a +column+ and list of current
107 108
      # +binds+
      def substitute_for(column, binds)
A
Aaron Patterson 已提交
109 110 111
        Arel.sql '?'
      end

112 113
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
114
      # Override to turn off referential integrity while executing <tt>&block</tt>.
115
      def disable_referential_integrity
116 117 118
        yield
      end

119 120
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
121 122 123
      # 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.
124
      def active?
125
        @active != false
126 127
      end

P
Pratik Naik 已提交
128 129
      # Disconnects from the database if already connected, and establishes a
      # new connection with the database.
130
      def reconnect!
131 132 133
        @active = true
      end

P
Pratik Naik 已提交
134 135
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
136 137
      def disconnect!
        @active = false
138 139
      end

140 141
      # Reset the state of this connection, directing the DBMS to clear
      # transactions and other connection-related server-side state. Usually a
P
Pratik Naik 已提交
142 143 144 145
      # database-dependent operation.
      #
      # The default implementation does nothing; the implementation should be
      # overridden by concrete adapters.
146
      def reset!
147
        # this should be overridden by concrete adapters
148 149
      end

A
Aaron Patterson 已提交
150 151 152 153 154 155 156
      ###
      # Clear any caching the database adapter may be doing, for example
      # clearing the prepared statement cache.  This is database specific.
      def clear_cache!
        # this should be overridden by concrete adapters
      end

157 158
      # 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.
159
      def requires_reloading?
160
        false
161 162
      end

P
Pratik Naik 已提交
163 164 165
      # 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.
166 167
      def verify!(*ignored)
        reconnect! unless active?
168
      end
169

P
Pratik Naik 已提交
170 171 172 173 174 175
      # 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.
176 177 178
      def raw_connection
        @connection
      end
179

180 181 182 183 184 185 186 187 188 189 190 191
      def open_transactions
        @open_transactions ||= 0
      end

      def increment_open_transactions
        @open_transactions ||= 0
        @open_transactions += 1
      end

      def decrement_open_transactions
        @open_transactions -= 1
      end
192 193 194 195 196

      def transaction_joinable=(joinable)
        @transaction_joinable = joinable
      end

J
Jonathan Viney 已提交
197 198
      def create_savepoint
      end
199

J
Jonathan Viney 已提交
200 201
      def rollback_to_savepoint
      end
202

J
Jonathan Viney 已提交
203 204
      def release_savepoint
      end
205

J
Jonathan Viney 已提交
206
      def current_savepoint_name
207
        "active_record_#{open_transactions}"
J
Jonathan Viney 已提交
208
      end
209

210
      protected
211

212 213 214 215 216 217 218
        def log(sql, name = "SQL", binds = [])
          @instrumenter.instrument(
            "sql.active_record",
            :sql           => sql,
            :name          => name,
            :connection_id => object_id,
            :binds         => binds) { yield }
219
        rescue Exception => e
220
          message = "#{e.class.name}: #{e.message}: #{sql}"
221
          @logger.debug message if @logger
222
          raise translate_exception(e, message)
D
Initial  
David Heinemeier Hansson 已提交
223 224
        end

225 226 227 228
        def translate_exception(e, message)
          # override in derived class
          ActiveRecord::StatementInvalid.new(message)
        end
229

230
    end
D
Initial  
David Heinemeier Hansson 已提交
231
  end
232
end