ActiveRecord::Tasks::DatabaseTasks のつかいかた

ActiveRecord には ActiveRecord::Tasks::DatabaseTasks というモジュールが定義されている。

Railsdb:create などの Rake タスクは実質的にこのモジュールで定義されている create_current などのメソッドを呼び出している。

ActiveRecord 単体でこれら AR::T::DatabaseTasks のメソッドを呼び出そうとしたところ、database configuration does not specify adapter のようなエラーが出て困った。

config = read_config_from_yaml # -> { 'adapter' => 'postgresql', 'username' => '...', ... }
ActiveRecord::Tasks::DatabaseTasks.database_configuration = config
ActiveRecord::Tasks::DatabaseTasks.create_current(ENV['RACK_ENV'] || 'development')

調べてみたところ、ActiveRecord::Base.configurations も設定する必要がある。

create_current calls each_current_configuration, which relies on ActiveRecord::Base.configurations, not ActiveRecord::Tasks::DatabaseTasks.database_configuration.

Using ActiveRecord Rake tasks out of Rails · Issue #11609 · rails/rails · GitHub

だいぶ意味がわからない仕様だけど、とりあえず動いた。