Skip to content

Commit 12094db

Browse files
committedJun 5, 2019
createFeatures check unique constraints on unfiltered layer
Fixes #30062
1 parent 74d6b23 commit 12094db

File tree

4 files changed

+38
-2
lines changed

4 files changed

+38
-2
lines changed
 

‎src/core/qgsvectorlayerutils.cpp

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,19 @@ QgsFeatureList QgsVectorLayerUtils::createFeatures( const QgsVectorLayer *layer,
491491

492492
// Cache unique values
493493
if ( hasUniqueConstraint && ! uniqueValueCaches.contains( idx ) )
494-
uniqueValueCaches[ idx ] = layer->uniqueValues( idx );
494+
{
495+
// If the layer is filtered, get unique values from an unfiltered clone
496+
if ( ! layer->subsetString().isEmpty() )
497+
{
498+
QgsVectorLayer *unfilteredClone { layer->clone( ) };
499+
unfilteredClone->setSubsetString( QString( ) );
500+
uniqueValueCaches[ idx ] = unfilteredClone->uniqueValues( idx );
501+
}
502+
else
503+
{
504+
uniqueValueCaches[ idx ] = layer->uniqueValues( idx );
505+
}
506+
}
495507

496508
// 2. client side default expression
497509
// note - deliberately not using else if!

‎tests/src/python/test_qgsvectorlayerutils.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212

1313
import os
1414
import qgis # NOQA
15+
import shutil
16+
import tempfile
1517

1618
from qgis.PyQt.QtCore import QVariant
1719
from qgis.core import (QgsProject,
@@ -32,7 +34,7 @@
3234
NULL
3335
)
3436
from qgis.testing import start_app, unittest
35-
37+
from utilities import unitTestDataPath
3638

3739
start_app()
3840

@@ -614,6 +616,28 @@ def test_create_nulls_and_defaults(self):
614616
for f in features:
615617
self.assertEqual(f.attributes()[0], 'my_default', f.id())
616618

619+
def test_unique_pk_when_subset(self):
620+
"""Test unique values on filtered layer GH #30062"""
621+
622+
src = unitTestDataPath('points_gpkg.gpkg')
623+
dest = tempfile.mktemp() + '.gpkg'
624+
shutil.copy(src, dest)
625+
vl = QgsVectorLayer(dest, 'vl', 'ogr')
626+
self.assertTrue(vl.isValid())
627+
features_data = []
628+
it = vl.getFeatures()
629+
for _ in range(3):
630+
f = next(it)
631+
features_data.append(QgsVectorLayerUtils.QgsFeatureData(f.geometry(), dict(zip(range(f.fields().count()), f.attributes()))))
632+
# Set a filter
633+
vl.setSubsetString('"fid" in (4,5,6)')
634+
self.assertTrue(vl.isValid())
635+
context = vl.createExpressionContext()
636+
features = QgsVectorLayerUtils.createFeatures(vl, features_data, context)
637+
self.assertTrue(vl.startEditing())
638+
vl.addFeatures(features)
639+
self.assertTrue(vl.commitChanges())
640+
617641

618642
if __name__ == '__main__':
619643
unittest.main()

‎tests/testdata/humanbeings.gpkg

0 Bytes
Binary file not shown.

‎tests/testdata/points_gpkg.gpkg

0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)
Please sign in to comment.