32 #define TEXT_PROVIDER_KEY QStringLiteral( "memory" )
33 #define TEXT_PROVIDER_DESCRIPTION QStringLiteral( "Memory provider" )
35 QgsMemoryProvider::QgsMemoryProvider(
const QString &uri,
const ProviderOptions &options, QgsDataProvider::ReadFlags flags )
40 QUrl url = QUrl::fromEncoded( uri.toUtf8() );
41 const QUrlQuery query( url );
43 if ( query.hasQueryItem( QStringLiteral(
"geometry" ) ) )
45 geometry = query.queryItemValue( QStringLiteral(
"geometry" ) );
49 geometry = url.path();
52 if ( geometry.compare( QLatin1String(
"none" ), Qt::CaseInsensitive ) == 0 )
61 if ( query.hasQueryItem( QStringLiteral(
"crs" ) ) )
63 QString crsDef = query.queryItemValue( QStringLiteral(
"crs" ) );
64 mCrs.createFromString( crsDef );
75 setNativeTypes( QList< NativeType >()
113 if ( query.hasQueryItem( QStringLiteral(
"field" ) ) )
115 QList<QgsField> attributes;
116 QRegExp reFieldDef(
"\\:"
117 "(int|integer|long|int8|real|double|string|date|time|datetime|binary|bool|boolean)"
121 "$", Qt::CaseInsensitive );
122 QStringList fields = query.allQueryItemValues( QStringLiteral(
"field" ) );
123 for (
int i = 0; i < fields.size(); i++ )
125 QString name = QUrl::fromPercentEncoding( fields.at( i ).toUtf8() );
126 QVariant::Type type = QVariant::String;
127 QVariant::Type subType = QVariant::Invalid;
128 QString
typeName( QStringLiteral(
"string" ) );
132 int pos = reFieldDef.indexIn( name );
135 name = name.mid( 0, pos );
136 typeName = reFieldDef.cap( 1 ).toLower();
137 if (
typeName == QLatin1String(
"int" ) ||
typeName == QLatin1String(
"integer" ) )
139 type = QVariant::Int;
140 typeName = QStringLiteral(
"integer" );
143 else if (
typeName == QLatin1String(
"int8" ) ||
typeName == QLatin1String(
"long" ) )
145 type = QVariant::LongLong;
146 typeName = QStringLiteral(
"int8" );
149 else if (
typeName == QLatin1String(
"real" ) ||
typeName == QLatin1String(
"double" ) )
151 type = QVariant::Double;
152 typeName = QStringLiteral(
"double" );
156 else if (
typeName == QLatin1String(
"date" ) )
158 type = QVariant::Date;
159 typeName = QStringLiteral(
"date" );
162 else if (
typeName == QLatin1String(
"time" ) )
164 type = QVariant::Time;
165 typeName = QStringLiteral(
"time" );
168 else if (
typeName == QLatin1String(
"datetime" ) )
170 type = QVariant::DateTime;
171 typeName = QStringLiteral(
"datetime" );
174 else if (
typeName == QLatin1String(
"bool" ) ||
typeName == QLatin1String(
"boolean" ) )
176 type = QVariant::Bool;
177 typeName = QStringLiteral(
"boolean" );
180 else if (
typeName == QLatin1String(
"binary" ) )
182 type = QVariant::ByteArray;
183 typeName = QStringLiteral(
"binary" );
187 if ( !reFieldDef.cap( 2 ).isEmpty() )
189 length = reFieldDef.cap( 2 ).toInt();
191 if ( !reFieldDef.cap( 3 ).isEmpty() )
195 if ( !reFieldDef.cap( 4 ).isEmpty() )
199 type = ( subType == QVariant::String ? QVariant::StringList : QVariant::List );
202 if ( !name.isEmpty() )
205 addAttributes( attributes );
208 if ( query.hasQueryItem( QStringLiteral(
"index" ) ) && query.queryItemValue( QStringLiteral(
"index" ) ) == QLatin1String(
"yes" ) )
210 createSpatialIndex();
215 QgsMemoryProvider::~QgsMemoryProvider()
217 delete mSpatialIndex;
220 QString QgsMemoryProvider::providerKey()
222 return TEXT_PROVIDER_KEY;
225 QString QgsMemoryProvider::providerDescription()
227 return TEXT_PROVIDER_DESCRIPTION;
230 QgsMemoryProvider *QgsMemoryProvider::createProvider(
const QString &uri,
231 const ProviderOptions &options,
232 QgsDataProvider::ReadFlags flags )
234 return new QgsMemoryProvider( uri, options, flags );
239 return new QgsMemoryFeatureSource(
this );
242 QString QgsMemoryProvider::dataSourceUri(
bool expandAuthConfig )
const
244 Q_UNUSED( expandAuthConfig )
246 QUrl uri( QStringLiteral(
"memory" ) );
249 query.addQueryItem( QStringLiteral(
"geometry" ), geometry );
251 if ( mCrs.isValid() )
254 QString authid = mCrs.authid();
255 if ( authid.startsWith( QLatin1String(
"EPSG:" ) ) )
263 query.addQueryItem( QStringLiteral(
"crs" ), crsDef );
267 query.addQueryItem( QStringLiteral(
"index" ), QStringLiteral(
"yes" ) );
271 for (
int i = 0; i < attrs.size(); i++ )
276 query.addQueryItem( QStringLiteral(
"field" ), fieldDef );
278 uri.setQuery( query );
280 return QString( uri.toEncoded() );
284 QString QgsMemoryProvider::storageType()
const
286 return QStringLiteral(
"Memory storage" );
291 return QgsFeatureIterator(
new QgsMemoryFeatureIterator(
new QgsMemoryFeatureSource(
this ),
true, request ) );
297 if ( mExtent.isEmpty() && !mFeatures.isEmpty() )
300 if ( mSubsetString.isEmpty() )
303 const auto constMFeatures = mFeatures;
304 for (
const QgsFeature &feat : constMFeatures )
306 if ( feat.hasGeometry() )
307 mExtent.combineExtentWith( feat.geometry().boundingBox() );
321 else if ( mFeatures.isEmpty() )
323 mExtent.setMinimal();
334 long QgsMemoryProvider::featureCount()
const
336 if ( mSubsetString.isEmpty() )
337 return mFeatures.count();
350 QgsFields QgsMemoryProvider::fields()
const
355 bool QgsMemoryProvider::isValid()
const
368 if ( QgsMemoryProvider *other = qobject_cast< QgsMemoryProvider * >( source ) )
371 mFeatures = other->mFeatures;
372 mNextFeatureId = other->mNextFeatureId;
373 mExtent = other->mExtent;
378 bool QgsMemoryProvider::addFeatures(
QgsFeatureList &flist, Flags flags )
382 bool updateExtent = mFeatures.isEmpty() || !mExtent.isEmpty();
384 int fieldCount = mFields.count();
387 const auto oldExtent { mExtent };
388 const auto oldNextFeatureId { mNextFeatureId };
391 for ( QgsFeatureList::iterator it = flist.begin(); it != flist.end() && result ; ++it )
393 it->setId( mNextFeatureId );
394 it->setValid(
true );
395 if ( it->attributes().count() < fieldCount )
400 for (
int i = it->attributes().count(); i < mFields.count(); ++i )
402 attributes.append( QVariant( mFields.at( i ).type() ) );
404 it->setAttributes( attributes );
406 else if ( it->attributes().count() > fieldCount )
409 pushError( tr(
"Feature has too many attributes (expecting %1, received %2)" ).arg( fieldCount ).arg( it->attributes().count() ) );
411 attributes.resize( mFields.count() );
412 it->setAttributes( attributes );
422 pushError( tr(
"Could not add feature with geometry type %1 to layer of type %2" ).arg(
QgsWkbTypes::displayString( it->geometry().wkbType() ),
429 bool conversionError {
false };
430 QString errorMessage;
431 for (
int i = 0; i < mFields.count(); ++i )
433 const QVariant originalValue = it->attribute( i );
434 QVariant attrValue = originalValue;
435 if ( ! attrValue.isNull() && ! mFields.at( i ).convertCompatible( attrValue, &errorMessage ) )
440 pushError( tr(
"Could not store attribute \"%1\": %2" )
441 .arg( mFields.at( i ).name(), errorMessage ) );
444 conversionError =
true;
447 else if ( attrValue.type() != originalValue.type() )
450 it->setAttribute( i, attrValue );
455 if ( conversionError )
457 if ( flags.testFlag( QgsFeatureSink::Flag::RollBackOnErrors ) )
464 mFeatures.insert( mNextFeatureId, *it );
465 addedFids.insert( mNextFeatureId );
467 if ( it->hasGeometry() )
470 mExtent.combineExtentWith( it->geometry().boundingBox() );
474 mSpatialIndex->addFeature( *it );
481 if ( ! result && flags.testFlag( QgsFeatureSink::Flag::RollBackOnErrors ) )
485 mFeatures.remove( addedFid );
488 mNextFeatureId = oldNextFeatureId;
498 bool QgsMemoryProvider::deleteFeatures(
const QgsFeatureIds &
id )
500 for ( QgsFeatureIds::const_iterator it =
id.begin(); it !=
id.end(); ++it )
502 QgsFeatureMap::iterator fit = mFeatures.find( *it );
505 if ( fit == mFeatures.end() )
510 mSpatialIndex->deleteFeature( *fit );
512 mFeatures.erase( fit );
521 bool QgsMemoryProvider::addAttributes(
const QList<QgsField> &attributes )
523 for ( QList<QgsField>::const_iterator it = attributes.begin(); it != attributes.end(); ++it )
525 switch ( it->type() )
528 case QVariant::Double:
529 case QVariant::String:
532 case QVariant::DateTime:
533 case QVariant::LongLong:
534 case QVariant::StringList:
537 case QVariant::ByteArray:
540 QgsDebugMsg(
"Field type not supported: " + it->typeName() );
544 mFields.append( *it );
546 for ( QgsFeatureMap::iterator fit = mFeatures.begin(); fit != mFeatures.end(); ++fit )
550 attr.append( QVariant() );
557 bool QgsMemoryProvider::renameAttributes(
const QgsFieldNameMap &renamedAttributes )
559 QgsFieldNameMap::const_iterator renameIt = renamedAttributes.constBegin();
561 for ( ; renameIt != renamedAttributes.constEnd(); ++renameIt )
563 int fieldIndex = renameIt.key();
564 if ( fieldIndex < 0 || fieldIndex >= mFields.count() )
569 if ( mFields.indexFromName( renameIt.value() ) >= 0 )
576 mFields.rename( fieldIndex, renameIt.value() );
581 bool QgsMemoryProvider::deleteAttributes(
const QgsAttributeIds &attributes )
583 QList<int> attrIdx = qgis::setToList( attributes );
584 std::sort( attrIdx.begin(), attrIdx.end(), std::greater<int>() );
587 for ( QList<int>::const_iterator it = attrIdx.constBegin(); it != attrIdx.constEnd(); ++it )
590 mFields.remove( idx );
592 for ( QgsFeatureMap::iterator fit = mFeatures.begin(); fit != mFeatures.end(); ++fit )
606 bool result {
true };
610 QString errorMessage;
611 for ( QgsChangedAttributesMap::const_iterator it = attr_map.begin(); it != attr_map.end(); ++it )
613 QgsFeatureMap::iterator fit = mFeatures.find( it.key() );
614 if ( fit == mFeatures.end() )
621 for ( QgsAttributeMap::const_iterator it2 = attrs.constBegin(); it2 != attrs.constEnd(); ++it2 )
623 QVariant attrValue = it2.value();
625 const bool conversionError { ! attrValue.isNull()
626 && ! mFields.at( it2.key() ).convertCompatible( attrValue, &errorMessage ) };
627 if ( conversionError )
632 pushError( tr(
"Could not change attribute %1 having type %2 for feature %4: %3" )
633 .arg( mFields.at( it2.key() ).name(), it2.value( ).typeName(),
634 errorMessage ).arg( it.key() ) );
639 rollBackAttrs.insert( it2.key(), fit->attribute( it2.key() ) );
640 fit->setAttribute( it2.key(), attrValue );
642 rollBackMap.insert( it.key(), rollBackAttrs );
648 changeAttributeValues( rollBackMap );
657 bool QgsMemoryProvider::changeGeometryValues(
const QgsGeometryMap &geometry_map )
659 for ( QgsGeometryMap::const_iterator it = geometry_map.begin(); it != geometry_map.end(); ++it )
661 QgsFeatureMap::iterator fit = mFeatures.find( it.key() );
662 if ( fit == mFeatures.end() )
667 mSpatialIndex->deleteFeature( *fit );
669 fit->setGeometry( it.value() );
673 mSpatialIndex->addFeature( *fit );
681 QString QgsMemoryProvider::subsetString()
const
683 return mSubsetString;
686 bool QgsMemoryProvider::setSubsetString(
const QString &theSQL,
bool updateFeatureCount )
688 Q_UNUSED( updateFeatureCount )
690 if ( !theSQL.isEmpty() )
693 if ( tempExpression.hasParserError() )
697 if ( theSQL == mSubsetString )
700 mSubsetString = theSQL;
702 mExtent.setMinimal();
708 bool QgsMemoryProvider::createSpatialIndex()
710 if ( !mSpatialIndex )
715 for ( QgsFeatureMap::iterator it = mFeatures.begin(); it != mFeatures.end(); ++it )
717 mSpatialIndex->addFeature( *it );
725 return mSpatialIndex ? SpatialIndexPresent : SpatialIndexNotPresent;
728 QgsVectorDataProvider::Capabilities QgsMemoryProvider::capabilities()
const
730 return AddFeatures | DeleteFeatures | ChangeGeometries |
731 ChangeAttributeValues | AddAttributes | DeleteAttributes | RenameAttributes | CreateSpatialIndex |
732 SelectAtId | CircularGeometries | FastTruncate;
735 bool QgsMemoryProvider::truncate()
739 mExtent.setMinimal();
743 void QgsMemoryProvider::updateExtents()
745 mExtent.setMinimal();
748 QString QgsMemoryProvider::name()
const
750 return TEXT_PROVIDER_KEY;
753 QString QgsMemoryProvider::description()
const
755 return TEXT_PROVIDER_DESCRIPTION;
Base class that can be used for any class that is capable of returning features.
This class represents a coordinate reference system (CRS).
@ WKT_PREFERRED
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
Class for 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)
This class wraps a request for features to a vector layer (or directly its vector data provider).
SpatialIndexPresence
Enumeration of spatial index presence states.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Encapsulate a field in an attribute table or data source.
QString typeName() const
Gets the field type.
Container of fields for a vector layer.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
A rectangle specified with double values.
void setMinimal() SIP_HOLDGIL
Set a rectangle so that min corner is at max and max corner is at min.
A spatial index for QgsFeature objects.
This is the base class for vector data providers.
static GeometryType geometryType(Type type) SIP_HOLDGIL
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
static Type parseType(const QString &wktStr)
Attempts to extract the WKB type from a WKT string.
Type
The WKB type describes the number of dimensions a geometry has.
static QString displayString(Type type) SIP_HOLDGIL
Returns a non-translated display string type for a WKB type, e.g., the geometry name used in WKT geom...
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
QSet< int > QgsAttributeIds
const QgsCoordinateReferenceSystem & crs
const QgsAttributeList & attributeIndexes