Skip to content

Commit f41b58d

Browse files
committed
use thread locals and an instance variable within QueryCache#BodyProxy to maintain appropriate linkage with AR database connection across threads
1 parent 3088d23 commit f41b58d

File tree

3 files changed

+13
-3
lines changed

3 files changed

+13
-3
lines changed

activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,7 @@ def new_connection
314314
end
315315

316316
def current_connection_id #:nodoc:
317-
Thread.current.object_id
317+
ActiveRecord::Base.connection_id ||= Thread.current.object_id
318318
end
319319

320320
def checkout_new_connection

activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb

+8
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,14 @@ def connection
115115
retrieve_connection
116116
end
117117

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+
118126
# Returns the configuration of the associated connection as a hash:
119127
#
120128
# ActiveRecord::Base.connection_config

activerecord/lib/active_record/query_cache.rb

+4-2
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,10 @@ def initialize(app)
2828
end
2929

3030
class BodyProxy # :nodoc:
31-
def initialize(original_cache_value, target)
31+
def initialize(original_cache_value, target, connection_id)
3232
@original_cache_value = original_cache_value
3333
@target = target
34+
@connection_id = connection_id
3435
end
3536

3637
def method_missing(method_sym, *arguments, &block)
@@ -48,6 +49,7 @@ def each(&block)
4849
def close
4950
@target.close if @target.respond_to?(:close)
5051
ensure
52+
ActiveRecord::Base.connection_id = @connection_id
5153
ActiveRecord::Base.connection.clear_query_cache
5254
unless @original_cache_value
5355
ActiveRecord::Base.connection.disable_query_cache!
@@ -60,7 +62,7 @@ def call(env)
6062
ActiveRecord::Base.connection.enable_query_cache!
6163

6264
status, headers, body = @app.call(env)
63-
[status, headers, BodyProxy.new(old, body)]
65+
[status, headers, BodyProxy.new(old, body, ActiveRecord::Base.connection_id)]
6466
rescue Exception => e
6567
ActiveRecord::Base.connection.clear_query_cache
6668
unless old

0 commit comments

Comments
 (0)