0

我正在试验 rails 7 multidb sharding,我希望能够为 rails 控制台会话设置默认分片。

我可以用

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

但这对于每个命令来说都非常麻烦。有没有办法从命令行设置它,比如

shard=shard_one rails c 
4

1 回答 1

0

我最终database.yml像这样破解了我的文件


<%= ctrys = ['nl','uk']; main = ENV.fetch('DEFAULT_SHARD'){'nl'}; ctrys.delete(main); ctrys.unshift(main);nil %>
development:
  <%= ctrys[0] %>:
    <<: *default_database
    database: <%= ENV.fetch("DATABASE_DATABASE_#{ctrys[0].upcase}") { Rails.application.credentials.dig(:mysql, :"database_#{ctrys[0]}") } %>
  <%= ctrys[1] %>:
    <<: *default_database
    database: <%= ENV.fetch("DATABASE_DATABASE_#{ctrys[1].upcase}") { Rails.application.credentials.dig(:mysql, :"database_#{ctrys[1]}") } %>

我可以这样使用它:

~prompt% DISABLE_SPRING=true DEFAULT_SHARD="uk" rails
Loading development environment (Rails 7.0.1)
hvg-web(dev)> ActiveRecord::Base.connection.pool.db_config.name
=> "uk"

(spring会缓存它,所以禁用spring)

不过,这个 hack 确实给测试运行者带来了挑战:

/usr/src/app# rspec
Running via Spring preloader in process 2504
Running via Spring preloader in process 2510
Rails couldn't infer whether you are using multiple databases from your database.yml and can't generate the tasks for the non-primary databases. If you'd like to use this feature, please simplify your ERB.

感觉很老套,但它确实有效——也许其他人可以想出一个更好的计划?

于 2022-02-03T14:47:15.123 回答