From 13015b38a13221a32717e17b13d49dc3110e00ea Mon Sep 17 00:00:00 2001 From: Edouard CHIN Date: Fri, 22 Nov 2019 03:05:13 +0100 Subject: [PATCH] Fix connection pools not shared between writer -> replica during tests: - ### Problem Connection pools are not properly shared. A replica can't see the data in the open transaction on the writing connection. ```ruby Dog.create!(name: 'bilou') AnimalsBase.connected_to(role: :reading) do Dog.find_by(name: 'bilou') # No result end ``` The reason of this bug is because when test starts, we iterate over `AR::Base.connection_handlers` which only contains the `writing` handler since models haven't been loaded (app isn't eagerloaded test env). ### Solution Share connection pools as soon as a connection is established by creating a subcriber. --- activerecord/lib/active_record/test_fixtures.rb | 1 + activerecord/test/cases/fixtures_test.rb | 7 ------- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/activerecord/lib/active_record/test_fixtures.rb b/activerecord/lib/active_record/test_fixtures.rb index 665fd98c24..a1a4c2e301 100644 --- a/activerecord/lib/active_record/test_fixtures.rb +++ b/activerecord/lib/active_record/test_fixtures.rb @@ -130,6 +130,7 @@ def setup_fixtures(config = ActiveRecord::Base) # When connections are established in the future, begin a transaction too @connection_subscriber = ActiveSupport::Notifications.subscribe("!connection.active_record") do |_, _, _, _, payload| spec_name = payload[:spec_name] if payload.key?(:spec_name) + setup_shared_connection_pool if spec_name begin diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index ff939ad1ac..198bede84a 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -1399,13 +1399,6 @@ class MultipleDatabaseFixturesTest < ActiveRecord::TestCase rw_conn = ActiveRecord::Base.connection ro_conn = ActiveRecord::Base.connection_handlers[:reading].connection_pool_list.first.connection - assert_not_equal rw_conn, ro_conn - - enlist_fixture_connections - - rw_conn = ActiveRecord::Base.connection - ro_conn = ActiveRecord::Base.connection_handlers[:reading].connection_pool_list.first.connection - assert_equal rw_conn, ro_conn end ensure -- GitLab