Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: Temporarily disable connections

Tags:

postgresql

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 few connections alive at all times.

So the script restores dump into my_temp_database. Then it should rename my_database to my_old_database, my_temp_database to my_database, and eventually drop my_old_database.

How can I disconnect all clients, superuser or not, from my_database, so that it can be renamed? How I can I temporarily prevent them from reconnecting?

Is there a better way to do what I need?

like image 219
Konrad Garus Avatar asked Jul 06 '10 10:07

Konrad Garus


People also ask

How do I close a connection in PostgreSQL?

You can use pg_terminate_backend() to kill a connection. You have to be superuser to use this function.

How do I turn off idle connections in PostgreSQL?

Kill an Idle Connection: We have to provide the process 'id' within the query in a terminate function. >> SELECT pg_terminate_backend(7408); The process has been magnificently killed.

Is there a timeout for idle PostgreSQL connections?

No, something akin to the other answers is required for previous versions. SET SESSION is just for the current session (it will go back to the default once you open a new connection).

Can Postgres handle multiple connections?

No, you can only have a single statement executing at the same time on a PostgreSQL connections.


1 Answers

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?

like image 71
araqnid Avatar answered Sep 18 '22 20:09

araqnid