QGIS API Documentation  2.99.0-Master (9fdd060)
qgsrelation.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsrelation.cpp
3  --------------------------------------
4  Date : 29.4.2013
5  Copyright : (C) 2013 Matthias Kuhn
6  Email : matthias at opengis dot ch
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 "qgsrelation.h"
17 
18 #include "qgsapplication.h"
19 #include "qgsfeatureiterator.h"
20 #include "qgslogger.h"
21 #include "qgsproject.h"
22 #include "qgsvectorlayer.h"
23 
24 QgsRelation QgsRelation::createFromXml( const QDomNode &node )
25 {
26  QDomElement elem = node.toElement();
27 
28  if ( elem.tagName() != QLatin1String( "relation" ) )
29  {
30  QgsLogger::warning( QApplication::translate( "QgsRelation", "Cannot create relation. Unexpected tag '%1'" ).arg( elem.tagName() ) );
31  }
32 
33  QgsRelation relation;
34 
35  QString referencingLayerId = elem.attribute( QStringLiteral( "referencingLayer" ) );
36  QString referencedLayerId = elem.attribute( QStringLiteral( "referencedLayer" ) );
37  QString id = elem.attribute( QStringLiteral( "id" ) );
38  QString name = elem.attribute( QStringLiteral( "name" ) );
39 
40  const QMap<QString, QgsMapLayer *> &mapLayers = QgsProject::instance()->mapLayers();
41 
44 
45  if ( !referencingLayer )
46  {
47  QgsLogger::warning( QApplication::translate( "QgsRelation", "Relation defined for layer '%1' which does not exist." ).arg( referencingLayerId ) );
48  }
49  else if ( QgsMapLayer::VectorLayer != referencingLayer->type() )
50  {
51  QgsLogger::warning( QApplication::translate( "QgsRelation", "Relation defined for layer '%1' which is not of type VectorLayer." ).arg( referencingLayerId ) );
52  }
53 
54  if ( !referencedLayer )
55  {
56  QgsLogger::warning( QApplication::translate( "QgsRelation", "Relation defined for layer '%1' which does not exist." ).arg( referencedLayerId ) );
57  }
58  else if ( QgsMapLayer::VectorLayer != referencedLayer->type() )
59  {
60  QgsLogger::warning( QApplication::translate( "QgsRelation", "Relation defined for layer '%1' which is not of type VectorLayer." ).arg( referencedLayerId ) );
61  }
62 
63  relation.mReferencingLayerId = referencingLayerId;
64  relation.mReferencingLayer = qobject_cast<QgsVectorLayer *>( referencingLayer );
65  relation.mReferencedLayerId = referencedLayerId;
66  relation.mReferencedLayer = qobject_cast<QgsVectorLayer *>( referencedLayer );
67  relation.mRelationId = id;
68  relation.mRelationName = name;
69 
70  QDomNodeList references = elem.elementsByTagName( QStringLiteral( "fieldRef" ) );
71  for ( int i = 0; i < references.size(); ++i )
72  {
73  QDomElement refEl = references.at( i ).toElement();
74 
75  QString referencingField = refEl.attribute( QStringLiteral( "referencingField" ) );
76  QString referencedField = refEl.attribute( QStringLiteral( "referencedField" ) );
77 
78  relation.addFieldPair( referencingField, referencedField );
79  }
80 
81  relation.updateRelationStatus();
82 
83  return relation;
84 }
85 
86 void QgsRelation::writeXml( QDomNode &node, QDomDocument &doc ) const
87 {
88  QDomElement elem = doc.createElement( QStringLiteral( "relation" ) );
89  elem.setAttribute( QStringLiteral( "id" ), mRelationId );
90  elem.setAttribute( QStringLiteral( "name" ), mRelationName );
91  elem.setAttribute( QStringLiteral( "referencingLayer" ), mReferencingLayerId );
92  elem.setAttribute( QStringLiteral( "referencedLayer" ), mReferencedLayerId );
93 
94  Q_FOREACH ( const FieldPair &fields, mFieldPairs )
95  {
96  QDomElement referenceElem = doc.createElement( QStringLiteral( "fieldRef" ) );
97  referenceElem.setAttribute( QStringLiteral( "referencingField" ), fields.first );
98  referenceElem.setAttribute( QStringLiteral( "referencedField" ), fields.second );
99  elem.appendChild( referenceElem );
100  }
101 
102  node.appendChild( elem );
103 }
104 
105 void QgsRelation::setId( const QString &id )
106 {
107  mRelationId = id;
108 
109  updateRelationStatus();
110 }
111 
112 void QgsRelation::setName( const QString &name )
113 {
114  mRelationName = name;
115 }
116 
117 void QgsRelation::setReferencingLayer( const QString &id )
118 {
119  mReferencingLayerId = id;
120 
121  updateRelationStatus();
122 }
123 
124 void QgsRelation::setReferencedLayer( const QString &id )
125 {
126  mReferencedLayerId = id;
127 
128  updateRelationStatus();
129 }
130 
131 void QgsRelation::addFieldPair( const QString &referencingField, const QString &referencedField )
132 {
133  mFieldPairs << FieldPair( referencingField, referencedField );
134  updateRelationStatus();
135 }
136 
137 void QgsRelation::addFieldPair( const FieldPair &fieldPair )
138 {
139  mFieldPairs << fieldPair;
140  updateRelationStatus();
141 }
142 
144 {
146 }
147 
149 {
150  QString filter = getRelatedFeaturesFilter( feature );
151  QgsDebugMsg( QString( "Filter conditions: '%1'" ).arg( filter ) );
152 
153  QgsFeatureRequest myRequest;
154  myRequest.setFilterExpression( filter );
155  return myRequest;
156 }
157 
158 QString QgsRelation::getRelatedFeaturesFilter( const QgsFeature &feature ) const
159 {
160  QStringList conditions;
161 
162  Q_FOREACH ( const QgsRelation::FieldPair &fieldPair, mFieldPairs )
163  {
164  QVariant val( feature.attribute( fieldPair.referencedField() ) );
165  conditions << QgsExpression::createFieldEqualityExpression( fieldPair.referencingField(), val );
166  }
167 
168  return conditions.join( QStringLiteral( " AND " ) );
169 }
170 
172 {
173  QStringList conditions;
174 
175  Q_FOREACH ( const QgsRelation::FieldPair &fieldPair, mFieldPairs )
176  {
177  int referencingIdx = referencingLayer()->fields().indexFromName( fieldPair.referencingField() );
178  conditions << QgsExpression::createFieldEqualityExpression( fieldPair.referencedField(), attributes.at( referencingIdx ) );
179  }
180 
181  QgsFeatureRequest myRequest;
182 
183  QgsDebugMsg( QString( "Filter conditions: '%1'" ).arg( conditions.join( " AND " ) ) );
184 
185  myRequest.setFilterExpression( conditions.join( QStringLiteral( " AND " ) ) );
186 
187  return myRequest;
188 }
189 
191 {
192  return getReferencedFeatureRequest( feature.attributes() );
193 }
194 
196 {
197  QgsFeatureRequest request = getReferencedFeatureRequest( feature );
198 
199  QgsFeature f;
200  mReferencedLayer->getFeatures( request ).nextFeature( f );
201  return f;
202 }
203 
204 QString QgsRelation::name() const
205 {
206  return mRelationName;
207 }
208 
209 QString QgsRelation::id() const
210 {
211  return mRelationId;
212 }
213 
215 {
216  mRelationId = QStringLiteral( "%1_%2_%3_%4" )
217  .arg( referencingLayerId(),
218  mFieldPairs.at( 0 ).referencingField(),
220  mFieldPairs.at( 0 ).referencedField() );
221  updateRelationStatus();
222 }
223 
225 {
226  return mReferencingLayerId;
227 }
228 
230 {
231  return mReferencingLayer;
232 }
233 
235 {
236  return mReferencedLayerId;
237 }
238 
240 {
241  return mReferencedLayer;
242 }
243 
244 QList<QgsRelation::FieldPair> QgsRelation::fieldPairs() const
245 {
246  return mFieldPairs;
247 }
248 
250 {
251  QgsAttributeList attrs;
252 
253  Q_FOREACH ( const FieldPair &pair, mFieldPairs )
254  {
255  attrs << mReferencedLayer->fields().lookupField( pair.second );
256  }
257  return attrs;
258 }
259 
261 {
262  QgsAttributeList attrs;
263 
264  Q_FOREACH ( const FieldPair &pair, mFieldPairs )
265  {
266  attrs << mReferencingLayer->fields().lookupField( pair.first );
267  }
268  return attrs;
269 
270 }
271 
272 bool QgsRelation::isValid() const
273 {
274  return mValid;
275 }
276 
278 {
279  return mReferencedLayerId == other.mReferencedLayerId && mReferencingLayerId == other.mReferencingLayerId && mFieldPairs == other.mFieldPairs;
280 }
281 
282 QString QgsRelation::resolveReferencedField( const QString &referencingField ) const
283 {
284  Q_FOREACH ( const FieldPair &pair, mFieldPairs )
285  {
286  if ( pair.first == referencingField )
287  return pair.second;
288  }
289  return QString();
290 }
291 
292 QString QgsRelation::resolveReferencingField( const QString &referencedField ) const
293 {
294  Q_FOREACH ( const FieldPair &pair, mFieldPairs )
295  {
296  if ( pair.second == referencedField )
297  return pair.first;
298  }
299  return QString();
300 }
301 
302 void QgsRelation::updateRelationStatus()
303 {
304  const QMap<QString, QgsMapLayer *> &mapLayers = QgsProject::instance()->mapLayers();
305 
306  mReferencingLayer = qobject_cast<QgsVectorLayer *>( mapLayers[mReferencingLayerId] );
307  mReferencedLayer = qobject_cast<QgsVectorLayer *>( mapLayers[mReferencedLayerId] );
308 
309  mValid = true;
310 
311  if ( mRelationId.isEmpty() )
312  {
313  QgsDebugMsg( "Invalid relation: no ID" );
314  mValid = false;
315  }
316  else
317  {
318  if ( !mReferencedLayer )
319  {
320  QgsDebugMsg( QString( "Invalid relation: referenced layer does not exist. ID: %1" ).arg( mReferencedLayerId ) );
321  mValid = false;
322  }
323  else if ( !mReferencingLayer )
324  {
325  QgsDebugMsg( QString( "Invalid relation: referencing layer does not exist. ID: %2" ).arg( mReferencingLayerId ) );
326  mValid = false;
327  }
328  else
329  {
330  if ( mFieldPairs.count() < 1 )
331  {
332  QgsDebugMsg( "Invalid relation: no pair of field is specified." );
333  mValid = false;
334  }
335 
336  Q_FOREACH ( const FieldPair &fieldPair, mFieldPairs )
337  {
338  if ( -1 == mReferencingLayer->fields().lookupField( fieldPair.first ) )
339  {
340  QgsDebugMsg( QString( "Invalid relation: field %1 does not exist in referencing layer %2" ).arg( fieldPair.first, mReferencingLayer->name() ) );
341  mValid = false;
342  break;
343  }
344  else if ( -1 == mReferencedLayer->fields().lookupField( fieldPair.second ) )
345  {
346  QgsDebugMsg( QString( "Invalid relation: field %1 does not exist in referencedg layer %2" ).arg( fieldPair.second, mReferencedLayer->name() ) );
347  mValid = false;
348  break;
349  }
350  }
351  }
352 
353  }
354 }
int lookupField(const QString &fieldName) const
Look up field&#39;s index from the field name.
Definition: qgsfields.cpp:299
Wrapper for iterator of features from vector data provider or vector layer.
bool isValid() const
Returns the validity of this relation.
Base class for all map layer types.
Definition: qgsmaplayer.h:56
void generateId()
Generate a (project-wide) unique id for this relation.
QgsAttributeList referencingFields() const
Returns a list of attributes used to form the referencing fields (foreign key) on the referencing (ch...
#define QgsDebugMsg(str)
Definition: qgslogger.h:37
static void warning(const QString &msg)
Goes to qWarning.
Definition: qgslogger.cpp:124
void setReferencingLayer(const QString &id)
Set the referencing (child) layer id.
void addFieldPair(const QString &referencingField, const QString &referencedField)
Add a field pairs which is part of this relation The first element of each pair are the field names o...
void setName(const QString &name)
Set a name for this relation.
QMap< QString, QgsMapLayer * > mapLayers() const
Returns a map of all registered layers by layer ID.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:62
QgsMapLayer::LayerType type() const
Returns the type of the layer.
QString id() const
A (project-wide) unique id for this relation.
void setId(const QString &id)
Set an id for this relation.
QgsAttributeList referencedFields() const
Returns a list of attributes used to form the referenced fields (most likely primary key) on the refe...
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
int indexFromName(const QString &fieldName) const
Get the field index from the field name.
Definition: qgsfields.cpp:184
QgsFeatureRequest getReferencedFeatureRequest(const QgsAttributes &attributes) const
Creates a request to return the feature on the referenced (parent) layer which is referenced by the p...
Defines a relation between matching fields of the two involved tables of a relation.
Definition: qgsrelation.h:61
QgsFields fields() const override
Returns the list of fields of this layer.
Q_INVOKABLE QString resolveReferencedField(const QString &referencingField) const
Get the referenced field counterpart given a referencing field.
This class wraps a request for features to a vector layer (or directly its vector data provider)...
QgsVectorLayer * referencedLayer() const
Access the referenced (parent) layer.
static QgsRelation createFromXml(const QDomNode &node)
Creates a relation from an XML structure.
Definition: qgsrelation.cpp:24
QgsFeatureRequest getRelatedFeaturesRequest(const QgsFeature &feature) const
Creates a request to return all the features on the referencing (child) layer which have a foreign ke...
Q_INVOKABLE QString resolveReferencingField(const QString &referencedField) const
Get the referencing field counterpart given a referenced field.
bool hasEqualDefinition(const QgsRelation &other) const
Compares the two QgsRelation, ignoring the name and the ID.
void setReferencedLayer(const QString &id)
Set the referenced (parent) 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...
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const override
Query the layer for features specified in request.
QgsFeatureIterator getRelatedFeatures(const QgsFeature &feature) const
Creates an iterator which returns all the features on the referencing (child) layer which have a fore...
QString referencingLayerId() const
Access the referencing (child) layer&#39;s id This is the layer which has the field(s) which point to ano...
QString getRelatedFeaturesFilter(const QgsFeature &feature) const
Returns a filter expression which returns all the features on the referencing (child) layer which hav...
QgsVectorLayer * referencingLayer() const
Access the referencing (child) layer This is the layer which has the field(s) which point to another ...
static QgsProject * instance()
Returns the QgsProject singleton instance.
Definition: qgsproject.cpp:379
QString referencedField() const
Get the name of the referenced (parent) field.
Definition: qgsrelation.h:74
QString name
Definition: qgsmaplayer.h:60
QList< int > QgsAttributeList
Definition: qgsfield.h:27
bool nextFeature(QgsFeature &f)
QgsFeature getReferencedFeature(const QgsFeature &feature) const
Creates a request to return the feature on the referenced (parent) layer which is referenced by the p...
A vector of attributes.
Definition: qgsattributes.h:58
Represents a vector layer which manages a vector based data sets.
QVariant attribute(const QString &name) const
Lookup attribute value from attribute name.
Definition: qgsfeature.cpp:255
QString referencedLayerId() const
Access the referenced (parent) layer&#39;s id.
QString referencingField() const
Get the name of the referencing (child) field.
Definition: qgsrelation.h:72
void writeXml(QDomNode &node, QDomDocument &doc) const
Writes a relation to an XML structure.
Definition: qgsrelation.cpp:86
QgsAttributes attributes
Definition: qgsfeature.h:72
QString name() const
Returns a human readable name for this relation.