QGIS API Documentation  3.0.2-Girona (307d082)
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 "qgsrenderer.h"
31 #include "qgsgeometryengine.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( QLatin1String( "" ), 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 
299  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
300  const QString &fileName,
301  const QString &fileEncoding,
303  const QString &driverName = "GPKG",
304  bool onlySelected = false,
305  QString *errorMessage SIP_OUT = nullptr,
306  const QStringList &datasourceOptions = QStringList(),
307  const QStringList &layerOptions = QStringList(),
308  bool skipAttributeCreation = false,
309  QString *newFilename = nullptr,
311  double symbologyScale = 1.0,
312  const QgsRectangle *filterExtent = nullptr,
313  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
314  bool forceMulti = false,
315  bool includeZ = false,
316  const QgsAttributeList &attributes = QgsAttributeList(),
317  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
318  );
319 
345  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
346  const QString &fileName,
347  const QString &fileEncoding,
348  const QgsCoordinateTransform &ct,
349  const QString &driverName = "GPKG",
350  bool onlySelected = false,
351  QString *errorMessage SIP_OUT = nullptr,
352  const QStringList &datasourceOptions = QStringList(),
353  const QStringList &layerOptions = QStringList(),
354  bool skipAttributeCreation = false,
355  QString *newFilename = nullptr,
357  double symbologyScale = 1.0,
358  const QgsRectangle *filterExtent = nullptr,
359  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown,
360  bool forceMulti = false,
361  bool includeZ = false,
362  const QgsAttributeList &attributes = QgsAttributeList(),
363  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr
364  );
365 
366 
372  class CORE_EXPORT SaveVectorOptions
373  {
374  public:
377 
378  virtual ~SaveVectorOptions() = default;
379 
381  QString driverName;
382 
384  QString layerName;
385 
387  QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile = CreateOrOverwriteFile;
388 
390  QString fileEncoding;
391 
396 
398  bool onlySelectedFeatures = false;
399 
401  QStringList datasourceOptions;
402 
404  QStringList layerOptions;
405 
407  bool skipAttributeCreation = false;
408 
411 
413  QgsVectorFileWriter::SymbologyExport symbologyExport = NoSymbology;
414 
416  double symbologyScale = 1.0;
417 
420 
424  QgsWkbTypes::Type overrideGeometryType = QgsWkbTypes::Unknown;
425 
427  bool forceMulti = false;
428 
430  bool includeZ = false;
431 
438  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter = nullptr;
439 
441  QgsFeedback *feedback = nullptr;
442  };
443 
453  static QgsVectorFileWriter::WriterError writeAsVectorFormat( QgsVectorLayer *layer,
454  const QString &fileName,
456  QString *newFilename = nullptr,
457  QString *errorMessage SIP_OUT = nullptr );
458 
460  QgsVectorFileWriter( const QString &vectorFileName,
461  const QString &fileEncoding,
462  const QgsFields &fields,
463  QgsWkbTypes::Type geometryType,
465  const QString &driverName = "GPKG",
466  const QStringList &datasourceOptions = QStringList(),
467  const QStringList &layerOptions = QStringList(),
468  QString *newFilename = nullptr,
470  );
471 
489  QgsVectorFileWriter( const QString &vectorFileName,
490  const QString &fileEncoding,
491  const QgsFields &fields,
492  QgsWkbTypes::Type geometryType,
493  const QgsCoordinateReferenceSystem &srs,
494  const QString &driverName,
495  const QStringList &datasourceOptions,
496  const QStringList &layerOptions,
497  QString *newFilename,
498  QgsVectorFileWriter::SymbologyExport symbologyExport,
499  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
500  const QString &layerName,
502  ) SIP_SKIP;
503 
505  QgsVectorFileWriter( const QgsVectorFileWriter &rh ) = delete;
507  QgsVectorFileWriter &operator=( const QgsVectorFileWriter &rh ) = delete;
508 
514  {
516  QString driverName;
517 
519  QString filterString;
520  };
521 
530  static QList< QgsVectorFileWriter::FilterFormatDetails > supportedFiltersAndFormats( VectorFormatOptions options = SortRecommended );
531 
541  static QStringList supportedFormatExtensions( VectorFormatOptions options = SortRecommended );
542 
550  static bool supportsFeatureStyles( const QString &driverName );
551 
557  {
559  QString longName;
560 
562  QString driverName;
563  };
564 
576  static QList< QgsVectorFileWriter::DriverDetails > ogrDriverList( VectorFormatOptions options = SortRecommended );
577 
584  static QString driverForExtension( const QString &extension );
585 
592  static QString fileFilterString( VectorFormatOptions options = SortRecommended );
593 
595  static QString filterForDriver( const QString &driverName );
596 
598  static QString convertCodecNameForEncodingOption( const QString &codecName );
599 
602 
604  QString errorMessage();
605 
606  bool addFeature( QgsFeature &feature, QgsFeatureSink::Flags flags = nullptr ) override;
607  bool addFeatures( QgsFeatureList &features, QgsFeatureSink::Flags flags = nullptr ) override;
608 
613  bool addFeatureWithStyle( QgsFeature &feature, QgsFeatureRenderer *renderer, QgsUnitTypes::DistanceUnit outputUnit = QgsUnitTypes::DistanceMeters );
614 
616  QMap<int, int> attrIdxToOgrIdx() { return mAttrIdxToOgrIdx; } SIP_SKIP
617 
619  ~QgsVectorFileWriter() override;
620 
626  static bool deleteShapeFile( const QString &fileName );
627 
628  QgsVectorFileWriter::SymbologyExport symbologyExport() const { return mSymbologyExport; }
629  void setSymbologyExport( QgsVectorFileWriter::SymbologyExport symExport ) { mSymbologyExport = symExport; }
630 
637  double symbologyScale() const { return mSymbologyScale; }
638 
645  void setSymbologyScale( double scale );
646 
647  static bool driverMetadata( const QString &driverName, MetaData &driverMetadata );
648 
655  static QStringList defaultDatasetOptions( const QString &driverName );
656 
663  static QStringList defaultLayerOptions( const QString &driverName );
664 
671  static OGRwkbGeometryType ogrTypeFromWkbType( QgsWkbTypes::Type type ) SIP_SKIP;
672 
677  static QgsVectorFileWriter::EditionCapabilities editionCapabilities( const QString &datasetName );
678 
683  static bool targetLayerExists( const QString &datasetName,
684  const QString &layerName );
685 
690  static bool areThereNewFieldsToCreate( const QString &datasetName,
691  const QString &layerName,
692  QgsVectorLayer *layer,
693  const QgsAttributeList &attributes );
694 
695  protected:
697  OGRGeometryH createEmptyGeometry( QgsWkbTypes::Type wkbType ) SIP_SKIP;
698 
700  OGRLayerH mLayer = nullptr;
701  OGRSpatialReferenceH mOgrRef = nullptr;
702 
704 
707  QString mErrorMessage;
708 
709  QTextCodec *mCodec = nullptr;
710 
713 
715  QMap<int, int> mAttrIdxToOgrIdx;
716 
718 
719  QMap< QgsSymbolLayer *, QString > mSymbolLayerTable;
720 
723 
724  QString mOgrDriverName;
725 
727  FieldValueConverter *mFieldValueConverter = nullptr;
728 
729  private:
730 #ifdef SIP_RUN
732 #endif
733 
734  struct PreparedWriterDetails
735  {
736  std::unique_ptr< QgsFeatureRenderer > renderer;
738  QgsWkbTypes::Type sourceWkbType = QgsWkbTypes::Unknown;
739  QgsFields sourceFields;
740  QString providerType;
741  long featureCount = 0;
742  QgsFeatureIds selectedFeatureIds;
743  QString dataSourceUri;
744  QString storageType;
745  QgsFeatureIterator geometryTypeScanIterator;
746  QgsExpressionContext expressionContext;
747  QSet< int > fieldsToConvertToInt;
748  QgsRenderContext renderContext;
749  bool shallTransform = false;
752  QgsAttributeList attributes;
753  QgsFields outputFields;
754  QgsFeatureIterator sourceFeatureIterator;
755  QgsGeometry filterRectGeometry;
756  std::unique_ptr< QgsGeometryEngine > filterRectEngine;
757  };
758 
763  static QgsVectorFileWriter::WriterError prepareWriteAsVectorFormat( QgsVectorLayer *layer,
765  PreparedWriterDetails &details );
766 
771  static QgsVectorFileWriter::WriterError writeAsVectorFormat( PreparedWriterDetails &details,
772  const QString &fileName,
774  QString *newFilename = nullptr,
775  QString *errorMessage SIP_OUT = nullptr );
776 
777  void init( QString vectorFileName, QString fileEncoding, const QgsFields &fields,
779  const QString &driverName, QStringList datasourceOptions,
780  QStringList layerOptions, QString *newFilename,
781  QgsVectorFileWriter::FieldValueConverter *fieldValueConverter,
782  const QString &layerName,
784  void resetMap( const QgsAttributeList &attributes );
785 
786  std::unique_ptr< QgsFeatureRenderer > mRenderer;
787  QgsRenderContext mRenderContext;
788 
789  bool mUsingTransaction = false;
790 
791  static QMap<QString, MetaData> initMetaData();
792  void createSymbolLayerTable( QgsVectorLayer *vl, const QgsCoordinateTransform &ct, OGRDataSourceH ds );
793  gdal::ogr_feature_unique_ptr createFeature( const QgsFeature &feature );
794  bool writeFeature( OGRLayerH layer, OGRFeatureH feature );
795 
797  QgsVectorFileWriter::WriterError exportFeaturesSymbolLevels( const PreparedWriterDetails &details, QgsFeatureIterator &fit, const QgsCoordinateTransform &ct, QString *errorMessage = nullptr );
798  double mmScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
799  double mapUnitScaleFactor( double scale, QgsUnitTypes::RenderUnit symbolUnits, QgsUnitTypes::DistanceUnit mapUnits );
800 
801  void startRender( QgsFeatureRenderer *sourceRenderer, const QgsFields &fields );
802  void stopRender();
803  std::unique_ptr< QgsFeatureRenderer > createSymbologyRenderer( QgsFeatureRenderer *sourceRenderer ) const;
805  static void addRendererAttributes( QgsFeatureRenderer *renderer, QgsRenderContext &context, const QgsFields &fields, QgsAttributeList &attList );
806  static QMap<QString, MetaData> sDriverMetadata;
807 
809  static QStringList concatenateOptions( const QMap<QString, Option *> &options );
810 
812 };
813 
814 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::EditionCapabilities )
815 Q_DECLARE_OPERATORS_FOR_FLAGS( QgsVectorFileWriter::VectorFormatOptions )
816 
817 // clazy:excludeall=qstring-allocations
818 
819 #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.
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeature.h:544
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
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: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.
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: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.
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.
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