@@ -380,17 +380,32 @@ QgsFeature QgsVectorLayerUtils::createFeature( const QgsVectorLayer *layer, cons
380380 bool checkUnique = true ;
381381
382382 // in order of priority:
383+ // 1. passed attribute value and if field does not have a unique constraint like primary key
384+ if ( attributes.contains ( idx ) )
385+ {
386+ v = attributes.value ( idx );
387+ if ( fields.at ( idx ).constraints ().constraints () & QgsFieldConstraints::ConstraintUnique
388+ && QgsVectorLayerUtils::valueExists ( layer, idx, v ) )
389+ {
390+ // unique constraint violated
391+ QVariant uniqueValue = QgsVectorLayerUtils::createUniqueValue ( layer, idx, v );
392+ if ( uniqueValue.isValid () )
393+ v = uniqueValue;
394+ }
395+ checkUnique = false ;
396+ }
383397
384- // 1. client side default expression
385- if ( layer->defaultValueDefinition ( idx ).isValid () )
398+ // 2. client side default expression
399+ // note - deliberately not using else if!
400+ if ( !v.isValid () && layer->defaultValueDefinition ( idx ).isValid () )
386401 {
387402 // client side default expression set - takes precedence over all. Why? Well, this is the only default
388403 // which QGIS users have control over, so we assume that they're deliberately overriding any
389404 // provider defaults for some good reason and we should respect that
390405 v = layer->defaultValue ( idx, newFeature, evalContext );
391406 }
392407
393- // 2 . provider side default value clause
408+ // 3 . provider side default value clause
394409 // note - not an else if deliberately. Users may return null from a default value expression to fallback to provider defaults
395410 if ( !v.isValid () && fields.fieldOrigin ( idx ) == QgsFields::OriginProvider )
396411 {
@@ -403,7 +418,7 @@ QgsFeature QgsVectorLayerUtils::createFeature( const QgsVectorLayer *layer, cons
403418 }
404419 }
405420
406- // 3 . provider side default literal
421+ // 4 . provider side default literal
407422 // note - deliberately not using else if!
408423 if ( !v.isValid () && fields.fieldOrigin ( idx ) == QgsFields::OriginProvider )
409424 {
@@ -416,13 +431,6 @@ QgsFeature QgsVectorLayerUtils::createFeature( const QgsVectorLayer *layer, cons
416431 }
417432 }
418433
419- // 4. passed attribute value
420- // note - deliberately not using else if!
421- if ( !v.isValid () && attributes.contains ( idx ) )
422- {
423- v = attributes.value ( idx );
424- }
425-
426434 // last of all... check that unique constraints are respected
427435 // we can't handle not null or expression constraints here, since there's no way to pick a sensible
428436 // value if the constraint is violated
0 commit comments