QGIS API Documentation 3.37.0-Master (fdefdf9c27f)
qgsfeatureiterator.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsfeatureiterator.cpp
3 ---------------------
4 begin : Juli 2012
5 copyright : (C) 2012 by Martin Dobias
6 email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15#include "qgsfeatureiterator.h"
16#include "qgssimplifymethod.h"
17#include "qgsexception.h"
19#include "qgsfeedback.h"
21
23 : mRequest( request )
24{
25}
26
28{
29 bool dataOk = false;
30 if ( mRequest.limit() >= 0 && mFetchedCount >= mRequest.limit() )
31 {
32 return false;
33 }
34
36 return false;
37
38 if ( mUseCachedFeatures )
39 {
40 if ( mFeatureIterator != mCachedFeatures.constEnd() )
41 {
42 f = mFeatureIterator->mFeature;
43 ++mFeatureIterator;
44 dataOk = true;
45 }
46 else
47 {
48 dataOk = false;
49 // even the zombie dies at this point...
50 mZombie = false;
51 }
52 }
53 else
54 {
55 switch ( mRequest.filterType() )
56 {
58 dataOk = nextFeatureFilterExpression( f );
59 break;
60
62 dataOk = nextFeatureFilterFids( f );
63 break;
64
65 default:
66 dataOk = fetchFeature( f );
67 break;
68 }
69 }
70
71 if ( dataOk )
73
74 return dataOk;
75}
76
78{
79 while ( fetchFeature( f ) )
80 {
83 return true;
84 }
85 return false;
86}
87
89{
90 while ( fetchFeature( f ) )
91 {
92 if ( mRequest.filterFids().contains( f.id() ) )
93 return true;
94 }
95 return false;
96}
97
99{
100 if ( transform.isValid() && feature.hasGeometry() )
101 {
102 try
103 {
104 QgsGeometry g = feature.geometry();
105 g.transform( transform );
106 feature.setGeometry( g );
107 }
108 catch ( QgsCsException & )
109 {
110 // transform error
112 {
113 mRequest.transformErrorCallback()( feature );
114 }
115 // remove geometry - we can't reproject so better not return a geometry in a different crs
116 feature.clearGeometry();
117 }
118 }
119}
120
122{
123 if ( transform.isShortCircuited() )
124 return RequestToSourceCrsResult::Success; // nothing to do
125
126 switch ( request.spatialFilterType() )
127 {
130
132 {
134 request.setFilterRect( newRect );
136 }
137
139 {
140 // we can't safely handle a distance within query, as we cannot transform the
141 // static within tolerance distance from one CRS to a static distance in a different CRS.
142
143 // in this case we transform the request's distance within requirement to a "worst case" bounding box filter, so
144 // that the request itself can still take advantage of spatial indices even when we have to do the distance within check locally
146 request.setFilterRect( newRect );
147
149 }
150 }
151
153}
154
156{
157 if ( mRequest.filterRect().isNull() )
158 return QgsRectangle();
159
160 QgsCoordinateTransform extentTransform = transform;
161 extentTransform.setBallparkTransformsAreAppropriate( true );
163}
164
166{
167 // Prepare if required the simplification of geometries to fetch:
168 // This code runs here because of 'prepareSimplification()' is virtual and it can be overridden
169 // in inherited iterators who change the default behavior.
170 // It would be better to call this method in the constructor enabling virtual-calls as it is described by example at:
171 // http://www.parashift.com/c%2B%2B-faq-lite/calling-virtuals-from-ctor-idiom.html
172 if ( refs == 0 )
173 {
175
176 // Should be called as last preparation step since it possibly will already fetch all features
177 setupOrderBy( mRequest.orderBy() );
178 }
179 refs++;
180}
181
183{
184 refs--;
185 if ( !refs )
186 delete this;
187}
188
190{
191 return mCompileFailed;
192}
193
195{
196 Q_UNUSED( simplifyMethod )
197 return false;
198}
199
200void QgsAbstractFeatureIterator::setupOrderBy( const QList<QgsFeatureRequest::OrderByClause> &orderBys )
201{
202 // Let the provider try using an efficient order by strategy first
203 if ( !orderBys.isEmpty() && !prepareOrderBy( orderBys ) )
204 {
205 // No success from the provider
206
207 // Prepare the expressions
208 QList<QgsFeatureRequest::OrderByClause> preparedOrderBys( orderBys );
209 QList<QgsFeatureRequest::OrderByClause>::iterator orderByIt( preparedOrderBys.begin() );
210
211 QgsExpressionContext *expressionContext( mRequest.expressionContext() );
212 do
213 {
214 orderByIt->prepare( expressionContext );
215 }
216 while ( ++orderByIt != preparedOrderBys.end() );
217
218 // Fetch all features
219 QgsIndexedFeature indexedFeature;
220 indexedFeature.mIndexes.resize( preparedOrderBys.size() );
221
222 while ( nextFeature( indexedFeature.mFeature ) )
223 {
224 expressionContext->setFeature( indexedFeature.mFeature );
225 int i = 0;
226 const auto constPreparedOrderBys = preparedOrderBys;
227 for ( const QgsFeatureRequest::OrderByClause &orderBy : constPreparedOrderBys )
228 {
229 indexedFeature.mIndexes.replace( i++, orderBy.expression().evaluate( expressionContext ) );
230 }
231
232 // We need all features, to ignore the limit for this pre-fetch
233 // keep the fetched count at 0.
234 mFetchedCount = 0;
235 mCachedFeatures.append( indexedFeature );
236 }
237
238 std::sort( mCachedFeatures.begin(), mCachedFeatures.end(), QgsExpressionSorter( preparedOrderBys ) );
239
240 mFeatureIterator = mCachedFeatures.constBegin();
241 mUseCachedFeatures = true;
242 // The real iterator is closed, we are only serving cached features
243 mZombie = true;
244 }
245}
246
247bool QgsAbstractFeatureIterator::providerCanSimplify( QgsSimplifyMethod::MethodType methodType ) const
248{
249 Q_UNUSED( methodType )
250 return false;
251}
252
253bool QgsAbstractFeatureIterator::prepareOrderBy( const QList<QgsFeatureRequest::OrderByClause> &orderBys )
254{
255 Q_UNUSED( orderBys )
256 return false;
257}
258
260{
261}
262
264
266{
267 if ( this != &other )
268 {
269 if ( mIter )
270 mIter->deref();
271 mIter = other.mIter;
272 if ( mIter )
273 mIter->ref();
274 }
275 return *this;
276}
277
279{
280 return mIter && mIter->isValid();
281}
@ Fids
Filter using feature IDs.
@ Expression
Filter using expression.
@ DistanceWithin
Filter by distance to reference geometry.
@ BoundingBox
Filter using a bounding box.
@ NoFilter
No spatial filtering of features.
@ Reverse
Reverse/inverse transform (from destination to source)
RequestToSourceCrsResult
Possible results from the updateRequestToSourceCrs() method.
@ Success
Request was successfully updated to the source CRS, or no changes were required.
@ DistanceWithinMustBeCheckedManually
The distance within request cannot be losslessly updated to the source CRS, and callers will need to ...
bool mZombie
A feature iterator may be closed already but still be serving features from the cache.
virtual bool nextFeatureFilterFids(QgsFeature &f)
By default, the iterator will fetch all features and check if the id is in the request.
void geometryToDestinationCrs(QgsFeature &feature, const QgsCoordinateTransform &transform) const
Transforms feature's geometry according to the specified coordinate transform.
QgsRectangle filterRectToSourceCrs(const QgsCoordinateTransform &transform) const
Returns a rectangle representing the original request's QgsFeatureRequest::filterRect().
virtual void setInterruptionChecker(QgsFeedback *interruptionChecker)
Attach an object that can be queried regularly by the iterator to check if it must stopped.
virtual bool fetchFeature(QgsFeature &f)=0
If you write a feature iterator for your provider, this is the method you need to implement!...
long long mFetchedCount
Number of features already fetched by iterator.
virtual bool prepareSimplification(const QgsSimplifyMethod &simplifyMethod)
Setup the simplification of geometries to fetch using the specified simplify method.
void deref()
Remove reference, delete if refs == 0.
QgsFeatureRequest mRequest
A copy of the feature request.
QgsAbstractFeatureIterator(const QgsFeatureRequest &request)
base class constructor - stores the iteration parameters
RequestToSourceCrsResult updateRequestToSourceCrs(QgsFeatureRequest &request, const QgsCoordinateTransform &transform) const
Update a QgsFeatureRequest so that spatial filters are transformed to the source's coordinate referen...
bool compileFailed() const
Indicator if there was an error when sending the compiled query to the server.
virtual bool isValid() const
Returns if this iterator is valid.
int refs
reference counting (to allow seamless copying of QgsFeatureIterator instances)
virtual bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
virtual bool nextFeatureFilterExpression(QgsFeature &f)
By default, the iterator will fetch all features and check if the feature matches the expression.
Class for doing transforms between two map coordinate systems.
void setBallparkTransformsAreAppropriate(bool appropriate)
Sets whether approximate "ballpark" results are appropriate for this coordinate transform.
bool isShortCircuited() const
Returns true if the transform short circuits because the source and destination are equivalent.
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool handle180Crossover=false) const
Transforms a rectangle from the source CRS to the destination CRS.
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:67
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.
QVariant evaluate()
Evaluate the feature and return the result.
Wrapper for iterator of features from vector data provider or vector layer.
QgsAbstractFeatureIterator * mIter
QgsFeatureIterator & operator=(const QgsFeatureIterator &other)
bool isValid() const
Will return if this iterator is valid.
The OrderByClause class represents an order by clause for a QgsFeatureRequest.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsRectangle filterRect() const
Returns the rectangle from which features will be taken.
QgsFeedback * feedback() const
Returns the feedback object that can be queried regularly by the iterator to check if it should be ca...
long long limit() const
Returns the maximum number of features to request, or -1 if no limit set.
QgsExpressionContext * expressionContext()
Returns the expression context used to evaluate filter expressions.
std::function< void(const QgsFeature &) > transformErrorCallback() const
Returns the callback function to use when encountering a transform error when iterating features and ...
OrderBy orderBy() const
Returns a list of order by clauses specified for this feature request.
Qgis::FeatureRequestFilterType filterType() const
Returns the attribute/ID filter type which is currently set on this request.
QgsExpression * filterExpression() const
Returns the filter expression (if set).
const QgsSimplifyMethod & simplifyMethod() const
Returns the simplification method for geometries that will be fetched.
Qgis::SpatialFilterType spatialFilterType() const
Returns the spatial filter type which is currently set on this request.
const QgsFeatureIds & filterFids() const
Returns the feature IDs that should be fetched.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
QgsGeometry geometry
Definition: qgsfeature.h:67
void clearGeometry()
Removes any geometry associated with the feature.
Definition: qgsfeature.cpp:181
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:230
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:167
Q_GADGET QgsFeatureId id
Definition: qgsfeature.h:64
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition: qgsfeedback.h:44
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:53
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:162
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
Temporarily used structure to cache order by information.
QVector< QVariant > mIndexes
A rectangle specified with double values.
Definition: qgsrectangle.h:42
bool isNull() const
Test if the rectangle is null (holding no spatial information).
Definition: qgsrectangle.h:505
This class contains information about how to simplify geometries fetched from a QgsFeatureIterator.
#define BUILTIN_UNREACHABLE
Definition: qgis.h:5853