Skip to content

Commit 8658da3

Browse files
committedMar 15, 2018
[postgres] Add a timeout for postgres connections
Defaults to 30 seconds, but configurable via advanced settings/ global_settings ini
1 parent 2526a6c commit 8658da3

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed
 

‎resources/qgis_global_settings.ini

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,7 @@ connections-xyz\OpenStreetMap\zmin=0
3434
# for now this is online version of the User Guide for latest (LTR) release
3535
helpSearchPath=https://docs.qgis.org/$qgis_short_version/$qgis_locale/docs/user_manual/
3636

37+
[providers]
38+
# Default timeout for PostgreSQL servers (seconds)
39+
PostgreSQL\default_timeout=30
40+

‎src/providers/postgres/qgspostgresconn.cpp

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
#include <netinet/in.h>
4141
#endif
4242

43+
const int PG_DEFAULT_TIMEOUT = 30;
4344

4445
QgsPostgresResult::~QgsPostgresResult()
4546
{
@@ -217,6 +218,18 @@ QgsPostgresConn::QgsPostgresConn( const QString &conninfo, bool readOnly, bool s
217218
QgsDataSourceUri uri( conninfo );
218219
QString expandedConnectionInfo = uri.connectionInfo( true );
219220

221+
auto addDefaultTimeout = []( QString & connectString )
222+
{
223+
if ( !connectString.contains( QStringLiteral( "connect_timeout=" ) ) )
224+
{
225+
// add default timeout
226+
QgsSettings settings;
227+
int timeout = settings.value( QStringLiteral( "PostgreSQL/default_timeout" ), PG_DEFAULT_TIMEOUT, QgsSettings::Providers ).toInt();
228+
connectString += QStringLiteral( " connect_timeout=%1" ).arg( timeout );
229+
}
230+
};
231+
addDefaultTimeout( expandedConnectionInfo );
232+
220233
mConn = PQconnectdb( expandedConnectionInfo.toLocal8Bit() ); // use what is set based on locale; after connecting, use Utf8
221234

222235
// remove temporary cert/key/CA if they exist
@@ -258,7 +271,9 @@ QgsPostgresConn::QgsPostgresConn( const QString &conninfo, bool readOnly, bool s
258271
uri.setPassword( password );
259272

260273
QgsDebugMsg( "Connecting to " + uri.connectionInfo( false ) );
261-
mConn = PQconnectdb( uri.connectionInfo().toLocal8Bit() );
274+
QString connectString = uri.connectionInfo();
275+
addDefaultTimeout( connectString );
276+
mConn = PQconnectdb( connectString.toLocal8Bit() );
262277
}
263278

264279
if ( PQstatus() == CONNECTION_OK )

0 commit comments

Comments
 (0)
Please sign in to comment.