Reestablish connection to previous database after after running `db:schema:load:name`

After running `db:schema:load:name` the previous connection is restored.

Fixes #42912
This commit is contained in:
Jacopo 2021-08-19 09:12:25 +02:00
parent 074c7f50c5
commit 718c71e051
3 changed files with 30 additions and 0 deletions

View File

@ -1,3 +1,9 @@
* Reestablish connection to previous database after after running `db:schema:load:name`
After running `db:schema:load:name` the previous connection is restored.
*Jacopo Beschi*
* Add database config option `database_tasks`
If you would like to connect to an external database without any database

View File

@ -493,8 +493,11 @@ db_namespace = namespace :db do
ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |name|
desc "Loads a database schema file (either db/schema.rb or db/structure.sql, depending on `config.active_record.schema_format`) into the #{name} database"
task name => :load_config do
original_db_config = ActiveRecord::Base.connection_db_config
db_config = ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env, name: name)
ActiveRecord::Tasks::DatabaseTasks.load_schema(db_config, ActiveRecord.schema_format, ENV["SCHEMA"])
ensure
ActiveRecord::Base.establish_connection(original_db_config) if original_db_config
end
end
end

View File

@ -475,6 +475,27 @@ module ApplicationTests
end
end
test "db:schema:load:name sets the connection back to its original state" do
Dir.chdir(app_path) do
dummy_task = <<~RUBY
task foo: :environment do
Book.first
end
RUBY
app_file("Rakefile", dummy_task, "a+")
generate_models_for_animals
rails("db:migrate:primary")
rails "db:migrate:animals", "db:schema:dump:animals"
assert_nothing_raised do
rails("db:schema:load:animals", "foo")
end
end
end
test "db:migrate respects timestamp ordering across databases" do
require "#{app_path}/config/environment"
app_file "db/migrate/01_one_migration.rb", <<-MIGRATION