QGIS API Documentation  2.99.0-Master (25b0421)
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 "qgsvectorlayer.h"
29 #include <ogr_api.h>
30 
31 #include <QPair>
32 
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( QLatin1String( "" ), Hidden )
136  , mValue( value )
137  {}
138 
139  QString mValue;
140  };
141 
142  struct MetaData
143  {
145  {}
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 
193  class CORE_EXPORT FieldValueConverter
194  {
195  public:
197  FieldValueConverter() = default;
198 
199  virtual ~FieldValueConverter() = default;
200 
206  virtual QgsField fieldDefinition( const QgsField &field );
207 
214  virtual QVariant convert( int fieldIdxInLayer, const QVariant &value );
215 
220  };
221 
226  {
228  CanAddNewLayer = 1 << 0,
229 
231  CanAppendToExistingLayer = 1 << 1,
232 
234  CanAddNewFieldsToExistingLayer = 1 << 2,
235 
237  CanDeleteLayer = 1 << 3
238  };
239 
243  Q_DECLARE_FLAGS( EditionCapabilities, EditionCapability )
244 
245 
250  {
253 
256 
259 
261  AppendToLayerAddFields
262  };
263 
287  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
288  const QString &fileName,
289  const QString &fileEncoding,
291  const QString &driverName = "GPKG",
292  bool onlySelected = false,
293  QString *errorMessage SIP_OUT = nullptr,
294  const QStringList &datasourceOptions = QStringList(),
295  const QStringList &layerOptions = QStringList(),
296  bool skipAttributeCreation = false,
297  QString *newFilename = nullptr,
299  double symbologyScale = 1.0,
300  const QgsRectangle *filterExtent = nullptr,
301  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
302  bool forceMulti = false,
303  bool includeZ = false,
304  const QgsAttributeList &attributes = QgsAttributeList(),
305  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
306  );
307 
333  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
334  const QString &fileName,
335  const QString &fileEncoding,
336  const QgsCoordinateTransform &ct,
337  const QString &driverName = "GPKG",
338  bool onlySelected = false,
339  QString *errorMessage SIP_OUT = nullptr,
340  const QStringList &datasourceOptions = QStringList(),
341  const QStringList &layerOptions = QStringList(),
342  bool skipAttributeCreation = false,
343  QString *newFilename = nullptr,
345  double symbologyScale = 1.0,
346  const QgsRectangle *filterExtent = nullptr,
347  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
348  bool forceMulti = false,
349  bool includeZ = false,
350  const QgsAttributeList &attributes = QgsAttributeList(),
351  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
352  );
353 
354 
360  class CORE_EXPORT SaveVectorOptions
361  {
362  public:
365 
366  virtual ~SaveVectorOptions() = default;
367 
369  QString driverName;
370 
372  QString layerName;
373 
375  QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile = CreateOrOverwriteFile;
376 
378  QString fileEncoding;
379 
384 
386  bool onlySelectedFeatures = false;
387 
389  QStringList datasourceOptions;
390 
392  QStringList layerOptions;
393 
395  bool skipAttributeCreation = false;
396 
399 
401  QgsVectorFileWriter::SymbologyExport symbologyExport = NoSymbology;
402 
404  double symbologyScale = 1.0;
405 
408 
412  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown;
413 
415  bool forceMulti = false;
416 
418  bool includeZ = false;
419 
426  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr;
427 
429  QgsFeedback *feedback = nullptr;
430  };
431 
441  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
442  const QString &fileName,
444  QString *newFilename = nullptr,
445  QString *errorMessage SIP_OUT = nullptr );
446 
448  QgsVectorFileWriter( const QString &vectorFileName,
449  const QString &fileEncoding,
450  const QgsFields &fields,
451  QgsWkbTypes::Type geometryType,
453  const QString &driverName = "GPKG",
454  const QStringList &datasourceOptions = QStringList(),
455  const QStringList &layerOptions = QStringList(),
456  QString *newFilename = nullptr,
458  );
459 
477  QgsVectorFileWriter( const QString &vectorFileName,
478  const QString &fileEncoding,
479  const QgsFields &fields,
480  QgsWkbTypes::Type geometryType,
481  const QgsCoordinateReferenceSystem &srs,
482  const QString &driverName,
483  const QStringList &datasourceOptions,
484  const QStringList &layerOptions,
485  QString *newFilename,
486  QgsVectorFileWriter::SymbologyExport symbologyExport,
487  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
488  const QString &layerName,
490  ) SIP_SKIP;
491 
493  QgsVectorFileWriter( const QgsVectorFileWriter &rh ) = delete;
495  QgsVectorFileWriter &operator=( const QgsVectorFileWriter &rh ) = delete;
496 
501  static QMap< QString, QString> supportedFiltersAndFormats();
502 
508  static QStringList supportedFormatExtensions();
509 
515  static QMap< QString, QString> ogrDriverList();
516 
523  static QString driverForExtension( const QString &extension );
524 
526  static QString fileFilterString();
527 
529  static QString filterForDriver( const QString &driverName );
530 
532  static QString convertCodecNameForEncodingOption( const QString &codecName );
533 
536 
538  QString errorMessage();
539 
540  bool addFeature( QgsFeature &feature, QgsFeatureSink::Flags flags = 0 ) override;
541  bool addFeatures( QgsFeatureList &features, QgsFeatureSink::Flags flags = 0 ) override;
542 
547  bool addFeatureWithStyle( QgsFeature &feature, QgsFeatureRenderer *renderer, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters );
548 
550  QMap<int, int> attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; } SIP_SKIP
551 
554 
560  static bool deleteShapeFile( const QString &fileName );
561 
562  QgsVectorFileWriter::SymbologyExport symbologyExport() const { return mSymbologyExport; }
563  void setSymbologyExport( QgsVectorFileWriter::SymbologyExport symExport ) { mSymbologyExport = symExport; }
564 
571  double symbologyScale() const { return mSymbologyScale; }
572 
579  void setSymbologyScale( double scale );
580 
581  static bool driverMetadata( const QString &driverName, MetaData &driverMetadata );
582 
589  static QStringList defaultDatasetOptions( const QString &driverName );
590 
597  static QStringList defaultLayerOptions( const QString &driverName );
598 
605  static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type ) SIP_SKIP;
606 
611  static QgsVectorFileWriter::EditionCapabilities editionCapabilities( const QString &datasetName );
612 
617  static bool targetLayerExists( const QString &datasetName,
618  const QString &layerName );
619 
624  static bool areThereNewFieldsToCreate( const QString &datasetName,
625  const QString &layerName,
626  QgsVectorLayer *layer,
627  const QgsAttributeList &attributes );
628 
629  protected:
631  OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType ) SIP_SKIP;
632 
633  OGRDataSourceH mDS = nullptr;
634  OGRLayerH mLayer = nullptr;
635  OGRSpatialReferenceH mOgrRef = nullptr;
636 
638 
641  QString mErrorMessage;
642 
643  QTextCodec *mCodec = nullptr;
644 
647 
649  QMap<int, int> mAttrIdxToOgrIdx;
650 
652 
653  QMap< QgsSymbolLayer *, QString > mSymbolLayerTable;
654 
657 
658  QString mOgrDriverName;
659 
661  FieldValueConverter *mFieldValueConverter = nullptr;
662 
663  private:
664 #ifdef SIP_RUN
666 #endif
667 
668  void init( QString vectorFileName, QString fileEncoding, const QgsFields &fields,
670  const QString &driverName, QStringList datasourceOptions,
671  QStringList layerOptions, QString *newFilename,
672  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
673  const QString &layerName,
675  void resetMap( const QgsAttributeList &attributes );
676 
677  QgsRenderContext mRenderContext;
678 
679  static QMap<QString, MetaData> initMetaData();
680  void createSymbolLayerTable( QgsVectorLayer *vl, const QgsCoordinateTransform &ct, OGRDataSourceH ds );
681  OGRFeatureH createFeature( const QgsFeature &feature );
682  bool writeFeature( OGRLayerH layer, OGRFeatureH feature );
683 
685  QgsVectorFileWriter::WriterError exportFeaturesSymbolLevels( QgsVectorLayer *layer, QgsFeatureIterator &fit, const QgsCoordinateTransform &ct, QString *errorMessage = nullptr );
686  double mmScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
687  double mapUnitScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
688 
689  void startRender( QgsVectorLayer *vl );
690  void stopRender( QgsVectorLayer *vl );
691  QgsFeatureRenderer *symbologyRenderer( QgsVectorLayer *vl ) const;
693  void addRendererAttributes( QgsVectorLayer *vl, QgsAttributeList &attList );
694  static QMap<QString, MetaData> sDriverMetadata;
695 
697  static QStringList concatenateOptions( const QMap<QString, Option *> &options );
698 };
699 
700 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities )
701 
702 // clazy:excludeall=qstring-allocations
703 
704 #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:39
QgsVectorFileWriter::OptionType type
void setSymbologyExport(QgsVectorFileWriter::SymbologyExport symExport)
QMap< int, int > attrIdxToOgrIdx()
WriterError mError
Contains error value if construction was not successful.
QList< QgsFeature > QgsFeatureList
Definition: qgsfeature.h:549
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
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:62
QgsVectorFileWriter::SymbologyExport symbologyExport() const
Base class for feedback objects to be used for cancelation 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:67
#define SIP_SKIP
Definition: qgis_sip.h:119
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:43
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.
QgsCoordinateTransform ct
Transform to reproject exported geometries with, or invalid transform for no transformation.
Interface to convert raw field values to their user-friendly value.
QList< int > QgsAttributeList
Definition: qgsfield.h:27
QString layerName
Layer name. If let empty, it will be derived from the filename.
Represents a vector layer which manages a vector based data sets.
Writing was interrupted by manual cancelation.
QgsWkbTypes::Type mWkbType
Geometry type which is being used.
RenderUnit
Rendering size units.
Definition: qgsunittypes.h:100
void * OGRSpatialReferenceH