QGIS API Documentation  3.8.0-Zanzibar (11aff65)
qgsvectorfilewriter.h
Go to the documentation of this file.
1 /***************************************************************************
2  qgsvectorfilewriter.h
3  generic vector file writer
4  -------------------
5  begin : Jun 6 2004
6  copyright : (C) 2004 by Tim Sutton
7  email : tim at linfiniti.com
8  ***************************************************************************/
9 
10 /***************************************************************************
11  * *
12  * This program is free software; you can redistribute it and/or modify *
13  * it under the terms of the GNU General Public License as published by *
14  * the Free Software Foundation; either version 2 of the License, or *
15  * (at your option) any later version. *
16  * *
17  ***************************************************************************/
18 
19 #ifndef QGSVECTORFILEWRITER_H
20 #define QGSVECTORFILEWRITER_H
21 
22 #include "qgis_core.h"
23 #include "qgis_sip.h"
24 #include "qgsfields.h"
25 #include "qgsfeedback.h"
26 #include "qgssymbol.h"
27 #include "qgstaskmanager.h"
28 #include "qgsogrutils.h"
29 #include "qgsrenderer.h"
30 #include "qgsgeometryengine.h"
31 #include "qgsfeaturesink.h"
32 #include <ogr_api.h>
33 
34 class QgsSymbolLayer;
35 class QTextCodec;
36 class QgsFeatureIterator;
37 
45 class CORE_EXPORT QgsVectorFileWriter : public QgsFeatureSink
46 {
47  public:
49  {
50  Set,
52  Int,
53  Hidden
54  };
55 
59  class Option
60  {
61  public:
62  Option( const QString &docString, QgsVectorFileWriter::OptionType type )
63  : docString( docString )
64  , type( type ) {}
65  virtual ~Option() = default;
66 
67  QString docString;
69  };
70 
75  {
76  public:
77  SetOption( const QString &docString, const QStringList &values, const QString &defaultValue, bool allowNone = false )
78  : Option( docString, Set )
79  , values( values.toSet() )
80  , defaultValue( defaultValue )
81  , allowNone( allowNone )
82  {}
83 
84  QSet<QString> values;
85  QString defaultValue;
86  bool allowNone;
87  };
88 
93  {
94  public:
95  StringOption( const QString &docString, const QString &defaultValue = QString() )
96  : Option( docString, String )
97  , defaultValue( defaultValue )
98  {}
99 
100  QString defaultValue;
101  };
102 
107  {
108  public:
109  IntOption( const QString &docString, int defaultValue )
110  : Option( docString, Int )
111  , defaultValue( defaultValue )
112  {}
113 
115  };
116 
121  {
122  public:
123  BoolOption( const QString &docString, bool defaultValue )
124  : SetOption( docString, QStringList() << QStringLiteral( "YES" ) << QStringLiteral( "NO" ), defaultValue ? "YES" : "NO" )
125  {}
126  };
127 
132  {
133  public:
134  explicit HiddenOption( const QString &value )
135  : Option( QString(), Hidden )
136  , mValue( value )
137  {}
138 
139  QString mValue;
140  };
141 
142  struct MetaData
143  {
145  MetaData() = default;
146 
147  MetaData( const QString &longName, const QString &trLongName, const QString &glob, const QString &ext, const QMap<QString, QgsVectorFileWriter::Option *> &driverOptions, const QMap<QString, QgsVectorFileWriter::Option *> &layerOptions, const QString &compulsoryEncoding = QString() )
148  : longName( longName )
149  , trLongName( trLongName )
150  , glob( glob )
151  , ext( ext )
152  , driverOptions( driverOptions )
153  , layerOptions( layerOptions )
154  , compulsoryEncoding( compulsoryEncoding )
155  {}
156 
157  QString longName;
158  QString trLongName;
159  QString glob;
160  QString ext;
161  QMap<QString, QgsVectorFileWriter::Option *> driverOptions;
162  QMap<QString, QgsVectorFileWriter::Option *> layerOptions;
165  };
166 
168  {
169  NoError = 0,
179  };
180 
182  {
183  NoSymbology = 0, //export only data
184  FeatureSymbology, //Keeps the number of features and export symbology per feature
185  SymbolLayerSymbology //Exports one feature per symbol layer (considering symbol levels)
186  };
187 
188 
194  {
195  SortRecommended = 1 << 1,
196  SkipNonSpatialFormats = 1 << 2,
197  };
198  Q_DECLARE_FLAGS( VectorFormatOptions, VectorFormatOption )
199 
200 
205  class CORE_EXPORT FieldValueConverter
206  {
207  public:
209  FieldValueConverter() = default;
210 
211  virtual ~FieldValueConverter() = default;
212 
218  virtual QgsField fieldDefinition( const QgsField &field );
219 
226  virtual QVariant convert( int fieldIdxInLayer, const QVariant &value );
227 
232  };
233 
238  {
240  CanAddNewLayer = 1 << 0,
241 
243  CanAppendToExistingLayer = 1 << 1,
244 
246  CanAddNewFieldsToExistingLayer = 1 << 2,
247 
249  CanDeleteLayer = 1 << 3
250  };
251 
255  Q_DECLARE_FLAGS( EditionCapabilities, EditionCapability )
256 
257 
262  {
265 
268 
271 
273  AppendToLayerAddFields
274  };
275 
276 #ifndef SIP_RUN
277 
302 #else
303 
327 #endif
328  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
329  const QString &fileName,
330  const QString &fileEncoding,
332  const QString &driverName = "GPKG",
333  bool onlySelected = false,
334  QString *errorMessage SIP_OUT = nullptr,
335  const QStringList &datasourceOptions = QStringList(),
336  const QStringList &layerOptions = QStringList(),
337  bool skipAttributeCreation = false,
338  QString *newFilename = nullptr,
340  double symbologyScale = 1.0,
341  const QgsRectangle *filterExtent = nullptr,
342  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
343  bool forceMulti = false,
344  bool includeZ = false,
345  const QgsAttributeList &attributes = QgsAttributeList(),
346  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
347 #ifndef SIP_RUN
348  , QString *newLayer = nullptr );
349 #else
350  );
351 #endif
352 
353 #ifndef SIP_RUN
354 
381 #else
382 
408 #endif
409  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
410  const QString &fileName,
411  const QString &fileEncoding,
412  const QgsCoordinateTransform &ct,
413  const QString &driverName = "GPKG",
414  bool onlySelected = false,
415  QString *errorMessage SIP_OUT = nullptr,
416  const QStringList &datasourceOptions = QStringList(),
417  const QStringList &layerOptions = QStringList(),
418  bool skipAttributeCreation = false,
419  QString *newFilename = nullptr,
421  double symbologyScale = 1.0,
422  const QgsRectangle *filterExtent = nullptr,
423  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
424  bool forceMulti = false,
425  bool includeZ = false,
426  const QgsAttributeList &attributes = QgsAttributeList(),
427  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
428 #ifndef SIP_RUN
429  , QString *newLayer = nullptr );
430 #else
431  );
432 #endif
433 
439  class CORE_EXPORT SaveVectorOptions
440  {
441  public:
444 
445  virtual ~SaveVectorOptions() = default;
446 
448  QString driverName;
449 
451  QString layerName;
452 
454  QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile = CreateOrOverwriteFile;
455 
457  QString fileEncoding;
458 
463 
465  bool onlySelectedFeatures = false;
466 
468  QStringList datasourceOptions;
469 
471  QStringList layerOptions;
472 
474  bool skipAttributeCreation = false;
475 
478 
480  QgsVectorFileWriter::SymbologyExport symbologyExport = NoSymbology;
481 
483  double symbologyScale = 1.0;
484 
487 
491  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown;
492 
494  bool forceMulti = false;
495 
497  bool includeZ = false;
498 
505  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr;
506 
508  QgsFeedback *feedback = nullptr;
509  };
510 
511 #ifndef SIP_RUN
512 
523 #else
524 
534 #endif
535  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
536  const QString &fileName,
538  QString *newFilename = nullptr,
539  QString *errorMessage SIP_OUT = nullptr
540 #ifndef SIP_RUN
541  , QString *newLayer = nullptr );
542 #else
543  );
544 #endif
545 
547  QgsVectorFileWriter( const QString &vectorFileName,
548  const QString &fileEncoding,
549  const QgsFields &fields,
550  QgsWkbTypes::Type geometryType,
552  const QString &driverName = "GPKG",
553  const QStringList &datasourceOptions = QStringList(),
554  const QStringList &layerOptions = QStringList(),
555  QString *newFilename = nullptr,
557  QgsFeatureSink::SinkFlags sinkFlags = nullptr
558 #ifndef SIP_RUN
559  , QString *newLayer = nullptr
560 #endif
561  );
562 
581  QgsVectorFileWriter( const QString &vectorFileName,
582  const QString &fileEncoding,
583  const QgsFields &fields,
584  QgsWkbTypes::Type geometryType,
585  const QgsCoordinateReferenceSystem &srs,
586  const QString &driverName,
587  const QStringList &datasourceOptions,
588  const QStringList &layerOptions,
589  QString *newFilename,
590  QgsVectorFileWriter::SymbologyExport symbologyExport,
591  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
592  const QString &layerName,
594  QString *newLayer = nullptr
595  ) SIP_SKIP;
596 
598  QgsVectorFileWriter( const QgsVectorFileWriter &rh ) = delete;
600  QgsVectorFileWriter &operator=( const QgsVectorFileWriter &rh ) = delete;
601 
607  {
609  QString driverName;
610 
612  QString filterString;
613 
618  QStringList globs;
619  };
620 
629  static QList< QgsVectorFileWriter::FilterFormatDetails > supportedFiltersAndFormats( VectorFormatOptions options = SortRecommended );
630 
640  static QStringList supportedFormatExtensions( VectorFormatOptions options = SortRecommended );
641 
649  static bool supportsFeatureStyles( const QString &driverName );
650 
656  {
658  QString longName;
659 
661  QString driverName;
662  };
663 
675  static QList< QgsVectorFileWriter::DriverDetails > ogrDriverList( VectorFormatOptions options = SortRecommended );
676 
683  static QString driverForExtension( const QString &extension );
684 
691  static QString fileFilterString( VectorFormatOptions options = SortRecommended );
692 
694  static QString filterForDriver( const QString &driverName );
695 
697  static QString convertCodecNameForEncodingOption( const QString &codecName );
698 
701 
703  QString errorMessage();
704 
705  bool addFeature( QgsFeature &feature, QgsFeatureSink::Flags flags = nullptr ) override;
706  bool addFeatures( QgsFeatureList &features, QgsFeatureSink::Flags flags = nullptr ) override;
707 
712  bool addFeatureWithStyle( QgsFeature &feature, QgsFeatureRenderer *renderer, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters );
713 
715  QMap<int, int> attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; } SIP_SKIP
716 
718  ~QgsVectorFileWriter() override;
719 
725  static bool deleteShapeFile( const QString &fileName );
726 
727  QgsVectorFileWriter::SymbologyExport symbologyExport() const { return mSymbologyExport; }
728  void setSymbologyExport( QgsVectorFileWriter::SymbologyExport symExport ) { mSymbologyExport = symExport; }
729 
736  double symbologyScale() const { return mSymbologyScale; }
737 
744  void setSymbologyScale( double scale );
745 
746  static bool driverMetadata( const QString &driverName, MetaData &driverMetadata );
747 
754  static QStringList defaultDatasetOptions( const QString &driverName );
755 
762  static QStringList defaultLayerOptions( const QString &driverName );
763 
770  static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type ) SIP_SKIP;
771 
776  static QgsVectorFileWriter::EditionCapabilities editionCapabilities( const QString &datasetName );
777 
782  static bool targetLayerExists( const QString &datasetName,
783  const QString &layerName );
784 
789  static bool areThereNewFieldsToCreate( const QString &datasetName,
790  const QString &layerName,
791  QgsVectorLayer *layer,
792  const QgsAttributeList &attributes );
793 
794  protected:
796  OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType ) SIP_SKIP;
797 
799  OGRLayerH mLayer = nullptr;
800  OGRSpatialReferenceH mOgrRef = nullptr;
801 
803 
806  QString mErrorMessage;
807 
808  QTextCodec *mCodec = nullptr;
809 
812 
814  QMap<int, int> mAttrIdxToOgrIdx;
815 
817 
818  QMap< QgsSymbolLayer *, QString > mSymbolLayerTable;
819 
822 
823  QString mOgrDriverName;
824 
826  FieldValueConverter *mFieldValueConverter = nullptr;
827 
828  private:
829 #ifdef SIP_RUN
831 #endif
832 
833  struct PreparedWriterDetails
834  {
835  std::unique_ptr< QgsFeatureRenderer > renderer;
837  QgsWkbTypes::Type sourceWkbType = QgsWkbTypes::Unknown;
838  QgsFields sourceFields;
839  QString providerType;
840  long featureCount = 0;
841  QgsFeatureIds selectedFeatureIds;
842  QString dataSourceUri;
843  QString storageType;
844  QgsFeatureIterator geometryTypeScanIterator;
845  QgsExpressionContext expressionContext;
846  QSet< int > fieldsToConvertToInt;
847  QgsRenderContext renderContext;
848  bool shallTransform = false;
851  QgsAttributeList attributes;
852  QgsFields outputFields;
853  QgsFeatureIterator sourceFeatureIterator;
854  QgsGeometry filterRectGeometry;
855  std::unique_ptr< QgsGeometryEngine > filterRectEngine;
856  QVariantMap providerUriParams;
857  };
858 
863  static QgsVectorFileWriter::WriterError prepareWriteAsVectorFormat( QgsVectorLayer *layer,
865  PreparedWriterDetails &details );
866 
871  static QgsVectorFileWriter::WriterError writeAsVectorFormat( PreparedWriterDetails &details,
872  const QString &fileName,
874  QString *newFilename = nullptr,
875  QString *errorMessage SIP_OUT = nullptr,
876  QString *newLayer = nullptr );
877 
878  void init( QString vectorFileName, QString fileEncoding, const QgsFields &fields,
880  const QString &driverName, QStringList datasourceOptions,
881  QStringList layerOptions, QString *newFilename,
882  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
883  const QString &layerName,
884  QgsVectorFileWriter::ActionOnExistingFile action, QString *newLayer, QgsFeatureSink::SinkFlags sinkFlags );
885  void resetMap( const QgsAttributeList &attributes );
886 
887  std::unique_ptr< QgsFeatureRenderer > mRenderer;
888  QgsRenderContext mRenderContext;
889 
890  bool mUsingTransaction = false;
891  bool supportsStringList = false;
892 
893  void createSymbolLayerTable( QgsVectorLayer *vl, const QgsCoordinateTransform &ct, OGRDataSourceH ds );
894  gdal::ogr_feature_unique_ptr createFeature( const QgsFeature &feature );
895  bool writeFeature( OGRLayerH layer, OGRFeatureH feature );
896 
898  QgsVectorFileWriter::WriterError exportFeaturesSymbolLevels( const PreparedWriterDetails &details, QgsFeatureIterator &fit, const QgsCoordinateTransform &ct, QString *errorMessage = nullptr );
899  double mmScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
900  double mapUnitScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
901 
902  void startRender( QgsFeatureRenderer *sourceRenderer, const QgsFields &fields );
903  void stopRender();
904  std::unique_ptr< QgsFeatureRenderer > createSymbologyRenderer( QgsFeatureRenderer *sourceRenderer ) const;
906  static void addRendererAttributes( QgsFeatureRenderer *renderer, QgsRenderContext &context, const QgsFields &fields, QgsAttributeList &attList );
907  static QMap<QString, MetaData> sDriverMetadata;
908 
910  static QStringList concatenateOptions( const QMap<QString, Option *> &options );
911 
913  friend class TestQgsVectorFileWriter;
914 };
915 
916 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities )
917 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::VectorFormatOptions )
918 
919 // clazy:excludeall=qstring-allocations
920 
921 #endif
Append features to existing layer, but do not create new fields.
Wrapper for iterator of features from vector data provider or vector layer.
BoolOption(const QString &docString, bool defaultValue)
A rectangle specified with double values.
Definition: qgsrectangle.h:41
QgsVectorFileWriter::OptionType type
Details of available driver formats.
void setSymbologyExport(QgsVectorFileWriter::SymbologyExport symExport)
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:34
QMap< int, int > attrIdxToOgrIdx()
QStringList globs
Matching glob patterns for format, e.g.
WriterError mError
Contains error value if construction was not successful.
Details of available filters and formats.
QString filterString
Filter string for file picker dialogs.
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:571
SymbologyExport mSymbologyExport
QgsAttributeList attributes
Attributes to export (empty means all unless skipAttributeCreation is set)
An interface for objects which accept features via addFeature(s) methods.
QMap< QgsSymbolLayer *, QString > mSymbolLayerTable
Container of fields for a vector layer.
Definition: qgsfields.h:42
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:111
StringOption(const QString &docString, const QString &defaultValue=QString())
MetaData(const QString &longName, const QString &trLongName, const QString &glob, const QString &ext, const QMap< QString, QgsVectorFileWriter::Option *> &driverOptions, const QMap< QString, QgsVectorFileWriter::Option *> &layerOptions, const QString &compulsoryEncoding=QString())
QStringList layerOptions
List of OGR layer creation options.
A convenience class for writing vector files to disk.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:55
gdal::ogr_datasource_unique_ptr mDS
QgsVectorFileWriter::SymbologyExport symbologyExport() const
Base class for feedback objects to be used for cancellation of something running in a worker thread...
Definition: qgsfeedback.h:44
IntOption(const QString &docString, int defaultValue)
Options to pass to writeAsVectorFormat()
Option(const QString &docString, QgsVectorFileWriter::OptionType type)
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:68
std::unique_ptr< std::remove_pointer< OGRFeatureH >::type, OGRFeatureDeleter > ogr_feature_unique_ptr
Scoped OGR feature.
Definition: qgsogrutils.h:129
#define SIP_SKIP
Definition: qgis_sip.h:119
QString driverName
Unique driver name.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QStringList datasourceOptions
List of OGR data source creation options.
SetOption(const QString &docString, const QStringList &values, const QString &defaultValue, bool allowNone=false)
QMap< QString, QgsVectorFileWriter::Option * > layerOptions
ActionOnExistingFile
Combination of CanAddNewLayer, CanAppendToExistingLayer, CanAddNewFieldsToExistingLayer or CanDeleteL...
#define SIP_FACTORY
Definition: qgis_sip.h:69
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:48
QMap< int, int > mAttrIdxToOgrIdx
Map attribute indizes to OGR field indexes.
QgsRectangle filterExtent
If not empty, only features intersecting the extent will be saved.
double symbologyScale() const
Returns the reference scale for output.
DistanceUnit
Units of distance.
Definition: qgsunittypes.h:54
QString compulsoryEncoding
Some formats require a compulsory encoding, typically UTF-8. If no compulsory encoding, empty string.
Contains information about the context of a rendering operation.
EditionCapability
Edition capability flags.
#define SIP_OUT
Definition: qgis_sip.h:51
double mSymbologyScale
Scale for symbology export (e.g. for symbols units in map units)
This class represents a coordinate reference system (CRS).
QMap< QString, QgsVectorFileWriter::Option * > driverOptions
Class for doing transforms between two map coordinate systems.
const QgsCoordinateReferenceSystem & outputCrs
QgsCoordinateTransform ct
Transform to reproject exported geometries with, or invalid transform for no transformation.
VectorFormatOption
Options for sorting and filtering vector formats.
Interface to convert raw field values to their user-friendly value.
QgsTask task which performs a QgsVectorFileWriter layer saving operation as a background task...
QList< int > QgsAttributeList
Definition: qgsfield.h:27
QString layerName
Layer name. If let empty, it will be derived from the filename.
std::unique_ptr< std::remove_pointer< OGRDataSourceH >::type, OGRDataSourceDeleter > ogr_datasource_unique_ptr
Scoped OGR data source.
Definition: qgsogrutils.h:114
Represents a vector layer which manages a vector based data sets.
Writing was interrupted by manual cancellation.
QgsWkbTypes::Type mWkbType
Geometry type which is being used.
RenderUnit
Rendering size units.
Definition: qgsunittypes.h:111
QString longName
Descriptive, user friendly name for the driver.
void * OGRSpatialReferenceH