QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
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
22#include <QString>
23
24using namespace Qt::StringLiterals;
25
27
28QString QgsJoinByAttributeAlgorithm::name() const
29{
30 return u"joinattributestable"_s;
31}
32
33QString QgsJoinByAttributeAlgorithm::displayName() const
34{
35 return QObject::tr( "Join attributes by field value" );
36}
37
38QStringList QgsJoinByAttributeAlgorithm::tags() const
39{
40 return QObject::tr( "join,connect,attributes,values,fields,tables" ).split( ',' );
41}
42
43QString QgsJoinByAttributeAlgorithm::group() const
44{
45 return QObject::tr( "Vector general" );
46}
47
48QString QgsJoinByAttributeAlgorithm::groupId() const
49{
50 return u"vectorgeneral"_s;
51}
52
53void QgsJoinByAttributeAlgorithm::initAlgorithm( const QVariantMap & )
54{
55 QStringList methods;
56 methods << QObject::tr( "Create separate feature for each matching feature (one-to-many)" ) << QObject::tr( "Take attributes of the first matching feature only (one-to-one)" );
57
58 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
59 addParameter( new QgsProcessingParameterField( u"FIELD"_s, QObject::tr( "Table field" ), QVariant(), u"INPUT"_s ) );
60
61 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT_2"_s, QObject::tr( "Input layer 2" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
62 addParameter( new QgsProcessingParameterField( u"FIELD_2"_s, QObject::tr( "Table field 2" ), QVariant(), u"INPUT_2"_s ) );
63
64 addParameter(
65 new QgsProcessingParameterField( u"FIELDS_TO_COPY"_s, QObject::tr( "Layer 2 fields to copy (leave empty to copy all fields)" ), QVariant(), u"INPUT_2"_s, Qgis::ProcessingFieldParameterDataType::Any, true, true )
66 );
67
68 addParameter( new QgsProcessingParameterEnum( u"METHOD"_s, QObject::tr( "Join type" ), methods, false, 1 ) );
69 addParameter( new QgsProcessingParameterBoolean( u"DISCARD_NONMATCHING"_s, QObject::tr( "Discard records which could not be joined" ), false ) );
70
71 addParameter( new QgsProcessingParameterString( u"PREFIX"_s, QObject::tr( "Joined field prefix" ), QVariant(), false, true ) );
72
73 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Joined layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true, true ) );
74
75 auto nonMatchingSink
76 = std::make_unique<QgsProcessingParameterFeatureSink>( u"NON_MATCHING"_s, QObject::tr( "Unjoinable features from first layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true, false );
77 // TODO GUI doesn't support advanced outputs yet
78 //nonMatchingSink->setFlags(nonMatchingSink->flags() | Qgis::ProcessingParameterFlag::Advanced );
79 addParameter( nonMatchingSink.release() );
80
81 addOutput( new QgsProcessingOutputNumber( u"JOINED_COUNT"_s, QObject::tr( "Number of joined features from input table" ) ) );
82 addOutput( new QgsProcessingOutputNumber( u"UNJOINABLE_COUNT"_s, QObject::tr( "Number of unjoinable features from input table" ) ) );
83}
84
85QString QgsJoinByAttributeAlgorithm::shortHelpString() const
86{
87 return QObject::tr(
88 "This algorithm takes an input vector layer and creates a new vector layer that is an extended version of the "
89 "input one, with additional attributes in its attribute table.\n\n"
90 "The additional attributes and their values are taken from a second vector layer. An attribute is selected "
91 "in each of them to define the join criteria."
92 );
93}
94
95QString QgsJoinByAttributeAlgorithm::shortDescription() const
96{
97 return QObject::tr(
98 "Creates a vector layer that is an extended version of the input one, "
99 "with additional attributes taken from a second vector layer."
100 );
101}
102
103Qgis::ProcessingAlgorithmDocumentationFlags QgsJoinByAttributeAlgorithm::documentationFlags() const
104{
106}
107
108QgsJoinByAttributeAlgorithm *QgsJoinByAttributeAlgorithm::createInstance() const
109{
110 return new QgsJoinByAttributeAlgorithm();
111}
112
113QVariantMap QgsJoinByAttributeAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
114{
115 QGS_MARK_ALGORITHM_SOURCE
116
117 const int joinMethod = parameterAsEnum( parameters, u"METHOD"_s, context );
118 const bool discardNonMatching = parameterAsBoolean( parameters, u"DISCARD_NONMATCHING"_s, context );
119
120 std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u"INPUT"_s, context ) );
121 if ( !input )
122 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
123
124 std::unique_ptr<QgsProcessingFeatureSource> input2( parameterAsSource( parameters, u"INPUT_2"_s, context ) );
125 if ( !input2 )
126 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT_2"_s ) );
127
128 const QString prefix = parameterAsString( parameters, u"PREFIX"_s, context );
129
130 const QString field1Name = parameterAsString( parameters, u"FIELD"_s, context );
131 const QString field2Name = parameterAsString( parameters, u"FIELD_2"_s, context );
132 const QStringList fieldsToCopy = parameterAsStrings( parameters, u"FIELDS_TO_COPY"_s, context );
133
134 const int joinField1Index = input->fields().lookupField( field1Name );
135 if ( joinField1Index < 0 )
136 throw QgsProcessingException( QObject::tr( "Invalid join field from layer 1: “%1” does not exist" ).arg( field1Name ) );
137
138 const int joinField2Index = input2->fields().lookupField( field2Name );
139 if ( joinField2Index < 0 )
140 throw QgsProcessingException( QObject::tr( "Invalid join field from layer 2: “%1” does not exist" ).arg( field2Name ) );
141
142 QgsFields outFields2;
143 QgsAttributeList fields2Indices;
144 if ( fieldsToCopy.empty() )
145 {
146 outFields2 = input2->fields();
147 fields2Indices.reserve( outFields2.count() );
148 for ( int i = 0; i < outFields2.count(); ++i )
149 {
150 fields2Indices << i;
151 }
152 }
153 else
154 {
155 fields2Indices.reserve( fieldsToCopy.count() );
156 for ( const QString &field : fieldsToCopy )
157 {
158 const int index = input2->fields().lookupField( field );
159 if ( index >= 0 )
160 {
161 fields2Indices << index;
162 outFields2.append( input2->fields().at( index ) );
163 }
164 }
165 }
166
167 if ( !prefix.isEmpty() )
168 {
169 for ( int i = 0; i < outFields2.count(); ++i )
170 {
171 outFields2.rename( i, prefix + outFields2[i].name() );
172 }
173 }
174
175 QgsAttributeList fields2Fetch = fields2Indices;
176 fields2Fetch << joinField2Index;
177
178 const QgsFields outFields = QgsProcessingUtils::combineFields( input->fields(), outFields2 );
179
180 QString dest;
181 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, outFields, input->wkbType(), input->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
182 if ( parameters.value( u"OUTPUT"_s ).isValid() && !sink )
183 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
184
185 QString destNonMatching1;
186 std::unique_ptr<QgsFeatureSink> sinkNonMatching1(
187 parameterAsSink( parameters, u"NON_MATCHING"_s, context, destNonMatching1, input->fields(), input->wkbType(), input->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey )
188 );
189 if ( parameters.value( u"NON_MATCHING"_s ).isValid() && !sinkNonMatching1 )
190 throw QgsProcessingException( invalidSinkError( parameters, u"NON_MATCHING"_s ) );
191
192 // cache attributes of input2
193 QMultiHash<QVariant, QgsAttributes> input2AttributeCache;
194 QgsFeatureIterator features
195 = input2->getFeatures( QgsFeatureRequest().setFlags( Qgis::FeatureRequestFlag::NoGeometry ).setSubsetOfAttributes( fields2Fetch ), Qgis::ProcessingFeatureSourceFlag::SkipGeometryValidityChecks );
196 double step = input2->featureCount() > 0 ? 50.0 / input2->featureCount() : 1;
197 int i = 0;
198 QgsFeature feat;
199 while ( features.nextFeature( feat ) )
200 {
201 i++;
202 if ( feedback->isCanceled() )
203 {
204 break;
205 }
206
207 feedback->setProgress( i * step );
208
209 if ( joinMethod == 1 && input2AttributeCache.contains( feat.attribute( joinField2Index ) ) )
210 continue;
211
212 // only keep selected attributes
213 QgsAttributes attributes;
214 for ( int field2Index : fields2Indices )
215 {
216 attributes << feat.attribute( field2Index );
217 }
218
219 input2AttributeCache.insert( feat.attribute( joinField2Index ), attributes );
220 }
221
222 // Create output vector layer with additional attribute
223 step = input->featureCount() > 0 ? 50.0 / input->featureCount() : 1;
225 i = 0;
226 long long joinedCount = 0;
227 long long unjoinedCount = 0;
228 while ( features.nextFeature( feat ) )
229 {
230 i++;
231 if ( feedback->isCanceled() )
232 {
233 break;
234 }
235
236 feedback->setProgress( 50 + i * step );
237
238 if ( input2AttributeCache.count( feat.attribute( joinField1Index ) ) > 0 )
239 {
240 joinedCount++;
241 if ( sink )
242 {
243 const QgsAttributes attrs = feat.attributes();
244
245 QList<QgsAttributes> attributes = input2AttributeCache.values( feat.attribute( joinField1Index ) );
246 QList<QgsAttributes>::iterator attrsIt = attributes.begin();
247 for ( ; attrsIt != attributes.end(); ++attrsIt )
248 {
249 QgsAttributes newAttrs = attrs;
250 newAttrs.append( *attrsIt );
251 feat.setAttributes( newAttrs );
252 if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) )
253 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
254 else
255 feedback->featureAddedToSink( u"OUTPUT"_s );
256 }
257 }
258 }
259 else
260 {
261 // no matching for input feature
262 if ( sink && !discardNonMatching )
263 {
264 if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) )
265 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
266 else
267 feedback->featureAddedToSink( u"OUTPUT"_s );
268 }
269 if ( sinkNonMatching1 )
270 {
271 if ( !sinkNonMatching1->addFeature( feat, QgsFeatureSink::FastInsert ) )
272 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, u"NON_MATCHING"_s ) );
273 else
274 feedback->featureAddedToSink( u"NON_MATCHING"_s );
275 }
276 unjoinedCount++;
277 }
278 }
279
280 feedback->pushInfo( QObject::tr( "%n feature(s) from input layer were successfully matched", nullptr, joinedCount ) );
281 if ( unjoinedCount > 0 )
282 feedback->reportError( QObject::tr( "%n feature(s) from input layer could not be matched", nullptr, unjoinedCount ) );
283
284 QVariantMap outputs;
285 if ( sink )
286 {
287 sink->finalize();
288 feedback->featureSinkFinalized( u"OUTPUT"_s );
289 outputs.insert( u"OUTPUT"_s, dest );
290 }
291 outputs.insert( u"JOINED_COUNT"_s, joinedCount );
292 outputs.insert( u"UNJOINABLE_COUNT"_s, unjoinedCount );
293 if ( sinkNonMatching1 )
294 {
295 sinkNonMatching1->finalize();
296 feedback->featureSinkFinalized( u"NON_MATCHING"_s );
297 outputs.insert( u"NON_MATCHING"_s, destNonMatching1 );
298 }
299 return outputs;
300}
301
302
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3755
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3749
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
Definition qgis.h:2360
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3836
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3847
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3930
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:60
QgsAttributes attributes
Definition qgsfeature.h:64
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:56
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
Container of fields for a vector layer.
Definition qgsfields.h:45
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
int count
Definition qgsfields.h:49
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.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
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:30