Force client disconnect using PostgreSQL

前端 未结 6 1095
轮回少年
轮回少年 2020-12-25 11:33

Is there a way to force clients to disconnect from PostgreSQL? I\'m looking for the equivlent of DB2\'s force application all.

I\'d like to do this on my development

相关标签:
6条回答
  • 2020-12-25 11:38

    I post my answer because I couldn't use any of them in my script, server 9.3:

    psql -U postgres -c "SELECT pid, (SELECT pg_terminate_backend(pid)) as killed from pg_stat_activity WHERE datname = 'my_database_to_alter';"
    

    In the next line, you can do anything yo want with 'my_database_to_alter'. As you can see, yo perform the query from the "postgres" database, which exists almost in every postgresql installation.

    Doing by superuser and outside the problem-database itself worked perfect for me.

    0 讨论(0)
  • 2020-12-25 11:44

    Kills idle processes in PostgreSQL 8.4:

    SELECT procpid, (SELECT pg_terminate_backend(procpid)) as killed from pg_stat_activity
       WHERE current_query LIKE '<IDLE>';
    
    0 讨论(0)
  • 2020-12-25 11:44

    probably a more heavy handed approach then should be used but:

    for x in `ps -eF | grep -E "postgres.*idle"| awk '{print $2}'`;do kill $x; done
    
    0 讨论(0)
  • 2020-12-25 11:46

    Combine pg_terminate_backend function and the pg_stat_activity system view.

    0 讨论(0)
  • 2020-12-25 11:48

    I found this thread on the mailing list. It suggests using SIGTERM to cause the clients to disconnect.

    Not as clean as db2 force application all.

    0 讨论(0)
  • 2020-12-25 11:57

    This SO answer beautifully explains (full quote from araqnid between the horizontal rules, then me again):


    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?


    Update from MarkJL: There is indeed a delay before the backends finish disconnecting.

    Now me again: That being said, mind that the procpid column was renamed to pid in PostgreSQL 9.2 and later.

    I think that this is much more helpful than the answer by Milen A. Radev which, while technically the same, does not come with usage examples and real-life suggestions.

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