Skip to content

Commit

Permalink
[postgres] Add a timeout for postgres connections
Browse files Browse the repository at this point in the history
Defaults to 30 seconds, but configurable via advanced settings/
global_settings ini
  • Loading branch information
nyalldawson committed Mar 15, 2018
1 parent 2526a6c commit 8658da3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
4 changes: 4 additions & 0 deletions resources/qgis_global_settings.ini
Expand Up @@ -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

17 changes: 16 additions & 1 deletion src/providers/postgres/qgspostgresconn.cpp
Expand Up @@ -40,6 +40,7 @@
#include <netinet/in.h>
#endif

const int PG_DEFAULT_TIMEOUT = 30;

QgsPostgresResult::~QgsPostgresResult()
{
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 )
Expand Down

0 comments on commit 8658da3

Please sign in to comment.