Postgresql – How to make PQExecPrepared() not hang if the network connection has been lost

clientpostgresql

We're using prepared statements and have found that if, after successfully connecting and executing some statements, the network link the connection was usning goes away, PQExecPrepared() hangs forever. Is there a way to dictate from the client side, a maximum time to wait? In comparison, if the Postgres server goes down, rather than the network, PQExecPrepared() returns immediately with an error.

Best Answer

When the remote PostgreSQL server goes down, the remote OS knows that and tells your OS that the connection has closed, by sending a TCP FIN. When the network goes down, there is no one who knows what happened (or at least no way for them to tell you what happened) so no TCP FIN. So you have to wait for the TCP connection itself to give up.

If you want more control over this, you can use PQsendQueryPrepared instead.