30#define AS_JOINFIELD QStringLiteral( "ASPK" )
31#define AS_EXTENSION QStringLiteral( "qgd" )
32#define AS_JOINPREFIX QStringLiteral( "auxiliary_storage_" )
76 :
QgsVectorLayer( QStringLiteral(
"%1|layername=%2" ).arg( filename, table ),
77 QStringLiteral(
"%1_auxiliarystorage" ).arg( table ), QStringLiteral(
"ogr" ) )
78 , mFileName( filename )
84 mJoinInfo.setJoinLayer(
this );
86 mJoinInfo.setTargetFieldName( pkField );
87 mJoinInfo.setEditable(
true );
88 mJoinInfo.setUpsertOnEdit(
true );
89 mJoinInfo.setCascadedDelete(
true );
90 mJoinInfo.setJoinFieldNamesBlockList( QStringList() << QStringLiteral(
"rowid" ) );
129 newFeature.setGeometry( targetFeature.
geometry() );
150 if ( ( definition.
name().isEmpty() && definition.
comment().isEmpty() ) ||
exists( definition ) )
163 if ( index >= 0 && auxIndex >= 0 )
174 QVector<QgsAttributeTableConfig::ColumnConfig> columns = attrCfg.
columns();
175 QVector<QgsAttributeTableConfig::ColumnConfig>::iterator it;
177 for ( it = columns.begin(); it != columns.end(); ++it )
247 for (
const QString &providerId : subProviderIds )
254 const QgsProperty existingProperty =
c.property( property );
258 || overwriteExisting )
261 c.setProperty( property, prop );
268 c.setProperty( property, prop );
298 const QgsProperty existingProperty =
c.property( property );
302 c.setProperty( property, prop );
309 c.setProperty( property, prop );
336 for (
const QString &providerId : subProviderIds )
343 const QgsProperty existingProperty =
c.property( property );
347 c.setProperty( property, prop );
354 c.setProperty( property, prop );
373 if ( def.
origin().compare( QLatin1String(
"labeling" ) ) == 0 )
379 if ( propName.compare( def.
name() ) == 0 )
386 else if ( def.
origin().compare( QLatin1String(
"symbol" ) ) == 0 )
392 if ( propName.compare( def.
name() ) == 0 )
408 if ( aDef.
origin().compare( QLatin1String(
"labeling" ) ) == 0 )
411 QgsPropertiesDefinition::const_iterator it = defs.constBegin();
412 for ( ; it != defs.constEnd(); ++it )
414 if ( it->name().compare( aDef.
name(), Qt::CaseInsensitive ) == 0 )
421 else if ( aDef.
origin().compare( QLatin1String(
"symbol" ) ) == 0 )
424 QgsPropertiesDefinition::const_iterator it = defs.constBegin();
425 for ( ; it != defs.constEnd(); ++it )
427 if ( it->name().compare( aDef.
name(), Qt::CaseInsensitive ) == 0 )
434 else if ( aDef.
origin().compare( QLatin1String(
"diagram" ) ) == 0 )
437 QgsPropertiesDefinition::const_iterator it = defs.constBegin();
438 for ( ; it != defs.constEnd(); ++it )
440 if ( it->name().compare( aDef.
name(), Qt::CaseInsensitive ) == 0 )
463 QString fieldName = def.
origin();
465 if ( !def.
name().isEmpty() )
466 fieldName = QStringLiteral(
"%1_%2" ).arg( fieldName, def.
name().toLower() );
468 if ( !def.
comment().isEmpty() )
469 fieldName = QStringLiteral(
"%1_%2" ).arg( fieldName, def.
comment() );
472 fieldName = QStringLiteral(
"%1%2" ).arg(
AS_JOINPREFIX, fieldName );
481 if ( !def.
name().isEmpty() || !def.
comment().isEmpty() )
483 QVariant::Type
type = QVariant::Invalid;
489 type = QVariant::String;
491 typeName = QStringLiteral(
"String" );
494 type = QVariant::Double;
497 typeName = QStringLiteral(
"Real" );
500 type = QVariant::Int;
501 typeName = QStringLiteral(
"Integer" );
518 const QStringList parts = f.
name().split(
'_' );
520 if ( parts.size() <= 1 )
523 const QString origin = parts[0];
524 const QString propertyName = parts[1];
526 if ( origin.compare( QLatin1String(
"labeling" ), Qt::CaseInsensitive ) == 0 )
529 for (
auto it = props.constBegin(); it != props.constEnd(); ++it )
531 if ( it.value().name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
534 if ( parts.size() >= 3 )
540 else if ( origin.compare( QLatin1String(
"symbol" ), Qt::CaseInsensitive ) == 0 )
543 for (
auto it = props.constBegin(); it != props.constEnd(); ++it )
545 if ( it.value().name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
548 if ( parts.size() >= 3 )
554 else if ( origin.compare( QLatin1String(
"diagram" ), Qt::CaseInsensitive ) == 0 )
557 for (
auto it = props.constBegin(); it != props.constEnd(); ++it )
559 if ( it.value().name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
562 if ( parts.size() >= 3 )
574 case QVariant::Double:
582 case QVariant::String:
588 if ( parts.size() >= 3 )
600 if ( !def.
name().isEmpty() || !def.
comment().isEmpty() )
620 mFileName = filenameForProject( project );
627 : mFileName( filename )
637 QFile::remove( mTmpFileName );
652 if ( mFileName.isEmpty() )
659 if ( QFile::exists( mFileName ) )
660 QFile::remove( mFileName );
662 return QFile::copy( mTmpFileName, mFileName );
677 if ( mValid && layer )
679 const QString table( layer->
id() );
683 if ( !tableExists( table, database.get() ) )
685 if ( !createTable( field.
typeName(), table, database.get(), mErrorString ) )
706 database = openDB( uri.
database() );
710 QString sql = QStringLiteral(
"DROP TABLE %1" ).arg( uri.
table() );
711 rc = exec( sql, database.get() );
713 sql = QStringLiteral(
"VACUUM" );
714 rc = exec( sql, database.get() );
729 database = openDB( uri.
database() );
733 const QString sql = QStringLiteral(
"CREATE TABLE %1 AS SELECT * FROM %2" ).arg( newTable, uri.
table() );
734 rc = exec( sql, database.get() );
748 mErrorString.clear();
750 QFile dest( filename );
751 if ( dest.exists() && !dest.remove() )
753 mErrorString = dest.errorString();
758 if ( !origin.copy( filename ) )
760 mErrorString = origin.errorString();
769 return saveAs( filenameForProject( project ) );
779 const QFileInfo fileinfo( filenameForProject( project ) );
780 return fileinfo.exists() && fileinfo.isFile();
783bool QgsAuxiliaryStorage::exec(
const QString &sql,
sqlite3 *handler )
789 const int err = sqlite3_exec( handler, sql.toStdString().c_str(),
nullptr,
nullptr,
nullptr );
791 if ( err == SQLITE_OK )
794 debugMsg( sql, handler );
800QString QgsAuxiliaryStorage::debugMsg(
const QString &sql,
sqlite3 *handler )
802 const QString err = QString::fromUtf8( sqlite3_errmsg( handler ) );
803 const QString msg = QObject::tr(
"Unable to execute" );
804 const QString errMsg = QObject::tr(
"%1 '%2': %3" ).arg( msg, sql, err );
809bool QgsAuxiliaryStorage::createTable(
const QString &type,
const QString &table,
sqlite3 *handler, QString &errorMsg )
811 const QString sql = QStringLiteral(
"CREATE TABLE IF NOT EXISTS '%1' ( '%2' %3 )" ).arg( table,
AS_JOINFIELD, type );
813 if ( !exec( sql, handler ) )
815 errorMsg = QgsAuxiliaryStorage::debugMsg( sql, handler );
827 rc = database.
open_v2( filename, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
nullptr );
830 debugMsg( QStringLiteral(
"sqlite3_open_v2" ), database.get() );
834 exec( QStringLiteral(
"PRAGMA foreign_keys = 1" ), database.get() );
842 const int rc = database.
open_v2( filename, SQLITE_OPEN_READWRITE,
nullptr );
846 debugMsg( QStringLiteral(
"sqlite3_open_v2" ), database.get() );
852bool QgsAuxiliaryStorage::tableExists(
const QString &table,
sqlite3 *handler )
854 const QString sql = QStringLiteral(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='%1'" ).arg( table );
857 char **results =
nullptr;
858 const int rc = sqlite3_get_table( handler, sql.toStdString().c_str(), &results, &rows, &columns,
nullptr );
859 if ( rc != SQLITE_OK )
861 debugMsg( sql, handler );
865 sqlite3_free_table( results );
876 if ( filename.isEmpty() )
881 else if ( QFile::exists( filename ) )
884 QFile::copy( filename, mTmpFileName );
900 return open( filenameForProject( project ) );
903QString QgsAuxiliaryStorage::filenameForProject(
const QgsProject &project )
906 const QString path = info.path() + QDir::separator() + info.baseName();
910void QgsAuxiliaryStorage::initTmpFileName()
912 QTemporaryFile tmpFile;
915 mTmpFileName = tmpFile.fileName();
920 if ( mCopy || mFileName.isEmpty() )
932 QStringList uriParts = uri.
uri().split(
'|' );
933 if ( uriParts.count() < 2 )
936 const QString databasePath = uriParts[0].replace(
' ', QString() );
938 const QString table = uriParts[1];
939 QStringList tableParts = table.split(
' ' );
941 if ( tableParts.count() < 1 )
944 const QString tableName = tableParts[0].replace( QLatin1String(
"layername=" ), QString() );
virtual QStringList subProviders() const
Gets list of sub-providers within the layer's labeling.
virtual void setSettings(QgsPalLayerSettings *settings, const QString &providerId=QString())=0
Set pal settings for a specific provider (takes ownership).
virtual QgsPalLayerSettings settings(const QString &providerId=QString()) const =0
Gets associated label settings.
This is a container for configuration of the attribute table.
QVector< QgsAttributeTableConfig::ColumnConfig > columns() const
Gets the list with all columns and their configuration.
void update(const QgsFields &fields)
Update the configuration with the given fields.
void setColumns(const QVector< QgsAttributeTableConfig::ColumnConfig > &columns)
Set the list of columns visible in the attribute table.
Class allowing to manage the auxiliary storage for a vector layer.
static QString nameFromProperty(const QgsPropertyDefinition &def, bool joined=false)
Returns the name of the auxiliary field for a property definition.
static QgsField createAuxiliaryField(const QgsPropertyDefinition &definition)
Creates a new auxiliary field from a property definition.
static QgsPropertyDefinition propertyDefinitionFromField(const QgsField &field)
Returns the property definition from an auxiliary field.
bool clear()
Deletes all features from the layer.
bool addAuxiliaryField(const QgsPropertyDefinition &definition)
Adds an auxiliary field for the given property.
bool isHiddenProperty(int index) const
Returns true if the underlying field has to be hidden from editing tools like attribute table,...
QgsVectorLayer * toSpatialLayer() const
An auxiliary layer is not spatial.
bool deleteAttribute(int attr) override
Removes attribute from the layer and commits changes.
QgsFields auxiliaryFields() const
Returns a list of all auxiliary fields currently managed by the layer.
QgsAuxiliaryLayer(const QString &pkField, const QString &filename, const QString &table, QgsVectorLayer *vlayer)
Constructor.
bool save()
Commits changes and starts editing then.
int propertyFromIndex(int index) const
Returns the underlying property key for the field index.
QgsVectorLayerJoinInfo joinInfo() const
Returns information to use for joining with primary key and so on.
QgsVectorLayer * clone() const override
Returns a new instance equivalent to this one.
QgsPropertyDefinition propertyDefinitionFromIndex(int index) const
Returns the property definition for the underlying field index.
bool exists(const QgsPropertyDefinition &definition) const
Returns true if the property is stored in the layer already, false otherwise.
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...
int indexOfPropertyDefinition(const QgsPropertyDefinition &definition) const
Returns the index of the auxiliary field for a specific property definition.
static QString extension()
Returns the extension used for auxiliary databases.
QString errorString() const
Returns the underlying error string describing potential errors happening in saveAs().
bool save() const
Saves the current database.
static bool exists(const QgsProject &project)
Returns true if the auxiliary database yet exists for a project, false otherwise.
QgsAuxiliaryLayer * createAuxiliaryLayer(const QgsField &field, QgsVectorLayer *layer) const
Creates an auxiliary layer for a vector layer.
virtual ~QgsAuxiliaryStorage()
Destructor.
bool saveAs(const QString &filename)
Saves the current database to a new path.
bool isValid() const
Returns the status of the auxiliary storage currently defined.
QString currentFileName() const
Returns the path of the current database used.
QgsAuxiliaryStorage(const QgsProject &project, bool copy=true)
Constructor.
QString fileName() const
Returns the target filename of the database.
static bool deleteTable(const QgsDataSourceUri &uri)
Removes a table from the auxiliary storage.
static bool duplicateTable(const QgsDataSourceUri &uri, const QString &newTable)
Duplicates a table and its content.
void setDataDefinedProperties(const QgsPropertyCollection &collection)
Sets the callout's property collection, used for data defined overrides.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the callout's property collection, used for data defined overrides.
static QgsPropertiesDefinition propertyDefinitions()
Returns the definitions for data defined properties available for use in callouts.
Property
Data definable properties.
Class for storing the component parts of a RDBMS data source URI (e.g.
QString table() const
Returns the table name stored in the URI.
QString uri(bool expandAuthConfig=true) const
Returns the complete URI as a string.
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 database() const
Returns the database name stored in the URI.
void setDatabase(const QString &database)
Sets the URI database name.
Stores the settings for rendering of all diagrams for a layer.
Property
Data definable properties.
static const QgsPropertiesDefinition & propertyDefinitions()
Returns the diagram property definitions.
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.
static QString quotedColumnRef(QString name)
Returns a quoted column reference (in double quotes)
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
virtual QgsFeatureIds allFeatureIds() const
Returns a list of all feature IDs for features present in the source.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
bool isValid() const
Returns the validity of this feature.
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Encapsulate a field in an attribute table or data source.
QString typeName() const
Gets the field type.
void setPrecision(int precision)
Set the field precision.
void setName(const QString &name)
Set the field name.
void setLength(int len)
Set the field length.
void setType(QVariant::Type type)
Set variant type.
void setTypeName(const QString &typeName)
Set the field type.
Container of fields for a vector layer.
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)
int indexOf(const QString &fieldName) const
Gets the field index from the field name.
int count() const
Returns number of items.
QgsField field(int fieldIdx) const
Returns the field at particular index (must be in range 0..N-1).
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
QString source() const
Returns the source for the layer.
QgsCoordinateReferenceSystem crs
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
static QgsVectorLayer * createMemoryLayer(const QString &name, const QgsFields &fields, Qgis::WkbType geometryType=Qgis::WkbType::NoGeometry, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem(), bool loadDefaultStyle=true) SIP_FACTORY
Creates a new memory layer using the specified parameters.
Contains settings for how a map layer will be labeled.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the label's property collection, used for data defined overrides.
QgsCallout * callout() const
Returns the label callout renderer, responsible for drawing label callouts.
Property
Data definable properties.
@ LabelRotation
Label rotation.
@ PositionY
Y-coordinate data defined label position.
@ Strikeout
Use strikeout.
@ FontStyle
Font style name.
@ PositionX
X-coordinate data defined label position.
@ CalloutDraw
Show callout.
@ Underline
Use underline.
@ MaxScale
Max scale (deprecated, for old project compatibility only)
@ Hali
Horizontal alignment for data defined label position (Left, Center, Right)
@ LabelAllParts
Whether all parts of multi-part features should be labeled.
@ Italic
Use italic style.
@ MinScale
Min scale (deprecated, for old project compatibility only)
@ Vali
Vertical alignment for data defined label position (Bottom, Base, Half, Cap, Top)
void setDataDefinedProperties(const QgsPropertyCollection &collection)
Sets the label's property collection, used for data defined overrides.
static const QgsPropertiesDefinition & propertyDefinitions()
Returns the labeling property definitions.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
QString absoluteFilePath() const
Returns full absolute path to the project file if the project is stored in a file system - derived fr...
A grouped map of multiple QgsProperty objects, each referenced by a integer key value.
Definition for a property.
StandardPropertyTemplate standardTemplate() const
Returns the property's standard template, if applicable.
QString comment() const
Returns the comment of the property.
DataType dataType() const
Returns the allowable field/value data type for the property.
void setOrigin(const QString &origin)
Sets the origin of the property.
@ ColorNoAlpha
Color with no alpha channel.
@ ColorWithAlpha
Color with alpha channel.
QString name() const
Returns the name of the property.
void setDataType(DataType type)
Sets the data type.
void setName(const QString &name)
Sets the name of the property.
QString origin() const
Returns the origin of the property.
void setComment(const QString &comment)
Sets comment of the property.
@ DataTypeString
Property requires a string value.
@ DataTypeBoolean
Property requires a boolean value.
@ DataTypeNumeric
Property requires a numeric value.
A store for object properties.
@ ExpressionBasedProperty
Expression based property (QgsExpressionBasedProperty)
@ FieldBasedProperty
Field based property (QgsFieldBasedProperty)
@ InvalidProperty
Invalid (not set) property.
QString asExpression() const
Returns an expression string representing the state of the property, or an empty string if the proper...
QString expressionString() const
Returns the expression used for the property value.
QString field() const
Returns the current field name the property references.
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.
static QgsProperty fromField(const QString &fieldName, bool isActive=true)
Returns a new FieldBasedProperty created from the specified field name.
Property
Data definable properties.
@ PropertyAngle
Symbol angle.
@ PropertyOffset
Symbol offset.
static const QgsPropertiesDefinition & propertyDefinitions()
Returns the symbol layer property definitions.
Defines left outer join from our vector layer to some other vector layer.
QString targetFieldName() const
Returns name of the field of our layer that will be used for join.
Represents a vector layer which manages a vector based data sets.
Q_INVOKABLE bool startEditing()
Makes the layer editable.
bool addAttribute(const QgsField &field)
Add an attribute field (but does not commit it) returns true if the field was added.
void updateFields()
Will regenerate the fields property of this layer by obtaining all fields from the dataProvider,...
const QgsDiagramLayerSettings * diagramLayerSettings() const
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
bool deleteFeatures(const QgsFeatureIds &fids, DeleteContext *context=nullptr)
Deletes a set of features from the layer (but does not commit it)
QgsAuxiliaryLayer * auxiliaryLayer()
Returns the current auxiliary layer.
const QgsAbstractVectorLayerLabeling * labeling() const
Access to const labeling configuration.
virtual bool deleteAttribute(int attr)
Deletes an attribute field (but does not commit it).
bool isEditable() const FINAL
Returns true if the provider is in editing mode.
Q_INVOKABLE Qgis::WkbType wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
void setEditorWidgetSetup(int index, const QgsEditorWidgetSetup &setup)
The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field ...
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...
QgsEditorWidgetSetup editorWidgetSetup(int index) const
The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field ...
QgsAttributeTableConfig attributeTableConfig() const
Returns the attribute table configuration object.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) FINAL
Adds a single feature to the sink.
void setAttributeTableConfig(const QgsAttributeTableConfig &attributeTableConfig)
Sets the attribute table configuration object.
void setDiagramLayerSettings(const QgsDiagramLayerSettings &s)
Unique pointer for sqlite3 databases, which automatically closes the database when the pointer goes o...
int open_v2(const QString &path, int flags, const char *zVfs)
Opens the database at the specified file path.
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
QVector< QgsSymbolLayer::Property > SymbolPropertyList
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 })) Q_GLOBAL_STATIC_WITH_ARGS(SymbolPropertyList
QVector< QgsPalLayerSettings::Property > PalPropertyList
#define QgsDebugError(str)
QMap< int, QgsPropertyDefinition > QgsPropertiesDefinition
Definition of available properties.