Class: QgsVectorDataProvider

class qgis.core.QgsVectorDataProvider(uri: str = '', providerOptions: QgsDataProvider.ProviderOptions = QgsDataProvider.ProviderOptions())

Bases: qgis._core.QgsDataProvider, qgis._core.QgsFeatureSink, qgis._core.QgsFeatureSource

Constructor for a vector data provider.

The uri argument specifies the uniform resource locator (URI) for the associated dataset.

Additional creation options are specified within the options value.

This is the base class for vector data providers.

Data providers abstract the retrieval and writing (where supported) of feature and attribute information from a spatial datasource.

Enums

Methods

addAttributes

Adds new attributes to the provider.

addFeatures

aggregate

Calculates an aggregated value from the layer’s features.

appendError

attributeIndexes

Returns list of indexes to fetch all attributes in nextFeature()

availableEncodings

Returns a list of available encodings

cancelReload

Cancels the current reloading of data.

capabilities

Returns flags containing the supported capabilities note, some capabilities may change depending on whether a spatial filter is active on this provider, so it may be prudent to check this value per intended operation.

capabilitiesString

Returns the above in friendly format.

changeAttributeValues

Changes attribute values of existing features.

changeFeatures

Changes attribute values and geometries of existing features.

changeGeometryValues

Changes geometries of existing features

childEvent

clearErrors

Clear recorded errors

clearMinMaxCache

Invalidates the min/max cache.

connectNotify

convertToProviderType

Converts the geometry to the provider type if possible / necessary

convertValue

createAttributeIndex

Create an attribute index on the datasource

createLabeling

Creates labeling settings, using provider backend specific information.

createRenderer

Creates a new vector layer feature renderer, using provider backend specific information.

createSpatialIndex

Creates a spatial index on the datasource (if supported by the provider type).

customEvent

dataComment

Returns a short comment for the data that this provider is providing access to (e.g.

defaultValue

Returns any literal default values which are present at the provider for a specified field index.

defaultValueClause

Returns any default value clauses which are present at the provider for a specified field index.

deleteAttributes

Deletes existing attributes from the provider.

deleteFeatures

Deletes one or more features from the provider.

dependencies

Gets the list of layer ids on which this layer depends.

disconnectNotify

discoverRelations

Discover the available relations with the given layers.

doesStrictFeatureTypeCheck

Returns True if the provider is strict about the type of inserted features (e.g.

empty

Returns True if the layer contains at least one feature.

encoding

Gets encoding which is used for accessing data

enumValues

Returns the possible enum values of an attribute.

errors

Gets recorded errors

featureCount

Number of features in the layer

featureSource

Returns feature source object that can be used for querying provider’s data.

fieldConstraints

Returns any constraints which are present at the provider for a specified field index.

fieldNameIndex

Returns the index of a field name or -1 if the field does not exist

fieldNameMap

Returns a map where the key is the name of the field and the value is its index

fields

Returns the fields associated with this data provider.

fillMinMaxCache

Populates the cache of minimum and maximum attribute values.

forceReload

Forces a reload of the underlying datasource if the provider implements this method.

getFeatures

Query the provider for features specified in request.

hasErrors

Provider has errors to report

hasFeatures

Will always return FeatureAvailability.FeaturesAvailable or FeatureAvailability.NoFeaturesAvailable.

hasMetadata

Returns True if the data source has metadata, False otherwise.

isDeleteStyleFromDatabaseSupported

It returns False by default.

isSaveAndLoadStyleToDatabaseSupported

It returns False by default.

isSignalConnected

maximumValue

Returns the maximum value of an attribute

metadata

Gets metadata, dependent on the provider type, that will be display in the metadata tab of the layer properties.

minimumValue

Returns the minimum value of an attribute

nativeTypes

Returns the names of the supported types

palAttributeIndexNames

Returns list of indexes to names for QgsPalLabeling fix

pkAttributeIndexes

Returns list of indexes of fields that make up the primary key

pushError

Push a notification about errors that happened in this providers scope.

receivers

renameAttributes

Renames existing attributes.

sender

senderSignalIndex

setEncoding

Set encoding used for accessing data from layer

setError

setNativeTypes

Set the list of native types supported by this provider.

skipConstraintCheck

Returns True if a constraint check should be skipped for a specified field (e.g., if the value returned by defaultValue() is trusted implicitly.

sourceCrs

sourceExtent

sourceName

storageType

Returns the permanent storage type for this layer as a friendly name.

supportedType

check if provider supports type of field

textEncoding

Gets this providers encoding

timerEvent

transaction

Returns the transaction this data provider is included in, if any.

translateMetadataKey

Gets the translated metadata key.

translateMetadataValue

Gets the translated metadata value.

truncate

Removes all features from the layer.

uniqueStringsMatching

Returns unique string values of an attribute which contain a specified subset string.

wkbType

Returns the geometry type which is returned by this layer

Signals

raiseError

Signals an error in this provider

Attributes

AddAttributes

AddFeatures

CancelSupport

ChangeAttributeValues

ChangeFeatures

ChangeGeometries

CircularGeometries

CreateAttributeIndex

CreateLabeling

CreateRenderer

CreateSpatialIndex

DeleteAttributes

DeleteFeatures

EditingCapabilities

FastTruncate

NoCapabilities

ReadLayerMetadata

RenameAttributes

SelectAtId

SelectEncoding

SimplifyGeometries

SimplifyGeometriesWithTopologicalValidation

TransactionSupport

Uncounted

UnknownCount

WriteLayerMetadata

AddAttributes = 8
AddFeatures = 1
CancelSupport = 8388608
class Capabilities

Bases: sip.wrapper

QgsVectorDataProvider.Capabilities(Union[QgsVectorDataProvider.Capabilities, QgsVectorDataProvider.Capability]) QgsVectorDataProvider.Capabilities(QgsVectorDataProvider.Capabilities)

class Capability

Bases: int

ChangeAttributeValues = 4
ChangeFeatures = 262144
ChangeGeometries = 256
CircularGeometries = 131072
CreateAttributeIndex = 4096
CreateLabeling = 33554432
CreateRenderer = 16777216
CreateSpatialIndex = 64
DeleteAttributes = 16
DeleteFeatures = 2
EditingCapabilities = 524575
FastTruncate = 1048576
class FeatureCountState

Bases: int

class NativeType(typeDesc: str, typeName: str, type: QVariant.Type, minLen: int = 0, maxLen: int = 0, minPrec: int = 0, maxPrec: int = 0, subType: QVariant.Type = QVariant.Invalid)

Bases: sip.wrapper

QgsVectorDataProvider.NativeType(QgsVectorDataProvider.NativeType)

mMaxLen
mMaxPrec
mMinLen
mMinPrec
mSubType
mType
mTypeDesc
mTypeName
NoCapabilities = 0
ReadLayerMetadata = 2097152
RenameAttributes = 524288
SelectAtId = 128
SelectEncoding = 8192
SimplifyGeometries = 16384
SimplifyGeometriesWithTopologicalValidation = 32768
TransactionSupport = 65536
Uncounted = -2
UnknownCount = -1
WriteLayerMetadata = 4194304
addAttributes(self, attributes: object) → bool

Adds new attributes to the provider. Returns True in case of success and False in case of failure. If attributes are added using this method then QgsVectorLayer.updateFields() must be called manually to ensure that the layer’s field are correctly reported.

addFeatures(self, flist: Iterable[QgsFeature], flags: Union[QgsFeatureSink.Flags, QgsFeatureSink.Flag] = 0) → Tuple[bool, List[QgsFeature]]
aggregate(self, aggregate: QgsAggregateCalculator.Aggregate, index: int, parameters: QgsAggregateCalculator.AggregateParameters, context: QgsExpressionContext, fids: object = None) → Tuple[Any, bool]

Calculates an aggregated value from the layer’s features. The base implementation does nothing, but subclasses can override this method to handoff calculation of aggregates to the provider.

Parameters
  • aggregate – aggregate to calculate

  • index – the index of the attribute to calculate aggregate over

  • parameters – parameters controlling aggregate calculation

  • context – expression context for filter

  • ok – will be set to True if calculation was successfully performed by the data provider

  • fids – list of fids to filter, otherwise will use all fids

Returns

calculated aggregate value

New in version 2.16.

appendError()
attributeIndexes(self) → List[int]

Returns list of indexes to fetch all attributes in nextFeature()

availableEncodings() → List[str]

Returns a list of available encodings

cancelReload(self) → bool

Cancels the current reloading of data.

Returns

True if the reloading has been correctly interrupted, False otherwise

See also

reloadData()

New in version 3.2.

capabilities(self) → QgsVectorDataProvider.Capabilities

Returns flags containing the supported capabilities note, some capabilities may change depending on whether a spatial filter is active on this provider, so it may be prudent to check this value per intended operation.

capabilitiesString(self) → str

Returns the above in friendly format.

changeAttributeValues(self, attr_map: object) → bool

Changes attribute values of existing features. This should succeed if the provider reports the ChangeAttributeValues capability.

Parameters

attr_map – a map containing changed attributes

Returns

True in case of success and False in case of failure

changeFeatures(self, attr_map: object, geometry_map: object) → bool

Changes attribute values and geometries of existing features. This should succeed if the provider reports both the ChangeAttributeValues and ChangeGeometries capabilities. Providers which report the ChangeFeatures capability implement an optimised version of this method.

Parameters
  • attr_map – a map containing changed attributes

  • geometry_map – A QgsGeometryMap whose index contains the feature IDs that will have their geometries changed. The second map parameter being the new geometries themselves

Returns

True in case of success and False in case of failure

changeGeometryValues(self, geometry_map: object) → bool

Changes geometries of existing features

Parameters

geometry_map – A QgsGeometryMap whose index contains the feature IDs that will have their geometries changed. The second map parameter being the new geometries themselves

Returns

True in case of success and False in case of failure

childEvent()
clearErrors(self)

Clear recorded errors

clearMinMaxCache(self)

Invalidates the min/max cache. This will force the provider to recalculate the cache the next time it is requested.

connectNotify()
convertToProviderType(self, geom: QgsGeometry) → QgsGeometry

Converts the geometry to the provider type if possible / necessary

Returns

the converted geometry or None if no conversion was necessary or possible

convertValue(type: QVariant.Type, value: str) → Any
createAttributeIndex(self, field: int) → bool

Create an attribute index on the datasource

createLabeling(self, configuration: Dict[str, Any] = {}) → QgsAbstractVectorLayerLabeling

Creates labeling settings, using provider backend specific information.

The configuration map can be used to pass provider-specific configuration maps to the provider to allow customization of the returned labeling object. Support and format of configuration varies by provider.

When called with an empty configuration map the provider’s default labeling settings will be returned.

This method returns a new labeling settings and the caller takes ownership of the returned object.

Only providers which report the CreateLabeling capability will return labeling settings. Other providers will return None.

New in version 3.6.

createRenderer(self, configuration: Dict[str, Any] = {}) → QgsFeatureRenderer

Creates a new vector layer feature renderer, using provider backend specific information.

The configuration map can be used to pass provider-specific configuration maps to the provider to allow customization of the returned renderer. Support and format of configuration varies by provider.

When called with an empty configuration map the provider’s default renderer will be returned.

This method returns a new renderer and the caller takes ownership of the returned object.

Only providers which report the CreateRenderer capability will return a feature renderer. Other providers will return None.

New in version 3.2.

createSpatialIndex(self) → bool

Creates a spatial index on the datasource (if supported by the provider type).

Returns

True in case of success

customEvent()
dataComment(self) → str

Returns a short comment for the data that this provider is providing access to (e.g. the comment for postgres table).

defaultValue(self, fieldIndex: int) → Any

Returns any literal default values which are present at the provider for a specified field index. Important - this should ONLY be called when creating an attribute to insert directly into the database. Do not call this method for non-feature creation or modification, e.g., when validating an attribute or to compare it against an existing value, as calling it can cause changes to the underlying data source (e.g., Postgres provider where the default value is calculated as a result of a sequence). It is recommended that you instead use the methods in QgsVectorLayerUtils such as QgsVectorLayerUtils.createFeature() so that default value handling and validation is automatically carried out.

defaultValueClause(self, fieldIndex: int) → str

Returns any default value clauses which are present at the provider for a specified field index. These clauses are usually SQL fragments which must be evaluated by the provider, e.g., sequence values.

See also

defaultValue()

New in version 3.0.

deleteAttributes(self, attributes: object) → bool

Deletes existing attributes from the provider. If attributes are deleted using this method then QgsVectorLayer.updateFields() must be called manually to ensure that the layer’s field are correctly reported.

Parameters

attributes – a set containing indices of attributes

Returns

True in case of success and False in case of failure

deleteFeatures(self, id: object) → bool

Deletes one or more features from the provider. This requires the DeleteFeatures capability.

Parameters

id – list containing feature ids to delete

Returns

True in case of success and False in case of failure

See also

truncate()

dependencies(self) → Set[QgsMapLayerDependency]

Gets the list of layer ids on which this layer depends. This in particular determines the order of layer loading.

disconnectNotify()
discoverRelations(self, self: QgsVectorLayer, layers: Iterable[QgsVectorLayer]) → List[QgsRelation]

Discover the available relations with the given layers.

Parameters
  • self – the layer using this data provider.

  • layers – the other layers.

Returns

the list of N-1 relations from this provider.

New in version 3.0.

doesStrictFeatureTypeCheck(self) → bool

Returns True if the provider is strict about the type of inserted features (e.g. no multipolygon in a polygon layer)

empty(self) → bool

Returns True if the layer contains at least one feature.

New in version 3.4.

encoding(self) → str

Gets encoding which is used for accessing data

enumValues(self, index: int) → List[str]

Returns the possible enum values of an attribute. Returns an empty stringlist if a provider does not support enum types or if the given attribute is not an enum type.

Parameters

index – the index of the attribute

errors(self) → List[str]

Gets recorded errors

featureCount(self) → int

Number of features in the layer

Returns

long containing number of features

featureSource(self) → QgsAbstractFeatureSource

Returns feature source object that can be used for querying provider’s data. The returned feature source is independent from provider - any changes to provider’s state (e.g. change of subset string) will not be reflected in the feature source, therefore it can be safely used for processing in background without having to care about possible changes within provider that may happen concurrently. Also, even in the case of provider being deleted, any feature source obtained from the provider will be kept alive and working (they are independent and owned by the caller).

Sometimes there are cases when some data needs to be shared between vector data provider and its feature source. In such cases, the implementation must ensure that the data is not susceptible to run condition. For example, if it is possible that both feature source and provider may need reading/writing to some shared data at the same time, some synchronization mechanisms must be used (e.g. mutexes) to prevent data corruption.

Returns

new instance of QgsAbstractFeatureSource (caller is responsible for deleting it)

New in version 2.4.

fieldConstraints(self, fieldIndex: int) → QgsFieldConstraints.Constraints

Returns any constraints which are present at the provider for a specified field index.

New in version 3.0.

fieldNameIndex(self, fieldName: str) → int

Returns the index of a field name or -1 if the field does not exist

fieldNameMap(self) → object

Returns a map where the key is the name of the field and the value is its index

fields(self) → QgsFields

Returns the fields associated with this data provider.

fillMinMaxCache(self)

Populates the cache of minimum and maximum attribute values.

forceReload(self)

Forces a reload of the underlying datasource if the provider implements this method. In particular on the OGR provider, a pooled connection will be invalidated. This forces QGIS to reopen a file or connection. This can be required if the underlying file is replaced.

getFeatures(self, request: QgsFeatureRequest = QgsFeatureRequest()) → QgsFeatureIterator

Query the provider for features specified in request.

Parameters

request – feature request describing parameters of features to return

Returns

iterator for matching features from provider

hasErrors(self) → bool

Provider has errors to report

hasFeatures(self) → QgsFeatureSource.FeatureAvailability

Will always return FeatureAvailability.FeaturesAvailable or FeatureAvailability.NoFeaturesAvailable.

Calls empty() internally. Providers should override empty() instead if they provide an optimized version of this call.

See also

empty()

New in version 3.4.

hasMetadata(self) → bool

Returns True if the data source has metadata, False otherwise.

Returns

True if data source has metadata, False otherwise.

New in version 3.0.

isDeleteStyleFromDatabaseSupported(self) → bool

It returns False by default. Must be implemented by providers that support delete styles from db returning True

isSaveAndLoadStyleToDatabaseSupported(self) → bool

It returns False by default. Must be implemented by providers that support saving and loading styles to db returning True

isSignalConnected()
maximumValue(self, index: int) → Any

Returns the maximum value of an attribute

Parameters

index – the index of the attribute

Default implementation walks all numeric attributes and caches minimal and maximal values. If provider has facilities to retrieve maximal value directly, override this function.

metadata(self) → Dict[str, Any]

Gets metadata, dependent on the provider type, that will be display in the metadata tab of the layer properties.

Returns

The provider metadata

minimumValue(self, index: int) → Any

Returns the minimum value of an attribute

Parameters

index – the index of the attribute

Default implementation walks all numeric attributes and caches minimal and maximal values. If provider has facilities to retrieve minimal value directly, override this function.

nativeTypes(self) → List[QgsVectorDataProvider.NativeType]

Returns the names of the supported types

palAttributeIndexNames(self) → Dict[int, str]

Returns list of indexes to names for QgsPalLabeling fix

pkAttributeIndexes(self) → List[int]

Returns list of indexes of fields that make up the primary key

pushError(self, msg: str)

Push a notification about errors that happened in this providers scope. Errors should be translated strings that require the users immediate attention.

For general debug information use QgsMessageLog.logMessage() instead.

New in version 3.0.

raiseError

Signals an error in this provider

New in version 3.0: [signal]

receivers()
renameAttributes(self, renamedAttributes: Dict[int, str]) → bool

Renames existing attributes. If attributes are renamed using this method then QgsVectorLayer.updateFields() must be called manually to ensure that the layer’s field are correctly reported.

Parameters

renamedAttributes – map of attribute index to new attribute name

Returns

True in case of success and False in case of failure

New in version 2.16.

sender()
senderSignalIndex()
setEncoding(self, e: str)

Set encoding used for accessing data from layer

setError()
setNativeTypes(self, nativeTypes: Iterable[QgsVectorDataProvider.NativeType])

Set the list of native types supported by this provider. Usually done in the constructor.

New in version 3.0.

skipConstraintCheck(self, fieldIndex: int, constraint: QgsFieldConstraints.Constraint, value: Any = None) → bool

Returns True if a constraint check should be skipped for a specified field (e.g., if the value returned by defaultValue() is trusted implicitly. An optional attribute value can be passed which can help refine the skip constraint check.

New in version 3.0.

sourceCrs(self) → QgsCoordinateReferenceSystem
sourceExtent(self) → QgsRectangle
sourceName(self) → str
storageType(self) → str

Returns the permanent storage type for this layer as a friendly name.

supportedType(self, field: QgsField) → bool

check if provider supports type of field

textEncoding(self) → QTextCodec

Gets this providers encoding

New in version 3.0.

timerEvent()
transaction(self) → QgsTransaction

Returns the transaction this data provider is included in, if any.

translateMetadataKey(self, mdKey: str) → str

Gets the translated metadata key.

Parameters

mdKey – The metadata key

Returns

The translated metadata value

translateMetadataValue(self, mdKey: str, value: Any) → str

Gets the translated metadata value.

Parameters
  • mdKey – The metadata key

  • value – The metadata value

Returns

The translated metadata value

truncate(self) → bool

Removes all features from the layer. This requires either the FastTruncate or DeleteFeatures capability. Providers with the FastTruncate capability will use an optimised method to truncate the layer.

Returns

True in case of success and False in case of failure.

See also

deleteFeatures()

New in version 3.0.

uniqueStringsMatching(self, index: int, substring: str, limit: int = -1, feedback: QgsFeedback = None) → List[str]

Returns unique string values of an attribute which contain a specified subset string. Subset matching is done in a case-insensitive manner.

Parameters
  • index – the index of the attribute

  • substring – substring to match (case insensitive)

  • limit – maxmum number of the values to return, or -1 to return all unique values

  • feedback – optional feedback object for canceling request

Returns

list of unique strings containing substring

wkbType(self) → QgsWkbTypes.Type

Returns the geometry type which is returned by this layer