Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require "active_record"
require "minitest/autorun"
class Person < ActiveRecord::Base
establish_connection adapter: "sqlite3", database: "foobar.db"
end
class ConnHandlerSwapTest < Minitest::Test
def setup
@readonly = ActiveRecord::ConnectionAdapters::ConnectionHandler.new
end
def swap_connection_handler(&block)
old_handler, ActiveRecord::Base.connection_handler = ActiveRecord::Base.connection_handler, @readonly
yield
ensure
ActiveRecord::Base.connection_handler = old_handler
end
def test_conn_swap
readonly_id = 0
swap_connection_handler do
readonly_id = ActiveRecord::Base.connection_handler.object_id
end
refute_equal readonly_id, Person.connection_handler.object_id
assert_equal readonly_id, @readonly.object_id
end
def test_conn_swap_in_fiber
readonly_id = 0
enum = Enumerator.new do |r|
r << ActiveRecord::Base.connection_handler.object_id
end
swap_connection_handler do
readonly_id = enum.next
end
assert_equal readonly_id, @readonly.object_id
end
end
@arthurnn

This comment has been minimized.

Copy link
Owner Author

commented Aug 2, 2017

Something like this would fix the test:

diff --git a/activerecord/lib/active_record/runtime_registry.rb b/activerecord/lib/active_record/runtime_registry.rb
index 4975cb8967..5b97f6920d 100644
--- a/activerecord/lib/active_record/runtime_registry.rb
+++ b/activerecord/lib/active_record/runtime_registry.rb
@@ -14,7 +14,14 @@ module ActiveRecord
   class RuntimeRegistry # :nodoc:
     extend ActiveSupport::PerThreadRegistry

-    attr_accessor :connection_handler, :sql_runtime
+    attr_accessor :sql_runtime
+
+    def connection_handler=(obj)
+      Thread.current.thread_variable_set "connection_handler", obj
+    end
+    def connection_handler
+      Thread.current.thread_variable_get "connection_handler"
+    end

     [:connection_handler, :sql_runtime].each do |val|
       class_eval %{ def self.#{val}; instance.#{val}; end }, __FILE__, __LINE__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.