consoleshardingruby-on-rails-7

Rails7 MultiDB switch shard for console


I'm experimenting with rails 7 multidb sharding, and I would like to be able to set the default shard for a rails console session.

I can use

ActiveRecord::Base.connected_to(role: :writing, shard: :default) do
  @id = Person.create! # Creates a record in shard default
end

but that's quite cumbersome for each command. Is there any way to set it from the command line, something like

shard=shard_one rails c 

Solution

  • I changed this to the following solution because the db:rollback tasks didn't work because it had an issue with reading the database.yml

    database.yml

    development:
      nl:
        <<: *default_database
        database: <%= ENV.fetch("DATABASE_DATABASE_NL") { Rails.application.credentials.dig(:mysql, :database_nl) } %>
      uk:
        <<: *default_database
        database: <%= ENV.fetch("DATABASE_DATABASE_UK") { Rails.application.credentials.dig(:mysql, :database_uk) } %>
    

    And add the following in your application.rb

    def config.database_configuration
      parsed = super
      default_shard = ENV.fetch('DEFAULT_SHARD') { 'nl' }
      default_shard_config = { "#{default_shard}": parsed[Rails.env].delete(default_shard) }
      parsed[Rails.env] = default_shard_config.merge(parsed[Rails.env])
      parsed
    end
    

    Now you can still run DISABLE_SPRING=true DEFAULT_SHARD="uk" rails but also bin/rails db:rollback:uk etc.