23QString QgsJoinByAttributeAlgorithm::name()
const
25 return QStringLiteral(
"joinattributestable" );
28QString QgsJoinByAttributeAlgorithm::displayName()
const
30 return QObject::tr(
"Join attributes by field value" );
33QStringList QgsJoinByAttributeAlgorithm::tags()
const
35 return QObject::tr(
"join,connect,attributes,values,fields,tables" ).split(
',' );
38QString QgsJoinByAttributeAlgorithm::group()
const
40 return QObject::tr(
"Vector general" );
43QString QgsJoinByAttributeAlgorithm::groupId()
const
45 return QStringLiteral(
"vectorgeneral" );
48void QgsJoinByAttributeAlgorithm::initAlgorithm(
const QVariantMap & )
51 methods << QObject::tr(
"Create separate feature for each matching feature (one-to-many)" )
52 << QObject::tr(
"Take attributes of the first matching feature only (one-to-one)" );
55 addParameter(
new QgsProcessingParameterField( QStringLiteral(
"FIELD" ), QObject::tr(
"Table field" ), QVariant(), QStringLiteral(
"INPUT" ) ) );
58 addParameter(
new QgsProcessingParameterField( QStringLiteral(
"FIELD_2" ), QObject::tr(
"Table field 2" ), QVariant(), QStringLiteral(
"INPUT_2" ) ) );
63 addParameter(
new QgsProcessingParameterBoolean( QStringLiteral(
"DISCARD_NONMATCHING" ), QObject::tr(
"Discard records which could not be joined" ),
false ) );
65 addParameter(
new QgsProcessingParameterString( QStringLiteral(
"PREFIX" ), QObject::tr(
"Joined field prefix" ), QVariant(),
false,
true ) );
69 auto nonMatchingSink = std::make_unique<QgsProcessingParameterFeatureSink>(
74 addParameter( nonMatchingSink.release() );
76 addOutput(
new QgsProcessingOutputNumber( QStringLiteral(
"JOINED_COUNT" ), QObject::tr(
"Number of joined features from input table" ) ) );
77 addOutput(
new QgsProcessingOutputNumber( QStringLiteral(
"UNJOINABLE_COUNT" ), QObject::tr(
"Number of unjoinable features from input table" ) ) );
80QString QgsJoinByAttributeAlgorithm::shortHelpString()
const
82 return QObject::tr(
"This algorithm takes an input vector layer and creates a new vector layer that is an extended version of the "
83 "input one, with additional attributes in its attribute table.\n\n"
84 "The additional attributes and their values are taken from a second vector layer. An attribute is selected "
85 "in each of them to define the join criteria." );
88QString QgsJoinByAttributeAlgorithm::shortDescription()
const
90 return QObject::tr(
"Creates a vector layer that is an extended version of the input one, "
91 "with additional attributes taken from a second vector layer." );
99QgsJoinByAttributeAlgorithm *QgsJoinByAttributeAlgorithm::createInstance()
const
101 return new QgsJoinByAttributeAlgorithm();
106 const int joinMethod = parameterAsEnum( parameters, QStringLiteral(
"METHOD" ), context );
107 const bool discardNonMatching = parameterAsBoolean( parameters, QStringLiteral(
"DISCARD_NONMATCHING" ), context );
109 std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral(
"INPUT" ), context ) );
113 std::unique_ptr<QgsProcessingFeatureSource> input2( parameterAsSource( parameters, QStringLiteral(
"INPUT_2" ), context ) );
117 const QString prefix = parameterAsString( parameters, QStringLiteral(
"PREFIX" ), context );
119 const QString field1Name = parameterAsString( parameters, QStringLiteral(
"FIELD" ), context );
120 const QString field2Name = parameterAsString( parameters, QStringLiteral(
"FIELD_2" ), context );
121 const QStringList fieldsToCopy = parameterAsStrings( parameters, QStringLiteral(
"FIELDS_TO_COPY" ), context );
123 const int joinField1Index = input->fields().lookupField( field1Name );
124 if ( joinField1Index < 0 )
125 throw QgsProcessingException( QObject::tr(
"Invalid join field from layer 1: “%1” does not exist" ).arg( field1Name ) );
127 const int joinField2Index = input2->fields().lookupField( field2Name );
128 if ( joinField2Index < 0 )
129 throw QgsProcessingException( QObject::tr(
"Invalid join field from layer 2: “%1” does not exist" ).arg( field2Name ) );
133 if ( fieldsToCopy.empty() )
135 outFields2 = input2->fields();
136 fields2Indices.reserve( outFields2.
count() );
137 for (
int i = 0; i < outFields2.
count(); ++i )
144 fields2Indices.reserve( fieldsToCopy.count() );
145 for (
const QString &field : fieldsToCopy )
147 const int index = input2->fields().
lookupField( field );
150 fields2Indices << index;
151 outFields2.
append( input2->fields().at( index ) );
156 if ( !prefix.isEmpty() )
158 for (
int i = 0; i < outFields2.
count(); ++i )
160 outFields2.
rename( i, prefix + outFields2[i].name() );
165 fields2Fetch << joinField2Index;
170 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral(
"OUTPUT" ), context, dest, outFields, input->wkbType(), input->sourceCrs(),
QgsFeatureSink::RegeneratePrimaryKey ) );
171 if ( parameters.value( QStringLiteral(
"OUTPUT" ) ).isValid() && !sink )
174 QString destNonMatching1;
175 std::unique_ptr<QgsFeatureSink> sinkNonMatching1( parameterAsSink( parameters, QStringLiteral(
"NON_MATCHING" ), context, destNonMatching1, input->fields(), input->wkbType(), input->sourceCrs(),
QgsFeatureSink::RegeneratePrimaryKey ) );
176 if ( parameters.value( QStringLiteral(
"NON_MATCHING" ) ).isValid() && !sinkNonMatching1 )
180 QMultiHash<QVariant, QgsAttributes> input2AttributeCache;
182 double step = input2->featureCount() > 0 ? 50.0 / input2->featureCount() : 1;
195 if ( joinMethod == 1 && input2AttributeCache.contains( feat.
attribute( joinField2Index ) ) )
201 for (
int j = 0; j < attributeCount; ++j )
203 if ( !fields2Indices.contains( j ) )
208 input2AttributeCache.insert( feat.
attribute( joinField2Index ), attributes );
212 step = input->featureCount() > 0 ? 50.0 / input->featureCount() : 1;
215 long long joinedCount = 0;
216 long long unjoinedCount = 0;
227 if ( input2AttributeCache.count( feat.
attribute( joinField1Index ) ) > 0 )
234 QList<QgsAttributes> attributes = input2AttributeCache.values( feat.
attribute( joinField1Index ) );
235 QList<QgsAttributes>::iterator attrsIt = attributes.begin();
236 for ( ; attrsIt != attributes.end(); ++attrsIt )
239 newAttrs.append( *attrsIt );
249 if ( sink && !discardNonMatching )
254 if ( sinkNonMatching1 )
257 throw QgsProcessingException( writeFeatureError( sinkNonMatching1.get(), parameters, QStringLiteral(
"NON_MATCHING" ) ) );
263 feedback->
pushInfo( QObject::tr(
"%n feature(s) from input layer were successfully matched",
nullptr, joinedCount ) );
264 if ( unjoinedCount > 0 )
265 feedback->
reportError( QObject::tr(
"%n feature(s) from input layer could not be matched",
nullptr, unjoinedCount ) );
271 outputs.insert( QStringLiteral(
"OUTPUT" ), dest );
273 outputs.insert( QStringLiteral(
"JOINED_COUNT" ), joinedCount );
274 outputs.insert( QStringLiteral(
"UNJOINABLE_COUNT" ), unjoinedCount );
275 if ( sinkNonMatching1 )
277 sinkNonMatching1->finalize();
278 outputs.insert( QStringLiteral(
"NON_MATCHING" ), 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.
int attributeCount() const
Returns the number of attributes attached to the 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.
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.
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
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.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
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