How to drop all database connections to a PostgreSQL database
namespace :db do
desc 'Drop all database connections'
task :drop_connections => :environment do
database = Rails::Application.config.database_configuration[RAILS_ENV]["database"]
field = if ActiveRecord::Base.connection.send( :postgresql_version ) < 90200
'pg_stat_activity.procpic' # PostgreSQL <= 9.1.x
else
'pg_stat_activity.pid' # PostgreSQL >= 9.2.x
end
begin
ActiveRecord::Base.connection.execute <<-SQL
SELECT pg_terminate_backend(#{field})
FROM pg_stat_activity
WHERE pg_stat_activity.datname = '#{database}';
SQL
rescue ActiveRecord::ActiveRecordError => e
puts 'Connection lost to the database'
end
end
end
Written by Gergo Sulymosi
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#