desc "Kill test and development postgres database connections"
task :pg_terminate => :environment do
dbs = []
dbs << ActiveRecord::Base.configurations["development"]["database"]
dbs << ActiveRecord::Base.configurations["test"]["database"]
db_names = "#{dbs.map{|name| "'#{name}'"}.join(", ")}"
terminated = false
last_error = ""
["procpid", "pid"].each do |process_id_field|
puts ">> Attempting to pg_terminate with #{process_id_field}"
begin
results = ActiveRecord::Base.connection.execute("
SELECT pg_terminate_backend(#{process_id_field})
FROM pg_stat_activity
WHERE #{process_id_field} <> pg_backend_pid()
AND datname IN(#{db_names})
")
terminated = true
rescue => e
last_error = e.to_s
end
break if terminated
end
if terminated
puts ">> #{db_names} connections terminated"
else
puts ">> Unable to terminate postgres connections"
puts last_error
end
end
Created
September 28, 2012 19:30
-
-
Save chrismccord/3801696 to your computer and use it in GitHub Desktop.
Rake Task to kill postgres test and development database connections
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment