Skip to content

Commit

Permalink
railtie: Fix connection pools (#72)
Browse files Browse the repository at this point in the history
Previously, the `readyset.connection_pool` railtie was setting up the
connection pool for the gem by calling
`ConnectionHandler.establish_connection`, which was resulting in the
connection pool's database key being set to that of the primary database
instead of "readyset". This commit resolves the issue by relying
directly on `ActiveRecord::Base.establish_connection` to set up the
connection pool. It also adds unit test converage to ensure the
connection pool is set up as expected.
  • Loading branch information
ethan-readyset authored Jan 25, 2024
1 parent f1b1d36 commit 59a6a1a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
15 changes: 7 additions & 8 deletions lib/readyset/railtie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,14 @@ class Railtie < Rails::Railtie
initializer 'readyset.connection_pools' do |app|
ActiveSupport.on_load(:after_initialize) do
shard = Readyset.config.shard
config = ActiveRecord::Base.
configurations.
configs_for(name: shard.to_s, env_name: Rails.env, include_hidden: true).
configuration_hash

ActiveRecord::Base.connection_handler.
establish_connection(config, role: ActiveRecord.reading_role, shard: shard)
ActiveRecord::Base.connection_handler.
establish_connection(config, role: ActiveRecord.writing_role, shard: shard)
ActiveRecord::Base.connected_to(role: ActiveRecord.reading_role, shard: shard) do
ActiveRecord::Base.establish_connection(:readyset)
end

ActiveRecord::Base.connected_to(role: ActiveRecord.writing_role, shard: shard) do
ActiveRecord::Base.establish_connection(:readyset)
end
end
end

Expand Down
14 changes: 14 additions & 0 deletions spec/railtie_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,18 @@ def index
expect(ActiveRecord::Relation.ancestors).to include(Readyset::RelationExtension)
end
end

describe 'readyset.connection_pools' do
it 'sets up connection pools for both the reading and writing roles' do
pools = ActiveRecord::Base.connection_handler.connection_pools
readyset_pool = pools.find { |pool| pool.shard == Readyset.config.shard }

expect(readyset_pool).not_to be_nil
expected_config = ActiveRecord::Base.
configurations.
configs_for(name: Readyset.config.shard.to_s, env_name: Rails.env, include_hidden: true)
expect(readyset_pool.db_config).to eq(expected_config)
expect(readyset_pool.connection_class).to eq(ActiveRecord::Base)
end
end
end

0 comments on commit 59a6a1a

Please sign in to comment.