QGIS API Documentation 3.41.0-Master (cea29feecf2)
Loading...
Searching...
No Matches
qgsalgorithmflattenrelationships.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmflattenrelationships.h
3 ---------------------
4 begin : August 2020
5 copyright : (C) 2020 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19#include "qgsrelationmanager.h"
20#include "qgsvectorlayer.h"
22
24
25QString QgsFlattenRelationshipsAlgorithm::name() const
26{
27 return QStringLiteral( "flattenrelationships" );
28}
29
30QString QgsFlattenRelationshipsAlgorithm::displayName() const
31{
32 return QObject::tr( "Flatten relationship" );
33}
34
35QStringList QgsFlattenRelationshipsAlgorithm::tags() const
36{
37 return QObject::tr( "join,export,single,table" ).split( ',' );
38}
39
40QString QgsFlattenRelationshipsAlgorithm::group() const
41{
42 return QObject::tr( "Vector general" );
43}
44
45QString QgsFlattenRelationshipsAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectorgeneral" );
48}
49
50QString QgsFlattenRelationshipsAlgorithm::shortDescription() const
51{
52 return QObject::tr( "Flatten a relationship for a vector layer." );
53}
54
55QString QgsFlattenRelationshipsAlgorithm::shortHelpString() const
56{
57 return QObject::tr( "This algorithm flattens a relationship for a vector layer, exporting a single layer "
58 "containing one master feature per related feature. This master feature contains all "
59 "the attributes for the related features." );
60}
61
62Qgis::ProcessingAlgorithmDocumentationFlags QgsFlattenRelationshipsAlgorithm::documentationFlags() const
63{
65}
66
67Qgis::ProcessingAlgorithmFlags QgsFlattenRelationshipsAlgorithm::flags() const
68{
70}
71
72void QgsFlattenRelationshipsAlgorithm::initAlgorithm( const QVariantMap & )
73{
74 addParameter( new QgsProcessingParameterVectorLayer( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
75
76 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Flattened layer" ), Qgis::ProcessingSourceType::VectorAnyGeometry ) );
77}
78
79QgsFlattenRelationshipsAlgorithm *QgsFlattenRelationshipsAlgorithm::createInstance() const
80{
81 return new QgsFlattenRelationshipsAlgorithm();
82}
83
84bool QgsFlattenRelationshipsAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
85{
86 QgsProject *project = context.project();
87 if ( !project )
88 throw QgsProcessingException( QObject::tr( "No project available for relationships" ) );
89
90 QgsVectorLayer *layer = parameterAsVectorLayer( parameters, QStringLiteral( "INPUT" ), context );
91 if ( !layer )
92 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
93
94 const QList<QgsRelation> relations = project->relationManager()->referencedRelations( layer );
95 if ( relations.size() > 1 )
96 throw QgsProcessingException( QObject::tr( "Found %n relation(s). This algorithm currently supports only a single relation.", nullptr, relations.size() ) );
97 else if ( relations.empty() )
98 throw QgsProcessingException( QObject::tr( "No relations found." ) );
99
100 mRelation = relations.at( 0 );
101
102 QgsVectorLayer *referencingLayer = mRelation.referencingLayer();
103 if ( !referencingLayer )
104 throw QgsProcessingException( QObject::tr( "Could not resolved referenced layer." ) );
105
106 mReferencingSource = std::make_unique<QgsVectorLayerFeatureSource>( referencingLayer );
107 mReferencingFields = referencingLayer->fields();
108
109 return true;
110}
111
112QVariantMap QgsFlattenRelationshipsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
113{
114 std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
115 if ( !input )
116 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
117
118 const QgsFields outFields = QgsProcessingUtils::combineFields( input->fields(), mReferencingFields );
119
120 QString dest;
121 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, outFields, input->wkbType(), input->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
122 if ( parameters.value( QStringLiteral( "OUTPUT" ) ).isValid() && !sink )
123 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
124
125 // Create output vector layer with additional attributes
126 const double step = input->featureCount() > 0 ? 100.0 / input->featureCount() : 1;
128 long long i = 0;
129 QgsFeature feat;
130 while ( features.nextFeature( feat ) )
131 {
132 i++;
133 if ( feedback->isCanceled() )
134 {
135 break;
136 }
137
138 feedback->setProgress( i * step );
139
140 QgsFeatureRequest referencingRequest = mRelation.getRelatedFeaturesRequest( feat );
141 referencingRequest.setFlags( referencingRequest.flags() | Qgis::FeatureRequestFlag::NoGeometry );
142 QgsFeatureIterator childIt = mReferencingSource->getFeatures( referencingRequest );
143 QgsFeature relatedFeature;
144 while ( childIt.nextFeature( relatedFeature ) )
145 {
146 QgsAttributes attrs = feat.attributes();
147 attrs.append( relatedFeature.attributes() );
148 QgsFeature outFeat = feat;
149 outFeat.setAttributes( attrs );
150 if ( !sink->addFeature( outFeat, QgsFeatureSink::FastInsert ) )
151 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
152 }
153 }
154
155 QVariantMap outputs;
156 if ( sink )
157 {
158 sink->finalize();
159 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
160 }
161 return outputs;
162}
163
164
@ 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< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3392
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3412
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
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 & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
Qgis::FeatureRequestFlags flags() const
Returns the flags which affect how features are fetched.
@ 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.
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
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Contains information about the context in which a processing algorithm is executed.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
A feature sink output for processing algorithms.
A vector layer (with or without geometry) 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).
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:107
QgsRelationManager * relationManager
Definition qgsproject.h:117
QList< QgsRelation > referencedRelations(const QgsVectorLayer *layer=nullptr) const
Gets all relations where this layer is the referenced part (i.e.
Represents a vector layer which manages a vector based data sets.