Quote field name identifiers in ORDER BY and MAX/MIN queries

Fixes #21100
This commit is contained in:
Alessandro Pasotti 2019-02-02 11:45:13 +01:00
parent 9a8c0d2898
commit b51426640d
2 changed files with 14 additions and 4 deletions

View File

@ -3604,7 +3604,7 @@ QSet<QVariant> QgsOgrProvider::uniqueValues( int index, int limit ) const
sql += " WHERE " + textEncoding()->fromUnicode( mSubsetString );
}
sql += " ORDER BY " + textEncoding()->fromUnicode( fld.name() ) + " ASC"; // quoting of fieldname produces a syntax error
sql += " ORDER BY " + quotedIdentifier( textEncoding()->fromUnicode( fld.name() ) ) + " ASC";
QgsDebugMsg( QStringLiteral( "SQL: %1" ).arg( textEncoding()->toUnicode( sql ) ) );
QgsOgrLayerUniquePtr l = mOgrLayer->ExecuteSQL( sql );
@ -3649,7 +3649,7 @@ QStringList QgsOgrProvider::uniqueStringsMatching( int index, const QString &sub
sql += " AND (" + textEncoding()->fromUnicode( mSubsetString ) + ')';
}
sql += " ORDER BY " + textEncoding()->fromUnicode( fld.name() ) + " ASC"; // quoting of fieldname produces a syntax error
sql += " ORDER BY " + quotedIdentifier( textEncoding()->fromUnicode( fld.name() ) ) + " ASC";
QgsDebugMsg( QStringLiteral( "SQL: %1" ).arg( textEncoding()->toUnicode( sql ) ) );
QgsOgrLayerUniquePtr l = mOgrLayer->ExecuteSQL( sql );
@ -3681,7 +3681,7 @@ QVariant QgsOgrProvider::minimumValue( int index ) const
QgsField fld = mAttributeFields.at( index );
// Don't quote column name (see https://trac.osgeo.org/gdal/ticket/5799#comment:9)
QByteArray sql = "SELECT MIN(" + textEncoding()->fromUnicode( fld.name() );
QByteArray sql = "SELECT MIN(" + quotedIdentifier( textEncoding()->fromUnicode( fld.name() ) );
sql += ") FROM " + quotedIdentifier( mOgrLayer->name() );
if ( !mSubsetString.isEmpty() )
@ -3715,7 +3715,7 @@ QVariant QgsOgrProvider::maximumValue( int index ) const
QgsField fld = mAttributeFields.at( index );
// Don't quote column name (see https://trac.osgeo.org/gdal/ticket/5799#comment:9)
QByteArray sql = "SELECT MAX(" + textEncoding()->fromUnicode( fld.name() );
QByteArray sql = "SELECT MAX(" + quotedIdentifier( textEncoding()->fromUnicode( fld.name() ) );
sql += ") FROM " + quotedIdentifier( mOgrLayer->name() );
if ( !mSubsetString.isEmpty() )

View File

@ -1293,6 +1293,16 @@ class TestPyQgsOGRProviderGpkg(unittest.TestCase):
self.assertNotEqual(vl.fields().indexFromName('json_content2'), -1)
self.assertEqual(vl.fields().indexFromName('json_content3'), -1)
def test_quote_identifier(self):
"""Regression #21100"""
tmpfile = os.path.join(self.basetestpath, 'bug21100-wierd_field_names.gpkg')
shutil.copy(os.path.join(unitTestDataPath(''), 'bug21100-wierd_field_names.gpkg'), tmpfile)
vl = QgsVectorLayer('{}|layerid=0'.format(tmpfile), 'foo', 'ogr')
self.assertTrue(vl.isValid())
for i in range(1, len(vl.fields())):
self.assertEqual(vl.uniqueValues(i), {'a', 'b', 'c'})
if __name__ == '__main__':
unittest.main()