QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
qgsalgorithmjoinbyattribute.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmjoinbyattribute.cpp
3 ---------------------
4 begin : April 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
21
23
24QString QgsJoinByAttributeAlgorithm::name() const
25{
26 return QStringLiteral( "joinattributestable" );
27}
28
29QString QgsJoinByAttributeAlgorithm::displayName() const
30{
31 return QObject::tr( "Join attributes by field value" );
32}
33
34QStringList QgsJoinByAttributeAlgorithm::tags() const
35{
36 return QObject::tr( "join,connect,attributes,values,fields,tables" ).split( ',' );
37}
38
39QString QgsJoinByAttributeAlgorithm::group() const
40{
41 return QObject::tr( "Vector general" );
42}
43
44QString QgsJoinByAttributeAlgorithm::groupId() const
45{
46 return QStringLiteral( "vectorgeneral" );
47}
48
49void QgsJoinByAttributeAlgorithm::initAlgorithm( const QVariantMap & )
50{
51 QStringList methods;
52 methods << QObject::tr( "Create separate feature for each matching feature (one-to-many)" )
53 << QObject::tr( "Take attributes of the first matching feature only (one-to-one)" );
54
55 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
56 addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELD" ), QObject::tr( "Table field" ), QVariant(), QStringLiteral( "INPUT" ) ) );
57
58 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT_2" ), QObject::tr( "Input layer 2" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
59 addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELD_2" ), QObject::tr( "Table field 2" ), QVariant(), QStringLiteral( "INPUT_2" ) ) );
60
61 addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELDS_TO_COPY" ), QObject::tr( "Layer 2 fields to copy (leave empty to copy all fields)" ), QVariant(), QStringLiteral( "INPUT_2" ), Qgis::ProcessingFieldParameterDataType::Any, true, true ) );
62
63 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "METHOD" ), QObject::tr( "Join type" ), methods, false, 1 ) );
64 addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "DISCARD_NONMATCHING" ), QObject::tr( "Discard records which could not be joined" ), false ) );
65
66 addParameter( new QgsProcessingParameterString( QStringLiteral( "PREFIX" ), QObject::tr( "Joined field prefix" ), QVariant(), false, true ) );
67
68 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Joined layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true, true ) );
69
70 auto nonMatchingSink = std::make_unique<QgsProcessingParameterFeatureSink>(
71 QStringLiteral( "NON_MATCHING" ), QObject::tr( "Unjoinable features from first layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true, false
72 );
73 // TODO GUI doesn't support advanced outputs yet
74 //nonMatchingSink->setFlags(nonMatchingSink->flags() | Qgis::ProcessingParameterFlag::Advanced );
75 addParameter( nonMatchingSink.release() );
76
77 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "JOINED_COUNT" ), QObject::tr( "Number of joined features from input table" ) ) );
78 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "UNJOINABLE_COUNT" ), QObject::tr( "Number of unjoinable features from input table" ) ) );
79}
80
81QString QgsJoinByAttributeAlgorithm::shortHelpString() const
82{
83 return QObject::tr( "This algorithm takes an input vector layer and creates a new vector layer that is an extended version of the "
84 "input one, with additional attributes in its attribute table.\n\n"
85 "The additional attributes and their values are taken from a second vector layer. An attribute is selected "
86 "in each of them to define the join criteria." );
87}
88
89QString QgsJoinByAttributeAlgorithm::shortDescription() const
90{
91 return QObject::tr( "Creates a vector layer that is an extended version of the input one, "
92 "with additional attributes taken from a second vector layer." );
93}
94
95Qgis::ProcessingAlgorithmDocumentationFlags QgsJoinByAttributeAlgorithm::documentationFlags() const
96{
98}
99
100QgsJoinByAttributeAlgorithm *QgsJoinByAttributeAlgorithm::createInstance() const
101{
102 return new QgsJoinByAttributeAlgorithm();
103}
104
105QVariantMap QgsJoinByAttributeAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
106{
107 const int joinMethod = parameterAsEnum( parameters, QStringLiteral( "METHOD" ), context );
108 const bool discardNonMatching = parameterAsBoolean( parameters, QStringLiteral( "DISCARD_NONMATCHING" ), context );
109
110 std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
111 if ( !input )
112 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
113
114 std::unique_ptr<QgsProcessingFeatureSource> input2( parameterAsSource( parameters, QStringLiteral( "INPUT_2" ), context ) );
115 if ( !input2 )
116 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT_2" ) ) );
117
118 const QString prefix = parameterAsString( parameters, QStringLiteral( "PREFIX" ), context );
119
120 const QString field1Name = parameterAsString( parameters, QStringLiteral( "FIELD" ), context );
121 const QString field2Name = parameterAsString( parameters, QStringLiteral( "FIELD_2" ), context );
122 const QStringList fieldsToCopy = parameterAsStrings( parameters, QStringLiteral( "FIELDS_TO_COPY" ), context );
123
124 const int joinField1Index = input->fields().lookupField( field1Name );
125 if ( joinField1Index < 0 )
126 throw QgsProcessingException( QObject::tr( "Invalid join field from layer 1: “%1” does not exist" ).arg( field1Name ) );
127
128 const int joinField2Index = input2->fields().lookupField( field2Name );
129 if ( joinField2Index < 0 )
130 throw QgsProcessingException( QObject::tr( "Invalid join field from layer 2: “%1” does not exist" ).arg( field2Name ) );
131
132 QgsFields outFields2;
133 QgsAttributeList fields2Indices;
134 if ( fieldsToCopy.empty() )
135 {
136 outFields2 = input2->fields();
137 fields2Indices.reserve( outFields2.count() );
138 for ( int i = 0; i < outFields2.count(); ++i )
139 {
140 fields2Indices << i;
141 }
142 }
143 else
144 {
145 fields2Indices.reserve( fieldsToCopy.count() );
146 for ( const QString &field : fieldsToCopy )
147 {
148 const int index = input2->fields().lookupField( field );
149 if ( index >= 0 )
150 {
151 fields2Indices << index;
152 outFields2.append( input2->fields().at( index ) );
153 }
154 }
155 }
156
157 if ( !prefix.isEmpty() )
158 {
159 for ( int i = 0; i < outFields2.count(); ++i )
160 {
161 outFields2.rename( i, prefix + outFields2[i].name() );
162 }
163 }
164
165 QgsAttributeList fields2Fetch = fields2Indices;
166 fields2Fetch << joinField2Index;
167
168 const QgsFields outFields = QgsProcessingUtils::combineFields( input->fields(), outFields2 );
169
170 QString dest;
171 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outFields, input->wkbType(), input->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
172 if ( parameters.value( QStringLiteral( "OUTPUT" ) ).isValid() && !sink )
173 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
174
175 QString destNonMatching1;
176 std::unique_ptr<QgsFeatureSink> sinkNonMatching1( parameterAsSink( parameters, QStringLiteral( "NON_MATCHING" ), context, destNonMatching1, input->fields(), input->wkbType(), input->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
177 if ( parameters.value( QStringLiteral( "NON_MATCHING" ) ).isValid() && !sinkNonMatching1 )
178 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "NON_MATCHING" ) ) );
179
180 // cache attributes of input2
181 QMultiHash<QVariant, QgsAttributes> input2AttributeCache;
182 QgsFeatureIterator features = input2->getFeatures( QgsFeatureRequest().setFlags( Qgis::FeatureRequestFlag::NoGeometry ).setSubsetOfAttributes( fields2Fetch ), Qgis::ProcessingFeatureSourceFlag::SkipGeometryValidityChecks );
183 double step = input2->featureCount() > 0 ? 50.0 / input2->featureCount() : 1;
184 int i = 0;
185 QgsFeature feat;
186 while ( features.nextFeature( feat ) )
187 {
188 i++;
189 if ( feedback->isCanceled() )
190 {
191 break;
192 }
193
194 feedback->setProgress( i * step );
195
196 if ( joinMethod == 1 && input2AttributeCache.contains( feat.attribute( joinField2Index ) ) )
197 continue;
198
199 // only keep selected attributes
200 QgsAttributes attributes;
201 for ( int field2Index : fields2Indices )
202 {
203 attributes << feat.attribute( field2Index );
204 }
205
206 input2AttributeCache.insert( feat.attribute( joinField2Index ), attributes );
207 }
208
209 // Create output vector layer with additional attribute
210 step = input->featureCount() > 0 ? 50.0 / input->featureCount() : 1;
212 i = 0;
213 long long joinedCount = 0;
214 long long unjoinedCount = 0;
215 while ( features.nextFeature( feat ) )
216 {
217 i++;
218 if ( feedback->isCanceled() )
219 {
220 break;
221 }
222
223 feedback->setProgress( 50 + i * step );
224
225 if ( input2AttributeCache.count( feat.attribute( joinField1Index ) ) > 0 )
226 {
227 joinedCount++;
228 if ( sink )
229 {
230 const QgsAttributes attrs = feat.attributes();
231
232 QList<QgsAttributes> attributes = input2AttributeCache.values( feat.attribute( joinField1Index ) );
233 QList<QgsAttributes>::iterator attrsIt = attributes.begin();
234 for ( ; attrsIt != attributes.end(); ++attrsIt )
235 {
236 QgsAttributes newAttrs = attrs;
237 newAttrs.append( *attrsIt );
238 feat.setAttributes( newAttrs );
239 if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) )
240 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
241 }
242 }
243 }
244 else
245 {
246 // no matching for input feature
247 if ( sink && !discardNonMatching )
248 {
249 if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) )
250 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
251 }
252 if ( sinkNonMatching1 )
253 {
254 if ( !sinkNonMatching1->addFeature( feat, QgsFeatureSink::FastInsert ) )
255 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, QStringLiteral( "NON_MATCHING" ) ) );
256 }
257 unjoinedCount++;
258 }
259 }
260
261 feedback->pushInfo( QObject::tr( "%n feature(s) from input layer were successfully matched", nullptr, joinedCount ) );
262 if ( unjoinedCount > 0 )
263 feedback->reportError( QObject::tr( "%n feature(s) from input layer could not be matched", nullptr, unjoinedCount ) );
264
265 QVariantMap outputs;
266 if ( sink )
267 {
268 sink->finalize();
269 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
270 }
271 outputs.insert( QStringLiteral( "JOINED_COUNT" ), joinedCount );
272 outputs.insert( QStringLiteral( "UNJOINABLE_COUNT" ), unjoinedCount );
273 if ( sinkNonMatching1 )
274 {
275 sinkNonMatching1->finalize();
276 outputs.insert( QStringLiteral( "NON_MATCHING" ), destNonMatching1 );
277 }
278 return outputs;
279}
280
281
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3539
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3533
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
Definition qgis.h:2196
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3619
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3630
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3711
A vector of attributes.
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).
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsAttributes attributes
Definition qgsfeature.h:67
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:73
int count
Definition qgsfields.h:50
bool rename(int fieldIdx, const QString &name)
Renames a name of field.
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A numeric output for processing algorithms.
A boolean parameter for processing algorithms.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
A string parameter for processing algorithms.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
QList< int > QgsAttributeList
Definition qgsfield.h:28