24using namespace Qt::StringLiterals;
28QString QgsJoinByAttributeAlgorithm::name()
const
30 return u
"joinattributestable"_s;
33QString QgsJoinByAttributeAlgorithm::displayName()
const
35 return QObject::tr(
"Join attributes by field value" );
38QStringList QgsJoinByAttributeAlgorithm::tags()
const
40 return QObject::tr(
"join,connect,attributes,values,fields,tables" ).split(
',' );
43QString QgsJoinByAttributeAlgorithm::group()
const
45 return QObject::tr(
"Vector general" );
48QString QgsJoinByAttributeAlgorithm::groupId()
const
50 return u
"vectorgeneral"_s;
53void QgsJoinByAttributeAlgorithm::initAlgorithm(
const QVariantMap & )
56 methods << QObject::tr(
"Create separate feature for each matching feature (one-to-many)" ) << QObject::tr(
"Take attributes of the first matching feature only (one-to-one)" );
69 addParameter(
new QgsProcessingParameterBoolean( u
"DISCARD_NONMATCHING"_s, QObject::tr(
"Discard records which could not be joined" ),
false ) );
79 addParameter( nonMatchingSink.release() );
81 addOutput(
new QgsProcessingOutputNumber( u
"JOINED_COUNT"_s, QObject::tr(
"Number of joined features from input table" ) ) );
82 addOutput(
new QgsProcessingOutputNumber( u
"UNJOINABLE_COUNT"_s, QObject::tr(
"Number of unjoinable features from input table" ) ) );
85QString QgsJoinByAttributeAlgorithm::shortHelpString()
const
88 "This algorithm takes an input vector layer and creates a new vector layer that is an extended version of the "
89 "input one, with additional attributes in its attribute table.\n\n"
90 "The additional attributes and their values are taken from a second vector layer. An attribute is selected "
91 "in each of them to define the join criteria."
95QString QgsJoinByAttributeAlgorithm::shortDescription()
const
98 "Creates a vector layer that is an extended version of the input one, "
99 "with additional attributes taken from a second vector layer."
108QgsJoinByAttributeAlgorithm *QgsJoinByAttributeAlgorithm::createInstance()
const
110 return new QgsJoinByAttributeAlgorithm();
115 QGS_MARK_ALGORITHM_SOURCE
117 const int joinMethod = parameterAsEnum( parameters, u
"METHOD"_s, context );
118 const bool discardNonMatching = parameterAsBoolean( parameters, u
"DISCARD_NONMATCHING"_s, context );
120 std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u
"INPUT"_s, context ) );
124 std::unique_ptr<QgsProcessingFeatureSource> input2( parameterAsSource( parameters, u
"INPUT_2"_s, context ) );
128 const QString prefix = parameterAsString( parameters, u
"PREFIX"_s, context );
130 const QString field1Name = parameterAsString( parameters, u
"FIELD"_s, context );
131 const QString field2Name = parameterAsString( parameters, u
"FIELD_2"_s, context );
132 const QStringList fieldsToCopy = parameterAsStrings( parameters, u
"FIELDS_TO_COPY"_s, context );
134 const int joinField1Index = input->fields().lookupField( field1Name );
135 if ( joinField1Index < 0 )
136 throw QgsProcessingException( QObject::tr(
"Invalid join field from layer 1: “%1” does not exist" ).arg( field1Name ) );
138 const int joinField2Index = input2->fields().lookupField( field2Name );
139 if ( joinField2Index < 0 )
140 throw QgsProcessingException( QObject::tr(
"Invalid join field from layer 2: “%1” does not exist" ).arg( field2Name ) );
144 if ( fieldsToCopy.empty() )
146 outFields2 = input2->fields();
147 fields2Indices.reserve( outFields2.
count() );
148 for (
int i = 0; i < outFields2.
count(); ++i )
155 fields2Indices.reserve( fieldsToCopy.count() );
156 for (
const QString &field : fieldsToCopy )
158 const int index = input2->fields().lookupField( field );
161 fields2Indices << index;
162 outFields2.
append( input2->fields().at( index ) );
167 if ( !prefix.isEmpty() )
169 for (
int i = 0; i < outFields2.
count(); ++i )
171 outFields2.
rename( i, prefix + outFields2[i].name() );
176 fields2Fetch << joinField2Index;
181 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u
"OUTPUT"_s, context, dest, outFields, input->wkbType(), input->sourceCrs(),
QgsFeatureSink::RegeneratePrimaryKey ) );
182 if ( parameters.value( u
"OUTPUT"_s ).isValid() && !sink )
185 QString destNonMatching1;
186 std::unique_ptr<QgsFeatureSink> sinkNonMatching1(
189 if ( parameters.value( u
"NON_MATCHING"_s ).isValid() && !sinkNonMatching1 )
193 QMultiHash<QVariant, QgsAttributes> input2AttributeCache;
196 double step = input2->featureCount() > 0 ? 50.0 / input2->featureCount() : 1;
209 if ( joinMethod == 1 && input2AttributeCache.contains( feat.
attribute( joinField2Index ) ) )
214 for (
int field2Index : fields2Indices )
216 attributes << feat.
attribute( field2Index );
219 input2AttributeCache.insert( feat.
attribute( joinField2Index ), attributes );
223 step = input->featureCount() > 0 ? 50.0 / input->featureCount() : 1;
226 long long joinedCount = 0;
227 long long unjoinedCount = 0;
238 if ( input2AttributeCache.count( feat.
attribute( joinField1Index ) ) > 0 )
245 QList<QgsAttributes> attributes = input2AttributeCache.values( feat.
attribute( joinField1Index ) );
246 QList<QgsAttributes>::iterator attrsIt = attributes.begin();
247 for ( ; attrsIt != attributes.end(); ++attrsIt )
250 newAttrs.append( *attrsIt );
262 if ( sink && !discardNonMatching )
269 if ( sinkNonMatching1 )
272 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, u
"NON_MATCHING"_s ) );
280 feedback->
pushInfo( QObject::tr(
"%n feature(s) from input layer were successfully matched",
nullptr, joinedCount ) );
281 if ( unjoinedCount > 0 )
282 feedback->
reportError( QObject::tr(
"%n feature(s) from input layer could not be matched",
nullptr, unjoinedCount ) );
289 outputs.insert( u
"OUTPUT"_s, dest );
291 outputs.insert( u
"JOINED_COUNT"_s, joinedCount );
292 outputs.insert( u
"UNJOINABLE_COUNT"_s, unjoinedCount );
293 if ( sinkNonMatching1 )
295 sinkNonMatching1->finalize();
297 outputs.insert( u
"NON_MATCHING"_s, destNonMatching1 );
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ VectorAnyGeometry
Any vector layer with geometry.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
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).
@ 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...
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
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.
void setProgress(double progress)
Sets the current progress for the feedback object.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
bool rename(int fieldIdx, const QString &name)
Renames a name of field.
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A numeric output for processing algorithms.
A boolean parameter for processing algorithms.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
A string parameter for processing algorithms.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
QList< int > QgsAttributeList