@@ -3537,26 +3537,51 @@ OGRLayerH QgsOgrProviderUtils::setSubsetString( OGRLayerH layer, GDALDatasetH ds
3537
3537
layerName = encoding->fromUnicode ( modifiedLayerName );
3538
3538
}
3539
3539
}
3540
- QByteArray sql ;
3540
+ OGRLayerH subsetLayer = 0 ;
3541
3541
if ( subsetString.startsWith ( QLatin1String ( " SELECT " ), Qt::CaseInsensitive ) )
3542
- sql = encoding->fromUnicode ( subsetString );
3542
+ {
3543
+ QByteArray sql = encoding->fromUnicode ( subsetString );
3544
+
3545
+ QgsDebugMsg ( QString ( " SQL: %1" ).arg ( encoding->toUnicode ( sql ) ) );
3546
+ subsetLayer = GDALDatasetExecuteSQL ( ds, sql.constData (), nullptr , nullptr );
3547
+ }
3543
3548
else
3544
3549
{
3550
+ QByteArray sqlPart1 = " SELECT " ;
3551
+ QByteArray sqlPart3 = " * FROM " + quotedIdentifier ( layerName, mGDALDriverName )
3552
+ + " WHERE " + encoding->fromUnicode ( subsetString );
3553
+
3554
+ origFidAddAttempted = true ;
3555
+
3545
3556
QByteArray fidColumn = OGR_L_GetFIDColumn ( layer );
3557
+ // Fallback to FID if OGR_L_GetFIDColumn returns nothing
3558
+ if ( fidColumn.isEmpty () )
3559
+ {
3560
+ fidColumn = " FID" ;
3561
+ }
3562
+
3563
+ QByteArray sql = sqlPart1 + fidColumn + " as orig_ogc_fid, " + sqlPart3;
3564
+ QgsDebugMsg ( QString ( " SQL: %1" ).arg ( encoding->toUnicode ( sql ) ) );
3565
+ subsetLayer = GDALDatasetExecuteSQL ( ds, sql.constData (), nullptr , nullptr );
3546
3566
3547
- sql = QByteArray ( " SELECT " );
3548
- if ( !fidColumn.isEmpty () )
3567
+ // See https://lists.osgeo.org/pipermail/qgis-developer/2017-September/049802.html
3568
+ // If execute SQL fails because it did not find the fidColumn, retry with hardcoded FID
3569
+ if ( !subsetLayer )
3549
3570
{
3550
- sql += fidColumn + " as orig_ogc_fid, " ;
3551
- origFidAddAttempted = true ;
3571
+ QByteArray sql = sqlPart1 + " FID as orig_ogc_fid, " + sqlPart3;
3572
+ QgsDebugMsg ( QString ( " SQL: %1" ).arg ( encoding->toUnicode ( sql ) ) );
3573
+ subsetLayer = GDALDatasetExecuteSQL ( ds, sql.constData (), nullptr , nullptr );
3574
+ }
3575
+ // If that also fails, just continue without the orig_ogc_fid
3576
+ if ( !subsetLayer )
3577
+ {
3578
+ QByteArray sql = sqlPart1 + sqlPart3;
3579
+ QgsDebugMsg ( QString ( " SQL: %1" ).arg ( encoding->toUnicode ( sql ) ) );
3580
+ subsetLayer = GDALDatasetExecuteSQL ( ds, sql.constData (), nullptr , nullptr );
3581
+ origFidAddAttempted = false ;
3552
3582
}
3553
- sql += " * FROM " + quotedIdentifier ( layerName, mGDALDriverName );
3554
- sql += " WHERE " + encoding->fromUnicode ( subsetString );
3555
3583
}
3556
3584
3557
- QgsDebugMsg ( QString ( " SQL: %1" ).arg ( encoding->toUnicode ( sql ) ) );
3558
- OGRLayerH subsetLayer = GDALDatasetExecuteSQL ( ds, sql.constData (), nullptr , nullptr );
3559
-
3560
3585
// Check if first column is orig_ogc_fid
3561
3586
if ( origFidAddAttempted && subsetLayer )
3562
3587
{
0 commit comments