query_cache.rb 2.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
module ActiveRecord
  module ConnectionAdapters # :nodoc:
    module QueryCache
      class << self
        def included(base)
          dirties_query_cache base, :insert, :update, :delete
        end

        def dirties_query_cache(base, *method_names)
          method_names.each do |method_name|
11
            base.class_eval <<-end_code, __FILE__, __LINE__ + 1
12 13 14 15
              def #{method_name}(*)                         # def update_with_query_dirty(*args)
                clear_query_cache if @query_cache_enabled   #   clear_query_cache if @query_cache_enabled
                super                                       #   update_without_query_dirty(*args)
              end                                           # end
16 17 18 19 20
            end_code
          end
        end
      end

21
      attr_reader :query_cache, :query_cache_enabled
N
Nick Sieger 已提交
22

23 24
      # Enable the query cache within the block.
      def cache
25
        old, @query_cache_enabled = @query_cache_enabled, true
26 27 28
        yield
      ensure
        clear_query_cache
29
        @query_cache_enabled = old
30 31 32 33
      end

      # Disable the query cache within the block.
      def uncached
34
        old, @query_cache_enabled = @query_cache_enabled, false
35 36
        yield
      ensure
37
        @query_cache_enabled = old
38 39
      end

P
Pratik Naik 已提交
40 41 42 43 44 45
      # Clears the query cache.
      #
      # One reason you may wish to call this method explicitly is between queries
      # that ask the database to randomize results. Otherwise the cache would see
      # the same SQL query and repeatedly return the same result each time, silently
      # undermining the randomness you were expecting.
46
      def clear_query_cache
47
        @query_cache.clear
48 49
      end

50
      def select_all(sql, name = nil, binds = [])
51
        if @query_cache_enabled
52
          cache_sql(sql, binds) { super }
53
        else
54
          super
55 56 57 58
        end
      end

      private
59
        def cache_sql(sql, binds)
60
          result =
A
Aaron Patterson 已提交
61
            if @query_cache[sql].key?(binds)
62
              ActiveSupport::Notifications.instrument("sql.active_record",
A
Aaron Patterson 已提交
63
                :sql => sql, :name => "CACHE", :connection_id => object_id)
A
Aaron Patterson 已提交
64
              @query_cache[sql][binds]
65
            else
A
Aaron Patterson 已提交
66
              @query_cache[sql][binds] = yield
67 68
            end

69
          result.collect { |row| row.dup }
70 71 72 73
        end
    end
  end
end