How to Terminate PostgreSQL Sessions
How to Terminate PostgreSQL Sessions
SESSIONS
I have encountered an interesting issue, as I could not perform specific database
operations due to unwanted and active sessions using the database. Thus, I will
Prerequisites
This blog post is based on a Debian Wheezy and PostgreSQL 9.1 version.
$ lsb_release -d
bit
I have deliberately written down this information here, as there are some minor
differences.
application, or just make sure nobody is querying database during a major update.
The solution is to use pg_stat_activity view to identify and filter active database
To prevent access during an update process or any other important activity you can
connections.
procpid as pid,
usename as username,
application_name as application,
client_addr as client_address,
current_query
FROM pg_stat_activity
current_query
----------+------+----------+-------------+----------------+-----------------------------------------------------
--------------------------------------------------------------------------------------------------------------
blog | 8603 | blog | blog_app | 192.168.3.11 | select * from posts order by pub_date
(3 rows)
Use the following query to terminate all connections to the specified database.
SELECT pg_terminate_backend(procpid)
FROM pg_stat_activity
SELECT pg_terminate_backend(procpid)
FROM pg_stat_activity
To terminate every other database connection you can use process ID attached to
SELECT pg_terminate_backend(procpid)
FROM pg_stat_activity
Alternatively, you can simply use username to filter out permitted connections.
SELECT pg_terminate_backend(procpid)
FROM pg_stat_activity
Every example mentioned above can be extended to include more conditions like
can just cancel running query using function shown in the following query.
SELECT pg_cancel_backend(procpid)
FROM pg_stat_activity
To prevent connections from specific database user revoke the connect privilege for
selected database.
REVOKE CONNECT
ON DATABASE wiki
FROM wiki
GRANT CONNECT
ON DATABASE wiki
TO wiki
REVOKE CONNECT
ON DATABASE wiki
FROM public
I did not mentioned it earlier but you can also use database user login privilege to
Alternatively, you can alter pg_database system table to disallow new connections to
specific database.
UPDATE pg_database
UPDATE pg_database
script
#!/bin/sh
#!/bin/sh
pg_terminate_backend(procpid) \
from pg_stat_activity \
Source: https://blog.sleeplessbeastie.eu/2014/07/23/how-to-terminate-postgresql-
sessions/