abstract_adapter.rb 6.6 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

6 7 8 9
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 已提交
10
require 'active_record/connection_adapters/abstract/connection_pool'
11
require 'active_record/connection_adapters/abstract/connection_specification'
12
require 'active_record/connection_adapters/abstract/query_cache'
13

D
Initial  
David Heinemeier Hansson 已提交
14 15 16 17 18
module ActiveRecord
  module ConnectionAdapters # :nodoc:
    # All the concrete database adapters follow the interface laid down in this class.
    # You can use this interface directly by borrowing the database connection from the Base with
    # Base.connection.
19 20 21 22 23 24
    #
    # Most of the methods in the adapter are useful during migrations.  Most
    # notably, SchemaStatements#create_table, SchemaStatements#drop_table,
    # SchemaStatements#add_index, SchemaStatements#remove_index,
    # SchemaStatements#add_column, SchemaStatements#change_column and
    # SchemaStatements#remove_column are very useful.
D
Initial  
David Heinemeier Hansson 已提交
25
    class AbstractAdapter
26
      include Quoting, DatabaseStatements, SchemaStatements
27
      include QueryCache
D
Initial  
David Heinemeier Hansson 已提交
28
      @@row_even = true
29

30
      def initialize(connection, logger = nil) #:nodoc:
D
Initial  
David Heinemeier Hansson 已提交
31 32
        @connection, @logger = connection, logger
        @runtime = 0
33
        @last_verification = 0
34
        @query_cache_enabled = false
D
Initial  
David Heinemeier Hansson 已提交
35 36
      end

37 38
      # Returns the human-readable name of the adapter.  Use mixed case - one
      # can always use downcase if needed.
39
      def adapter_name
40 41
        'Abstract'
      end
42

43
      # Does this adapter support migrations?  Backend specific, as the
44
      # abstract adapter always returns +false+.
45 46
      def supports_migrations?
        false
47
      end
48

49 50 51 52 53
      # Does this adapter support using DISTINCT within COUNT?  This is +true+
      # for all adapters except sqlite.
      def supports_count_distinct?
        true
      end
54

55 56 57 58 59 60 61
      # 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

62 63 64 65
      # 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.
66
      def prefetch_primary_key?(table_name = nil)
67 68 69
        false
      end

70
      def reset_runtime #:nodoc:
71 72
        rt, @runtime = @runtime, 0
        rt
73
      end
74

75 76
      # QUOTING ==================================================

77 78 79 80 81
      # Override to return the quoted table name. Defaults to column quoting.
      def quote_table_name(name)
        quote_column_name(name)
      end

82 83
      # REFERENTIAL INTEGRITY ====================================

P
Pratik Naik 已提交
84
      # Override to turn off referential integrity while executing <tt>&block</tt>.
85 86 87 88
      def disable_referential_integrity(&block)
        yield
      end

89 90 91 92
      # CONNECTION MANAGEMENT ====================================

      # Is this connection active and ready to perform queries?
      def active?
93
        @active != false
94 95 96 97
      end

      # Close this connection and open a new one in its place.
      def reconnect!
98 99 100 101 102 103
        @active = true
      end

      # Close this connection
      def disconnect!
        @active = false
104 105
      end

106 107 108 109 110 111
      # Reset the state of this connection, directing the DBMS to clear
      # transactions and other connection-related server-side state. Usually a
      # database-dependent operation; the default method simply executes a
      # ROLLBACK and swallows any exceptions which is probably not enough to
      # ensure the connection is clean.
      def reset!
112 113 114
        silence_stderr do # postgres prints on stderr when you do this w/o a txn
          execute "ROLLBACK" rescue nil
        end
115 116
      end

117 118
      # Returns true if its safe 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.
119
      def requires_reloading?
120 121 122
        false
      end

123 124
      # Lazily verify this connection, calling <tt>active?</tt> only if it
      # hasn't been called for +timeout+ seconds.
125 126 127 128 129 130 131
      def verify!(timeout)
        now = Time.now.to_i
        if (now - @last_verification) > timeout
          reconnect! unless active?
          @last_verification = now
        end
      end
132

133 134 135 136 137 138
      # Provides access to the underlying database connection. Useful for
      # when you need to call a proprietary method such as postgresql's lo_*
      # methods
      def raw_connection
        @connection
      end
139

140 141 142 143 144 145 146 147 148 149 150 151 152
      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

153
      def log_info(sql, name, runtime)
154 155 156 157 158
        if @logger && @logger.debug?
          name = "#{name.nil? ? "SQL" : name} (#{sprintf("%f", runtime)})"
          @logger.debug format_log_entry(name, sql.squeeze(' '))
        end
      end
159

160
      protected
161
        def log(sql, name)
162
          if block_given?
163 164 165 166 167
            result = nil
            seconds = Benchmark.realtime { result = yield }
            @runtime += seconds
            log_info(sql, name, seconds)
            result
168 169 170
          else
            log_info(sql, name, 0)
            nil
D
Initial  
David Heinemeier Hansson 已提交
171
          end
172
        rescue Exception => e
173
          # Log message and raise exception.
174
          # Set last_verification to 0, so that connection gets verified
175 176
          # upon reentering the request loop
          @last_verification = 0
177 178 179
          message = "#{e.class.name}: #{e.message}: #{sql}"
          log_info(message, name, 0)
          raise ActiveRecord::StatementInvalid, message
D
Initial  
David Heinemeier Hansson 已提交
180 181 182
        end

        def format_log_entry(message, dump = nil)
183
          if ActiveRecord::Base.colorize_logging
184 185 186
            if @@row_even
              @@row_even = false
              message_color, dump_color = "4;36;1", "0;1"
187
            else
188 189
              @@row_even = true
              message_color, dump_color = "4;35;1", "0"
190
            end
191

192 193
            log_entry = "  \e[#{message_color}m#{message}\e[0m   "
            log_entry << "\e[#{dump_color}m%#{String === dump ? 's' : 'p'}\e[0m" % dump if dump
194
            log_entry
D
Initial  
David Heinemeier Hansson 已提交
195
          else
196
            "%s  %s" % [message, dump]
D
Initial  
David Heinemeier Hansson 已提交
197 198
          end
        end
199
    end
D
Initial  
David Heinemeier Hansson 已提交
200
  end
201
end