QGIS API Documentation  3.14.0-Pi (9f7028fd23)
qgsvectorlayerutils.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsvectorlayerutils.cpp
3  -----------------------
4  Date : October 2016
5  Copyright : (C) 2016 by Nyall Dawson
6  Email : nyall dot dawson 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 
16 #include <QRegularExpression>
17 
18 #include "qgsexpressioncontext.h"
19 #include "qgsfeatureiterator.h"
20 #include "qgsfeaturerequest.h"
21 #include "qgsvectorlayerutils.h"
22 #include "qgsvectordataprovider.h"
23 #include "qgsproject.h"
24 #include "qgsrelationmanager.h"
25 #include "qgsfeedback.h"
26 #include "qgsvectorlayer.h"
27 #include "qgsthreadingutils.h"
28 #include "qgsgeometrycollection.h"
30 #include "qgsmultisurface.h"
31 #include "qgsgeometryfactory.h"
32 #include "qgscurvepolygon.h"
33 #include "qgspolygon.h"
34 #include "qgslinestring.h"
35 #include "qgsmultipoint.h"
37 #include "qgsvectorlayerlabeling.h"
38 #include "qgspallabeling.h"
39 #include "qgsrenderer.h"
40 #include "qgssymbollayer.h"
41 #include "qgsstyleentityvisitor.h"
42 #include "qgsstyle.h"
43 
44 QgsFeatureIterator QgsVectorLayerUtils::getValuesIterator( const QgsVectorLayer *layer, const QString &fieldOrExpression, bool &ok, bool selectedOnly )
45 {
46  std::unique_ptr<QgsExpression> expression;
47  QgsExpressionContext context;
48 
49  int attrNum = layer->fields().lookupField( fieldOrExpression );
50  if ( attrNum == -1 )
51  {
52  // try to use expression
53  expression.reset( new QgsExpression( fieldOrExpression ) );
55 
56  if ( expression->hasParserError() || !expression->prepare( &context ) )
57  {
58  ok = false;
59  return QgsFeatureIterator();
60  }
61  }
62 
63  QSet<QString> lst;
64  if ( !expression )
65  lst.insert( fieldOrExpression );
66  else
67  lst = expression->referencedColumns();
68 
70  .setFlags( ( expression && expression->needsGeometry() ) ?
73  .setSubsetOfAttributes( lst, layer->fields() );
74 
75  ok = true;
76  if ( !selectedOnly )
77  {
78  return layer->getFeatures( request );
79  }
80  else
81  {
82  return layer->getSelectedFeatures( request );
83  }
84 }
85 
86 QList<QVariant> QgsVectorLayerUtils::getValues( const QgsVectorLayer *layer, const QString &fieldOrExpression, bool &ok, bool selectedOnly, QgsFeedback *feedback )
87 {
88  QList<QVariant> values;
89  QgsFeatureIterator fit = getValuesIterator( layer, fieldOrExpression, ok, selectedOnly );
90  if ( ok )
91  {
92  std::unique_ptr<QgsExpression> expression;
93  QgsExpressionContext context;
94 
95  int attrNum = layer->fields().lookupField( fieldOrExpression );
96  if ( attrNum == -1 )
97  {
98  // use expression, already validated in the getValuesIterator() function
99  expression.reset( new QgsExpression( fieldOrExpression ) );
101  }
102 
103  QgsFeature f;
104  while ( fit.nextFeature( f ) )
105  {
106  if ( expression )
107  {
108  context.setFeature( f );
109  QVariant v = expression->evaluate( &context );
110  values << v;
111  }
112  else
113  {
114  values << f.attribute( attrNum );
115  }
116  if ( feedback && feedback->isCanceled() )
117  {
118  ok = false;
119  return values;
120  }
121  }
122  }
123  return values;
124 }
125 
126 QList<double> QgsVectorLayerUtils::getDoubleValues( const QgsVectorLayer *layer, const QString &fieldOrExpression, bool &ok, bool selectedOnly, int *nullCount, QgsFeedback *feedback )
127 {
128  QList<double> values;
129 
130  if ( nullCount )
131  *nullCount = 0;
132 
133  QList<QVariant> variantValues = getValues( layer, fieldOrExpression, ok, selectedOnly, feedback );
134  if ( !ok )
135  return values;
136 
137  bool convertOk;
138  const auto constVariantValues = variantValues;
139  for ( const QVariant &value : constVariantValues )
140  {
141  double val = value.toDouble( &convertOk );
142  if ( convertOk )
143  values << val;
144  else if ( value.isNull() )
145  {
146  if ( nullCount )
147  *nullCount += 1;
148  }
149  if ( feedback && feedback->isCanceled() )
150  {
151  ok = false;
152  return values;
153  }
154  }
155  return values;
156 }
157 
158 bool QgsVectorLayerUtils::valueExists( const QgsVectorLayer *layer, int fieldIndex, const QVariant &value, const QgsFeatureIds &ignoreIds )
159 {
160  if ( !layer )
161  return false;
162 
163  QgsFields fields = layer->fields();
164 
165  if ( fieldIndex < 0 || fieldIndex >= fields.count() )
166  return false;
167 
168  // If it's a joined field search the value in the source layer
169  if ( fields.fieldOrigin( fieldIndex ) == QgsFields::FieldOrigin::OriginJoin )
170  {
171  int srcFieldIndex;
172  const QgsVectorLayerJoinInfo *joinInfo { layer->joinBuffer()->joinForFieldIndex( fieldIndex, fields, srcFieldIndex ) };
173  if ( ! joinInfo )
174  {
175  return false;
176  }
177  fieldIndex = srcFieldIndex;
178  layer = joinInfo->joinLayer();
179  if ( ! layer )
180  {
181  return false;
182  }
183  fields = layer->fields();
184  }
185 
186  QString fieldName = fields.at( fieldIndex ).name();
187 
188  // build up an optimised feature request
189  QgsFeatureRequest request;
190  request.setNoAttributes();
192 
193  // at most we need to check ignoreIds.size() + 1 - the feature not in ignoreIds is the one we're interested in
194  int limit = ignoreIds.size() + 1;
195  request.setLimit( limit );
196 
197  request.setFilterExpression( QStringLiteral( "%1=%2" ).arg( QgsExpression::quotedColumnRef( fieldName ),
198  QgsExpression::quotedValue( value ) ) );
199 
200  QgsFeature feat;
201  QgsFeatureIterator it = layer->getFeatures( request );
202  while ( it.nextFeature( feat ) )
203  {
204  if ( ignoreIds.contains( feat.id() ) )
205  continue;
206 
207  return true;
208  }
209 
210  return false;
211 }
212 
213 QVariant QgsVectorLayerUtils::createUniqueValue( const QgsVectorLayer *layer, int fieldIndex, const QVariant &seed )
214 {
215  if ( !layer )
216  return QVariant();
217 
218  QgsFields fields = layer->fields();
219 
220  if ( fieldIndex < 0 || fieldIndex >= fields.count() )
221  return QVariant();
222 
223  QgsField field = fields.at( fieldIndex );
224 
225  if ( field.isNumeric() )
226  {
227  QVariant maxVal = layer->maximumValue( fieldIndex );
228  QVariant newVar( maxVal.toLongLong() + 1 );
229  if ( field.convertCompatible( newVar ) )
230  return newVar;
231  else
232  return QVariant();
233  }
234  else
235  {
236  switch ( field.type() )
237  {
238  case QVariant::String:
239  {
240  QString base;
241  if ( seed.isValid() )
242  base = seed.toString();
243 
244  if ( !base.isEmpty() )
245  {
246  // strip any existing _1, _2 from the seed
247  QRegularExpression rx( QStringLiteral( "(.*)_\\d+" ) );
248  QRegularExpressionMatch match = rx.match( base );
249  if ( match.hasMatch() )
250  {
251  base = match.captured( 1 );
252  }
253  }
254  else
255  {
256  // no base seed - fetch first value from layer
257  QgsFeatureRequest req;
258  req.setLimit( 1 );
259  req.setSubsetOfAttributes( QgsAttributeList() << fieldIndex );
261  QgsFeature f;
262  layer->getFeatures( req ).nextFeature( f );
263  base = f.attribute( fieldIndex ).toString();
264  }
265 
266  // try variants like base_1, base_2, etc until a new value found
267  QStringList vals = layer->uniqueStringsMatching( fieldIndex, base );
268 
269  // might already be unique
270  if ( !base.isEmpty() && !vals.contains( base ) )
271  return base;
272 
273  for ( int i = 1; i < 10000; ++i )
274  {
275  QString testVal = base + '_' + QString::number( i );
276  if ( !vals.contains( testVal ) )
277  return testVal;
278  }
279 
280  // failed
281  return QVariant();
282  }
283 
284  default:
285  // todo other types - dates? times?
286  break;
287  }
288  }
289 
290  return QVariant();
291 }
292 
293 QVariant QgsVectorLayerUtils::createUniqueValueFromCache( const QgsVectorLayer *layer, int fieldIndex, const QSet<QVariant> &existingValues, const QVariant &seed )
294 {
295  if ( !layer )
296  return QVariant();
297 
298  QgsFields fields = layer->fields();
299 
300  if ( fieldIndex < 0 || fieldIndex >= fields.count() )
301  return QVariant();
302 
303  QgsField field = fields.at( fieldIndex );
304 
305  if ( field.isNumeric() )
306  {
307  QVariant maxVal = existingValues.isEmpty() ? 0 : *std::max_element( existingValues.begin(), existingValues.end() );
308  QVariant newVar( maxVal.toLongLong() + 1 );
309  if ( field.convertCompatible( newVar ) )
310  return newVar;
311  else
312  return QVariant();
313  }
314  else
315  {
316  switch ( field.type() )
317  {
318  case QVariant::String:
319  {
320  QString base;
321  if ( seed.isValid() )
322  base = seed.toString();
323 
324  if ( !base.isEmpty() )
325  {
326  // strip any existing _1, _2 from the seed
327  QRegularExpression rx( QStringLiteral( "(.*)_\\d+" ) );
328  QRegularExpressionMatch match = rx.match( base );
329  if ( match.hasMatch() )
330  {
331  base = match.captured( 1 );
332  }
333  }
334  else
335  {
336  // no base seed - fetch first value from layer
337  QgsFeatureRequest req;
338  base = existingValues.isEmpty() ? QString() : existingValues.values().first().toString();
339  }
340 
341  // try variants like base_1, base_2, etc until a new value found
342  QStringList vals;
343  for ( const auto &v : qgis::as_const( existingValues ) )
344  {
345  if ( v.toString().startsWith( base ) )
346  vals.push_back( v.toString() );
347  }
348 
349  // might already be unique
350  if ( !base.isEmpty() && !vals.contains( base ) )
351  return base;
352 
353  for ( int i = 1; i < 10000; ++i )
354  {
355  QString testVal = base + '_' + QString::number( i );
356  if ( !vals.contains( testVal ) )
357  return testVal;
358  }
359 
360  // failed
361  return QVariant();
362  }
363 
364  default:
365  // todo other types - dates? times?
366  break;
367  }
368  }
369 
370  return QVariant();
371 
372 }
373 
374 bool QgsVectorLayerUtils::validateAttribute( const QgsVectorLayer *layer, const QgsFeature &feature, int attributeIndex, QStringList &errors,
376 {
377  if ( !layer )
378  return false;
379 
380  if ( attributeIndex < 0 || attributeIndex >= layer->fields().count() )
381  return false;
382 
383  QgsFields fields = layer->fields();
384  QgsField field = fields.at( attributeIndex );
385  QVariant value = feature.attribute( attributeIndex );
386  bool valid = true;
387  errors.clear();
388 
389  QgsFieldConstraints constraints = field.constraints();
390 
391  if ( constraints.constraints() & QgsFieldConstraints::ConstraintExpression && !constraints.constraintExpression().isEmpty()
394  {
396  context.setFeature( feature );
397 
398  QgsExpression expr( constraints.constraintExpression() );
399 
400  valid = expr.evaluate( &context ).toBool();
401 
402  if ( expr.hasParserError() )
403  {
404  errors << QObject::tr( "parser error: %1" ).arg( expr.parserErrorString() );
405  }
406  else if ( expr.hasEvalError() )
407  {
408  errors << QObject::tr( "evaluation error: %1" ).arg( expr.evalErrorString() );
409  }
410  else if ( !valid )
411  {
412  errors << QObject::tr( "%1 check failed" ).arg( constraints.constraintDescription() );
413  }
414  }
415 
416  bool notNullConstraintViolated { false };
417 
421  {
422  bool exempt = false;
423  if ( fields.fieldOrigin( attributeIndex ) == QgsFields::OriginProvider
425  {
426  int providerIdx = fields.fieldOriginIndex( attributeIndex );
427  exempt = layer->dataProvider()->skipConstraintCheck( providerIdx, QgsFieldConstraints::ConstraintNotNull, value );
428  }
429 
430  if ( !exempt )
431  {
432  valid = valid && !value.isNull();
433 
434  if ( value.isNull() )
435  {
436  errors << QObject::tr( "value is NULL" );
437  notNullConstraintViolated = true;
438  }
439  }
440  }
441 
442  // if a NOT NULL constraint is violated we don't need to check for UNIQUE
443  if ( ! notNullConstraintViolated )
444  {
445 
449  {
450  bool exempt = false;
451  if ( fields.fieldOrigin( attributeIndex ) == QgsFields::OriginProvider
453  {
454  int providerIdx = fields.fieldOriginIndex( attributeIndex );
455  exempt = layer->dataProvider()->skipConstraintCheck( providerIdx, QgsFieldConstraints::ConstraintUnique, value );
456  }
457 
458  if ( !exempt )
459  {
460 
461  bool alreadyExists = QgsVectorLayerUtils::valueExists( layer, attributeIndex, value, QgsFeatureIds() << feature.id() );
462  valid = valid && !alreadyExists;
463 
464  if ( alreadyExists )
465  {
466  errors << QObject::tr( "value is not unique" );
467  }
468  }
469  }
470  }
471 
472  return valid;
473 }
474 
476  const QgsAttributeMap &attributes, QgsExpressionContext *context )
477 {
478  QgsFeatureList features { createFeatures( layer, QgsFeaturesDataList() << QgsFeatureData( geometry, attributes ), context ) };
479  return features.isEmpty() ? QgsFeature() : features.first();
480 }
481 
483 {
484  if ( !layer )
485  return QgsFeatureList();
486 
487  QgsFeatureList result;
488  result.reserve( featuresData.length() );
489 
490  QgsExpressionContext *evalContext = context;
491  std::unique_ptr< QgsExpressionContext > tempContext;
492  if ( !evalContext )
493  {
494  // no context passed, so we create a default one
496  evalContext = tempContext.get();
497  }
498 
499  QgsFields fields = layer->fields();
500 
501  // Cache unique values
502  QMap<int, QSet<QVariant>> uniqueValueCache;
503 
504  auto checkUniqueValue = [ & ]( const int fieldIdx, const QVariant & value )
505  {
506  if ( ! uniqueValueCache.contains( fieldIdx ) )
507  {
508  // If the layer is filtered, get unique values from an unfiltered clone
509  if ( ! layer->subsetString().isEmpty() )
510  {
511  std::unique_ptr<QgsVectorLayer> unfilteredClone { layer->clone( ) };
512  unfilteredClone->setSubsetString( QString( ) );
513  uniqueValueCache[ fieldIdx ] = unfilteredClone->uniqueValues( fieldIdx );
514  }
515  else
516  {
517  uniqueValueCache[ fieldIdx ] = layer->uniqueValues( fieldIdx );
518  }
519  }
520  return uniqueValueCache[ fieldIdx ].contains( value );
521  };
522 
523  for ( const auto &fd : qgis::as_const( featuresData ) )
524  {
525 
526  QgsFeature newFeature( fields );
527  newFeature.setValid( true );
528  newFeature.setGeometry( fd.geometry() );
529 
530  // initialize attributes
531  newFeature.initAttributes( fields.count() );
532  for ( int idx = 0; idx < fields.count(); ++idx )
533  {
534  QVariant v;
535  bool checkUnique = true;
536  const bool hasUniqueConstraint { static_cast<bool>( fields.at( idx ).constraints().constraints() & QgsFieldConstraints::ConstraintUnique ) };
537 
538  // in order of priority:
539  // 1. passed attribute value and if field does not have a unique constraint like primary key
540  if ( fd.attributes().contains( idx ) )
541  {
542  v = fd.attributes().value( idx );
543  }
544 
545  // 2. client side default expression
546  // note - deliberately not using else if!
547  QgsDefaultValue defaultValueDefinition = layer->defaultValueDefinition( idx );
548  if ( ( v.isNull() || ( hasUniqueConstraint
549  && checkUniqueValue( idx, v ) )
550  || defaultValueDefinition.applyOnUpdate() )
551  && defaultValueDefinition.isValid() )
552  {
553  // client side default expression set - takes precedence over all. Why? Well, this is the only default
554  // which QGIS users have control over, so we assume that they're deliberately overriding any
555  // provider defaults for some good reason and we should respect that
556  v = layer->defaultValue( idx, newFeature, evalContext );
557  }
558 
559  // 3. provider side default value clause
560  // note - not an else if deliberately. Users may return null from a default value expression to fallback to provider defaults
561  if ( ( v.isNull() || ( hasUniqueConstraint
562  && checkUniqueValue( idx, v ) ) )
563  && fields.fieldOrigin( idx ) == QgsFields::OriginProvider )
564  {
565  int providerIndex = fields.fieldOriginIndex( idx );
566  QString providerDefault = layer->dataProvider()->defaultValueClause( providerIndex );
567  if ( !providerDefault.isEmpty() )
568  {
569  v = providerDefault;
570  checkUnique = false;
571  }
572  }
573 
574  // 4. provider side default literal
575  // note - deliberately not using else if!
576  if ( ( v.isNull() || ( checkUnique && hasUniqueConstraint
577  && checkUniqueValue( idx, v ) ) )
578  && fields.fieldOrigin( idx ) == QgsFields::OriginProvider )
579  {
580  int providerIndex = fields.fieldOriginIndex( idx );
581  v = layer->dataProvider()->defaultValue( providerIndex );
582  if ( v.isValid() )
583  {
584  //trust that the provider default has been sensibly set not to violate any constraints
585  checkUnique = false;
586  }
587  }
588 
589  // 5. passed attribute value
590  // note - deliberately not using else if!
591  if ( v.isNull() && fd.attributes().contains( idx ) )
592  {
593  v = fd.attributes().value( idx );
594  }
595 
596  // last of all... check that unique constraints are respected if the value is valid
597  if ( v.isValid() )
598  {
599  // we can't handle not null or expression constraints here, since there's no way to pick a sensible
600  // value if the constraint is violated
601  if ( checkUnique && hasUniqueConstraint )
602  {
603  if ( checkUniqueValue( idx, v ) )
604  {
605  // unique constraint violated
606  QVariant uniqueValue = QgsVectorLayerUtils::createUniqueValueFromCache( layer, idx, uniqueValueCache[ idx ], v );
607  if ( uniqueValue.isValid() )
608  v = uniqueValue;
609  }
610  }
611  if ( hasUniqueConstraint )
612  {
613  uniqueValueCache[ idx ].insert( v );
614  }
615  }
616  newFeature.setAttribute( idx, v );
617  }
618  result.append( newFeature );
619  }
620  return result;
621 }
622 
623 QgsFeature QgsVectorLayerUtils::duplicateFeature( QgsVectorLayer *layer, const QgsFeature &feature, QgsProject *project, int depth, QgsDuplicateFeatureContext &duplicateFeatureContext )
624 {
625  if ( !layer )
626  return QgsFeature();
627 
628  if ( !layer->isEditable() )
629  return QgsFeature();
630 
631  //get context from layer
633  context.setFeature( feature );
634 
635  QgsFeature newFeature = createFeature( layer, feature.geometry(), feature.attributes().toMap(), &context );
636 
637  const QList<QgsRelation> relations = project->relationManager()->referencedRelations( layer );
638 
639  for ( const QgsRelation &relation : relations )
640  {
641  //check if composition (and not association)
642  if ( relation.strength() == QgsRelation::Composition && depth < 1 )
643  {
644  depth++;
645  //get features connected over this relation
646  QgsFeatureIterator relatedFeaturesIt = relation.getRelatedFeatures( feature );
647  QgsFeatureIds childFeatureIds;
648  QgsFeature childFeature;
649  while ( relatedFeaturesIt.nextFeature( childFeature ) )
650  {
651  //set childlayer editable
652  relation.referencingLayer()->startEditing();
653  //change the fk of the child to the id of the new parent
654  const auto pairs = relation.fieldPairs();
655  for ( const QgsRelation::FieldPair &fieldPair : pairs )
656  {
657  childFeature.setAttribute( fieldPair.first, newFeature.attribute( fieldPair.second ) );
658  }
659  //call the function for the child
660  childFeatureIds.insert( duplicateFeature( relation.referencingLayer(), childFeature, project, depth, duplicateFeatureContext ).id() );
661  }
662 
663  //store for feedback
664  duplicateFeatureContext.setDuplicatedFeatures( relation.referencingLayer(), childFeatureIds );
665  }
666  }
667 
668  layer->addFeature( newFeature );
669 
670  return newFeature;
671 }
672 
673 std::unique_ptr<QgsVectorLayerFeatureSource> QgsVectorLayerUtils::getFeatureSource( QPointer<QgsVectorLayer> layer, QgsFeedback *feedback )
674 {
675  std::unique_ptr<QgsVectorLayerFeatureSource> featureSource;
676 
677  auto getFeatureSource = [ layer, &featureSource, feedback ]
678  {
679 #if QT_VERSION >= QT_VERSION_CHECK( 5, 10, 0 )
680  Q_ASSERT( QThread::currentThread() == qApp->thread() || feedback );
681 #else
682  Q_UNUSED( feedback )
683 #endif
684  QgsVectorLayer *lyr = layer.data();
685 
686  if ( lyr )
687  {
688  featureSource.reset( new QgsVectorLayerFeatureSource( lyr ) );
689  }
690  };
691 
693 
694  return featureSource;
695 }
696 
698 {
699  if ( !feature.fields().isEmpty() )
700  {
701  QgsAttributes attributes;
702  attributes.reserve( fields.size() );
703  // feature has a field mapping, so we can match attributes to field names
704  for ( const QgsField &field : fields )
705  {
706  int index = feature.fields().lookupField( field.name() );
707  attributes.append( index >= 0 ? feature.attribute( index ) : QVariant( field.type() ) );
708  }
709  feature.setAttributes( attributes );
710  }
711  else
712  {
713  // no field name mapping in feature, just use order
714  const int lengthDiff = feature.attributes().count() - fields.count();
715  if ( lengthDiff > 0 )
716  {
717  // truncate extra attributes
718  QgsAttributes attributes = feature.attributes().mid( 0, fields.count() );
719  feature.setAttributes( attributes );
720  }
721  else if ( lengthDiff < 0 )
722  {
723  // add missing null attributes
724  QgsAttributes attributes = feature.attributes();
725  attributes.reserve( fields.count() );
726  for ( int i = feature.attributes().count(); i < fields.count(); ++i )
727  {
728  attributes.append( QVariant( fields.at( i ).type() ) );
729  }
730  feature.setAttributes( attributes );
731  }
732  }
733  feature.setFields( fields );
734 }
735 
737 {
738  QgsWkbTypes::Type inputWkbType( layer->wkbType( ) );
739  QgsFeatureList resultFeatures;
740  QgsFeature newF( feature );
741  // Fix attributes
743  // Does geometry need transformations?
745  bool newFHasGeom = newFGeomType !=
746  QgsWkbTypes::GeometryType::UnknownGeometry &&
747  newFGeomType != QgsWkbTypes::GeometryType::NullGeometry;
748  bool layerHasGeom = inputWkbType !=
749  QgsWkbTypes::Type::NoGeometry &&
750  inputWkbType != QgsWkbTypes::Type::Unknown;
751  // Drop geometry if layer is geometry-less
752  if ( ( newFHasGeom && !layerHasGeom ) || !newFHasGeom )
753  {
754  QgsFeature _f = QgsFeature( layer->fields() );
755  _f.setAttributes( newF.attributes() );
756  resultFeatures.append( _f );
757  }
758  else
759  {
760  // Geometry need fixing?
761  const QVector< QgsGeometry > geometries = newF.geometry().coerceToType( inputWkbType );
762 
763  if ( geometries.count() != 1 )
764  {
765  QgsAttributeMap attrMap;
766  for ( int j = 0; j < newF.fields().count(); j++ )
767  {
768  attrMap[j] = newF.attribute( j );
769  }
770  resultFeatures.reserve( geometries.size() );
771  for ( const QgsGeometry &geometry : geometries )
772  {
773  QgsFeature _f( createFeature( layer, geometry, attrMap ) );
774  resultFeatures.append( _f );
775  }
776  }
777  else
778  {
779  newF.setGeometry( geometries.at( 0 ) );
780  resultFeatures.append( newF );
781  }
782  }
783  return resultFeatures;
784 }
785 
787 {
788  QgsFeatureList resultFeatures;
789  for ( const QgsFeature &f : features )
790  {
791  const QgsFeatureList features( makeFeatureCompatible( f, layer ) );
792  for ( const auto &_f : features )
793  {
794  resultFeatures.append( _f );
795  }
796  }
797  return resultFeatures;
798 }
799 
801 {
802  QList<QgsVectorLayer *> layers;
803  QMap<QgsVectorLayer *, QgsFeatureIds>::const_iterator i;
804  for ( i = mDuplicatedFeatures.begin(); i != mDuplicatedFeatures.end(); ++i )
805  layers.append( i.key() );
806  return layers;
807 }
808 
810 {
811  return mDuplicatedFeatures[layer];
812 }
813 
814 void QgsVectorLayerUtils::QgsDuplicateFeatureContext::setDuplicatedFeatures( QgsVectorLayer *layer, const QgsFeatureIds &ids )
815 {
816  mDuplicatedFeatures.insert( layer, ids );
817 }
818 /*
819 QMap<QgsVectorLayer *, QgsFeatureIds> QgsVectorLayerUtils::QgsDuplicateFeatureContext::duplicateFeatureContext() const
820 {
821  return mDuplicatedFeatures;
822 }
823 */
824 
826  mGeometry( geometry ),
827  mAttributes( attributes )
828 {}
829 
831 {
832  return mGeometry;
833 }
834 
836 {
837  return mAttributes;
838 }
839 
840 bool _fieldIsEditable( const QgsVectorLayer *layer, int fieldIndex, const QgsFeature &feature )
841 {
842  return layer->isEditable() &&
843  !layer->editFormConfig().readOnly( fieldIndex ) &&
844  ( ( layer->dataProvider() && layer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeAttributeValues ) || FID_IS_NEW( feature.id() ) );
845 }
846 
847 bool QgsVectorLayerUtils::fieldIsEditable( const QgsVectorLayer *layer, int fieldIndex, const QgsFeature &feature )
848 {
849  if ( layer->fields().fieldOrigin( fieldIndex ) == QgsFields::OriginJoin )
850  {
851  int srcFieldIndex;
852  const QgsVectorLayerJoinInfo *info = layer->joinBuffer()->joinForFieldIndex( fieldIndex, layer->fields(), srcFieldIndex );
853 
854  if ( !info || !info->isEditable() )
855  return false;
856 
857  // check that joined feature exist, else it is not editable
858  if ( !info->hasUpsertOnEdit() )
859  {
860  const QgsFeature joinedFeature = layer->joinBuffer()->joinedFeatureOf( info, feature );
861  if ( !joinedFeature.isValid() )
862  return false;
863  }
864 
865  return _fieldIsEditable( info->joinLayer(), srcFieldIndex, feature );
866  }
867  else
868  return _fieldIsEditable( layer, fieldIndex, feature );
869 }
870 
871 QHash<QString, QHash<QString, QSet<QgsSymbolLayerId>>> QgsVectorLayerUtils::labelMasks( const QgsVectorLayer *layer )
872 {
873  class LabelMasksVisitor : public QgsStyleEntityVisitorInterface
874  {
875  public:
876  bool visitEnter( const QgsStyleEntityVisitorInterface::Node &node ) override
877  {
879  {
880  currentRule = node.identifier;
881  return true;
882  }
883  return false;
884  }
885  bool visit( const QgsStyleEntityVisitorInterface::StyleLeaf &leaf ) override
886  {
887  if ( leaf.entity && leaf.entity->type() == QgsStyle::LabelSettingsEntity )
888  {
889  auto labelSettingsEntity = static_cast<const QgsStyleLabelSettingsEntity *>( leaf.entity );
890  if ( labelSettingsEntity->settings().format().mask().enabled() )
891  {
892  for ( const auto &r : labelSettingsEntity->settings().format().mask().maskedSymbolLayers() )
893  {
894  masks[currentRule][r.layerId()].insert( r.symbolLayerId() );
895  }
896  }
897  }
898  return true;
899  }
900 
901  QHash<QString, QHash<QString, QSet<QgsSymbolLayerId>>> masks;
902  // Current label rule, empty string for a simple labeling
903  QString currentRule;
904  };
905 
906  if ( ! layer->labeling() )
907  return {};
908 
909  LabelMasksVisitor visitor;
910  layer->labeling()->accept( &visitor );
911  return std::move( visitor.masks );
912 }
913 
914 QHash<QString, QSet<QgsSymbolLayerId>> QgsVectorLayerUtils::symbolLayerMasks( const QgsVectorLayer *layer )
915 {
916  if ( ! layer->renderer() )
917  return {};
918 
920  {
921  public:
922  bool visitEnter( const QgsStyleEntityVisitorInterface::Node &node ) override
923  {
925  }
926 
927  void visitSymbol( const QgsSymbol *symbol )
928  {
929  for ( int idx = 0; idx < symbol->symbolLayerCount(); idx++ )
930  {
931  const QgsSymbolLayer *sl = symbol->symbolLayer( idx );
932  for ( const auto &mask : sl->masks() )
933  {
934  masks[mask.layerId()].insert( mask.symbolLayerId() );
935  }
936  // recurse over sub symbols
937  const QgsSymbol *subSymbol = const_cast<QgsSymbolLayer *>( sl )->subSymbol();
938  if ( subSymbol )
939  visitSymbol( subSymbol );
940  }
941  }
942 
943  bool visit( const QgsStyleEntityVisitorInterface::StyleLeaf &leaf ) override
944  {
945  if ( leaf.entity && leaf.entity->type() == QgsStyle::SymbolEntity )
946  {
947  auto symbolEntity = static_cast<const QgsStyleSymbolEntity *>( leaf.entity );
948  if ( symbolEntity->symbol() )
949  visitSymbol( symbolEntity->symbol() );
950  }
951  return true;
952  }
953  QHash<QString, QSet<QgsSymbolLayerId>> masks;
954  };
955 
956  SymbolLayerVisitor visitor;
957  layer->renderer()->accept( &visitor );
958  return visitor.masks;
959 }
960 
962 {
964 
965  QgsExpression exp( layer->displayExpression() );
966  context.setFeature( feature );
967  exp.prepare( &context );
968  QString displayString = exp.evaluate( &context ).toString();
969 
970  return displayString;
971 }
972 
974 {
975  if ( !layer )
976  return false;
977 
978  const QList<QgsRelation> relations = project->relationManager()->referencedRelations( layer );
979  for ( const QgsRelation &relation : relations )
980  {
981  if ( relation.strength() == QgsRelation::Composition )
982  {
983  QgsFeatureIds childFeatureIds;
984 
985  const auto constFids = fids;
986  for ( const QgsFeatureId fid : constFids )
987  {
988  //get features connected over this relation
989  QgsFeatureIterator relatedFeaturesIt = relation.getRelatedFeatures( layer->getFeature( fid ) );
990  QgsFeature childFeature;
991  while ( relatedFeaturesIt.nextFeature( childFeature ) )
992  {
993  childFeatureIds.insert( childFeature.id() );
994  }
995  }
996 
997  if ( childFeatureIds.count() > 0 )
998  {
999  if ( context.layers().contains( relation.referencingLayer() ) )
1000  {
1001  QgsFeatureIds handledFeatureIds = context.duplicatedFeatures( relation.referencingLayer() );
1002  // add feature ids
1003  handledFeatureIds.unite( childFeatureIds );
1004  context.setDuplicatedFeatures( relation.referencingLayer(), handledFeatureIds );
1005  }
1006  else
1007  {
1008  // add layer and feature id
1009  context.setDuplicatedFeatures( relation.referencingLayer(), childFeatureIds );
1010  }
1011  }
1012  }
1013  }
1014 
1015  if ( layer->joinBuffer()->containsJoins() )
1016  {
1017  const auto constVectorJoins = layer->joinBuffer()->vectorJoins();
1018  for ( const QgsVectorLayerJoinInfo &info : constVectorJoins )
1019  {
1020  if ( info.isEditable() && info.hasCascadedDelete() )
1021  {
1022  QgsFeatureIds joinFeatureIds;
1023  const auto constFids = fids;
1024  for ( const QgsFeatureId &fid : constFids )
1025  {
1026  const QgsFeature joinFeature = layer->joinBuffer()->joinedFeatureOf( &info, layer->getFeature( fid ) );
1027  if ( joinFeature.isValid() )
1028  joinFeatureIds.insert( joinFeature.id() );
1029  }
1030 
1031  if ( joinFeatureIds.count() > 0 )
1032  {
1033  if ( context.layers().contains( info.joinLayer() ) )
1034  {
1035  QgsFeatureIds handledFeatureIds = context.duplicatedFeatures( info.joinLayer() );
1036  // add feature ids
1037  handledFeatureIds.unite( joinFeatureIds );
1038  context.setDuplicatedFeatures( info.joinLayer(), handledFeatureIds );
1039  }
1040  else
1041  {
1042  // add layer and feature id
1043  context.setDuplicatedFeatures( info.joinLayer(), joinFeatureIds );
1044  }
1045  }
1046  }
1047  }
1048  }
1049 
1050  return context.layers().count();
1051 }
QgsFields::OriginProvider
@ OriginProvider
Field comes from the underlying data provider of the vector layer (originIndex = index in provider's ...
Definition: qgsfields.h:51
qgspolygon.h
QgsFeatureRequest::NoGeometry
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
Definition: qgsfeaturerequest.h:107
QgsVectorLayer::getFeatures
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
Definition: qgsvectorlayer.cpp:993
QgsExpressionContext
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
Definition: qgsexpressioncontext.h:369
QgsProject::relationManager
QgsRelationManager relationManager
Definition: qgsproject.h:103
qgsexpressioncontextutils.h
QgsExpressionContext::appendScopes
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of the context.
Definition: qgsexpressioncontext.cpp:495
QgsField::isNumeric
bool isNumeric
Definition: qgsfield.h:53
qgspallabeling.h
QgsVectorLayer::wkbType
Q_INVOKABLE QgsWkbTypes::Type wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
Definition: qgsvectorlayer.cpp:664
qgsfeaturerequest.h
QgsDefaultValue
The QgsDefaultValue class provides a container for managing client side default values for fields.
Definition: qgsdefaultvalue.h:48
QgsVectorLayer::uniqueStringsMatching
QStringList uniqueStringsMatching(int index, const QString &substring, int limit=-1, QgsFeedback *feedback=nullptr) const
Returns unique string values of an attribute which contain a specified subset string.
Definition: qgsvectorlayer.cpp:4056
QgsVectorLayer::dataProvider
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider, it may be nullptr.
Definition: qgsvectorlayer.cpp:627
qgslinestring.h
QgsExpression::evalErrorString
QString evalErrorString() const
Returns evaluation error.
Definition: qgsexpression.cpp:379
QgsVectorLayerUtils::impactsCascadeFeatures
static bool impactsCascadeFeatures(const QgsVectorLayer *layer, const QgsFeatureIds &fids, const QgsProject *project, QgsDuplicateFeatureContext &context)
Definition: qgsvectorlayerutils.cpp:973
QgsFeature::initAttributes
void initAttributes(int fieldCount)
Initialize this feature with the given number of fields.
Definition: qgsfeature.cpp:202
QgsFields::isEmpty
bool isEmpty() const
Checks whether the container is empty.
Definition: qgsfields.cpp:128
QgsVectorLayerUtils::duplicateFeature
static QgsFeature duplicateFeature(QgsVectorLayer *layer, const QgsFeature &feature, QgsProject *project, int depth, QgsDuplicateFeatureContext &duplicateFeatureContext)
Duplicates a feature and it's children (one level deep).
Definition: qgsvectorlayerutils.cpp:623
QgsStyleSymbolEntity
Definition: qgsstyle.h:1134
qgsgeometryfactory.h
QgsFeatureRenderer::accept
virtual bool accept(QgsStyleEntityVisitorInterface *visitor) const
Accepts the specified symbology visitor, causing it to visit all symbols associated with the renderer...
Definition: qgsrenderer.cpp:465
QgsFieldConstraints
Definition: qgsfieldconstraints.h:32
QgsVectorLayerUtils::QgsFeatureData::attributes
QgsAttributeMap attributes() const
Returns attributes.
Definition: qgsvectorlayerutils.cpp:835
qgsfeatureiterator.h
QgsFields::count
int count() const
Returns number of items.
Definition: qgsfields.cpp:133
QgsFields
Definition: qgsfields.h:44
SymbolLayerVisitor
Definition: qgsmaskingwidget.cpp:86
qgsmultipoint.h
QgsFieldConstraints::constraintExpression
QString constraintExpression() const
Returns the constraint expression for the field, if set.
Definition: qgsfieldconstraints.cpp:67
QgsFeature::geometry
QgsGeometry geometry
Definition: qgsfeature.h:71
QgsGeometry::wkbType
QgsWkbTypes::Type wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
Definition: qgsgeometry.cpp:345
QgsFeature::setValid
void setValid(bool validity)
Sets the validity of the feature.
Definition: qgsfeature.cpp:188
QgsVectorLayerJoinBuffer::joinForFieldIndex
const QgsVectorLayerJoinInfo * joinForFieldIndex(int index, const QgsFields &fields, int &sourceFieldIndex) const
Finds the vector join for a layer field index.
Definition: qgsvectorlayerjoinbuffer.cpp:397
QgsRelation::Composition
@ Composition
Fix relation, related elements are part of the parent and a parent copy will copy any children or del...
Definition: qgsrelation.h:60
QgsStyleEntityVisitorInterface
Definition: qgsstyleentityvisitor.h:33
QgsDefaultValue::isValid
bool isValid() const
Returns if this default value should be applied.
Definition: qgsdefaultvalue.cpp:51
QgsVectorLayerUtils::getValuesIterator
static QgsFeatureIterator getValuesIterator(const QgsVectorLayer *layer, const QString &fieldOrExpression, bool &ok, bool selectedOnly)
Create a feature iterator for a specified field name or expression.
Definition: qgsvectorlayerutils.cpp:44
QgsExpressionContextUtils::globalProjectLayerScopes
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Definition: qgsexpressioncontextutils.cpp:306
QgsVectorLayerUtils::QgsFeatureData::QgsFeatureData
QgsFeatureData(const QgsGeometry &geometry=QgsGeometry(), const QgsAttributeMap &attributes=QgsAttributeMap())
Constructs a new QgsFeatureData with given geometry and attributes.
Definition: qgsvectorlayerutils.cpp:825
QgsVectorDataProvider::skipConstraintCheck
virtual bool skipConstraintCheck(int fieldIndex, QgsFieldConstraints::Constraint constraint, const QVariant &value=QVariant()) const
Returns true if a constraint check should be skipped for a specified field (e.g., if the value return...
Definition: qgsvectordataprovider.cpp:157
QgsWkbTypes::Type
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:68
QgsVectorLayerUtils::symbolLayerMasks
static QHash< QString, QSet< QgsSymbolLayerId > > symbolLayerMasks(const QgsVectorLayer *)
Returns all masks that may be defined on symbol layers for a given vector layer.
Definition: qgsvectorlayerutils.cpp:914
QgsFeatureRequest::setSubsetOfAttributes
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
Definition: qgsfeaturerequest.cpp:190
QgsVectorLayerUtils::QgsFeatureData
Encapsulate geometry and attributes for new features, to be passed to createFeatures.
Definition: qgsvectorlayerutils.h:84
QgsSymbol
Definition: qgssymbol.h:63
QgsSymbol::symbolLayer
QgsSymbolLayer * symbolLayer(int layer)
Returns the symbol layer at the specified index.
Definition: qgssymbol.cpp:366
QgsAttributeList
QList< int > QgsAttributeList
Definition: qgsfield.h:26
QgsGeometry::coerceToType
QVector< QgsGeometry > coerceToType(QgsWkbTypes::Type type) const
Attempts to coerce this geometry into the specified destination type.
Definition: qgsgeometry.cpp:1327
QgsField::name
QString name
Definition: qgsfield.h:59
QgsFieldConstraints::ConstraintNotNull
@ ConstraintNotNull
Field may not be null.
Definition: qgsfieldconstraints.h:45
QgsStyleEntityVisitorInterface::StyleLeaf
Contains information relating to the style entity currently being visited.
Definition: qgsstyleentityvisitor.h:60
QgsVectorLayer::defaultValue
QVariant defaultValue(int index, const QgsFeature &feature=QgsFeature(), QgsExpressionContext *context=nullptr) const
Returns the calculated default value for the specified field index.
Definition: qgsvectorlayer.cpp:3879
QgsVectorDataProvider::defaultValue
virtual QVariant defaultValue(int fieldIndex) const
Returns any literal default values which are present at the provider for a specified field index.
Definition: qgsvectordataprovider.cpp:136
QgsVectorLayerUtils::labelMasks
static QHash< QString, QHash< QString, QSet< QgsSymbolLayerId > > > labelMasks(const QgsVectorLayer *)
Returns masks defined in labeling options of a layer.
Definition: qgsvectorlayerutils.cpp:871
QgsStyle::SymbolEntity
@ SymbolEntity
Symbols.
Definition: qgsstyle.h:180
QgsVectorLayer::isEditable
bool isEditable() const FINAL
Returns true if the provider is in editing mode.
Definition: qgsvectorlayer.cpp:3586
QgsProject
Definition: qgsproject.h:92
QgsStyle::LabelSettingsEntity
@ LabelSettingsEntity
Label settings.
Definition: qgsstyle.h:185
QgsFeatureRequest::setFilterExpression
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
Definition: qgsfeaturerequest.cpp:129
QgsExpression::quotedValue
static QString quotedValue(const QVariant &value)
Returns a string representation of a literal value, including appropriate quotations where required.
Definition: qgsexpression.cpp:79
QgsVectorLayer::fields
QgsFields fields() const FINAL
Returns the list of fields of this layer.
Definition: qgsvectorlayer.cpp:3280
QgsFeature::id
QgsFeatureId id
Definition: qgsfeature.h:68
QgsVectorLayerUtils::getValues
static QList< QVariant > getValues(const QgsVectorLayer *layer, const QString &fieldOrExpression, bool &ok, bool selectedOnly=false, QgsFeedback *feedback=nullptr)
Fetches all values from a specified field name or expression.
Definition: qgsvectorlayerutils.cpp:86
QgsFeatureRequest
Definition: qgsfeaturerequest.h:75
QgsVectorDataProvider::capabilities
virtual QgsVectorDataProvider::Capabilities capabilities() const
Returns flags containing the supported capabilities.
Definition: qgsvectordataprovider.cpp:191
QgsExpression::hasEvalError
bool hasEvalError() const
Returns true if an error occurred when evaluating last input.
Definition: qgsexpression.cpp:374
QgsFeatureRequest::NoFlags
@ NoFlags
Definition: qgsfeaturerequest.h:106
qgsexpressioncontext.h
QgsSymbolLayer
Definition: qgssymbollayer.h:52
QgsVectorLayerUtils::QgsDuplicateFeatureContext::layers
QList< QgsVectorLayer * > layers() const
Returns all the layers on which features have been duplicated.
Definition: qgsvectorlayerutils.cpp:800
_fieldIsEditable
bool _fieldIsEditable(const QgsVectorLayer *layer, int fieldIndex, const QgsFeature &feature)
Definition: qgsvectorlayerutils.cpp:840
QgsFeature::setGeometry
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Definition: qgsfeature.cpp:137
QgsRelationManager::referencedRelations
QList< QgsRelation > referencedRelations(const QgsVectorLayer *layer=nullptr) const
Gets all relations where this layer is the referenced part (i.e.
Definition: qgsrelationmanager.cpp:160
QgsVectorLayerUtils::QgsFeaturesDataList
QList< QgsVectorLayerUtils::QgsFeatureData > QgsFeaturesDataList
Alias for list of QgsFeatureData.
Definition: qgsvectorlayerutils.h:106
qgsvectorlayerjoinbuffer.h
QgsExpression::parserErrorString
QString parserErrorString() const
Returns parser error.
Definition: qgsexpression.cpp:207
QgsFeature::isValid
bool isValid() const
Returns the validity of this feature.
Definition: qgsfeature.cpp:183
QgsFeature::setFields
void setFields(const QgsFields &fields, bool initAttributes=false)
Assign a field map with the feature to allow attribute access by attribute name.
Definition: qgsfeature.cpp:162
QgsFieldConstraints::constraints
Constraints constraints
Definition: qgsfieldconstraints.h:36
QgsFieldConstraints::ConstraintOrigin
ConstraintOrigin
Origin of constraints.
Definition: qgsfieldconstraints.h:54
QgsFeedback
Definition: qgsfeedback.h:43
QgsVectorLayer::labeling
const QgsAbstractVectorLayerLabeling * labeling() const
Access to const labeling configuration.
Definition: qgsvectorlayer.h:1598
QgsVectorLayerJoinInfo::hasUpsertOnEdit
bool hasUpsertOnEdit() const
Returns whether a feature created on the target layer has to impact the joined layer by creating a ne...
Definition: qgsvectorlayerjoininfo.h:121
QgsVectorLayerUtils::QgsDuplicateFeatureContext
Contains mainly the QMap with QgsVectorLayer and QgsFeatureIds do list all the duplicated features.
Definition: qgsvectorlayerutils.h:46
QgsField::convertCompatible
bool convertCompatible(QVariant &v) const
Converts the provided variant to a compatible format.
Definition: qgsfield.cpp:339
QgsVectorLayer::uniqueValues
QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const FINAL
Calculates a list of unique values contained within an attribute in the layer.
Definition: qgsvectorlayer.cpp:3949
QgsFields::size
int size() const
Returns number of items.
Definition: qgsfields.cpp:138
QgsFields::fieldOrigin
FieldOrigin fieldOrigin(int fieldIdx) const
Gets field's origin (value from an enumeration)
Definition: qgsfields.cpp:189
qgsvectordataprovider.h
QgsFeatureList
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:572
QgsAttributeMap
QMap< int, QVariant > QgsAttributeMap
Definition: qgsattributes.h:38
QgsVectorLayerJoinInfo::isEditable
bool isEditable() const
Returns whether joined fields may be edited through the form of the target layer.
Definition: qgsvectorlayerjoininfo.h:108
QgsFieldConstraints::ConstraintUnique
@ ConstraintUnique
Field must have a unique value.
Definition: qgsfieldconstraints.h:46
QgsWkbTypes::geometryType
static GeometryType geometryType(Type type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
Definition: qgswkbtypes.h:937
qgsvectorlayerutils.h
QgsVectorLayerJoinBuffer::vectorJoins
const QgsVectorJoinList & vectorJoins() const
Definition: qgsvectorlayerjoinbuffer.h:82
QgsStyleEntityInterface::type
virtual QgsStyle::StyleEntity type() const =0
Returns the type of style entity.
qgssymbollayer.h
QgsFeature::attribute
QVariant attribute(const QString &name) const
Lookup attribute value from attribute name.
Definition: qgsfeature.cpp:262
QgsVectorLayer::maximumValue
QVariant maximumValue(int index) const FINAL
Returns the maximum value for an attribute column or an invalid variant in case of error.
Definition: qgsvectorlayer.cpp:4162
QgsVectorLayerUtils::createUniqueValue
static QVariant createUniqueValue(const QgsVectorLayer *layer, int fieldIndex, const QVariant &seed=QVariant())
Returns a new attribute value for the specified field index which is guaranteed to be unique.
Definition: qgsvectorlayerutils.cpp:213
QgsFieldConstraints::ConstraintStrengthNotSet
@ ConstraintStrengthNotSet
Constraint is not set.
Definition: qgsfieldconstraints.h:66
QgsStyleEntityVisitorInterface::NodeType::SymbolRule
@ SymbolRule
Rule based symbology or label child rule.
QgsVectorLayerJoinInfo
Definition: qgsvectorlayerjoininfo.h:33
QgsStyleEntityVisitorInterface::Node
Contains information relating to a node (i.e.
Definition: qgsstyleentityvisitor.h:110
QgsFieldConstraints::constraintStrength
ConstraintStrength constraintStrength(Constraint constraint) const
Returns the strength of a field constraint, or ConstraintStrengthNotSet if the constraint is not pres...
Definition: qgsfieldconstraints.cpp:27
qgsrenderer.h
QgsFieldConstraints::constraintDescription
QString constraintDescription() const
Returns the descriptive name for the constraint expression.
Definition: qgsfieldconstraints.h:133
QgsAttributes::toMap
QgsAttributeMap toMap() const
Returns a QgsAttributeMap of the attribute values.
Definition: qgsattributes.cpp:21
QgsVectorLayerUtils::QgsFeatureData::geometry
QgsGeometry geometry() const
Returns geometry.
Definition: qgsvectorlayerutils.cpp:830
QgsFeatureRequest::setNoAttributes
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
Definition: qgsfeaturerequest.cpp:197
QgsExpression::prepare
bool prepare(const QgsExpressionContext *context)
Gets the expression ready for evaluation - find out column indexes.
Definition: qgsexpression.cpp:323
qgsrelationmanager.h
qgscurvepolygon.h
QgsFeatureIds
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:34
QgsVectorLayerUtils::getFeatureSource
static std::unique_ptr< QgsVectorLayerFeatureSource > getFeatureSource(QPointer< QgsVectorLayer > layer, QgsFeedback *feedback=nullptr)
Gets the feature source from a QgsVectorLayer pointer.
Definition: qgsvectorlayerutils.cpp:673
QgsRelation::FieldPair
Definition: qgsrelation.h:74
QgsEditFormConfig::readOnly
bool readOnly(int idx) const
This returns true if the field is manually set to read only or if the field does not support editing ...
Definition: qgseditformconfig.cpp:189
QgsFeature::attributes
QgsAttributes attributes
Definition: qgsfeature.h:69
QgsVectorLayer::defaultValueDefinition
QgsDefaultValue defaultValueDefinition(int index) const
Returns the definition of the expression used when calculating the default value for a field.
Definition: qgsvectorlayer.cpp:3941
QgsStyleLabelSettingsEntity
Definition: qgsstyle.h:1227
QgsExpression::evaluate
QVariant evaluate()
Evaluate the feature and return the result.
Definition: qgsexpression.cpp:346
qgsstyle.h
QgsVectorLayerUtils::createFeature
static QgsFeature createFeature(const QgsVectorLayer *layer, const QgsGeometry &geometry=QgsGeometry(), const QgsAttributeMap &attributes=QgsAttributeMap(), QgsExpressionContext *context=nullptr)
Creates a new feature ready for insertion into a layer.
Definition: qgsvectorlayerutils.cpp:475
QgsStyleEntityVisitorInterface::StyleLeaf::entity
const QgsStyleEntityInterface * entity
Reference to style entity being visited.
Definition: qgsstyleentityvisitor.h:103
qgsvectorlayer.h
QgsVectorLayer::getSelectedFeatures
QgsFeatureIterator getSelectedFeatures(QgsFeatureRequest request=QgsFeatureRequest()) const
Returns an iterator of the selected features.
Definition: qgsvectorlayer.cpp:3468
QgsFeedback::isCanceled
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:66
QgsFeature::setAttribute
bool setAttribute(int field, const QVariant &attr)
Set an attribute's value by field index.
Definition: qgsfeature.cpp:211
QgsFieldConstraints::ConstraintOriginNotSet
@ ConstraintOriginNotSet
Constraint is not set.
Definition: qgsfieldconstraints.h:56
QgsSymbolLayer::masks
virtual QgsSymbolLayerReferenceList masks() const
Returns masks defined by this symbol layer.
Definition: qgssymbollayer.cpp:800
QgsVectorLayerUtils::matchAttributesToFields
static void matchAttributesToFields(QgsFeature &feature, const QgsFields &fields)
Matches the attributes in feature to the specified fields.
Definition: qgsvectorlayerutils.cpp:697
qgsthreadingutils.h
QgsWkbTypes::GeometryType
GeometryType
The geometry types are used to group QgsWkbTypes::Type in a coarse way.
Definition: qgswkbtypes.h:139
QgsFeatureIterator::nextFeature
bool nextFeature(QgsFeature &f)
Definition: qgsfeatureiterator.h:373
QgsGeometry
Definition: qgsgeometry.h:122
QgsThreadingUtils::runOnMainThread
static bool runOnMainThread(const Func &func, QgsFeedback *feedback=nullptr)
Guarantees that func is executed on the main thread.
Definition: qgsthreadingutils.h:56
QgsVectorLayerUtils::makeFeatureCompatible
static QgsFeatureList makeFeatureCompatible(const QgsFeature &feature, const QgsVectorLayer *layer)
Converts input feature to be compatible with the given layer.
Definition: qgsvectorlayerutils.cpp:736
QgsVectorDataProvider::ChangeAttributeValues
@ ChangeAttributeValues
Allows modification of attribute values.
Definition: qgsvectordataprovider.h:77
QgsVectorLayer
Definition: qgsvectorlayer.h:385
QgsFeatureRequest::setLimit
QgsFeatureRequest & setLimit(long limit)
Set the maximum number of features to request.
Definition: qgsfeaturerequest.cpp:178
QgsVectorLayer::editFormConfig
QgsEditFormConfig editFormConfig
Definition: qgsvectorlayer.h:392
QgsVectorLayerJoinBuffer::joinedFeatureOf
QgsFeature joinedFeatureOf(const QgsVectorLayerJoinInfo *info, const QgsFeature &feature) const
Returns the joined feature corresponding to the feature.
Definition: qgsvectorlayerjoinbuffer.cpp:429
QgsVectorLayerUtils::validateAttribute
static bool validateAttribute(const QgsVectorLayer *layer, const QgsFeature &feature, int attributeIndex, QStringList &errors, QgsFieldConstraints::ConstraintStrength strength=QgsFieldConstraints::ConstraintStrengthNotSet, QgsFieldConstraints::ConstraintOrigin origin=QgsFieldConstraints::ConstraintOriginNotSet)
Tests an attribute value to check whether it passes all constraints which are present on the correspo...
Definition: qgsvectorlayerutils.cpp:374
QgsVectorLayerFeatureSource
Definition: qgsvectorlayerfeatureiterator.h:51
QgsVectorLayerUtils::fieldIsEditable
static bool fieldIsEditable(const QgsVectorLayer *layer, int fieldIndex, const QgsFeature &feature)
Definition: qgsvectorlayerutils.cpp:847
QgsVectorLayerJoinInfo::joinLayer
QgsVectorLayer * joinLayer() const
Returns joined layer (may be nullptr if the reference was set by layer ID and not resolved yet)
Definition: qgsvectorlayerjoininfo.h:58
QgsFieldConstraints::ConstraintExpression
@ ConstraintExpression
Field has an expression constraint set. See constraintExpression().
Definition: qgsfieldconstraints.h:47
QgsExpression::quotedColumnRef
static QString quotedColumnRef(QString name)
Returns a quoted column reference (in double quotes)
Definition: qgsexpression.cpp:65
QgsFields::fieldOriginIndex
int fieldOriginIndex(int fieldIdx) const
Gets field's origin index (its meaning is specific to each type of origin)
Definition: qgsfields.cpp:197
QgsField::constraints
QgsFieldConstraints constraints
Definition: qgsfield.h:62
QgsRelation
Definition: qgsrelation.h:41
QgsVectorLayerJoinBuffer::containsJoins
bool containsJoins() const
Quick way to test if there is any join at all.
Definition: qgsvectorlayerjoinbuffer.h:80
QgsVectorLayerUtils::createFeatures
static QgsFeatureList createFeatures(const QgsVectorLayer *layer, const QgsFeaturesDataList &featuresData, QgsExpressionContext *context=nullptr)
Creates a set of new features ready for insertion into a layer.
Definition: qgsvectorlayerutils.cpp:482
QgsVectorDataProvider::defaultValueClause
virtual QString defaultValueClause(int fieldIndex) const
Returns any default value clauses which are present at the provider for a specified field index.
Definition: qgsvectordataprovider.cpp:142
QgsVectorLayer::subsetString
QString subsetString
Definition: qgsvectorlayer.h:389
QgsAttributes
Definition: qgsattributes.h:57
qgsgeometrycollection.h
QgsFeature::fields
QgsFields fields
Definition: qgsfeature.h:70
QgsFeature
Definition: qgsfeature.h:55
qgsvectorlayerlabeling.h
QgsExpression::hasParserError
bool hasParserError() const
Returns true if an error occurred when parsing the input expression.
Definition: qgsexpression.cpp:202
QgsVectorLayer::getFeature
QgsFeature getFeature(QgsFeatureId fid) const
Queries the layer for the feature with the given id.
Definition: qgsvectorlayer.h:1183
QgsFieldConstraints::ConstraintOriginProvider
@ ConstraintOriginProvider
Constraint was set at data provider.
Definition: qgsfieldconstraints.h:57
QgsFieldConstraints::ConstraintStrength
ConstraintStrength
Strength of constraints.
Definition: qgsfieldconstraints.h:64
QgsVectorLayerUtils::QgsDuplicateFeatureContext::duplicatedFeatures
QgsFeatureIds duplicatedFeatures(QgsVectorLayer *layer) const
Returns the duplicated features in the given layer.
Definition: qgsvectorlayerutils.cpp:809
QgsFeature::setAttributes
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:127
QgsDefaultValue::applyOnUpdate
bool applyOnUpdate
Definition: qgsdefaultvalue.h:67
FID_IS_NEW
#define FID_IS_NEW(fid)
Definition: qgsfeatureid.h:28
QgsFields::lookupField
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
Definition: qgsfields.cpp:324
QgsVectorLayerUtils::createUniqueValueFromCache
static QVariant createUniqueValueFromCache(const QgsVectorLayer *layer, int fieldIndex, const QSet< QVariant > &existingValues, const QVariant &seed=QVariant())
Returns a new attribute value for the specified field index which is guaranteed to be unique within r...
Definition: qgsvectorlayerutils.cpp:293
QgsVectorLayer::createExpressionContext
QgsExpressionContext createExpressionContext() const FINAL
This method needs to be reimplemented in all classes which implement this interface and return an exp...
Definition: qgsvectorlayer.cpp:4933
QgsFields::at
QgsField at(int i) const
Gets field at particular index (must be in range 0..N-1)
Definition: qgsfields.cpp:163
QgsExpression
Definition: qgsexpression.h:113
QgsVectorLayer::displayExpression
QString displayExpression
Definition: qgsvectorlayer.h:390
QgsStyleEntityVisitorInterface::Node::identifier
QString identifier
A string identifying the node.
Definition: qgsstyleentityvisitor.h:133
QgsVectorLayerUtils::valueExists
static bool valueExists(const QgsVectorLayer *layer, int fieldIndex, const QVariant &value, const QgsFeatureIds &ignoreIds=QgsFeatureIds())
Returns true if the specified value already exists within a field.
Definition: qgsvectorlayerutils.cpp:158
QgsFeatureIterator
Definition: qgsfeatureiterator.h:263
QgsVectorLayer::clone
QgsVectorLayer * clone() const override
Returns a new instance equivalent to this one.
Definition: qgsvectorlayer.cpp:238
QgsVectorLayer::addFeature
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) FINAL
Adds a single feature to the sink.
Definition: qgsvectorlayer.cpp:1011
qgsfeedback.h
QgsAbstractVectorLayerLabeling::accept
virtual bool accept(QgsStyleEntityVisitorInterface *visitor) const
Accepts the specified symbology visitor, causing it to visit all symbols associated with the labeling...
Definition: qgsvectorlayerlabeling.cpp:44
QgsFeatureRequest::setFlags
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
Definition: qgsfeaturerequest.cpp:184
QgsVectorLayerUtils::makeFeaturesCompatible
static QgsFeatureList makeFeaturesCompatible(const QgsFeatureList &features, const QgsVectorLayer *layer)
Converts input features to be compatible with the given layer.
Definition: qgsvectorlayerutils.cpp:786
qgsmultisurface.h
qgsproject.h
QgsField::type
QVariant::Type type
Definition: qgsfield.h:57
QgsStyleEntityVisitorInterface::Node::type
QgsStyleEntityVisitorInterface::NodeType type
Node type.
Definition: qgsstyleentityvisitor.h:125
QgsFields::OriginJoin
@ OriginJoin
Field comes from a joined layer (originIndex / 1000 = index of the join, originIndex % 1000 = index w...
Definition: qgsfields.h:52
QgsVectorLayer::joinBuffer
QgsVectorLayerJoinBuffer * joinBuffer()
Returns the join buffer object.
Definition: qgsvectorlayer.h:641
qgsstyleentityvisitor.h
QgsFieldConstraints::constraintOrigin
ConstraintOrigin constraintOrigin(Constraint constraint) const
Returns the origin of a field constraint, or ConstraintOriginNotSet if the constraint is not present ...
Definition: qgsfieldconstraints.cpp:19
QgsVectorLayer::setSubsetString
virtual bool setSubsetString(const QString &subset)
Sets the string (typically sql) used to define a subset of the layer.
Definition: qgsvectorlayer.cpp:943
QgsSymbol::symbolLayerCount
int symbolLayerCount() const
Returns the total number of symbol layers contained in the symbol.
Definition: qgssymbol.h:183
QgsFeatureId
qint64 QgsFeatureId
Definition: qgsfeatureid.h:25
QgsExpressionContext::setFeature
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Definition: qgsexpressioncontext.cpp:521
QgsVectorLayer::renderer
QgsFeatureRenderer * renderer()
Returns renderer.
Definition: qgsvectorlayer.h:881
QgsVectorLayerUtils::getFeatureDisplayString
static QString getFeatureDisplayString(const QgsVectorLayer *layer, const QgsFeature &feature)
Definition: qgsvectorlayerutils.cpp:961
QgsVectorLayerUtils::getDoubleValues
static QList< double > getDoubleValues(const QgsVectorLayer *layer, const QString &fieldOrExpression, bool &ok, bool selectedOnly=false, int *nullCount=nullptr, QgsFeedback *feedback=nullptr)
Fetches all double values from a specified field name or expression.
Definition: qgsvectorlayerutils.cpp:126
QgsField
Definition: qgsfield.h:49