QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmsplitvectorlayer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmsplitvectorlayer.cpp
3 ---------------------
4 begin : May 2020
5 copyright : (C) 2020 by Alexander Bruy
6 email : alexander dot bruy at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19#include "qgsvectorfilewriter.h"
20#include "qgsvariantutils.h"
21#include "qgsfileutils.h"
22
24
25QString QgsSplitVectorLayerAlgorithm::name() const
26{
27 return QStringLiteral( "splitvectorlayer" );
28}
29
30QString QgsSplitVectorLayerAlgorithm::displayName() const
31{
32 return QObject::tr( "Split vector layer" );
33}
34
35QStringList QgsSplitVectorLayerAlgorithm::tags() const
36{
37 return QObject::tr( "vector,split,field,unique" ).split( ',' );
38}
39
40QString QgsSplitVectorLayerAlgorithm::group() const
41{
42 return QObject::tr( "Vector general" );
43}
44
45QString QgsSplitVectorLayerAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectorgeneral" );
48}
49
50QString QgsSplitVectorLayerAlgorithm::shortHelpString() const
51{
52 return QObject::tr( "This algorithm splits input vector layer into multiple layers by specified unique ID field." )
53 + QStringLiteral( "\n\n" )
54 + QObject::tr( "Each of the layers created in the output folder contains all features from "
55 "the input layer with the same value for the specified attribute. The number "
56 "of files generated is equal to the number of different values found for the "
57 "specified attribute." );
58}
59
60QString QgsSplitVectorLayerAlgorithm::shortDescription() const
61{
62 return QObject::tr( "Splits a vector layer into multiple layers, each containing "
63 "all the features with the same value for a specified attribute." );
64}
65
66QgsSplitVectorLayerAlgorithm *QgsSplitVectorLayerAlgorithm::createInstance() const
67{
68 return new QgsSplitVectorLayerAlgorithm();
69}
70
71void QgsSplitVectorLayerAlgorithm::initAlgorithm( const QVariantMap & )
72{
73 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
74 addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELD" ), QObject::tr( "Unique ID field" ), QVariant(), QStringLiteral( "INPUT" ) ) );
75 auto prefixFieldParam = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral( "PREFIX_FIELD" ), QObject::tr( "Add field prefix to file names" ), true );
76 addParameter( prefixFieldParam.release() );
77
78 const QStringList options = QgsVectorFileWriter::supportedFormatExtensions();
79 auto fileTypeParam = std::make_unique<QgsProcessingParameterEnum>( QStringLiteral( "FILE_TYPE" ), QObject::tr( "Output file type" ), options, false, 0, true );
80 fileTypeParam->setFlags( fileTypeParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
81 addParameter( fileTypeParam.release() );
82
83 addParameter( new QgsProcessingParameterFolderDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "Output directory" ) ) );
84 addOutput( new QgsProcessingOutputMultipleLayers( QStringLiteral( "OUTPUT_LAYERS" ), QObject::tr( "Output layers" ) ) );
85}
86
87QVariantMap QgsSplitVectorLayerAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
88{
89 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
90 if ( !source )
91 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
92
93 const QString fieldName = parameterAsString( parameters, QStringLiteral( "FIELD" ), context );
94 const QString outputDir = parameterAsString( parameters, QStringLiteral( "OUTPUT" ), context );
95 QString outputFormat;
96 if ( parameters.value( QStringLiteral( "FILE_TYPE" ) ).isValid() )
97 {
98 const int idx = parameterAsEnum( parameters, QStringLiteral( "FILE_TYPE" ), context );
99 outputFormat = QgsVectorFileWriter::supportedFormatExtensions().at( idx );
100 }
101 else
102 {
103 outputFormat = context.preferredVectorFormat();
104 if ( !QgsVectorFileWriter::supportedFormatExtensions().contains( outputFormat, Qt::CaseInsensitive ) )
105 outputFormat = QStringLiteral( "gpkg" );
106 }
107
108 if ( !QDir().mkpath( outputDir ) )
109 throw QgsProcessingException( QObject::tr( "Failed to create output directory." ) );
110
111 const QgsFields fields = source->fields();
112 const QgsCoordinateReferenceSystem crs = source->sourceCrs();
113 const Qgis::WkbType geometryType = source->wkbType();
114 const int fieldIndex = fields.lookupField( fieldName );
115 const QSet<QVariant> uniqueValues = source->uniqueValues( fieldIndex );
116 QString baseName = outputDir + QDir::separator();
117
118 if ( parameterAsBool( parameters, QStringLiteral( "PREFIX_FIELD" ), context ) )
119 {
120 baseName.append( fieldName + "_" );
121 }
122
123 int current = 0;
124 const double step = uniqueValues.size() > 0 ? 100.0 / uniqueValues.size() : 1;
125
126 int count = 0;
127 QgsFeature feat;
128 QStringList outputLayers;
129 std::unique_ptr<QgsFeatureSink> sink;
130
131 for ( auto it = uniqueValues.constBegin(); it != uniqueValues.constEnd(); ++it )
132 {
133 if ( feedback->isCanceled() )
134 break;
135
136 QString fileName;
137 if ( QgsVariantUtils::isNull( *it ) )
138 {
139 fileName = QStringLiteral( "%1NULL.%2" ).arg( baseName ).arg( outputFormat );
140 }
141 else if ( ( *it ).toString().isEmpty() )
142 {
143 fileName = QStringLiteral( "%1EMPTY.%2" ).arg( baseName ).arg( outputFormat );
144 }
145 else
146 {
147 fileName = QStringLiteral( "%1%2.%3" ).arg( baseName ).arg( QgsFileUtils::stringToSafeFilename( ( *it ).toString() ) ).arg( outputFormat );
148 }
149 feedback->pushInfo( QObject::tr( "Creating layer: %1" ).arg( fileName ) );
150
151 sink.reset( QgsProcessingUtils::createFeatureSink( fileName, context, fields, geometryType, crs ) );
152 const QString expr = QgsExpression::createFieldEqualityExpression( fieldName, *it );
153 QgsFeatureIterator features = source->getFeatures( QgsFeatureRequest().setFilterExpression( expr ), Qgis::ProcessingFeatureSourceFlag::SkipGeometryValidityChecks );
154 count = 0;
155 while ( features.nextFeature( feat ) )
156 {
157 if ( feedback->isCanceled() )
158 break;
159
160 if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) )
161 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
162 count += 1;
163 }
164 sink->finalize();
165
166 feedback->pushInfo( QObject::tr( "Added %n feature(s) to layer", nullptr, count ) );
167 outputLayers << fileName;
168
169 current += 1;
170 feedback->setProgress( current * step );
171 }
172
173 QVariantMap outputs;
174 outputs.insert( QStringLiteral( "OUTPUT" ), outputDir );
175 outputs.insert( QStringLiteral( "OUTPUT_LAYERS" ), outputLayers );
176 return outputs;
177}
178
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:256
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Represents a coordinate reference system (CRS).
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.
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).
@ 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...
Definition qgsfeature.h:58
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
Container of fields for a vector layer.
Definition qgsfields.h:46
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
static QString stringToSafeFilename(const QString &string)
Converts a string to a safe filename, replacing characters which are not safe for filenames with an '...
Contains information about the context in which a processing algorithm is executed.
QString preferredVectorFormat() const
Returns the preferred vector format to use for vector outputs.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
A multi-layer output for processing algorithms which create map layers, when the number and nature of...
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
A folder destination parameter, for specifying the destination path for a folder created by the algor...
static QgsFeatureSink * createFeatureSink(QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap(), const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QgsRemappingSinkDefinition *remappingDefinition=nullptr)
Creates a feature sink ready for adding features.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
static QStringList supportedFormatExtensions(VectorFormatOptions options=SortRecommended)
Returns a list of file extensions for supported formats, e.g "shp", "gpkg".
const QgsCoordinateReferenceSystem & crs