Skip to content

Instantly share code, notes, and snippets.

@nachokb
Forked from mfilej/db_terminate_backend.rake
Last active August 29, 2015 14:11
Show Gist options
  • Save nachokb/7edb72e2258c7eaa96eb to your computer and use it in GitHub Desktop.
Save nachokb/7edb72e2258c7eaa96eb to your computer and use it in GitHub Desktop.
# 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