Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@trekdemo
Created November 13, 2012 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save trekdemo/4065701 to your computer and use it in GitHub Desktop.
Save trekdemo/4065701 to your computer and use it in GitHub Desktop.
Drop postgres connections to a database in a Rails application
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment