Add ability to create/drop/migrate all dbs for a given env

`each_current_configuration` is used by create, drop, and other methods
to find the configs for a given environment and returning those to the
method calling them.

The change here allows for the database commands to operate on all the
configs in the environment. Previously we couldn't slice the hashes and
iterate over them becasue they could be two tier or could be three
tier. By using the database config structs we don't need to care whether
we're dealing with a three tier or two tier, we can just parse all the
configs based on the environment.

This makes it possible for us to run `bin/rails db:create` and it will
create all the configs for the dev and test environment ust like it does
for a two tier - it creates the db for dev and test. Now `db:create`
will create `primary` for dev and test, and `animals` for dev and test
if our database.yml looks like:

```
development:
  primary:
    etc
  animals:
    etc

test:
  primary:
    etc
  animals:
    etc
```

This means that `bin/rails db:create`, `bin/rails db:drop`, and
`bin/rails db:migrate` will operate on the dev and test env for both
primary and animals ds.
This commit is contained in:
eileencodes 2018-03-16 14:04:09 -04:00
parent d79d6867a2
commit 5eb4488d02
2 changed files with 11 additions and 8 deletions

View File

@ -73,8 +73,11 @@ db_namespace = namespace :db do
desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)."
task migrate: :load_config do
ActiveRecord::Tasks::DatabaseTasks.migrate
db_namespace["_dump"].invoke
ActiveRecord::Base.configs_for(Rails.env) do |spec_name, config|
ActiveRecord::Base.establish_connection(config)
ActiveRecord::Tasks::DatabaseTasks.migrate
db_namespace["_dump"].invoke
end
end
# IMPORTANT: This task won't dump the schema if ActiveRecord::Base.dump_schema_after_migration is set to false

View File

@ -261,8 +261,8 @@ module ActiveRecord
end
def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env)
each_current_configuration(environment) { |configuration, configuration_environment|
load_schema configuration, format, file, configuration_environment
each_current_configuration(environment) { |configuration, spec_name, env|
load_schema configuration, format, file, env
}
ActiveRecord::Base.establish_connection(environment.to_sym)
end
@ -312,10 +312,10 @@ module ActiveRecord
environments = [environment]
environments << "test" if environment == "development"
ActiveRecord::Base.configurations.slice(*environments).each do |configuration_environment, configuration|
next unless configuration["database"]
yield configuration, configuration_environment
environments.each do |env|
ActiveRecord::Base.configs_for(env) do |spec_name, configuration|
yield configuration, spec_name, env
end
end
end