QGIS API Documentation  3.18.1-Zürich (202f1bf7e5)
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
qgsvectorlayercache.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsvectorlayercache.cpp
3  Cache features of a vector layer
4  -------------------
5  begin : January 2013
6  copyright : (C) Matthias Kuhn
7  email : matthias at opengis dot ch
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 
18 #include "qgsvectorlayercache.h"
19 #include "qgscacheindex.h"
21 #include "qgsvectorlayerjoininfo.h"
23 #include "qgsvectorlayer.h"
24 
25 #include <QElapsedTimer>
26 
27 QgsVectorLayerCache::QgsVectorLayerCache( QgsVectorLayer *layer, int cacheSize, QObject *parent )
28  : QObject( parent )
29  , mLayer( layer )
30 {
31  mCache.setMaxCost( cacheSize );
32 
33  connect( mLayer, &QgsVectorLayer::featureDeleted, this, &QgsVectorLayerCache::featureDeleted );
34  connect( mLayer, &QgsVectorLayer::featureAdded, this, &QgsVectorLayerCache::onFeatureAdded );
35  connect( mLayer, &QgsVectorLayer::destroyed, this, &QgsVectorLayerCache::layerDeleted );
36 
37  setCacheGeometry( true );
40 
41  connect( mLayer, &QgsVectorLayer::attributeDeleted, this, &QgsVectorLayerCache::attributeDeleted );
42  connect( mLayer, &QgsVectorLayer::updatedFields, this, &QgsVectorLayerCache::invalidate );
43  connect( mLayer, &QgsVectorLayer::dataChanged, this, &QgsVectorLayerCache::invalidate );
44  connect( mLayer, &QgsVectorLayer::attributeValueChanged, this, &QgsVectorLayerCache::onAttributeValueChanged );
45 
46  connectJoinedLayers();
47 }
48 
50 {
51  qDeleteAll( mCacheIndices );
52  mCacheIndices.clear();
53 }
54 
55 void QgsVectorLayerCache::setCacheSize( int cacheSize )
56 {
57  mCache.setMaxCost( cacheSize );
58 }
59 
61 {
62  return mCache.maxCost();
63 }
64 
65 void QgsVectorLayerCache::setCacheGeometry( bool cacheGeometry )
66 {
67  bool shouldCacheGeometry = cacheGeometry && mLayer->isSpatial();
68  bool mustInvalidate = shouldCacheGeometry && !mCacheGeometry; // going from no geometry -> geometry, so have to clear existing cache entries
69  mCacheGeometry = shouldCacheGeometry;
70  if ( cacheGeometry )
71  {
72  connect( mLayer, &QgsVectorLayer::geometryChanged, this, &QgsVectorLayerCache::geometryChanged );
73  }
74  else
75  {
76  disconnect( mLayer, &QgsVectorLayer::geometryChanged, this, &QgsVectorLayerCache::geometryChanged );
77  }
78  if ( mustInvalidate )
79  {
80  invalidate();
81  }
82 }
83 
85 {
86  mCachedAttributes = attributes;
87 }
88 
89 void QgsVectorLayerCache::setFullCache( bool fullCache )
90 {
91  mFullCache = fullCache;
92 
93  if ( mFullCache )
94  {
95  // Add a little more than necessary...
96  setCacheSize( mLayer->featureCount() + 100 );
97 
98  // Initialize the cache...
100  .setSubsetOfAttributes( mCachedAttributes )
101  .setFlags( mCacheGeometry ? QgsFeatureRequest::NoFlags : QgsFeatureRequest::NoGeometry ) ) );
102 
103  int i = 0;
104 
105  QElapsedTimer t;
106  t.start();
107 
108  QgsFeature f;
109  while ( it.nextFeature( f ) )
110  {
111  ++i;
112 
113  if ( t.elapsed() > 1000 )
114  {
115  bool cancel = false;
116  emit progress( i, cancel );
117  if ( cancel )
118  break;
119 
120  t.restart();
121  }
122  }
123 
124  it.close();
125 
126  emit finished();
127  }
128 }
129 
131 {
132  mCacheIndices.append( cacheIndex );
133 }
134 
135 void QgsVectorLayerCache::setCacheAddedAttributes( bool cacheAddedAttributes )
136 {
137  if ( cacheAddedAttributes )
138  {
139  connect( mLayer, &QgsVectorLayer::attributeAdded, this, &QgsVectorLayerCache::attributeAdded );
140  }
141  else
142  {
143  disconnect( mLayer, &QgsVectorLayer::attributeAdded, this, &QgsVectorLayerCache::attributeAdded );
144  }
145 }
146 
147 bool QgsVectorLayerCache::featureAtId( QgsFeatureId featureId, QgsFeature &feature, bool skipCache )
148 {
149  bool featureFound = false;
150 
151  QgsCachedFeature *cachedFeature = nullptr;
152 
153  if ( !skipCache )
154  {
155  cachedFeature = mCache[ featureId ];
156  }
157 
158  if ( cachedFeature )
159  {
160  feature = QgsFeature( *cachedFeature->feature() );
161  featureFound = true;
162  }
163  else if ( mLayer->getFeatures( QgsFeatureRequest()
164  .setFilterFid( featureId )
165  .setSubsetOfAttributes( mCachedAttributes )
166  .setFlags( !mCacheGeometry ? QgsFeatureRequest::NoGeometry : QgsFeatureRequest::Flags() ) )
167  .nextFeature( feature ) )
168  {
169  cacheFeature( feature );
170  featureFound = true;
171  }
172 
173  return featureFound;
174 }
175 
177 {
178  return mCache.remove( fid );
179 }
180 
182 {
183  return mLayer;
184 }
185 
187 {
188  return mLayer->crs();
189 }
190 
192 {
193  return mLayer->wkbType();
194 }
195 
197 {
198  return mLayer->fields();
199 }
200 
202 {
203  return mLayer->featureCount();
204 }
205 
207 {
208  // If a request is too large for the cache don't notify to prevent from indexing incomplete requests
209  if ( fids.count() <= mCache.size() )
210  {
211  for ( const auto &idx : qgis::as_const( mCacheIndices ) )
212  {
213  idx->requestCompleted( featureRequest, fids );
214  }
215  if ( featureRequest.filterType() == QgsFeatureRequest::FilterNone &&
216  ( featureRequest.filterRect().isNull() || featureRequest.filterRect().contains( mLayer->extent() ) ) )
217  {
218  mFullCache = true;
219  }
220  }
221 }
222 
224 {
225  const auto constMCacheIndices = mCacheIndices;
226  for ( QgsAbstractCacheIndex *idx : constMCacheIndices )
227  {
228  idx->flushFeature( fid );
229  }
230 }
231 
232 void QgsVectorLayerCache::onAttributeValueChanged( QgsFeatureId fid, int field, const QVariant &value )
233 {
234  QgsCachedFeature *cachedFeat = mCache[ fid ];
235 
236  if ( cachedFeat )
237  {
238  cachedFeat->mFeature->setAttribute( field, value );
239  }
240 
241  emit attributeValueChanged( fid, field, value );
242 }
243 
244 void QgsVectorLayerCache::onJoinAttributeValueChanged( QgsFeatureId fid, int field, const QVariant &value )
245 {
246  const QgsVectorLayer *joinLayer = qobject_cast<const QgsVectorLayer *>( sender() );
247 
248  const auto constVectorJoins = mLayer->vectorJoins();
249  for ( const QgsVectorLayerJoinInfo &info : constVectorJoins )
250  {
251  if ( joinLayer == info.joinLayer() )
252  {
253  const QgsFeature feature = mLayer->joinBuffer()->targetedFeatureOf( &info, joinLayer->getFeature( fid ) );
254 
255  const QString fieldName = info.prefixedFieldName( joinLayer->fields().field( field ) );
256  const int fieldIndex = mLayer->fields().indexFromName( fieldName );
257 
258  if ( feature.isValid() && fieldIndex != -1 )
259  {
260  onAttributeValueChanged( feature.id(), fieldIndex, value );
261  return;
262  }
263  }
264  }
265 }
266 
267 void QgsVectorLayerCache::featureDeleted( QgsFeatureId fid )
268 {
269  mCache.remove( fid );
270 }
271 
272 void QgsVectorLayerCache::onFeatureAdded( QgsFeatureId fid )
273 {
274  if ( mFullCache )
275  {
276  if ( cacheSize() <= mLayer->featureCount() )
277  {
278  setCacheSize( mLayer->featureCount() + 100 );
279  }
280 
281  QgsFeature feat;
282  featureAtId( fid, feat );
283  }
284  emit featureAdded( fid );
285 }
286 
287 void QgsVectorLayerCache::attributeAdded( int field )
288 {
289  Q_UNUSED( field )
290  mCachedAttributes.append( field );
291  invalidate();
292 }
293 
294 void QgsVectorLayerCache::attributeDeleted( int field )
295 {
296  QgsAttributeList attrs = mCachedAttributes;
297  mCachedAttributes.clear();
298 
299  const auto constAttrs = attrs;
300  for ( int attr : constAttrs )
301  {
302  if ( attr < field )
303  mCachedAttributes << attr;
304  else if ( attr > field )
305  mCachedAttributes << attr - 1;
306  }
307 }
308 
309 void QgsVectorLayerCache::geometryChanged( QgsFeatureId fid, const QgsGeometry &geom )
310 {
311  QgsCachedFeature *cachedFeat = mCache[ fid ];
312 
313  if ( cachedFeat )
314  {
315  cachedFeat->mFeature->setGeometry( geom );
316  }
317 }
318 
319 void QgsVectorLayerCache::layerDeleted()
320 {
321  emit cachedLayerDeleted();
322  mLayer = nullptr;
323 }
324 
325 void QgsVectorLayerCache::invalidate()
326 {
327  mCache.clear();
328  mFullCache = false;
329  emit invalidated();
330 }
331 
332 bool QgsVectorLayerCache::canUseCacheForRequest( const QgsFeatureRequest &featureRequest, QgsFeatureIterator &it )
333 {
334  // check first for available indices
335  const auto constMCacheIndices = mCacheIndices;
336  for ( QgsAbstractCacheIndex *idx : constMCacheIndices )
337  {
338  if ( idx->getCacheIterator( it, featureRequest ) )
339  {
340  return true;
341  }
342  }
343 
344  // no indexes available, but maybe we have already cached all required features anyway?
345  switch ( featureRequest.filterType() )
346  {
348  {
349  if ( mCache.contains( featureRequest.filterFid() ) )
350  {
351  it = QgsFeatureIterator( new QgsCachedFeatureIterator( this, featureRequest ) );
352  return true;
353  }
354  break;
355  }
357  {
358  if ( qgis::listToSet( mCache.keys() ).contains( featureRequest.filterFids() ) )
359  {
360  it = QgsFeatureIterator( new QgsCachedFeatureIterator( this, featureRequest ) );
361  return true;
362  }
363  break;
364  }
367  {
368  if ( mFullCache )
369  {
370  it = QgsFeatureIterator( new QgsCachedFeatureIterator( this, featureRequest ) );
371  return true;
372  }
373  break;
374  }
375 
376  }
377  return false;
378 }
379 
381 {
383  bool requiresWriterIt = true; // If a not yet cached, but cacheable request is made, this stays true.
384 
385  if ( checkInformationCovered( featureRequest ) )
386  {
387  // If we have a full cache available, run on this
388  if ( mFullCache )
389  {
390  it = QgsFeatureIterator( new QgsCachedFeatureIterator( this, featureRequest ) );
391  requiresWriterIt = false;
392  }
393  else
394  {
395  // may still be able to satisfy request using cache
396  requiresWriterIt = !canUseCacheForRequest( featureRequest, it );
397  }
398  }
399  else
400  {
401  // Let the layer answer the request, so no caching of requests
402  // we don't want to cache is done
403  requiresWriterIt = false;
404  it = mLayer->getFeatures( featureRequest );
405  }
406 
407  if ( requiresWriterIt && mLayer->dataProvider() )
408  {
409  // No index was able to satisfy the request
410  QgsFeatureRequest myRequest = QgsFeatureRequest( featureRequest );
411 
412  // Make sure if we cache the geometry, it gets fetched
413  if ( mCacheGeometry && mLayer->isSpatial() )
414  myRequest.setFlags( featureRequest.flags() & ~QgsFeatureRequest::NoGeometry );
415 
416  // Make sure, all the cached attributes are requested as well
417  QSet<int> attrs = qgis::listToSet( featureRequest.subsetOfAttributes() ) + qgis::listToSet( mCachedAttributes );
418  myRequest.setSubsetOfAttributes( qgis::setToList( attrs ) );
419 
420  it = QgsFeatureIterator( new QgsCachedFeatureWriterIterator( this, myRequest ) );
421  }
422 
423  return it;
424 }
425 
427 {
428  return mCache.contains( fid );
429 }
430 
432 {
433  QgsAttributeList requestedAttributes;
434 
435  if ( !featureRequest.flags().testFlag( QgsFeatureRequest::SubsetOfAttributes ) )
436  {
437  requestedAttributes = mLayer->attributeList();
438  }
439  else
440  {
441  requestedAttributes = featureRequest.subsetOfAttributes();
442  }
443 
444  // Check if we even cache the information requested
445  const auto constRequestedAttributes = requestedAttributes;
446  for ( int attr : constRequestedAttributes )
447  {
448  if ( !mCachedAttributes.contains( attr ) )
449  {
450  return false;
451  }
452  }
453 
454  // If the request needs geometry but we don't cache this...
455  return !( !featureRequest.flags().testFlag( QgsFeatureRequest::NoGeometry )
456  && !mCacheGeometry );
457 }
458 
459 void QgsVectorLayerCache::connectJoinedLayers() const
460 {
461  const auto constVectorJoins = mLayer->vectorJoins();
462  for ( const QgsVectorLayerJoinInfo &info : constVectorJoins )
463  {
464  const QgsVectorLayer *vl = info.joinLayer();
465  if ( vl )
466  connect( vl, &QgsVectorLayer::attributeValueChanged, this, &QgsVectorLayerCache::onJoinAttributeValueChanged );
467  }
468 }
Abstract base class for cache indices.
Definition: qgscacheindex.h:32
This class represents a coordinate reference system (CRS).
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
@ SubsetOfAttributes
Fetch only a subset of attributes (setSubsetOfAttributes sets this flag)
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
QgsAttributeList subsetOfAttributes() const
Returns the subset of attributes which at least need to be fetched.
const QgsRectangle & filterRect() const
Returns the rectangle from which features will be taken.
FilterType filterType() const
Returns the filter type which is currently set on this request.
const QgsFeatureIds & filterFids() const
Gets feature IDs that should be fetched.
@ FilterFid
Filter using feature ID.
@ FilterFids
Filter using feature IDs.
@ FilterNone
No filter is applied.
@ FilterExpression
Filter using expression.
const Flags & flags() const
QgsFeatureId filterFid() const
Gets the feature ID that should be fetched.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:56
bool isValid() const
Returns the validity of this feature.
Definition: qgsfeature.cpp:190
Q_GADGET QgsFeatureId id
Definition: qgsfeature.h:64
Container of fields for a vector layer.
Definition: qgsfields.h:45
int indexFromName(const QString &fieldName) const
Gets the field index from the field name.
Definition: qgsfields.cpp:202
QgsField field(int fieldIdx) const
Gets field at particular index (must be in range 0..N-1)
Definition: qgsfields.cpp:168
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:124
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:91
void dataChanged()
Data of layer changed.
bool contains(const QgsRectangle &rect) const
Returns true when rectangle contains other rectangle.
Definition: qgsrectangle.h:342
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
Definition: qgsrectangle.h:447
bool isFidCached(QgsFeatureId fid) const
Check if a certain feature id is cached.
void setFullCache(bool fullCache)
This enables or disables full caching.
void finished()
When filling the cache, this signal gets emitted once the cache is fully initialized.
void featureRemoved(QgsFeatureId fid)
Gets called, whenever a feature has been removed.
void setCacheAddedAttributes(bool cacheAddedAttributes)
If this is enabled, the subset of cached attributes will automatically be extended to also include ne...
void invalidated()
The cache has been invalidated and cleared.
void setCacheSize(int cacheSize)
Sets the maximum number of features to keep in the cache.
void setCacheSubsetOfAttributes(const QgsAttributeList &attributes)
Set the subset of attributes to be cached.
void featureAdded(QgsFeatureId fid)
Emitted when a new feature has been added to the layer and this cache.
QgsFields fields() const
Returns the fields associated with features in the cache.
void cachedLayerDeleted()
Is emitted when the cached layer is deleted.
friend class QgsCachedFeatureWriterIterator
QgsWkbTypes::Type wkbType() const
Returns the geometry type for features in the cache.
void requestCompleted(const QgsFeatureRequest &featureRequest, const QgsFeatureIds &fids)
Gets called, whenever the full list of feature ids for a certain request is known.
void attributeValueChanged(QgsFeatureId fid, int field, const QVariant &value)
Emitted when an attribute is changed.
bool removeCachedFeature(QgsFeatureId fid)
Removes the feature identified by fid from the cache if present.
void progress(int i, bool &cancel)
When filling the cache, this signal gets emitted periodically to notify about the progress and to be ...
QgsVectorLayer * layer()
Returns the layer to which this cache belongs.
QgsCoordinateReferenceSystem sourceCrs() const
Returns the coordinate reference system for features in the cache.
bool checkInformationCovered(const QgsFeatureRequest &featureRequest)
Checks if the information required to complete the request is cached.
bool cacheGeometry() const
Returns true if the cache will fetch and cache feature geometries.
int cacheSize()
Returns the maximum number of features this cache will hold.
friend class QgsCachedFeatureIterator
void addCacheIndex(QgsAbstractCacheIndex *cacheIndex)
Adds a QgsAbstractCacheIndex to this cache.
long featureCount() const
Returns the number of features contained in the source, or -1 if the feature count is unknown.
QgsVectorLayerCache(QgsVectorLayer *layer, int cacheSize, QObject *parent=nullptr)
void setCacheGeometry(bool cacheGeometry)
Enable or disable the caching of geometries.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &featureRequest=QgsFeatureRequest())
Query this VectorLayerCache for features.
bool featureAtId(QgsFeatureId featureId, QgsFeature &feature, bool skipCache=false)
Gets the feature at the given feature id.
QgsFeature targetedFeatureOf(const QgsVectorLayerJoinInfo *info, const QgsFeature &feature) const
Returns the targeted feature corresponding to the joined feature.
Defines left outer join from our vector layer to some other vector layer.
Represents a vector layer which manages a vector based data sets.
Q_INVOKABLE QgsWkbTypes::Type wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
void attributeAdded(int idx)
Will be emitted, when a new attribute has been added to this vector layer.
bool isSpatial() const FINAL
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
QgsAttributeList attributeList() const
Returns list of attribute indexes.
QgsVectorLayerJoinBuffer * joinBuffer()
Returns the join buffer object.
void attributeDeleted(int idx)
Will be emitted, when an attribute has been deleted from this vector layer.
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider, it may be nullptr.
QgsFeature getFeature(QgsFeatureId fid) const
Queries the layer for the feature with the given id.
void attributeValueChanged(QgsFeatureId fid, int idx, const QVariant &value)
Emitted whenever an attribute value change is done in the edit buffer.
QgsRectangle extent() const FINAL
Returns the extent of the layer.
long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
void updatedFields()
Emitted whenever the fields available from this layer have been changed.
void featureAdded(QgsFeatureId fid)
Emitted when a new feature has been added to the layer.
void featureDeleted(QgsFeatureId fid)
Emitted when a feature has been deleted.
const QList< QgsVectorLayerJoinInfo > vectorJoins() const
void geometryChanged(QgsFeatureId fid, const QgsGeometry &geometry)
Emitted whenever a geometry change is done in the edit buffer.
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:70
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:37
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
Definition: qgsfeatureid.h:28
QList< int > QgsAttributeList
Definition: qgsfield.h:26
const QgsField & field
Definition: qgsfield.h:472