QGIS API Documentation
3.14.0-Pi (9f7028fd23)
|
Go to the documentation of this file.
35 #include <QProgressDialog>
37 #define FEATURE_BUFFER_SIZE 200
45 QMap<int, int> *oldToNewAttrIdx,
46 QString *errorMessage,
47 const QMap<QString, QVariant> *options
52 const QString &providerKey,
57 const QMap<QString, QVariant> &options,
58 QgsFeatureSink::SinkFlags sinkFlags )
60 , mAttributeCount( -1 )
68 mError = pReg->
createEmptyLayer( providerKey, uri, fields, geometryType,
crs, overwrite, mOldToNewAttrIdx,
69 errMsg, !options.isEmpty() ? &options :
nullptr );
72 mErrorMessage = errMsg;
76 const auto constMOldToNewAttrIdx = mOldToNewAttrIdx;
77 for (
int idx : constMOldToNewAttrIdx )
79 if ( idx > mAttributeCount )
80 mAttributeCount = idx;
87 QString uriUpdated( uri );
89 if ( providerKey == QLatin1String(
"ogr" ) )
92 if ( options.contains( QStringLiteral(
"layerName" ) ) )
93 layerName = options.value( QStringLiteral(
"layerName" ) ).toString();
94 if ( !layerName.isEmpty() )
96 uriUpdated += QLatin1String(
"|layername=" );
97 uriUpdated += layerName;
106 mErrorMessage = QObject::tr(
"Loading of layer failed" );
108 delete vectorProvider;
118 if ( sinkFlags.testFlag( QgsFeatureSink::SinkFlag::RegeneratePrimaryKey ) && path.endsWith( QLatin1String(
".gpkg" ), Qt::CaseInsensitive ) )
120 QString fidName = options.value( QStringLiteral(
"FID" ), QStringLiteral(
"FID" ) ).toString();
124 mOldToNewAttrIdx.remove( fidIdx );
128 mProvider = vectorProvider;
145 return mErrorMessage;
150 QgsFeatureList::iterator fIt = features.begin();
152 for ( ; fIt != features.end(); ++fIt )
169 for (
int i = 0; i < attrs.count(); ++i )
173 int dstIdx = mOldToNewAttrIdx.value( i, -1 );
177 QgsDebugMsgLevel( QStringLiteral(
"moving field from pos %1 to %2" ).arg( i ).arg( dstIdx ), 3 );
181 mFeatureBuffer.append( newFeat );
193 if ( mFeatureBuffer.count() <= 0 )
198 QStringList errors = mProvider->
errors();
201 mErrorMessage = QObject::tr(
"Creation error for features from #%1 to #%2. Provider errors was: \n%3" )
202 .arg( mFeatureBuffer.first().id() )
203 .arg( mFeatureBuffer.last().id() )
204 .arg( errors.join( QStringLiteral(
"\n" ) ) );
207 mErrorCount += mFeatureBuffer.count();
209 mFeatureBuffer.clear();
214 mFeatureBuffer.clear();
218 bool QgsVectorLayerExporter::createSpatialIndex()
233 const QString &providerKey,
236 QString *errorMessage,
237 const QMap<QString, QVariant> &options,
242 bool shallTransform =
false;
251 shallTransform =
true;
256 outputCRS = layer->
crs();
260 bool overwrite =
false;
261 bool forceSinglePartGeom =
false;
262 QMap<QString, QVariant> providerOptions = options;
263 if ( !options.isEmpty() )
265 overwrite = providerOptions.take( QStringLiteral(
"overwrite" ) ).toBool();
266 forceSinglePartGeom = providerOptions.take( QStringLiteral(
"forceSinglePartGeometryType" ) ).toBool();
274 if ( layer->
providerType() == QLatin1String(
"ogr" ) && layer->
storageType() == QLatin1String(
"ESRI Shapefile" ) )
277 for (
int fldIdx = 0; fldIdx < fields.
count(); ++fldIdx )
279 fields.
rename( fldIdx, fields.
at( fldIdx ).
name().toLower() );
283 bool convertGeometryToSinglePart =
false;
287 convertGeometryToSinglePart =
true;
326 shallTransform =
false;
336 bool canceled =
false;
346 *
errorMessage +=
'\n' + QObject::tr(
"Import was canceled at %1 of %2" ).arg( n ).arg( approxTotal );
360 if ( shallTransform )
375 QString msg = QObject::tr(
"Failed to transform a point while drawing a feature with ID '%1'. Writing stopped. (Exception: %2)" )
376 .arg( fet.
id() ).arg( e.
what() );
391 const QgsGeometryCollection *
c = qgsgeometry_cast<const QgsGeometryCollection *>( singlePartGeometry.constGet() );
392 if ( (
c &&
c->partCount() > 1 ) || ! singlePartGeometry.convertToSingleType() )
395 QString msg = QObject::tr(
"Failed to transform a feature with ID '%1' to single part. Writing stopped." )
416 feedback->
setProgress( 100.0 *
static_cast< double >( n ) / approxTotal );
431 if ( !writer->createSpatialIndex() )
445 *
errorMessage +=
'\n' + QObject::tr(
"Only %1 of %2 features written." ).arg( n - errors ).arg( n );
455 else if ( errors > 0 )
467 :
QgsTask( tr(
"Exporting %1" ).arg( layer->name() ),
QgsTask::CanCancel )
469 , mOwnsLayer( ownsLayer )
471 , mDestProviderKey( providerKey )
472 , mDestCrs( destinationCrs )
473 , mOptions( options )
482 std::unique_ptr< QgsVectorLayerExporterTask > newTask(
new QgsVectorLayerExporterTask( layer, uri, providerKey, destinationCrs, options ) );
483 newTask->mOwnsLayer =
true;
484 return newTask.release();
489 mOwnedFeedback->cancel();
502 mLayer.data(), mDestUri, mDestProviderKey, mDestCrs,
false, &mErrorMessage,
503 mOptions, mOwnedFeedback.get() );
@ 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.
QgsDataProvider * createProvider(const QString &providerKey, const QString &dataSource, const QgsDataProvider::ProviderOptions &options=QgsDataProvider::ProviderOptions())
Creates a new instance of a provider.
OperationResult transform(const QgsCoordinateTransform &ct, QgsCoordinateTransform::TransformDirection direction=QgsCoordinateTransform::ForwardTransform, bool transformZ=false) SIP_THROW(QgsCsException)
Transforms this geometry as described by the coordinate transform ct.
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.
Setting options for creating vector data providers.
void errorOccurred(int error, const QString &errorMessage)
Emitted when an error occurs which prevented the layer being exported (or if the task is canceled).
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.
static Type singleType(Type type)
Returns the single type for a WKB type.
#define QgsDebugMsgLevel(str, level)
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
@ 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.
static bool isMultiType(Type type)
Returns true if the WKB type is a multi type.
int count() const
Returns number of items.
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.
@ ErrFeatureWriteFailed
An error occurred while writing a feature to the destination.
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.
long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
@ NoError
No errors were encountered.
QString providerType() const
Returns the provider type (provider key) for this layer.
virtual void cancel()
Notifies the task that it should terminate.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
QgsVectorLayerExporter::ExportError 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.
QStringList errors() const
Gets recorded errors.
virtual QgsVectorDataProvider::Capabilities capabilities() const
Returns flags containing the supported capabilities.
QgsVectorLayerExporter::ExportError 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)
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
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
@ ErrInvalidLayer
Could not access newly created destination layer.
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.
@ ErrUserCanceled
User canceled the export.
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets 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.
static ExportError 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.
#define FEATURE_BUFFER_SIZE
void clearErrors()
Clear recorded errors.
QString errorMessage() const
Returns any error message encountered during the export.
bool isCanceled() const
Tells whether the operation has been canceled already.
bool setAttribute(int field, const QVariant &attr)
Set 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.
QgsCoordinateTransformContext transformContext() const
Returns the layer data provider coordinate transform context or a default transform context if the la...
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
bool hasGeometry() const
Returns true if the feature has an associated geometry.
ExportError errorCode() const
Returns any encountered error code, or false if no error was encountered.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
QString storageType() const
Returns the permanent storage type for this layer as a friendly name.
bool rename(int fieldIdx, const QString &name)
Renames a name of field.
@ ErrProjection
An error occurred while reprojecting features to destination CRS.
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
Gets field at particular index (must be in range 0..N-1)
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 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,...