/
qgsogrprovider.cpp
4492 lines (3930 loc) · 147 KB
/
qgsogrprovider.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
qgsogrprovider.cpp Data provider for OGR supported formats
Formerly known as qgsshapefileprovider.cpp
begin : Oct 29, 2003
copyright : (C) 2003 by Gary E.Sherman
email : sherman at mrcc.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsogrprovider.h"
///@cond PRIVATE
#include "qgscplerrorhandler_p.h"
#include "qgslogger.h"
#include "qgsvectorfilewriter.h"
#include "qgsapplication.h"
#include "qgssettings.h"
#include "qgsogrconnpool.h"
#include "qgsogrtransaction.h"
#include "qgsogrfeatureiterator.h"
#include "qgsgdalutils.h"
#include "qgsfeedback.h"
#include "qgscplhttpfetchoverrider.h"
#include "qgsmetadatautils.h"
#include "qgslocalec.h"
#include "qgssymbol.h"
#include "qgsembeddedsymbolrenderer.h"
#include "qgsprovidersublayerdetails.h"
#include "qgsvectorlayer.h"
#include "qgsproviderregistry.h"
#include "qgsvariantutils.h"
#include "qgsjsonutils.h"
#include "qgssetrequestinitiator_p.h"
#include <nlohmann/json.hpp>
#define CPL_SUPRESS_CPLUSPLUS //#spellok
#include <gdal.h> // to collect version information
#include <ogr_api.h>
#include <ogr_srs_api.h>
#include <cpl_string.h>
#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(3, 2, 1)
// Temporary solution for gdal < 3.2.1 without GDAL Unique support
#include "qgssqliteutils.h"
#include <sqlite3.h>
// end temporary
#endif
#include <limits>
#include <memory>
#include <QTextCodec>
#include <QFile>
#include <QFileInfo>
#include <QRegularExpression>
#define TEXT_PROVIDER_KEY QStringLiteral( "ogr" )
#define TEXT_PROVIDER_DESCRIPTION QStringLiteral( "OGR data provider" )
bool QgsOgrProvider::convertField( QgsField &field, const QTextCodec &encoding )
{
OGRFieldType ogrType = OFTString; //default to string
OGRFieldSubType ogrSubType = OFSTNone;
int ogrWidth = field.length();
int ogrPrecision = field.precision();
if ( ogrPrecision > 0 )
ogrWidth += 1;
switch ( field.type() )
{
case QVariant::LongLong:
ogrType = OFTInteger64;
ogrPrecision = 0;
ogrWidth = ogrWidth > 0 && ogrWidth <= 21 ? ogrWidth : 21;
break;
case QVariant::String:
ogrType = OFTString;
if ( ogrWidth < 0 || ogrWidth > 255 )
ogrWidth = 255;
break;
case QVariant::Int:
ogrType = OFTInteger;
ogrWidth = ogrWidth > 0 && ogrWidth <= 10 ? ogrWidth : 10;
ogrPrecision = 0;
break;
case QVariant::Bool:
ogrType = OFTInteger;
ogrSubType = OFSTBoolean;
ogrWidth = 1;
ogrPrecision = 0;
break;
case QVariant::Double:
ogrType = OFTReal;
break;
case QVariant::Date:
ogrType = OFTDate;
break;
case QVariant::Time:
ogrType = OFTTime;
break;
case QVariant::DateTime:
ogrType = OFTDateTime;
break;
case QVariant::StringList:
{
ogrType = OFTStringList;
break;
}
case QVariant::List:
if ( field.subType() == QVariant::String )
{
ogrType = OFTStringList;
}
else if ( field.subType() == QVariant::Int )
{
ogrType = OFTIntegerList;
}
else if ( field.subType() == QVariant::LongLong )
{
ogrType = OFTInteger64List;
}
else if ( field.subType() == QVariant::Double )
{
ogrType = OFTRealList;
}
else
{
// other lists are supported at this moment
return false;
}
break;
case QVariant::Map:
ogrType = OFTString;
ogrSubType = OFSTJSON;
break;
default:
return false;
}
if ( ogrSubType != OFSTNone )
field.setTypeName( encoding.toUnicode( OGR_GetFieldSubTypeName( ogrSubType ) ) );
else
field.setTypeName( encoding.toUnicode( OGR_GetFieldTypeName( ogrType ) ) );
field.setLength( ogrWidth );
field.setPrecision( ogrPrecision );
return true;
}
void QgsOgrProvider::repack()
{
if ( !mValid || mGDALDriverName != QLatin1String( "ESRI Shapefile" ) || !mOgrOrigLayer )
return;
// run REPACK on shape files
QByteArray sql = QByteArray( "REPACK " ) + mOgrOrigLayer->name(); // don't quote the layer name as it works with spaces in the name and won't work if the name is quoted
QgsDebugMsgLevel( QStringLiteral( "SQL: %1" ).arg( QString::fromUtf8( sql ) ), 2 );
CPLErrorReset();
mOgrOrigLayer->ExecuteSQLNoReturn( sql );
if ( CPLGetLastErrorType() != CE_None )
{
pushError( tr( "OGR[%1] error %2: %3" ).arg( CPLGetLastErrorType() ).arg( CPLGetLastErrorNo() ).arg( CPLGetLastErrorMsg() ) );
}
if ( mFilePath.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) || mFilePath.endsWith( QLatin1String( ".dbf" ), Qt::CaseInsensitive ) )
{
QString packedDbf( mFilePath.left( mFilePath.size() - 4 ) + "_packed.dbf" );
if ( QFile::exists( packedDbf ) )
{
QgsMessageLog::logMessage( tr( "Possible corruption after REPACK detected. %1 still exists. This may point to a permission or locking problem of the original DBF." ).arg( packedDbf ), tr( "OGR" ), Qgis::MessageLevel::Critical );
mOgrSqlLayer.reset();
mOgrOrigLayer.reset();
QString errCause;
if ( mLayerName.isNull() )
{
mOgrOrigLayer = QgsOgrProviderUtils::getLayer( mFilePath, true, mOpenOptions, mLayerIndex, errCause, true );
}
else
{
mOgrOrigLayer = QgsOgrProviderUtils::getLayer( mFilePath, true, mOpenOptions, mLayerName, errCause, true );
}
if ( !mOgrOrigLayer )
{
QgsMessageLog::logMessage( tr( "Original layer could not be reopened." ) + " " + errCause, tr( "OGR" ), Qgis::MessageLevel::Critical );
mValid = false;
}
mOgrLayer = mOgrOrigLayer.get();
}
}
if ( mFeaturesCounted != static_cast< long long >( Qgis::FeatureCountState::Uncounted ) &&
mFeaturesCounted != static_cast< long long >( Qgis::FeatureCountState::UnknownCount ) )
{
long long oldcount = mFeaturesCounted;
recalculateFeatureCount();
if ( oldcount != mFeaturesCounted )
emit dataChanged();
}
}
Qgis::VectorExportResult QgsOgrProvider::createEmptyLayer( const QString &uri,
const QgsFields &fields,
Qgis::WkbType wkbType,
const QgsCoordinateReferenceSystem &srs,
bool overwrite,
QMap<int, int> *oldToNewAttrIdxMap,
QString *errorMessage,
const QMap<QString, QVariant> *options )
{
QString encoding;
QString driverName = QStringLiteral( "GPKG" );
QStringList dsOptions, layerOptions;
QString layerName;
if ( options )
{
if ( options->contains( QStringLiteral( "fileEncoding" ) ) )
encoding = options->value( QStringLiteral( "fileEncoding" ) ).toString();
if ( options->contains( QStringLiteral( "driverName" ) ) )
driverName = options->value( QStringLiteral( "driverName" ) ).toString();
if ( options->contains( QStringLiteral( "datasourceOptions" ) ) )
dsOptions << options->value( QStringLiteral( "datasourceOptions" ) ).toStringList();
if ( options->contains( QStringLiteral( "layerOptions" ) ) )
layerOptions << options->value( QStringLiteral( "layerOptions" ) ).toStringList();
if ( options->contains( QStringLiteral( "layerName" ) ) )
layerName = options->value( QStringLiteral( "layerName" ) ).toString();
}
oldToNewAttrIdxMap->clear();
if ( errorMessage )
errorMessage->clear();
QgsVectorFileWriter::ActionOnExistingFile action( QgsVectorFileWriter::CreateOrOverwriteFile );
bool update = false;
if ( options && options->contains( QStringLiteral( "update" ) ) )
{
update = options->value( QStringLiteral( "update" ) ).toBool();
if ( update )
{
// when updating an existing dataset, always use the original driver
GDALDriverH hDriver = GDALIdentifyDriverEx( uri.toUtf8().constData(), GDAL_OF_VECTOR, nullptr, nullptr );
if ( hDriver )
{
driverName = GDALGetDriverShortName( hDriver );
}
if ( !overwrite && !layerName.isEmpty() )
{
gdal::dataset_unique_ptr hDS( GDALOpenEx( uri.toUtf8().constData(), GDAL_OF_VECTOR, nullptr, nullptr, nullptr ) );
if ( hDS )
{
if ( GDALDatasetGetLayerByName( hDS.get(), layerName.toUtf8().constData() ) )
{
if ( errorMessage )
*errorMessage += QObject::tr( "Layer %2 of %1 exists and overwrite flag is false." )
.arg( uri, layerName );
return Qgis::VectorExportResult::ErrorCreatingDataSource;
}
}
}
if ( QFileInfo::exists( uri ) )
action = QgsVectorFileWriter::CreateOrOverwriteLayer;
}
}
if ( !overwrite && !update )
{
if ( QFileInfo::exists( uri ) )
{
if ( errorMessage )
*errorMessage += QObject::tr( "Unable to create the datasource. %1 exists and overwrite flag is false." )
.arg( uri );
return Qgis::VectorExportResult::ErrorCreatingDataSource;
}
}
QgsFields cleanedFields = fields;
#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(3, 6, 3)
// Temporary solution. Proper fix in https://github.com/OSGeo/gdal/pull/7147
if ( driverName == QLatin1String( "OpenFileGDB" ) )
{
QString fidColumn = QStringLiteral( "OBJECTID" );
for ( const QString &layerOption : layerOptions )
{
if ( layerOption.startsWith( QLatin1String( "FID=" ), Qt::CaseInsensitive ) )
{
fidColumn = layerOption.mid( static_cast<int>( strlen( "FID=" ) ) );
break;
}
}
const int objectIdIndex = cleanedFields.lookupField( fidColumn );
if ( objectIdIndex >= 0 )
{
cleanedFields.remove( objectIdIndex );
}
}
#endif
QString newLayerName( layerName );
QgsVectorFileWriter::SaveVectorOptions saveOptions;
saveOptions.layerName = layerName;
saveOptions.fileEncoding = encoding;
saveOptions.driverName = driverName;
saveOptions.datasourceOptions = dsOptions;
saveOptions.layerOptions = layerOptions;
saveOptions.actionOnExistingFile = action;
saveOptions.symbologyExport = Qgis::FeatureSymbologyExport::NoSymbology;
std::unique_ptr< QgsVectorFileWriter > writer( QgsVectorFileWriter::create( uri, cleanedFields, wkbType, srs, QgsCoordinateTransformContext(), saveOptions, QgsFeatureSink::SinkFlags(), nullptr, &newLayerName ) );
layerName = newLayerName;
QgsVectorFileWriter::WriterError error = writer->hasError();
if ( error )
{
if ( errorMessage )
*errorMessage += writer->errorMessage();
return static_cast<Qgis::VectorExportResult>( error );
}
QMap<int, int> attrIdxMap = writer->attrIdxToOgrIdx();
writer.reset();
{
bool firstFieldIsFid = false;
bool fidColumnIsField = false;
if ( !layerName.isEmpty() )
{
gdal::dataset_unique_ptr hDS( GDALOpenEx( uri.toUtf8().constData(), GDAL_OF_VECTOR, nullptr, nullptr, nullptr ) );
if ( hDS )
{
OGRLayerH hLayer = GDALDatasetGetLayerByName( hDS.get(), layerName.toUtf8().constData() );
if ( hLayer )
{
// Expose the OGR FID if it comes from a "real" column (typically GPKG)
// and make sure that this FID column is not exposed as a regular OGR field (shouldn't happen normally)
const QString ogrFidColumnName { OGR_L_GetFIDColumn( hLayer ) };
firstFieldIsFid = !( EQUAL( OGR_L_GetFIDColumn( hLayer ), "" ) ) &&
OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hLayer ), ogrFidColumnName.toUtf8() ) < 0 &&
cleanedFields.indexFromName( ogrFidColumnName.toUtf8() ) < 0;
// At this point we must check if there is a real FID field in the the fields argument,
// because in that case we don't want to shift all fields (see issue GH #34333)
// Check for unique values should be performed in client code.
for ( const auto &f : std::as_const( fields ) )
{
if ( f.name().compare( ogrFidColumnName, Qt::CaseSensitivity::CaseInsensitive ) == 0 )
{
fidColumnIsField = true;
break;
}
}
}
}
}
const bool shiftColumnsByOne { firstFieldIsFid &&( ! fidColumnIsField ) };
for ( QMap<int, int>::const_iterator attrIt = attrIdxMap.constBegin(); attrIt != attrIdxMap.constEnd(); ++attrIt )
{
oldToNewAttrIdxMap->insert( attrIt.key(), *attrIt + ( shiftColumnsByOne ? 1 : 0 ) );
}
}
QgsOgrProviderUtils::invalidateCachedLastModifiedDate( uri );
return Qgis::VectorExportResult::Success;
}
QgsOgrProvider::QgsOgrProvider( QString const &uri, const ProviderOptions &options, QgsDataProvider::ReadFlags flags )
: QgsVectorDataProvider( uri, options, flags )
{
QgsApplication::registerOgrDrivers();
QgsSettings settings;
// we always disable GDAL side shapefile encoding handling, and do it on the QGIS side.
// why? it's not the ideal choice, but...
// - if we DON'T disable GDAL side encoding support, then there's NO way to change the encoding used when reading
// shapefiles. And unfortunately the embedded encoding (which is read by GDAL) is sometimes wrong, so we need
// to expose support for users to be able to change and correct this
// - we can't change this setting on-the-fly. If we don't set it upfront, we can't reverse this decision later when
// a user does want/need to manually specify the encoding
CPLSetConfigOption( "SHAPE_ENCODING", "" );
#ifndef QT_NO_NETWORKPROXY
QgsGdalUtils::setupProxy();
#endif
// make connection to the data source
QgsDebugMsgLevel( "Data source uri is [" + uri + ']', 2 );
mFilePath = QgsOgrProviderUtils::analyzeURI( uri,
mIsSubLayer,
mLayerIndex,
mLayerName,
mSubsetString,
mOgrGeometryTypeFilter,
mOpenOptions );
const QVariantMap parts = QgsOgrProviderMetadata().decodeUri( uri );
if ( parts.contains( QStringLiteral( "uniqueGeometryType" ) ) )
{
mUniqueGeometryType = parts.value( QStringLiteral( "uniqueGeometryType" ) ).toString() == QLatin1String( "yes" );
}
// to be called only after mFilePath has been set
invalidateNetworkCache();
if ( uri.contains( QLatin1String( "authcfg" ) ) )
{
const thread_local QRegularExpression authcfgRe( QStringLiteral( " authcfg='([^']+)'" ) );
QRegularExpressionMatch match;
if ( uri.contains( authcfgRe, &match ) )
{
mAuthCfg = match.captured( 1 );
// momentarily re-add authcfg since it was stripped off in analyzeURI
mFilePath = QgsOgrProviderUtils::expandAuthConfig( QStringLiteral( "%1 authcfg='%2'" ).arg( mFilePath, mAuthCfg ) );
}
}
QgsCPLHTTPFetchOverrider oCPLHTTPFetcher( mAuthCfg );
QgsSetCPLHTTPFetchOverriderInitiatorClass( oCPLHTTPFetcher, QStringLiteral( "QgsOgrProvider" ) );
if ( mReadFlags & QgsDataProvider::ForceReadOnly )
{
open( OpenModeForceReadOnly );
}
else
{
open( OpenModeInitial );
}
QList<NativeType> nativeTypes;
if ( mOgrOrigLayer )
{
nativeTypes = QgsOgrUtils::nativeFieldTypesForDriver( mOgrOrigLayer->driver() );
}
setNativeTypes( nativeTypes );
if ( mOgrOrigLayer )
{
bool is3D = OGR_GT_HasZ( mOGRGeomType );
/* We will not analyse the first geometry to compute if we have 3D or 2D data.
* We will believe in the metadata, even if the metadata is corrupted or misdefined.
* Below, here is an example of how retrieve the 3D/2D state according to the first geometry:
*/
// if ( !is3D )
// {
// gdal::ogr_feature_unique_ptr f;
// mOgrOrigLayer->ResetReading();
// f.reset( mOgrOrigLayer->GetNextFeature() );
// if ( f )
// {
// OGRGeometryH g = OGR_F_GetGeometryRef( f.get() );
// if ( g && !OGR_G_IsEmpty( g ) )
// {
// is3D = OGR_G_Is3D( g );
// }
// }
// }
elevationProperties()->setContainsElevationData( is3D );
mOgrOrigLayer->ResetReading(); // release
}
// layer metadata
loadMetadata();
QgsOgrConnPool::instance()->ref( QgsOgrProviderUtils::connectionPoolId( dataSourceUri( true ), mShareSameDatasetAmongLayers ) );
}
QgsOgrProvider::~QgsOgrProvider()
{
QgsOgrConnPool::instance()->unref( QgsOgrProviderUtils::connectionPoolId( dataSourceUri( true ), mShareSameDatasetAmongLayers ) );
// We must also make sure to flush unusef cached connections so that
// the file can be removed (#15137)
QgsOgrConnPool::instance()->invalidateConnections( QgsOgrProviderUtils::connectionPoolId( dataSourceUri( true ), mShareSameDatasetAmongLayers ) );
// Do that as last step for final cleanup that might be prevented by
// still opened datasets.
close();
}
QString QgsOgrProvider::dataSourceUri( bool expandAuthConfig ) const
{
if ( expandAuthConfig && QgsDataProvider::dataSourceUri( ).contains( QLatin1String( "authcfg" ) ) )
{
return QgsOgrProviderUtils::expandAuthConfig( QgsDataProvider::dataSourceUri( ) );
}
else
{
return QgsDataProvider::dataSourceUri( );
}
}
QgsTransaction *QgsOgrProvider::transaction() const
{
return static_cast<QgsTransaction *>( mTransaction );
}
void QgsOgrProvider::setTransaction( QgsTransaction *transaction )
{
QgsDebugMsgLevel( QStringLiteral( "set transaction %1" ).arg( transaction != nullptr ), 2 );
// static_cast since layers cannot be added to a transaction of a non-matching provider
mTransaction = static_cast<QgsOgrTransaction *>( transaction );
}
QgsAbstractFeatureSource *QgsOgrProvider::featureSource() const
{
return new QgsOgrFeatureSource( this );
}
bool QgsOgrProvider::setSubsetString( const QString &theSQL, bool updateFeatureCount )
{
return _setSubsetString( theSQL, updateFeatureCount, true );
}
QString QgsOgrProvider::subsetString() const
{
return mSubsetString;
}
uint QgsOgrProvider::subLayerCount() const
{
uint count = layerCount();
QString errCause;
QgsOgrLayerUniquePtr layerStyles = QgsOgrProviderUtils::getLayer( mFilePath, QStringLiteral( "layer_styles" ), errCause );
if ( layerStyles )
{
count--;
}
return count;
}
QStringList subLayerDetailsToStringList( const QList< QgsProviderSublayerDetails > &layers )
{
QStringList res;
res.reserve( layers.size() );
for ( const QgsProviderSublayerDetails &layer : layers )
{
const OGRwkbGeometryType ogrGeomType = QgsOgrProviderUtils::ogrTypeFromQgisType( layer.wkbType() );
const QStringList parts { QString::number( layer.layerNumber() ),
layer.name(),
QString::number( layer.featureCount() ),
QgsOgrProviderUtils::ogrWkbGeometryTypeName( ogrGeomType ),
layer.geometryColumnName(),
layer.description() };
res << parts.join( QgsDataProvider::sublayerSeparator() );
}
return res;
}
QStringList QgsOgrProvider::subLayers() const
{
const bool withFeatureCount = ( mReadFlags & QgsDataProvider::SkipFeatureCount ) == 0;
Qgis::SublayerQueryFlags flags = withFeatureCount
? ( Qgis::SublayerQueryFlag::CountFeatures | Qgis::SublayerQueryFlag::ResolveGeometryType )
: Qgis::SublayerQueryFlag::ResolveGeometryType;
if ( mIsSubLayer )
flags |= Qgis::SublayerQueryFlag::IncludeSystemTables;
return subLayerDetailsToStringList( _subLayers( flags ) );
}
QgsLayerMetadata QgsOgrProvider::layerMetadata() const
{
return mLayerMetadata;
}
QList<QgsProviderSublayerDetails> QgsOgrProvider::_subLayers( Qgis::SublayerQueryFlags flags ) const
{
QgsCPLHTTPFetchOverrider oCPLHTTPFetcher( mAuthCfg );
QgsSetCPLHTTPFetchOverriderInitiatorClass( oCPLHTTPFetcher, QStringLiteral( "QgsOgrProvider" ) );
if ( !mValid )
{
return {};
}
if ( !mSubLayerList.isEmpty() )
return mSubLayerList;
const size_t totalLayerCount = layerCount();
if ( mOgrLayer && ( mIsSubLayer || totalLayerCount == 1 ) )
{
mSubLayerList << QgsOgrProviderUtils::querySubLayerList( mLayerIndex, mOgrLayer, nullptr, mGDALDriverName, flags, dataSourceUri(), totalLayerCount == 1 );
}
else
{
// In case there is no free opened dataset in the cache, keep the first
// layer alive while we iterate over the other layers, so that we can
// reuse the same dataset. Can help in a particular with a FileGDB with
// the FileGDB driver
QgsOgrLayerUniquePtr firstLayer;
for ( size_t i = 0; i < totalLayerCount ; i++ )
{
QString errCause;
QgsOgrLayerUniquePtr layer = QgsOgrProviderUtils::getLayer( mOgrOrigLayer->datasetName(),
mOgrOrigLayer->updateMode(),
mOgrOrigLayer->options(),
i,
errCause,
// do not check timestamp beyond the first
// layer
firstLayer == nullptr );
if ( !layer )
continue;
mSubLayerList << QgsOgrProviderUtils::querySubLayerList( i, layer.get(), nullptr, mGDALDriverName, flags, dataSourceUri(), totalLayerCount == 1 );
if ( firstLayer == nullptr )
{
firstLayer = std::move( layer );
}
}
}
return mSubLayerList;
}
void QgsOgrProvider::setEncoding( const QString &e )
{
QgsCPLHTTPFetchOverrider oCPLHTTPFetcher( mAuthCfg );
QgsSetCPLHTTPFetchOverriderInitiatorClass( oCPLHTTPFetcher, QStringLiteral( "QgsOgrProvider" ) );
QgsSettings settings;
// if the layer has the OLCStringsAsUTF8 capability, we CANNOT override the
// encoding on the QGIS side!
if ( mOgrLayer && !mOgrLayer->TestCapability( OLCStringsAsUTF8 ) )
{
QgsVectorDataProvider::setEncoding( e );
}
else
{
QgsVectorDataProvider::setEncoding( QStringLiteral( "UTF-8" ) );
}
loadFields();
}
// This is reused by dataItem
OGRwkbGeometryType QgsOgrProvider::getOgrGeomType( const QString &driverName, OGRLayerH ogrLayer )
{
OGRFeatureDefnH fdef = OGR_L_GetLayerDefn( ogrLayer );
OGRwkbGeometryType geomType = wkbUnknown;
if ( fdef )
{
geomType = OGR_FD_GetGeomType( fdef );
// Handle wkbUnknown and its Z/M variants. QGIS has no unknown Z/M variants,
// so just use flat wkbUnknown
if ( wkbFlatten( geomType ) == wkbUnknown )
geomType = wkbUnknown;
// Some ogr drivers (e.g. GML) are not able to determine the geometry type of a layer like this.
// In such cases, we use virtual sublayers for each geometry if the layer contains
// multiple geometries (see subLayers) otherwise we guess geometry type from the first
// feature that has a geometry (limit us to a few features, not the whole layer)
//
// For ESRI formats with a GeometryCollection25D type we also query features for the geometry type,
// as they may be ESRI MultiPatch files which we want to report as MultiPolygon25D types
if ( geomType == wkbUnknown
|| ( geomType == wkbGeometryCollection25D && ( driverName == QLatin1String( "ESRI Shapefile" ) || driverName == QLatin1String( "OpenFileGDB" ) || driverName == QLatin1String( "FileGDB" ) ) ) )
{
geomType = wkbNone;
OGR_L_ResetReading( ogrLayer );
for ( int i = 0; i < 10; i++ )
{
gdal::ogr_feature_unique_ptr nextFeature( OGR_L_GetNextFeature( ogrLayer ) );
if ( !nextFeature )
break;
geomType = QgsOgrProviderUtils::resolveGeometryTypeForFeature( nextFeature.get(), driverName );
if ( geomType != wkbNone )
break;
}
OGR_L_ResetReading( ogrLayer );
}
}
return geomType;
}
void QgsOgrProvider::loadFields()
{
QgsOgrConnPool::instance()->invalidateConnections( QgsOgrProviderUtils::connectionPoolId( dataSourceUri( true ), mShareSameDatasetAmongLayers ) );
//the attribute fields need to be read again when the encoding changes
mAttributeFields.clear();
mDefaultValues.clear();
mPrimaryKeyAttrs.clear();
if ( !mOgrLayer )
return;
if ( mOgrGeometryTypeFilter != wkbUnknown )
{
mOGRGeomType = mOgrGeometryTypeFilter;
}
else
{
QRecursiveMutex *mutex = nullptr;
OGRLayerH ogrLayer = mOgrLayer->getHandleAndMutex( mutex );
QMutexLocker locker( mutex );
mOGRGeomType = getOgrGeomType( mGDALDriverName, ogrLayer );
}
QgsOgrFeatureDefn &fdef = mOgrLayer->GetLayerDefn();
// Expose the OGR FID if it comes from a "real" column (typically GPKG)
// and make sure that this FID column is not exposed as a regular OGR field (shouldn't happen normally)
QByteArray fidColumn( mOgrLayer->GetFIDColumn() );
mFirstFieldIsFid = !fidColumn.isEmpty() &&
fdef.GetFieldIndex( fidColumn ) < 0;
#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(3, 2, 1)
// This is a temporary solution until GDAL Unique support is available
QSet<QString> uniqueFieldNames;
if ( mGDALDriverName == QLatin1String( "GPKG" ) )
{
sqlite3_database_unique_ptr dsPtr;
if ( dsPtr.open_v2( mFilePath, SQLITE_OPEN_READONLY, nullptr ) == SQLITE_OK )
{
QString errMsg;
uniqueFieldNames = QgsSqliteUtils::uniqueFields( dsPtr.get(), mOgrLayer->name(), errMsg );
if ( ! errMsg.isEmpty() )
{
QgsMessageLog::logMessage( tr( "GPKG error searching for unique constraints on fields for table %1. (%2)" ).arg( QString( mOgrLayer->name() ), errMsg ), tr( "OGR" ) );
}
}
}
#endif
int createdFields = 0;
if ( mFirstFieldIsFid )
{
QgsField fidField(
fidColumn,
QVariant::LongLong,
QStringLiteral( "Integer64" )
);
// Set constraints for feature id
QgsFieldConstraints constraints = fidField.constraints();
constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider );
constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider );
fidField.setConstraints( constraints );
mAttributeFields.append(
fidField
);
mDefaultValues.insert( 0, tr( "Autogenerate" ) );
createdFields++;
mPrimaryKeyAttrs << 0;
}
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,3,0)
// needed for field domain retrieval on GDAL 3.3+
QRecursiveMutex *datasetMutex = nullptr;
GDALDatasetH ds = mOgrLayer->getDatasetHandleAndMutex( datasetMutex );
QMutexLocker locker( datasetMutex );
#endif
for ( int i = 0; i < fdef.GetFieldCount(); ++i )
{
OGRFieldDefnH fldDef = fdef.GetFieldDefn( i );
const OGRFieldType ogrType = OGR_Fld_GetType( fldDef );
const OGRFieldSubType ogrSubType = OGR_Fld_GetSubType( fldDef );
QVariant::Type varType = QVariant::Invalid;
QVariant::Type varSubType = QVariant::Invalid;
QgsOgrUtils::ogrFieldTypeToQVariantType( ogrType, ogrSubType, varType, varSubType );
//TODO: fix this hack
#ifdef ANDROID
QString name = OGR_Fld_GetNameRef( fldDef );
#else
QString name = textEncoding()->toUnicode( OGR_Fld_GetNameRef( fldDef ) );
#endif
if ( mAttributeFields.indexFromName( name ) != -1 )
{
QString tmpname = name + "_%1";
int fix = 0;
while ( mAttributeFields.indexFromName( name ) != -1 )
{
name = tmpname.arg( ++fix );
}
}
int width = OGR_Fld_GetWidth( fldDef );
int prec = OGR_Fld_GetPrecision( fldDef );
if ( prec > 0 )
width -= 1;
QString typeName = OGR_GetFieldTypeName( ogrType );
if ( ogrSubType != OFSTNone )
typeName = OGR_GetFieldSubTypeName( ogrSubType );
QgsField newField = QgsField(
name,
varType,
#ifdef ANDROID
typeName,
#else
textEncoding()->toUnicode( typeName.toStdString().c_str() ),
#endif
width, prec, QString(), varSubType
);
const QString alias = textEncoding()->toUnicode( OGR_Fld_GetAlternativeNameRef( fldDef ) );
if ( !alias.isEmpty() )
{
newField.setAlias( alias );
}
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,7,0)
{
const QString comment = textEncoding()->toUnicode( OGR_Fld_GetComment( fldDef ) );
if ( !comment.isEmpty() )
{
newField.setComment( comment );
}
}
#endif
// check if field is nullable
bool nullable = OGR_Fld_IsNullable( fldDef );
if ( !nullable )
{
QgsFieldConstraints constraints;
constraints.setConstraint( QgsFieldConstraints::ConstraintNotNull, QgsFieldConstraints::ConstraintOriginProvider );
newField.setConstraints( constraints );
}
#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(3, 2, 1)
if ( uniqueFieldNames.contains( OGR_Fld_GetNameRef( fldDef ) ) )
#else
if ( OGR_Fld_IsUnique( fldDef ) )
#endif
{
QgsFieldConstraints constraints = newField.constraints();
constraints.setConstraint( QgsFieldConstraints::ConstraintUnique, QgsFieldConstraints::ConstraintOriginProvider );
newField.setConstraints( constraints );
}
// check if field has default value
QString defaultValue = textEncoding()->toUnicode( OGR_Fld_GetDefault( fldDef ) );
if ( !defaultValue.isEmpty() && !OGR_Fld_IsDefaultDriverSpecific( fldDef ) )
{
if ( defaultValue.startsWith( '\'' ) )
{
defaultValue = defaultValue.remove( 0, 1 );
defaultValue.chop( 1 );
defaultValue.replace( QLatin1String( "''" ), QLatin1String( "'" ) );
}
mDefaultValues.insert( createdFields, defaultValue );
}
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,3,0)
if ( const char *domainName = OGR_Fld_GetDomainName( fldDef ) )
{
QgsFieldConstraints constraints = newField.constraints();
constraints.setDomainName( domainName );
newField.setConstraints( constraints );
// dataset retains ownership of domain!
if ( OGRFieldDomainH domain = GDALDatasetGetFieldDomain( ds, domainName ) )
{
switch ( OGR_FldDomain_GetSplitPolicy( domain ) )
{
case OFDSP_DEFAULT_VALUE:
newField.setSplitPolicy( Qgis::FieldDomainSplitPolicy::DefaultValue );
break;
case OFDSP_DUPLICATE:
newField.setSplitPolicy( Qgis::FieldDomainSplitPolicy::Duplicate );
break;
case OFDSP_GEOMETRY_RATIO:
newField.setSplitPolicy( Qgis::FieldDomainSplitPolicy::GeometryRatio );
break;
}
switch ( OGR_FldDomain_GetDomainType( domain ) )
{
case OFDT_CODED:
{
QVariantList valueConfig;
const OGRCodedValue *codedValue = OGR_CodedFldDomain_GetEnumeration( domain );
while ( codedValue && codedValue->pszCode )
{
const QString code( codedValue->pszCode );
// if pszValue is null then it indicates we are working with a set of acceptable values which aren't
// coded. In this case we copy the code as the value so that QGIS exposes the domain as a choice of
// the valid code values.
const QString value( codedValue->pszValue ? codedValue->pszValue : codedValue->pszCode );
QVariantMap config;
config[ value ] = code;
valueConfig.append( config );
codedValue++;
}
QVariantMap editorConfig;
editorConfig.insert( QStringLiteral( "map" ), valueConfig );
newField.setEditorWidgetSetup( QgsEditorWidgetSetup( QStringLiteral( "ValueMap" ), editorConfig ) );
break;
}
case OFDT_RANGE:
if ( newField.isNumeric() )
{
// QGIS doesn't support the inclusive option yet!
bool isInclusive = false;
QVariantMap editorConfig;
editorConfig.insert( QStringLiteral( "Step" ), 1 );
editorConfig.insert( QStringLiteral( "Style" ), QStringLiteral( "SpinBox" ) );
editorConfig.insert( QStringLiteral( "AllowNull" ), nullable );
editorConfig.insert( QStringLiteral( "Precision" ), newField.precision() );
OGRFieldType domainFieldType = OGR_FldDomain_GetFieldType( domain );
bool hasMinOrMax = false;
if ( const OGRField *min = OGR_RangeFldDomain_GetMin( domain, &isInclusive ) )
{
const QVariant minValue = QgsOgrUtils::OGRFieldtoVariant( min, domainFieldType );
if ( minValue.isValid() )
{
editorConfig.insert( QStringLiteral( "Min" ), minValue );
hasMinOrMax = true;
}
}
if ( const OGRField *max = OGR_RangeFldDomain_GetMax( domain, &isInclusive ) )
{
const QVariant maxValue = QgsOgrUtils::OGRFieldtoVariant( max, domainFieldType );
if ( maxValue.isValid() )
{
editorConfig.insert( QStringLiteral( "Max" ), maxValue );
hasMinOrMax = true;
}
}
if ( hasMinOrMax )
newField.setEditorWidgetSetup( QgsEditorWidgetSetup( QStringLiteral( "Range" ), editorConfig ) );
}
// GDAL also supports range domains for fields types like date/datetimes, but the QGIS corresponding field
// config doesn't support this yet!
break;
case OFDT_GLOB:
// not supported by QGIS yet
break;
}
}
}
#endif
mAttributeFields.append( newField );
createdFields++;
}
}
void QgsOgrProvider::loadMetadata()
{
// Set default, may be overridden by stored metadata
mLayerMetadata.setCrs( crs() );
if ( mOgrOrigLayer )
{
QRecursiveMutex *mutex = nullptr;
OGRLayerH layer = mOgrOrigLayer->getHandleAndMutex( mutex );