QGIS API Documentation
3.26.3-Buenos Aires (65e4edfdad)
|
Go to the documentation of this file.
30 #define AS_JOINFIELD QStringLiteral( "ASPK" )
31 #define AS_EXTENSION QStringLiteral( "qgd" )
32 #define AS_JOINPREFIX QStringLiteral( "auxiliary_storage_" )
68 :
QgsVectorLayer( QStringLiteral( "%1|layername=%2" ).arg( filename, table ),
69 QStringLiteral( "%1_auxiliarystorage" ).arg( table ), QStringLiteral( "ogr" ) )
70 , mFileName( filename )
76 mJoinInfo.setJoinLayer(
this );
78 mJoinInfo.setTargetFieldName( pkField );
79 mJoinInfo.setEditable(
true );
80 mJoinInfo.setUpsertOnEdit(
true );
81 mJoinInfo.setCascadedDelete(
true );
82 mJoinInfo.setJoinFieldNamesBlockList( QStringList() << QStringLiteral(
"rowid" ) );
142 if ( ( definition.
name().isEmpty() && definition.
comment().isEmpty() ) ||
exists( definition ) )
155 if ( index >= 0 && auxIndex >= 0 )
166 QVector<QgsAttributeTableConfig::ColumnConfig> columns = attrCfg.
columns();
167 QVector<QgsAttributeTableConfig::ColumnConfig>::iterator it;
169 for ( it = columns.begin(); it != columns.end(); ++it )
239 for (
const QString &providerId : subProviderIds )
246 const QgsProperty existingProperty =
c.property( property );
250 || overwriteExisting )
253 c.setProperty( property, prop );
260 c.setProperty( property, prop );
290 const QgsProperty existingProperty =
c.property( property );
294 c.setProperty( property, prop );
301 c.setProperty( property, prop );
328 for (
const QString &providerId : subProviderIds )
335 const QgsProperty existingProperty =
c.property( property );
339 c.setProperty( property, prop );
346 c.setProperty( property, prop );
365 if ( def.
origin().compare( QLatin1String(
"labeling" ) ) == 0 )
371 if ( propName.compare( def.
name() ) == 0 )
387 if ( aDef.
origin().compare( QLatin1String(
"labeling" ) ) == 0 )
390 QgsPropertiesDefinition::const_iterator it = defs.constBegin();
391 for ( ; it != defs.constEnd(); ++it )
393 if ( it->name().compare( aDef.
name(), Qt::CaseInsensitive ) == 0 )
400 else if ( aDef.
origin().compare( QLatin1String(
"symbol" ) ) == 0 )
403 QgsPropertiesDefinition::const_iterator it = defs.constBegin();
404 for ( ; it != defs.constEnd(); ++it )
406 if ( it->name().compare( aDef.
name(), Qt::CaseInsensitive ) == 0 )
413 else if ( aDef.
origin().compare( QLatin1String(
"diagram" ) ) == 0 )
416 QgsPropertiesDefinition::const_iterator it = defs.constBegin();
417 for ( ; it != defs.constEnd(); ++it )
419 if ( it->name().compare( aDef.
name(), Qt::CaseInsensitive ) == 0 )
442 QString fieldName = def.
origin();
444 if ( !def.
name().isEmpty() )
445 fieldName = QStringLiteral(
"%1_%2" ).arg( fieldName, def.
name().toLower() );
447 if ( !def.
comment().isEmpty() )
448 fieldName = QStringLiteral(
"%1_%2" ).arg( fieldName, def.
comment() );
451 fieldName = QStringLiteral(
"%1%2" ).arg(
AS_JOINPREFIX, fieldName );
460 if ( !def.
name().isEmpty() || !def.
comment().isEmpty() )
462 QVariant::Type
type = QVariant::Invalid;
468 type = QVariant::String;
470 typeName = QStringLiteral(
"String" );
473 type = QVariant::Double;
476 typeName = QStringLiteral(
"Real" );
479 type = QVariant::Int;
480 typeName = QStringLiteral(
"Integer" );
497 const QStringList parts = f.
name().split(
'_' );
499 if ( parts.size() <= 1 )
502 const QString origin = parts[0];
503 const QString propertyName = parts[1];
505 if ( origin.compare( QLatin1String(
"labeling" ), Qt::CaseInsensitive ) == 0 )
508 for (
auto it = props.constBegin(); it != props.constEnd(); ++it )
510 if ( it.value().name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
513 if ( parts.size() >= 3 )
519 else if ( origin.compare( QLatin1String(
"symbol" ), Qt::CaseInsensitive ) == 0 )
522 for (
auto it = props.constBegin(); it != props.constEnd(); ++it )
524 if ( it.value().name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
527 if ( parts.size() >= 3 )
533 else if ( origin.compare( QLatin1String(
"diagram" ), Qt::CaseInsensitive ) == 0 )
536 for (
auto it = props.constBegin(); it != props.constEnd(); ++it )
538 if ( it.value().name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
541 if ( parts.size() >= 3 )
553 case QVariant::Double:
561 case QVariant::String:
567 if ( parts.size() >= 3 )
579 if ( !def.
name().isEmpty() || !def.
comment().isEmpty() )
599 mFileName = filenameForProject( project );
606 : mFileName( filename )
616 QFile::remove( mTmpFileName );
631 if ( mFileName.isEmpty() )
638 if ( QFile::exists( mFileName ) )
639 QFile::remove( mFileName );
641 return QFile::copy( mTmpFileName, mFileName );
656 if ( mValid && layer )
658 const QString table( layer->
id() );
662 if ( !tableExists( table, database.get() ) )
664 if ( !createTable(
field.
typeName(), table, database.get(), mErrorString ) )
685 database = openDB( uri.
database() );
689 QString sql = QStringLiteral(
"DROP TABLE %1" ).arg( uri.
table() );
690 rc = exec( sql, database.get() );
692 sql = QStringLiteral(
"VACUUM" );
693 rc = exec( sql, database.get() );
708 database = openDB( uri.
database() );
712 const QString sql = QStringLiteral(
"CREATE TABLE %1 AS SELECT * FROM %2" ).arg( newTable, uri.
table() );
713 rc = exec( sql, database.get() );
727 mErrorString.clear();
729 QFile dest( filename );
730 if ( dest.exists() && !dest.remove() )
732 mErrorString = dest.errorString();
737 if ( !origin.copy( filename ) )
739 mErrorString = origin.errorString();
748 return saveAs( filenameForProject( project ) );
758 const QFileInfo fileinfo( filenameForProject( project ) );
759 return fileinfo.exists() && fileinfo.isFile();
762 bool QgsAuxiliaryStorage::exec(
const QString &sql,
sqlite3 *handler )
768 const int err = sqlite3_exec( handler, sql.toStdString().c_str(),
nullptr,
nullptr,
nullptr );
770 if ( err == SQLITE_OK )
773 debugMsg( sql, handler );
779 QString QgsAuxiliaryStorage::debugMsg(
const QString &sql,
sqlite3 *handler )
781 const QString err = QString::fromUtf8( sqlite3_errmsg( handler ) );
782 const QString msg = QObject::tr(
"Unable to execute" );
783 const QString errMsg = QObject::tr(
"%1 '%2': %3" ).arg( msg, sql, err );
788 bool QgsAuxiliaryStorage::createTable(
const QString &type,
const QString &table,
sqlite3 *handler, QString &errorMsg )
790 const QString sql = QStringLiteral(
"CREATE TABLE IF NOT EXISTS '%1' ( '%2' %3 )" ).arg( table,
AS_JOINFIELD, type );
792 if ( !exec( sql, handler ) )
794 errorMsg = QgsAuxiliaryStorage::debugMsg( sql, handler );
806 rc = database.
open_v2( filename, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
nullptr );
809 debugMsg( QStringLiteral(
"sqlite3_open_v2" ), database.get() );
813 exec( QStringLiteral(
"PRAGMA foreign_keys = 1" ), database.get() );
821 const int rc = database.
open_v2( filename, SQLITE_OPEN_READWRITE,
nullptr );
825 debugMsg( QStringLiteral(
"sqlite3_open_v2" ), database.get() );
831 bool QgsAuxiliaryStorage::tableExists(
const QString &table,
sqlite3 *handler )
833 const QString sql = QStringLiteral(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='%1'" ).arg( table );
836 char **results =
nullptr;
837 const int rc = sqlite3_get_table( handler, sql.toStdString().c_str(), &results, &rows, &columns,
nullptr );
838 if ( rc != SQLITE_OK )
840 debugMsg( sql, handler );
844 sqlite3_free_table( results );
855 if ( filename.isEmpty() )
860 else if ( QFile::exists( filename ) )
863 QFile::copy( filename, mTmpFileName );
879 return open( filenameForProject( project ) );
882 QString QgsAuxiliaryStorage::filenameForProject(
const QgsProject &project )
885 const QString path = info.path() + QDir::separator() + info.baseName();
889 void QgsAuxiliaryStorage::initTmpFileName()
891 QTemporaryFile tmpFile;
894 mTmpFileName = tmpFile.fileName();
899 if ( mCopy || mFileName.isEmpty() )
911 QStringList uriParts = uri.
uri().split(
'|' );
912 if ( uriParts.count() < 2 )
915 const QString databasePath = uriParts[0].replace(
' ', QString() );
917 const QString table = uriParts[1];
918 QStringList tableParts = table.split(
' ' );
920 if ( tableParts.count() < 1 )
923 const QString tableName = tableParts[0].replace( QLatin1String(
"layername=" ), QString() );
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsCoordinateReferenceSystem crs
static QgsProperty fromField(const QString &fieldName, bool isActive=true)
Returns a new FieldBasedProperty created from the specified field name.
@ Hali
Horizontal alignment for data defined label position (Left, Center, Right)
Class for storing the component parts of a RDBMS data source URI (e.g. a Postgres data source).
Q_GLOBAL_STATIC_WITH_ARGS(PalPropertyList, palHiddenProperties,({ QgsPalLayerSettings::PositionX, QgsPalLayerSettings::PositionY, QgsPalLayerSettings::Show, QgsPalLayerSettings::LabelRotation, QgsPalLayerSettings::Family, QgsPalLayerSettings::FontStyle, QgsPalLayerSettings::Size, QgsPalLayerSettings::Bold, QgsPalLayerSettings::Italic, QgsPalLayerSettings::Underline, QgsPalLayerSettings::Color, QgsPalLayerSettings::Strikeout, QgsPalLayerSettings::MultiLineAlignment, QgsPalLayerSettings::BufferSize, QgsPalLayerSettings::BufferDraw, QgsPalLayerSettings::BufferColor, QgsPalLayerSettings::LabelDistance, QgsPalLayerSettings::Hali, QgsPalLayerSettings::Vali, QgsPalLayerSettings::ScaleVisibility, QgsPalLayerSettings::MinScale, QgsPalLayerSettings::MaxScale, QgsPalLayerSettings::AlwaysShow, QgsPalLayerSettings::CalloutDraw, QgsPalLayerSettings::LabelAllParts })) QgsAuxiliaryLayer
static QgsField createAuxiliaryField(const QgsPropertyDefinition &definition)
Creates a new auxiliary field from a property definition.
Q_INVOKABLE QgsWkbTypes::Type wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
A store for object properties.
QgsPropertyDefinition propertyDefinitionFromIndex(int index) const
Returns the property definition for the underlying field index.
void updateFields()
Will regenerate the fields property of this layer by obtaining all fields from the dataProvider,...
Class allowing to manage the auxiliary storage for a vector layer.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the diagram's property collection, used for data defined overrides.
bool save()
Commits changes and starts editing then.
Contains settings for how a map layer will be labeled.
int indexOfPropertyDefinition(const QgsPropertyDefinition &definition) const
Returns the index of the auxiliary field for a specific property definition.
@ DataTypeString
Property requires a string value.
@ PositionY
Y-coordinate data defined label position.
bool exists(const QgsPropertyDefinition &definition) const
Returns true if the property is stored in the layer already, false otherwise.
@ FieldBasedProperty
Field based property (QgsFieldBasedProperty)
int propertyFromIndex(int index) const
Returns the underlying property key for the field index.
int count() const
Returns number of items.
Container of fields for a vector layer.
static QgsPropertiesDefinition propertyDefinitions()
Returns the definitions for data defined properties available for use in callouts.
@ Strikeout
Use strikeout.
QString asExpression() const
Returns an expression string representing the state of the property, or an empty string if the proper...
bool save() const
Saves the current database.
@ DataTypeBoolean
Property requires a boolean value.
QString fileName() const
Returns the target filename of the database.
QString typeName() const
Gets the field type.
@ DataTypeNumeric
Property requires a numeric value.
void setDatabase(const QString &database)
Sets the URI database name.
void setDataDefinedProperties(const QgsPropertyCollection &collection)
Sets the diagram's property collection, used for data defined overrides.
QgsAuxiliaryLayer * auxiliaryLayer()
Returns the current auxiliary layer.
static QgsVectorLayer * createMemoryLayer(const QString &name, const QgsFields &fields, QgsWkbTypes::Type geometryType=QgsWkbTypes::NoGeometry, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem()) SIP_FACTORY
Creates a new memory layer using the specified parameters.
void setDiagramLayerSettings(const QgsDiagramLayerSettings &s)
@ Vali
Vertical alignment for data defined label position (Bottom, Base, Half, Cap, Top)
Q_INVOKABLE bool startEditing()
Makes the layer editable.
static bool exists(const QgsProject &project)
Returns true if the auxiliary database yet exists for a project, false otherwise.
static QgsProperty fromExpression(const QString &expression, bool isActive=true)
Returns a new ExpressionBasedProperty created from the specified expression.
Type propertyType() const
Returns the property type.
bool append(const QgsField &field, FieldOrigin origin=OriginProvider, int originIndex=-1)
Appends a field. The field must have unique name, otherwise it is rejected (returns false)
QgsVectorLayer * toSpatialLayer() const
An auxiliary layer is not spatial.
bool isValid() const
Returns the status of the auxiliary storage currently defined.
virtual void setSettings(QgsPalLayerSettings *settings, const QString &providerId=QString())=0
Set pal settings for a specific provider (takes ownership).
static QString extension()
Returns the extension used for auxiliary databases.
bool isEditable() const FINAL
Returns true if the provider is in editing mode.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
QString expressionString() const
Returns the expression used for the property value.
void setEditorWidgetSetup(int index, const QgsEditorWidgetSetup &setup)
The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field ...
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
QgsAuxiliaryLayer * createAuxiliaryLayer(const QgsField &field, QgsVectorLayer *layer) const
Creates an auxiliary layer for a vector layer.
virtual QgsFeatureIds allFeatureIds() const
Returns a list of all feature IDs for features present in the source.
QVector< QgsPalLayerSettings::Property > PalPropertyList
QString targetFieldName() const
Returns name of the field of our layer that will be used for join.
QgsEditorWidgetSetup editorWidgetSetup(int index) const
The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field ...
DataType dataType() const
Returns the allowable field/value data type for the property.
This is a container for configuration of the attribute table. The configuration is specific for one v...
static const QgsPropertiesDefinition & propertyDefinitions()
Returns the symbol layer property definitions.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
@ MaxScale
Max scale (deprecated, for old project compatibility only)
void setComment(const QString &comment)
Sets comment of the property.
This class wraps a request for features to a vector layer (or directly its vector data provider).
@ ExpressionBasedProperty
Expression based property (QgsExpressionBasedProperty)
QMap< int, QgsPropertyDefinition > QgsPropertiesDefinition
Definition of available properties.
void setTypeName(const QString &typeName)
Set the field type.
Q_INVOKABLE bool commitChanges(bool stopEditing=true)
Attempts to commit to the underlying data provider any buffered changes made since the last to call t...
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
void setDataDefinedProperties(const QgsPropertyCollection &collection)
Sets the callout's property collection, used for data defined overrides.
void setDataDefinedProperties(const QgsPropertyCollection &collection)
Sets the label's property collection, used for data defined overrides.
bool isValid() const
Returns the validity of this feature.
@ ColorWithAlpha
Color with alpha channel.
virtual QStringList subProviders() const
Gets list of sub-providers within the layer's labeling.
const QgsAbstractVectorLayerLabeling * labeling() const
Access to const labeling configuration.
@ LabelAllParts
Whether all parts of multi-part features should be labeled.
@ CalloutDraw
Show callout.
QVector< QgsAttributeTableConfig::ColumnConfig > columns() const
Gets the list with all columns and their configuration.
bool clear()
Deletes all features from the layer.
QgsAuxiliaryStorage(const QgsProject &project, bool copy=true)
Constructor.
@ LabelRotation
Label rotation.
Stores the settings for rendering of all diagrams for a layer.
Definition for a property.
void setLength(int len)
Set the field length.
QgsVectorLayerJoinInfo joinInfo() const
Returns information to use for joining with primary key and so on.
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
QgsAuxiliaryLayer(const QString &pkField, const QString &filename, const QString &table, QgsVectorLayer *vlayer)
Constructor.
StandardPropertyTemplate standardTemplate() const
Returns the property's standard template, if applicable.
static const QgsPropertiesDefinition & propertyDefinitions()
Returns the labeling property definitions.
Defines left outer join from our vector layer to some other vector layer. The join is done based on [...
void setColumns(const QVector< QgsAttributeTableConfig::ColumnConfig > &columns)
Set the list of columns visible in the attribute table.
static QString createFieldEqualityExpression(const QString &fieldName, const QVariant &value, QVariant::Type fieldType=QVariant::Type::Invalid)
Create an expression allowing to evaluate if a field is equal to a value.
int open_v2(const QString &path, int flags, const char *zVfs)
Opens the database at the specified file path.
QString origin() const
Returns the origin of the property.
QgsField field(int fieldIdx) const
Returns the field at particular index (must be in range 0..N-1).
QString absoluteFilePath() const
Returns full absolute path to the project file if the project is stored in a file system - derived fr...
static bool duplicateTable(const QgsDataSourceUri &uri, const QString &newTable)
Duplicates a table and its content.
QString comment() const
Returns the comment of the property.
@ PositionX
X-coordinate data defined label position.
A grouped map of multiple QgsProperty objects, each referenced by a integer key value.
const QgsDiagramLayerSettings * diagramLayerSettings() const
QString source() const
Returns the source for the layer.
void setName(const QString &name)
Sets the name of the property.
virtual ~QgsAuxiliaryStorage()
Destructor.
@ Italic
Use italic style.
void setAttributeTableConfig(const QgsAttributeTableConfig &attributeTableConfig)
Sets the attribute table configuration object.
bool nextFeature(QgsFeature &f)
bool deleteFeatures(const QgsFeatureIds &fids, DeleteContext *context=nullptr)
Deletes a set of features from the layer (but does not commit it)
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
void setPrecision(int precision)
Set the field precision.
Represents a vector layer which manages a vector based data sets.
QString name() const
Returns the name of the property.
QgsAttributeTableConfig attributeTableConfig() const
Returns the attribute table configuration object.
void setDataSource(const QString &aSchema, const QString &aTable, const QString &aGeometryColumn, const QString &aSql=QString(), const QString &aKeyColumn=QString())
Sets all data source related members at once.
QString field() const
Returns the current field name the property references.
@ FontStyle
Font style name.
QgsCallout * callout() const
Returns the label callout renderer, responsible for drawing label callouts.
static QString nameFromProperty(const QgsPropertyDefinition &def, bool joined=false)
Returns the name of the auxiliary field for a property definition.
static const QgsPropertiesDefinition & propertyDefinitions()
Returns the diagram property definitions.
static QString quotedColumnRef(QString name)
Returns a quoted column reference (in double quotes)
QString database() const
Returns the database name stored in the URI.
QString uri(bool expandAuthConfig=true) const
Returns the complete URI as a string.
QString errorString() const
Returns the underlying error string describing potential errors happening in saveAs().
virtual bool deleteAttribute(int attr)
Deletes an attribute field (but does not commit it).
void setType(QVariant::Type type)
Set variant type.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
QgsFields auxiliaryFields() const
Returns a list of all auxiliary fields currently managed by the layer.
Property
Data definable properties.
bool deleteAttribute(int attr) override
Removes attribute from the layer and commits changes.
Property
Data definable properties.
@ Underline
Use underline.
QString currentFileName() const
Returns the path of the current database used.
bool addAuxiliaryField(const QgsPropertyDefinition &definition)
Adds an auxiliary field for the given property.
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
static QgsPropertyDefinition propertyDefinitionFromField(const QgsField &field)
Returns the property definition from an auxiliary field.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the label's property collection, used for data defined overrides.
QString table() const
Returns the table name stored in the URI.
Unique pointer for sqlite3 databases, which automatically closes the database when the pointer goes o...
Property
Data definable properties.
Wrapper for iterator of features from vector data provider or vector layer.
QgsVectorLayer * clone() const override
Returns a new instance equivalent to this one.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) FINAL
Adds a single feature to the sink.
@ MinScale
Min scale (deprecated, for old project compatibility only)
void setDataType(DataType type)
Sets the data type.
@ ColorNoAlpha
Color with no alpha channel.
virtual QgsPalLayerSettings settings(const QString &providerId=QString()) const =0
Gets associated label settings.
void setName(const QString &name)
Set the field name.
static int createProperty(QgsPalLayerSettings::Property property, QgsVectorLayer *vlayer, bool overwriteExisting=true)
Creates if necessary a new auxiliary field for a PAL property and activates this property in settings...
bool saveAs(const QString &filename)
Saves the current database to a new path.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the callout's property collection, used for data defined overrides.
bool isHiddenProperty(int index) const
Returns true if the underlying field has to be hidden from editing tools like attribute table,...
@ InvalidProperty
Invalid (not set) property.
void setOrigin(const QString &origin)
Sets the origin of the property.
int indexOf(const QString &fieldName) const
Gets the field index from the field name.
static bool deleteTable(const QgsDataSourceUri &uri)
Removes a table from the auxiliary storage.
bool addAttribute(const QgsField &field)
Add an attribute field (but does not commit it) returns true if the field was added.
Encapsulate a field in an attribute table or data source.
void update(const QgsFields &fields)
Update the configuration with the given fields.