QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
qgsalgorithmextractbyattribute.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmextractbyattribute.cpp
3 ----------------------------------
4 begin : April 2017
5 copyright : (C) 2017 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
20#include <QString>
21
22using namespace Qt::StringLiterals;
23
25
26QString QgsExtractByAttributeAlgorithm::name() const
27{
28 return u"extractbyattribute"_s;
29}
30
31QString QgsExtractByAttributeAlgorithm::displayName() const
32{
33 return QObject::tr( "Extract by attribute" );
34}
35
36QStringList QgsExtractByAttributeAlgorithm::tags() const
37{
38 return QObject::tr( "extract,filter,attribute,value,contains,null,field" ).split( ',' );
39}
40
41QString QgsExtractByAttributeAlgorithm::group() const
42{
43 return QObject::tr( "Vector selection" );
44}
45
46QString QgsExtractByAttributeAlgorithm::groupId() const
47{
48 return u"vectorselection"_s;
49}
50
51void QgsExtractByAttributeAlgorithm::initAlgorithm( const QVariantMap & )
52{
53 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
54 addParameter( new QgsProcessingParameterField( u"FIELD"_s, QObject::tr( "Selection attribute" ), QVariant(), u"INPUT"_s ) );
55 addParameter( new QgsProcessingParameterEnum( u"OPERATOR"_s, QObject::tr( "Operator" ), QStringList() << QObject::tr( "=" ) << QObject::tr( "≠" ) << QObject::tr( ">" ) << QObject::tr( "≥" ) << QObject::tr( "<" ) << QObject::tr( "≤" ) << QObject::tr( "begins with" ) << QObject::tr( "contains" ) << QObject::tr( "is null" ) << QObject::tr( "is not null" ) << QObject::tr( "does not contain" ), false, 0 ) );
56 addParameter( new QgsProcessingParameterString( u"VALUE"_s, QObject::tr( "Value" ), QVariant(), false, true ) );
57
58 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Extracted (attribute)" ) ) );
59 QgsProcessingParameterFeatureSink *failOutput = new QgsProcessingParameterFeatureSink( u"FAIL_OUTPUT"_s, QObject::tr( "Extracted (non-matching)" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true );
60 failOutput->setCreateByDefault( false );
61 addParameter( failOutput );
62}
63
64QString QgsExtractByAttributeAlgorithm::shortHelpString() const
65{
66 return QObject::tr( "This algorithm creates a new vector layer that only contains matching features from an input layer. "
67 "The criteria for adding features to the resulting layer is defined based on the values "
68 "of an attribute from the input layer." );
69}
70
71QString QgsExtractByAttributeAlgorithm::shortDescription() const
72{
73 return QObject::tr( "Creates a vector layer that only contains features matching an attribute value from an input layer." );
74}
75
76QgsExtractByAttributeAlgorithm *QgsExtractByAttributeAlgorithm::createInstance() const
77{
78 return new QgsExtractByAttributeAlgorithm();
79}
80
81QVariantMap QgsExtractByAttributeAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
82{
83 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
84 if ( !source )
85 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
86
87 const QString fieldName = parameterAsString( parameters, u"FIELD"_s, context );
88 const Operation op = static_cast<Operation>( parameterAsEnum( parameters, u"OPERATOR"_s, context ) );
89 const QString value = parameterAsString( parameters, u"VALUE"_s, context );
90
91 QString matchingSinkId;
92 std::unique_ptr<QgsFeatureSink> matchingSink( parameterAsSink( parameters, u"OUTPUT"_s, context, matchingSinkId, source->fields(), source->wkbType(), source->sourceCrs() ) );
93 if ( !matchingSink )
94 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
95
96 QString nonMatchingSinkId;
97 std::unique_ptr<QgsFeatureSink> nonMatchingSink( parameterAsSink( parameters, u"FAIL_OUTPUT"_s, context, nonMatchingSinkId, source->fields(), source->wkbType(), source->sourceCrs() ) );
98
99 const int idx = source->fields().lookupField( fieldName );
100 if ( idx < 0 )
101 throw QgsProcessingException( QObject::tr( "Field '%1' was not found in INPUT source" ).arg( fieldName ) );
102
103 const QMetaType::Type fieldType = source->fields().at( idx ).type();
104
105 if ( fieldType != QMetaType::Type::QString && ( op == BeginsWith || op == Contains || op == DoesNotContain ) )
106 {
107 QString method;
108 switch ( op )
109 {
110 case BeginsWith:
111 method = QObject::tr( "begins with" );
112 break;
113 case Contains:
114 method = QObject::tr( "contains" );
115 break;
116 case DoesNotContain:
117 method = QObject::tr( "does not contain" );
118 break;
119
120 default:
121 break;
122 }
123
124 throw QgsProcessingException( QObject::tr( "Operator '%1' can be used only with string fields." ).arg( method ) );
125 }
126
127 const QString fieldRef = QgsExpression::quotedColumnRef( fieldName );
128 const QString quotedVal = QgsExpression::quotedValue( value );
129 QString expr;
130 switch ( op )
131 {
132 case Equals:
133 expr = u"%1 = %3"_s.arg( fieldRef, quotedVal );
134 break;
135 case NotEquals:
136 expr = u"%1 != %3"_s.arg( fieldRef, quotedVal );
137 break;
138 case GreaterThan:
139 expr = u"%1 > %3"_s.arg( fieldRef, quotedVal );
140 break;
141 case GreaterThanEqualTo:
142 expr = u"%1 >= %3"_s.arg( fieldRef, quotedVal );
143 break;
144 case LessThan:
145 expr = u"%1 < %3"_s.arg( fieldRef, quotedVal );
146 break;
147 case LessThanEqualTo:
148 expr = u"%1 <= %3"_s.arg( fieldRef, quotedVal );
149 break;
150 case BeginsWith:
151 expr = u"%1 LIKE '%2%'"_s.arg( fieldRef, value );
152 break;
153 case Contains:
154 expr = u"%1 LIKE '%%2%'"_s.arg( fieldRef, value );
155 break;
156 case IsNull:
157 expr = u"%1 IS NULL"_s.arg( fieldRef );
158 break;
159 case IsNotNull:
160 expr = u"%1 IS NOT NULL"_s.arg( fieldRef );
161 break;
162 case DoesNotContain:
163 expr = u"%1 NOT LIKE '%%2%'"_s.arg( fieldRef, value );
164 break;
165 }
166
167 QgsExpression expression( expr );
168 if ( expression.hasParserError() )
169 {
170 throw QgsProcessingException( expression.parserErrorString() );
171 }
172
173 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, source.get() );
174
175 const long count = source->featureCount();
176
177 const double step = count > 0 ? 100.0 / count : 1;
178 int current = 0;
179
180 if ( !nonMatchingSink )
181 {
182 // not saving failing features - so only fetch good features
184 req.setFilterExpression( expr );
185 req.setExpressionContext( expressionContext );
186
188 QgsFeature f;
189 while ( it.nextFeature( f ) )
190 {
191 if ( feedback->isCanceled() )
192 {
193 break;
194 }
195
196 if ( !matchingSink->addFeature( f, QgsFeatureSink::FastInsert ) )
197 throw QgsProcessingException( writeFeatureError( matchingSink.get(), parameters, u"OUTPUT"_s ) );
198
199 feedback->setProgress( current * step );
200 current++;
201 }
202 }
203 else
204 {
205 // saving non-matching features, so we need EVERYTHING
206 expressionContext.setFields( source->fields() );
207 expression.prepare( &expressionContext );
208
210 QgsFeature f;
211 while ( it.nextFeature( f ) )
212 {
213 if ( feedback->isCanceled() )
214 {
215 break;
216 }
217
218 expressionContext.setFeature( f );
219 if ( expression.evaluate( &expressionContext ).toBool() )
220 {
221 if ( !matchingSink->addFeature( f, QgsFeatureSink::FastInsert ) )
222 throw QgsProcessingException( writeFeatureError( matchingSink.get(), parameters, u"OUTPUT"_s ) );
223 }
224 else
225 {
226 if ( !nonMatchingSink->addFeature( f, QgsFeatureSink::FastInsert ) )
227 throw QgsProcessingException( writeFeatureError( nonMatchingSink.get(), parameters, u"FAIL_OUTPUT"_s ) );
228 }
229
230 feedback->setProgress( current * step );
231 current++;
232 }
233 }
234
235 if ( matchingSink )
236 matchingSink->finalize();
237 if ( nonMatchingSink )
238 nonMatchingSink->finalize();
239
240 QVariantMap outputs;
241 outputs.insert( u"OUTPUT"_s, matchingSinkId );
242 if ( nonMatchingSink )
243 outputs.insert( u"FAIL_OUTPUT"_s, nonMatchingSinkId );
244 return outputs;
245}
246
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3610
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3604
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3782
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
Handles parsing and evaluation of expressions (formerly called "search strings").
static QString quotedValue(const QVariant &value)
Returns a string representation of a literal value, including appropriate quotations where required.
static QString quotedColumnRef(QString name)
Returns a quoted column reference (in double quotes).
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 & setFilterExpression(const QString &expression)
Set the filter expression.
QgsFeatureRequest & setExpressionContext(const QgsExpressionContext &context)
Sets the expression context used to evaluate filter expressions.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
Contains information about the context in which a processing algorithm is executed.
void setCreateByDefault(bool createByDefault)
Sets whether the destination should be created by default.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
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.