Upgraded Rails and RSpec
[monkeycharger.git] / vendor / rails / activerecord / lib / active_record / connection_adapters / abstract / query_cache.rb
blobe6b8e3ae90bd21ca8e0c08eed44b0085b0cb4045
1 module ActiveRecord
2   module ConnectionAdapters # :nodoc:
3     module QueryCache
4       class << self
5         def included(base)
6           base.class_eval do
7             attr_accessor :query_cache_enabled
8             alias_method_chain :columns, :query_cache
9             alias_method_chain :select_all, :query_cache
10           end
12           dirties_query_cache base, :insert, :update, :delete
13         end
15         def dirties_query_cache(base, *method_names)
16           method_names.each do |method_name|
17             base.class_eval <<-end_code, __FILE__, __LINE__
18               def #{method_name}_with_query_dirty(*args)
19                 clear_query_cache if @query_cache_enabled
20                 #{method_name}_without_query_dirty(*args)
21               end
23               alias_method_chain :#{method_name}, :query_dirty
24             end_code
25           end
26         end
27       end
29       # Enable the query cache within the block.
30       def cache
31         old, @query_cache_enabled = @query_cache_enabled, true
32         @query_cache ||= {}
33         yield
34       ensure
35         clear_query_cache
36         @query_cache_enabled = old
37       end
39       # Disable the query cache within the block.
40       def uncached
41         old, @query_cache_enabled = @query_cache_enabled, false
42         yield
43       ensure
44         @query_cache_enabled = old
45       end
47       def clear_query_cache
48         @query_cache.clear if @query_cache
49       end
51       def select_all_with_query_cache(*args)
52         if @query_cache_enabled
53           cache_sql(args.first) { select_all_without_query_cache(*args) }
54         else
55           select_all_without_query_cache(*args)
56         end
57       end
59       def columns_with_query_cache(*args)
60         if @query_cache_enabled
61           @query_cache["SHOW FIELDS FROM #{args.first}"] ||= columns_without_query_cache(*args)
62         else
63           columns_without_query_cache(*args)
64         end
65       end
67       private
68         def cache_sql(sql)
69           result =
70             if @query_cache.has_key?(sql)
71               log_info(sql, "CACHE", 0.0)
72               @query_cache[sql]
73             else
74               @query_cache[sql] = yield
75             end
77           if Array === result
78             result.collect { |row| row.dup }
79           else
80             result.duplicable? ? result.dup : result
81           end
82         rescue TypeError
83           result
84         end
85     end
86   end
87 end