Rails + Postgres drop error: database is being accessed by other users

If you kill the running postgresql connections for your application, you can then run db:drop just fine. So how to kill those connections? I use the following rake task:

# lib/tasks/kill_postgres_connections.rake
task :kill_postgres_connections => :environment do
  db_name = "#{File.basename(Rails.root)}_#{Rails.env}"
  sh = <<EOF
ps xa \
  | grep postgres: \
  | grep #{db_name} \
  | grep -v grep \
  | awk '{print $1}' \
  | xargs kill
EOF
  puts `#{sh}`
end

task "db:drop" => :kill_postgres_connections

Killing the connections out from under rails will sometimes cause it to barf the next time you try to load a page, but reloading it again re-establishes the connection.


Here's a quick way to kill all the connections to your postgres database.

sudo kill -9 `ps -u postgres -o pid` 

Warning: this will kill any running processes that the postgres user has open, so make sure you want to do this first.


Easier and more updated way is: 1. Use ps -ef | grep postgres to find the connection # 2. sudo kill -9 "# of the connection

Note: There may be identical PID. Killing one kills all.