abstract_adapter.rb 4.5 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1 2 3
require 'benchmark'
require 'date'

4 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'
require 'active_record/connection_adapters/abstract/connection_specification'

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

25 26 27
      @@reconnect_success = 0
      @@reconnect_failure = 0
      def self.reconnect_success_rate
28
        (100.0 * @@reconnect_success / (@@reconnect_success + @@reconnect_failure)).to_i
29 30
      end

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

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

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

48 49 50 51 52 53 54 55
      # 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.
      def prefetch_primary_key?
        false
      end

56
      def reset_runtime #:nodoc:
57 58
        rt, @runtime = @runtime, 0
        rt
59
      end
60

61
      protected
62
        def log(sql, name)
63 64 65 66 67 68 69
          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
70
            else
71
              yield
D
Initial  
David Heinemeier Hansson 已提交
72
            end
73 74 75
          else
            log_info(sql, name, 0)
            nil
D
Initial  
David Heinemeier Hansson 已提交
76
          end
77
        rescue Exception => e
78 79 80 81 82 83
          message = "#{e.class.name}: #{e.message}: #{sql}"
          unless reconnect_if_inactive!
            message = "(reconnect failed) #{message}"
          end
          log_info(message, name, 0)
          raise ActiveRecord::StatementInvalid, message
D
Initial  
David Heinemeier Hansson 已提交
84 85 86
        end

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

89
          @logger.debug(
D
Initial  
David Heinemeier Hansson 已提交
90
            format_log_entry(
91
              "#{name.nil? ? "SQL" : name} (#{sprintf("%f", runtime)})",
D
Initial  
David Heinemeier Hansson 已提交
92 93 94 95 96 97
              sql.gsub(/ +/, " ")
            )
          )
        end

        def format_log_entry(message, dump = nil)
98
          if ActiveRecord::Base.colorize_logging
99 100 101
            if @@row_even
              @@row_even = false
              message_color, dump_color = "4;36;1", "0;1"
102
            else
103 104
              @@row_even = true
              message_color, dump_color = "4;35;1", "0"
105
            end
106

107 108
            log_entry = "  \e[#{message_color}m#{message}\e[0m   "
            log_entry << "\e[#{dump_color}m%#{String === dump ? 's' : 'p'}\e[0m" % dump if dump
109
            log_entry
D
Initial  
David Heinemeier Hansson 已提交
110
          else
111
            "%s  %s" % [message, dump]
D
Initial  
David Heinemeier Hansson 已提交
112 113
          end
        end
114 115 116 117 118

      private
        def reconnect_if_inactive!
          if respond_to?(:active?) and respond_to?(:reconnect!)
            reconnect! unless active?
119 120
            if active?
              @@reconnect_success += 1
121
              @logger.info "#{adapter_name} automatically reconnected.  Success rate: #{self.class.reconnect_success_rate}%" if @logger
122
              true
123 124
            else
              @@reconnect_failure += 1
125
              @logger.warn "#{adapter_name} automatic reconnection failed.  Success rate: #{self.class.reconnect_success_rate}%" if @logger
126
              false
127
            end
128 129 130 131
          else
            @logger.warn "#{adapter_name} does not yet support automatic reconnection." if @logger
          end
        end
132
    end
D
Initial  
David Heinemeier Hansson 已提交
133
  end
134
end