[QGIS-Developer] PyQGIS - how to handle primary keys in geopackage
Nyall Dawson
nyall.dawson at gmail.com
Wed Mar 28 15:01:23 PDT 2018
On 28 March 2018 at 08:32, Alexandre Neto <senhor.neto at gmail.com> wrote:
> My multipart split plugin (which I am porting to 3), It breaks multipart
> features and transforms each part in individual features, copying the
> attributes from the original feature.
>
> In the process, I need to be careful with the autoincrement primary keys.
> For PostGIS and Spatialite, asking for the providers pkattributesindex works
> and I can do the following:
>
> new_attributes = feature.attributes()
>
> # When attribute is a Primary Key, replace by default value
> ### This is not working well with spatialite provider###
> for j in provider.pkAttributeIndexes():
> if provider.defaultValue(j):
> new_attributes[j] = provider.defaultValue(j)
> else:
> new_attributes[j] = QVariant()
>
> But for geopackage the provider.pkAttributeIndexes() always returns an empty
> list...
>
> The above code was copied a long time ago from the split features tools in
> core. Looking at the code now, there is no longer that part where the
> provider's primary keys are searched, Nevertheless, the code works and the
> split features tool leave the pkattributes NULL to be autogenerated. Wasn't
> able to figure out where that is done now ...
The canonical/correct 3.0 way to do this is to use
QgsVectorLayerUtils.createFeature
That method should be used whenever you are creating a brand new
feature which is destined for a particular vector layer, and needs to
correctly respect constraints and default value clauses set on the
provider side.
Nyall
More information about the QGIS-Developer
mailing list