26#include <QApplication>
29#include "moc_qgsrelation.cpp"
31using namespace Qt::StringLiterals;
34 : d( new QgsRelationPrivate() )
39 : d( new QgsRelationPrivate() )
48 , mContext( other.mContext )
53 : d( std::move( other.d ) )
54 , mContext( std::move( other.mContext ) )
63 mContext = other.mContext;
72 d = std::move( other.d );
73 mContext = std::move( other.mContext );
79 QDomElement elem = node.toElement();
81 if ( elem.tagName() !=
"relation"_L1 )
83 QgsLogger::warning( QApplication::translate(
"QgsRelation",
"Cannot create relation. Unexpected tag '%1'" ).arg( elem.tagName() ) );
90 QString
id = elem.attribute( u
"id"_s );
92 QString
strength = elem.attribute( u
"strength"_s );
94 QMap<QString, QgsMapLayer *> mapLayers = relationContext.
project()->
mapLayers();
118 relation.d->mReferencingLayer = qobject_cast<QgsVectorLayer *>(
referencingLayer );
120 relation.d->mReferencedLayer = qobject_cast<QgsVectorLayer *>(
referencedLayer );
121 relation.d->mRelationId =
id;
122 relation.d->mRelationName =
name;
125 QDomNodeList references = elem.elementsByTagName( u
"fieldRef"_s );
126 for (
int i = 0; i < references.size(); ++i )
128 QDomElement refEl = references.at( i ).toElement();
130 QString referencingField = refEl.attribute( u
"referencingField"_s );
131 QString referencedField = refEl.attribute( u
"referencedField"_s );
133 relation.
addFieldPair( referencingField, referencedField );
143 QDomElement elem = doc.createElement( u
"relation"_s );
144 elem.setAttribute( u
"id"_s, d->mRelationId );
145 elem.setAttribute( u
"name"_s, d->mRelationName );
146 elem.setAttribute( u
"referencingLayer"_s, d->mReferencingLayerId );
147 elem.setAttribute( u
"referencedLayer"_s, d->mReferencedLayerId );
150 for (
const FieldPair &pair : std::as_const( d->mFieldPairs ) )
152 QDomElement referenceElem = doc.createElement( u
"fieldRef"_s );
153 referenceElem.setAttribute( u
"referencingField"_s, pair.first );
154 referenceElem.setAttribute( u
"referencedField"_s, pair.second );
155 elem.appendChild( referenceElem );
158 node.appendChild( elem );
172 d->mRelationName =
name;
185 d->mReferencingLayerId =
id;
193 d->mReferencedLayerId =
id;
201 d->mFieldPairs <<
FieldPair( referencingField, referencedField );
208 d->mFieldPairs << fieldPair;
229 QStringList conditions;
231 if ( ! d->mPolymorphicRelationId.isEmpty() )
241 conditions << u
" FALSE "_s;
245 for (
const FieldPair &pair : std::as_const( d->mFieldPairs ) )
247 QVariant val( feature.
attribute( pair.referencedField() ) );
249 if ( referencingIdx >= 0 )
260 return conditions.join(
" AND "_L1 );
265 QStringList conditions;
267 for (
const FieldPair &pair : std::as_const( d->mFieldPairs ) )
271 if ( referencedIdx >= 0 )
284 QgsDebugMsgLevel( u
"Filter conditions: '%1'"_s.arg( conditions.join(
" AND " ) ), 2 );
301 ( void )d->mReferencedLayer->getFeatures( request ).nextFeature( f );
307 return d->mRelationName;
312 return d->mRelationStrength;
317 return d->mRelationId;
322 if ( !d->mFieldPairs.isEmpty() )
325 d->mRelationId = u
"%1_%2_%3_%4"_s
336 return d->mReferencingLayerId;
341 return d->mReferencingLayer;
346 return d->mReferencedLayerId;
351 return d->mReferencedLayer;
356 return d->mFieldPairs;
362 attrs.reserve( d->mFieldPairs.size() );
363 for (
const FieldPair &pair : std::as_const( d->mFieldPairs ) )
365 attrs << d->mReferencedLayer->fields().lookupField( pair.second );
374 for (
const FieldPair &pair : std::as_const( d->mFieldPairs ) )
376 attrs << d->mReferencingLayer->fields().lookupField( pair.first );
391 return std::find_if( fields.constBegin(), fields.constEnd(), [&](
const auto & fieldIdx )
393 if ( !referencingLayer()->fields().exists( fieldIdx ) )
399 } ) == fields.constEnd();
404 return d->mValid && !d->mReferencingLayer.isNull() && !d->mReferencedLayer.isNull() && d->mReferencingLayer.data()->isValid() && d->mReferencedLayer.data()->isValid();
412 if ( d->mReferencingLayer.isNull() )
414 if ( d->mReferencingLayerId.isEmpty() )
415 return QObject::tr(
"Referencing layer not set" );
417 return QObject::tr(
"Referencing layer %1 does not exist" ).arg( d->mReferencingLayerId );
419 else if ( !d->mReferencingLayer.data()->isValid() )
420 return QObject::tr(
"Referencing layer %1 is not valid" ).arg( d->mReferencingLayerId );
421 else if ( d->mReferencedLayer.isNull() )
423 if ( d->mReferencedLayerId.isEmpty() )
424 return QObject::tr(
"Referenced layer not set" );
426 return QObject::tr(
"Referenced layer %1 does not exist" ).arg( d->mReferencedLayerId );
428 else if ( !d->mReferencedLayer.data()->isValid() )
429 return QObject::tr(
"Referenced layer %1 is not valid" ).arg( d->mReferencedLayerId );
431 return d->mValidationError;
436 return d->mReferencedLayerId == other.d->mReferencedLayerId && d->mReferencingLayerId == other.d->mReferencingLayerId && d->mFieldPairs == other.d->mFieldPairs;
441 for (
const FieldPair &pair : std::as_const( d->mFieldPairs ) )
443 if ( pair.first == referencingField )
451 for (
const FieldPair &pair : std::as_const( d->mFieldPairs ) )
453 if ( pair.second == referencedField )
461 const QMap<QString, QgsMapLayer *> &mapLayers = mContext.project()->mapLayers();
463 d->mReferencingLayer = qobject_cast<QgsVectorLayer *>( mapLayers[d->mReferencingLayerId] );
464 d->mReferencedLayer = qobject_cast<QgsVectorLayer *>( mapLayers[d->mReferencedLayerId] );
468 if ( d->mRelationId.isEmpty() )
471 d->mValidationError = QObject::tr(
"Relationship has no ID" );
476 if ( !d->mReferencedLayer )
478 QgsDebugMsgLevel( u
"Invalid relation: referenced layer does not exist. ID: %1"_s.arg( d->mReferencedLayerId ), 4 );
479 d->mValidationError = QObject::tr(
"Referenced layer %1 does not exist" ).arg( d->mReferencedLayerId );
482 else if ( !d->mReferencingLayer )
484 QgsDebugMsgLevel( u
"Invalid relation: referencing layer does not exist. ID: %2"_s.arg( d->mReferencingLayerId ), 4 );
485 d->mValidationError = QObject::tr(
"Referencing layer %1 does not exist" ).arg( d->mReferencingLayerId );
490 if ( d->mFieldPairs.count() < 1 )
492 QgsDebugMsgLevel( u
"Invalid relation: no pair of field is specified."_s, 4 );
493 d->mValidationError = QObject::tr(
"No fields specified for relationship" );
497 for (
const FieldPair &pair : std::as_const( d->mFieldPairs ) )
499 if ( -1 == d->mReferencingLayer->fields().lookupField( pair.first ) )
501 QgsDebugError( u
"Invalid relation: field %1 does not exist in referencing layer %2"_s.arg( pair.first, d->mReferencingLayer->name() ) );
502 d->mValidationError = QObject::tr(
"Field %1 does not exist in referencing layer %2" ).arg( pair.first, d->mReferencingLayer->name() );
506 else if ( -1 == d->mReferencedLayer->fields().lookupField( pair.second ) )
508 QgsDebugError( u
"Invalid relation: field %1 does not exist in referenced layer %2"_s.arg( pair.second, d->mReferencedLayer->name() ) );
509 d->mValidationError = QObject::tr(
"Field %1 does not exist in referenced layer %2" ).arg( pair.second, d->mReferencedLayer->name() );
527 return d->mPolymorphicRelationId;
532 if ( ! mContext.project() || ! mContext.project()->relationManager() )
535 return mContext.project()->relationManager()->polymorphicRelation( d->mPolymorphicRelationId );
540 if ( d->mPolymorphicRelationId.isNull() )
548 switch ( cardinality )
551 return QObject::tr(
"One-to-one" );
553 return QObject::tr(
"One-to-many" );
555 return QObject::tr(
"Many-to-one" );
557 return QObject::tr(
"Many-to-many" );
567 return QObject::tr(
"Association" );
569 return QObject::tr(
"Composition" );
RelationshipStrength
Relationship strength.
@ Composition
Fix relation, related elements are part of the parent and a parent copy will copy any children or del...
@ Association
Loose relation, related elements are not part of the parent and a parent copy will not copy any child...
RelationshipType
Relationship types.
@ Generated
A generated relation is a child of a polymorphic relation.
@ Normal
A normal relation.
RelationshipCardinality
Relationship cardinality.
@ ManyToMany
Many to many relationship.
@ ManyToOne
Many to one relationship.
@ OneToOne
One to one relationship.
@ OneToMany
One to many relationship.
static QString createFieldEqualityExpression(const QString &fieldName, const QVariant &value, QMetaType::Type fieldType=QMetaType::Type::UnknownType)
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.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
@ ConstraintNotNull
Field may not be null.
Encapsulate a field in an attribute table or data source.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
static void warning(const QString &msg)
Goes to qWarning.
Base class for all map layer types.
A relation where the referenced (parent) layer is calculated based on fields from the referencing (ch...
QString layerRepresentation(const QgsVectorLayer *layer) const
Returns layer representation as evaluated string.
QString referencedLayerField
virtual QString translate(const QString &context, const QString &sourceText, const char *disambiguation=nullptr, int n=-1) const =0
Translates a string using the Qt QTranslator mechanism.
QMap< QString, QgsMapLayer * > mapLayers(const bool validOnly=false) const
Returns a map of all registered layers by layer ID.
A container for the context for various read/write operations on objects.
const QgsProjectTranslator * projectTranslator() const
Returns the project translator.
const QgsProject * project() const
Gets the associated project.
Defines a relation between matching fields of the two involved tables of a relation.
QString referencingField() const
Gets the name of the referencing (child) field.
QString referencedField() const
Gets the name of the referenced (parent) field.
QgsFeatureRequest getReferencedFeatureRequest(const QgsAttributes &attributes) const
Creates a request to return the feature on the referenced (parent) layer which is referenced by the p...
QList< int > referencedFields
static QString cardinalityToDisplayString(Qgis::RelationshipCardinality cardinality)
Returns a user-friendly translated string representing a relationship cardinality.
Q_INVOKABLE QgsFeature getReferencedFeature(const QgsFeature &feature) const
Creates a request to return the feature on the referenced (parent) layer which is referenced by the p...
void setId(const QString &id)
Set an id for this relation.
QgsFeatureIterator getRelatedFeatures(const QgsFeature &feature) const
Creates an iterator which returns all the features on the referencing (child) layer which have a fore...
QgsRelation()
Default constructor.
void setReferencedLayer(const QString &id)
Set the referenced (parent) layer id.
void setPolymorphicRelationId(const QString &polymorphicRelationId)
Sets the parent polymorphic relation id.
QgsRelation & operator=(const QgsRelation &other)
Copies a relation.
void generateId()
Generate a (project-wide) unique id for this relation.
Q_INVOKABLE QString resolveReferencingField(const QString &referencedField) const
Gets the referencing field counterpart given a referenced field.
bool hasEqualDefinition(const QgsRelation &other) const
Compares the two QgsRelation, ignoring the name and the ID.
static QgsRelation createFromXml(const QDomNode &node, QgsReadWriteContext &context, const QgsRelationContext &relationContext=QgsRelationContext())
Creates a relation from an XML structure.
QString validationError() const
Returns a user-friendly explanation for why the relationship is invalid.
Q_INVOKABLE QString resolveReferencedField(const QString &referencingField) const
Gets the referenced field counterpart given a referencing field.
QString polymorphicRelationId
QgsVectorLayer * referencedLayer
Qgis::RelationshipType type() const
Returns the type of the relation.
void setStrength(Qgis::RelationshipStrength strength)
Set a strength for this relation.
static QString strengthToDisplayString(Qgis::RelationshipStrength strength)
Returns a user-friendly translated string representing a relationship strength.
Q_INVOKABLE void addFieldPair(const QString &referencingField, const QString &referencedField)
Add a field pair which is part of this relation The first element of each pair are the field names of...
void setReferencingLayer(const QString &id)
Set the referencing (child) layer id.
QList< QgsRelation::FieldPair > fieldPairs() const
Returns the field pairs which form this relation The first element of each pair are the field names o...
QString referencedLayerId
QgsPolymorphicRelation polymorphicRelation
Qgis::RelationshipStrength strength
QgsVectorLayer * referencingLayer
QString referencingLayerId
bool referencingFieldsAllowNull() const
Returns true if none of the referencing fields has a NOT NULL constraint.
void setName(const QString &name)
Set a name for this relation.
void writeXml(QDomNode &node, QDomDocument &doc) const
Writes a relation to an XML structure.
Q_INVOKABLE QString getRelatedFeaturesFilter(const QgsFeature &feature) const
Returns a filter expression which returns all the features on the referencing (child) layer which hav...
void updateRelationStatus()
Updates the validity status of this relation.
QList< int > referencingFields
QgsFeatureRequest getRelatedFeaturesRequest(const QgsFeature &feature) const
Creates a request to return all the features on the referencing (child) layer which have a foreign ke...
Represents a vector layer which manages a vector based dataset.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const final
Queries the layer for features specified in request.
T qgsEnumKeyToValue(const QString &key, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given key of an enum.
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
#define BUILTIN_UNREACHABLE
QList< int > QgsAttributeList
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)