QGIS API Documentation  3.13.0-Master (b0e71a822e)
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( qgis::listToSet( values ) )
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 
303 #else
304 
329 #endif
330  Q_DECL_DEPRECATED static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
331  const QString &fileName,
332  const QString &fileEncoding,
334  const QString &driverName = "GPKG",
335  bool onlySelected = false,
336  QString *errorMessage SIP_OUT = nullptr,
337  const QStringList &datasourceOptions = QStringList(),
338  const QStringList &layerOptions = QStringList(),
339  bool skipAttributeCreation = false,
340  QString *newFilename = nullptr,
342  double symbologyScale = 1.0,
343  const QgsRectangle *filterExtent = nullptr,
344  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
345  bool forceMulti = false,
346  bool includeZ = false,
347  const QgsAttributeList &attributes = QgsAttributeList(),
348  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
349 #ifndef SIP_RUN
350  , QString *newLayer = nullptr );
351 #else
352  ) SIP_DEPRECATED;
353 #endif
354 
355 #ifndef SIP_RUN
356 
384 #else
385 
412 #endif
413  Q_DECL_DEPRECATED static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
414  const QString &fileName,
415  const QString &fileEncoding,
416  const QgsCoordinateTransform &ct,
417  const QString &driverName = "GPKG",
418  bool onlySelected = false,
419  QString *errorMessage SIP_OUT = nullptr,
420  const QStringList &datasourceOptions = QStringList(),
421  const QStringList &layerOptions = QStringList(),
422  bool skipAttributeCreation = false,
423  QString *newFilename = nullptr,
425  double symbologyScale = 1.0,
426  const QgsRectangle *filterExtent = nullptr,
427  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
428  bool forceMulti = false,
429  bool includeZ = false,
430  const QgsAttributeList &attributes = QgsAttributeList(),
431  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
432 #ifndef SIP_RUN
433  , QString *newLayer = nullptr );
434 #else
435  ) SIP_DEPRECATED;
436 #endif
437 
443  class CORE_EXPORT SaveVectorOptions
444  {
445  public:
448 
449  virtual ~SaveVectorOptions() = default;
450 
452  QString driverName;
453 
455  QString layerName;
456 
458  QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile = CreateOrOverwriteFile;
459 
461  QString fileEncoding;
462 
467 
469  bool onlySelectedFeatures = false;
470 
472  QStringList datasourceOptions;
473 
475  QStringList layerOptions;
476 
478  bool skipAttributeCreation = false;
479 
482 
484  QgsVectorFileWriter::SymbologyExport symbologyExport = NoSymbology;
485 
487  double symbologyScale = 1.0;
488 
491 
495  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown;
496 
498  bool forceMulti = false;
499 
501  bool includeZ = false;
502 
509  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr;
510 
512  QgsFeedback *feedback = nullptr;
513  };
514 
515 #ifndef SIP_RUN
516 
528 #else
529 
540 #endif
541  Q_DECL_DEPRECATED static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
542  const QString &fileName,
544  QString *newFilename = nullptr,
545  QString *errorMessage SIP_OUT = nullptr
546 #ifndef SIP_RUN
547  , QString *newLayer = nullptr );
548 #else
549  ) SIP_DEPRECATED;
550 #endif
551 
556  Q_DECL_DEPRECATED QgsVectorFileWriter( const QString &vectorFileName,
557  const QString &fileEncoding,
558  const QgsFields &fields,
559  QgsWkbTypes::Type geometryType,
561  const QString &driverName = "GPKG",
562  const QStringList &datasourceOptions = QStringList(),
563  const QStringList &layerOptions = QStringList(),
564  QString *newFilename = nullptr,
566  QgsFeatureSink::SinkFlags sinkFlags = nullptr
567 #ifndef SIP_RUN
568  , QString *newLayer = nullptr,
570 #endif
571  ) SIP_DEPRECATED;
572 
594  Q_DECL_DEPRECATED QgsVectorFileWriter( const QString &vectorFileName,
595  const QString &fileEncoding,
596  const QgsFields &fields,
597  QgsWkbTypes::Type geometryType,
598  const QgsCoordinateReferenceSystem &srs,
599  const QString &driverName,
600  const QStringList &datasourceOptions,
601  const QStringList &layerOptions,
602  QString *newFilename,
603  QgsVectorFileWriter::SymbologyExport symbologyExport,
604  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
605  const QString &layerName,
607  QString *newLayer = nullptr,
609  QgsFeatureSink::SinkFlags sinkFlags = nullptr
610  ) SIP_SKIP;
611 
613  QgsVectorFileWriter( const QgsVectorFileWriter &rh ) = delete;
615  QgsVectorFileWriter &operator=( const QgsVectorFileWriter &rh ) = delete;
616 
630  static QgsVectorFileWriter *create( const QString &fileName,
631  const QgsFields &fields,
632  QgsWkbTypes::Type geometryType,
633  const QgsCoordinateReferenceSystem &srs,
634  const QgsCoordinateTransformContext &transformContext,
635  const QgsVectorFileWriter::SaveVectorOptions &options,
636  QgsFeatureSink::SinkFlags sinkFlags = nullptr,
637  QString *newFilename = nullptr,
638  QString *newLayer = nullptr );
639 
652  static QgsVectorFileWriter::WriterError writeAsVectorFormatV2( QgsVectorLayer *layer,
653  const QString &fileName,
654  const QgsCoordinateTransformContext &transformContext,
655  const QgsVectorFileWriter::SaveVectorOptions &options,
656  QString *newFilename = nullptr,
657  QString *newLayer = nullptr,
658  QString *errorMessage SIP_OUT = nullptr );
659 
665  {
667  QString driverName;
668 
670  QString filterString;
671 
676  QStringList globs;
677  };
678 
687  static QList< QgsVectorFileWriter::FilterFormatDetails > supportedFiltersAndFormats( VectorFormatOptions options = SortRecommended );
688 
698  static QStringList supportedFormatExtensions( VectorFormatOptions options = SortRecommended );
699 
707  static bool supportsFeatureStyles( const QString &driverName );
708 
714  {
716  QString longName;
717 
719  QString driverName;
720  };
721 
733  static QList< QgsVectorFileWriter::DriverDetails > ogrDriverList( VectorFormatOptions options = SortRecommended );
734 
741  static QString driverForExtension( const QString &extension );
742 
749  static QString fileFilterString( VectorFormatOptions options = SortRecommended );
750 
752  static QString filterForDriver( const QString &driverName );
753 
755  static QString convertCodecNameForEncodingOption( const QString &codecName );
756 
759 
761  QString errorMessage();
762 
763  bool addFeature( QgsFeature &feature, QgsFeatureSink::Flags flags = nullptr ) override;
764  bool addFeatures( QgsFeatureList &features, QgsFeatureSink::Flags flags = nullptr ) override;
765 
770  bool addFeatureWithStyle( QgsFeature &feature, QgsFeatureRenderer *renderer, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters );
771 
773  QMap<int, int> attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; } SIP_SKIP
774 
776  ~QgsVectorFileWriter() override;
777 
783  static bool deleteShapeFile( const QString &fileName );
784 
785  QgsVectorFileWriter::SymbologyExport symbologyExport() const { return mSymbologyExport; }
786  void setSymbologyExport( QgsVectorFileWriter::SymbologyExport symExport ) { mSymbologyExport = symExport; }
787 
794  double symbologyScale() const { return mSymbologyScale; }
795 
802  void setSymbologyScale( double scale );
803 
804  static bool driverMetadata( const QString &driverName, MetaData &driverMetadata );
805 
812  static QStringList defaultDatasetOptions( const QString &driverName );
813 
820  static QStringList defaultLayerOptions( const QString &driverName );
821 
828  static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type ) SIP_SKIP;
829 
834  static QgsVectorFileWriter::EditionCapabilities editionCapabilities( const QString &datasetName );
835 
840  static bool targetLayerExists( const QString &datasetName,
841  const QString &layerName );
842 
847  static bool areThereNewFieldsToCreate( const QString &datasetName,
848  const QString &layerName,
849  QgsVectorLayer *layer,
850  const QgsAttributeList &attributes );
851 
852  protected:
854  OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType ) SIP_SKIP;
855 
857  OGRLayerH mLayer = nullptr;
858  OGRSpatialReferenceH mOgrRef = nullptr;
859 
861 
864  QString mErrorMessage;
865 
866  QTextCodec *mCodec = nullptr;
867 
870 
872  QMap<int, int> mAttrIdxToOgrIdx;
873 
875 
876  QMap< QgsSymbolLayer *, QString > mSymbolLayerTable;
877 
880 
881  QString mOgrDriverName;
882 
884  FieldValueConverter *mFieldValueConverter = nullptr;
885 
886  private:
887 #ifdef SIP_RUN
889 #endif
890 
891  struct PreparedWriterDetails
892  {
893  std::unique_ptr< QgsFeatureRenderer > renderer;
895  QgsWkbTypes::Type sourceWkbType = QgsWkbTypes::Unknown;
896  QgsFields sourceFields;
897  QString providerType;
898  long featureCount = 0;
899  QgsFeatureIds selectedFeatureIds;
900  QString dataSourceUri;
901  QString storageType;
902  QgsFeatureIterator geometryTypeScanIterator;
903  QgsExpressionContext expressionContext;
904  QSet< int > fieldsToConvertToInt;
905  QgsRenderContext renderContext;
906  bool shallTransform = false;
909  QgsAttributeList attributes;
910  QgsFields outputFields;
911  QgsFeatureIterator sourceFeatureIterator;
912  QgsGeometry filterRectGeometry;
913  std::unique_ptr< QgsGeometryEngine > filterRectEngine;
914  QVariantMap providerUriParams;
915  };
916 
921  static QgsVectorFileWriter::WriterError prepareWriteAsVectorFormat( QgsVectorLayer *layer,
923  PreparedWriterDetails &details );
924 
938  static QgsVectorFileWriter::WriterError writeAsVectorFormatV2( PreparedWriterDetails &details,
939  const QString &fileName,
940  const QgsCoordinateTransformContext &transformContext,
942  QString *newFilename = nullptr,
943  QString *newLayer = nullptr,
944  QString *errorMessage SIP_OUT = nullptr );
945 
951  Q_DECL_DEPRECATED static QgsVectorFileWriter::WriterError writeAsVectorFormat( PreparedWriterDetails &details,
952  const QString &fileName,
954  QString *newFilename = nullptr,
955  QString *errorMessage SIP_OUT = nullptr,
956  QString *newLayer = nullptr ) SIP_DEPRECATED;
957 
958  void init( QString vectorFileName, QString fileEncoding, const QgsFields &fields,
959  QgsWkbTypes::Type geometryType, QgsCoordinateReferenceSystem srs,
960  const QString &driverName, QStringList datasourceOptions,
961  QStringList layerOptions, QString *newFilename,
962  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
963  const QString &layerName,
964  QgsVectorFileWriter::ActionOnExistingFile action, QString *newLayer, QgsFeatureSink::SinkFlags sinkFlags,
965  const QgsCoordinateTransformContext &transformContext );
966  void resetMap( const QgsAttributeList &attributes );
967 
968  std::unique_ptr< QgsFeatureRenderer > mRenderer;
969  QgsRenderContext mRenderContext;
970 
971 
972  std::unique_ptr< QgsCoordinateTransform > mCoordinateTransform;
973 
974  bool mUsingTransaction = false;
975  bool supportsStringList = false;
976 
977  void createSymbolLayerTable( QgsVectorLayer *vl, const QgsCoordinateTransform &ct, OGRDataSourceH ds );
978  gdal::ogr_feature_unique_ptr createFeature( const QgsFeature &feature );
979  bool writeFeature( OGRLayerH layer, OGRFeatureH feature );
980 
982  QgsVectorFileWriter::WriterError exportFeaturesSymbolLevels( const PreparedWriterDetails &details, QgsFeatureIterator &fit, const QgsCoordinateTransform &ct, QString *errorMessage = nullptr );
983  double mmScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
984  double mapUnitScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
985 
986  void startRender( QgsFeatureRenderer *sourceRenderer, const QgsFields &fields );
987  void stopRender();
988  std::unique_ptr< QgsFeatureRenderer > createSymbologyRenderer( QgsFeatureRenderer *sourceRenderer ) const;
990  static void addRendererAttributes( QgsFeatureRenderer *renderer, QgsRenderContext &context, const QgsFields &fields, QgsAttributeList &attList );
991 
993  static QStringList concatenateOptions( const QMap<QString, Option *> &options );
994 
996  friend class TestQgsVectorFileWriter;
997 };
998 
999 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities )
1000 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::VectorFormatOptions )
1001 
1002 // clazy:excludeall=qstring-allocations
1003 
1004 #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
Handles storage of information regarding WKB types and their properties.
Definition: qgswkbtypes.h:40
SymbologyExport mSymbologyExport
QgsAttributeList attributes
Attributes to export (empty means all unless skipAttributeCreation is set)
Helper functions for various unit types.
Definition: qgsunittypes.h:38
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:122
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:43
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:126
QString driverName
Unique driver name.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
Definition: qgsgeos.h:79
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:76
Encapsulate a field in an attribute table or data source.
Definition: qgsfield.h:49
Contains information about the context in which a coordinate transform is executed.
#define SIP_DEPRECATED
Definition: qgis_sip.h:106
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:67
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:58
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:26
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.
QString longName
Descriptive, user friendly name for the driver.
void * OGRSpatialReferenceH