Skip to content
This repository
Browse code

use thread locals and an instance variable within QueryCache#BodyProx…

…y to maintain appropriate linkage with AR database connection across threads
  • Loading branch information...
commit f41b58d3b25eb57ba5c890b713301ba2e3fcb9b7 1 parent 3088d23
Mark J. Titorenko authored June 13, 2011
2  activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -314,7 +314,7 @@ def new_connection
314 314
       end
315 315
 
316 316
       def current_connection_id #:nodoc:
317  
-        Thread.current.object_id
  317
+        ActiveRecord::Base.connection_id ||= Thread.current.object_id
318 318
       end
319 319
 
320 320
       def checkout_new_connection
8  activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
@@ -115,6 +115,14 @@ def connection
115 115
         retrieve_connection
116 116
       end
117 117
 
  118
+      def connection_id
  119
+        Thread.current['ActiveRecord::Base.connection_id']
  120
+      end
  121
+
  122
+      def connection_id=(connection_id)
  123
+        Thread.current['ActiveRecord::Base.connection_id'] = connection_id
  124
+      end
  125
+
118 126
       # Returns the configuration of the associated connection as a hash:
119 127
       #
120 128
       #  ActiveRecord::Base.connection_config
6  activerecord/lib/active_record/query_cache.rb
@@ -28,9 +28,10 @@ def initialize(app)
28 28
     end
29 29
 
30 30
     class BodyProxy # :nodoc:
31  
-      def initialize(original_cache_value, target)
  31
+      def initialize(original_cache_value, target, connection_id)
32 32
         @original_cache_value = original_cache_value
33 33
         @target               = target
  34
+        @connection_id        = connection_id
34 35
       end
35 36
 
36 37
       def method_missing(method_sym, *arguments, &block)
@@ -48,6 +49,7 @@ def each(&block)
48 49
       def close
49 50
         @target.close if @target.respond_to?(:close)
50 51
       ensure
  52
+        ActiveRecord::Base.connection_id = @connection_id
51 53
         ActiveRecord::Base.connection.clear_query_cache
52 54
         unless @original_cache_value
53 55
           ActiveRecord::Base.connection.disable_query_cache!
@@ -60,7 +62,7 @@ def call(env)
60 62
       ActiveRecord::Base.connection.enable_query_cache!
61 63
 
62 64
       status, headers, body = @app.call(env)
63  
-      [status, headers, BodyProxy.new(old, body)]
  65
+      [status, headers, BodyProxy.new(old, body, ActiveRecord::Base.connection_id)]
64 66
     rescue Exception => e
65 67
       ActiveRecord::Base.connection.clear_query_cache
66 68
       unless old

0 notes on commit f41b58d

Please sign in to comment.
Something went wrong with that request. Please try again.