I am trying to script the back up of a database and part of the flow is that I need to drop and then recreate the database from a backup.
When there are connections to the database I get a failure message like this:
DETAIL: There are 2 other sessions using the database.
I have been looking for a way to either ignore this or kill connections prior to dropping the database. I am trying to use the query below but it doesnt seem to actually allow me to drop the db after running it.
-- Drop connections
\set database_name `echo $DB_NAME`
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = ':database_name'
AND pid <> pg_backend_pid();
I took the query from an SO post which seemed to suggest it could be used, is there a more reliable way to do this or a way to force the dropping of a database regardless of whether there are active connections?
psql
after running that query? Otherwise you'll still have one open connection to that database - the one that your query used – Considerate