QGIS API Documentation 4.3.0-Master (0cef2469b72)
Loading...
Searching...
No Matches
qgsmemoryprovider.cpp
Go to the documentation of this file.
1/***************************************************************************
2 memoryprovider.cpp - provider with storage in memory
3 ------------------
4 begin : June 2008
5 copyright : (C) 2008 by Martin Dobias
6 email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgsmemoryprovider.h"
17
18#include "qgsapplication.h"
20#include "qgsfeature.h"
21#include "qgsfields.h"
22#include "qgsgeometry.h"
23#include "qgslogger.h"
25#include "qgsspatialindex.h"
26#include "qgsvariantutils.h"
27
28#include <QIcon>
29#include <QRegularExpression>
30#include <QString>
31#include <QUrl>
32#include <QUrlQuery>
33
34#include "moc_qgsmemoryprovider.cpp"
35
36using namespace Qt::StringLiterals;
37
39
40#define TEXT_PROVIDER_KEY u"memory"_s
41#define TEXT_PROVIDER_DESCRIPTION u"Memory provider"_s
42
43QgsMemoryProvider::QgsMemoryProvider( const QString &uri, const ProviderOptions &options, Qgis::DataProviderReadFlags flags )
44 : QgsVectorDataProvider( uri, options, flags )
45{
46 // Initialize the geometry with the uri to support old style uri's
47 // (ie, just 'point', 'line', 'polygon')
48 const QUrl url = QUrl::fromEncoded( uri.toUtf8() );
49 const QUrlQuery query( url );
50 QString geometry;
51 if ( query.hasQueryItem( u"geometry"_s ) )
52 {
53 geometry = query.queryItemValue( u"geometry"_s );
54 }
55 else
56 {
57 geometry = url.path();
58 }
59
60 if ( geometry.compare( "none"_L1, Qt::CaseInsensitive ) == 0 )
61 {
63 }
64 else
65 {
66 mWkbType = QgsWkbTypes::parseType( geometry );
67 }
68
69 if ( query.hasQueryItem( u"crs"_s ) )
70 {
71 const QString crsDef = query.queryItemValue( u"crs"_s );
72 mCrs.createFromString( crsDef );
73 }
74 else
75 {
76 // TODO - remove in QGIS 5.0. Layers without an explicit CRS set SHOULD have an invalid CRS. But in order to maintain
77 // 3.x api, we have to be tolerant/shortsighted(?) here and fallback to EPSG:4326
78 mCrs = QgsCoordinateReferenceSystem( u"EPSG:4326"_s );
79 }
80
81 elevationProperties()->setContainsElevationData( QgsWkbTypes::hasZ( mWkbType ) );
82
83 mNextFeatureId = 1;
84
85 setNativeTypes(
86 QList< NativeType >()
87 << QgsVectorDataProvider::NativeType( tr( "Whole Number (integer)" ), u"integer"_s, QMetaType::Type::Int, 0, 10 )
88 // Decimal number from OGR/Shapefile/dbf may come with length up to 32 and
89 // precision up to length-2 = 30 (default, if width is not specified in dbf is length = 24 precision = 15)
90 // We know that double (QVariant::Double) has only 15-16 significant numbers,
91 // but setting that correct limits would disable the use of memory provider with
92 // data from Shapefiles. In any case, the data are handled as doubles.
93 // So the limits set here are not correct but enable use of data from Shapefiles.
94 << QgsVectorDataProvider::NativeType( tr( "Decimal Number (real)" ), u"double"_s, QMetaType::Type::Double, 0, 32, 0, 30 )
95 << QgsVectorDataProvider::NativeType( tr( "Text (string)" ), u"string"_s, QMetaType::Type::QString, 0, 255 )
96
97 // date type
98 << QgsVectorDataProvider::NativeType( QgsVariantUtils::typeToDisplayString( QMetaType::Type::QDate ), u"date"_s, QMetaType::Type::QDate, -1, -1, -1, -1 )
99 << QgsVectorDataProvider::NativeType( QgsVariantUtils::typeToDisplayString( QMetaType::Type::QTime ), u"time"_s, QMetaType::Type::QTime, -1, -1, -1, -1 )
100 << QgsVectorDataProvider::NativeType( QgsVariantUtils::typeToDisplayString( QMetaType::Type::QDateTime ), u"datetime"_s, QMetaType::Type::QDateTime, -1, -1, -1, -1 )
101
102 // integer types
103 << QgsVectorDataProvider::NativeType( tr( "Whole Number (smallint - 16bit)" ), u"int2"_s, QMetaType::Type::Int, -1, -1, 0, 0 )
104 << QgsVectorDataProvider::NativeType( tr( "Whole Number (integer - 32bit)" ), u"int4"_s, QMetaType::Type::Int, -1, -1, 0, 0 )
105 << QgsVectorDataProvider::NativeType( tr( "Whole Number (integer - 64bit)" ), u"int8"_s, QMetaType::Type::LongLong, -1, -1, 0, 0 )
106 << QgsVectorDataProvider::NativeType( tr( "Decimal Number (numeric)" ), u"numeric"_s, QMetaType::Type::Double, 1, 20, 0, 20 )
107 << QgsVectorDataProvider::NativeType( tr( "Decimal Number (decimal)" ), u"decimal"_s, QMetaType::Type::Double, 1, 20, 0, 20 )
108
109 // floating point
110 << QgsVectorDataProvider::NativeType( tr( "Decimal Number (real)" ), u"real"_s, QMetaType::Type::Double, -1, -1, -1, -1 )
111 << QgsVectorDataProvider::NativeType( tr( "Decimal Number (double)" ), u"double precision"_s, QMetaType::Type::Double, -1, -1, -1, -1 )
112
113 // string types
114 << QgsVectorDataProvider::NativeType( tr( "Text, unlimited length (text)" ), u"text"_s, QMetaType::Type::QString, -1, -1, -1, -1 )
115
116 // boolean
117 << QgsVectorDataProvider::NativeType( QgsVariantUtils::typeToDisplayString( QMetaType::Type::Bool ), u"boolean"_s, QMetaType::Type::Bool )
118
119 // blob
120 << QgsVectorDataProvider::NativeType( QgsVariantUtils::typeToDisplayString( QMetaType::Type::QByteArray ), u"binary"_s, QMetaType::Type::QByteArray )
121
122 // list types
123 << QgsVectorDataProvider::NativeType( QgsVariantUtils::typeToDisplayString( QMetaType::Type::QStringList ), u"stringlist"_s, QMetaType::Type::QStringList, 0, 0, 0, 0, QMetaType::Type::QString )
125 NativeType( QgsVariantUtils::typeToDisplayString( QMetaType::Type::QVariantList, QMetaType::Type::Int ), u"integerlist"_s, QMetaType::Type::QVariantList, 0, 0, 0, 0, QMetaType::Type::Int )
127 NativeType( QgsVariantUtils::typeToDisplayString( QMetaType::Type::QVariantList, QMetaType::Type::Double ), u"doublelist"_s, QMetaType::Type::QVariantList, 0, 0, 0, 0, QMetaType::Type::Double )
129 NativeType( QgsVariantUtils::typeToDisplayString( QMetaType::Type::QVariantList, QMetaType::Type::LongLong ), u"integer64list"_s, QMetaType::Type::QVariantList, 0, 0, 0, 0, QMetaType::Type::LongLong )
130
131 // complex types
132 << QgsVectorDataProvider::NativeType( QgsVariantUtils::typeToDisplayString( QMetaType::Type::QVariantMap ), u"map"_s, QMetaType::Type::QVariantMap, -1, -1, -1, -1 )
133 << QgsVectorDataProvider::NativeType( tr( "Geometry" ), u"geometry"_s, QMetaType::Type::User )
134 );
135
136 if ( query.hasQueryItem( u"field"_s ) )
137 {
138 QList<QgsField> attributes;
139 const thread_local QRegularExpression reFieldDef(
140 "\\:"
141 "([\\w\\s]+)" // type
142 "(?:\\((\\-?\\d+)" // length
143 "(?:\\,(\\-?\\d+))?" // precision
144 "\\))?(\\[\\])?" // array
145 "$",
146 QRegularExpression::CaseInsensitiveOption
147 );
148 const QStringList fields = query.allQueryItemValues( u"field"_s );
149 for ( int i = 0; i < fields.size(); i++ )
150 {
151 QString name = QUrl::fromPercentEncoding( fields.at( i ).toUtf8() );
152 const QRegularExpressionMatch regularExpressionMatch = reFieldDef.match( name );
153
154 // If no match -> use string as type
155 QMetaType::Type type = QMetaType::Type::QString;
156 QMetaType::Type subType = QMetaType::Type::UnknownType;
157 QString typeName( u"string"_s );
158 int length = 255;
159 int precision = 0;
160
161 if ( regularExpressionMatch.hasMatch() )
162 {
163 name = name.mid( 0, regularExpressionMatch.capturedStart() );
164 typeName = regularExpressionMatch.captured( 1 ).toLower();
165
166 // Search typeName correspondence in native types
167 bool isNativeType = false;
168 const QList<QgsVectorDataProvider::NativeType> nativeTypesList( nativeTypes() );
169 for ( const NativeType &nativeType : nativeTypesList )
170 {
171 if ( nativeType.mTypeName.toLower() == typeName )
172 {
173 isNativeType = true;
174 type = nativeType.mType;
175 subType = nativeType.mSubType;
176 typeName = nativeType.mTypeName;
177 break;
178 }
179 }
180
181 // Not a native type -> check other supported types:
182 if ( isNativeType == false )
183 {
184 if ( typeName == "int"_L1 )
185 {
186 type = QMetaType::Type::Int;
187 typeName = u"integer"_s;
188 }
189 else if ( typeName == "long"_L1 )
190 {
191 type = QMetaType::Type::LongLong;
192 typeName = u"int8"_s;
193 }
194 else if ( typeName == "bool"_L1 )
195 {
196 type = QMetaType::Type::Bool;
197 typeName = u"boolean"_s;
198 }
199 else
200 {
201 QgsLogger::warning( tr( "Unsupported typeName '%1'. Will be handled as string." ).arg( typeName ) );
202 type = QMetaType::Type::QString;
203 typeName = u"string"_s;
204 }
205 }
206
207 // Set default length/precision for double/real
208 if ( typeName == "real"_L1 || typeName == "double"_L1 )
209 {
210 length = 20;
211 precision = 5;
212 }
213
214 if ( !regularExpressionMatch.captured( 2 ).isEmpty() )
215 length = regularExpressionMatch.captured( 2 ).toInt();
216
217 if ( !regularExpressionMatch.captured( 3 ).isEmpty() )
218 precision = regularExpressionMatch.captured( 3 ).toInt();
219
220 // Array
221 if ( !regularExpressionMatch.captured( 4 ).isEmpty() )
222 {
223 if ( subType == QMetaType::Type::UnknownType )
224 subType = type;
225
226 if ( type != QMetaType::Type::QVariantList && type != QMetaType::Type::QStringList )
227 type = type == QMetaType::Type::QString ? QMetaType::Type::QStringList : QMetaType::Type::QVariantList;
228
229 const QLatin1String listSuffix( "list" );
230 if ( !typeName.endsWith( listSuffix ) )
231 typeName += "list"_L1;
232 }
233 }
234
235 attributes.append( QgsField( name, type, typeName, length, precision, QString(), subType ) );
236 }
237 addAttributes( attributes );
238 }
239
240 if ( query.hasQueryItem( u"index"_s ) && query.queryItemValue( u"index"_s ) == "yes"_L1 )
241 {
242 createSpatialIndex();
243 }
244}
245
246QgsMemoryProvider::~QgsMemoryProvider()
247{}
248
249QString QgsMemoryProvider::providerKey()
250{
251 return TEXT_PROVIDER_KEY;
252}
253
254QString QgsMemoryProvider::providerDescription()
255{
256 return TEXT_PROVIDER_DESCRIPTION;
257}
258
259QgsAbstractFeatureSource *QgsMemoryProvider::featureSource() const
260{
261 return new QgsMemoryFeatureSource( this );
262}
263
264QString QgsMemoryProvider::dataSourceUri( bool expandAuthConfig ) const
265{
266 Q_UNUSED( expandAuthConfig )
267
268 QUrl uri( u"memory"_s );
269 QUrlQuery query;
270 const QString geometry = QgsWkbTypes::displayString( mWkbType );
271 query.addQueryItem( u"geometry"_s, geometry );
272
273 if ( mCrs.isValid() )
274 {
275 QString crsDef;
276 const QString authid = mCrs.authid();
277 if ( authid.startsWith( "EPSG:"_L1 ) )
278 {
279 crsDef = authid;
280 }
281 else
282 {
283 crsDef = u"wkt:%1"_s.arg( mCrs.toWkt( Qgis::CrsWktVariant::Preferred ) );
284 }
285 query.addQueryItem( u"crs"_s, crsDef );
286 }
287 if ( mSpatialIndex )
288 {
289 query.addQueryItem( u"index"_s, u"yes"_s );
290 }
291
292 QgsAttributeList attrs = const_cast<QgsMemoryProvider *>( this )->attributeIndexes();
293 for ( int i = 0; i < attrs.size(); i++ )
294 {
295 const QgsField field = mFields.at( attrs[i] );
296 QString fieldDef = field.name();
297
298 QString typeName = field.typeName();
299 bool isList = false;
300 if ( field.type() == QMetaType::Type::QVariantList || field.type() == QMetaType::Type::QStringList )
301 {
302 switch ( field.subType() )
303 {
304 case QMetaType::Type::Int:
305 typeName = u"integer"_s;
306 break;
307
308 case QMetaType::Type::LongLong:
309 typeName = u"long"_s;
310 break;
311
312 case QMetaType::Type::Double:
313 typeName = u"double"_s;
314 break;
315
316 case QMetaType::Type::QString:
317 typeName = u"string"_s;
318 break;
319
320 default:
321 break;
322 }
323 isList = true;
324 }
325
326 fieldDef.append( u":%2(%3,%4)%5"_s.arg( typeName ).arg( field.length() ).arg( field.precision() ).arg( isList ? u"[]"_s : QString() ) );
327 query.addQueryItem( u"field"_s, fieldDef );
328 }
329 uri.setQuery( query );
330
331 return QString( uri.toEncoded() );
332}
333
334QString QgsMemoryProvider::storageType() const
335{
336 return u"Memory storage"_s;
337}
338
339QgsFeatureIterator QgsMemoryProvider::getFeatures( const QgsFeatureRequest &request ) const
340{
341 return QgsFeatureIterator( new QgsMemoryFeatureIterator( new QgsMemoryFeatureSource( this ), true, request ) );
342}
343
344
345QgsRectangle QgsMemoryProvider::extent() const
346{
347 return extent3D().toRectangle();
348}
349
350QgsBox3D QgsMemoryProvider::extent3D() const
351{
352 if ( mExtent3D.isEmpty() && !mFeatures.isEmpty() )
353 {
354 mExtent3D.setNull();
355 if ( mSubsetString.isEmpty() )
356 {
357 // fast way - iterate through all features
358 const auto constMFeatures = mFeatures;
359 for ( const QgsFeature &feat : constMFeatures )
360 {
361 if ( feat.hasGeometry() )
362 mExtent3D.combineWith( feat.geometry().boundingBox3D() );
363 }
364 }
365 else
366 {
367 QgsFeature feat;
368 QgsFeatureIterator featIt = getFeatures( QgsFeatureRequest().setNoAttributes() );
369 while ( featIt.nextFeature( feat ) )
370 {
371 if ( feat.hasGeometry() )
372 mExtent3D.combineWith( feat.geometry().boundingBox3D() );
373 }
374 }
375 }
376 else if ( mFeatures.isEmpty() )
377 {
378 mExtent3D.setNull();
379 }
380
381 return mExtent3D;
382}
383
384Qgis::WkbType QgsMemoryProvider::wkbType() const
385{
386 return mWkbType;
387}
388
389long long QgsMemoryProvider::featureCount() const
390{
391 if ( mSubsetString.isEmpty() )
392 return mFeatures.count();
393
394 // subset string set, no alternative but testing each feature
395 QgsFeatureIterator fit = QgsFeatureIterator( new QgsMemoryFeatureIterator( new QgsMemoryFeatureSource( this ), true, QgsFeatureRequest().setNoAttributes() ) );
396 long long count = 0;
397 QgsFeature feature;
398 while ( fit.nextFeature( feature ) )
399 {
400 count++;
401 }
402 return count;
403}
404
405QgsFields QgsMemoryProvider::fields() const
406{
407 return mFields;
408}
409
410bool QgsMemoryProvider::isValid() const
411{
412 return ( mWkbType != Qgis::WkbType::Unknown );
413}
414
415QgsCoordinateReferenceSystem QgsMemoryProvider::crs() const
416{
417 // TODO: make provider projection-aware
418 return mCrs; // return default CRS
419}
420
421void QgsMemoryProvider::handlePostCloneOperations( QgsVectorDataProvider *source )
422{
423 if ( QgsMemoryProvider *other = qobject_cast< QgsMemoryProvider * >( source ) )
424 {
425 // these properties aren't copied when cloning a memory provider by uri, so we need to do it manually
426 mFeatures = other->mFeatures;
427 mNextFeatureId = other->mNextFeatureId;
428 mExtent3D = other->mExtent3D;
429 if ( other->mSpatialIndex )
430 {
431 mSpatialIndex = std::make_unique<QgsSpatialIndex>( *other->mSpatialIndex.get() );
432 // immediately detach spatial index, so we aren't sharing the mutex with the original layer, which would cause temporary hangs during render
433 mSpatialIndex->detach();
434 }
435 }
436}
437
438// returns TRUE if all features were added successfully, or FALSE if any feature could not be added
439bool QgsMemoryProvider::addFeatures( QgsFeatureList &flist, Flags flags )
440{
441 bool result = true;
442 // whether or not to update the layer extent on the fly as we add features
443 const bool updateExtent = mFeatures.isEmpty() || !mExtent3D.isEmpty();
444
445 const int fieldCount = mFields.count();
446
447 // For rollback
448 const auto oldExtent3D { mExtent3D };
449 const auto oldNextFeatureId { mNextFeatureId };
450 QgsFeatureIds addedFids;
451
452 for ( QgsFeatureList::iterator it = flist.begin(); it != flist.end() && result; ++it )
453 {
454 it->setId( mNextFeatureId );
455 it->setValid( true );
456 const int attributeCount = it->attributeCount();
457 if ( attributeCount < fieldCount )
458 {
459 // ensure features have the correct number of attributes by padding
460 // them with null attributes for missing values
461 QgsAttributes attributes = it->attributes();
462 for ( int i = attributeCount; i < mFields.count(); ++i )
463 {
464 attributes.append( QgsVariantUtils::createNullVariant( mFields.at( i ).type() ) );
465 }
466 it->setAttributes( attributes );
467 }
468 else if ( attributeCount > fieldCount )
469 {
470 // too many attributes
471 pushError( tr( "Feature has too many attributes (expecting %1, received %2)" ).arg( fieldCount ).arg( attributeCount ) );
472 QgsAttributes attributes = it->attributes();
473 attributes.resize( mFields.count() );
474 it->setAttributes( attributes );
475 }
476
477 if ( it->hasGeometry() && mWkbType == Qgis::WkbType::NoGeometry )
478 {
479 it->clearGeometry();
480 }
481 else if ( it->hasGeometry() && QgsWkbTypes::geometryType( it->geometry().wkbType() ) != QgsWkbTypes::geometryType( mWkbType ) )
482 {
483 pushError( tr( "Could not add feature with geometry type %1 to layer of type %2" ).arg( QgsWkbTypes::displayString( it->geometry().wkbType() ), QgsWkbTypes::displayString( mWkbType ) ) );
484 result = false;
485 continue;
486 }
487
488 // Check attribute conversion
489 bool conversionError { false };
490 QString errorMessage;
491 for ( int i = 0; i < mFields.count(); ++i )
492 {
493 const QVariant originalValue = it->attribute( i );
494 QVariant attrValue = originalValue;
495 if ( !QgsVariantUtils::isNull( attrValue ) && !mFields.at( i ).convertCompatible( attrValue, &errorMessage ) )
496 {
497 // Push first conversion error only
498 if ( result )
499 {
500 pushError( tr( "Could not store attribute \"%1\": %2" ).arg( mFields.at( i ).name(), errorMessage ) );
501 }
502 result = false;
503 conversionError = true;
504 continue;
505 }
506 else if ( attrValue.userType() != originalValue.userType() )
507 {
508 // convertCompatible has resulted in a data type conversion
509 it->setAttribute( i, attrValue );
510 }
511 }
512
513 // Skip the feature if there is at least one conversion error
514 if ( conversionError )
515 {
516 if ( flags.testFlag( QgsFeatureSink::Flag::RollBackOnErrors ) )
517 {
518 break;
519 }
520 continue;
521 }
522
523 mFeatures.insert( mNextFeatureId, *it );
524 addedFids.insert( mNextFeatureId );
525
526 if ( it->hasGeometry() )
527 {
528 if ( updateExtent )
529 {
530 mExtent3D.combineWith( it->geometry().boundingBox3D() );
531 }
532
533 // update spatial index
534 if ( mSpatialIndex )
535 mSpatialIndex->addFeature( *it );
536 }
537
538 mNextFeatureId++;
539 }
540
541 // Roll back
542 if ( !result && flags.testFlag( QgsFeatureSink::Flag::RollBackOnErrors ) )
543 {
544 for ( const QgsFeatureId &addedFid : addedFids )
545 {
546 mFeatures.remove( addedFid );
547 }
548 mExtent3D = oldExtent3D;
549 mNextFeatureId = oldNextFeatureId;
550 }
551 else
552 {
553 clearMinMaxCache();
554 }
555
556 return result;
557}
558
559bool QgsMemoryProvider::deleteFeatures( const QgsFeatureIds &id )
560{
561 for ( QgsFeatureIds::const_iterator it = id.begin(); it != id.end(); ++it )
562 {
563 const QgsFeatureMap::iterator fit = mFeatures.find( *it );
564
565 // check whether such feature exists
566 if ( fit == mFeatures.end() )
567 continue;
568
569 // update spatial index
570 if ( mSpatialIndex )
571 mSpatialIndex->deleteFeature( *fit );
572
573 mFeatures.erase( fit );
574 }
575
576 updateExtents();
577 clearMinMaxCache();
578
579 return true;
580}
581
582bool QgsMemoryProvider::addAttributes( const QList<QgsField> &attributes )
583{
584 bool fieldWasAdded { false };
585 for ( QgsField field : attributes )
586 {
587 if ( !supportedType( field ) )
588 continue;
589
590 // Make sure added attributes typeName correspond to a native type name
591 bool isNativeTypeName = false;
592 NativeType nativeTypeCandidate( QString(), QString(), QMetaType::Type::UnknownType );
593 const QList<QgsVectorDataProvider::NativeType> nativeTypesList( nativeTypes() );
594 for ( const NativeType &nativeType : nativeTypesList )
595 {
596 if ( nativeType.mTypeName.toLower() == field.typeName().toLower() )
597 {
598 isNativeTypeName = true;
599 break;
600 }
601
602 if ( nativeType.mType == field.type() && nativeTypeCandidate.mType == QMetaType::Type::UnknownType )
603 nativeTypeCandidate = nativeType;
604 }
605 if ( !isNativeTypeName )
606 {
607 if ( nativeTypeCandidate.mType == QMetaType::Type::UnknownType )
608 {
609 QgsLogger::warning( "Field type not supported: " + field.typeName() );
610 continue;
611 }
612
613 field.setTypeName( nativeTypeCandidate.mTypeName );
614 }
615
616 // add new field as a last one
617 mFields.append( field );
618 fieldWasAdded = true;
619
620 for ( QgsFeatureMap::iterator fit = mFeatures.begin(); fit != mFeatures.end(); ++fit )
621 {
622 QgsFeature &f = fit.value();
623 QgsAttributes attr = f.attributes();
624 attr.append( QVariant() );
625 f.setAttributes( attr );
626 }
627 }
628 return fieldWasAdded;
629}
630
631bool QgsMemoryProvider::renameAttributes( const QgsFieldNameMap &renamedAttributes )
632{
633 QgsFieldNameMap::const_iterator renameIt = renamedAttributes.constBegin();
634 bool result = true;
635 for ( ; renameIt != renamedAttributes.constEnd(); ++renameIt )
636 {
637 const int fieldIndex = renameIt.key();
638 if ( fieldIndex < 0 || fieldIndex >= mFields.count() )
639 {
640 result = false;
641 continue;
642 }
643 if ( mFields.indexFromName( renameIt.value() ) >= 0 )
644 {
645 //field name already in use
646 result = false;
647 continue;
648 }
649
650 mFields.rename( fieldIndex, renameIt.value() );
651 }
652 return result;
653}
654
655bool QgsMemoryProvider::deleteAttributes( const QgsAttributeIds &attributes )
656{
657 QList<int> attrIdx( attributes.begin(), attributes.end() );
658 std::sort( attrIdx.begin(), attrIdx.end(), std::greater<int>() );
659
660 // delete attributes one-by-one with decreasing index
661 for ( QList<int>::const_iterator it = attrIdx.constBegin(); it != attrIdx.constEnd(); ++it )
662 {
663 const int idx = *it;
664 mFields.remove( idx );
665
666 for ( QgsFeatureMap::iterator fit = mFeatures.begin(); fit != mFeatures.end(); ++fit )
667 {
668 QgsFeature &f = fit.value();
669 QgsAttributes attr = f.attributes();
670 attr.remove( idx );
671 f.setAttributes( attr );
672 }
673 }
674 clearMinMaxCache();
675 return true;
676}
677
678bool QgsMemoryProvider::changeAttributeValues( const QgsChangedAttributesMap &attr_map )
679{
680 bool result { true };
681
682 QgsChangedAttributesMap rollBackMap;
683
684 QString errorMessage;
685 for ( QgsChangedAttributesMap::const_iterator it = attr_map.begin(); it != attr_map.end(); ++it )
686 {
687 const QgsFeatureMap::iterator fit = mFeatures.find( it.key() );
688 if ( fit == mFeatures.end() )
689 continue;
690
691 const QgsAttributeMap &attrs = it.value();
692 QgsAttributeMap rollBackAttrs;
693
694 // Break on errors
695 for ( QgsAttributeMap::const_iterator it2 = attrs.constBegin(); it2 != attrs.constEnd(); ++it2 )
696 {
697 const int fieldIndex = it2.key();
698 if ( fieldIndex < 0 || fieldIndex >= mFields.count() )
699 continue;
700
701 QVariant attrValue = it2.value();
703 continue;
704
705 // Check attribute conversion
706 const bool conversionError { !QgsVariantUtils::isNull( attrValue ) && !mFields.at( it2.key() ).convertCompatible( attrValue, &errorMessage ) };
707 if ( conversionError )
708 {
709 // Push first conversion error only
710 if ( result )
711 {
712 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() ) );
713 }
714 result = false;
715 break;
716 }
717 rollBackAttrs.insert( it2.key(), fit->attribute( it2.key() ) );
718 fit->setAttribute( it2.key(), attrValue );
719 }
720 rollBackMap.insert( it.key(), rollBackAttrs );
721 }
722
723 // Roll back
724 if ( !result )
725 {
726 changeAttributeValues( rollBackMap );
727 }
728 else
729 {
730 clearMinMaxCache();
731 }
732 return result;
733}
734
735bool QgsMemoryProvider::changeGeometryValues( const QgsGeometryMap &geometry_map )
736{
737 for ( QgsGeometryMap::const_iterator it = geometry_map.begin(); it != geometry_map.end(); ++it )
738 {
739 const QgsFeatureMap::iterator fit = mFeatures.find( it.key() );
740 if ( fit == mFeatures.end() )
741 continue;
742
743 // update spatial index
744 if ( mSpatialIndex )
745 mSpatialIndex->deleteFeature( *fit );
746
747 fit->setGeometry( it.value() );
748
749 // update spatial index
750 if ( mSpatialIndex )
751 mSpatialIndex->addFeature( *fit );
752 }
753
754 updateExtents();
755
756 return true;
757}
758
759QString QgsMemoryProvider::subsetString() const
760{
761 return mSubsetString;
762}
763
764bool QgsMemoryProvider::setSubsetString( const QString &theSQL, bool updateFeatureCount )
765{
766 Q_UNUSED( updateFeatureCount )
767
768 if ( !theSQL.isEmpty() )
769 {
770 const QgsExpression tempExpression( theSQL );
771 if ( tempExpression.hasParserError() )
772 return false;
773 }
774
775 if ( theSQL == mSubsetString )
776 return true;
777
778 mSubsetString = theSQL;
779 clearMinMaxCache();
780 mExtent3D.setNull();
781
782 emit dataChanged();
783 return true;
784}
785
786bool QgsMemoryProvider::supportsSubsetString() const
787{
788 return true;
789}
790
791QString QgsMemoryProvider::subsetStringDialect() const
792{
793 return tr( "QGIS expression" );
794}
795
796QString QgsMemoryProvider::subsetStringHelpUrl() const
797{
798 // unfortunately we can't access QgsHelp here, that's a GUI class!
799 return QString();
800}
801
802bool QgsMemoryProvider::createSpatialIndex()
803{
804 if ( !mSpatialIndex )
805 {
806 mSpatialIndex = std::make_unique<QgsSpatialIndex>();
807
808 // add existing features to index
809 for ( QgsFeatureMap::iterator it = mFeatures.begin(); it != mFeatures.end(); ++it )
810 {
811 mSpatialIndex->addFeature( *it );
812 }
813 }
814 return true;
815}
816
817Qgis::SpatialIndexPresence QgsMemoryProvider::hasSpatialIndex() const
818{
820}
821
822Qgis::VectorProviderCapabilities QgsMemoryProvider::capabilities() const
823{
833 };
834 if ( mWkbType != Qgis::WkbType::NoGeometry )
835 {
837 }
838 return caps;
839}
840
841bool QgsMemoryProvider::truncate()
842{
843 mFeatures.clear();
844 clearMinMaxCache();
845 mExtent3D.setNull();
846 return true;
847}
848
849void QgsMemoryProvider::updateExtents()
850{
851 mExtent3D.setNull();
852}
853
854QString QgsMemoryProvider::name() const
855{
856 return TEXT_PROVIDER_KEY;
857}
858
859QString QgsMemoryProvider::description() const
860{
861 return TEXT_PROVIDER_DESCRIPTION;
862}
863
864
865QgsMemoryProviderMetadata::QgsMemoryProviderMetadata()
866 : QgsProviderMetadata( QgsMemoryProvider::providerKey(), QgsMemoryProvider::providerDescription() )
867{}
868
869QIcon QgsMemoryProviderMetadata::icon() const
870{
871 return QgsApplication::getThemeIcon( u"mIconMemory.svg"_s );
872}
873
874QgsDataProvider *QgsMemoryProviderMetadata::createProvider( const QString &uri, const QgsDataProvider::ProviderOptions &options, Qgis::DataProviderReadFlags flags )
875{
876 return new QgsMemoryProvider( uri, options, flags );
877}
878
879QList<Qgis::LayerType> QgsMemoryProviderMetadata::supportedLayerTypes() const
880{
881 return { Qgis::LayerType::Vector };
882}
883
884#undef TEXT_PROVIDER_KEY
885#undef TEXT_PROVIDER_DESCRIPTION
886
@ SelectAtId
Fast access to features using their ID.
Definition qgis.h:553
@ FastTruncate
Supports fast truncation of the layer (removing all features).
Definition qgis.h:563
@ AddFeatures
Allows adding features.
Definition qgis.h:547
@ CircularGeometries
Supports circular geometry types (circularstring, compoundcurve, curvepolygon).
Definition qgis.h:560
@ ChangeGeometries
Allows modifications of geometries.
Definition qgis.h:554
@ AddAttributes
Allows addition of new attributes (fields).
Definition qgis.h:550
@ CreateSpatialIndex
Allows creation of spatial index.
Definition qgis.h:552
@ RenameAttributes
Supports renaming attributes (fields).
Definition qgis.h:562
@ DeleteFeatures
Allows deletion of features.
Definition qgis.h:548
@ DeleteAttributes
Allows deletion of attributes (fields).
Definition qgis.h:551
@ ChangeAttributeValues
Allows modification of attribute values.
Definition qgis.h:549
SpatialIndexPresence
Enumeration of spatial index presence states.
Definition qgis.h:619
@ NotPresent
No spatial index exists for the source.
Definition qgis.h:621
@ Present
A valid spatial index exists for the source.
Definition qgis.h:622
QFlags< DataProviderReadFlag > DataProviderReadFlags
Flags which control data provider construction.
Definition qgis.h:532
QFlags< VectorProviderCapability > VectorProviderCapabilities
Vector data provider capabilities.
Definition qgis.h:584
@ Vector
Vector layer.
Definition qgis.h:207
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:314
@ NoGeometry
No geometry.
Definition qgis.h:332
@ Unknown
Unknown.
Definition qgis.h:315
@ Preferred
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
Definition qgis.h:2631
Base class that can be used for any class that is capable of returning features.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
A vector of attributes.
A 3-dimensional box composed of x, y, z coordinates.
Definition qgsbox3d.h:45
Represents a coordinate reference system (CRS).
Abstract base class for spatial data provider implementations.
Handles parsing and evaluation of expressions (formerly called "search strings").
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
@ RollBackOnErrors
Roll back the whole transaction if a single add feature operation fails.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsAttributes attributes
Definition qgsfeature.h:64
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:66
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
QMetaType::Type type
Definition qgsfield.h:63
QString typeName() const
Gets the field type.
Definition qgsfield.cpp:158
QString name
Definition qgsfield.h:65
int precision
Definition qgsfield.h:62
int length
Definition qgsfield.h:61
QMetaType::Type subType() const
If the field is a collection, gets its element's type.
Definition qgsfield.cpp:153
void setTypeName(const QString &typeName)
Set the field type.
Definition qgsfield.cpp:249
Container of fields for a vector layer.
Definition qgsfields.h:45
QgsBox3D boundingBox3D() const
Returns the 3D bounding box of the geometry.
static void warning(const QString &msg)
Goes to qWarning.
Holds data provider key, description, and associated shared library file or function pointer informat...
A rectangle specified with double values.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
static QString typeToDisplayString(QMetaType::Type type, QMetaType::Type subType=QMetaType::Type::UnknownType)
Returns a user-friendly translated string representing a QVariant type.
static QVariant createNullVariant(QMetaType::Type metaType)
Helper method to properly create a null QVariant from a metaType Returns the created QVariant.
static bool isUnsetAttributeValue(const QVariant &variant)
Check if the variant is a QgsUnsetAttributeValue.
Base class for vector data providers.
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
static Qgis::WkbType parseType(const QString &wktStr)
Attempts to extract the WKB type from a WKT string.
static Q_INVOKABLE QString displayString(Qgis::WkbType type)
Returns a non-translated display string type for a WKB type, e.g., the geometry name used in WKT geom...
static Q_INVOKABLE bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
QMap< int, QString > QgsFieldNameMap
QMap< int, QVariant > QgsAttributeMap
QMap< QgsFeatureId, QgsGeometry > QgsGeometryMap
QMap< QgsFeatureId, QgsAttributeMap > QgsChangedAttributesMap
QList< QgsFeature > QgsFeatureList
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
QList< int > QgsAttributeList
Definition qgsfield.h:30
QSet< int > QgsAttributeIds
Setting options for creating vector data providers.