26 #include <QDomElement>
35 QList<QgsVectorLayer *> lst;
45 static bool _hasCycleDFS(
QgsVectorLayer *n, QHash<QgsVectorLayer *, int> &mark )
47 if ( mark.value( n ) == 1 )
49 if ( mark.value( n ) == 0 )
52 const auto outEdges { _outEdges( n ) };
55 if ( _hasCycleDFS( m, mark ) )
66 QMutexLocker locker( &mMutex );
67 mVectorJoins.push_back( joinInfo );
71 QHash<QgsVectorLayer *, int> markDFS;
72 if ( mLayer && _hasCycleDFS( mLayer, markDFS ) )
75 mVectorJoins.pop_back();
85 connectJoinedLayer( vl );
93 cacheJoinLayer( mVectorJoins.last() );
106 QMutexLocker locker( &mMutex );
107 for (
int i = 0; i < mVectorJoins.size(); ++i )
109 if ( mVectorJoins.at( i ).joinLayerId() == joinLayerId )
116 mVectorJoins.removeAt( i );
139 if ( joinFieldIndex < 0 || joinFieldIndex >= cacheLayer->
fields().
count() )
148 QVector<int> subsetIndices;
156 if ( !cacheLayerAttrs.contains( joinFieldIndex ) )
157 cacheLayerAttrs.append( joinFieldIndex );
166 QString key = attrs.at( joinFieldIndex ).toString();
170 for (
int i = 0; i < subsetIndices.count(); ++i )
171 subsetAttrs[i] = attrs.at( subsetIndices.at( i ) );
177 for (
int i = 0; i < attrs.size(); i++ )
179 if ( i == joinFieldIndex )
182 QString joinInfoPrefix = joinInfo.
prefix();
183 if ( joinInfoPrefix.isNull() )
184 joinInfoPrefix = QString(
"%1_" ).arg( cacheLayer->
name() );
187 const QString joinFieldName = joinInfoPrefix + cacheLayer->
fields().
names().at( i );
195 attributesCache.append( attrs.at( i ) );
212 QVector<int> subsetIndices;
213 for (
int i = 0; i < joinFieldsSubset.count(); ++i )
215 QString joinedFieldName = joinFieldsSubset.at( i );
216 int index = joinLayerFields.
lookupField( joinedFieldName );
219 subsetIndices.append( index );
223 QgsDebugMsg(
"Join layer subset field not found: " + joinedFieldName );
227 return subsetIndices;
234 QList< QgsVectorLayerJoinInfo>::const_iterator joinIt = mVectorJoins.constBegin();
235 for (
int joinIdx = 0; joinIt != mVectorJoins.constEnd(); ++joinIt, ++joinIdx )
244 QString joinFieldName = joinIt->joinFieldName();
246 QSet<QString> subset;
247 if ( joinIt->hasSubset() )
250 subset = qgis::listToSet( subsetNames );
253 if ( joinIt->prefix().isNull() )
255 prefix = joinLayer->
name() +
'_';
259 prefix = joinIt->prefix();
262 for (
int idx = 0; idx < joinFields.
count(); ++idx )
265 if ( joinIt->hasSubset() && !subset.contains( joinFields.
at( idx ).
name() ) )
270 if ( joinIt->hasSubset() || joinFields.
at( idx ).
name() != joinFieldName )
282 QMutexLocker locker( &mMutex );
283 QList< QgsVectorLayerJoinInfo >::iterator joinIt = mVectorJoins.begin();
284 for ( ; joinIt != mVectorJoins.end(); ++joinIt )
286 if ( joinIt->isUsingMemoryCache() && joinIt->cacheDirty )
287 cacheJoinLayer( *joinIt );
294 QDomElement vectorJoinsElem = document.createElement( QStringLiteral(
"vectorjoins" ) );
295 layer_node.appendChild( vectorJoinsElem );
296 QList< QgsVectorLayerJoinInfo >::const_iterator joinIt = mVectorJoins.constBegin();
297 for ( ; joinIt != mVectorJoins.constEnd(); ++joinIt )
302 QDomElement joinElem = document.createElement( QStringLiteral(
"join" ) );
304 joinElem.setAttribute( QStringLiteral(
"targetFieldName" ), joinIt->targetFieldName() );
306 joinElem.setAttribute( QStringLiteral(
"joinLayerId" ), joinIt->joinLayerId() );
307 joinElem.setAttribute( QStringLiteral(
"joinFieldName" ), joinIt->joinFieldName() );
309 joinElem.setAttribute( QStringLiteral(
"memoryCache" ), joinIt->isUsingMemoryCache() );
310 joinElem.setAttribute( QStringLiteral(
"dynamicForm" ), joinIt->isDynamicFormEnabled() );
311 joinElem.setAttribute( QStringLiteral(
"editable" ), joinIt->isEditable() );
312 joinElem.setAttribute( QStringLiteral(
"upsertOnEdit" ), joinIt->hasUpsertOnEdit() );
313 joinElem.setAttribute( QStringLiteral(
"cascadedDelete" ), joinIt->hasCascadedDelete() );
315 if ( joinIt->hasSubset() )
317 QDomElement subsetElem = document.createElement( QStringLiteral(
"joinFieldsSubset" ) );
320 const auto constSubsetNames = subsetNames;
321 for (
const QString &fieldName : constSubsetNames )
323 QDomElement fieldElem = document.createElement( QStringLiteral(
"field" ) );
324 fieldElem.setAttribute( QStringLiteral(
"name" ), fieldName );
325 subsetElem.appendChild( fieldElem );
328 joinElem.appendChild( subsetElem );
331 if ( !joinIt->prefix().isNull() )
333 joinElem.setAttribute( QStringLiteral(
"customPrefix" ), joinIt->prefix() );
334 joinElem.setAttribute( QStringLiteral(
"hasCustomPrefix" ), 1 );
337 vectorJoinsElem.appendChild( joinElem );
343 mVectorJoins.clear();
344 QDomElement vectorJoinsElem = layer_node.firstChildElement( QStringLiteral(
"vectorjoins" ) );
345 if ( !vectorJoinsElem.isNull() )
347 QDomNodeList joinList = vectorJoinsElem.elementsByTagName( QStringLiteral(
"join" ) );
348 for (
int i = 0; i < joinList.size(); ++i )
350 QDomElement infoElem = joinList.at( i ).toElement();
352 info.
setJoinFieldName( infoElem.attribute( QStringLiteral(
"joinFieldName" ) ) );
354 info.
setJoinLayerId( infoElem.attribute( QStringLiteral(
"joinLayerId" ) ) );
358 info.
setEditable( infoElem.attribute( QStringLiteral(
"editable" ) ).toInt() );
359 info.
setUpsertOnEdit( infoElem.attribute( QStringLiteral(
"upsertOnEdit" ) ).toInt() );
360 info.
setCascadedDelete( infoElem.attribute( QStringLiteral(
"cascadedDelete" ) ).toInt() );
362 QDomElement subsetElem = infoElem.firstChildElement( QStringLiteral(
"joinFieldsSubset" ) );
363 if ( !subsetElem.isNull() )
365 QStringList *fieldNames =
new QStringList;
366 QDomNodeList fieldNodes = infoElem.elementsByTagName( QStringLiteral(
"field" ) );
367 fieldNames->reserve( fieldNodes.count() );
368 for (
int i = 0; i < fieldNodes.count(); ++i )
369 *fieldNames << fieldNodes.at( i ).toElement().attribute( QStringLiteral(
"name" ) );
373 if ( infoElem.attribute( QStringLiteral(
"hasCustomPrefix" ) ).toInt() )
374 info.
setPrefix( infoElem.attribute( QStringLiteral(
"customPrefix" ) ) );
385 bool resolved =
false;
386 for ( QgsVectorJoinList::iterator it = mVectorJoins.begin(); it != mVectorJoins.end(); ++it )
388 if ( it->joinLayer() )
391 if (
QgsVectorLayer *joinedLayer = qobject_cast<QgsVectorLayer *>( project->
mapLayer( it->joinLayerId() ) ) )
393 it->setJoinLayer( joinedLayer );
394 connectJoinedLayer( joinedLayer );
408 int joinIndex = mVectorJoins.indexOf( *info );
409 if ( joinIndex == -1 )
412 for (
int i = 0; i < fields.
count(); ++i )
429 int sourceJoinIndex = originIndex / 1000;
430 sourceFieldIndex = originIndex % 1000;
432 if ( sourceJoinIndex < 0 || sourceJoinIndex >= mVectorJoins.count() )
435 return &( mVectorJoins[sourceJoinIndex] );
440 QList<const QgsVectorLayerJoinInfo *> infos;
442 const auto constMVectorJoins = mVectorJoins;
445 if ( infos.contains( &info ) )
448 if ( info.targetFieldName() ==
field.
name() )
449 infos.append( &info );
476 return joinedFeature;
496 return targetedFeature;
502 cloned->mVectorJoins = mVectorJoins;
506 void QgsVectorLayerJoinBuffer::joinedLayerUpdatedFields()
511 QgsVectorLayer *joinedLayer = qobject_cast<QgsVectorLayer *>( sender() );
512 Q_ASSERT( joinedLayer );
515 for ( QgsVectorJoinList::iterator it = mVectorJoins.begin(); it != mVectorJoins.end(); ++it )
517 if ( joinedLayer == it->joinLayer() )
519 it->cachedAttributes.clear();
520 cacheJoinLayer( *it );
527 void QgsVectorLayerJoinBuffer::joinedLayerModified()
529 QgsVectorLayer *joinedLayer = qobject_cast<QgsVectorLayer *>( sender() );
530 Q_ASSERT( joinedLayer );
533 for ( QgsVectorJoinList::iterator it = mVectorJoins.begin(); it != mVectorJoins.end(); ++it )
535 if ( joinedLayer == it->joinLayer() )
537 it->cacheDirty =
true;
542 void QgsVectorLayerJoinBuffer::joinedLayerWillBeDeleted()
544 QgsVectorLayer *joinedLayer = qobject_cast<QgsVectorLayer *>( sender() );
545 Q_ASSERT( joinedLayer );
550 void QgsVectorLayerJoinBuffer::connectJoinedLayer(
QgsVectorLayer *vl )
568 if ( joinLayer && joinLayer->
isEditable() && info.isEditable() && info.hasUpsertOnEdit() )
572 for (
const QgsFeature &feature : std::as_const( features ) )
574 const QgsFeature joinFeature = info.extractJoinedFeature( feature );
578 const QVariant idFieldValue = feature.
attribute( info.targetFieldName() );
591 if ( existingFeature.
isValid() )
593 if ( info.hasSubset() )
596 const auto constSubsetNames = subsetNames;
597 for (
const QString &
field : constSubsetNames )
607 for (
const auto &
field : joinFields )
618 bool notNullFields =
false;
620 for (
const auto &
field : joinFields )
622 if (
field.
name() == info.joinFieldName() )
627 notNullFields =
true;
633 joinFeatures << joinFeature;
676 for (
auto it = newValues.constBegin(); it != newValues.constEnd(); ++it )
678 const int field = it.key();
679 const QVariant newValue = it.value();
682 if ( oldValues.contains(
field ) )
683 oldValue = oldValues[
field];
701 const auto constFids = fids;
707 if ( info.isEditable() && info.hasCascadedDelete() )
711 info.joinLayer()->deleteFeature( joinFeature.
id(), context );
Class allowing to manage the auxiliary storage for a vector layer.
static QString createFieldEqualityExpression(const QString &fieldName, const QVariant &value)
Create an expression allowing to evaluate if a field is equal to a value.
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).
QgsFeatureRequest & setLimit(long long limit)
Set the maximum number of features to request.
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
bool setAttribute(int field, const QVariant &attr)
Sets an attribute's value by field index.
void initAttributes(int fieldCount)
Initialize this feature with the given number of fields.
void setFields(const QgsFields &fields, bool initAttributes=false)
Assigns a field map with the feature to allow attribute access by attribute name.
bool isValid() const
Returns the validity of this feature.
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Encapsulate a field in an attribute table or data source.
void setName(const QString &name)
Set the field name.
Container of fields for a vector layer.
bool append(const QgsField &field, FieldOrigin origin=OriginProvider, int originIndex=-1)
Appends a field. The field must have unique name, otherwise it is rejected (returns false)
int indexFromName(const QString &fieldName) const
Gets the field index from the field name.
int indexOf(const QString &fieldName) const
Gets the field index from the field name.
@ OriginJoin
Field comes from a joined layer (originIndex / 1000 = index of the join, originIndex % 1000 = index w...
int count() const
Returns number of items.
FieldOrigin fieldOrigin(int fieldIdx) const
Returns the field's origin (value from an enumeration).
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
int fieldOriginIndex(int fieldIdx) const
Returns the field's origin index (its meaning is specific to each type of origin).
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
QStringList names() const
Returns a list with field names.
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
void willBeDeleted()
Emitted in the destructor when the layer is about to be deleted, but it is still in a perfectly valid...
void layerModified()
Emitted when modifications has been done on layer.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Q_INVOKABLE QgsMapLayer * mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layer ID.
Manages joined fields for a vector layer.
void resolveReferences(QgsProject *project)
Resolves layer IDs of joined layers using given project's available layers.
QgsFeature targetedFeatureOf(const QgsVectorLayerJoinInfo *info, const QgsFeature &feature) const
Returns the targeted feature corresponding to the joined feature.
bool addJoin(const QgsVectorLayerJoinInfo &joinInfo)
Joins another vector layer to this layer.
void readXml(const QDomNode &layer_node)
Reads joins from project file.
QgsVectorLayerJoinBuffer(QgsVectorLayer *layer=nullptr)
void writeXml(QDomNode &layer_node, QDomDocument &document) const
Saves mVectorJoins to xml under the layer node.
int joinedFieldsOffset(const QgsVectorLayerJoinInfo *info, const QgsFields &fields)
Find out what is the first index of the join within fields.
const QgsVectorJoinList & vectorJoins() const
const QgsVectorLayerJoinInfo * joinForFieldIndex(int index, const QgsFields &fields, int &sourceFieldIndex) const
Finds the vector join for a layer field index.
bool changeAttributeValue(QgsFeatureId fid, int field, const QVariant &newValue, const QVariant &oldValue=QVariant())
Changes attribute value in joined layers.
bool deleteFeatures(const QgsFeatureIds &fids, QgsVectorLayer::DeleteContext *context=nullptr) const
Deletes a list of features from joined layers.
QList< const QgsVectorLayerJoinInfo * > joinsWhereFieldIsId(const QgsField &field) const
Returns joins where the field of a target layer is considered as an id.
bool removeJoin(const QString &joinLayerId)
Removes a vector layer join.
bool containsJoins() const
Quick way to test if there is any join at all.
bool changeAttributeValues(QgsFeatureId fid, const QgsAttributeMap &newValues, const QgsAttributeMap &oldValues=QgsAttributeMap())
Changes attributes' values in joined layers.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features in joined layers.
QgsVectorLayerJoinBuffer * clone() const
Create a copy of the join buffer.
void joinedFieldsChanged()
Emitted whenever the list of joined fields changes (e.g.
void createJoinCaches()
Calls cacheJoinLayer() for all vector joins.
void updateFields(QgsFields &fields)
Updates field map with joined attributes.
static QVector< int > joinSubsetIndices(QgsVectorLayer *joinLayer, const QStringList &joinFieldsSubset)
Returns a vector of indices for use in join based on field names from the layer.
bool deleteFeature(QgsFeatureId fid, QgsVectorLayer::DeleteContext *context=nullptr) const
Deletes a feature from joined layers.
QgsFeature joinedFeatureOf(const QgsVectorLayerJoinInfo *info, const QgsFeature &feature) const
Returns the joined feature corresponding to the feature.
bool isAuxiliaryJoin(const QgsVectorLayerJoinInfo &info) const
Returns true if the join information is about auxiliary layer, false otherwise.
Defines left outer join from our vector layer to some other vector layer.
void setDynamicFormEnabled(bool enabled)
Sets whether the form has to be dynamically updated with joined fields when a feature is being create...
void setUsingMemoryCache(bool enabled)
Sets whether values from the joined layer should be cached in memory to speed up lookups.
void setJoinLayerId(const QString &layerId)
Sets ID of the joined layer. It will need to be overwritten by setJoinLayer() to a reference to real ...
void setEditable(bool enabled)
Sets whether the form of the target layer allows editing joined fields.
bool cacheDirty
True if the cached join attributes need to be updated.
bool isEditable() const
Returns whether joined fields may be edited through the form of the target layer.
void setCascadedDelete(bool enabled)
Sets whether a feature deleted on the target layer has to impact the joined layer by deleting the cor...
void setJoinFieldName(const QString &fieldName)
Sets name of the field of joined layer that will be used for join.
bool isUsingMemoryCache() const
Returns whether values from the joined layer should be cached in memory to speed up lookups.
QString prefix() const
Returns prefix of fields from the joined layer. If nullptr, joined layer's name will be used.
void setTargetFieldName(const QString &fieldName)
Sets name of the field of our layer that will be used for join.
QString joinFieldName() const
Returns name of the field of joined layer that will be used for join.
void setUpsertOnEdit(bool enabled)
Sets whether a feature created on the target layer has to impact the joined layer by creating a new f...
QString targetFieldName() const
Returns name of the field of our layer that will be used for join.
QString joinLayerId() const
ID of the joined layer - may be used to resolve reference to the joined layer.
QgsVectorLayer * joinLayer() const
Returns joined layer (may be nullptr if the reference was set by layer ID and not resolved yet)
void setPrefix(const QString &prefix)
Sets prefix of fields from the joined layer. If nullptr, joined layer's name will be used.
bool hasSubset(bool blocklisted=true) const
Returns true if blocklisted fields is not empty or if a subset of names has been set.
QStringList * joinFieldNamesSubset() const
Returns the subset of fields to be used from joined layer.
QHash< QString, QgsAttributes > cachedAttributes
Cache for joined attributes to provide fast lookup (size is 0 if no memory caching)
void setJoinFieldNamesSubset(QStringList *fieldNamesSubset)
Sets the subset of fields to be used from joined layer.
Represents a vector layer which manages a vector based data sets.
void updateFields()
Will regenerate the fields property of this layer by obtaining all fields from the dataProvider,...
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) FINAL
Adds a list of features to the sink.
QgsAuxiliaryLayer * auxiliaryLayer()
Returns the current auxiliary layer.
bool isEditable() const FINAL
Returns true if the provider is in editing mode.
QgsFeature getFeature(QgsFeatureId fid) const
Queries the layer for the feature with the given id.
bool changeAttributeValue(QgsFeatureId fid, int field, const QVariant &newValue, const QVariant &oldValue=QVariant(), bool skipDefaultValues=false)
Changes an attribute value for a feature (but does not immediately commit the changes).
void updatedFields()
Emitted whenever the fields available from this layer have been changed.
const QList< QgsVectorLayerJoinInfo > vectorJoins() const
QMap< int, QVariant > QgsAttributeMap
QList< QgsFeature > QgsFeatureList
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
QList< int > QgsAttributeList
QList< QgsVectorLayerJoinInfo > QgsVectorJoinList
Context for cascade delete features.