QGIS API Documentation  2.99.0-Master (c4aa4d0)
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 "qgsogrutils.h"
30 #include <ogr_api.h>
31 
32 class QgsSymbolLayer;
33 class QTextCodec;
34 class QgsFeatureIterator;
35 
43 class CORE_EXPORT QgsVectorFileWriter : public QgsFeatureSink
44 {
45  public:
47  {
48  Set,
50  Int,
51  Hidden
52  };
53 
57  class Option
58  {
59  public:
60  Option( const QString &docString, QgsVectorFileWriter::OptionType type )
61  : docString( docString )
62  , type( type ) {}
63  virtual ~Option() = default;
64 
65  QString docString;
67  };
68 
73  {
74  public:
75  SetOption( const QString &docString, const QStringList &values, const QString &defaultValue, bool allowNone = false )
76  : Option( docString, Set )
77  , values( values.toSet() )
78  , defaultValue( defaultValue )
79  , allowNone( allowNone )
80  {}
81 
82  QSet<QString> values;
83  QString defaultValue;
84  bool allowNone;
85  };
86 
91  {
92  public:
93  StringOption( const QString &docString, const QString &defaultValue = QString() )
94  : Option( docString, String )
95  , defaultValue( defaultValue )
96  {}
97 
98  QString defaultValue;
99  };
100 
105  {
106  public:
107  IntOption( const QString &docString, int defaultValue )
108  : Option( docString, Int )
109  , defaultValue( defaultValue )
110  {}
111 
113  };
114 
119  {
120  public:
121  BoolOption( const QString &docString, bool defaultValue )
122  : SetOption( docString, QStringList() << QStringLiteral( "YES" ) << QStringLiteral( "NO" ), defaultValue ? "YES" : "NO" )
123  {}
124  };
125 
130  {
131  public:
132  explicit HiddenOption( const QString &value )
133  : Option( QLatin1String( "" ), Hidden )
134  , mValue( value )
135  {}
136 
137  QString mValue;
138  };
139 
140  struct MetaData
141  {
143  MetaData() = default;
144 
145  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() )
146  : longName( longName )
147  , trLongName( trLongName )
148  , glob( glob )
149  , ext( ext )
150  , driverOptions( driverOptions )
151  , layerOptions( layerOptions )
152  , compulsoryEncoding( compulsoryEncoding )
153  {}
154 
155  QString longName;
156  QString trLongName;
157  QString glob;
158  QString ext;
159  QMap<QString, QgsVectorFileWriter::Option *> driverOptions;
160  QMap<QString, QgsVectorFileWriter::Option *> layerOptions;
163  };
164 
166  {
167  NoError = 0,
177  };
178 
180  {
181  NoSymbology = 0, //export only data
182  FeatureSymbology, //Keeps the number of features and export symbology per feature
183  SymbolLayerSymbology //Exports one feature per symbol layer (considering symbol levels)
184  };
185 
186 
192  {
193  SortRecommended = 1 << 1,
194  SkipNonSpatialFormats = 1 << 2,
195  };
196  Q_DECLARE_FLAGS( VectorFormatOptions, VectorFormatOption )
197 
198 
203  class CORE_EXPORT FieldValueConverter
204  {
205  public:
207  FieldValueConverter() = default;
208 
209  virtual ~FieldValueConverter() = default;
210 
216  virtual QgsField fieldDefinition( const QgsField &field );
217 
224  virtual QVariant convert( int fieldIdxInLayer, const QVariant &value );
225 
230  };
231 
236  {
238  CanAddNewLayer = 1 << 0,
239 
241  CanAppendToExistingLayer = 1 << 1,
242 
244  CanAddNewFieldsToExistingLayer = 1 << 2,
245 
247  CanDeleteLayer = 1 << 3
248  };
249 
253  Q_DECLARE_FLAGS( EditionCapabilities, EditionCapability )
254 
255 
260  {
263 
266 
269 
271  AppendToLayerAddFields
272  };
273 
297  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
298  const QString &fileName,
299  const QString &fileEncoding,
301  const QString &driverName = "GPKG",
302  bool onlySelected = false,
303  QString *errorMessage SIP_OUT = nullptr,
304  const QStringList &datasourceOptions = QStringList(),
305  const QStringList &layerOptions = QStringList(),
306  bool skipAttributeCreation = false,
307  QString *newFilename = nullptr,
309  double symbologyScale = 1.0,
310  const QgsRectangle *filterExtent = nullptr,
311  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
312  bool forceMulti = false,
313  bool includeZ = false,
314  const QgsAttributeList &attributes = QgsAttributeList(),
315  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
316  );
317 
343  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
344  const QString &fileName,
345  const QString &fileEncoding,
346  const QgsCoordinateTransform &ct,
347  const QString &driverName = "GPKG",
348  bool onlySelected = false,
349  QString *errorMessage SIP_OUT = nullptr,
350  const QStringList &datasourceOptions = QStringList(),
351  const QStringList &layerOptions = QStringList(),
352  bool skipAttributeCreation = false,
353  QString *newFilename = nullptr,
355  double symbologyScale = 1.0,
356  const QgsRectangle *filterExtent = nullptr,
357  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
358  bool forceMulti = false,
359  bool includeZ = false,
360  const QgsAttributeList &attributes = QgsAttributeList(),
361  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
362  );
363 
364 
370  class CORE_EXPORT SaveVectorOptions
371  {
372  public:
375 
376  virtual ~SaveVectorOptions() = default;
377 
379  QString driverName;
380 
382  QString layerName;
383 
385  QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile = CreateOrOverwriteFile;
386 
388  QString fileEncoding;
389 
394 
396  bool onlySelectedFeatures = false;
397 
399  QStringList datasourceOptions;
400 
402  QStringList layerOptions;
403 
405  bool skipAttributeCreation = false;
406 
409 
411  QgsVectorFileWriter::SymbologyExport symbologyExport = NoSymbology;
412 
414  double symbologyScale = 1.0;
415 
418 
422  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown;
423 
425  bool forceMulti = false;
426 
428  bool includeZ = false;
429 
436  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr;
437 
439  QgsFeedback *feedback = nullptr;
440  };
441 
451  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
452  const QString &fileName,
454  QString *newFilename = nullptr,
455  QString *errorMessage SIP_OUT = nullptr );
456 
458  QgsVectorFileWriter( const QString &vectorFileName,
459  const QString &fileEncoding,
460  const QgsFields &fields,
461  QgsWkbTypes::Type geometryType,
463  const QString &driverName = "GPKG",
464  const QStringList &datasourceOptions = QStringList(),
465  const QStringList &layerOptions = QStringList(),
466  QString *newFilename = nullptr,
468  );
469 
487  QgsVectorFileWriter( const QString &vectorFileName,
488  const QString &fileEncoding,
489  const QgsFields &fields,
490  QgsWkbTypes::Type geometryType,
491  const QgsCoordinateReferenceSystem &srs,
492  const QString &driverName,
493  const QStringList &datasourceOptions,
494  const QStringList &layerOptions,
495  QString *newFilename,
496  QgsVectorFileWriter::SymbologyExport symbologyExport,
497  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
498  const QString &layerName,
500  ) SIP_SKIP;
501 
503  QgsVectorFileWriter( const QgsVectorFileWriter &rh ) = delete;
505  QgsVectorFileWriter &operator=( const QgsVectorFileWriter &rh ) = delete;
506 
512  {
514  QString driverName;
515 
517  QString filterString;
518  };
519 
528  static QList< QgsVectorFileWriter::FilterFormatDetails > supportedFiltersAndFormats( VectorFormatOptions options = SortRecommended );
529 
539  static QStringList supportedFormatExtensions( VectorFormatOptions options = SortRecommended );
540 
548  static bool supportsFeatureStyles( const QString &driverName );
549 
555  {
557  QString longName;
558 
560  QString driverName;
561  };
562 
574  static QList< QgsVectorFileWriter::DriverDetails > ogrDriverList( VectorFormatOptions options = SortRecommended );
575 
582  static QString driverForExtension( const QString &extension );
583 
590  static QString fileFilterString( VectorFormatOptions options = SortRecommended );
591 
593  static QString filterForDriver( const QString &driverName );
594 
596  static QString convertCodecNameForEncodingOption( const QString &codecName );
597 
600 
602  QString errorMessage();
603 
604  bool addFeature( QgsFeature &feature, QgsFeatureSink::Flags flags = nullptr ) override;
605  bool addFeatures( QgsFeatureList &features, QgsFeatureSink::Flags flags = nullptr ) override;
606 
611  bool addFeatureWithStyle( QgsFeature &feature, QgsFeatureRenderer *renderer, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters );
612 
614  QMap<int, int> attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; } SIP_SKIP
615 
617  ~QgsVectorFileWriter() override;
618 
624  static bool deleteShapeFile( const QString &fileName );
625 
626  QgsVectorFileWriter::SymbologyExport symbologyExport() const { return mSymbologyExport; }
627  void setSymbologyExport( QgsVectorFileWriter::SymbologyExport symExport ) { mSymbologyExport = symExport; }
628 
635  double symbologyScale() const { return mSymbologyScale; }
636 
643  void setSymbologyScale( double scale );
644 
645  static bool driverMetadata( const QString &driverName, MetaData &driverMetadata );
646 
653  static QStringList defaultDatasetOptions( const QString &driverName );
654 
661  static QStringList defaultLayerOptions( const QString &driverName );
662 
669  static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type ) SIP_SKIP;
670 
675  static QgsVectorFileWriter::EditionCapabilities editionCapabilities( const QString &datasetName );
676 
681  static bool targetLayerExists( const QString &datasetName,
682  const QString &layerName );
683 
688  static bool areThereNewFieldsToCreate( const QString &datasetName,
689  const QString &layerName,
690  QgsVectorLayer *layer,
691  const QgsAttributeList &attributes );
692 
693  protected:
695  OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType ) SIP_SKIP;
696 
698  OGRLayerH mLayer = nullptr;
699  OGRSpatialReferenceH mOgrRef = nullptr;
700 
702 
705  QString mErrorMessage;
706 
707  QTextCodec *mCodec = nullptr;
708 
711 
713  QMap<int, int> mAttrIdxToOgrIdx;
714 
716 
717  QMap< QgsSymbolLayer *, QString > mSymbolLayerTable;
718 
721 
722  QString mOgrDriverName;
723 
725  FieldValueConverter *mFieldValueConverter = nullptr;
726 
727  private:
728 #ifdef SIP_RUN
730 #endif
731 
732  void init( QString vectorFileName, QString fileEncoding, const QgsFields &fields,
734  const QString &driverName, QStringList datasourceOptions,
735  QStringList layerOptions, QString *newFilename,
736  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
737  const QString &layerName,
739  void resetMap( const QgsAttributeList &attributes );
740 
741  std::unique_ptr< QgsFeatureRenderer > mRenderer;
742  QgsRenderContext mRenderContext;
743 
744  bool mUsingTransaction = false;
745 
746  static QMap<QString, MetaData> initMetaData();
747  void createSymbolLayerTable( QgsVectorLayer *vl, const QgsCoordinateTransform &ct, OGRDataSourceH ds );
748  gdal::ogr_feature_unique_ptr createFeature( const QgsFeature &feature );
749  bool writeFeature( OGRLayerH layer, OGRFeatureH feature );
750 
752  QgsVectorFileWriter::WriterError exportFeaturesSymbolLevels( QgsVectorLayer *layer, QgsFeatureIterator &fit, const QgsCoordinateTransform &ct, QString *errorMessage = nullptr );
753  double mmScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
754  double mapUnitScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
755 
756  void startRender( QgsVectorLayer *vl );
757  void stopRender();
758  std::unique_ptr< QgsFeatureRenderer > createSymbologyRenderer( QgsVectorLayer *vl ) const;
760  void addRendererAttributes( QgsVectorLayer *vl, QgsAttributeList &attList );
761  static QMap<QString, MetaData> sDriverMetadata;
762 
764  static QStringList concatenateOptions( const QMap<QString, Option *> &options );
765 };
766 
767 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities )
768 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::VectorFormatOptions )
769 
770 // clazy:excludeall=qstring-allocations
771 
772 #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
Details of available driver formats.
void setSymbologyExport(QgsVectorFileWriter::SymbologyExport symExport)
QMap< int, int > attrIdxToOgrIdx()
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: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
gdal::ogr_datasource_unique_ptr mDS
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
QString driverName
Unique driver name.
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
std::unique_ptr< void, OGRDataSourceDeleter > ogr_datasource_unique_ptr
Scoped OGR data source.
Definition: qgsogrutils.h:114
Class for doing transforms between two map coordinate systems.
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.
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
QString longName
Descriptive, user friendly name for the driver.
void * OGRSpatialReferenceH
std::unique_ptr< void, OGRFeatureDeleter > ogr_feature_unique_ptr
Scoped OGR feature.
Definition: qgsogrutils.h:129