22#include <QRegularExpression>
26QString QgsSaveFeaturesAlgorithm::name()
const
28 return QStringLiteral(
"savefeatures" );
31QString QgsSaveFeaturesAlgorithm::displayName()
const
33 return QObject::tr(
"Save vector features to file" );
36QStringList QgsSaveFeaturesAlgorithm::tags()
const
38 return QObject::tr(
"save,write,export" ).split(
',' );
41QString QgsSaveFeaturesAlgorithm::group()
const
43 return QObject::tr(
"Vector general" );
46QString QgsSaveFeaturesAlgorithm::groupId()
const
48 return QStringLiteral(
"vectorgeneral" );
51QString QgsSaveFeaturesAlgorithm::shortHelpString()
const
53 return QObject::tr(
"This algorithm saves vector features to a specified file dataset.\n\n"
54 "For dataset formats supporting layers, an optional layer name parameter can be used to specify a custom string.\n\n"
55 "Optional GDAL-defined dataset and layer options can be specified. For more information on this, "
56 "read the online GDAL documentation." );
59QString QgsSaveFeaturesAlgorithm::shortDescription()
const
61 return QObject::tr(
"Saves vector features to a specified file dataset." );
64QgsSaveFeaturesAlgorithm *QgsSaveFeaturesAlgorithm::createInstance()
const
66 return new QgsSaveFeaturesAlgorithm();
69void QgsSaveFeaturesAlgorithm::initAlgorithm(
const QVariantMap & )
74 auto param = std::make_unique<QgsProcessingParameterString>( QStringLiteral(
"LAYER_NAME" ), QObject::tr(
"Layer name" ), QVariant(),
false,
true );
76 addParameter( param.release() );
77 param = std::make_unique<QgsProcessingParameterString>( QStringLiteral(
"DATASOURCE_OPTIONS" ), QObject::tr(
"GDAL dataset options (separate individual options with semicolons)" ), QVariant(),
false,
true );
79 addParameter( param.release() );
80 param = std::make_unique<QgsProcessingParameterString>( QStringLiteral(
"LAYER_OPTIONS" ), QObject::tr(
"GDAL layer options (separate individual options with semicolons)" ), QVariant(),
false,
true );
82 addParameter( param.release() );
84 auto paramEnum = std::make_unique<QgsProcessingParameterEnum>( QStringLiteral(
"ACTION_ON_EXISTING_FILE" ), QObject::tr(
"Action to take on pre-existing file" ), QStringList() << QObject::tr(
"Create or overwrite file" ) << QObject::tr(
"Create or overwrite layer" ) << QObject::tr(
"Append features to existing layer, but do not create new fields" ) << QObject::tr(
"Append features to existing layer, and create new fields if needed" ),
false, 0 );
86 addParameter( paramEnum.release() );
94 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral(
"INPUT" ), context ) );
98 QString layerName = parameterAsString( parameters, QStringLiteral(
"LAYER_NAME" ), context ).trimmed();
99 QVariantMap createOptions;
100 if ( !layerName.isEmpty() )
102 createOptions[QStringLiteral(
"layerName" )] = layerName;
105 const QStringList datasourceOptions = parameterAsString( parameters, QStringLiteral(
"DATASOURCE_OPTIONS" ), context ).trimmed().split(
';', Qt::SkipEmptyParts );
106 const QStringList layerOptions = parameterAsString( parameters, QStringLiteral(
"LAYER_OPTIONS" ), context ).trimmed().split(
';', Qt::SkipEmptyParts );
108 QString destination = parameterAsString( parameters, QStringLiteral(
"OUTPUT" ), context );
113 QString finalFileName;
114 QString finalLayerName;
125 if ( writer->hasError() )
127 throw QgsProcessingException( QObject::tr(
"Could not create layer %1: %2" ).arg( destination, writer->errorMessage() ) );
132 for (
const QgsField &field : source->fields() )
135 feedback->
pushWarning( QObject::tr(
"%1: Aliases are not supported by %2" ).arg( field.name(), writer->driverLongName() ) );
137 feedback->
pushWarning( QObject::tr(
"%1: Comments are not supported by %2" ).arg( field.name(), writer->driverLongName() ) );
141 destination = finalFileName;
142 if ( !saveOptions.
layerName.isEmpty() && !finalLayerName.isEmpty() )
143 destination += QStringLiteral(
"|layername=%1" ).arg( finalLayerName );
145 std::unique_ptr<QgsFeatureSink> sink(
new QgsProcessingFeatureSink( writer.release(), destination, context,
true ) );
149 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
168 finalFileName = destination;
169 finalLayerName.clear();
170 const int separatorIndex = destination.indexOf(
'|' );
171 if ( separatorIndex > -1 )
173 const thread_local QRegularExpression layerNameRx( QStringLiteral(
"\\|layername=([^\\|]*)" ) );
174 const QRegularExpressionMatch match = layerNameRx.match( destination );
175 if ( match.hasMatch() )
177 finalLayerName = match.captured( 1 );
179 finalFileName = destination.mid( 0, separatorIndex );
183 outputs.insert( QStringLiteral(
"OUTPUT" ), destination );
184 outputs.insert( QStringLiteral(
"FILE_PATH" ), finalFileName );
185 outputs.insert( QStringLiteral(
"LAYER_NAME" ), finalLayerName );
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ FieldComments
Writer can support field comments.
@ FieldAliases
Writer can support field aliases.
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
@ NoSymbology
Export only data.
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.
Wraps a request for features to a vector layer (or directly its vector data provider).
QFlags< SinkFlag > SinkFlags
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
bool isCanceled() const
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
Encapsulate a field in an attribute table or data source.
Contains information about the context in which a processing algorithm is executed.
QString defaultEncoding() const
Returns the default encoding to use for newly created files.
QgsProcessingFeedback * feedback()
Returns the associated feedback object.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
QgsProxyFeatureSink subclass which reports feature addition errors to a QgsProcessingContext.
Base class for providing feedback from a processing algorithm.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
A string output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A generic file based destination parameter, for specifying the destination path for a file (non-map l...
Options to pass to QgsVectorFileWriter::writeAsVectorFormat().
QString fileEncoding
Encoding to use.
QString driverName
OGR driver to use.
QString layerName
Layer name. If let empty, it will be derived from the filename.
QStringList layerOptions
List of OGR layer creation options.
Qgis::FeatureSymbologyExport symbologyExport
Symbology to export.
QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile
Action on existing file.
QStringList datasourceOptions
List of OGR data source creation options.
static QString driverForExtension(const QString &extension)
Returns the OGR driver name for a specified file extension.
static QgsVectorFileWriter * create(const QString &fileName, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &srs, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QString *newFilename=nullptr, QString *newLayer=nullptr)
Create a new vector file writer.
static QString fileFilterString(VectorFormatOptions options=SortRecommended)
Returns filter string that can be used for dialogs.
ActionOnExistingFile
Enumeration to describe how to handle existing files.