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