abstract_adapter.rb 7.8 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1 2
require 'benchmark'
require 'date'
3 4
require 'bigdecimal'
require 'bigdecimal/util'
D
Initial  
David Heinemeier Hansson 已提交
5

J
Joshua Peek 已提交
6
# TODO: Autoload these files
7 8 9 10
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 已提交
11
require 'active_record/connection_adapters/abstract/connection_pool'
12
require 'active_record/connection_adapters/abstract/connection_specification'
13
require 'active_record/connection_adapters/abstract/query_cache'
14

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

D
Initial  
David Heinemeier Hansson 已提交
36
      @@row_even = true
37

38
      def initialize(connection, logger = nil) #:nodoc:
D
Initial  
David Heinemeier Hansson 已提交
39 40
        @connection, @logger = connection, logger
        @runtime = 0
41
        @last_verification = 0
42
        @query_cache_enabled = false
D
Initial  
David Heinemeier Hansson 已提交
43 44
      end

45 46
      # Returns the human-readable name of the adapter.  Use mixed case - one
      # can always use downcase if needed.
47
      def adapter_name
48 49
        'Abstract'
      end
50

51
      # Does this adapter support migrations?  Backend specific, as the
52
      # abstract adapter always returns +false+.
53 54
      def supports_migrations?
        false
55
      end
56

57 58 59 60 61
      # Does this adapter support using DISTINCT within COUNT?  This is +true+
      # for all adapters except sqlite.
      def supports_count_distinct?
        true
      end
62

63 64 65 66 67 68
      # 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
69 70 71 72 73 74
      
      # Does this adapter support savepoints? PostgreSQL and MySQL do, SQLite
      # does not.
      def supports_savepoints?
        false
      end
75

76 77 78 79
      # 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.
80
      def prefetch_primary_key?(table_name = nil)
81 82 83
        false
      end

84
      def reset_runtime #:nodoc:
85 86
        rt, @runtime = @runtime, 0
        rt
87
      end
88

89 90
      # QUOTING ==================================================

91 92 93 94 95
      # Override to return the quoted table name. Defaults to column quoting.
      def quote_table_name(name)
        quote_column_name(name)
      end

96 97
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
98
      # Override to turn off referential integrity while executing <tt>&block</tt>.
99 100 101 102
      def disable_referential_integrity(&block)
        yield
      end

103 104
      # CONNECTION MANAGEMENT ====================================

P
Pratik Naik 已提交
105 106 107
      # 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.
108
      def active?
109
        @active != false
110 111
      end

P
Pratik Naik 已提交
112 113
      # Disconnects from the database if already connected, and establishes a
      # new connection with the database.
114
      def reconnect!
115 116 117
        @active = true
      end

P
Pratik Naik 已提交
118 119
      # Disconnects from the database if already connected. Otherwise, this
      # method does nothing.
120 121
      def disconnect!
        @active = false
122 123
      end

124 125
      # Reset the state of this connection, directing the DBMS to clear
      # transactions and other connection-related server-side state. Usually a
P
Pratik Naik 已提交
126 127 128 129
      # database-dependent operation.
      #
      # The default implementation does nothing; the implementation should be
      # overridden by concrete adapters.
130
      def reset!
131
        # this should be overridden by concrete adapters
132 133
      end

134
      # Returns true if its safe to reload the connection between requests for development mode.
135
      def requires_reloading?
136
        true
137 138
      end

P
Pratik Naik 已提交
139 140 141
      # 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.
142 143
      def verify!(*ignored)
        reconnect! unless active?
144
      end
145

P
Pratik Naik 已提交
146 147 148 149 150 151
      # 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.
152 153 154
      def raw_connection
        @connection
      end
155

156 157 158 159 160 161 162 163 164 165 166 167
      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
J
Jonathan Viney 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181
      
      def create_savepoint
      end
      
      def rollback_to_savepoint
      end
      
      def release_savepoint
      end
      
      def current_savepoint_name
        "rails_savepoint_#{open_transactions}"
      end
      
182 183 184
      # Whether this AbstractAdapter is currently being used inside a unit test
      # with transactional fixtures turned on. See DatabaseStatements#transaction
      # for more information about the effect of this option.
J
Jonathan Viney 已提交
185
      attr_accessor :transactional_fixtures
186

J
Jeremy Kemper 已提交
187
      def log_info(sql, name, ms)
188
        if @logger && @logger.debug?
J
Jeremy Kemper 已提交
189
          name = '%s (%.1fms)' % [name || 'SQL', ms]
190
          @logger.debug(format_log_entry(name, sql.squeeze(' ')))
191 192
        end
      end
193

194
      protected
195
        def log(sql, name)
196
          if block_given?
197
            result = nil
J
Jeremy Kemper 已提交
198 199 200
            ms = Benchmark.ms { result = yield }
            @runtime += ms
            log_info(sql, name, ms)
201
            result
202 203 204
          else
            log_info(sql, name, 0)
            nil
D
Initial  
David Heinemeier Hansson 已提交
205
          end
206
        rescue Exception => e
207
          # Log message and raise exception.
208
          # Set last_verification to 0, so that connection gets verified
209 210
          # upon reentering the request loop
          @last_verification = 0
211 212 213
          message = "#{e.class.name}: #{e.message}: #{sql}"
          log_info(message, name, 0)
          raise ActiveRecord::StatementInvalid, message
D
Initial  
David Heinemeier Hansson 已提交
214 215 216
        end

        def format_log_entry(message, dump = nil)
217
          if ActiveRecord::Base.colorize_logging
218 219 220
            if @@row_even
              @@row_even = false
              message_color, dump_color = "4;36;1", "0;1"
221
            else
222 223
              @@row_even = true
              message_color, dump_color = "4;35;1", "0"
224
            end
225

226 227
            log_entry = "  \e[#{message_color}m#{message}\e[0m   "
            log_entry << "\e[#{dump_color}m%#{String === dump ? 's' : 'p'}\e[0m" % dump if dump
228
            log_entry
D
Initial  
David Heinemeier Hansson 已提交
229
          else
230
            "%s  %s" % [message, dump]
D
Initial  
David Heinemeier Hansson 已提交
231 232
          end
        end
233
    end
D
Initial  
David Heinemeier Hansson 已提交
234
  end
235
end