QGIS API Documentation 3.41.0-Master (45a0abf3bec)
Loading...
Searching...
No Matches
qgsalgorithmjoinbylocation.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmjoinbylocation.cpp
3 ---------------------
4 begin : January 2020
5 copyright : (C) 2020 by Alexis Roy-Lizotte
6 email : roya2 at premiertech 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#include "qgsprocessing.h"
20#include "qgsgeometryengine.h"
21#include "qgsvectorlayer.h"
22#include "qgsapplication.h"
23#include "qgsfeature.h"
24#include "qgsfeaturesource.h"
25
27
28
29void QgsJoinByLocationAlgorithm::initAlgorithm( const QVariantMap & )
30{
31 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ),
32 QObject::tr( "Join to features in" ), QList< int > () << static_cast< int >( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
33
34 std::unique_ptr< QgsProcessingParameterEnum > predicateParam = std::make_unique< QgsProcessingParameterEnum >( QStringLiteral( "PREDICATE" ), QObject::tr( "Features they (geometric predicate)" ), translatedPredicates(), true, 0 );
35 QVariantMap predicateMetadata;
36 QVariantMap widgetMetadata;
37 widgetMetadata.insert( QStringLiteral( "useCheckBoxes" ), true );
38 widgetMetadata.insert( QStringLiteral( "columns" ), 2 );
39 predicateMetadata.insert( QStringLiteral( "widget_wrapper" ), widgetMetadata );
40 predicateParam->setMetadata( predicateMetadata );
41 addParameter( predicateParam.release() );
42 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "JOIN" ),
43 QObject::tr( "By comparing to" ), QList< int > () << static_cast< int >( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
44 addParameter( new QgsProcessingParameterField( QStringLiteral( "JOIN_FIELDS" ),
45 QObject::tr( "Fields to add (leave empty to use all fields)" ),
46 QVariant(), QStringLiteral( "JOIN" ), Qgis::ProcessingFieldParameterDataType::Any, true, true ) );
47
48 QStringList joinMethods;
49 joinMethods << QObject::tr( "Create separate feature for each matching feature (one-to-many)" )
50 << QObject::tr( "Take attributes of the first matching feature only (one-to-one)" )
51 << QObject::tr( "Take attributes of the feature with largest overlap only (one-to-one)" );
52 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "METHOD" ),
53 QObject::tr( "Join type" ),
54 joinMethods, false, static_cast< int >( OneToMany ) ) );
55 addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "DISCARD_NONMATCHING" ),
56 QObject::tr( "Discard records which could not be joined" ),
57 false ) );
58 addParameter( new QgsProcessingParameterString( QStringLiteral( "PREFIX" ),
59 QObject::tr( "Joined field prefix" ), QVariant(), false, true ) );
60 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Joined layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true, true ) );
61 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "NON_MATCHING" ), QObject::tr( "Unjoinable features from first layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true, false ) );
62 addOutput( new QgsProcessingOutputNumber( QStringLiteral( "JOINED_COUNT" ), QObject::tr( "Number of joined features from input table" ) ) );
63}
64
65QString QgsJoinByLocationAlgorithm::name() const
66{
67 return QStringLiteral( "joinattributesbylocation" );
68}
69
70QString QgsJoinByLocationAlgorithm::displayName() const
71{
72 return QObject::tr( "Join attributes by location" );
73}
74
75QStringList QgsJoinByLocationAlgorithm::tags() const
76{
77 return QObject::tr( "join,intersects,intersecting,touching,within,contains,overlaps,relation,spatial" ).split( ',' );
78}
79
80QString QgsJoinByLocationAlgorithm::group() const
81{
82 return QObject::tr( "Vector general" );
83}
84
85QString QgsJoinByLocationAlgorithm::groupId() const
86{
87 return QStringLiteral( "vectorgeneral" );
88}
89
90QString QgsJoinByLocationAlgorithm::shortHelpString() const
91{
92 return QObject::tr( "This algorithm takes an input vector layer and creates a new vector layer "
93 "that is an extended version of the input one, with additional attributes in its attribute table.\n\n"
94 "The additional attributes and their values are taken from a second vector layer. "
95 "A spatial criteria is applied to select the values from the second layer that are added "
96 "to each feature from the first layer in the resulting one." );
97}
98
99QString QgsJoinByLocationAlgorithm::shortDescription() const
100{
101 return QObject::tr( "Join attributes from one vector layer to another by location." );
102}
103
104Qgis::ProcessingAlgorithmDocumentationFlags QgsJoinByLocationAlgorithm::documentationFlags() const
105{
107}
108
109QgsJoinByLocationAlgorithm *QgsJoinByLocationAlgorithm::createInstance() const
110{
111 return new QgsJoinByLocationAlgorithm();
112}
113
114QStringList QgsJoinByLocationAlgorithm::translatedPredicates()
115{
116 return { QObject::tr( "intersect" ),
117 QObject::tr( "contain" ),
118 QObject::tr( "equal" ),
119 QObject::tr( "touch" ),
120 QObject::tr( "overlap" ),
121 QObject::tr( "are within" ),
122 QObject::tr( "cross" ) };
123}
124
125QVariantMap QgsJoinByLocationAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
126{
127 mBaseSource.reset( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
128 if ( !mBaseSource )
129 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
130
131 mJoinSource.reset( parameterAsSource( parameters, QStringLiteral( "JOIN" ), context ) );
132 if ( !mJoinSource )
133 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "JOIN" ) ) );
134
135 mJoinMethod = static_cast< JoinMethod >( parameterAsEnum( parameters, QStringLiteral( "METHOD" ), context ) );
136
137 const QStringList joinedFieldNames = parameterAsStrings( parameters, QStringLiteral( "JOIN_FIELDS" ), context );
138
139 mPredicates = parameterAsEnums( parameters, QStringLiteral( "PREDICATE" ), context );
140 sortPredicates( mPredicates );
141
142 QString prefix = parameterAsString( parameters, QStringLiteral( "PREFIX" ), context );
143
144 QgsFields joinFields;
145 if ( joinedFieldNames.empty() )
146 {
147 joinFields = mJoinSource->fields();
148 mJoinedFieldIndices = joinFields.allAttributesList();
149 }
150 else
151 {
152 mJoinedFieldIndices.reserve( joinedFieldNames.count() );
153 for ( const QString &field : joinedFieldNames )
154 {
155 int index = mJoinSource->fields().lookupField( field );
156 if ( index >= 0 )
157 {
158 mJoinedFieldIndices << index;
159 joinFields.append( mJoinSource->fields().at( index ) );
160 }
161 }
162 }
163
164 if ( !prefix.isEmpty() )
165 {
166 for ( int i = 0; i < joinFields.count(); ++i )
167 {
168 joinFields.rename( i, prefix + joinFields[ i ].name() );
169 }
170 }
171
172 const QgsFields outputFields = QgsProcessingUtils::combineFields( mBaseSource->fields(), joinFields );
173
174 QString joinedSinkId;
175 mJoinedFeatures.reset( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, joinedSinkId, outputFields,
176 mBaseSource->wkbType(), mBaseSource->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
177
178 if ( parameters.value( QStringLiteral( "OUTPUT" ) ).isValid() && !mJoinedFeatures )
179 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
180
181 mDiscardNonMatching = parameterAsBoolean( parameters, QStringLiteral( "DISCARD_NONMATCHING" ), context );
182
183 QString nonMatchingSinkId;
184 mUnjoinedFeatures.reset( parameterAsSink( parameters, QStringLiteral( "NON_MATCHING" ), context, nonMatchingSinkId, mBaseSource->fields(),
185 mBaseSource->wkbType(), mBaseSource->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
186 if ( parameters.value( QStringLiteral( "NON_MATCHING" ) ).isValid() && !mUnjoinedFeatures )
187 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "NON_MATCHING" ) ) );
188
189 switch ( mJoinMethod )
190 {
191 case OneToMany:
192 case JoinToFirst:
193 {
194 if ( mBaseSource->featureCount() > 0 && mJoinSource->featureCount() > 0 && mBaseSource->featureCount() < mJoinSource->featureCount() )
195 {
196 // joining FEWER features to a layer with MORE features. So we iterate over the FEW features and find matches from the MANY
197 processAlgorithmByIteratingOverInputSource( context, feedback );
198 }
199 else
200 {
201 // default -- iterate over the join source and match back to the base source. We do this on the assumption that the most common
202 // use case is joining a points layer to a polygon layer (taking polygon attributes and adding them to the points), so by iterating
203 // over the polygons we can take advantage of prepared geometries for the spatial relationship test.
204
205 // TODO - consider using more heuristics to determine whether it's always best to iterate over the join
206 // source.
207 processAlgorithmByIteratingOverJoinedSource( context, feedback );
208 }
209 break;
210 }
211
212 case JoinToLargestOverlap:
213 processAlgorithmByIteratingOverInputSource( context, feedback );
214 break;
215 }
216
217 QVariantMap outputs;
218 if ( mJoinedFeatures )
219 {
220 mJoinedFeatures->finalize();
221 outputs.insert( QStringLiteral( "OUTPUT" ), joinedSinkId );
222 }
223 if ( mUnjoinedFeatures )
224 {
225 mUnjoinedFeatures->finalize();
226 outputs.insert( QStringLiteral( "NON_MATCHING" ), nonMatchingSinkId );
227 }
228
229 // need to release sinks to finalize writing
230 mJoinedFeatures.reset();
231 mUnjoinedFeatures.reset();
232
233 outputs.insert( QStringLiteral( "JOINED_COUNT" ), static_cast< long long >( mJoinedCount ) );
234 return outputs;
235}
236
237bool QgsJoinByLocationAlgorithm::featureFilter( const QgsFeature &feature, QgsGeometryEngine *engine, bool comparingToJoinedFeature, const QList<int> &predicates )
238{
239 const QgsAbstractGeometry *geom = feature.geometry().constGet();
240 bool ok = false;
241 for ( const int predicate : predicates )
242 {
243 switch ( predicate )
244 {
245 case 0:
246 // intersects
247 if ( engine->intersects( geom ) )
248 {
249 ok = true;
250 }
251 break;
252 case 1:
253 // contains
254 if ( comparingToJoinedFeature )
255 {
256 if ( engine->contains( geom ) )
257 {
258 ok = true;
259 }
260 }
261 else
262 {
263 if ( engine->within( geom ) )
264 {
265 ok = true;
266 }
267 }
268 break;
269 case 2:
270 // equals
271 if ( engine->isEqual( geom ) )
272 {
273 ok = true;
274 }
275 break;
276 case 3:
277 // touches
278 if ( engine->touches( geom ) )
279 {
280 ok = true;
281 }
282 break;
283 case 4:
284 // overlaps
285 if ( engine->overlaps( geom ) )
286 {
287 ok = true;
288 }
289 break;
290 case 5:
291 // within
292 if ( comparingToJoinedFeature )
293 {
294 if ( engine->within( geom ) )
295 {
296 ok = true;
297 }
298 }
299 else
300 {
301 if ( engine->contains( geom ) )
302 {
303 ok = true;
304 }
305 }
306 break;
307 case 6:
308 // crosses
309 if ( engine->crosses( geom ) )
310 {
311 ok = true;
312 }
313 break;
314 }
315 if ( ok )
316 return ok;
317 }
318 return ok;
319}
320
321void QgsJoinByLocationAlgorithm::processAlgorithmByIteratingOverJoinedSource( QgsProcessingContext &context, QgsProcessingFeedback *feedback )
322{
323 if ( mBaseSource->hasSpatialIndex() == Qgis::SpatialIndexPresence::NotPresent )
324 feedback->pushWarning( QObject::tr( "No spatial index exists for input layer, performance will be severely degraded" ) );
325
326 QgsFeatureIterator joinIter = mJoinSource->getFeatures( QgsFeatureRequest().setDestinationCrs( mBaseSource->sourceCrs(), context.transformContext() ).setSubsetOfAttributes( mJoinedFieldIndices ) );
327 QgsFeature f;
328
329 // Create output vector layer with additional attributes
330 const double step = mJoinSource->featureCount() > 0 ? 100.0 / mJoinSource->featureCount() : 1;
331 long i = 0;
332 while ( joinIter.nextFeature( f ) )
333 {
334 if ( feedback->isCanceled() )
335 break;
336
337 processFeatureFromJoinSource( f, feedback );
338
339 i++;
340 feedback->setProgress( i * step );
341 }
342
343 if ( !mDiscardNonMatching || mUnjoinedFeatures )
344 {
345 QgsFeatureIds unjoinedIds = mBaseSource->allFeatureIds();
346 unjoinedIds.subtract( mAddedIds );
347
348 QgsFeature f2;
349 QgsFeatureRequest remainings = QgsFeatureRequest().setFilterFids( unjoinedIds );
350 QgsFeatureIterator remainIter = mBaseSource->getFeatures( remainings );
351
352 QgsAttributes emptyAttributes;
353 emptyAttributes.reserve( mJoinedFieldIndices.count() );
354 for ( int i = 0; i < mJoinedFieldIndices.count(); ++i )
355 emptyAttributes << QVariant();
356
357 while ( remainIter.nextFeature( f2 ) )
358 {
359 if ( feedback->isCanceled() )
360 break;
361
362 if ( mJoinedFeatures && !mDiscardNonMatching )
363 {
364 QgsAttributes attributes = f2.attributes();
365 attributes.append( emptyAttributes );
366 QgsFeature outputFeature( f2 );
367 outputFeature.setAttributes( attributes );
368 if ( !mJoinedFeatures->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
369 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral( "OUTPUT" ) ) );
370 }
371
372 if ( mUnjoinedFeatures )
373 {
374 if ( !mUnjoinedFeatures->addFeature( f2, QgsFeatureSink::FastInsert ) )
375 throw QgsProcessingException( writeFeatureError( mUnjoinedFeatures.get(), QVariantMap(), QStringLiteral( "NON_MATCHING" ) ) );
376 }
377 }
378 }
379}
380
381void QgsJoinByLocationAlgorithm::processAlgorithmByIteratingOverInputSource( QgsProcessingContext &context, QgsProcessingFeedback *feedback )
382{
383 if ( mJoinSource->hasSpatialIndex() == Qgis::SpatialIndexPresence::NotPresent )
384 feedback->pushWarning( QObject::tr( "No spatial index exists for join layer, performance will be severely degraded" ) );
385
386 QgsFeatureIterator it = mBaseSource->getFeatures();
387 QgsFeature f;
388
389 const double step = mBaseSource->featureCount() > 0 ? 100.0 / mBaseSource->featureCount() : 1;
390 long i = 0;
391 while ( it .nextFeature( f ) )
392 {
393 if ( feedback->isCanceled() )
394 break;
395
396 processFeatureFromInputSource( f, context, feedback );
397
398 i++;
399 feedback->setProgress( i * step );
400 }
401}
402
403void QgsJoinByLocationAlgorithm::sortPredicates( QList<int> &predicates )
404{
405 // Sort predicate list so that faster predicates are earlier in the list
406 // Some predicates in GEOS do not have prepared geometry implementations, and are slow to calculate. So if users
407 // are testing multiple predicates, make sure the optimised ones are always tested first just in case we can shortcut
408 // these slower ones
409
410 std::sort( predicates.begin(), predicates.end(), []( int a, int b ) -> bool
411 {
412 // return true if predicate a is faster than b
413
414 if ( a == 0 ) // intersects is fastest
415 return true;
416 else if ( b == 0 )
417 return false;
418
419 else if ( a == 5 ) // contains is fast for polygons
420 return true;
421 else if ( b == 5 )
422 return false;
423
424 // that's it, the rest don't have optimised prepared methods (as of GEOS 3.8)
425 return a < b;
426 } );
427}
428
429bool QgsJoinByLocationAlgorithm::processFeatureFromJoinSource( QgsFeature &joinFeature, QgsProcessingFeedback *feedback )
430{
431 if ( !joinFeature.hasGeometry() )
432 return false;
433
434 const QgsGeometry featGeom = joinFeature.geometry();
435 std::unique_ptr< QgsGeometryEngine > engine;
437 QgsFeatureIterator it = mBaseSource->getFeatures( req );
438 QgsFeature baseFeature;
439 bool ok = false;
440 QgsAttributes joinAttributes;
441
442 while ( it.nextFeature( baseFeature ) )
443 {
444 if ( feedback->isCanceled() )
445 break;
446
447 switch ( mJoinMethod )
448 {
449 case JoinToFirst:
450 if ( mAddedIds.contains( baseFeature.id() ) )
451 {
452 // already added this feature, and user has opted to only output first match
453 continue;
454 }
455 break;
456
457 case OneToMany:
458 break;
459
460 case JoinToLargestOverlap:
461 Q_ASSERT_X( false, "QgsJoinByLocationAlgorithm::processFeatureFromJoinSource", "processFeatureFromJoinSource should not be used with join to largest overlap method" );
462 }
463
464 if ( !engine )
465 {
466 engine.reset( QgsGeometry::createGeometryEngine( featGeom.constGet() ) );
467 engine->prepareGeometry();
468 for ( int ix : std::as_const( mJoinedFieldIndices ) )
469 {
470 joinAttributes.append( joinFeature.attribute( ix ) );
471 }
472 }
473 if ( featureFilter( baseFeature, engine.get(), false, mPredicates ) )
474 {
475 if ( mJoinedFeatures )
476 {
477 QgsFeature outputFeature( baseFeature );
478 outputFeature.setAttributes( baseFeature.attributes() + joinAttributes );
479 if ( !mJoinedFeatures->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
480 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral( "OUTPUT" ) ) );
481 }
482 if ( !ok )
483 ok = true;
484
485 mAddedIds.insert( baseFeature.id() );
486 mJoinedCount++;
487 }
488 }
489 return ok;
490}
491
492bool QgsJoinByLocationAlgorithm::processFeatureFromInputSource( QgsFeature &baseFeature, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
493{
494 if ( !baseFeature.hasGeometry() )
495 {
496 // no geometry, treat as if we didn't find a match...
497 if ( mJoinedFeatures && !mDiscardNonMatching )
498 {
499 QgsAttributes emptyAttributes;
500 emptyAttributes.reserve( mJoinedFieldIndices.count() );
501 for ( int i = 0; i < mJoinedFieldIndices.count(); ++i )
502 emptyAttributes << QVariant();
503
504 QgsAttributes attributes = baseFeature.attributes();
505 attributes.append( emptyAttributes );
506 QgsFeature outputFeature( baseFeature );
507 outputFeature.setAttributes( attributes );
508 if ( !mJoinedFeatures->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
509 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral( "OUTPUT" ) ) );
510 }
511
512 if ( mUnjoinedFeatures )
513 {
514 if ( !mUnjoinedFeatures->addFeature( baseFeature, QgsFeatureSink::FastInsert ) )
515 throw QgsProcessingException( writeFeatureError( mUnjoinedFeatures.get(), QVariantMap(), QStringLiteral( "NON_MATCHING" ) ) );
516 }
517
518 return false;
519 }
520
521 const QgsGeometry featGeom = baseFeature.geometry();
522 std::unique_ptr< QgsGeometryEngine > engine;
523 QgsFeatureRequest req = QgsFeatureRequest().setDestinationCrs( mBaseSource->sourceCrs(), context.transformContext() ).setFilterRect( featGeom.boundingBox() ).setSubsetOfAttributes( mJoinedFieldIndices );
524
525 QgsFeatureIterator it = mJoinSource->getFeatures( req );
526 QgsFeature joinFeature;
527 bool ok = false;
528
529 double largestOverlap = std::numeric_limits< double >::lowest();
530 QgsFeature bestMatch;
531
532 while ( it.nextFeature( joinFeature ) )
533 {
534 if ( feedback->isCanceled() )
535 break;
536
537 if ( !engine )
538 {
539 engine.reset( QgsGeometry::createGeometryEngine( featGeom.constGet() ) );
540 engine->prepareGeometry();
541 }
542
543 if ( featureFilter( joinFeature, engine.get(), true, mPredicates ) )
544 {
545 switch ( mJoinMethod )
546 {
547 case JoinToFirst:
548 case OneToMany:
549 if ( mJoinedFeatures )
550 {
551 QgsAttributes joinAttributes = baseFeature.attributes();
552 joinAttributes.reserve( joinAttributes.size() + mJoinedFieldIndices.size() );
553 for ( int ix : std::as_const( mJoinedFieldIndices ) )
554 {
555 joinAttributes.append( joinFeature.attribute( ix ) );
556 }
557
558 QgsFeature outputFeature( baseFeature );
559 outputFeature.setAttributes( joinAttributes );
560 if ( !mJoinedFeatures->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
561 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral( "OUTPUT" ) ) );
562 }
563 break;
564
565 case JoinToLargestOverlap:
566 {
567 // calculate area of overlap
568 std::unique_ptr< QgsAbstractGeometry > intersection( engine->intersection( joinFeature.geometry().constGet() ) );
569 double overlap = 0;
570 switch ( QgsWkbTypes::geometryType( intersection->wkbType() ) )
571 {
573 overlap = intersection->length();
574 break;
575
577 overlap = intersection->area();
578 break;
579
583 break;
584 }
585
586 if ( overlap > largestOverlap )
587 {
588 largestOverlap = overlap;
589 bestMatch = joinFeature;
590 }
591 break;
592 }
593 }
594
595 ok = true;
596
597 if ( mJoinMethod == JoinToFirst )
598 break;
599 }
600 }
601
602 switch ( mJoinMethod )
603 {
604 case OneToMany:
605 case JoinToFirst:
606 break;
607
608 case JoinToLargestOverlap:
609 {
610 if ( bestMatch.isValid() )
611 {
612 // grab attributes from feature with best match
613 if ( mJoinedFeatures )
614 {
615 QgsAttributes joinAttributes = baseFeature.attributes();
616 joinAttributes.reserve( joinAttributes.size() + mJoinedFieldIndices.size() );
617 for ( int ix : std::as_const( mJoinedFieldIndices ) )
618 {
619 joinAttributes.append( bestMatch.attribute( ix ) );
620 }
621
622 QgsFeature outputFeature( baseFeature );
623 outputFeature.setAttributes( joinAttributes );
624 if ( !mJoinedFeatures->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
625 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral( "OUTPUT" ) ) );
626 }
627 }
628 else
629 {
630 ok = false; // shouldn't happen...
631 }
632 break;
633 }
634 }
635
636 if ( !ok )
637 {
638 // didn't find a match...
639 if ( mJoinedFeatures && !mDiscardNonMatching )
640 {
641 QgsAttributes emptyAttributes;
642 emptyAttributes.reserve( mJoinedFieldIndices.count() );
643 for ( int i = 0; i < mJoinedFieldIndices.count(); ++i )
644 emptyAttributes << QVariant();
645
646 QgsAttributes attributes = baseFeature.attributes();
647 attributes.append( emptyAttributes );
648 QgsFeature outputFeature( baseFeature );
649 outputFeature.setAttributes( attributes );
650 if ( !mJoinedFeatures->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
651 throw QgsProcessingException( writeFeatureError( mJoinedFeatures.get(), QVariantMap(), QStringLiteral( "OUTPUT" ) ) );
652 }
653
654 if ( mUnjoinedFeatures )
655 {
656 if ( !mUnjoinedFeatures->addFeature( baseFeature, QgsFeatureSink::FastInsert ) )
657 throw QgsProcessingException( writeFeatureError( mUnjoinedFeatures.get(), QVariantMap(), QStringLiteral( "NON_MATCHING" ) ) );
658 }
659 }
660 else
661 mJoinedCount++;
662
663 return ok;
664}
665
666
668
669
670
@ VectorAnyGeometry
Any vector layer with geometry.
@ NotPresent
No spatial index exists for the source.
@ Polygon
Polygons.
@ Unknown
Unknown types.
@ Null
No geometry.
@ 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:3367
Abstract base class for all geometries.
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).
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets the feature IDs that should be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
@ 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
QgsFeatureId id
Definition qgsfeature.h:66
QgsGeometry geometry
Definition qgsfeature.h:69
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool isValid() const
Returns the validity of this 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
QgsAttributeList allAttributesList() const
Utility function to get list of attribute indexes.
bool rename(int fieldIdx, const QString &name)
Renames a name of field.
A geometry engine is a low-level representation of a QgsAbstractGeometry object, optimised for use wi...
virtual bool isEqual(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if this is equal to geom.
virtual bool intersects(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom intersects this.
virtual bool touches(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom touches this.
virtual bool crosses(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom crosses this.
virtual bool overlaps(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom overlaps this.
virtual bool within(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom is within this.
virtual bool contains(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const =0
Checks if geom contains this.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
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).
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
QSet< QgsFeatureId > QgsFeatureIds