Skip to content
Permalink
Browse files

[postgres] Add a timeout for postgres connections

Defaults to 30 seconds, but configurable via advanced settings/
global_settings ini
  • Loading branch information
nyalldawson committed Mar 12, 2018
1 parent 2526a6c commit 8658da39e3d4b45235f6a4c89cb98ed62b82b6f0
Showing with 20 additions and 1 deletion.
  1. +4 −0 resources/qgis_global_settings.ini
  2. +16 −1 src/providers/postgres/qgspostgresconn.cpp
@@ -34,3 +34,7 @@ connections-xyz\OpenStreetMap\zmin=0
# for now this is online version of the User Guide for latest (LTR) release
helpSearchPath=https://docs.qgis.org/$qgis_short_version/$qgis_locale/docs/user_manual/

[providers]
# Default timeout for PostgreSQL servers (seconds)
PostgreSQL\default_timeout=30

@@ -40,6 +40,7 @@
#include <netinet/in.h>
#endif

const int PG_DEFAULT_TIMEOUT = 30;

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

auto addDefaultTimeout = []( QString & connectString )
{
if ( !connectString.contains( QStringLiteral( "connect_timeout=" ) ) )
{
// add default timeout
QgsSettings settings;
int timeout = settings.value( QStringLiteral( "PostgreSQL/default_timeout" ), PG_DEFAULT_TIMEOUT, QgsSettings::Providers ).toInt();
connectString += QStringLiteral( " connect_timeout=%1" ).arg( timeout );
}
};
addDefaultTimeout( expandedConnectionInfo );

mConn = PQconnectdb( expandedConnectionInfo.toLocal8Bit() ); // use what is set based on locale; after connecting, use Utf8

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

QgsDebugMsg( "Connecting to " + uri.connectionInfo( false ) );
mConn = PQconnectdb( uri.connectionInfo().toLocal8Bit() );
QString connectString = uri.connectionInfo();
addDefaultTimeout( connectString );
mConn = PQconnectdb( connectString.toLocal8Bit() );
}

if ( PQstatus() == CONNECTION_OK )

0 comments on commit 8658da3

Please sign in to comment.
You can’t perform that action at this time.