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

I have a rails application running over Postgres.

I have two servers: one for testing and the other for production.

Very often I need to clone the production DB on the test server.

The command I'm runnig via Vlad is:

rake RAILS_ENV='test_server' db:drop db:create

The problem I'm having is that I receive the following error:

ActiveRecord::StatementInvalid: PGError: ERROR: database <database_name> is being accessed by other users DROP DATABASE IF EXISTS <database_name>

This happens if someone has accessed the application via web recently (postgres keeps a "session" opened)

Is there any way that I can terminate the sessions on the postgres DB?

Thank you.

Edit

I can delete the database using phppgadmin's interface but not with the rake task.

How can I replicate phppgadmin's drop with a rake task?


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.


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.


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.