I've implemented simple horizontal sharding in a rails application. There are 2 shards: Primary, and shard_one.
When running in test environment,
I've set up a super simple test in a global setup in test_helper.rb to test this:
ActiveRecord::Base.connected_to(shard: :primary, role: :reading) do
p Tenant.count
end
ActiveRecord::Base.connected_to(shard: :shard_one, role: :reading) do
p Tenant.count
end
The output of which is
ArgumentError: unknown keyword: :shard
The databases exist, migrations run successfully. No problems with the configurations.
So there's definitely some sort of initialization not running for the test runner, but I don't know what it is.
The application configuration is :
test:
primary:
<<: *default
url: <%= ENV['TEST_DATABASE_URL'] %>
shard_one:
<<: *default
url: <%= ENV['TEST_ARCHIVE_DATABASE_URL'] %>
class ApplicationRecord < RxModule::ApplicationRecord
self.abstract_class = true
connects_to shards: {
primary: { writing: :primary, reading: :primary },
archive: { writing: :shard_one, reading: :shard_one }
}
end
Does anyone have any insight here?
I tried api ActiveRecord::Base.connected_to?(shard: :primary, role: :reading), and it works as expected. Without shard parameter, it works too. And I even drill down to /var/lib/gems/2.7.0/gems/activerecord-6.1.7.2/lib/active_record/connection_handling.rb and confirm the api contains shard parameter.