DatabaseCleaner / database_cleaner-active_record

Strategies for cleaning databases using ActiveRecord. Can be used to ensure a clean state for testing.
MIT License
64 stars 63 forks source link

Add support for horizontal sharding for Rails 6.1+ #108

Open alexeisersun opened 5 months ago

alexeisersun commented 5 months ago

Since Rails 6.1, it is possible for a model to connect to multiple databases. A minimal example of such application is:

class ApplicationRecord < ActiveRecord::Base
  connects_to shard: {
    defaul: { writing: :primary_db },
    shard_one: { writing: :secondary_db }
  }
end

class User < ApplicationRecord; end

ApplicationRecord.connected_to(shard: :shard_one, role: :writing) do
  User.create!(...) # creates users in secondary_db DB
end

ApplicationRecord.connection_handler.connection_pools.map { |pool|
pool.db_config.configuration_hash[:database] } # [:primary_db,
:secondary_db]

With support for multiple databases for a model, one would have something like this in tests:

DatabaseCleaner[:active_record, db: ApplicationRecord]

DatabaseCleaner.start
DatabaseCleaner.clean

In .clean, however, the bug occurs: it doesn't actually delete or truncate data from the :secondary_db.

To fix the bug, DatabaseCleaner should iterate through all connection pools the model is connected to.