Class: QgsVectorDataProvider¶
Base class for vector data providers.
Data providers abstract the retrieval and writing (where supported) of feature and attribute information from a spatial datasource.
Note
This is an abstract class, with methods which must be implemented by a subclass.
The following methods must be implemented: QgsDataProvider.crs()
, QgsDataProvider.description()
, QgsDataProvider.extent()
, featureSource()
, QgsDataProvider.isValid()
, QgsDataProvider.name()
Class Hierarchy¶
Base classes¶
Abstract base class for spatial data provider implementations. |
|
An interface for objects which accept features via addFeature(s) methods. |
|
An interface for objects which provide features via a getFeatures method. |
Enums
alias of |
|
Enumeration of feature count states |
Abstract Methods
Number of features in the layer |
|
Returns feature source object that can be used for querying provider's data. |
|
Returns the fields associated with this data provider. |
|
Query the provider for features specified in request. |
|
Returns the geometry type which is returned by this layer |
Methods
Returns the above in friendly format. |
|
Clear recorded errors |
|
Invalidates the min/max cache. |
|
Converts the geometry to the provider type if possible / necessary |
|
Returns the encoding which is used for accessing data. |
|
Gets recorded errors |
|
Returns any constraints which are present at the provider for a specified field index. |
|
Returns the index of a field name or -1 if the field does not exist |
|
Returns a map where the key is the name of the field and the value is its index |
|
Populates the cache of minimum and maximum attribute values. |
|
Provider has errors to report |
|
Returns the names of the supported types |
|
Returns list of indexes to names for |
|
Push a notification about errors that happened in this providers scope. |
|
Set the list of native types supported by this provider. |
|
check if provider supports type of field |
|
Gets this providers encoding |
Virtual Methods
In PyQGIS, only methods marked as virtual
can be safely overridden in a Python subclass of QgsVectorDataProvider. See the FAQ for more details.
Adds new attributes to the provider. |
|
Calculates an aggregated value from the layer's features. |
|
Returns the provider's supported attribute editing capabilities. |
|
Returns list of indexes to fetch all attributes in |
|
Cancels the current reloading of data. |
|
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. |
|
Changes attribute values of existing features. |
|
Changes attribute values and geometries of existing features. |
|
Changes geometries of existing features |
|
Create an attribute index on the datasource |
|
Creates labeling settings, using provider backend specific information. |
|
Creates a new vector layer feature renderer, using provider backend specific information. |
|
Creates a spatial index on the datasource (if supported by the provider type). |
|
Returns a short comment for the data that this provider is providing access to (e.g. the comment for postgres table). |
|
Returns any literal default values which are present at the provider for a specified field index. |
|
Returns any default value clauses which are present at the provider for a specified field index. |
|
Deletes existing attributes from the provider. |
|
Deletes one or more features from the provider. |
|
Gets the list of layer ids on which this layer depends. |
|
Discover the available relations with the given layers. |
|
Returns |
|
Returns |
|
Returns the possible enum values of an attribute. |
|
Returns the name of the column storing geometry, if applicable. |
|
Handles any post-clone operations required after this vector data provider was cloned from the source provider. |
|
Will always return FeatureAvailability.FeaturesAvailable or FeatureAvailability.NoFeaturesAvailable. |
|
Returns |
|
Returns |
|
Returns the maximum value of an attribute |
|
Gets metadata, dependent on the provider type, that will be display in the metadata tab of the layer properties. |
|
Returns the minimum value of an attribute |
|
Returns list of indexes of fields that make up the primary key |
|
Renames existing attributes. |
|
Set encoding used for accessing data from layer. |
|
Returns |
|
Returns the permanent storage type for this layer as a friendly name. |
|
Returns the transaction this data provider is included in, if any. |
|
Gets the translated metadata key. |
|
Gets the translated metadata value. |
|
Removes all features from the layer. |
|
Returns unique string values of an attribute which contain a specified subset string. |
|
Returns the vector layer type flags. |
Static Methods
Returns a list of available encodings |
|
Convert value to type |
Signals
Signals an error in this provider |
- class qgis.core.QgsVectorDataProvider[source]¶
Bases:
QgsDataProvider
,QgsFeatureSink
,QgsFeatureSource
- __init__(uri: str | None = '', providerOptions: QgsDataProvider.ProviderOptions = QgsDataProvider.ProviderOptions(), flags: Qgis.DataProviderReadFlags | Qgis.DataProviderReadFlag = Qgis.DataProviderReadFlags())
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 and since QGIS 3.16 creation flags are specified within theflags
value.- Parameters:
uri (Optional[str] = '')
providerOptions (QgsDataProvider.ProviderOptions = QgsDataProvider.ProviderOptions())
flags (Union[Qgis.DataProviderReadFlags, Qgis.DataProviderReadFlag] = Qgis.DataProviderReadFlags())
- Capabilities¶
alias of
VectorProviderCapabilities
- Capability¶
alias of
VectorProviderCapability
- class FeatureCountState(*values)¶
Bases:
IntEnum
Enumeration of feature count states
Added in version 3.20.
Uncounted
: Feature count not yet computedUnknownCount
: Provider returned an unknown feature count
- class NativeType(typeDesc: str | None, typeName: str | None, type: QMetaType.Type, minLen: int = 0, maxLen: int = 0, minPrec: int = 0, maxPrec: int = 0, subType: QMetaType.Type = QMetaType.Type.UnknownType)¶
- class NativeType(typeDesc: str | None, typeName: str | None, type: QVariant.Type, minLen: int = 0, maxLen: int = 0, minPrec: int = 0, maxPrec: int = 0, subType: QVariant.Type = QVariant.Type.Invalid)
- class NativeType(a0: QgsVectorDataProvider.NativeType)
Bases:
object
- mMaxLen¶
- mMaxPrec¶
- mMinLen¶
- mMinPrec¶
- mSubType¶
- mType¶
- mTypeDesc¶
- mTypeName¶
- virtual addAttributes(self, attributes: Any) bool [source]¶
Adds new
attributes
to the provider. ReturnsTrue
in case of success andFalse
in case of failure. If attributes are added using this method thenQgsVectorLayer.updateFields()
must be called manually to ensure that the layer’s field are correctly reported.- Parameters:
attributes (Any)
- Return type:
bool
- virtual aggregate(self, aggregate: Qgis.Aggregate, index: int, parameters: QgsAggregateCalculator.AggregateParameters, context: QgsExpressionContext | None, fids: Any | None = None)[source]¶
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 (Qgis.Aggregate) – aggregate to calculate
index (int) – the index of the attribute to calculate aggregate over
parameters (QgsAggregateCalculator.AggregateParameters) – parameters controlling aggregate calculation
context (Optional[QgsExpressionContext]) – expression context for filter
ok – will be set to
True
if calculation was successfully performed by the data providerfids (Optional[Any] = None) -> (Any) – list of fids to filter, otherwise will use all fids
- Returns:
calculated aggregate value
- virtual attributeEditCapabilities(self) Qgis.VectorDataProviderAttributeEditCapabilities [source]¶
Returns the provider’s supported attribute editing capabilities.
See also
Added in version 3.32.
- Return type:
- virtual attributeIndexes(self) List[int] [source]¶
Returns list of indexes to fetch all attributes in
nextFeature()
- Return type:
List[int]
- static availableEncodings() List[str] [source]¶
Returns a list of available encodings
- Return type:
List[str]
- virtual cancelReload(self) bool [source]¶
Cancels the current reloading of data.
- Return type:
bool
- Returns:
True
if the reloading has been correctly interrupted,False
otherwise
See also
reloadData()
Added in version 3.2.
- virtual capabilities(self) Qgis.VectorProviderCapabilities [source]¶
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.
See also
- Return type:
- virtual changeAttributeValues(self, attr_map: Any) bool [source]¶
Changes attribute values of existing features. This should succeed if the provider reports the ChangeAttributeValues capability. The method returns
False
if the provider does not have ChangeAttributeValues capability or if any of the changes could not be successfully applied.- Parameters:
attr_map (Any) – a map containing changed attributes
- Return type:
bool
- Returns:
True
in case of success andFalse
in case of failure
- virtual changeFeatures(self, attr_map: Any, geometry_map: Any) bool [source]¶
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 (Any) – a map containing changed attributes
geometry_map (Any) – A
QgsGeometryMap
whose index contains the feature IDs that will have their geometries changed. The second map parameter being the new geometries themselves
- Return type:
bool
- Returns:
True
in case of success andFalse
in case of failure
- virtual changeGeometryValues(self, geometry_map: Any) bool [source]¶
Changes geometries of existing features
- Parameters:
geometry_map (Any) – A
QgsGeometryMap
whose index contains the feature IDs that will have their geometries changed. The second map parameter being the new geometries themselves- Return type:
bool
- Returns:
True
in case of success andFalse
in case of failure
- clearMinMaxCache(self)[source]¶
Invalidates the min/max cache. This will force the provider to recalculate the cache the next time it is requested.
- convertToProviderType(self, geom: QgsGeometry) QgsGeometry [source]¶
Converts the geometry to the provider type if possible / necessary
- Return type:
- Returns:
the converted geometry or
None
if no conversion was necessary or possible
Note
The default implementation simply calls the static version of this function.
- Parameters:
geom (
QgsGeometry
)
- convertToProviderType(geometry: QgsGeometry, providerGeometryType: Qgis.WkbType) QgsGeometry [source]
Converts the
geometry
to the provider geometry typeproviderGeometryType
if possible / necessary- Return type:
- Returns:
the converted geometry or
None
if no conversion was necessary or possible
Added in version 3.34.
- Parameters:
geometry (
QgsGeometry
)providerGeometryType (Qgis.WkbType)
- static convertValue(type: QMetaType.Type, value: str | None) Any [source]¶
Convert
value
totype
- Parameters:
type (QMetaType.Type)
value (Optional[str])
- Return type:
Any
- static convertValue(type: QVariant.Type, value: str | None) Any [source]
Convert
value
totype
Deprecated since version 3.38: Use the method with a QMetaType.Type argument instead.
- Parameters:
type (QVariant.Type)
value (Optional[str])
- Return type:
Any
- virtual createAttributeIndex(self, field: int) bool [source]¶
Create an attribute index on the datasource
- Parameters:
field (int)
- Return type:
bool
- virtual createLabeling(self, configuration: Dict[str, Any] = {}) QgsAbstractVectorLayerLabeling | None [source]¶
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 ofconfiguration
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
.Added in version 3.6.
- Parameters:
configuration (Dict[str, Any] = {})
- Return type:
Optional[QgsAbstractVectorLayerLabeling]
- virtual createRenderer(self, configuration: Dict[str, Any] = {}) QgsFeatureRenderer | None [source]¶
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 ofconfiguration
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
.Added in version 3.2.
- Parameters:
configuration (Dict[str, Any] = {})
- Return type:
Optional[QgsFeatureRenderer]
- virtual createSpatialIndex(self) bool [source]¶
Creates a spatial index on the datasource (if supported by the provider type).
- Return type:
bool
- Returns:
True
in case of success
- virtual dataComment(self) str [source]¶
Returns a short comment for the data that this provider is providing access to (e.g. the comment for postgres table).
- Return type:
str
- virtual defaultValue(self, fieldIndex: int) Any [source]¶
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 asQgsVectorLayerUtils.createFeature()
so that default value handling and validation is automatically carried out.See also
- Parameters:
fieldIndex (int)
- Return type:
Any
- virtual defaultValueClause(self, fieldIndex: int) str [source]¶
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
- Parameters:
fieldIndex (int)
- Return type:
str
- virtual deleteAttributes(self, attributes: Any) bool [source]¶
Deletes existing
attributes
from the provider. If attributes are deleted using this method thenQgsVectorLayer.updateFields()
must be called manually to ensure that the layer’s field are correctly reported.- Parameters:
attributes (Any) – a set containing indices of attributes
- Return type:
bool
- Returns:
True
in case of success andFalse
in case of failure
- virtual deleteFeatures(self, id: Any) bool [source]¶
Deletes one or more features from the provider. This requires the DeleteFeatures capability.
- Parameters:
id (Any) – list containing feature ids to delete
- Return type:
bool
- Returns:
True
in case of success andFalse
in case of failure
See also
- virtual dependencies(self) Set[QgsMapLayerDependency] ¶
Gets the list of layer ids on which this layer depends. This in particular determines the order of layer loading.
- Return type:
- virtual discoverRelations(self, target: QgsVectorLayer | None, layers: Iterable[QgsVectorLayer]) List[QgsRelation] ¶
Discover the available relations with the given layers.
- Parameters:
target (Optional[QgsVectorLayer]) – the layer using this data provider.
layers (Iterable[QgsVectorLayer]) – the other layers.
- Return type:
List[QgsRelation]
- Returns:
the list of N-1 relations from this provider.
- virtual doesStrictFeatureTypeCheck(self) bool [source]¶
Returns
True
if the provider is strict about the type of inserted features (e.g. no multipolygon in a polygon layer)- Return type:
bool
- virtual empty(self) bool [source]¶
Returns
True
if the layer does not contain any feature.Added in version 3.4.
- Return type:
bool
- encoding(self) str [source]¶
Returns the encoding which is used for accessing data.
See also
- Return type:
str
- virtual enumValues(self, index: int) List[str] [source]¶
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 (int) – the index of the attribute
- Return type:
List[str]
- Returns:
reference to the list to fill
- abstract featureCount(self) int ¶
Number of features in the layer
- Return type:
int
- Returns:
number of features
- abstract featureSource(self) QgsAbstractFeatureSource | None [source]¶
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.
- Return type:
Optional[QgsAbstractFeatureSource]
- Returns:
new instance of
QgsAbstractFeatureSource
(caller is responsible for deleting it)
- fieldConstraints(self, fieldIndex: int) QgsFieldConstraints.Constraints [source]¶
Returns any constraints which are present at the provider for a specified field index.
See also
- Parameters:
fieldIndex (int)
- Return type:
- fieldNameIndex(self, fieldName: str | None) int [source]¶
Returns the index of a field name or -1 if the field does not exist
- Parameters:
fieldName (Optional[str])
- Return type:
int
- fieldNameMap(self) Any ¶
Returns a map where the key is the name of the field and the value is its index
- Return type:
Any
- abstract fields(self) QgsFields [source]¶
Returns the fields associated with this data provider.
- Return type:
- virtual forceReload(self)[source]¶
Deprecated since version 3.12.
Will be removed in QGIS 4.0 - use
reloadData()
instead.
- virtual geometryColumnName(self) str [source]¶
Returns the name of the column storing geometry, if applicable.
Added in version 3.42.
- Return type:
str
- abstract getFeatures(self, request: QgsFeatureRequest = QgsFeatureRequest()) QgsFeatureIterator [source]¶
Query the provider for features specified in request.
- Parameters:
request (
QgsFeatureRequest
= QgsFeatureRequest()) – feature request describing parameters of features to return- Return type:
- Returns:
iterator for matching features from provider
- virtual handlePostCloneOperations(self, source: QgsVectorDataProvider | None)[source]¶
Handles any post-clone operations required after this vector data provider was cloned from the
source
provider.Added in version 3.8.1.
- Parameters:
source (Optional[QgsVectorDataProvider])
- virtual hasFeatures(self) Qgis.FeatureAvailability [source]¶
Will always return FeatureAvailability.FeaturesAvailable or FeatureAvailability.NoFeaturesAvailable.
Calls
empty()
internally. Providers should overrideempty()
instead if they provide an optimized version of this call.See also
Added in version 3.4.
- Return type:
- virtual hasMetadata(self) bool [source]¶
Returns
True
if the data source has metadata,False
otherwise.- Return type:
bool
- Returns:
True
if data source has metadata,False
otherwise.
- virtual isSqlQuery(self) bool [source]¶
Returns
True
if the layer is a query (SQL) layer.Note
this is simply a shortcut to check if the SqlQuery flag is set.
See also
Added in version 3.24.
- Return type:
bool
- virtual maximumValue(self, index: int) Any [source]¶
Returns the maximum value of an attribute
- Parameters:
index (int) – 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.
- Return type:
Any
- virtual metadata(self) Dict[str, Any] [source]¶
Gets metadata, dependent on the provider type, that will be display in the metadata tab of the layer properties.
- Return type:
Dict[str, Any]
- Returns:
The provider metadata
- virtual minimumValue(self, index: int) Any [source]¶
Returns the minimum value of an attribute
- Parameters:
index (int) – 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.
- Return type:
Any
- nativeTypes(self) List[QgsVectorDataProvider.NativeType] ¶
Returns the names of the supported types
- Return type:
- palAttributeIndexNames(self) Dict[int, str] [source]¶
Returns list of indexes to names for
QgsPalLabeling
fixDeprecated since version 3.32: This method is unused and will always return an empty hash.
- Return type:
Dict[int, str]
- virtual pkAttributeIndexes(self) List[int] [source]¶
Returns list of indexes of fields that make up the primary key
- Return type:
List[int]
- pushError(self, msg: str | None)[source]¶
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.- Parameters:
msg (Optional[str])
- virtual renameAttributes(self, renamedAttributes: Dict[int, str | None]) bool [source]¶
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 (Dict[int, Optional[str]]) – map of attribute index to new attribute name
- Return type:
bool
- Returns:
True
in case of success andFalse
in case of failure
- virtual setEncoding(self, e: str | None)[source]¶
Set encoding used for accessing data from layer.
An empty encoding string indicates that the provider should automatically select the most appropriate encoding for the data source.
Warning
Support for setting the provider encoding depends on the underlying data provider. Check
capabilities()
for the QgsVectorDataProvider.SelectEncoding capability in order to determine if the provider supports this ability.See also
- Parameters:
e (Optional[str])
- setNativeTypes(self, nativeTypes: Iterable[QgsVectorDataProvider.NativeType])[source]¶
Set the list of native types supported by this provider. Usually done in the constructor.
- Parameters:
nativeTypes (Iterable[QgsVectorDataProvider.NativeType])
- virtual skipConstraintCheck(self, fieldIndex: int, constraint: QgsFieldConstraints.Constraint, value: Any = None) bool [source]¶
Returns
True
if a constraint check should be skipped for a specified field (e.g., if the value returned bydefaultValue()
is trusted implicitly. An optional attribute value can be passed which can help refine the skip constraint check.See also
- Parameters:
fieldIndex (int)
constraint (QgsFieldConstraints.Constraint)
value (Any = None)
- Return type:
bool
- virtual storageType(self) str [source]¶
Returns the permanent storage type for this layer as a friendly name.
- Return type:
str
- supportedType(self, field: QgsField) bool [source]¶
check if provider supports type of field
- Parameters:
field (QgsField)
- Return type:
bool
- textEncoding(self) QTextCodec | None [source]¶
Gets this providers encoding
- Return type:
Optional[QTextCodec]
- virtual transaction(self) QgsTransaction | None [source]¶
Returns the transaction this data provider is included in, if any.
- Return type:
Optional[QgsTransaction]
- virtual translateMetadataKey(self, mdKey: str | None) str [source]¶
Gets the translated metadata key.
- Parameters:
mdKey (Optional[str]) – The metadata key
- Return type:
str
- Returns:
The translated metadata value
- virtual translateMetadataValue(self, mdKey: str | None, value: Any) str [source]¶
Gets the translated metadata value.
- Parameters:
mdKey (Optional[str]) – The metadata key
value (Any) – The metadata value
- Return type:
str
- Returns:
The translated metadata value
- virtual truncate(self) bool [source]¶
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.
- Return type:
bool
- Returns:
True
in case of success andFalse
in case of failure.
See also
- virtual uniqueStringsMatching(self, index: int, substring: str | None, limit: int = -1, feedback: QgsFeedback | None = None) List[str] [source]¶
Returns unique string values of an attribute which contain a specified subset string. Subset matching is done in a case-insensitive manner.
- Parameters:
index (int) – the index of the attribute
substring (Optional[str]) – substring to match (case insensitive)
limit (int = -1) – maxmum number of the values to return, or -1 to return all unique values
feedback (Optional[QgsFeedback] = None) – optional feedback object for canceling request
- Return type:
List[str]
- Returns:
list of unique strings containing substring
- virtual vectorLayerTypeFlags(self) Qgis.VectorLayerTypeFlags [source]¶
Returns the vector layer type flags.
See also
Added in version 3.24.
- Return type:
- abstract wkbType(self) Qgis.WkbType [source]¶
Returns the geometry type which is returned by this layer
- Return type: