Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
[postgres] Fixes #40162 : Don't use explain plan when estimating coun…
…t on table
  • Loading branch information
troopa81 committed Nov 26, 2020
1 parent 5bd0058 commit feff180
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/providers/postgres/qgspostgresprovider.cpp
Expand Up @@ -3591,7 +3591,7 @@ long QgsPostgresProvider::featureCount() const
long num = -1;
if ( !mIsQuery && mUseEstimatedMetadata )
{
if ( connectionRO()->pgVersion() >= 90000 )
if ( relkind() == Relkind::View && connectionRO()->pgVersion() >= 90000 )
{
// parse explain output to estimate feature count
// we don't use pg_class reltuples because it returns 0 for view
Expand All @@ -3608,6 +3608,12 @@ long QgsPostgresProvider::featureCount() const
else
QgsLogger::warning( QStringLiteral( "Cannot parse JSON explain result to estimate feature count (%1) : %2" ).arg( sql, json ) );
}
else
{
sql = QStringLiteral( "SELECT reltuples::bigint FROM pg_catalog.pg_class WHERE oid=regclass(%1)::oid" ).arg( quotedValue( mQuery ) );
QgsPostgresResult result( connectionRO()->PQexec( sql ) );
num = result.PQgetvalue( 0, 0 ).toLong();
}
}
else
{
Expand Down
13 changes: 12 additions & 1 deletion tests/src/python/test_provider_postgres.py
Expand Up @@ -2296,6 +2296,17 @@ def testCheckTidPkOnViews(self):
for f in vl0.getFeatures():
self.assertNotEqual(f.attribute(0), NULL)

def testFeatureCountEstimatedOnTable(self):
"""
Test feature count on table when estimated data is enabled
"""
vl = QgsVectorLayer(
self.dbconn +
' sslmode=disable key=\'pk\' estimatedmetadata=true srid=4326 type=POINT table="qgis_test"."someData" (geom) sql=',
'test', 'postgres')
self.assertTrue(vl.isValid())
self.assertTrue(vl.featureCount() > 0)

def testFeatureCountEstimatedOnView(self):
"""
Test feature count on view when estimated data is enabled
Expand All @@ -2308,7 +2319,7 @@ def testFeatureCountEstimatedOnView(self):
' sslmode=disable key=\'pk\' estimatedmetadata=true srid=4326 type=POINT table="qgis_test"."somedataview" (geom) sql=',
'test', 'postgres')
self.assertTrue(vl.isValid())
self.assertTrue(self.source.featureCount() > 0)
self.assertTrue(vl.featureCount() > 0)

def testIdentityPk(self):
"""Test a table with identity pk, see GH #29560"""
Expand Down

0 comments on commit feff180

Please sign in to comment.