Created
July 7, 2013 11:02
-
-
Save mfilej/5943114 to your computer and use it in GitHub Desktop.
Rake task to terminate idle postgresql connections that prevent a database to be dropped
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://stackoverflow.com/questions/5108876/kill-a-postgresql-session-connection | |
namespace :db do | |
desc "Fix 'database is being accessed by other users'" | |
task :terminate => :environment do | |
ActiveRecord::Base.connection.execute <<-SQL | |
SELECT | |
pg_terminate_backend(pid) | |
FROM | |
pg_stat_activity | |
WHERE | |
-- don't kill my own connection! | |
pid <> pg_backend_pid() | |
-- don't kill the connections to other databases | |
AND datname = '#{ActiveRecord::Base.connection.current_database}'; | |
SQL | |
end | |
end | |
Rake::Task["db:drop"].enhance ["db:terminate"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
+1 just found this and came in very handy
Thanks!!