/
qgsmemoryprovider.cpp
812 lines (694 loc) · 25.3 KB
/
qgsmemoryprovider.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
/***************************************************************************
memoryprovider.cpp - provider with storage in memory
------------------
begin : June 2008
copyright : (C) 2008 by Martin Dobias
email : wonder dot sk at gmail dot 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 "qgsmemoryprovider.h"
#include "qgsmemoryfeatureiterator.h"
#include "qgsfeature.h"
#include "qgsfields.h"
#include "qgsgeometry.h"
#include "qgslogger.h"
#include "qgsspatialindex.h"
#include "qgscoordinatereferencesystem.h"
#include <QUrl>
#include <QUrlQuery>
#include <QRegularExpression>
///@cond PRIVATE
#define TEXT_PROVIDER_KEY QStringLiteral( "memory" )
#define TEXT_PROVIDER_DESCRIPTION QStringLiteral( "Memory provider" )
QgsMemoryProvider::QgsMemoryProvider( const QString &uri, const ProviderOptions &options, QgsDataProvider::ReadFlags flags )
: QgsVectorDataProvider( uri, options, flags )
{
// Initialize the geometry with the uri to support old style uri's
// (ie, just 'point', 'line', 'polygon')
QUrl url = QUrl::fromEncoded( uri.toUtf8() );
const QUrlQuery query( url );
QString geometry;
if ( query.hasQueryItem( QStringLiteral( "geometry" ) ) )
{
geometry = query.queryItemValue( QStringLiteral( "geometry" ) );
}
else
{
geometry = url.path();
}
if ( geometry.compare( QLatin1String( "none" ), Qt::CaseInsensitive ) == 0 )
{
mWkbType = QgsWkbTypes::NoGeometry;
}
else
{
mWkbType = QgsWkbTypes::parseType( geometry );
}
if ( query.hasQueryItem( QStringLiteral( "crs" ) ) )
{
QString crsDef = query.queryItemValue( QStringLiteral( "crs" ) );
mCrs.createFromString( crsDef );
}
else
{
// TODO - remove in QGIS 4.0. Layers without an explicit CRS set SHOULD have an invalid CRS. But in order to maintain
// 3.x api, we have to be tolerant/shortsighted(?) here and fallback to EPSG:4326
mCrs = QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:4326" ) );
}
mNextFeatureId = 1;
setNativeTypes( QList< NativeType >()
<< QgsVectorDataProvider::NativeType( tr( "Whole number (integer)" ), QStringLiteral( "integer" ), QVariant::Int, 0, 10 )
// Decimal number from OGR/Shapefile/dbf may come with length up to 32 and
// precision up to length-2 = 30 (default, if width is not specified in dbf is length = 24 precision = 15)
// We know that double (QVariant::Double) has only 15-16 significant numbers,
// but setting that correct limits would disable the use of memory provider with
// data from Shapefiles. In any case, the data are handled as doubles.
// So the limits set here are not correct but enable use of data from Shapefiles.
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "double" ), QVariant::Double, 0, 32, 0, 30 )
<< QgsVectorDataProvider::NativeType( tr( "Text (string)" ), QStringLiteral( "string" ), QVariant::String, 0, 255 )
// date type
<< QgsVectorDataProvider::NativeType( tr( "Date" ), QStringLiteral( "date" ), QVariant::Date, -1, -1, -1, -1 )
<< QgsVectorDataProvider::NativeType( tr( "Time" ), QStringLiteral( "time" ), QVariant::Time, -1, -1, -1, -1 )
<< QgsVectorDataProvider::NativeType( tr( "Date & Time" ), QStringLiteral( "datetime" ), QVariant::DateTime, -1, -1, -1, -1 )
// integer types
<< QgsVectorDataProvider::NativeType( tr( "Whole number (smallint - 16bit)" ), QStringLiteral( "int2" ), QVariant::Int, -1, -1, 0, 0 )
<< QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 32bit)" ), QStringLiteral( "int4" ), QVariant::Int, -1, -1, 0, 0 )
<< QgsVectorDataProvider::NativeType( tr( "Whole number (integer - 64bit)" ), QStringLiteral( "int8" ), QVariant::LongLong, -1, -1, 0, 0 )
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (numeric)" ), QStringLiteral( "numeric" ), QVariant::Double, 1, 20, 0, 20 )
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (decimal)" ), QStringLiteral( "decimal" ), QVariant::Double, 1, 20, 0, 20 )
// floating point
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (real)" ), QStringLiteral( "real" ), QVariant::Double, -1, -1, -1, -1 )
<< QgsVectorDataProvider::NativeType( tr( "Decimal number (double)" ), QStringLiteral( "double precision" ), QVariant::Double, -1, -1, -1, -1 )
// string types
<< QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), QStringLiteral( "text" ), QVariant::String, -1, -1, -1, -1 )
// boolean
<< QgsVectorDataProvider::NativeType( tr( "Boolean" ), QStringLiteral( "boolean" ), QVariant::Bool )
// blob
<< QgsVectorDataProvider::NativeType( tr( "Binary object (BLOB)" ), QStringLiteral( "binary" ), QVariant::ByteArray )
// list types
<< QgsVectorDataProvider::NativeType( tr( "String list" ), QStringLiteral( "stringlist" ), QVariant::StringList, 0, 0, 0, 0, QVariant::String )
<< QgsVectorDataProvider::NativeType( tr( "Integer list" ), QStringLiteral( "integerlist" ), QVariant::List, 0, 0, 0, 0, QVariant::Int )
<< QgsVectorDataProvider::NativeType( tr( "Decimal (real) list" ), QStringLiteral( "doublelist" ), QVariant::List, 0, 0, 0, 0, QVariant::Double )
<< QgsVectorDataProvider::NativeType( tr( "Integer (64bit) list" ), QStringLiteral( "doublelist" ), QVariant::List, 0, 0, 0, 0, QVariant::Double )
);
if ( query.hasQueryItem( QStringLiteral( "field" ) ) )
{
QList<QgsField> attributes;
const thread_local QRegularExpression reFieldDef( "\\:"
"([\\w\\s]+)" // type
"(?:\\((\\-?\\d+)" // length
"(?:\\,(\\-?\\d+))?" // precision
"\\))?(\\[\\])?" // array
"$",
QRegularExpression::CaseInsensitiveOption );
QStringList fields = query.allQueryItemValues( QStringLiteral( "field" ) );
for ( int i = 0; i < fields.size(); i++ )
{
QString name = QUrl::fromPercentEncoding( fields.at( i ).toUtf8() );
QRegularExpressionMatch regularExpressionMatch = reFieldDef.match( name );
// If no match -> use string as type
QVariant::Type type = QVariant::String;
QVariant::Type subType = QVariant::Invalid;
QString typeName( QStringLiteral( "string" ) );
int length = 255;
int precision = 0;
if ( regularExpressionMatch.hasMatch() )
{
name = name.mid( 0, regularExpressionMatch.capturedStart() );
typeName = regularExpressionMatch.captured( 1 ).toLower();
// Search typeName correspondence in native types
bool isNativeType = false;
const QList<QgsVectorDataProvider::NativeType> nativeTypesList( nativeTypes() );
for ( const NativeType &nativeType : nativeTypesList )
{
if ( nativeType.mTypeName.toLower() == typeName )
{
isNativeType = true;
type = nativeType.mType;
subType = nativeType.mSubType;
typeName = nativeType.mTypeName;
break;
}
}
// Not a native type -> check other supported types:
if ( isNativeType == false )
{
if ( typeName == QLatin1String( "int" ) )
{
type = QVariant::Int;
typeName = QStringLiteral( "integer" );
}
else if ( typeName == QLatin1String( "long" ) )
{
type = QVariant::LongLong;
typeName = QStringLiteral( "int8" );
}
else if ( typeName == QLatin1String( "bool" ) )
{
type = QVariant::Bool;
typeName = QStringLiteral( "boolean" );
}
else
{
QgsLogger::warning( tr( "Unsupported typeName '%1'. Will be handled as string." ).arg( typeName ) );
type = QVariant::String;
typeName = QStringLiteral( "string" );
}
}
// Set default length/precision for double/real
if ( typeName == QLatin1String( "real" ) || typeName == QLatin1String( "double" ) )
{
length = 20;
precision = 5;
}
if ( !regularExpressionMatch.captured( 2 ).isEmpty() )
length = regularExpressionMatch.captured( 2 ).toInt();
if ( !regularExpressionMatch.captured( 3 ).isEmpty() )
precision = regularExpressionMatch.captured( 3 ).toInt();
// Array
if ( !regularExpressionMatch.captured( 4 ).isEmpty() )
{
if ( subType == QVariant::Invalid )
subType = type;
if ( type != QVariant::List && type != QVariant::StringList )
type = type == QVariant::String ? QVariant::StringList : QVariant::List;
const QLatin1String listSuffix( "list" );
if ( !typeName.endsWith( listSuffix ) )
typeName += QLatin1String( "list" );
}
}
attributes.append( QgsField( name, type, typeName, length, precision, QString(), subType ) );
}
addAttributes( attributes );
}
if ( query.hasQueryItem( QStringLiteral( "index" ) ) && query.queryItemValue( QStringLiteral( "index" ) ) == QLatin1String( "yes" ) )
{
createSpatialIndex();
}
}
QgsMemoryProvider::~QgsMemoryProvider()
{
delete mSpatialIndex;
}
QString QgsMemoryProvider::providerKey()
{
return TEXT_PROVIDER_KEY;
}
QString QgsMemoryProvider::providerDescription()
{
return TEXT_PROVIDER_DESCRIPTION;
}
QgsMemoryProvider *QgsMemoryProvider::createProvider( const QString &uri,
const ProviderOptions &options,
QgsDataProvider::ReadFlags flags )
{
return new QgsMemoryProvider( uri, options, flags );
}
QgsAbstractFeatureSource *QgsMemoryProvider::featureSource() const
{
return new QgsMemoryFeatureSource( this );
}
QString QgsMemoryProvider::dataSourceUri( bool expandAuthConfig ) const
{
Q_UNUSED( expandAuthConfig )
QUrl uri( QStringLiteral( "memory" ) );
QUrlQuery query;
QString geometry = QgsWkbTypes::displayString( mWkbType );
query.addQueryItem( QStringLiteral( "geometry" ), geometry );
if ( mCrs.isValid() )
{
QString crsDef;
QString authid = mCrs.authid();
if ( authid.startsWith( QLatin1String( "EPSG:" ) ) )
{
crsDef = authid;
}
else
{
crsDef = QStringLiteral( "wkt:%1" ).arg( mCrs.toWkt( QgsCoordinateReferenceSystem::WKT_PREFERRED ) );
}
query.addQueryItem( QStringLiteral( "crs" ), crsDef );
}
if ( mSpatialIndex )
{
query.addQueryItem( QStringLiteral( "index" ), QStringLiteral( "yes" ) );
}
QgsAttributeList attrs = const_cast<QgsMemoryProvider *>( this )->attributeIndexes();
for ( int i = 0; i < attrs.size(); i++ )
{
const QgsField field = mFields.at( attrs[i] );
QString fieldDef = field.name();
QString typeName = field.typeName();
bool isList = false;
if ( field.type() == QVariant::List || field.type() == QVariant::StringList )
{
switch ( field.subType() )
{
case QVariant::Int:
typeName = QStringLiteral( "integer" );
break;
case QVariant::LongLong:
typeName = QStringLiteral( "long" );
break;
case QVariant::Double:
typeName = QStringLiteral( "double" );
break;
case QVariant::String:
typeName = QStringLiteral( "string" );
break;
default:
break;
}
isList = true;
}
fieldDef.append( QStringLiteral( ":%2(%3,%4)%5" ).arg( typeName ).arg( field.length() ).arg( field.precision() ).arg( isList ? QStringLiteral( "[]" ) : QString() ) );
query.addQueryItem( QStringLiteral( "field" ), fieldDef );
}
uri.setQuery( query );
return QString( uri.toEncoded() );
}
QString QgsMemoryProvider::storageType() const
{
return QStringLiteral( "Memory storage" );
}
QgsFeatureIterator QgsMemoryProvider::getFeatures( const QgsFeatureRequest &request ) const
{
return QgsFeatureIterator( new QgsMemoryFeatureIterator( new QgsMemoryFeatureSource( this ), true, request ) );
}
QgsRectangle QgsMemoryProvider::extent() const
{
if ( mExtent.isEmpty() && !mFeatures.isEmpty() )
{
mExtent.setMinimal();
if ( mSubsetString.isEmpty() )
{
// fast way - iterate through all features
const auto constMFeatures = mFeatures;
for ( const QgsFeature &feat : constMFeatures )
{
if ( feat.hasGeometry() )
mExtent.combineExtentWith( feat.geometry().boundingBox() );
}
}
else
{
QgsFeature f;
QgsFeatureIterator fi = getFeatures( QgsFeatureRequest().setNoAttributes() );
while ( fi.nextFeature( f ) )
{
if ( f.hasGeometry() )
mExtent.combineExtentWith( f.geometry().boundingBox() );
}
}
}
else if ( mFeatures.isEmpty() )
{
mExtent.setMinimal();
}
return mExtent;
}
QgsWkbTypes::Type QgsMemoryProvider::wkbType() const
{
return mWkbType;
}
long long QgsMemoryProvider::featureCount() const
{
if ( mSubsetString.isEmpty() )
return mFeatures.count();
// subset string set, no alternative but testing each feature
QgsFeatureIterator fit = QgsFeatureIterator( new QgsMemoryFeatureIterator( new QgsMemoryFeatureSource( this ), true, QgsFeatureRequest().setNoAttributes() ) );
long long count = 0;
QgsFeature feature;
while ( fit.nextFeature( feature ) )
{
count++;
}
return count;
}
QgsFields QgsMemoryProvider::fields() const
{
return mFields;
}
bool QgsMemoryProvider::isValid() const
{
return ( mWkbType != QgsWkbTypes::Unknown );
}
QgsCoordinateReferenceSystem QgsMemoryProvider::crs() const
{
// TODO: make provider projection-aware
return mCrs; // return default CRS
}
void QgsMemoryProvider::handlePostCloneOperations( QgsVectorDataProvider *source )
{
if ( QgsMemoryProvider *other = qobject_cast< QgsMemoryProvider * >( source ) )
{
// these properties aren't copied when cloning a memory provider by uri, so we need to do it manually
mFeatures = other->mFeatures;
mNextFeatureId = other->mNextFeatureId;
mExtent = other->mExtent;
}
}
// returns TRUE if all features were added successfully, or FALSE if any feature could not be added
bool QgsMemoryProvider::addFeatures( QgsFeatureList &flist, Flags flags )
{
bool result = true;
// whether or not to update the layer extent on the fly as we add features
bool updateExtent = mFeatures.isEmpty() || !mExtent.isEmpty();
int fieldCount = mFields.count();
// For rollback
const auto oldExtent { mExtent };
const auto oldNextFeatureId { mNextFeatureId };
QgsFeatureIds addedFids ;
for ( QgsFeatureList::iterator it = flist.begin(); it != flist.end() && result ; ++it )
{
it->setId( mNextFeatureId );
it->setValid( true );
if ( it->attributes().count() < fieldCount )
{
// ensure features have the correct number of attributes by padding
// them with null attributes for missing values
QgsAttributes attributes = it->attributes();
for ( int i = it->attributes().count(); i < mFields.count(); ++i )
{
attributes.append( QVariant( mFields.at( i ).type() ) );
}
it->setAttributes( attributes );
}
else if ( it->attributes().count() > fieldCount )
{
// too many attributes
pushError( tr( "Feature has too many attributes (expecting %1, received %2)" ).arg( fieldCount ).arg( it->attributes().count() ) );
QgsAttributes attributes = it->attributes();
attributes.resize( mFields.count() );
it->setAttributes( attributes );
}
if ( it->hasGeometry() && mWkbType == QgsWkbTypes::NoGeometry )
{
it->clearGeometry();
}
else if ( it->hasGeometry() && QgsWkbTypes::geometryType( it->geometry().wkbType() ) !=
QgsWkbTypes::geometryType( mWkbType ) )
{
pushError( tr( "Could not add feature with geometry type %1 to layer of type %2" ).arg( QgsWkbTypes::displayString( it->geometry().wkbType() ),
QgsWkbTypes::displayString( mWkbType ) ) );
result = false;
continue;
}
// Check attribute conversion
bool conversionError { false };
QString errorMessage;
for ( int i = 0; i < mFields.count(); ++i )
{
const QVariant originalValue = it->attribute( i );
QVariant attrValue = originalValue;
if ( ! attrValue.isNull() && ! mFields.at( i ).convertCompatible( attrValue, &errorMessage ) )
{
// Push first conversion error only
if ( result )
{
pushError( tr( "Could not store attribute \"%1\": %2" )
.arg( mFields.at( i ).name(), errorMessage ) );
}
result = false;
conversionError = true;
continue;
}
else if ( attrValue.type() != originalValue.type() )
{
// convertCompatible has resulted in a data type conversion
it->setAttribute( i, attrValue );
}
}
// Skip the feature if there is at least one conversion error
if ( conversionError )
{
if ( flags.testFlag( QgsFeatureSink::Flag::RollBackOnErrors ) )
{
break;
}
continue;
}
mFeatures.insert( mNextFeatureId, *it );
addedFids.insert( mNextFeatureId );
if ( it->hasGeometry() )
{
if ( updateExtent )
mExtent.combineExtentWith( it->geometry().boundingBox() );
// update spatial index
if ( mSpatialIndex )
mSpatialIndex->addFeature( *it );
}
mNextFeatureId++;
}
// Roll back
if ( ! result && flags.testFlag( QgsFeatureSink::Flag::RollBackOnErrors ) )
{
for ( const QgsFeatureId &addedFid : addedFids )
{
mFeatures.remove( addedFid );
}
mExtent = oldExtent;
mNextFeatureId = oldNextFeatureId;
}
else
{
clearMinMaxCache();
}
return result;
}
bool QgsMemoryProvider::deleteFeatures( const QgsFeatureIds &id )
{
for ( QgsFeatureIds::const_iterator it = id.begin(); it != id.end(); ++it )
{
QgsFeatureMap::iterator fit = mFeatures.find( *it );
// check whether such feature exists
if ( fit == mFeatures.end() )
continue;
// update spatial index
if ( mSpatialIndex )
mSpatialIndex->deleteFeature( *fit );
mFeatures.erase( fit );
}
updateExtents();
clearMinMaxCache();
return true;
}
bool QgsMemoryProvider::addAttributes( const QList<QgsField> &attributes )
{
for ( QgsField field : attributes )
{
if ( !supportedType( field ) )
continue;
// Make sure added attributes typeName correspond to a native type name
bool isNativeTypeName = false;
NativeType nativeTypeCandidate( QString(), QString(), QVariant::Invalid );
const QList<QgsVectorDataProvider::NativeType> nativeTypesList( nativeTypes() );
for ( const NativeType &nativeType : nativeTypesList )
{
if ( nativeType.mTypeName.toLower() == field.typeName().toLower() )
{
isNativeTypeName = true;
break;
}
if ( nativeType.mType == field.type()
&& nativeTypeCandidate.mType == QVariant::Invalid )
nativeTypeCandidate = nativeType;
}
if ( !isNativeTypeName )
{
if ( nativeTypeCandidate.mType == QVariant::Invalid )
{
QgsLogger::warning( "Field type not supported: " + field.typeName() );
continue;
}
field.setTypeName( nativeTypeCandidate.mTypeName );
}
// add new field as a last one
mFields.append( field );
for ( QgsFeatureMap::iterator fit = mFeatures.begin(); fit != mFeatures.end(); ++fit )
{
QgsFeature &f = fit.value();
QgsAttributes attr = f.attributes();
attr.append( QVariant() );
f.setAttributes( attr );
}
}
return true;
}
bool QgsMemoryProvider::renameAttributes( const QgsFieldNameMap &renamedAttributes )
{
QgsFieldNameMap::const_iterator renameIt = renamedAttributes.constBegin();
bool result = true;
for ( ; renameIt != renamedAttributes.constEnd(); ++renameIt )
{
int fieldIndex = renameIt.key();
if ( fieldIndex < 0 || fieldIndex >= mFields.count() )
{
result = false;
continue;
}
if ( mFields.indexFromName( renameIt.value() ) >= 0 )
{
//field name already in use
result = false;
continue;
}
mFields.rename( fieldIndex, renameIt.value() );
}
return result;
}
bool QgsMemoryProvider::deleteAttributes( const QgsAttributeIds &attributes )
{
QList<int> attrIdx = qgis::setToList( attributes );
std::sort( attrIdx.begin(), attrIdx.end(), std::greater<int>() );
// delete attributes one-by-one with decreasing index
for ( QList<int>::const_iterator it = attrIdx.constBegin(); it != attrIdx.constEnd(); ++it )
{
int idx = *it;
mFields.remove( idx );
for ( QgsFeatureMap::iterator fit = mFeatures.begin(); fit != mFeatures.end(); ++fit )
{
QgsFeature &f = fit.value();
QgsAttributes attr = f.attributes();
attr.remove( idx );
f.setAttributes( attr );
}
}
clearMinMaxCache();
return true;
}
bool QgsMemoryProvider::changeAttributeValues( const QgsChangedAttributesMap &attr_map )
{
bool result { true };
QgsChangedAttributesMap rollBackMap;
QString errorMessage;
for ( QgsChangedAttributesMap::const_iterator it = attr_map.begin(); it != attr_map.end(); ++it )
{
QgsFeatureMap::iterator fit = mFeatures.find( it.key() );
if ( fit == mFeatures.end() )
continue;
const QgsAttributeMap &attrs = it.value();
QgsAttributeMap rollBackAttrs;
// Break on errors
for ( QgsAttributeMap::const_iterator it2 = attrs.constBegin(); it2 != attrs.constEnd(); ++it2 )
{
QVariant attrValue = it2.value();
// Check attribute conversion
const bool conversionError { ! attrValue.isNull()
&& ! mFields.at( it2.key() ).convertCompatible( attrValue, &errorMessage ) };
if ( conversionError )
{
// Push first conversion error only
if ( result )
{
pushError( tr( "Could not change attribute %1 having type %2 for feature %4: %3" )
.arg( mFields.at( it2.key() ).name(), it2.value( ).typeName(),
errorMessage ).arg( it.key() ) );
}
result = false;
break;
}
rollBackAttrs.insert( it2.key(), fit->attribute( it2.key() ) );
fit->setAttribute( it2.key(), attrValue );
}
rollBackMap.insert( it.key(), rollBackAttrs );
}
// Roll back
if ( ! result )
{
changeAttributeValues( rollBackMap );
}
else
{
clearMinMaxCache();
}
return result;
}
bool QgsMemoryProvider::changeGeometryValues( const QgsGeometryMap &geometry_map )
{
for ( QgsGeometryMap::const_iterator it = geometry_map.begin(); it != geometry_map.end(); ++it )
{
QgsFeatureMap::iterator fit = mFeatures.find( it.key() );
if ( fit == mFeatures.end() )
continue;
// update spatial index
if ( mSpatialIndex )
mSpatialIndex->deleteFeature( *fit );
fit->setGeometry( it.value() );
// update spatial index
if ( mSpatialIndex )
mSpatialIndex->addFeature( *fit );
}
updateExtents();
return true;
}
QString QgsMemoryProvider::subsetString() const
{
return mSubsetString;
}
bool QgsMemoryProvider::setSubsetString( const QString &theSQL, bool updateFeatureCount )
{
Q_UNUSED( updateFeatureCount )
if ( !theSQL.isEmpty() )
{
QgsExpression tempExpression( theSQL );
if ( tempExpression.hasParserError() )
return false;
}
if ( theSQL == mSubsetString )
return true;
mSubsetString = theSQL;
clearMinMaxCache();
mExtent.setMinimal();
emit dataChanged();
return true;
}
bool QgsMemoryProvider::createSpatialIndex()
{
if ( !mSpatialIndex )
{
mSpatialIndex = new QgsSpatialIndex();
// add existing features to index
for ( QgsFeatureMap::iterator it = mFeatures.begin(); it != mFeatures.end(); ++it )
{
mSpatialIndex->addFeature( *it );
}
}
return true;
}
QgsFeatureSource::SpatialIndexPresence QgsMemoryProvider::hasSpatialIndex() const
{
return mSpatialIndex ? SpatialIndexPresent : SpatialIndexNotPresent;
}
QgsVectorDataProvider::Capabilities QgsMemoryProvider::capabilities() const
{
return AddFeatures | DeleteFeatures | ChangeGeometries |
ChangeAttributeValues | AddAttributes | DeleteAttributes | RenameAttributes | CreateSpatialIndex |
SelectAtId | CircularGeometries | FastTruncate;
}
bool QgsMemoryProvider::truncate()
{
mFeatures.clear();
clearMinMaxCache();
mExtent.setMinimal();
return true;
}
void QgsMemoryProvider::updateExtents()
{
mExtent.setMinimal();
}
QString QgsMemoryProvider::name() const
{
return TEXT_PROVIDER_KEY;
}
QString QgsMemoryProvider::description() const
{
return TEXT_PROVIDER_DESCRIPTION;
}
///@endcond