abstract_adapter.rb 5.3 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 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'
require 'active_record/connection_adapters/abstract/connection_specification'
11
require 'active_record/connection_adapters/abstract/query_cache'
12

D
Initial  
David Heinemeier Hansson 已提交
13 14 15 16 17
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.
18 19 20 21 22 23
    #
    # 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 已提交
24
    class AbstractAdapter
25
      include Quoting, DatabaseStatements, SchemaStatements
26
      include QueryCache
D
Initial  
David Heinemeier Hansson 已提交
27
      @@row_even = true
28

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

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

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

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

53 54 55 56
      # 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.
57
      def prefetch_primary_key?(table_name = nil)
58 59 60
        false
      end

61
      def reset_runtime #:nodoc:
62 63
        rt, @runtime = @runtime, 0
        rt
64
      end
65

66 67 68 69 70 71
      # QUOTING ==================================================

      # Override to return the quoted table name if the database needs it
      def quote_table_name(name)
        name
      end
72 73 74 75 76

      # CONNECTION MANAGEMENT ====================================

      # Is this connection active and ready to perform queries?
      def active?
77
        @active != false
78 79 80 81
      end

      # Close this connection and open a new one in its place.
      def reconnect!
82 83 84 85 86 87
        @active = true
      end

      # Close this connection
      def disconnect!
        @active = false
88 89
      end

90 91
      # 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.
92
      def requires_reloading?
93 94 95
        false
      end

96
      # Lazily verify this connection, calling +active?+ only if it hasn't
97
      # been called for +timeout+ seconds.
98 99 100 101 102 103 104
      def verify!(timeout)
        now = Time.now.to_i
        if (now - @last_verification) > timeout
          reconnect! unless active?
          @last_verification = now
        end
      end
105

106 107 108 109 110 111
      # 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
112

113
      def log_info(sql, name, runtime)
114 115 116 117 118
        if @logger && @logger.debug?
          name = "#{name.nil? ? "SQL" : name} (#{sprintf("%f", runtime)})"
          @logger.debug format_log_entry(name, sql.squeeze(' '))
        end
      end
119

120
      protected
121
        def log(sql, name)
122 123 124 125 126 127 128
          if block_given?
            if @logger and @logger.level <= Logger::INFO
              result = nil
              seconds = Benchmark.realtime { result = yield }
              @runtime += seconds
              log_info(sql, name, seconds)
              result
129
            else
130
              yield
D
Initial  
David Heinemeier Hansson 已提交
131
            end
132 133 134
          else
            log_info(sql, name, 0)
            nil
D
Initial  
David Heinemeier Hansson 已提交
135
          end
136
        rescue Exception => e
137
          # Log message and raise exception.
138
          # Set last_verification to 0, so that connection gets verified
139 140
          # upon reentering the request loop
          @last_verification = 0
141 142 143
          message = "#{e.class.name}: #{e.message}: #{sql}"
          log_info(message, name, 0)
          raise ActiveRecord::StatementInvalid, message
D
Initial  
David Heinemeier Hansson 已提交
144 145 146
        end

        def format_log_entry(message, dump = nil)
147
          if ActiveRecord::Base.colorize_logging
148 149 150
            if @@row_even
              @@row_even = false
              message_color, dump_color = "4;36;1", "0;1"
151
            else
152 153
              @@row_even = true
              message_color, dump_color = "4;35;1", "0"
154
            end
155

156 157
            log_entry = "  \e[#{message_color}m#{message}\e[0m   "
            log_entry << "\e[#{dump_color}m%#{String === dump ? 's' : 'p'}\e[0m" % dump if dump
158
            log_entry
D
Initial  
David Heinemeier Hansson 已提交
159
          else
160
            "%s  %s" % [message, dump]
D
Initial  
David Heinemeier Hansson 已提交
161 162
          end
        end
163
    end
D
Initial  
David Heinemeier Hansson 已提交
164
  end
165
end