diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 4240cb20c0..f7e46ac23d 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -1403,6 +1403,8 @@ module ActiveRecord ) pool.with_connection { |connection| yield(connection) } + ensure + pool&.disconnect! end MIGRATOR_SALT = 2053462845 diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 8946e0afb9..43d140283e 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -933,6 +933,24 @@ class MigrationTest < ActiveRecord::TestCase end end + if current_adapter?(:PostgreSQLAdapter) + def test_with_advisory_lock_closes_connection + migration = Class.new(ActiveRecord::Migration::Current) { + def version; 100 end + def migrate(x) + end + }.new + + migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 100) + + query = "SELECT COUNT(*) FROM pg_stat_activity WHERE datname = '#{ActiveRecord::Base.connection_db_config.database}'" + + assert_no_changes -> { ActiveRecord::Base.connection.exec_query(query).rows.flatten.first } do + migrator.migrate + end + end + end + def test_with_advisory_lock_raises_the_right_error_when_it_fails_to_release_lock migration = Class.new(ActiveRecord::Migration::Current).new migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 100)