QGIS API Documentation
3.26.3-Buenos Aires (65e4edfdad)
|
Go to the documentation of this file.
36 #include <QProgressDialog>
44 QMap<int, int> *oldToNewAttrIdx,
45 QString *errorMessage,
46 const QMap<QString, QVariant> *options
51 const QString &providerKey,
56 const QMap<QString, QVariant> &options,
57 QgsFeatureSink::SinkFlags sinkFlags )
59 , mAttributeCount( -1 )
64 QMap<QString, QVariant> modifiedOptions( options );
66 if ( providerKey == QLatin1String(
"ogr" ) &&
67 options.contains( QStringLiteral(
"driverName" ) ) &&
68 ( options[ QStringLiteral(
"driverName" ) ].toString().compare( QLatin1String(
"GPKG" ), Qt::CaseInsensitive ) == 0 ||
69 options[ QStringLiteral(
"driverName" ) ].toString().compare( QLatin1String(
"SQLite" ), Qt::CaseInsensitive ) == 0 ) )
76 QStringList modifiedLayerOptions;
77 if ( options.contains( QStringLiteral(
"layerOptions" ) ) )
79 const QStringList layerOptions = options.value( QStringLiteral(
"layerOptions" ) ).toStringList();
80 for (
const QString &layerOption : layerOptions )
82 if ( layerOption.compare( QLatin1String(
"SPATIAL_INDEX=YES" ), Qt::CaseInsensitive ) == 0 ||
83 layerOption.compare( QLatin1String(
"SPATIAL_INDEX=ON" ), Qt::CaseInsensitive ) == 0 ||
84 layerOption.compare( QLatin1String(
"SPATIAL_INDEX=TRUE" ), Qt::CaseInsensitive ) == 0 ||
85 layerOption.compare( QLatin1String(
"SPATIAL_INDEX=1" ), Qt::CaseInsensitive ) == 0 )
89 else if ( layerOption.compare( QLatin1String(
"SPATIAL_INDEX=NO" ), Qt::CaseInsensitive ) == 0 ||
90 layerOption.compare( QLatin1String(
"SPATIAL_INDEX=OFF" ), Qt::CaseInsensitive ) == 0 ||
91 layerOption.compare( QLatin1String(
"SPATIAL_INDEX=FALSE" ), Qt::CaseInsensitive ) == 0 ||
92 layerOption.compare( QLatin1String(
"SPATIAL_INDEX=0" ), Qt::CaseInsensitive ) == 0 )
94 mCreateSpatialIndex =
false;
98 modifiedLayerOptions << layerOption;
102 modifiedLayerOptions << QStringLiteral(
"SPATIAL_INDEX=FALSE" );
103 modifiedOptions[ QStringLiteral(
"layerOptions" ) ] = modifiedLayerOptions;
110 mError = pReg->
createEmptyLayer( providerKey, uri, fields, geometryType,
crs, overwrite, mOldToNewAttrIdx,
111 errMsg, !modifiedOptions.isEmpty() ? &modifiedOptions :
nullptr );
113 if (
errorCode() != Qgis::VectorExportResult::Success )
115 mErrorMessage = errMsg;
119 const auto constMOldToNewAttrIdx = mOldToNewAttrIdx;
120 for (
const int idx : constMOldToNewAttrIdx )
122 if ( idx > mAttributeCount )
123 mAttributeCount = idx;
130 QString uriUpdated( uri );
132 if ( providerKey == QLatin1String(
"ogr" ) )
135 if ( options.contains( QStringLiteral(
"layerName" ) ) )
136 layerName = options.value( QStringLiteral(
"layerName" ) ).toString();
137 if ( !layerName.isEmpty() )
139 uriUpdated += QLatin1String(
"|layername=" );
140 uriUpdated += layerName;
146 if ( providerKey == QLatin1String(
"oracle" ) )
155 mError = Qgis::VectorExportResult::ErrorInvalidLayer;
156 mErrorMessage = QObject::tr(
"Loading of layer failed" );
158 delete vectorProvider;
168 if ( sinkFlags.testFlag( QgsFeatureSink::SinkFlag::RegeneratePrimaryKey ) && path.endsWith( QLatin1String(
".gpkg" ), Qt::CaseInsensitive ) )
170 const QString fidName = options.value( QStringLiteral(
"FID" ), QStringLiteral(
"FID" ) ).toString();
174 mOldToNewAttrIdx.remove( fidIdx );
178 mProvider = vectorProvider;
179 mError = Qgis::VectorExportResult::Success;
186 if ( mCreateSpatialIndex )
188 createSpatialIndex();
201 return mErrorMessage;
206 QgsFeatureList::iterator fIt = features.begin();
208 for ( ; fIt != features.end(); ++fIt )
225 for (
int i = 0; i < attrs.count(); ++i )
229 const int dstIdx = mOldToNewAttrIdx.value( i, -1 );
233 QgsDebugMsgLevel( QStringLiteral(
"moving field from pos %1 to %2" ).arg( i ).arg( dstIdx ), 3 );
237 mFeatureBuffer.append( newFeat );
240 if ( mFeatureBufferMemoryUsage >= 100 * 1000 * 1000 )
250 return mErrorMessage;
255 mFeatureBufferMemoryUsage = 0;
256 if ( mFeatureBuffer.count() <= 0 )
261 const QStringList errors = mProvider->
errors();
264 mErrorMessage = QObject::tr(
"Creation error for features from #%1 to #%2. Provider errors was: \n%3" )
265 .arg( mFeatureBuffer.first().id() )
266 .arg( mFeatureBuffer.last().id() )
267 .arg( errors.join( QLatin1Char(
'\n' ) ) );
269 mError = Qgis::VectorExportResult::ErrorFeatureWriteFailed;
270 mErrorCount += mFeatureBuffer.count();
272 mFeatureBuffer.clear();
277 mFeatureBuffer.clear();
281 bool QgsVectorLayerExporter::createSpatialIndex()
283 mCreateSpatialIndex =
false;
296 const QString &providerKey,
299 QString *errorMessage,
300 const QMap<QString, QVariant> &options,
305 bool shallTransform =
false;
308 return Qgis::VectorExportResult::ErrorInvalidLayer;
314 shallTransform =
true;
319 outputCRS = layer->
crs();
323 bool overwrite =
false;
324 bool forceSinglePartGeom =
false;
325 QMap<QString, QVariant> providerOptions = options;
326 if ( !options.isEmpty() )
328 overwrite = providerOptions.take( QStringLiteral(
"overwrite" ) ).toBool();
329 forceSinglePartGeom = providerOptions.take( QStringLiteral(
"forceSinglePartGeometryType" ) ).toBool();
337 if ( layer->
providerType() == QLatin1String(
"ogr" ) && layer->
storageType() == QLatin1String(
"ESRI Shapefile" ) )
340 for (
int fldIdx = 0; fldIdx < fields.
count(); ++fldIdx )
342 fields.
rename( fldIdx, fields.
at( fldIdx ).
name().toLower() );
346 bool convertGeometryToSinglePart =
false;
350 convertGeometryToSinglePart =
true;
358 if ( err != Qgis::VectorExportResult::Success )
389 shallTransform =
false;
399 bool canceled =
false;
409 *
errorMessage +=
'\n' + QObject::tr(
"Import was canceled at %1 of %2" ).arg( n ).arg( approxTotal );
423 if ( shallTransform )
438 const QString msg = QObject::tr(
"Failed to transform a point while drawing a feature with ID '%1'. Writing stopped. (Exception: %2)" )
439 .arg( fet.
id() ).arg( e.
what() );
444 return Qgis::VectorExportResult::ErrorProjectingFeatures;
454 const QgsGeometryCollection *
c = qgsgeometry_cast<const QgsGeometryCollection *>( singlePartGeometry.constGet() );
455 if ( (
c &&
c->partCount() > 1 ) || ! singlePartGeometry.convertToSingleType() )
458 const QString msg = QObject::tr(
"Failed to transform a feature with ID '%1' to single part. Writing stopped." )
463 return Qgis::VectorExportResult::ErrorFeatureWriteFailed;
479 feedback->
setProgress( 100.0 *
static_cast< double >( n ) / approxTotal );
494 if ( writer->mCreateSpatialIndex && !writer->createSpatialIndex() )
508 *
errorMessage +=
'\n' + QObject::tr(
"Only %1 of %2 features written." ).arg( n - errors ).arg( n );
517 return Qgis::VectorExportResult::UserCanceled;
518 else if ( errors > 0 )
519 return Qgis::VectorExportResult::ErrorFeatureWriteFailed;
521 return Qgis::VectorExportResult::Success;
530 :
QgsTask( tr(
"Exporting %1" ).arg( layer->name() ),
QgsTask::CanCancel )
532 , mOwnsLayer( ownsLayer )
534 , mDestProviderKey( providerKey )
535 , mDestCrs( destinationCrs )
536 , mOptions( options )
545 std::unique_ptr< QgsVectorLayerExporterTask > newTask(
new QgsVectorLayerExporterTask( layer, uri, providerKey, destinationCrs, options ) );
546 newTask->mOwnsLayer =
true;
547 return newTask.release();
552 mOwnedFeedback->cancel();
565 mLayer.data(), mDestUri, mDestProviderKey, mDestCrs,
false, &mErrorMessage,
566 mOptions, mOwnedFeedback.get() );
568 return mError == Qgis::VectorExportResult::Success;
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsCoordinateReferenceSystem crs
void setProgress(double progress)
Sets the current progress for the feedback object.
virtual bool createSpatialIndex()
Creates a spatial index on the datasource (if supported by the provider type).
Q_INVOKABLE QgsWkbTypes::Type wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
void cancel() override
Notifies the task that it should terminate.
Qgis::VectorExportResult createEmptyLayer_t(const QString &uri, const QgsFields &fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem &destCRS, bool overwrite, QMap< int, int > *oldToNewAttrIdx, QString *errorMessage, const QMap< QString, QVariant > *options)
static QString displayString(Type type) SIP_HOLDGIL
Returns a non-translated display string type for a WKB type, e.g., the geometry name used in WKT geom...
Setting options for creating vector data providers.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
void initAttributes(int fieldCount)
Initialize this feature with the given number of fields.
#define QgsDebugMsgLevel(str, level)
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false) SIP_THROW(QgsCsException)
Transforms this geometry as described by the coordinate transform ct.
VectorExportResult
Vector layer export result codes.
A registry / canonical manager of data providers.
long long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
@ CreateSpatialIndex
Allows creation of spatial index.
const QgsCoordinateReferenceSystem & crs
~QgsVectorLayerExporter() override
Finalizes the export and closes the new created layer.
static QgsVectorLayerExporterTask * withLayerOwnership(QgsVectorLayer *layer, const QString &uri, const QString &providerKey, const QgsCoordinateReferenceSystem &destinationCrs, const QMap< QString, QVariant > &options=QMap< QString, QVariant >())
Creates a new QgsVectorLayerExporterTask which has ownership over a source layer.
int count() const
Returns number of items.
Container of fields for a vector layer.
QgsVectorLayerExporter(const QString &uri, const QString &provider, const QgsFields &fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem &crs, bool overwrite=false, const QMap< QString, QVariant > &options=QMap< QString, QVariant >(), QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags())
Constructor for QgsVectorLayerExporter.
int errorCount() const
Returns the number of error messages encountered during the export.
bool isCanceled() const SIP_HOLDGIL
Tells whether the operation has been canceled already.
void exportComplete()
Emitted when exporting the layer is successfully completed.
Type
The WKB type describes the number of dimensions a geometry has.
QgsVectorLayerExporterTask(QgsVectorLayer *layer, const QString &uri, const QString &providerKey, const QgsCoordinateReferenceSystem &destinationCrs, const QMap< QString, QVariant > &options=QMap< QString, QVariant >(), bool ownsLayer=false)
Constructor for QgsVectorLayerExporterTask.
int approximateMemoryUsage() const
Returns the approximate RAM usage of the feature, in bytes.
QString providerType() const
Returns the provider type (provider key) for this layer.
bool isMultipart() const SIP_HOLDGIL
Returns true if WKB of the geometry is of WKBMulti* type.
virtual void cancel()
Notifies the task that it should terminate.
static Qgis::VectorExportResult exportLayer(QgsVectorLayer *layer, const QString &uri, const QString &providerKey, const QgsCoordinateReferenceSystem &destCRS, bool onlySelected=false, QString *errorMessage=nullptr, const QMap< QString, QVariant > &options=QMap< QString, QVariant >(), QgsFeedback *feedback=nullptr)
Writes the contents of vector layer to a different datasource.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
QStringList errors() const
Gets recorded errors.
This class wraps a request for features to a vector layer (or directly its vector data provider).
virtual Q_INVOKABLE QgsVectorDataProvider::Capabilities capabilities() const
Returns flags containing the supported capabilities.
QgsTask task which performs a QgsVectorLayerExporter layer export operation as a background task....
Custom exception class for Coordinate Reference System related exceptions.
Qgis::VectorExportResult errorCode() const
Returns any encountered error code, or false if no error was encountered.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
void setDependentLayers(const QList< QgsMapLayer * > &dependentLayers)
Sets a list of layers on which the task depends.
const Q_INVOKABLE QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
void setProgress(double progress)
Sets the task's current progress.
QList< QgsFeature > QgsFeatureList
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Breaks a provider data source URI into its component paths (e.g.
@ AddFeatures
Allows adding features.
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets the feature IDs that should be fetched.
bool flushBuffer() override
Flushes any internal buffer which may exist in the sink, causing any buffered features to be added to...
void progressChanged(double progress)
Emitted when the feedback object reports a progress change.
This class represents a coordinate reference system (CRS).
void clearErrors()
Clear recorded errors.
QString errorMessage() const
Returns any error message encountered during the export.
bool setAttribute(int field, const QVariant &attr)
Sets an attribute's value by field index.
bool addFeatures(QgsFeatureList &flist, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
QString lastError() const override
Returns the most recent error encountered by the sink, e.g.
QgsCoordinateTransformContext transformContext() const
Returns the layer data provider coordinate transform context or a default transform context if the la...
QgsDataProvider * createProvider(const QString &providerKey, const QString &dataSource, const QgsDataProvider::ProviderOptions &options=QgsDataProvider::ProviderOptions(), QgsDataProvider::ReadFlags flags=QgsDataProvider::ReadFlags())
Creates a new instance of a provider.
bool nextFeature(QgsFeature &f)
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
A geometry is the spatial representation of a feature.
Represents a vector layer which manages a vector based data sets.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
QString storageType() const
Returns the permanent storage type for this layer as a friendly name.
A convenience class for exporting vector layers to a destination data provider.
Qgis::VectorExportResult createEmptyLayer(const QString &providerKey, const QString &uri, const QgsFields &fields, QgsWkbTypes::Type wkbType, const QgsCoordinateReferenceSystem &srs, bool overwrite, QMap< int, int > &oldToNewAttrIdxMap, QString &errorMessage, const QMap< QString, QVariant > *options)
Creates new empty vector layer.
A vector of attributes. Mostly equal to QVector<QVariant>.
This is the base class for vector data providers.
bool rename(int fieldIdx, const QString &name)
Renames a name of field.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
static bool isMultiType(Type type) SIP_HOLDGIL
Returns true if the WKB type is a multi type.
Wrapper for iterator of features from vector data provider or vector layer.
static Type singleType(Type type) SIP_HOLDGIL
Returns the single type for a WKB type.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
void errorOccurred(Qgis::VectorExportResult error, const QString &errorMessage)
Emitted when an error occurs which prevented the layer being exported (or if the task is canceled).
void finished(bool result) override
If the task is managed by a QgsTaskManager, this will be called after the task has finished (whether ...
virtual bool isValid() const =0
Returns true if this is a valid layer.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
bool run() override
Performs the task's operation.
Abstract base class for long running background tasks. Tasks can be controlled directly,...