Rails Snippet: Force drop a PostgreSQL DB
While developing a new Rails site I discovered the need to drop (delete) my database and recreate it. Word to the wise: make sure you DON’T do this on your production server! I’ve not done it (yet!), but I thought I’d best give the warning.
Rails will refuse to drop a database while anything is connected to it - your editor’s database panel, a forgotten rails console, whatever. These days Rails can force the disconnect for you:
rails db:drop:_unsafe db:create db:migrate
Or, my preferred one-liner while iterating on a fresh schema:
rails db:reset
If you’d rather do it at the Postgres level (or the above still complains), this SQL kicks off every connected client first:
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'your_database' AND pid <> pg_backend_pid();
Remember to do this for both the _development and _test databases, then drop away:
DROP DATABASE "your_database";
Back in Rails, rails db:create db:migrate (plus rails db:seed if you want your seed data) and you’re on your merry way.
A really simple little article, but it can cause a lot of trouble if used improperly. And once more for the people at the back: ❗️ DON’T ❗️ do this on your production server!