PostgreSQL: Temporarily disable connections

后端 未结 5 1798
我在风中等你
我在风中等你 2020-12-14 00:50

I have a script in PostgreSQL which restores test database from dump every night. The database is accessed by app servers and processes with connection pool which keeps a fe

相关标签:
5条回答
  • 2020-12-14 01:07

    After you have terminated the current active connections you can also issue this command that will only allow super users to login. This assumes you are ok with all super users having access still. Hopefully you don't hand out super user rights to just anyone.

    ALTER DATABASE your_db CONNECTION LIMIT 0;
    
    0 讨论(0)
  • 2020-12-14 01:14

    I had a different usage scenario, in which I wanted to disable a DB for everyone (including superuser) and forever, but not plainly drop it just yet, to be able to reactivate it quickly if needed.

    This worked fine on an old 8.3 Postgres:

    UPDATE pg_database SET datallowconn=false WHERE datname='my_db_name';
    
    0 讨论(0)
  • 2020-12-14 01:16

    To mark database 'applogs' as not accepting new connections:

    update pg_database set datallowconn = false where datname = 'applogs';
    

    Another possibility would be to revoke 'connect' access on the database for the client role(s).

    Disconnect users from database = kill backend. So to disconnect all other users from "applogs" database, for example:

    select pg_terminate_backend(procpid)
    from pg_stat_activity
    where datname = 'applogs' and procpid <> pg_backend_pid();
    

    Once you've done both of those, you are the only user connected to 'applogs'. Although there might actually be a delay before the backends actually finish disconnecting?

    0 讨论(0)
  • 2020-12-14 01:28

    Starting PostgreSQL 9.5 we finally can:

    ALTER DATABASE db WITH ALLOW_CONNECTIONS false;
    
    0 讨论(0)
  • 2020-12-14 01:28

    If you are connected in session with the DB that you want to dissallow connecting to, and to stay connected in the same session after you disallow connections, then use this :

    UPDATE pg_database SET datallowconn = false WHERE datname = '_db_name_' ;
    

    ... which allows you to do stuff without any other connection happening until you re-enable

    But if you use this, it must be from in a session in another DB :

    ALTER DATABASE _db_name_ WITH ALLOW_CONNECTIONS false ;
    

    (( i realise this is almost a summary of the answers above ))

    0 讨论(0)
提交回复
热议问题