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