abstract_adapter.rb 5.1 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 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'
require 'active_record/connection_adapters/abstract/connection_specification'

D
Initial  
David Heinemeier Hansson 已提交
12 13 14 15 16
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.
17 18 19 20 21 22
    #
    # 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 已提交
23
    class AbstractAdapter
24
      include Quoting, DatabaseStatements, SchemaStatements
D
Initial  
David Heinemeier Hansson 已提交
25
      @@row_even = true
26
      
27
      def initialize(connection, logger = nil) #:nodoc:
D
Initial  
David Heinemeier Hansson 已提交
28 29
        @connection, @logger = connection, logger
        @runtime = 0
30
        @last_verification = 0
D
Initial  
David Heinemeier Hansson 已提交
31 32
      end

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

39
      # Does this adapter support migrations?  Backend specific, as the
40
      # abstract adapter always returns +false+.
41 42
      def supports_migrations?
        false
43
      end
44 45 46 47 48 49
      
      # Does this adapter support using DISTINCT within COUNT?  This is +true+
      # for all adapters except sqlite.
      def supports_count_distinct?
        true
      end
50

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

59
      def reset_runtime #:nodoc:
60 61
        rt, @runtime = @runtime, 0
        rt
62
      end
63

64 65 66 67 68

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

      # Is this connection active and ready to perform queries?
      def active?
69
        @active != false
70 71 72 73
      end

      # Close this connection and open a new one in its place.
      def reconnect!
74 75 76 77 78 79
        @active = true
      end

      # Close this connection
      def disconnect!
        @active = false
80 81
      end

82 83 84 85 86 87
      # 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.
      def supports_reloading?
        false
      end

88 89 90 91 92 93 94 95 96
      # Lazily verify this connection, calling +active?+ only if it hasn't
      # been called for +timeout+ seconds.       
      def verify!(timeout)
        now = Time.now.to_i
        if (now - @last_verification) > timeout
          reconnect! unless active?
          @last_verification = now
        end
      end
97 98 99 100 101 102 103
      
      # 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
104

105
      protected
106
        def log(sql, name)
107 108 109 110 111 112 113
          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
114
            else
115
              yield
D
Initial  
David Heinemeier Hansson 已提交
116
            end
117 118 119
          else
            log_info(sql, name, 0)
            nil
D
Initial  
David Heinemeier Hansson 已提交
120
          end
121
        rescue Exception => e
122
          # Log message and raise exception.
123 124 125
          # Set last_verfication to 0, so that connection gets verified
          # upon reentering the request loop
          @last_verification = 0
126 127 128
          message = "#{e.class.name}: #{e.message}: #{sql}"
          log_info(message, name, 0)
          raise ActiveRecord::StatementInvalid, message
D
Initial  
David Heinemeier Hansson 已提交
129 130 131
        end

        def log_info(sql, name, runtime)
132
          return unless @logger
D
Initial  
David Heinemeier Hansson 已提交
133

134
          @logger.debug(
D
Initial  
David Heinemeier Hansson 已提交
135
            format_log_entry(
136
              "#{name.nil? ? "SQL" : name} (#{sprintf("%f", runtime)})",
D
Initial  
David Heinemeier Hansson 已提交
137 138 139 140 141 142
              sql.gsub(/ +/, " ")
            )
          )
        end

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

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