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