QGIS API Documentation  3.22.4-Białowieża (ce8e65e95e)
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 "qgslogger.h"
17 
18 #include "qgssimplifymethod.h"
19 #include "qgsexception.h"
20 #include "qgsexpressionsorter.h"
21 #include "qgsfeedback.h"
22 #include "qgscoordinatetransform.h"
23 
25  : mRequest( request )
26 {
27 }
28 
30 {
31  bool dataOk = false;
32  if ( mRequest.limit() >= 0 && mFetchedCount >= mRequest.limit() )
33  {
34  return false;
35  }
36 
38  return false;
39 
40  if ( mUseCachedFeatures )
41  {
42  if ( mFeatureIterator != mCachedFeatures.constEnd() )
43  {
44  f = mFeatureIterator->mFeature;
45  ++mFeatureIterator;
46  dataOk = true;
47  }
48  else
49  {
50  dataOk = false;
51  // even the zombie dies at this point...
52  mZombie = false;
53  }
54  }
55  else
56  {
57  switch ( mRequest.filterType() )
58  {
60  dataOk = nextFeatureFilterExpression( f );
61  break;
62 
64  dataOk = nextFeatureFilterFids( f );
65  break;
66 
67  default:
68  dataOk = fetchFeature( f );
69  break;
70  }
71  }
72 
73  if ( dataOk )
74  mFetchedCount++;
75 
76  return dataOk;
77 }
78 
80 {
81  while ( fetchFeature( f ) )
82  {
85  return true;
86  }
87  return false;
88 }
89 
91 {
92  while ( fetchFeature( f ) )
93  {
94  if ( mRequest.filterFids().contains( f.id() ) )
95  return true;
96  }
97  return false;
98 }
99 
101 {
102  if ( transform.isValid() && feature.hasGeometry() )
103  {
104  try
105  {
106  QgsGeometry g = feature.geometry();
107  g.transform( transform );
108  feature.setGeometry( g );
109  }
110  catch ( QgsCsException & )
111  {
112  // transform error
114  {
115  mRequest.transformErrorCallback()( feature );
116  }
117  // remove geometry - we can't reproject so better not return a geometry in a different crs
118  feature.clearGeometry();
119  }
120  }
121 }
122 
124 {
125  if ( mRequest.filterRect().isNull() )
126  return QgsRectangle();
127 
128  QgsCoordinateTransform extentTransform = transform;
129  extentTransform.setBallparkTransformsAreAppropriate( true );
130  return extentTransform.transformBoundingBox( mRequest.filterRect(), Qgis::TransformDirection::Reverse );
131 }
132 
134 {
135  // Prepare if required the simplification of geometries to fetch:
136  // This code runs here because of 'prepareSimplification()' is virtual and it can be overridden
137  // in inherited iterators who change the default behavior.
138  // It would be better to call this method in the constructor enabling virtual-calls as it is described by example at:
139  // http://www.parashift.com/c%2B%2B-faq-lite/calling-virtuals-from-ctor-idiom.html
140  if ( refs == 0 )
141  {
143 
144  // Should be called as last preparation step since it possibly will already fetch all features
145  setupOrderBy( mRequest.orderBy() );
146  }
147  refs++;
148 }
149 
151 {
152  refs--;
153  if ( !refs )
154  delete this;
155 }
156 
158 {
159  return mCompileFailed;
160 }
161 
163 {
164  Q_UNUSED( simplifyMethod )
165  return false;
166 }
167 
168 void QgsAbstractFeatureIterator::setupOrderBy( const QList<QgsFeatureRequest::OrderByClause> &orderBys )
169 {
170  // Let the provider try using an efficient order by strategy first
171  if ( !orderBys.isEmpty() && !prepareOrderBy( orderBys ) )
172  {
173  // No success from the provider
174 
175  // Prepare the expressions
176  QList<QgsFeatureRequest::OrderByClause> preparedOrderBys( orderBys );
177  QList<QgsFeatureRequest::OrderByClause>::iterator orderByIt( preparedOrderBys.begin() );
178 
179  QgsExpressionContext *expressionContext( mRequest.expressionContext() );
180  do
181  {
182  orderByIt->prepare( expressionContext );
183  }
184  while ( ++orderByIt != preparedOrderBys.end() );
185 
186  // Fetch all features
187  QgsIndexedFeature indexedFeature;
188  indexedFeature.mIndexes.resize( preparedOrderBys.size() );
189 
190  while ( nextFeature( indexedFeature.mFeature ) )
191  {
192  expressionContext->setFeature( indexedFeature.mFeature );
193  int i = 0;
194  const auto constPreparedOrderBys = preparedOrderBys;
195  for ( const QgsFeatureRequest::OrderByClause &orderBy : constPreparedOrderBys )
196  {
197  indexedFeature.mIndexes.replace( i++, orderBy.expression().evaluate( expressionContext ) );
198  }
199 
200  // We need all features, to ignore the limit for this pre-fetch
201  // keep the fetched count at 0.
202  mFetchedCount = 0;
203  mCachedFeatures.append( indexedFeature );
204  }
205 
206  std::sort( mCachedFeatures.begin(), mCachedFeatures.end(), QgsExpressionSorter( preparedOrderBys ) );
207 
208  mFeatureIterator = mCachedFeatures.constBegin();
209  mUseCachedFeatures = true;
210  // The real iterator is closed, we are only serving cached features
211  mZombie = true;
212  }
213 }
214 
215 bool QgsAbstractFeatureIterator::providerCanSimplify( QgsSimplifyMethod::MethodType methodType ) const
216 {
217  Q_UNUSED( methodType )
218  return false;
219 }
220 
221 bool QgsAbstractFeatureIterator::prepareOrderBy( const QList<QgsFeatureRequest::OrderByClause> &orderBys )
222 {
223  Q_UNUSED( orderBys )
224  return false;
225 }
226 
228 {
229 }
230 
232 
234 {
235  if ( this != &other )
236  {
237  if ( mIter )
238  mIter->deref();
239  mIter = other.mIter;
240  if ( mIter )
241  mIter->ref();
242  }
243  return *this;
244 }
245 
247 {
248  return mIter && mIter->isValid();
249 }
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.
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.
QgsRectangle filterRectToSourceCrs(const QgsCoordinateTransform &transform) const SIP_THROW(QgsCsException)
Returns a rectangle representing the original request's QgsFeatureRequest::filterRect().
QgsFeatureRequest mRequest
A copy of the feature request.
QgsAbstractFeatureIterator(const QgsFeatureRequest &request)
base class constructor - stores the iteration parameters
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, return 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 isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool handle180Crossover=false) const SIP_THROW(QgsCsException)
Transforms a rectangle from the source CRS to the destination CRS.
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:66
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).
const QgsSimplifyMethod & simplifyMethod() const
Returns the simplification method for geometries that will be fetched.
QgsRectangle filterRect() const
Returns the rectangle from which features will be taken.
QgsExpression * filterExpression() const
Returns the filter expression (if set).
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.
OrderBy orderBy() const
Returns a list of order by clauses specified for this feature request.
QgsExpressionContext * expressionContext()
Returns the expression context used to evaluate filter expressions.
FilterType filterType() const
Returns the attribute/ID filter type which is currently set on this request.
const QgsFeatureIds & filterFids() const
Returns the feature IDs that should be fetched.
@ FilterFids
Filter using feature IDs.
@ FilterExpression
Filter using expression.
std::function< void(const QgsFeature &) > transformErrorCallback() const
Returns the callback function to use when encountering a transform error when iterating features and ...
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:177
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:223
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:163
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:45
bool isCanceled() const SIP_HOLDGIL
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:54
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:125
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false) SIP_THROW(QgsCsException)
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 (all coordinates zero or after call to setMinimal()).
Definition: qgsrectangle.h:479
This class contains information about how to simplify geometries fetched from a QgsFeatureIterator.