QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
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
20#include "qgsfileutils.h"
21#include "qgsvariantutils.h"
22#include "qgsvectorfilewriter.h"
23
25
26QString QgsSplitVectorLayerAlgorithm::name() const
27{
28 return QStringLiteral( "splitvectorlayer" );
29}
30
31QString QgsSplitVectorLayerAlgorithm::displayName() const
32{
33 return QObject::tr( "Split vector layer" );
34}
35
36QStringList QgsSplitVectorLayerAlgorithm::tags() const
37{
38 return QObject::tr( "vector,split,field,unique" ).split( ',' );
39}
40
41QString QgsSplitVectorLayerAlgorithm::group() const
42{
43 return QObject::tr( "Vector general" );
44}
45
46QString QgsSplitVectorLayerAlgorithm::groupId() const
47{
48 return QStringLiteral( "vectorgeneral" );
49}
50
51QString QgsSplitVectorLayerAlgorithm::shortHelpString() const
52{
53 return QObject::tr( "This algorithm splits input vector layer into multiple layers by specified unique ID field." )
54 + QStringLiteral( "\n\n" )
55 + QObject::tr( "Each of the layers created in the output folder contains all features from "
56 "the input layer with the same value for the specified attribute. The number "
57 "of files generated is equal to the number of different values found for the "
58 "specified attribute." );
59}
60
61QString QgsSplitVectorLayerAlgorithm::shortDescription() const
62{
63 return QObject::tr( "Splits a vector layer into multiple layers, each containing "
64 "all the features with the same value for a specified attribute." );
65}
66
67QgsSplitVectorLayerAlgorithm *QgsSplitVectorLayerAlgorithm::createInstance() const
68{
69 return new QgsSplitVectorLayerAlgorithm();
70}
71
72void QgsSplitVectorLayerAlgorithm::initAlgorithm( const QVariantMap & )
73{
74 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::Vector ) ) );
75 addParameter( new QgsProcessingParameterField( QStringLiteral( "FIELD" ), QObject::tr( "Unique ID field" ), QVariant(), QStringLiteral( "INPUT" ) ) );
76 auto prefixFieldParam = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral( "PREFIX_FIELD" ), QObject::tr( "Add field prefix to file names" ), true );
77 addParameter( prefixFieldParam.release() );
78
79 const QStringList options = QgsVectorFileWriter::supportedFormatExtensions();
80 auto fileTypeParam = std::make_unique<QgsProcessingParameterEnum>( QStringLiteral( "FILE_TYPE" ), QObject::tr( "Output file type" ), options, false, 0, true );
81 fileTypeParam->setFlags( fileTypeParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
82 addParameter( fileTypeParam.release() );
83
84 addParameter( new QgsProcessingParameterFolderDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "Output directory" ) ) );
85 addOutput( new QgsProcessingOutputMultipleLayers( QStringLiteral( "OUTPUT_LAYERS" ), QObject::tr( "Output layers" ) ) );
86}
87
88QVariantMap QgsSplitVectorLayerAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
89{
90 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
91 if ( !source )
92 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
93
94 const QString fieldName = parameterAsString( parameters, QStringLiteral( "FIELD" ), context );
95 const QString outputDir = parameterAsString( parameters, QStringLiteral( "OUTPUT" ), context );
96 QString outputFormat;
97 if ( parameters.value( QStringLiteral( "FILE_TYPE" ) ).isValid() )
98 {
99 const int idx = parameterAsEnum( parameters, QStringLiteral( "FILE_TYPE" ), context );
100 outputFormat = QgsVectorFileWriter::supportedFormatExtensions().at( idx );
101 }
102 else
103 {
104 outputFormat = context.preferredVectorFormat();
105 if ( !QgsVectorFileWriter::supportedFormatExtensions().contains( outputFormat, Qt::CaseInsensitive ) )
106 outputFormat = QStringLiteral( "gpkg" );
107 }
108
109 if ( !QDir().mkpath( outputDir ) )
110 throw QgsProcessingException( QObject::tr( "Failed to create output directory." ) );
111
112 const QgsFields fields = source->fields();
113 const QgsCoordinateReferenceSystem crs = source->sourceCrs();
114 const Qgis::WkbType geometryType = source->wkbType();
115 const int fieldIndex = fields.lookupField( fieldName );
116 const QSet<QVariant> uniqueValues = source->uniqueValues( fieldIndex );
117 QString baseName = outputDir + QDir::separator();
118
119 if ( parameterAsBool( parameters, QStringLiteral( "PREFIX_FIELD" ), context ) )
120 {
121 baseName.append( fieldName + "_" );
122 }
123
124 int current = 0;
125 const double step = uniqueValues.size() > 0 ? 100.0 / uniqueValues.size() : 1;
126
127 int count = 0;
128 QgsFeature feat;
129 QStringList outputLayers;
130 std::unique_ptr<QgsFeatureSink> sink;
131
132 for ( auto it = uniqueValues.constBegin(); it != uniqueValues.constEnd(); ++it )
133 {
134 if ( feedback->isCanceled() )
135 break;
136
137 QString fileName;
138 if ( QgsVariantUtils::isNull( *it ) )
139 {
140 fileName = QStringLiteral( "%1NULL.%2" ).arg( baseName ).arg( outputFormat );
141 }
142 else if ( ( *it ).toString().isEmpty() )
143 {
144 fileName = QStringLiteral( "%1EMPTY.%2" ).arg( baseName ).arg( outputFormat );
145 }
146 else
147 {
148 fileName = QStringLiteral( "%1%2.%3" ).arg( baseName ).arg( QgsFileUtils::stringToSafeFilename( ( *it ).toString() ) ).arg( outputFormat );
149 }
150 feedback->pushInfo( QObject::tr( "Creating layer: %1" ).arg( fileName ) );
151
152 sink.reset( QgsProcessingUtils::createFeatureSink( fileName, context, fields, geometryType, crs ) );
153 const QString expr = QgsExpression::createFieldEqualityExpression( fieldName, *it );
154 QgsFeatureIterator features = source->getFeatures( QgsFeatureRequest().setFilterExpression( expr ), Qgis::ProcessingFeatureSourceFlag::SkipGeometryValidityChecks );
155 count = 0;
156 while ( features.nextFeature( feat ) )
157 {
158 if ( feedback->isCanceled() )
159 break;
160
161 if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) )
162 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
163 count += 1;
164 }
165 sink->finalize();
166
167 feedback->pushInfo( QObject::tr( "Added %n feature(s) to layer", nullptr, count ) );
168 outputLayers << fileName;
169
170 current += 1;
171 feedback->setProgress( current * step );
172 }
173
174 QVariantMap outputs;
175 outputs.insert( QStringLiteral( "OUTPUT" ), outputDir );
176 outputs.insert( QStringLiteral( "OUTPUT_LAYERS" ), outputLayers );
177 return outputs;
178}
179
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
Definition qgis.h:3539
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3711
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:277
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
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".