19#include "moc_qgsauxiliarystorage.cpp"
31#define AS_JOINFIELD QStringLiteral( "ASPK" )
32#define AS_EXTENSION QStringLiteral( "qgd" )
33#define AS_JOINPREFIX QStringLiteral( "auxiliary_storage_" )
77 :
QgsVectorLayer( QStringLiteral(
"%1|layername=%2" ).arg( filename, table ),
78 QStringLiteral(
"%1_auxiliarystorage" ).arg( table ), QStringLiteral(
"ogr" ) )
79 , mFileName( filename )
85 mJoinInfo.setJoinLayer(
this );
87 mJoinInfo.setTargetFieldName( pkField );
88 mJoinInfo.setEditable(
true );
89 mJoinInfo.setUpsertOnEdit(
true );
90 mJoinInfo.setCascadedDelete(
true );
91 mJoinInfo.setJoinFieldNamesBlockList( QStringList() << QStringLiteral(
"rowid" ) );
130 newFeature.setGeometry( targetFeature.
geometry() );
151 if ( ( definition.
name().isEmpty() && definition.
comment().isEmpty() ) ||
exists( definition ) )
164 if ( index >= 0 && auxIndex >= 0 )
175 QVector<QgsAttributeTableConfig::ColumnConfig> columns = attrCfg.
columns();
176 QVector<QgsAttributeTableConfig::ColumnConfig>::iterator it;
178 for ( it = columns.begin(); it != columns.end(); ++it )
248 for (
const QString &providerId : subProviderIds )
255 const QgsProperty existingProperty =
c.property( property );
259 || overwriteExisting )
262 c.setProperty( property, prop );
269 c.setProperty( property, prop );
299 const QgsProperty existingProperty =
c.property( property );
303 c.setProperty( property, prop );
310 c.setProperty( property, prop );
337 for (
const QString &providerId : subProviderIds )
344 const QgsProperty existingProperty =
c.property( property );
348 c.setProperty( property, prop );
355 c.setProperty( property, prop );
374 if ( def.
origin().compare( QLatin1String(
"labeling" ) ) == 0 )
377 for (
const int p : palProps )
380 if ( propName.compare( def.
name() ) == 0 )
387 else if ( def.
origin().compare( QLatin1String(
"symbol" ) ) == 0 )
390 for (
int p : symbolProps )
393 if ( propName.compare( def.
name() ) == 0 )
409 if ( aDef.
origin().compare( QLatin1String(
"labeling" ) ) == 0 )
412 QgsPropertiesDefinition::const_iterator it = defs.constBegin();
413 for ( ; it != defs.constEnd(); ++it )
415 if ( it->name().compare( aDef.
name(), Qt::CaseInsensitive ) == 0 )
422 else if ( aDef.
origin().compare( QLatin1String(
"symbol" ) ) == 0 )
425 QgsPropertiesDefinition::const_iterator it = defs.constBegin();
426 for ( ; it != defs.constEnd(); ++it )
428 if ( it->name().compare( aDef.
name(), Qt::CaseInsensitive ) == 0 )
435 else if ( aDef.
origin().compare( QLatin1String(
"diagram" ) ) == 0 )
438 QgsPropertiesDefinition::const_iterator it = defs.constBegin();
439 for ( ; it != defs.constEnd(); ++it )
441 if ( it->name().compare( aDef.
name(), Qt::CaseInsensitive ) == 0 )
464 QString fieldName = def.
origin();
466 if ( !def.
name().isEmpty() )
467 fieldName = QStringLiteral(
"%1_%2" ).arg( fieldName, def.
name().toLower() );
469 if ( !def.
comment().isEmpty() )
470 fieldName = QStringLiteral(
"%1_%2" ).arg( fieldName, def.
comment() );
473 fieldName = QStringLiteral(
"%1%2" ).arg(
AS_JOINPREFIX, fieldName );
482 if ( !def.
name().isEmpty() || !def.
comment().isEmpty() )
484 QMetaType::Type
type = QMetaType::Type::UnknownType;
490 type = QMetaType::Type::QString;
492 typeName = QStringLiteral(
"String" );
495 type = QMetaType::Type::Double;
498 typeName = QStringLiteral(
"Real" );
501 type = QMetaType::Type::Int;
502 typeName = QStringLiteral(
"Integer" );
519 const QStringList parts = f.
name().split(
'_' );
521 if ( parts.size() <= 1 )
524 const QString origin = parts[0];
525 const QString propertyName = parts[1];
527 if ( origin.compare( QLatin1String(
"labeling" ), Qt::CaseInsensitive ) == 0 )
530 for (
auto it = props.constBegin(); it != props.constEnd(); ++it )
532 if ( it.value().name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
535 if ( parts.size() >= 3 )
541 else if ( origin.compare( QLatin1String(
"symbol" ), Qt::CaseInsensitive ) == 0 )
544 for (
auto it = props.constBegin(); it != props.constEnd(); ++it )
546 if ( it.value().name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
549 if ( parts.size() >= 3 )
555 else if ( origin.compare( QLatin1String(
"diagram" ), Qt::CaseInsensitive ) == 0 )
558 for (
auto it = props.constBegin(); it != props.constEnd(); ++it )
560 if ( it.value().name().compare( propertyName, Qt::CaseInsensitive ) == 0 )
563 if ( parts.size() >= 3 )
575 case QMetaType::Type::Double:
579 case QMetaType::Type::Bool:
583 case QMetaType::Type::QString:
589 if ( parts.size() >= 3 )
601 if ( !def.
name().isEmpty() || !def.
comment().isEmpty() )
621 mFileName = filenameForProject( project );
628 : mFileName( filename )
638 QFile::remove( mTmpFileName );
653 if ( mFileName.isEmpty() )
660 if ( QFile::exists( mFileName ) )
661 QFile::remove( mFileName );
663 return QFile::copy( mTmpFileName, mFileName );
678 if ( mValid && layer )
680 const QString table( layer->
id() );
684 if ( !tableExists( table, database.get() ) )
686 if ( !createTable( field.
typeName(), table, database.get(), mErrorString ) )
707 database = openDB( uri.
database() );
711 QString sql = QStringLiteral(
"DROP TABLE %1" ).arg( uri.
table() );
712 rc = exec( sql, database.get() );
714 sql = QStringLiteral(
"VACUUM" );
715 rc = exec( sql, database.get() );
730 database = openDB( uri.
database() );
734 const QString sql = QStringLiteral(
"CREATE TABLE %1 AS SELECT * FROM %2" ).arg( newTable, uri.
table() );
735 rc = exec( sql, database.get() );
749 mErrorString.clear();
751 QFile dest( filename );
752 if ( dest.exists() && !dest.remove() )
754 mErrorString = dest.errorString();
759 if ( !origin.copy( filename ) )
761 mErrorString = origin.errorString();
770 return saveAs( filenameForProject( project ) );
780 const QFileInfo fileinfo( filenameForProject( project ) );
781 return fileinfo.exists() && fileinfo.isFile();
784bool QgsAuxiliaryStorage::exec(
const QString &sql,
sqlite3 *handler )
790 const int err = sqlite3_exec( handler, sql.toStdString().c_str(),
nullptr,
nullptr,
nullptr );
792 if ( err == SQLITE_OK )
795 debugMsg( sql, handler );
801QString QgsAuxiliaryStorage::debugMsg(
const QString &sql,
sqlite3 *handler )
803 const QString err = QString::fromUtf8( sqlite3_errmsg( handler ) );
804 const QString msg = QObject::tr(
"Unable to execute" );
805 const QString errMsg = QObject::tr(
"%1 '%2': %3" ).arg( msg, sql, err );
810bool QgsAuxiliaryStorage::createTable(
const QString &type,
const QString &table,
sqlite3 *handler, QString &errorMsg )
812 const QString sql = QStringLiteral(
"CREATE TABLE IF NOT EXISTS '%1' ( '%2' %3 )" ).arg( table,
AS_JOINFIELD, type );
814 if ( !exec( sql, handler ) )
816 errorMsg = QgsAuxiliaryStorage::debugMsg( sql, handler );
828 rc = database.
open_v2( filename, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
nullptr );
831 debugMsg( QStringLiteral(
"sqlite3_open_v2" ), database.get() );
835 exec( QStringLiteral(
"PRAGMA foreign_keys = 1" ), database.get() );
843 const int rc = database.
open_v2( filename, SQLITE_OPEN_READWRITE,
nullptr );
847 debugMsg( QStringLiteral(
"sqlite3_open_v2" ), database.get() );
853bool QgsAuxiliaryStorage::tableExists(
const QString &table,
sqlite3 *handler )
855 const QString sql = QStringLiteral(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='%1'" ).arg( table );
858 char **results =
nullptr;
859 const int rc = sqlite3_get_table( handler, sql.toStdString().c_str(), &results, &rows, &columns,
nullptr );
860 if ( rc != SQLITE_OK )
862 debugMsg( sql, handler );
866 sqlite3_free_table( results );
877 if ( filename.isEmpty() )
882 else if ( QFile::exists( filename ) )
885 QFile::copy( filename, mTmpFileName );
901 return open( filenameForProject( project ) );
904QString QgsAuxiliaryStorage::filenameForProject(
const QgsProject &project )
907 const QString path = info.path() + QDir::separator() + info.baseName();
911void QgsAuxiliaryStorage::initTmpFileName()
913 QTemporaryFile tmpFile;
916 mTmpFileName = tmpFile.fileName();
921 if ( mCopy || mFileName.isEmpty() )
933 QStringList uriParts = uri.
uri().split(
'|' );
934 if ( uriParts.count() < 2 )
937 const QString databasePath = uriParts[0].replace(
' ', QString() );
939 const QString table = uriParts[1];
940 QStringList tableParts = table.split(
' ' );
942 if ( tableParts.count() < 1 )
945 const QString tableName = tableParts[0].replace( QLatin1String(
"layername=" ), QString() );
@ Invalid
Invalid (not set) property.
@ Field
Field based property.
@ Expression
Expression based property.
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()
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, QMetaType::Type fieldType=QMetaType::Type::UnknownType)
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)
Fetch next feature and stores in f, returns true on success.
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.
Q_INVOKABLE 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 setType(QMetaType::Type type)
Set variant type.
void setLength(int len)
Set the field length.
void setTypeName(const QString &typeName)
Set the field type.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Q_INVOKABLE int indexOf(const QString &fieldName) const
Gets the field index from the field name.
QgsField field(int fieldIdx) const
Returns the field at particular index (must be in range 0..N-1).
Q_INVOKABLE 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
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.
void setDataDefinedProperties(const QgsPropertyCollection &collection)
Sets the label's property collection, used for data defined overrides.
Property
Data definable properties.
@ PositionX
X-coordinate data defined label position.
@ MinScale
Min scale (deprecated, for old project compatibility only)
@ LabelRotation
Label rotation.
@ FontStyle
Font style name.
@ Italic
Use italic style.
@ PositionY
Y-coordinate data defined label position.
@ Vali
Vertical alignment for data defined label position (Bottom, Base, Half, Cap, Top)
@ MaxScale
Max scale (deprecated, for old project compatibility only)
@ Strikeout
Use strikeout.
@ LabelAllParts
Whether all parts of multi-part features should be labeled.
@ Underline
Use underline.
@ Hali
Horizontal alignment for data defined label position (Left, Center, Right)
@ CalloutDraw
Show callout.
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.
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.
Qgis::PropertyType propertyType() const
Returns the property type.
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.
static QgsProperty fromField(const QString &fieldName, bool isActive=true)
Returns a new FieldBasedProperty created from the specified field name.
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 deleteFeatures(const QgsFeatureIds &fids, QgsVectorLayer::DeleteContext *context=nullptr)
Deletes a set of features from the layer (but does not commit it)
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.
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)
Sets the editor widget setup for the field at the specified index.
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
Returns the editor widget setup for the field at the specified index.
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
Q_GLOBAL_STATIC_WITH_ARGS(PalPropertyList, palHiddenProperties,({ static_cast< int >(QgsPalLayerSettings::Property::PositionX), static_cast< int >(QgsPalLayerSettings::Property::PositionY), static_cast< int >(QgsPalLayerSettings::Property::Show), static_cast< int >(QgsPalLayerSettings::Property::LabelRotation), static_cast< int >(QgsPalLayerSettings::Property::Family), static_cast< int >(QgsPalLayerSettings::Property::FontStyle), static_cast< int >(QgsPalLayerSettings::Property::Size), static_cast< int >(QgsPalLayerSettings::Property::Bold), static_cast< int >(QgsPalLayerSettings::Property::Italic), static_cast< int >(QgsPalLayerSettings::Property::Underline), static_cast< int >(QgsPalLayerSettings::Property::Color), static_cast< int >(QgsPalLayerSettings::Property::Strikeout), static_cast< int >(QgsPalLayerSettings::Property::MultiLineAlignment), static_cast< int >(QgsPalLayerSettings::Property::BufferSize), static_cast< int >(QgsPalLayerSettings::Property::BufferDraw), static_cast< int >(QgsPalLayerSettings::Property::BufferColor), static_cast< int >(QgsPalLayerSettings::Property::LabelDistance), static_cast< int >(QgsPalLayerSettings::Property::Hali), static_cast< int >(QgsPalLayerSettings::Property::Vali), static_cast< int >(QgsPalLayerSettings::Property::ScaleVisibility), static_cast< int >(QgsPalLayerSettings::Property::MinScale), static_cast< int >(QgsPalLayerSettings::Property::MaxScale), static_cast< int >(QgsPalLayerSettings::Property::AlwaysShow), static_cast< int >(QgsPalLayerSettings::Property::CalloutDraw), static_cast< int >(QgsPalLayerSettings::Property::LabelAllParts) })) Q_GLOBAL_STATIC_WITH_ARGS(SymbolPropertyList
QVector< int > SymbolPropertyList
QVector< int > PalPropertyList
#define QgsDebugError(str)
QMap< int, QgsPropertyDefinition > QgsPropertiesDefinition
Definition of available properties.