Tuesday, August 19, 2014

Force drop db while others may be connected in postgresql

You can't drop postgres database while clients are connected to it. Quite robust way to work around it, is
  1. Make sure noone can connect to this database
    update pg_database set datallowconn = 'false' where datname = 'mydb';
  2. Force disconnection of all clients connected to this database.
    For postgres < 9.2:
    SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname = 'mydb';
    for postgres versions >= 9.2 change procpid to pid:
    SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'mydb';
  3. Drop it
    DROP DATABASE mydb;
Steps 1 and 2 require superuser privileges, step 3 requires database owner privilege.
You can't do it all using only dropdb utility - which is a simple wrapper around DROP DATABASE server query.

No comments:

Post a Comment