QGIS API Documentation 3.99.0-Master (e59a7c0ab9f)
qgsvectorfilewriter.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsvectorfilewriter.cpp
3 generic vector file writer
4 -------------------
5 begin : Sat Jun 16 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#include "qgsapplication.h"
20#include "qgsfields.h"
21
22#include "qgsgdalutils.h"
23#include "qgsfielddomain.h"
24#include "qgslogger.h"
25#include "qgsmaplayerutils.h"
26#include "qgsmessagelog.h"
28#include "qgsvectorfilewriter.h"
29#include "qgssettings.h"
30#include "qgssymbol.h"
31#include "qgssymbollayer.h"
32#include "qgslocalec.h"
33#include "qgsogrutils.h"
34#include "qgsvectorlayer.h"
35#include "qgsproviderregistry.h"
37#include "qgsreadwritelocker.h"
38
39#include <QFile>
40#include <QFileInfo>
41#include <QDir>
42#include <QTextCodec>
43#include <QTextStream>
44#include <QSet>
45#include <QMetaType>
46#include <QMutex>
47#include <QRegularExpression>
48#include <QJsonDocument>
49
50#include <cassert>
51#include <cstdlib> // size_t
52#include <limits> // std::numeric_limits
53
54#include <ogr_srs_api.h>
55#include <cpl_error.h>
56#include <cpl_conv.h>
57#include <cpl_string.h>
58#include <gdal.h>
59
64
65QVariant QgsVectorFileWriter::FieldValueConverter::convert( int /*fieldIdxInLayer*/, const QVariant &value )
66{
67 return value;
68}
69
74
75QgsVectorFileWriter::QgsVectorFileWriter( const QString &vectorFileName,
76 const QString &fileEncoding,
77 const QgsFields &fields,
78 Qgis::WkbType geometryType,
80 const QString &driverName,
81 const QStringList &datasourceOptions,
82 const QStringList &layerOptions,
83 QString *newFilename,
86 QString *newLayer,
87 const QgsCoordinateTransformContext &transformContext,
88 FieldNameSource fieldNameSource )
89 : mError( NoError )
90 , mWkbType( geometryType )
92 , mSymbologyScale( 1.0 )
93{
94 init( vectorFileName, fileEncoding, fields, geometryType,
95 srs, driverName, datasourceOptions, layerOptions, newFilename, nullptr,
96 QString(), CreateOrOverwriteFile, newLayer, sinkFlags, transformContext, fieldNameSource, nullptr );
97}
98
99QgsVectorFileWriter::QgsVectorFileWriter( const QString &vectorFileName,
100 const QString &fileEncoding,
101 const QgsFields &fields,
102 Qgis::WkbType geometryType,
104 const QString &driverName,
105 const QStringList &datasourceOptions,
106 const QStringList &layerOptions,
107 QString *newFilename,
108 Qgis::FeatureSymbologyExport symbologyExport,
109 FieldValueConverter *fieldValueConverter,
110 const QString &layerName,
112 QString *newLayer,
113 const QgsCoordinateTransformContext &transformContext,
115 FieldNameSource fieldNameSource,
116 bool includeConstraints,
117 bool setFieldDomains,
118 const QgsAbstractDatabaseProviderConnection *sourceDatabaseProviderConnection )
119 : mError( NoError )
120 , mWkbType( geometryType )
121 , mSymbologyExport( symbologyExport )
122 , mSymbologyScale( 1.0 )
123 , mIncludeConstraints( includeConstraints )
124 , mSetFieldDomains( setFieldDomains )
125{
126 init( vectorFileName, fileEncoding, fields, geometryType, srs, driverName,
127 datasourceOptions, layerOptions, newFilename, fieldValueConverter,
128 layerName, action, newLayer, sinkFlags, transformContext, fieldNameSource, sourceDatabaseProviderConnection );
129}
130
132 const QString &fileName,
133 const QgsFields &fields,
134 Qgis::WkbType geometryType,
136 const QgsCoordinateTransformContext &transformContext,
139 QString *newFilename,
140 QString *newLayer
141)
142{
144 return new QgsVectorFileWriter( fileName, options.fileEncoding, fields, geometryType, srs,
145 options.driverName, options.datasourceOptions, options.layerOptions,
146 newFilename, options.symbologyExport, options.fieldValueConverter, options.layerName,
147 options.actionOnExistingFile, newLayer, transformContext, sinkFlags, options.fieldNameSource, options.includeConstraints, options.setFieldDomains, options.sourceDatabaseProviderConnection );
149}
150
151bool QgsVectorFileWriter::supportsFeatureStyles( const QString &driverName )
152{
153 if ( driverName == QLatin1String( "MapInfo MIF" ) )
154 {
155 return true;
156 }
157 GDALDriverH gdalDriver = GDALGetDriverByName( driverName.toLocal8Bit().constData() );
158 if ( !gdalDriver )
159 return false;
160
161 char **driverMetadata = GDALGetMetadata( gdalDriver, nullptr );
162 if ( !driverMetadata )
163 return false;
164
165#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,7,0)
166 return CSLFetchBoolean( driverMetadata, GDAL_DCAP_FEATURE_STYLES_WRITE, false );
167#else
168 return CSLFetchBoolean( driverMetadata, GDAL_DCAP_FEATURE_STYLES, false );
169#endif
170}
171
172void QgsVectorFileWriter::init( QString vectorFileName,
173 QString fileEncoding,
174 const QgsFields &fields,
175 Qgis::WkbType geometryType,
177 const QString &driverName,
178 QStringList datasourceOptions,
179 QStringList layerOptions,
180 QString *newFilename,
181 FieldValueConverter *fieldValueConverter,
182 const QString &layerNameIn,
183 ActionOnExistingFile action,
184 QString *newLayer, SinkFlags sinkFlags,
185 const QgsCoordinateTransformContext &transformContext, FieldNameSource fieldNameSource,
186 const QgsAbstractDatabaseProviderConnection *sourceDatabaseProviderConnection )
187{
188#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(3,5,0)
189 ( void )sourceDatabaseProviderConnection;
190#endif
191
192 mRenderContext.setRendererScale( mSymbologyScale );
193
194 if ( vectorFileName.isEmpty() )
195 {
196 mErrorMessage = QObject::tr( "Empty filename given" );
198 return;
199 }
200
201 if ( driverName == QLatin1String( "MapInfo MIF" ) )
202 {
203 mOgrDriverName = QStringLiteral( "MapInfo File" );
204 }
205 else if ( driverName == QLatin1String( "SpatiaLite" ) )
206 {
207 mOgrDriverName = QStringLiteral( "SQLite" );
208 if ( !datasourceOptions.contains( QStringLiteral( "SPATIALITE=YES" ) ) )
209 {
210 datasourceOptions.append( QStringLiteral( "SPATIALITE=YES" ) );
211 }
212 }
213 else if ( driverName == QLatin1String( "DBF file" ) )
214 {
215 mOgrDriverName = QStringLiteral( "ESRI Shapefile" );
216 if ( !layerOptions.contains( QStringLiteral( "SHPT=NULL" ) ) )
217 {
218 layerOptions.append( QStringLiteral( "SHPT=NULL" ) );
219 }
221 }
222 else
223 {
224 mOgrDriverName = driverName;
225 }
226
227#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(3,3,1)
228 QString fidFieldName;
229 if ( mOgrDriverName == QLatin1String( "GPKG" ) )
230 {
231 for ( const QString &layerOption : layerOptions )
232 {
233 if ( layerOption.startsWith( QLatin1String( "FID=" ) ) )
234 {
235 fidFieldName = layerOption.mid( 4 );
236 break;
237 }
238 }
239 if ( fidFieldName.isEmpty() )
240 fidFieldName = QStringLiteral( "fid" );
241 }
242#endif
243
244 // find driver in OGR
245 OGRSFDriverH poDriver;
247
248 poDriver = OGRGetDriverByName( mOgrDriverName.toLocal8Bit().constData() );
249
250 if ( !poDriver )
251 {
252 mErrorMessage = QObject::tr( "OGR driver for '%1' not found (OGR error: %2)" )
253 .arg( driverName,
254 QString::fromUtf8( CPLGetLastErrorMsg() ) );
256 return;
257 }
258
259 mOgrDriverLongName = QString( GDALGetMetadataItem( poDriver, GDAL_DMD_LONGNAME, nullptr ) );
260
261 MetaData metadata;
262 bool metadataFound = driverMetadata( driverName, metadata );
263
264 if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
265 {
266 if ( layerOptions.join( QString() ).toUpper().indexOf( QLatin1String( "ENCODING=" ) ) == -1 )
267 {
268 layerOptions.append( "ENCODING=" + convertCodecNameForEncodingOption( fileEncoding ) );
269 }
270
271 if ( driverName == QLatin1String( "ESRI Shapefile" ) && !vectorFileName.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) )
272 {
273 vectorFileName += QLatin1String( ".shp" );
274 }
275 else if ( driverName == QLatin1String( "DBF file" ) && !vectorFileName.endsWith( QLatin1String( ".dbf" ), Qt::CaseInsensitive ) )
276 {
277 vectorFileName += QLatin1String( ".dbf" );
278 }
279
280 if ( action == CreateOrOverwriteFile || action == CreateOrOverwriteLayer )
281 deleteShapeFile( vectorFileName );
282 }
283 else
284 {
285 if ( metadataFound )
286 {
287 QStringList allExts = metadata.glob.split( ' ', Qt::SkipEmptyParts );
288 bool found = false;
289 const auto constAllExts = allExts;
290 for ( const QString &ext : constAllExts )
291 {
292 // Remove the wildcard (*) at the beginning of the extension
293 if ( vectorFileName.endsWith( ext.mid( 1 ), Qt::CaseInsensitive ) )
294 {
295 found = true;
296 break;
297 }
298 }
299
300 if ( !found )
301 {
302 allExts = metadata.ext.split( ' ', Qt::SkipEmptyParts );
303 vectorFileName += '.' + allExts[0];
304 }
305 }
306
307 if ( action == CreateOrOverwriteFile )
308 {
309 if ( vectorFileName.endsWith( QLatin1String( ".gdb" ), Qt::CaseInsensitive ) )
310 {
311 QDir dir( vectorFileName );
312 if ( dir.exists() )
313 {
314 QFileInfoList fileList = dir.entryInfoList(
315 QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst );
316 const auto constFileList = fileList;
317 for ( const QFileInfo &info : constFileList )
318 {
319 QFile::remove( info.absoluteFilePath() );
320 }
321 }
322 QDir().rmdir( vectorFileName );
323 }
324 else
325 {
326 QFile::remove( vectorFileName );
327 }
328 }
329 }
330
331 if ( metadataFound && !metadata.compulsoryEncoding.isEmpty() )
332 {
333 if ( fileEncoding.compare( metadata.compulsoryEncoding, Qt::CaseInsensitive ) != 0 )
334 {
335 QgsDebugMsgLevel( QStringLiteral( "forced %1 encoding for %2" ).arg( metadata.compulsoryEncoding, driverName ), 2 );
336 fileEncoding = metadata.compulsoryEncoding;
337 }
338
339 }
340
341 char **options = nullptr;
342 if ( !datasourceOptions.isEmpty() )
343 {
344 options = new char *[ datasourceOptions.size() + 1 ];
345 for ( int i = 0; i < datasourceOptions.size(); i++ )
346 {
347 QgsDebugMsgLevel( QStringLiteral( "-dsco=%1" ).arg( datasourceOptions[i] ), 2 );
348 options[i] = CPLStrdup( datasourceOptions[i].toUtf8().constData() );
349 }
350 options[ datasourceOptions.size()] = nullptr;
351 }
352
353 mAttrIdxToOgrIdx.remove( 0 );
354
355 // create the data source
356 if ( action == CreateOrOverwriteFile )
357 mDS.reset( OGR_Dr_CreateDataSource( poDriver, vectorFileName.toUtf8().constData(), options ) );
358 else
359 mDS.reset( OGROpen( vectorFileName.toUtf8().constData(), TRUE, nullptr ) );
360
361 if ( options )
362 {
363 for ( int i = 0; i < datasourceOptions.size(); i++ )
364 CPLFree( options[i] );
365 delete [] options;
366 options = nullptr;
367 }
368
369 if ( !mDS )
370 {
372 if ( action == CreateOrOverwriteFile )
373 mErrorMessage = QObject::tr( "Creation of data source failed (OGR error: %1)" )
374 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
375 else
376 mErrorMessage = QObject::tr( "Opening of data source in update mode failed (OGR error: %1)" )
377 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
378 return;
379 }
380
381 QString layerName( layerNameIn );
382 if ( layerName.isEmpty() )
383 layerName = QFileInfo( vectorFileName ).baseName();
384
385 if ( action == CreateOrOverwriteLayer )
386 {
387 const int layer_count = OGR_DS_GetLayerCount( mDS.get() );
388 for ( int i = 0; i < layer_count; i++ )
389 {
390 OGRLayerH hLayer = OGR_DS_GetLayer( mDS.get(), i );
391 if ( EQUAL( OGR_L_GetName( hLayer ), layerName.toUtf8().constData() ) )
392 {
393 if ( OGR_DS_DeleteLayer( mDS.get(), i ) != OGRERR_NONE )
394 {
396 mErrorMessage = QObject::tr( "Overwriting of existing layer failed (OGR error: %1)" )
397 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
398 return;
399 }
400 break;
401 }
402 }
403 }
404
405 if ( action == CreateOrOverwriteFile )
406 {
407 QgsDebugMsgLevel( QStringLiteral( "Created data source" ), 2 );
408 }
409 else
410 {
411 QgsDebugMsgLevel( QStringLiteral( "Opened data source in update mode" ), 2 );
412 }
413
414 // use appropriate codec
415 mCodec = QTextCodec::codecForName( fileEncoding.toLocal8Bit().constData() );
416 if ( !mCodec )
417 {
418 QgsDebugError( "error finding QTextCodec for " + fileEncoding );
419
420 QgsSettings settings;
421 QString enc = settings.value( QStringLiteral( "UI/encoding" ), "System" ).toString();
422 mCodec = QTextCodec::codecForName( enc.toLocal8Bit().constData() );
423 if ( !mCodec )
424 {
425 QgsDebugError( "error finding QTextCodec for " + enc );
426 mCodec = QTextCodec::codecForLocale();
427 Q_ASSERT( mCodec );
428 }
429 }
430
431 // consider spatial reference system of the layer
432 if ( driverName == QLatin1String( "KML" ) || driverName == QLatin1String( "LIBKML" ) || driverName == QLatin1String( "GPX" ) )
433 {
434 if ( srs.authid() != QLatin1String( "EPSG:4326" ) )
435 {
436 // Those drivers outputs WGS84 geometries, let's align our output CRS to have QGIS take charge of geometry transformation
438 mCoordinateTransform.reset( new QgsCoordinateTransform( srs, wgs84, transformContext ) );
439 srs = wgs84;
440 }
441 }
442
444
445 // datasource created, now create the output layer
446 OGRwkbGeometryType wkbType = ogrTypeFromWkbType( geometryType );
447
448 // Remove FEATURE_DATASET layer option (used for ESRI File GDB driver) if its value is not set
449 int optIndex = layerOptions.indexOf( QLatin1String( "FEATURE_DATASET=" ) );
450 if ( optIndex != -1 )
451 {
452 layerOptions.removeAt( optIndex );
453 }
454
455 if ( !layerOptions.isEmpty() )
456 {
457 options = new char *[ layerOptions.size() + 1 ];
458 for ( int i = 0; i < layerOptions.size(); i++ )
459 {
460 QgsDebugMsgLevel( QStringLiteral( "-lco=%1" ).arg( layerOptions[i] ), 2 );
461 options[i] = CPLStrdup( layerOptions[i].toUtf8().constData() );
462 }
463 options[ layerOptions.size()] = nullptr;
464 }
465
466 // disable encoding conversion of OGR Shapefile layer
467 CPLSetConfigOption( "SHAPE_ENCODING", "" );
468
469 if ( action == CreateOrOverwriteFile || action == CreateOrOverwriteLayer )
470 {
471 mLayer = OGR_DS_CreateLayer( mDS.get(), layerName.toUtf8().constData(), mOgrRef, wkbType, options );
472 if ( newLayer && mLayer )
473 {
474 *newLayer = OGR_L_GetName( mLayer );
475 if ( driverName == QLatin1String( "GPX" ) )
476 {
477 // See logic in GDAL ogr/ogrsf_frmts/gpx/ogrgpxdatasource.cpp ICreateLayer()
478 switch ( QgsWkbTypes::flatType( geometryType ) )
479 {
481 {
482 if ( !EQUAL( layerName.toUtf8().constData(), "track_points" ) &&
483 !EQUAL( layerName.toUtf8().constData(), "route_points" ) )
484 {
485 *newLayer = QStringLiteral( "waypoints" );
486 }
487 }
488 break;
489
491 {
492 const char *pszForceGPXTrack
493 = CSLFetchNameValue( options, "FORCE_GPX_TRACK" );
494 if ( pszForceGPXTrack && CPLTestBool( pszForceGPXTrack ) )
495 *newLayer = QStringLiteral( "tracks" );
496 else
497 *newLayer = QStringLiteral( "routes" );
498
499 }
500 break;
501
503 {
504 const char *pszForceGPXRoute
505 = CSLFetchNameValue( options, "FORCE_GPX_ROUTE" );
506 if ( pszForceGPXRoute && CPLTestBool( pszForceGPXRoute ) )
507 *newLayer = QStringLiteral( "routes" );
508 else
509 *newLayer = QStringLiteral( "tracks" );
510 }
511 break;
512
513 default:
514 break;
515 }
516 }
517 }
518 }
519 else if ( driverName == QLatin1String( "DGN" ) )
520 {
521 mLayer = OGR_DS_GetLayerByName( mDS.get(), "elements" );
522 }
523 else
524 {
525 mLayer = OGR_DS_GetLayerByName( mDS.get(), layerName.toUtf8().constData() );
526 }
527
528 if ( options )
529 {
530 for ( int i = 0; i < layerOptions.size(); i++ )
531 CPLFree( options[i] );
532 delete [] options;
533 options = nullptr;
534 }
535
536 if ( srs.isValid() )
537 {
538 if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
539 {
540 QString layerName = vectorFileName.left( vectorFileName.indexOf( QLatin1String( ".shp" ), Qt::CaseInsensitive ) );
541 QFile prjFile( layerName + ".qpj" );
542 if ( prjFile.exists() )
543 prjFile.remove();
544 }
545 }
546
547 if ( !mLayer )
548 {
549 if ( action == CreateOrOverwriteFile || action == CreateOrOverwriteLayer )
550 mErrorMessage = QObject::tr( "Creation of layer failed (OGR error: %1)" )
551 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
552 else
553 mErrorMessage = QObject::tr( "Opening of layer failed (OGR error: %1)" )
554 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
556 return;
557 }
558
559 OGRFeatureDefnH defn = OGR_L_GetLayerDefn( mLayer );
560
561 QgsDebugMsgLevel( QStringLiteral( "created layer" ), 2 );
562
563 // create the fields
564 QgsDebugMsgLevel( "creating " + QString::number( fields.size() ) + " fields", 2 );
565
566 mFields = fields;
568 QSet<int> existingIdxs;
569
570 mFieldValueConverter = fieldValueConverter;
571
572#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,7,0)
573 if ( const char *pszCreateFieldDefnFlags = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATION_FIELD_DEFN_FLAGS, nullptr ) )
574 {
575 char **papszTokens = CSLTokenizeString2( pszCreateFieldDefnFlags, " ", 0 );
576 if ( CSLFindString( papszTokens, "AlternativeName" ) >= 0 )
577 {
579 }
580 if ( CSLFindString( papszTokens, "Comment" ) >= 0 )
581 {
583 }
584 CSLDestroy( papszTokens );
585 }
586#endif
587
588 switch ( action )
589 {
593 {
594#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,5,0)
595 QSet<QString> existingDestDomainNames;
596 if ( sourceDatabaseProviderConnection )
597 {
598 char **domainNames = GDALDatasetGetFieldDomainNames( mDS.get(), nullptr );
599 for ( const char *const *iterDomainNames = domainNames; iterDomainNames && *iterDomainNames; ++iterDomainNames )
600 {
601 existingDestDomainNames.insert( QString::fromUtf8( *iterDomainNames ) );
602 }
603 CSLDestroy( domainNames );
604 }
605#endif
606#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,6,0)
607 QSet< QString > usedAlternativeNames;
608#endif
609
610 const QString ogrFidColumnName { OGR_L_GetFIDColumn( mLayer ) };
611 const int fidNameIndex = OGR_FD_GetFieldIndex( defn, ogrFidColumnName.toUtf8() );
612 // if native fid column in created layer matches an attribute from the user-specified fields, we'll be
613 // promoting that to a real attribute.
614 const bool promoteFidColumnToAttribute = !ogrFidColumnName.isEmpty() && fidNameIndex < 0 && fields.lookupField( ogrFidColumnName ) >= 0;
615 int offsetRoomForFid = promoteFidColumnToAttribute ? 1 : 0;
616
617 for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx )
618 {
619 QgsField attrField = fields.at( fldIdx );
620
621 if ( fieldValueConverter )
622 {
623 attrField = fieldValueConverter->fieldDefinition( fields.at( fldIdx ) );
624 }
625
626 if ( action == AppendToLayerAddFields )
627 {
628 int ogrIdx = OGR_FD_GetFieldIndex( defn, mCodec->fromUnicode( attrField.name() ) );
629 if ( ogrIdx >= 0 )
630 {
631 mAttrIdxToOgrIdx.insert( fldIdx, ogrIdx );
632 continue;
633 }
634 }
635
636 QString name;
637 switch ( fieldNameSource )
638 {
639 case Original:
640 name = attrField.name();
641 break;
642
643 case PreferAlias:
644 name = !attrField.alias().isEmpty() ? attrField.alias() : attrField.name();
645 break;
646 }
647
648 OGRFieldType ogrType = OFTString; //default to string
649 OGRFieldSubType ogrSubType = OFSTNone;
650 int ogrWidth = attrField.length();
651 int ogrPrecision = attrField.precision();
652 if ( ogrPrecision > 0 )
653 ++ogrWidth;
654
655 switch ( attrField.type() )
656 {
657 case QMetaType::Type::LongLong:
658 {
659 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES, nullptr );
660 if ( pszDataTypes && strstr( pszDataTypes, "Integer64" ) )
661 ogrType = OFTInteger64;
662 else
663 ogrType = OFTReal;
664 ogrWidth = ogrWidth > 0 && ogrWidth <= 20 ? ogrWidth : 20;
665 ogrPrecision = 0;
666 break;
667 }
668 case QMetaType::Type::QString:
669 ogrType = OFTString;
670 if ( ( ogrWidth <= 0 || ogrWidth > 255 ) && mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
671 ogrWidth = 255;
672 break;
673
674 case QMetaType::Type::Int:
675 ogrType = OFTInteger;
676 ogrWidth = ogrWidth > 0 && ogrWidth <= 10 ? ogrWidth : 10;
677 ogrPrecision = 0;
678 break;
679
680 case QMetaType::Type::Bool:
681 ogrType = OFTInteger;
682 ogrSubType = OFSTBoolean;
683 ogrWidth = 1;
684 ogrPrecision = 0;
685 break;
686
687 case QMetaType::Type::Double:
688#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(3,3,1)
689 if ( mOgrDriverName == QLatin1String( "GPKG" ) && attrField.precision() == 0 && attrField.name().compare( fidFieldName, Qt::CaseInsensitive ) == 0 )
690 {
691 // Convert field to match required FID type
692 ogrType = OFTInteger64;
693 break;
694 }
695#endif
696 ogrType = OFTReal;
697 break;
698
699 case QMetaType::Type::QDate:
700 ogrType = OFTDate;
701 break;
702
703 case QMetaType::Type::QTime:
704 if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
705 {
706 ogrType = OFTString;
707 ogrWidth = 12; // %02d:%02d:%06.3f
708 }
709 else
710 {
711 ogrType = OFTTime;
712 }
713 break;
714
715 case QMetaType::Type::QDateTime:
716 if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
717 {
718 ogrType = OFTString;
719 ogrWidth = 24; // "%04d/%02d/%02d %02d:%02d:%06.3f"
720 }
721 else
722 {
723 ogrType = OFTDateTime;
724 }
725 break;
726
727 case QMetaType::Type::QByteArray:
728 ogrType = OFTBinary;
729 break;
730
731 case QMetaType::Type::QStringList:
732 {
733 // handle GPKG conversion to JSON
734 if ( mOgrDriverName == QLatin1String( "GPKG" ) )
735 {
736 ogrType = OFTString;
737 ogrSubType = OFSTJSON;
738 break;
739 }
740
741 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES, nullptr );
742 if ( pszDataTypes && strstr( pszDataTypes, "StringList" ) )
743 {
744 ogrType = OFTStringList;
745 mSupportedListSubTypes.insert( QMetaType::Type::QString );
746 }
747 else
748 {
749 ogrType = OFTString;
750 ogrWidth = 255;
751 }
752 break;
753 }
754
755 case QMetaType::Type::QVariantMap:
756 {
757 // handle GPKG conversion to JSON
758 const char *pszDataSubTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATASUBTYPES, nullptr );
759 if ( pszDataSubTypes && strstr( pszDataSubTypes, "JSON" ) )
760 {
761 ogrType = OFTString;
762 ogrSubType = OFSTJSON;
763 break;
764 }
765 }
766
767 //intentional fall-through
768 [[fallthrough]];
769
770 case QMetaType::Type::QVariantList:
771 // handle GPKG conversion to JSON
772 if ( mOgrDriverName == QLatin1String( "GPKG" ) )
773 {
774 ogrType = OFTString;
775 ogrSubType = OFSTJSON;
776 break;
777 }
778
779 // fall through to default for other unsupported types
780 if ( attrField.subType() == QMetaType::Type::QString )
781 {
782 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES, nullptr );
783 if ( pszDataTypes && strstr( pszDataTypes, "StringList" ) )
784 {
785 ogrType = OFTStringList;
786 mSupportedListSubTypes.insert( QMetaType::Type::QString );
787 }
788 else
789 {
790 ogrType = OFTString;
791 ogrWidth = 255;
792 }
793 break;
794 }
795 else if ( attrField.subType() == QMetaType::Type::Int )
796 {
797 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES, nullptr );
798 if ( pszDataTypes && strstr( pszDataTypes, "IntegerList" ) )
799 {
800 ogrType = OFTIntegerList;
801 mSupportedListSubTypes.insert( QMetaType::Type::Int );
802 }
803 else
804 {
805 ogrType = OFTString;
806 ogrWidth = 255;
807 }
808 break;
809 }
810 else if ( attrField.subType() == QMetaType::Type::Double )
811 {
812 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES, nullptr );
813 if ( pszDataTypes && strstr( pszDataTypes, "RealList" ) )
814 {
815 ogrType = OFTRealList;
816 mSupportedListSubTypes.insert( QMetaType::Type::Double );
817 }
818 else
819 {
820 ogrType = OFTString;
821 ogrWidth = 255;
822 }
823 break;
824 }
825 else if ( attrField.subType() == QMetaType::Type::LongLong )
826 {
827 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES, nullptr );
828 if ( pszDataTypes && strstr( pszDataTypes, "Integer64List" ) )
829 {
830 ogrType = OFTInteger64List;
831 mSupportedListSubTypes.insert( QMetaType::Type::LongLong );
832 }
833 else
834 {
835 ogrType = OFTString;
836 ogrWidth = 255;
837 }
838 break;
839 }
840 //intentional fall-through
841 [[fallthrough]];
842
843 default:
844 //assert(0 && "invalid variant type!");
845 mErrorMessage = QObject::tr( "Unsupported type for field %1" )
846 .arg( attrField.name() );
848 return;
849 }
850
851 if ( mOgrDriverName == QLatin1String( "SQLite" ) && name.compare( QLatin1String( "ogc_fid" ), Qt::CaseInsensitive ) == 0 )
852 {
853 int i;
854 for ( i = 0; i < 10; i++ )
855 {
856 name = QStringLiteral( "ogc_fid%1" ).arg( i );
857
858 int j;
859 for ( j = 0; j < fields.size() && name.compare( fields.at( j ).name(), Qt::CaseInsensitive ) != 0; j++ )
860 ;
861
862 if ( j == fields.size() )
863 break;
864 }
865
866 if ( i == 10 )
867 {
868 mErrorMessage = QObject::tr( "No available replacement for internal fieldname ogc_fid found" ).arg( attrField.name() );
870 return;
871 }
872
873 QgsMessageLog::logMessage( QObject::tr( "Reserved attribute name ogc_fid replaced with %1" ).arg( name ), QObject::tr( "OGR" ) );
874 }
875
876 // create field definition
877 gdal::ogr_field_def_unique_ptr fld( OGR_Fld_Create( mCodec->fromUnicode( name ), ogrType ) );
878 if ( ogrWidth > 0 )
879 {
880 OGR_Fld_SetWidth( fld.get(), ogrWidth );
881 }
882
883 if ( ogrPrecision >= 0 )
884 {
885 OGR_Fld_SetPrecision( fld.get(), ogrPrecision );
886 }
887
888 if ( ogrSubType != OFSTNone )
889 OGR_Fld_SetSubType( fld.get(), ogrSubType );
890
891#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,6,0)
892 if ( !attrField.alias().isEmpty() )
893 {
894 QString alternativeName = attrField.alias();
895 int counter = 1;
896 while ( usedAlternativeNames.contains( alternativeName ) )
897 {
898 // field alternative names MUST be unique (at least for Geopackage, but let's apply the constraint universally)
899 alternativeName = attrField.alias() + QStringLiteral( " (%1)" ).arg( ++counter );
900 }
901 OGR_Fld_SetAlternativeName( fld.get(), mCodec->fromUnicode( alternativeName ).constData() );
902 usedAlternativeNames.insert( alternativeName );
903 }
904#endif
905#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,7,0)
906 OGR_Fld_SetComment( fld.get(), mCodec->fromUnicode( attrField.comment() ).constData() );
907#endif
908
910 {
912 {
913 OGR_Fld_SetNullable( fld.get(), false );
914 }
916 {
917 OGR_Fld_SetUnique( fld.get(), true );
918 }
919 }
920#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,5,0)
921 if ( mSetFieldDomains && sourceDatabaseProviderConnection )
922 {
923 const QString domainName = attrField.constraints().domainName();
924 if ( !domainName.isEmpty() )
925 {
926 bool canSetFieldDomainName = false;
927 if ( existingDestDomainNames.contains( domainName ) )
928 {
929 // If the target dataset already knows this field domain,
930 // we can directly assign its name to the new field.
931 canSetFieldDomainName = true;
932 }
933 else if ( GDALDatasetTestCapability( mDS.get(), ODsCAddFieldDomain ) )
934 {
935 // Otherwise, if the output dataset can create field domains,
936 // - convert the QGIS field domain to a GDAL one
937 // - register it to the GDAL dataset
938 // - if successful, note that we know that field domain (if it
939 // is shared by other fields)
940 // - assign its name to the new field.
941 try
942 {
943 std::unique_ptr<QgsFieldDomain> domain( sourceDatabaseProviderConnection->fieldDomain( domainName ) );
944 if ( domain )
945 {
946 OGRFieldDomainH hFieldDomain = QgsOgrUtils::convertFieldDomain( domain.get() );
947 if ( hFieldDomain )
948 {
949 char *pszFailureReason = nullptr;
950 if ( GDALDatasetAddFieldDomain( mDS.get(), hFieldDomain, &pszFailureReason ) )
951 {
952 existingDestDomainNames.insert( domainName );
953 canSetFieldDomainName = true;
954 }
955 else
956 {
957 QgsDebugError( QStringLiteral( "cannot create field domain: %1" ).arg( pszFailureReason ) );
958 }
959 CPLFree( pszFailureReason );
960 OGR_FldDomain_Destroy( hFieldDomain );
961 }
962 }
963 }
965 {
966 QgsDebugError( QStringLiteral( "Cannot retrieve field domain: %1" ).arg( domainName ) );
967 }
968 }
969 if ( canSetFieldDomainName )
970 {
971 OGR_Fld_SetDomainName( fld.get(), domainName.toUtf8().toStdString().c_str() );
972 }
973 }
974 }
975#endif
976
977 // create the field
978 QgsDebugMsgLevel( "creating field " + attrField.name() +
979 " type " + QString( QVariant::typeToName( attrField.type() ) ) +
980 " width " + QString::number( ogrWidth ) +
981 " precision " + QString::number( ogrPrecision ), 2 );
982 if ( OGR_L_CreateField( mLayer, fld.get(), true ) != OGRERR_NONE )
983 {
984 QgsDebugError( "error creating field " + attrField.name() );
985 mErrorMessage = QObject::tr( "Creation of field %1 (%2) failed (OGR error: %3)" )
986 .arg( attrField.name(),
987 QVariant::typeToName( attrField.type() ),
988 QString::fromUtf8( CPLGetLastErrorMsg() ) );
990 return;
991 }
992
993 int ogrIdx = OGR_FD_GetFieldIndex( defn, mCodec->fromUnicode( name ) );
994 QgsDebugMsgLevel( QStringLiteral( "returned field index for %1: %2" ).arg( name ).arg( ogrIdx ), 2 );
995 if ( ogrIdx < 0 || existingIdxs.contains( ogrIdx ) )
996 {
997 // GDAL 1.7 not just truncates, but launders more aggressivly.
998 ogrIdx = OGR_FD_GetFieldCount( defn ) - 1;
999
1000 if ( ogrIdx < 0 )
1001 {
1002 QgsDebugError( "error creating field " + attrField.name() );
1003 mErrorMessage = QObject::tr( "Created field %1 not found (OGR error: %2)" )
1004 .arg( attrField.name(),
1005 QString::fromUtf8( CPLGetLastErrorMsg() ) );
1007 return;
1008 }
1009 }
1010
1011 if ( promoteFidColumnToAttribute )
1012 {
1013 if ( ogrFidColumnName.compare( attrField.name(), Qt::CaseInsensitive ) == 0 )
1014 {
1015 ogrIdx = 0;
1016 offsetRoomForFid = 0;
1017 }
1018 else
1019 {
1020 // shuffle to make space for fid column
1021 ogrIdx += offsetRoomForFid;
1022 }
1023 }
1024
1025 existingIdxs.insert( ogrIdx );
1026 mAttrIdxToOgrIdx.insert( fldIdx, ogrIdx );
1027 }
1028 }
1029 break;
1030
1032 {
1033 for ( int fldIdx = 0; fldIdx < fields.count(); ++fldIdx )
1034 {
1035 QgsField attrField = fields.at( fldIdx );
1036 QString name( attrField.name() );
1037 int ogrIdx = OGR_FD_GetFieldIndex( defn, mCodec->fromUnicode( name ) );
1038 if ( ogrIdx >= 0 )
1039 mAttrIdxToOgrIdx.insert( fldIdx, ogrIdx );
1040 }
1041 }
1042 break;
1043 }
1044
1045 // Geopackages require a unique feature id. If the input feature stream cannot guarantee
1046 // the uniqueness of the FID column, we drop it and let OGR generate new ones
1047 if ( sinkFlags.testFlag( QgsFeatureSink::RegeneratePrimaryKey ) && driverName == QLatin1String( "GPKG" ) )
1048 {
1049 int fidIdx = fields.lookupField( QStringLiteral( "FID" ) );
1050
1051 if ( fidIdx >= 0 )
1052 mAttrIdxToOgrIdx.remove( fidIdx );
1053 }
1054
1055 QgsDebugMsgLevel( QStringLiteral( "Done creating fields" ), 2 );
1056
1057 mWkbType = geometryType;
1058
1059 if ( newFilename )
1060 *newFilename = vectorFileName;
1061
1062 // enabling transaction on databases that support it
1063 mUsingTransaction = true;
1064 if ( OGRERR_NONE != OGR_L_StartTransaction( mLayer ) )
1065 {
1066 mUsingTransaction = false;
1067 }
1068}
1069
1071{
1072 return OGR_G_CreateGeometry( ogrTypeFromWkbType( wkbType ) );
1073}
1074
1076class QgsVectorFileWriterMetadataContainer
1077{
1078 public:
1079
1080 QgsVectorFileWriterMetadataContainer()
1081 {
1082 QMap<QString, QgsVectorFileWriter::Option *> datasetOptions;
1083 QMap<QString, QgsVectorFileWriter::Option *> layerOptions;
1084
1085 // Arrow
1086 datasetOptions.clear();
1087 layerOptions.clear();
1088
1089 layerOptions.insert( QStringLiteral( "COMPRESSION" ), new QgsVectorFileWriter::SetOption(
1090 QObject::tr( "Compression method." ),
1091 QStringList()
1092 << QStringLiteral( "UNCOMPRESSED" )
1093 << QStringLiteral( "ZSTD" )
1094 << QStringLiteral( "LZ4" ),
1095 QStringLiteral( "LZ4" ), // Default value
1096 false // Allow None
1097 ) );
1098
1099 layerOptions.insert( QStringLiteral( "GEOMETRY_ENCODING" ), new QgsVectorFileWriter::SetOption(
1100 QObject::tr( "Geometry encoding." ),
1101 QStringList()
1102 << QStringLiteral( "GEOARROW" )
1103 << QStringLiteral( "WKB" )
1104 << QStringLiteral( "WKT" ),
1105 QStringLiteral( "GEOARROW" ), // Default value
1106 false // Allow None
1107 ) );
1108
1109 layerOptions.insert( QStringLiteral( "BATCH_SIZE" ), new QgsVectorFileWriter::IntOption(
1110 QObject::tr( "Maximum number of rows per batch." ),
1111 65536 // Default value
1112 ) );
1113
1114 layerOptions.insert( QStringLiteral( "FID" ), new QgsVectorFileWriter::StringOption(
1115 QObject::tr( "Name for the feature identifier column" ),
1116 QString() // Default value
1117 ) );
1118
1119 layerOptions.insert( QStringLiteral( "GEOMETRY_NAME" ), new QgsVectorFileWriter::StringOption(
1120 QObject::tr( "Name for the geometry column" ),
1121 QStringLiteral( "geometry" ) // Default value
1122 ) );
1123
1124 driverMetadata.insert( QStringLiteral( "Arrow" ),
1126 QStringLiteral( "(Geo)Arrow" ),
1127 QObject::tr( "(Geo)Arrow" ),
1128 QStringLiteral( "*.arrow *.feather *.arrows *.ipc" ),
1129 QStringLiteral( "arrow" ),
1130 datasetOptions,
1131 layerOptions,
1132 QStringLiteral( "UTF-8" )
1133 )
1134 );
1135
1136 // Arc/Info ASCII Coverage
1137 datasetOptions.clear();
1138 layerOptions.clear();
1139
1140 driverMetadata.insert( QStringLiteral( "AVCE00" ),
1142 QStringLiteral( "Arc/Info ASCII Coverage" ),
1143 QObject::tr( "Arc/Info ASCII Coverage" ),
1144 QStringLiteral( "*.e00" ),
1145 QStringLiteral( "e00" ),
1146 datasetOptions,
1147 layerOptions
1148 )
1149 );
1150
1151 // Comma Separated Value
1152 datasetOptions.clear();
1153 layerOptions.clear();
1154
1155 layerOptions.insert( QStringLiteral( "LINEFORMAT" ), new QgsVectorFileWriter::SetOption(
1156 QObject::tr( "By default when creating new .csv files they "
1157 "are created with the line termination conventions "
1158 "of the local platform (CR/LF on Win32 or LF on all other systems). "
1159 "This may be overridden through the use of the LINEFORMAT option." ),
1160 QStringList()
1161 << QStringLiteral( "CRLF" )
1162 << QStringLiteral( "LF" ),
1163 QString(), // Default value
1164 true // Allow None
1165 ) );
1166
1167 layerOptions.insert( QStringLiteral( "GEOMETRY" ), new QgsVectorFileWriter::SetOption(
1168 QObject::tr( "By default, the geometry of a feature written to a .csv file is discarded. "
1169 "It is possible to export the geometry in its WKT representation by "
1170 "specifying GEOMETRY=AS_WKT. It is also possible to export point geometries "
1171 "into their X,Y,Z components by specifying GEOMETRY=AS_XYZ, GEOMETRY=AS_XY "
1172 "or GEOMETRY=AS_YX." ),
1173 QStringList()
1174 << QStringLiteral( "AS_WKT" )
1175 << QStringLiteral( "AS_XYZ" )
1176 << QStringLiteral( "AS_XY" )
1177 << QStringLiteral( "AS_YX" ),
1178 QString(), // Default value
1179 true // Allow None
1180 ) );
1181
1182 layerOptions.insert( QStringLiteral( "GEOMETRY_NAME" ), new QgsVectorFileWriter::StringOption(
1183 QObject::tr( "Name of geometry column. Only used if GEOMETRY=AS_WKT. Defaults to 'WKT'." ),
1184 QStringLiteral( "WKT" ) // Default value
1185 ) );
1186
1187 layerOptions.insert( QStringLiteral( "CREATE_CSVT" ), new QgsVectorFileWriter::BoolOption(
1188 QObject::tr( "Create the associated .csvt file to describe the type of each "
1189 "column of the layer and its optional width and precision. "
1190 "This option also creates a .prj file which stores coordinate system information." ),
1191 false // Default value
1192 ) );
1193
1194 layerOptions.insert( QStringLiteral( "SEPARATOR" ), new QgsVectorFileWriter::SetOption(
1195 QObject::tr( "Field separator character." ),
1196 QStringList()
1197 << QStringLiteral( "COMMA" )
1198 << QStringLiteral( "SEMICOLON" )
1199 << QStringLiteral( "TAB" )
1200 << QStringLiteral( "SPACE" )
1201#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,12,0)
1202 << QStringLiteral( "PIPE" )
1203#endif
1204 , QStringLiteral( "COMMA" ) // Default value
1205 ) );
1206
1207 layerOptions.insert( QStringLiteral( "STRING_QUOTING" ), new QgsVectorFileWriter::SetOption(
1208 QObject::tr( "Double-quote strings. IF_AMBIGUOUS means that string values that look like numbers will be quoted." ),
1209 QStringList()
1210 << QStringLiteral( "IF_NEEDED" )
1211 << QStringLiteral( "IF_AMBIGUOUS" )
1212 << QStringLiteral( "ALWAYS" ),
1213 QStringLiteral( "IF_AMBIGUOUS" ) // Default value
1214 ) );
1215
1216 layerOptions.insert( QStringLiteral( "WRITE_BOM" ), new QgsVectorFileWriter::BoolOption(
1217 QObject::tr( "Write a UTF-8 Byte Order Mark (BOM) at the start of the file." ),
1218 false // Default value
1219 ) );
1220
1221#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,12,0)
1222 layerOptions.insert( QStringLiteral( "HEADER" ), new QgsVectorFileWriter::BoolOption(
1223 QObject::tr( "Whether to write a header line with the field names." ),
1224 true // Default value
1225 ) );
1226#endif
1227
1228 driverMetadata.insert( QStringLiteral( "CSV" ),
1230 QStringLiteral( "Comma Separated Value [CSV]" ),
1231 QObject::tr( "Comma Separated Value [CSV]" ),
1232 QStringLiteral( "*.csv" ),
1233 QStringLiteral( "csv" ),
1234 datasetOptions,
1235 layerOptions
1236 )
1237 );
1238
1239 // FlatGeobuf
1240 datasetOptions.clear();
1241 layerOptions.clear();
1242
1243 driverMetadata.insert( QStringLiteral( "FlatGeobuf" ),
1245 QStringLiteral( "FlatGeobuf" ),
1246 QObject::tr( "FlatGeobuf" ),
1247 QStringLiteral( "*.fgb" ),
1248 QStringLiteral( "fgb" ),
1249 datasetOptions,
1250 layerOptions,
1251 QStringLiteral( "UTF-8" )
1252 )
1253 );
1254
1255 // ESRI Shapefile
1256 datasetOptions.clear();
1257 layerOptions.clear();
1258
1259 layerOptions.insert( QStringLiteral( "SHPT" ), new QgsVectorFileWriter::SetOption(
1260 QObject::tr( "Override the type of shapefile created. "
1261 "Can be one of NULL for a simple .dbf file with no .shp file, POINT, "
1262 "ARC, POLYGON or MULTIPOINT for 2D, or POINTZ, ARCZ, POLYGONZ or "
1263 "MULTIPOINTZ for 3D;" ) +
1264 QObject::tr( " POINTM, ARCM, POLYGONM or MULTIPOINTM for measured geometries"
1265 " and POINTZM, ARCZM, POLYGONZM or MULTIPOINTZM for 3D measured"
1266 " geometries." ) +
1267 QObject::tr( " MULTIPATCH files are supported since GDAL 2.2." ) +
1268 ""
1269 , QStringList()
1270 << QStringLiteral( "NULL" )
1271 << QStringLiteral( "POINT" )
1272 << QStringLiteral( "ARC" )
1273 << QStringLiteral( "POLYGON" )
1274 << QStringLiteral( "MULTIPOINT" )
1275 << QStringLiteral( "POINTZ" )
1276 << QStringLiteral( "ARCZ" )
1277 << QStringLiteral( "POLYGONZ" )
1278 << QStringLiteral( "MULTIPOINTZ" )
1279 << QStringLiteral( "POINTM" )
1280 << QStringLiteral( "ARCM" )
1281 << QStringLiteral( "POLYGONM" )
1282 << QStringLiteral( "MULTIPOINTM" )
1283 << QStringLiteral( "POINTZM" )
1284 << QStringLiteral( "ARCZM" )
1285 << QStringLiteral( "POLYGONZM" )
1286 << QStringLiteral( "MULTIPOINTZM" )
1287 << QStringLiteral( "MULTIPATCH" )
1288 << QString(),
1289 QString(), // Default value
1290 true // Allow None
1291 ) );
1292
1293 // there does not seem to be a reason to provide this option to the user again
1294 // as we set encoding for shapefiles based on "fileEncoding" parameter passed to the writer
1295#if 0
1296 layerOptions.insert( "ENCODING", new QgsVectorFileWriter::SetOption(
1297 QObject::tr( "Set the encoding value in the DBF file. "
1298 "The default value is LDID/87. It is not clear "
1299 "what other values may be appropriate." ),
1300 QStringList()
1301 << "LDID/87",
1302 "LDID/87" // Default value
1303 ) );
1304#endif
1305
1306 layerOptions.insert( QStringLiteral( "RESIZE" ), new QgsVectorFileWriter::BoolOption(
1307 QObject::tr( "Set to YES to resize fields to their optimal size." ),
1308 false // Default value
1309 ) );
1310
1311 driverMetadata.insert( QStringLiteral( "ESRI" ),
1313 QStringLiteral( "ESRI Shapefile" ),
1314 QObject::tr( "ESRI Shapefile" ),
1315 QStringLiteral( "*.shp" ),
1316 QStringLiteral( "shp" ),
1317 datasetOptions,
1318 layerOptions
1319 )
1320 );
1321
1322 // DBF File
1323 datasetOptions.clear();
1324 layerOptions.clear();
1325
1326 driverMetadata.insert( QStringLiteral( "DBF File" ),
1328 QStringLiteral( "DBF File" ),
1329 QObject::tr( "DBF File" ),
1330 QStringLiteral( "*.dbf" ),
1331 QStringLiteral( "dbf" ),
1332 datasetOptions,
1333 layerOptions
1334 )
1335 );
1336
1337 // GeoJSON
1338 datasetOptions.clear();
1339 layerOptions.clear();
1340
1341 layerOptions.insert( QStringLiteral( "WRITE_BBOX" ), new QgsVectorFileWriter::BoolOption(
1342 QObject::tr( "Set to YES to write a bbox property with the bounding box "
1343 "of the geometries at the feature and feature collection level." ),
1344 false // Default value
1345 ) );
1346
1347 layerOptions.insert( QStringLiteral( "COORDINATE_PRECISION" ), new QgsVectorFileWriter::IntOption(
1348 QObject::tr( "Maximum number of figures after decimal separator to write in coordinates. "
1349 "Defaults to 15. Truncation will occur to remove trailing zeros." ),
1350 15 // Default value
1351 ) );
1352
1353 layerOptions.insert( QStringLiteral( "RFC7946" ), new QgsVectorFileWriter::BoolOption(
1354 QObject::tr( "Whether to use RFC 7946 standard. "
1355 "If disabled GeoJSON 2008 initial version will be used. "
1356 "Default is NO (thus GeoJSON 2008). See also Documentation (via Help button)" ),
1357 false // Default value
1358 ) );
1359
1360 driverMetadata.insert( QStringLiteral( "GeoJSON" ),
1362 QStringLiteral( "GeoJSON" ),
1363 QObject::tr( "GeoJSON" ),
1364 QStringLiteral( "*.geojson" ),
1365 QStringLiteral( "geojson" ),
1366 datasetOptions,
1367 layerOptions,
1368 QStringLiteral( "UTF-8" )
1369 )
1370 );
1371
1372 // GeoJSONSeq
1373 datasetOptions.clear();
1374 layerOptions.clear();
1375
1376 layerOptions.insert( QStringLiteral( "COORDINATE_PRECISION" ), new QgsVectorFileWriter::IntOption(
1377 QObject::tr( "Maximum number of figures after decimal separator to write in coordinates. "
1378 "Defaults to 15. Truncation will occur to remove trailing zeros." ),
1379 15 // Default value
1380 ) );
1381
1382 layerOptions.insert( QStringLiteral( "RS" ), new QgsVectorFileWriter::BoolOption(
1383 QObject::tr( "Whether to start records with the RS=0x1E character (RFC 8142 standard). "
1384 "Defaults to NO: Newline Delimited JSON (geojsonl). \n"
1385 "If set to YES: RFC 8142 standard: GeoJSON Text Sequences (geojsons)." ),
1386 false // Default value = NO
1387 ) );
1388
1389 driverMetadata.insert( QStringLiteral( "GeoJSONSeq" ),
1391 QStringLiteral( "GeoJSON - Newline Delimited" ),
1392 QObject::tr( "GeoJSON - Newline Delimited" ),
1393 QStringLiteral( "*.geojsonl *.geojsons *.json" ),
1394 QStringLiteral( "geojsonl geojsons json" ),
1395 datasetOptions,
1396 layerOptions,
1397 QStringLiteral( "UTF-8" )
1398 )
1399 );
1400
1401 // GeoRSS
1402 datasetOptions.clear();
1403 layerOptions.clear();
1404
1405 datasetOptions.insert( QStringLiteral( "FORMAT" ), new QgsVectorFileWriter::SetOption(
1406 QObject::tr( "whether the document must be in RSS 2.0 or Atom 1.0 format. "
1407 "Default value : RSS" ),
1408 QStringList()
1409 << QStringLiteral( "RSS" )
1410 << QStringLiteral( "ATOM" ),
1411 QStringLiteral( "RSS" ) // Default value
1412 ) );
1413
1414 datasetOptions.insert( QStringLiteral( "GEOM_DIALECT" ), new QgsVectorFileWriter::SetOption(
1415 QObject::tr( "The encoding of location information. Default value : SIMPLE. "
1416 "W3C_GEO only supports point geometries. "
1417 "SIMPLE or W3C_GEO only support geometries in geographic WGS84 coordinates." ),
1418 QStringList()
1419 << QStringLiteral( "SIMPLE" )
1420 << QStringLiteral( "GML" )
1421 << QStringLiteral( "W3C_GEO" ),
1422 QStringLiteral( "SIMPLE" ) // Default value
1423 ) );
1424
1425 datasetOptions.insert( QStringLiteral( "USE_EXTENSIONS" ), new QgsVectorFileWriter::BoolOption(
1426 QObject::tr( "If defined to YES, extension fields will be written. "
1427 "If the field name not found in the base schema matches "
1428 "the foo_bar pattern, foo will be considered as the namespace "
1429 "of the element, and a <foo:bar> element will be written. "
1430 "Otherwise, elements will be written in the <ogr:> namespace." ),
1431 false // Default value
1432 ) );
1433
1434 datasetOptions.insert( QStringLiteral( "WRITE_HEADER_AND_FOOTER" ), new QgsVectorFileWriter::BoolOption(
1435 QObject::tr( "If defined to NO, only <entry> or <item> elements will be written. "
1436 "The user will have to provide the appropriate header and footer of the document." ),
1437 true // Default value
1438 ) );
1439
1440 datasetOptions.insert( QStringLiteral( "HEADER" ), new QgsVectorFileWriter::StringOption(
1441 QObject::tr( "XML content that will be put between the <channel> element and the "
1442 "first <item> element for a RSS document, or between the xml tag and "
1443 "the first <entry> element for an Atom document." ),
1444 QString() // Default value
1445 ) );
1446
1447 datasetOptions.insert( QStringLiteral( "TITLE" ), new QgsVectorFileWriter::StringOption(
1448 QObject::tr( "Value put inside the <title> element in the header. "
1449 "If not provided, a dummy value will be used as that element is compulsory." ),
1450 QString() // Default value
1451 ) );
1452
1453 datasetOptions.insert( QStringLiteral( "DESCRIPTION" ), new QgsVectorFileWriter::StringOption(
1454 QObject::tr( "Value put inside the <description> element in the header. "
1455 "If not provided, a dummy value will be used as that element is compulsory." ),
1456 QString() // Default value
1457 ) );
1458
1459 datasetOptions.insert( QStringLiteral( "LINK" ), new QgsVectorFileWriter::StringOption(
1460 QObject::tr( "Value put inside the <link> element in the header. "
1461 "If not provided, a dummy value will be used as that element is compulsory." ),
1462 QString() // Default value
1463 ) );
1464
1465 datasetOptions.insert( QStringLiteral( "UPDATED" ), new QgsVectorFileWriter::StringOption(
1466 QObject::tr( "Value put inside the <updated> element in the header. "
1467 "Should be formatted as a XML datetime. "
1468 "If not provided, a dummy value will be used as that element is compulsory." ),
1469 QString() // Default value
1470 ) );
1471
1472 datasetOptions.insert( QStringLiteral( "AUTHOR_NAME" ), new QgsVectorFileWriter::StringOption(
1473 QObject::tr( "Value put inside the <author><name> element in the header. "
1474 "If not provided, a dummy value will be used as that element is compulsory." ),
1475 QString() // Default value
1476 ) );
1477
1478 datasetOptions.insert( QStringLiteral( "ID" ), new QgsVectorFileWriter::StringOption(
1479 QObject::tr( "Value put inside the <id> element in the header. "
1480 "If not provided, a dummy value will be used as that element is compulsory." ),
1481 QString() // Default value
1482 ) );
1483
1484 driverMetadata.insert( QStringLiteral( "GeoRSS" ),
1486 QStringLiteral( "GeoRSS" ),
1487 QObject::tr( "GeoRSS" ),
1488 QStringLiteral( "*.xml" ),
1489 QStringLiteral( "xml" ),
1490 datasetOptions,
1491 layerOptions,
1492 QStringLiteral( "UTF-8" )
1493 )
1494 );
1495
1496 // Geography Markup Language [GML]
1497 datasetOptions.clear();
1498 layerOptions.clear();
1499
1500 datasetOptions.insert( QStringLiteral( "XSISCHEMAURI" ), new QgsVectorFileWriter::StringOption(
1501 QObject::tr( "If provided, this URI will be inserted as the schema location. "
1502 "Note that the schema file isn't actually accessed by OGR, so it "
1503 "is up to the user to ensure it will match the schema of the OGR "
1504 "produced GML data file." ),
1505 QString() // Default value
1506 ) );
1507
1508 datasetOptions.insert( QStringLiteral( "XSISCHEMA" ), new QgsVectorFileWriter::SetOption(
1509 QObject::tr( "This writes a GML application schema file to a corresponding "
1510 ".xsd file (with the same basename). If INTERNAL is used the "
1511 "schema is written within the GML file, but this is experimental "
1512 "and almost certainly not valid XML. "
1513 "OFF disables schema generation (and is implicit if XSISCHEMAURI is used)." ),
1514 QStringList()
1515 << QStringLiteral( "EXTERNAL" )
1516 << QStringLiteral( "INTERNAL" )
1517 << QStringLiteral( "OFF" ),
1518 QStringLiteral( "EXTERNAL" ) // Default value
1519 ) );
1520
1521 datasetOptions.insert( QStringLiteral( "PREFIX" ), new QgsVectorFileWriter::StringOption(
1522 QObject::tr( "This is the prefix for the application target namespace." ),
1523 QStringLiteral( "ogr" ) // Default value
1524 ) );
1525
1526 datasetOptions.insert( QStringLiteral( "STRIP_PREFIX" ), new QgsVectorFileWriter::BoolOption(
1527 QObject::tr( "Can be set to TRUE to avoid writing the prefix of the "
1528 "application target namespace in the GML file." ),
1529 false // Default value
1530 ) );
1531
1532 datasetOptions.insert( QStringLiteral( "TARGET_NAMESPACE" ), new QgsVectorFileWriter::StringOption(
1533 QObject::tr( "Defaults to 'http://ogr.maptools.org/'. "
1534 "This is the application target namespace." ),
1535 QStringLiteral( "http://ogr.maptools.org/" ) // Default value
1536 ) );
1537
1538 datasetOptions.insert( QStringLiteral( "FORMAT" ), new QgsVectorFileWriter::SetOption(
1539 QObject::tr( "GML version to use." ),
1540 QStringList()
1541 << QStringLiteral( "GML2" )
1542 << QStringLiteral( "GML3" )
1543 << QStringLiteral( "GML3Deegree" )
1544 << QStringLiteral( "GML3.2" ),
1545 QStringLiteral( "GML3.2" ) // Default value
1546 ) );
1547
1548 datasetOptions.insert( QStringLiteral( "GML3_LONGSRS" ), new QgsVectorFileWriter::BoolOption(
1549 QObject::tr( "Only valid when FORMAT=GML3/GML3Degree/GML3.2. Default to YES. " //needs review here
1550 "If YES, SRS with EPSG authority will be written with the "
1551 "'urn:ogc:def:crs:EPSG::' prefix. In the case the SRS is a "
1552 "geographic SRS without explicit AXIS order, but that the same "
1553 "SRS authority code imported with ImportFromEPSGA() should be "
1554 "treated as lat/long, then the function will take care of coordinate "
1555 "order swapping. If set to NO, SRS with EPSG authority will be "
1556 "written with the 'EPSG:' prefix, even if they are in lat/long order." ),
1557 true // Default value
1558 ) );
1559
1560 datasetOptions.insert( QStringLiteral( "WRITE_FEATURE_BOUNDED_BY" ), new QgsVectorFileWriter::BoolOption(
1561 QObject::tr( "only valid when FORMAT=GML3/GML3Degree/GML3.2) Default to YES. "
1562 "If set to NO, the <gml:boundedBy> element will not be written for "
1563 "each feature." ),
1564 true // Default value
1565 ) );
1566
1567 datasetOptions.insert( QStringLiteral( "SPACE_INDENTATION" ), new QgsVectorFileWriter::BoolOption(
1568 QObject::tr( "Default to YES. If YES, the output will be indented with spaces "
1569 "for more readability, but at the expense of file size." ),
1570 true // Default value
1571 ) );
1572
1573
1574 driverMetadata.insert( QStringLiteral( "GML" ),
1576 QStringLiteral( "Geography Markup Language [GML]" ),
1577 QObject::tr( "Geography Markup Language [GML]" ),
1578 QStringLiteral( "*.gml" ),
1579 QStringLiteral( "gml" ),
1580 datasetOptions,
1581 layerOptions,
1582 QStringLiteral( "UTF-8" )
1583 )
1584 );
1585
1586 // GeoPackage
1587 datasetOptions.clear();
1588 layerOptions.clear();
1589
1590 layerOptions.insert( QStringLiteral( "IDENTIFIER" ), new QgsVectorFileWriter::StringOption(
1591 QObject::tr( "Human-readable identifier (e.g. short name) for the layer content" ),
1592 QString() // Default value
1593 ) );
1594
1595 layerOptions.insert( QStringLiteral( "DESCRIPTION" ), new QgsVectorFileWriter::StringOption(
1596 QObject::tr( "Human-readable description for the layer content" ),
1597 QString() // Default value
1598 ) );
1599
1600 layerOptions.insert( QStringLiteral( "FID" ), new QgsVectorFileWriter::StringOption(
1601 QObject::tr( "Name for the feature identifier column" ),
1602 QStringLiteral( "fid" ) // Default value
1603 ) );
1604
1605 layerOptions.insert( QStringLiteral( "GEOMETRY_NAME" ), new QgsVectorFileWriter::StringOption(
1606 QObject::tr( "Name for the geometry column" ),
1607 QStringLiteral( "geom" ) // Default value
1608 ) );
1609
1610 layerOptions.insert( QStringLiteral( "SPATIAL_INDEX" ), new QgsVectorFileWriter::BoolOption(
1611 QObject::tr( "If a spatial index must be created." ),
1612 true // Default value
1613 ) );
1614
1615 driverMetadata.insert( QStringLiteral( "GPKG" ),
1617 QStringLiteral( "GeoPackage" ),
1618 QObject::tr( "GeoPackage" ),
1619#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,7,0)
1620 QStringLiteral( "*.gpkg *.gpkg.zip" ),
1621#else
1622 QStringLiteral( "*.gpkg" ),
1623#endif
1624 QStringLiteral( "gpkg" ),
1625 datasetOptions,
1626 layerOptions,
1627 QStringLiteral( "UTF-8" )
1628 )
1629 );
1630
1631 // Generic Mapping Tools [GMT]
1632 datasetOptions.clear();
1633 layerOptions.clear();
1634
1635 driverMetadata.insert( QStringLiteral( "GMT" ),
1637 QStringLiteral( "Generic Mapping Tools [GMT]" ),
1638 QObject::tr( "Generic Mapping Tools [GMT]" ),
1639 QStringLiteral( "*.gmt" ),
1640 QStringLiteral( "gmt" ),
1641 datasetOptions,
1642 layerOptions
1643 )
1644 );
1645
1646 // GPS eXchange Format [GPX]
1647 datasetOptions.clear();
1648 layerOptions.clear();
1649
1650 layerOptions.insert( QStringLiteral( "FORCE_GPX_TRACK" ), new QgsVectorFileWriter::BoolOption(
1651 QObject::tr( "By default when writing a layer whose features are of "
1652 "type wkbLineString, the GPX driver chooses to write "
1653 "them as routes. If FORCE_GPX_TRACK=YES is specified, "
1654 "they will be written as tracks." ),
1655 false // Default value
1656 ) );
1657
1658 layerOptions.insert( QStringLiteral( "FORCE_GPX_ROUTE" ), new QgsVectorFileWriter::BoolOption(
1659 QObject::tr( "By default when writing a layer whose features are of "
1660 "type wkbMultiLineString, the GPX driver chooses to write "
1661 "them as tracks. If FORCE_GPX_ROUTE=YES is specified, "
1662 "they will be written as routes, provided that the multilines "
1663 "are composed of only one single line." ),
1664 false // Default value
1665 ) );
1666
1667 datasetOptions.insert( QStringLiteral( "GPX_USE_EXTENSIONS" ), new QgsVectorFileWriter::BoolOption(
1668 QObject::tr( "If GPX_USE_EXTENSIONS=YES is specified, "
1669 "extra fields will be written inside the <extensions> tag." ),
1670 false // Default value
1671 ) );
1672
1673 datasetOptions.insert( QStringLiteral( "GPX_EXTENSIONS_NS" ), new QgsVectorFileWriter::StringOption(
1674 QObject::tr( "Only used if GPX_USE_EXTENSIONS=YES and GPX_EXTENSIONS_NS_URL "
1675 "is set. The namespace value used for extension tags. By default, 'ogr'." ),
1676 QStringLiteral( "ogr" ) // Default value
1677 ) );
1678
1679 datasetOptions.insert( QStringLiteral( "GPX_EXTENSIONS_NS_URL" ), new QgsVectorFileWriter::StringOption(
1680 QObject::tr( "Only used if GPX_USE_EXTENSIONS=YES and GPX_EXTENSIONS_NS "
1681 "is set. The namespace URI. By default, 'http://osgeo.org/gdal'." ),
1682 QStringLiteral( "http://osgeo.org/gdal" ) // Default value
1683 ) );
1684
1685 datasetOptions.insert( QStringLiteral( "LINEFORMAT" ), new QgsVectorFileWriter::SetOption(
1686 QObject::tr( "By default files are created with the line termination "
1687 "conventions of the local platform (CR/LF on win32 or LF "
1688 "on all other systems). This may be overridden through use "
1689 "of the LINEFORMAT layer creation option which may have a value "
1690 "of CRLF (DOS format) or LF (Unix format)." ),
1691 QStringList()
1692 << QStringLiteral( "CRLF" )
1693 << QStringLiteral( "LF" ),
1694 QString(), // Default value
1695 true // Allow None
1696 ) );
1697
1698 driverMetadata.insert( QStringLiteral( "GPX" ),
1700 QStringLiteral( "GPS eXchange Format [GPX]" ),
1701 QObject::tr( "GPS eXchange Format [GPX]" ),
1702 QStringLiteral( "*.gpx" ),
1703 QStringLiteral( "gpx" ),
1704 datasetOptions,
1705 layerOptions,
1706 QStringLiteral( "UTF-8" )
1707 )
1708 );
1709
1710 // INTERLIS 1
1711 datasetOptions.clear();
1712 layerOptions.clear();
1713
1714 driverMetadata.insert( QStringLiteral( "Interlis 1" ),
1716 QStringLiteral( "INTERLIS 1" ),
1717 QObject::tr( "INTERLIS 1" ),
1718 QStringLiteral( "*.itf *.xml *.ili" ),
1719 QStringLiteral( "ili" ),
1720 datasetOptions,
1721 layerOptions
1722 )
1723 );
1724
1725 // INTERLIS 2
1726 datasetOptions.clear();
1727 layerOptions.clear();
1728
1729 driverMetadata.insert( QStringLiteral( "Interlis 2" ),
1731 QStringLiteral( "INTERLIS 2" ),
1732 QObject::tr( "INTERLIS 2" ),
1733 QStringLiteral( "*.xtf *.xml *.ili" ),
1734 QStringLiteral( "ili" ),
1735 datasetOptions,
1736 layerOptions
1737 )
1738 );
1739
1740 // Keyhole Markup Language [KML]
1741 datasetOptions.clear();
1742 layerOptions.clear();
1743
1744 datasetOptions.insert( QStringLiteral( "NameField" ), new QgsVectorFileWriter::StringOption(
1745 QObject::tr( "Allows you to specify the field to use for the KML <name> element." ),
1746 QStringLiteral( "Name" ) // Default value
1747 ) );
1748
1749 datasetOptions.insert( QStringLiteral( "DescriptionField" ), new QgsVectorFileWriter::StringOption(
1750 QObject::tr( "Allows you to specify the field to use for the KML <description> element." ),
1751 QStringLiteral( "Description" ) // Default value
1752 ) );
1753
1754 datasetOptions.insert( QStringLiteral( "AltitudeMode" ), new QgsVectorFileWriter::SetOption(
1755 QObject::tr( "Allows you to specify the AltitudeMode to use for KML geometries. "
1756 "This will only affect 3D geometries and must be one of the valid KML options." ),
1757 QStringList()
1758 << QStringLiteral( "clampToGround" )
1759 << QStringLiteral( "relativeToGround" )
1760 << QStringLiteral( "absolute" ),
1761 QStringLiteral( "relativeToGround" ) // Default value
1762 ) );
1763
1764 datasetOptions.insert( QStringLiteral( "DOCUMENT_ID" ), new QgsVectorFileWriter::StringOption(
1765 QObject::tr( "The DOCUMENT_ID datasource creation option can be used to specified "
1766 "the id of the root <Document> node. The default value is root_doc." ),
1767 QStringLiteral( "root_doc" ) // Default value
1768 ) );
1769
1770 driverMetadata.insert( QStringLiteral( "KML" ),
1772 QStringLiteral( "Keyhole Markup Language [KML]" ),
1773 QObject::tr( "Keyhole Markup Language [KML]" ),
1774 QStringLiteral( "*.kml" ),
1775 QStringLiteral( "kml" ),
1776 datasetOptions,
1777 layerOptions,
1778 QStringLiteral( "UTF-8" )
1779 )
1780 );
1781
1782 // Mapinfo
1783 datasetOptions.clear();
1784 layerOptions.clear();
1785
1786 auto insertMapInfoOptions = []( QMap<QString, QgsVectorFileWriter::Option *> &datasetOptions, QMap<QString, QgsVectorFileWriter::Option *> &layerOptions )
1787 {
1788 datasetOptions.insert( QStringLiteral( "SPATIAL_INDEX_MODE" ), new QgsVectorFileWriter::SetOption(
1789 QObject::tr( "Use this to turn on 'quick spatial index mode'. "
1790 "In this mode writing files can be about 5 times faster, "
1791 "but spatial queries can be up to 30 times slower." ),
1792 QStringList()
1793 << QStringLiteral( "QUICK" )
1794 << QStringLiteral( "OPTIMIZED" ),
1795 QStringLiteral( "QUICK" ), // Default value
1796 true // Allow None
1797 ) );
1798
1799 datasetOptions.insert( QStringLiteral( "BLOCK_SIZE" ), new QgsVectorFileWriter::IntOption(
1800 QObject::tr( "(multiples of 512): Block size for .map files. Defaults "
1801 "to 512. MapInfo 15.2 and above creates .tab files with a "
1802 "blocksize of 16384 bytes. Any MapInfo version should be "
1803 "able to handle block sizes from 512 to 32256." ),
1804 512
1805 ) );
1806 layerOptions.insert( QStringLiteral( "BOUNDS" ), new QgsVectorFileWriter::StringOption(
1807 QObject::tr( "xmin,ymin,xmax,ymax: Define custom layer bounds to increase the "
1808 "accuracy of the coordinates. Note: the geometry of written "
1809 "features must be within the defined box." ),
1810 QString() // Default value
1811 ) );
1812 };
1813 insertMapInfoOptions( datasetOptions, layerOptions );
1814
1815 driverMetadata.insert( QStringLiteral( "MapInfo File" ),
1817 QStringLiteral( "Mapinfo" ),
1818 QObject::tr( "Mapinfo TAB" ),
1819 QStringLiteral( "*.tab" ),
1820 QStringLiteral( "tab" ),
1821 datasetOptions,
1822 layerOptions
1823 )
1824 );
1825 datasetOptions.clear();
1826 layerOptions.clear();
1827 insertMapInfoOptions( datasetOptions, layerOptions );
1828
1829 // QGIS internal alias for MIF files
1830 driverMetadata.insert( QStringLiteral( "MapInfo MIF" ),
1832 QStringLiteral( "Mapinfo" ),
1833 QObject::tr( "Mapinfo MIF" ),
1834 QStringLiteral( "*.mif" ),
1835 QStringLiteral( "mif" ),
1836 datasetOptions,
1837 layerOptions
1838 )
1839 );
1840
1841 // Microstation DGN
1842 datasetOptions.clear();
1843 layerOptions.clear();
1844
1845 datasetOptions.insert( QStringLiteral( "3D" ), new QgsVectorFileWriter::BoolOption(
1846 QObject::tr( "Determine whether 2D (seed_2d.dgn) or 3D (seed_3d.dgn) "
1847 "seed file should be used. This option is ignored if the SEED option is provided." ),
1848 false // Default value
1849 ) );
1850
1851 datasetOptions.insert( QStringLiteral( "SEED" ), new QgsVectorFileWriter::StringOption(
1852 QObject::tr( "Override the seed file to use." ),
1853 QString() // Default value
1854 ) );
1855
1856 datasetOptions.insert( QStringLiteral( "COPY_WHOLE_SEED_FILE" ), new QgsVectorFileWriter::BoolOption(
1857 QObject::tr( "Indicate whether the whole seed file should be copied. "
1858 "If not, only the first three elements will be copied." ),
1859 false // Default value
1860 ) );
1861
1862 datasetOptions.insert( QStringLiteral( "COPY_SEED_FILE_COLOR_TABLE" ), new QgsVectorFileWriter::BoolOption(
1863 QObject::tr( "Indicates whether the color table should be copied from the seed file." ),
1864 false // Default value
1865 ) );
1866
1867 datasetOptions.insert( QStringLiteral( "MASTER_UNIT_NAME" ), new QgsVectorFileWriter::StringOption(
1868 QObject::tr( "Override the master unit name from the seed file with "
1869 "the provided one or two character unit name." ),
1870 QString() // Default value
1871 ) );
1872
1873 datasetOptions.insert( QStringLiteral( "SUB_UNIT_NAME" ), new QgsVectorFileWriter::StringOption(
1874 QObject::tr( "Override the sub unit name from the seed file with the provided "
1875 "one or two character unit name." ),
1876 QString() // Default value
1877 ) );
1878
1879 datasetOptions.insert( QStringLiteral( "SUB_UNITS_PER_MASTER_UNIT" ), new QgsVectorFileWriter::IntOption(
1880 QObject::tr( "Override the number of subunits per master unit. "
1881 "By default the seed file value is used." ),
1882 0 // Default value
1883 ) );
1884
1885 datasetOptions.insert( QStringLiteral( "UOR_PER_SUB_UNIT" ), new QgsVectorFileWriter::IntOption(
1886 QObject::tr( "Override the number of UORs (Units of Resolution) "
1887 "per sub unit. By default the seed file value is used." ),
1888 0 // Default value
1889 ) );
1890
1891 datasetOptions.insert( QStringLiteral( "ORIGIN" ), new QgsVectorFileWriter::StringOption(
1892 QObject::tr( "ORIGIN=x,y,z: Override the origin of the design plane. "
1893 "By default the origin from the seed file is used." ),
1894 QString() // Default value
1895 ) );
1896
1897 driverMetadata.insert( QStringLiteral( "DGN" ),
1899 QStringLiteral( "Microstation DGN" ),
1900 QObject::tr( "Microstation DGN" ),
1901 QStringLiteral( "*.dgn" ),
1902 QStringLiteral( "dgn" ),
1903 datasetOptions,
1904 layerOptions
1905 )
1906 );
1907
1908 // S-57 Base file
1909 datasetOptions.clear();
1910 layerOptions.clear();
1911
1912 datasetOptions.insert( QStringLiteral( "UPDATES" ), new QgsVectorFileWriter::SetOption(
1913 QObject::tr( "Should update files be incorporated into the base data on the fly." ),
1914 QStringList()
1915 << QStringLiteral( "APPLY" )
1916 << QStringLiteral( "IGNORE" ),
1917 QStringLiteral( "APPLY" ) // Default value
1918 ) );
1919
1920 datasetOptions.insert( QStringLiteral( "SPLIT_MULTIPOINT" ), new QgsVectorFileWriter::BoolOption(
1921 QObject::tr( "Should multipoint soundings be split into many single point sounding features. "
1922 "Multipoint geometries are not well handled by many formats, "
1923 "so it can be convenient to split single sounding features with many points "
1924 "into many single point features." ),
1925 false // Default value
1926 ) );
1927
1928 datasetOptions.insert( QStringLiteral( "ADD_SOUNDG_DEPTH" ), new QgsVectorFileWriter::BoolOption(
1929 QObject::tr( "Should a DEPTH attribute be added on SOUNDG features and assign the depth "
1930 "of the sounding. This should only be enabled when SPLIT_MULTIPOINT is "
1931 "also enabled." ),
1932 false // Default value
1933 ) );
1934
1935 datasetOptions.insert( QStringLiteral( "RETURN_PRIMITIVES" ), new QgsVectorFileWriter::BoolOption(
1936 QObject::tr( "Should all the low level geometry primitives be returned as special "
1937 "IsolatedNode, ConnectedNode, Edge and Face layers." ),
1938 false // Default value
1939 ) );
1940
1941 datasetOptions.insert( QStringLiteral( "PRESERVE_EMPTY_NUMBERS" ), new QgsVectorFileWriter::BoolOption(
1942 QObject::tr( "If enabled, numeric attributes assigned an empty string as a value will "
1943 "be preserved as a special numeric value. This option should not generally "
1944 "be needed, but may be useful when translated S-57 to S-57 losslessly." ),
1945 false // Default value
1946 ) );
1947
1948 datasetOptions.insert( QStringLiteral( "LNAM_REFS" ), new QgsVectorFileWriter::BoolOption(
1949 QObject::tr( "Should LNAM and LNAM_REFS fields be attached to features capturing "
1950 "the feature to feature relationships in the FFPT group of the S-57 file." ),
1951 true // Default value
1952 ) );
1953
1954 datasetOptions.insert( QStringLiteral( "RETURN_LINKAGES" ), new QgsVectorFileWriter::BoolOption(
1955 QObject::tr( "Should additional attributes relating features to their underlying "
1956 "geometric primitives be attached. These are the values of the FSPT group, "
1957 "and are primarily needed when doing S-57 to S-57 translations." ),
1958 false // Default value
1959 ) );
1960
1961 datasetOptions.insert( QStringLiteral( "RECODE_BY_DSSI" ), new QgsVectorFileWriter::BoolOption(
1962 QObject::tr( "Should attribute values be recoded to UTF-8 from the character encoding "
1963 "specified in the S57 DSSI record." ),
1964 false // Default value
1965 ) );
1966
1967 // set OGR_S57_OPTIONS = "RETURN_PRIMITIVES=ON,RETURN_LINKAGES=ON,LNAM_REFS=ON"
1968
1969 driverMetadata.insert( QStringLiteral( "S57" ),
1971 QStringLiteral( "S-57 Base file" ),
1972 QObject::tr( "S-57 Base file" ),
1973 QStringLiteral( "*.000" ),
1974 QStringLiteral( "000" ),
1975 datasetOptions,
1976 layerOptions
1977 )
1978 );
1979
1980 // Spatial Data Transfer Standard [SDTS]
1981 datasetOptions.clear();
1982 layerOptions.clear();
1983
1984 driverMetadata.insert( QStringLiteral( "SDTS" ),
1986 QStringLiteral( "Spatial Data Transfer Standard [SDTS]" ),
1987 QObject::tr( "Spatial Data Transfer Standard [SDTS]" ),
1988 QStringLiteral( "*catd.ddf" ),
1989 QStringLiteral( "ddf" ),
1990 datasetOptions,
1991 layerOptions
1992 )
1993 );
1994
1995 // SQLite
1996 datasetOptions.clear();
1997 layerOptions.clear();
1998
1999 datasetOptions.insert( QStringLiteral( "METADATA" ), new QgsVectorFileWriter::BoolOption(
2000 QObject::tr( "Can be used to avoid creating the geometry_columns and spatial_ref_sys "
2001 "tables in a new database. By default these metadata tables are created "
2002 "when a new database is created." ),
2003 true // Default value
2004 ) );
2005
2006 // Will handle the SpatiaLite alias
2007 datasetOptions.insert( QStringLiteral( "SPATIALITE" ), new QgsVectorFileWriter::HiddenOption(
2008 QStringLiteral( "NO" )
2009 ) );
2010
2011
2012 datasetOptions.insert( QStringLiteral( "INIT_WITH_EPSG" ), new QgsVectorFileWriter::HiddenOption(
2013 QStringLiteral( "NO" )
2014 ) );
2015
2016 layerOptions.insert( QStringLiteral( "FORMAT" ), new QgsVectorFileWriter::SetOption(
2017 QObject::tr( "Controls the format used for the geometry column. Defaults to WKB. "
2018 "This is generally more space and processing efficient, but harder "
2019 "to inspect or use in simple applications than WKT (Well Known Text)." ),
2020 QStringList()
2021 << QStringLiteral( "WKB" )
2022 << QStringLiteral( "WKT" ),
2023 QStringLiteral( "WKB" ) // Default value
2024 ) );
2025
2026 layerOptions.insert( QStringLiteral( "LAUNDER" ), new QgsVectorFileWriter::BoolOption(
2027 QObject::tr( "Controls whether layer and field names will be laundered for easier use "
2028 "in SQLite. Laundered names will be converted to lower case and some special "
2029 "characters(' - #) will be changed to underscores." ),
2030 true // Default value
2031 ) );
2032
2033 layerOptions.insert( QStringLiteral( "SPATIAL_INDEX" ), new QgsVectorFileWriter::HiddenOption(
2034 QStringLiteral( "NO" )
2035 ) );
2036
2037 layerOptions.insert( QStringLiteral( "COMPRESS_GEOM" ), new QgsVectorFileWriter::HiddenOption(
2038 QStringLiteral( "NO" )
2039 ) );
2040
2041 layerOptions.insert( QStringLiteral( "SRID" ), new QgsVectorFileWriter::HiddenOption(
2042 QString()
2043 ) );
2044
2045 layerOptions.insert( QStringLiteral( "COMPRESS_COLUMNS" ), new QgsVectorFileWriter::StringOption(
2046 QObject::tr( "column_name1[,column_name2, …] A list of (String) columns that "
2047 "must be compressed with ZLib DEFLATE algorithm. This might be beneficial "
2048 "for databases that have big string blobs. However, use with care, since "
2049 "the value of such columns will be seen as compressed binary content with "
2050 "other SQLite utilities (or previous OGR versions). With OGR, when inserting, "
2051 "modifying or querying compressed columns, compression/decompression is "
2052 "done transparently. However, such columns cannot be (easily) queried with "
2053 "an attribute filter or WHERE clause. Note: in table definition, such columns "
2054 "have the 'VARCHAR_deflate' declaration type." ),
2055 QString() // Default value
2056 ) );
2057
2058 driverMetadata.insert( QStringLiteral( "SQLite" ),
2060 QStringLiteral( "SQLite" ),
2061 QObject::tr( "SQLite" ),
2062 QStringLiteral( "*.sqlite" ),
2063 QStringLiteral( "sqlite" ),
2064 datasetOptions,
2065 layerOptions,
2066 QStringLiteral( "UTF-8" )
2067 )
2068 );
2069
2070 // SpatiaLite
2071 datasetOptions.clear();
2072 layerOptions.clear();
2073
2074 datasetOptions.insert( QStringLiteral( "METADATA" ), new QgsVectorFileWriter::BoolOption(
2075 QObject::tr( "Can be used to avoid creating the geometry_columns and spatial_ref_sys "
2076 "tables in a new database. By default these metadata tables are created "
2077 "when a new database is created." ),
2078 true // Default value
2079 ) );
2080
2081 datasetOptions.insert( QStringLiteral( "SPATIALITE" ), new QgsVectorFileWriter::HiddenOption(
2082 QStringLiteral( "YES" )
2083 ) );
2084
2085 datasetOptions.insert( QStringLiteral( "INIT_WITH_EPSG" ), new QgsVectorFileWriter::BoolOption(
2086 QObject::tr( "Insert the content of the EPSG CSV files into the spatial_ref_sys table. "
2087 "Set to NO for regular SQLite databases." ),
2088 true // Default value
2089 ) );
2090
2091 layerOptions.insert( QStringLiteral( "FORMAT" ), new QgsVectorFileWriter::HiddenOption(
2092 QStringLiteral( "SPATIALITE" )
2093 ) );
2094
2095 layerOptions.insert( QStringLiteral( "LAUNDER" ), new QgsVectorFileWriter::BoolOption(
2096 QObject::tr( "Controls whether layer and field names will be laundered for easier use "
2097 "in SQLite. Laundered names will be converted to lower case and some special "
2098 "characters(' - #) will be changed to underscores." ),
2099 true // Default value
2100 ) );
2101
2102 layerOptions.insert( QStringLiteral( "SPATIAL_INDEX" ), new QgsVectorFileWriter::BoolOption(
2103 QObject::tr( "If the database is of the SpatiaLite flavor, and if OGR is linked "
2104 "against libspatialite, this option can be used to control if a spatial "
2105 "index must be created." ),
2106 true // Default value
2107 ) );
2108
2109 layerOptions.insert( QStringLiteral( "COMPRESS_GEOM" ), new QgsVectorFileWriter::BoolOption(
2110 QObject::tr( "If the format of the geometry BLOB is of the SpatiaLite flavor, "
2111 "this option can be used to control if the compressed format for "
2112 "geometries (LINESTRINGs, POLYGONs) must be used." ),
2113 false // Default value
2114 ) );
2115
2116 layerOptions.insert( QStringLiteral( "SRID" ), new QgsVectorFileWriter::StringOption(
2117 QObject::tr( "Used to force the SRID number of the SRS associated with the layer. "
2118 "When this option isn't specified and that a SRS is associated with the "
2119 "layer, a search is made in the spatial_ref_sys to find a match for the "
2120 "SRS, and, if there is no match, a new entry is inserted for the SRS in "
2121 "the spatial_ref_sys table. When the SRID option is specified, this "
2122 "search (and the eventual insertion of a new entry) will not be done: "
2123 "the specified SRID is used as such." ),
2124 QString() // Default value
2125 ) );
2126
2127 layerOptions.insert( QStringLiteral( "COMPRESS_COLUMNS" ), new QgsVectorFileWriter::StringOption(
2128 QObject::tr( "column_name1[,column_name2, …] A list of (String) columns that "
2129 "must be compressed with ZLib DEFLATE algorithm. This might be beneficial "
2130 "for databases that have big string blobs. However, use with care, since "
2131 "the value of such columns will be seen as compressed binary content with "
2132 "other SQLite utilities (or previous OGR versions). With OGR, when inserting, "
2133 "modifying or queryings compressed columns, compression/decompression is "
2134 "done transparently. However, such columns cannot be (easily) queried with "
2135 "an attribute filter or WHERE clause. Note: in table definition, such columns "
2136 "have the 'VARCHAR_deflate' declaration type." ),
2137 QString() // Default value
2138 ) );
2139
2140 driverMetadata.insert( QStringLiteral( "SpatiaLite" ),
2142 QStringLiteral( "SpatiaLite" ),
2143 QObject::tr( "SpatiaLite" ),
2144 QStringLiteral( "*.sqlite" ),
2145 QStringLiteral( "sqlite" ),
2146 datasetOptions,
2147 layerOptions,
2148 QStringLiteral( "UTF-8" )
2149 )
2150 );
2151 // AutoCAD DXF
2152 datasetOptions.clear();
2153 layerOptions.clear();
2154
2155 datasetOptions.insert( QStringLiteral( "HEADER" ), new QgsVectorFileWriter::StringOption(
2156 QObject::tr( "Override the header file used - in place of header.dxf." ),
2157 QString() // Default value
2158 ) );
2159
2160 datasetOptions.insert( QStringLiteral( "TRAILER" ), new QgsVectorFileWriter::StringOption(
2161 QObject::tr( "Override the trailer file used - in place of trailer.dxf." ),
2162 QString() // Default value
2163 ) );
2164
2165#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,11,0)
2166 datasetOptions.insert( QStringLiteral( "INSUNITS" ), new QgsVectorFileWriter::SetOption(
2167 QObject::tr( "Drawing units for the model space ($INSUNITS system variable)." ),
2168 QStringList()
2169 << QStringLiteral( "AUTO" )
2170 << QStringLiteral( "HEADER_VALUE" )
2171 << QStringLiteral( "UNITLESS" )
2172 << QStringLiteral( "INCHES" )
2173 << QStringLiteral( "FEET" )
2174 << QStringLiteral( "MILLIMETERS" )
2175 << QStringLiteral( "CENTIMETERS" )
2176 << QStringLiteral( "METERS" )
2177 << QStringLiteral( "US_SURVEY_FEET" ),
2178 QStringLiteral( "AUTO" ) // Default value
2179 ) );
2180
2181 datasetOptions.insert( QStringLiteral( "MEASUREMENT" ), new QgsVectorFileWriter::SetOption(
2182 QObject::tr( "Whether the current drawing uses imperial or metric hatch "
2183 "pattern and linetype ($MEASUREMENT system variable)." ),
2184 QStringList()
2185 << QStringLiteral( "HEADER_VALUE" )
2186 << QStringLiteral( "IMPERIAL" )
2187 << QStringLiteral( "METRIC" ),
2188 QStringLiteral( "HEADER_VALUE" ) // Default value
2189 ) );
2190#endif
2191
2192 driverMetadata.insert( QStringLiteral( "DXF" ),
2194 QStringLiteral( "AutoCAD DXF" ),
2195 QObject::tr( "AutoCAD DXF" ),
2196 QStringLiteral( "*.dxf" ),
2197 QStringLiteral( "dxf" ),
2198 datasetOptions,
2199 layerOptions
2200 )
2201 );
2202
2203 // Geoconcept
2204 datasetOptions.clear();
2205 layerOptions.clear();
2206
2207 datasetOptions.insert( QStringLiteral( "EXTENSION" ), new QgsVectorFileWriter::SetOption(
2208 QObject::tr( "Indicates the GeoConcept export file extension. "
2209 "TXT was used by earlier releases of GeoConcept. GXT is currently used." ),
2210 QStringList()
2211 << QStringLiteral( "GXT" )
2212 << QStringLiteral( "TXT" ),
2213 QStringLiteral( "GXT" ) // Default value
2214 ) );
2215
2216 datasetOptions.insert( QStringLiteral( "CONFIG" ), new QgsVectorFileWriter::StringOption(
2217 QObject::tr( "Path to the GCT: the GCT file describes the GeoConcept types definitions: "
2218 "In this file, every line must start with //# followed by a keyword. "
2219 "Lines starting with // are comments." ),
2220 QString() // Default value
2221 ) );
2222
2223 datasetOptions.insert( QStringLiteral( "FEATURETYPE" ), new QgsVectorFileWriter::StringOption(
2224 QObject::tr( "Defines the feature to be created. The TYPE corresponds to one of the Name "
2225 "found in the GCT file for a type section. The SUBTYPE corresponds to one of "
2226 "the Name found in the GCT file for a sub-type section within the previous "
2227 "type section." ),
2228 QString() // Default value
2229 ) );
2230
2231 driverMetadata.insert( QStringLiteral( "Geoconcept" ),
2233 QStringLiteral( "Geoconcept" ),
2234 QObject::tr( "Geoconcept" ),
2235 QStringLiteral( "*.gxt *.txt" ),
2236 QStringLiteral( "gxt" ),
2237 datasetOptions,
2238 layerOptions
2239 )
2240 );
2241
2242 // ESRI OpenFileGDB
2243 datasetOptions.clear();
2244 layerOptions.clear();
2245
2246#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,9,0)
2247 layerOptions.insert( QStringLiteral( "TARGET_ARCGIS_VERSION" ), new QgsVectorFileWriter::SetOption(
2248 QObject::tr( "Selects which ArcGIS version this dataset should be compatible with. ALL is used by default and means any ArcGIS 10.x or ArcGIS Pro version. Using ARCGIS_PRO_3_2_OR_LATER is required to export 64-bit integer fields as such, otherwise they will be converted as Real fields. ARCGIS_PRO_3_2_OR_LATER also supports proper Date and Time field types." ),
2249 QStringList()
2250 << QStringLiteral( "ALL" )
2251 << QStringLiteral( "ARCGIS_PRO_3_2_OR_LATER" ),
2252 QStringLiteral( "ALL" ) // Default value
2253 ) );
2254#endif
2255
2256 layerOptions.insert( QStringLiteral( "FEATURE_DATASET" ), new QgsVectorFileWriter::StringOption(
2257 QObject::tr( "When this option is set, the new layer will be created inside the named "
2258 "FeatureDataset folder. If the folder does not already exist, it will be created." ),
2259 QString() // Default value
2260 ) );
2261
2262 layerOptions.insert( QStringLiteral( "LAYER_ALIAS" ), new QgsVectorFileWriter::StringOption(
2263 QObject::tr( "Set layer name alias." ),
2264 QString() // Default value
2265 ) );
2266
2267 layerOptions.insert( QStringLiteral( "GEOMETRY_NAME" ), new QgsVectorFileWriter::StringOption(
2268 QObject::tr( "Set name of geometry column in new layer. Defaults to 'SHAPE'." ),
2269 QStringLiteral( "SHAPE" ) // Default value
2270 ) );
2271
2272 layerOptions.insert( QStringLiteral( "GEOMETRY_NULLABLE" ), new QgsVectorFileWriter::BoolOption(
2273 QObject::tr( "Whether the values of the geometry column can be NULL. Can be set to NO so that geometry is required. Default to 'YES'." ),
2274 true // Default value
2275 ) );
2276
2277 layerOptions.insert( QStringLiteral( "FID" ), new QgsVectorFileWriter::StringOption(
2278 QObject::tr( "Name of the OID column to create. Defaults to 'OBJECTID'." ),
2279 QStringLiteral( "OBJECTID" ) // Default value
2280 ) );
2281
2282 // TODO missing options -- requires double option type
2283 // XYTOLERANCE
2284 // ZTOLERANCE
2285 // MTOLERANCE
2286 // XORIGIN
2287 // YORIGIN
2288 // ZORIGIN
2289 // MORIGIN
2290 // XYSCALE
2291 // ZSCALE
2292 // ZORIGIN
2293
2294 layerOptions.insert( QStringLiteral( "COLUMN_TYPES" ), new QgsVectorFileWriter::StringOption(
2295 QObject::tr( "A list of strings of format field_name=fgdb_field_type (separated by comma) to force the FileGDB column type of fields to be created." ),
2296 QString( ) // Default value
2297 ) );
2298
2299 layerOptions.insert( QStringLiteral( "DOCUMENTATION" ), new QgsVectorFileWriter::StringOption(
2300 QObject::tr( "XML documentation for the layer." ),
2301 QString( ) // Default value
2302 ) );
2303 layerOptions.insert( QStringLiteral( "CONFIGURATION_KEYWORD" ), new QgsVectorFileWriter::SetOption(
2304 QObject::tr( "Customize how data is stored. By default text in UTF-8 and data up to 1TB." ),
2305 {QStringLiteral( "DEFAULTS" ), QStringLiteral( "MAX_FILE_SIZE_4GB" ), QStringLiteral( "MAX_FILE_SIZE_256TB" )},
2306 QStringLiteral( "DEFAULTS" ), // Default value
2307 false // Allow None
2308 ) );
2309
2310 layerOptions.insert( QStringLiteral( "CREATE_SHAPE_AREA_AND_LENGTH_FIELDS" ), new QgsVectorFileWriter::BoolOption(
2311 QObject::tr( " Defaults to NO (through CreateLayer() API). When this option is set, a Shape_Area and Shape_Length special fields will be created for polygonal layers (Shape_Length only for linear layers). These fields will automatically be populated with the feature’s area or length whenever a new feature is added to the dataset or an existing feature is amended. When using ogr2ogr with a source layer that has Shape_Area/Shape_Length special fields, and this option is not explicitly specified, it will be automatically set, so that the resulting FileGeodatabase has those fields properly tagged." ),
2312 false // Default value
2313 ) );
2314
2315 driverMetadata.insert( QStringLiteral( "OpenFileGDB" ),
2317 QStringLiteral( "ESRI File Geodatabase" ),
2318 QObject::tr( "ESRI File Geodatabase" ),
2319 QStringLiteral( "*.gdb" ),
2320 QStringLiteral( "gdb" ),
2321 datasetOptions,
2322 layerOptions,
2323 QStringLiteral( "UTF-8" )
2324 )
2325 );
2326
2327#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(3,11,0)
2328 // ESRI FileGDB (using ESRI FileGDB API SDK)
2329 datasetOptions.clear();
2330 layerOptions.clear();
2331
2332 layerOptions.insert( QStringLiteral( "FEATURE_DATASET" ), new QgsVectorFileWriter::StringOption(
2333 QObject::tr( "When this option is set, the new layer will be created inside the named "
2334 "FeatureDataset folder. If the folder does not already exist, it will be created." ),
2335 QString() // Default value
2336 ) );
2337
2338 layerOptions.insert( QStringLiteral( "GEOMETRY_NAME" ), new QgsVectorFileWriter::StringOption(
2339 QObject::tr( "Set name of geometry column in new layer. Defaults to 'SHAPE'." ),
2340 QStringLiteral( "SHAPE" ) // Default value
2341 ) );
2342
2343 layerOptions.insert( QStringLiteral( "FID" ), new QgsVectorFileWriter::StringOption(
2344 QObject::tr( "Name of the OID column to create. Defaults to 'OBJECTID'." ),
2345 QStringLiteral( "OBJECTID" ) // Default value
2346 ) );
2347
2348 driverMetadata.insert( QStringLiteral( "FileGDB" ),
2350 QStringLiteral( "ESRI FileGDB" ),
2351 QObject::tr( "ESRI FileGDB" ),
2352 QStringLiteral( "*.gdb" ),
2353 QStringLiteral( "gdb" ),
2354 datasetOptions,
2355 layerOptions,
2356 QStringLiteral( "UTF-8" )
2357 )
2358 );
2359#endif
2360
2361 // XLSX
2362 datasetOptions.clear();
2363 layerOptions.clear();
2364
2365 layerOptions.insert( QStringLiteral( "OGR_XLSX_FIELD_TYPES" ), new QgsVectorFileWriter::SetOption(
2366 QObject::tr( "By default, the driver will try to detect the data type of fields. If set "
2367 "to STRING, all fields will be of String type." ),
2368 QStringList()
2369 << QStringLiteral( "AUTO" )
2370 << QStringLiteral( "STRING" ),
2371 QStringLiteral( "AUTO" ), // Default value
2372 false // Allow None
2373 ) );
2374
2375 layerOptions.insert( QStringLiteral( "OGR_XLSX_HEADERS" ), new QgsVectorFileWriter::SetOption(
2376 QObject::tr( "By default, the driver will read the first lines of each sheet to detect "
2377 "if the first line might be the name of columns. If set to FORCE, the driver "
2378 "will consider the first line as the header line. If set to "
2379 "DISABLE, it will be considered as the first feature. Otherwise "
2380 "auto-detection will occur." ),
2381 QStringList()
2382 << QStringLiteral( "FORCE" )
2383 << QStringLiteral( "DISABLE" )
2384 << QStringLiteral( "AUTO" ),
2385 QStringLiteral( "AUTO" ), // Default value
2386 false // Allow None
2387 ) );
2388
2389 driverMetadata.insert( QStringLiteral( "XLSX" ),
2391 QStringLiteral( "MS Office Open XML spreadsheet" ),
2392 QObject::tr( "MS Office Open XML spreadsheet [XLSX]" ),
2393 QStringLiteral( "*.xlsx" ),
2394 QStringLiteral( "xlsx" ),
2395 datasetOptions,
2396 layerOptions,
2397 QStringLiteral( "UTF-8" )
2398 )
2399 );
2400
2401 // ODS
2402 datasetOptions.clear();
2403 layerOptions.clear();
2404
2405 layerOptions.insert( QStringLiteral( "OGR_ODS_FIELD_TYPES" ), new QgsVectorFileWriter::SetOption(
2406 QObject::tr( "By default, the driver will try to detect the data type of fields. If set "
2407 "to STRING, all fields will be of String type." ),
2408 QStringList()
2409 << QStringLiteral( "AUTO" )
2410 << QStringLiteral( "STRING" ),
2411 QStringLiteral( "AUTO" ), // Default value
2412 false // Allow None
2413 ) );
2414
2415 layerOptions.insert( QStringLiteral( "OGR_ODS_HEADERS" ), new QgsVectorFileWriter::SetOption(
2416 QObject::tr( "By default, the driver will read the first lines of each sheet to detect "
2417 "if the first line might be the name of columns. If set to FORCE, the driver "
2418 "will consider the first line as the header line. If set to "
2419 "DISABLE, it will be considered as the first feature. Otherwise "
2420 "auto-detection will occur." ),
2421 QStringList()
2422 << QStringLiteral( "FORCE" )
2423 << QStringLiteral( "DISABLE" )
2424 << QStringLiteral( "AUTO" ),
2425 QStringLiteral( "AUTO" ), // Default value
2426 false // Allow None
2427 ) );
2428
2429 driverMetadata.insert( QStringLiteral( "ODS" ),
2431 QStringLiteral( "Open Document Spreadsheet" ),
2432 QObject::tr( "Open Document Spreadsheet [ODS]" ),
2433 QStringLiteral( "*.ods" ),
2434 QStringLiteral( "ods" ),
2435 datasetOptions,
2436 layerOptions,
2437 QStringLiteral( "UTF-8" )
2438 )
2439 );
2440
2441 // Parquet
2442 datasetOptions.clear();
2443 layerOptions.clear();
2444
2445 layerOptions.insert( QStringLiteral( "COMPRESSION" ), new QgsVectorFileWriter::SetOption(
2446 QObject::tr( "Compression method." ),
2447 QStringList()
2448 << QStringLiteral( "UNCOMPRESSED" )
2449 << QStringLiteral( "SNAPPY" ),
2450 QStringLiteral( "SNAPPY" ), // Default value
2451 false // Allow None
2452 ) );
2453
2454 layerOptions.insert( QStringLiteral( "GEOMETRY_ENCODING" ), new QgsVectorFileWriter::SetOption(
2455 QObject::tr( "Geometry encoding." ),
2456 QStringList()
2457 << QStringLiteral( "WKB" )
2458 << QStringLiteral( "WKT" )
2459 << QStringLiteral( "GEOARROW" ),
2460 QStringLiteral( "WKB" ), // Default value
2461 false // Allow None
2462 ) );
2463
2464 layerOptions.insert( QStringLiteral( "ROW_GROUP_SIZE" ), new QgsVectorFileWriter::IntOption(
2465 QObject::tr( "Maximum number of rows per group." ),
2466 65536 // Default value
2467 ) );
2468
2469 layerOptions.insert( QStringLiteral( "FID" ), new QgsVectorFileWriter::StringOption(
2470 QObject::tr( "Name for the feature identifier column" ),
2471 QString() // Default value
2472 ) );
2473
2474 layerOptions.insert( QStringLiteral( "GEOMETRY_NAME" ), new QgsVectorFileWriter::StringOption(
2475 QObject::tr( "Name for the geometry column" ),
2476 QStringLiteral( "geometry" ) // Default value
2477 ) );
2478
2479 layerOptions.insert( QStringLiteral( "EDGES" ), new QgsVectorFileWriter::SetOption(
2480 QObject::tr( "Name of the coordinate system for the edges." ),
2481 QStringList()
2482 << QStringLiteral( "PLANAR" )
2483 << QStringLiteral( "SPHERICAL" ),
2484 QStringLiteral( "PLANAR" ), // Default value
2485 false // Allow None
2486 ) );
2487
2488 driverMetadata.insert( QStringLiteral( "Parquet" ),
2490 QStringLiteral( "(Geo)Parquet" ),
2491 QObject::tr( "(Geo)Parquet" ),
2492 QStringLiteral( "*.parquet" ),
2493 QStringLiteral( "parquet" ),
2494 datasetOptions,
2495 layerOptions,
2496 QStringLiteral( "UTF-8" )
2497 )
2498 );
2499
2500 // PGDump
2501 datasetOptions.clear();
2502 layerOptions.clear();
2503
2504 datasetOptions.insert( QStringLiteral( "LINEFORMAT" ), new QgsVectorFileWriter::SetOption(
2505 QObject::tr( "Line termination character sequence." ),
2506 QStringList()
2507 << QStringLiteral( "CRLF" )
2508 << QStringLiteral( "LF" ),
2509 QStringLiteral( "LF" ), // Default value
2510 false // Allow None
2511 ) );
2512
2513
2514 layerOptions.insert( QStringLiteral( "GEOM_TYPE" ), new QgsVectorFileWriter::SetOption(
2515 QObject::tr( "Format of geometry columns." ),
2516 QStringList()
2517 << QStringLiteral( "geometry" )
2518 << QStringLiteral( "geography" ),
2519 QStringLiteral( "geometry" ), // Default value
2520 false // Allow None
2521 ) );
2522
2523 layerOptions.insert( QStringLiteral( "LAUNDER" ), new QgsVectorFileWriter::BoolOption(
2524 QObject::tr( "Controls whether layer and field names will be laundered for easier use. "
2525 "Laundered names will be converted to lower case and some special "
2526 "characters(' - #) will be changed to underscores." ),
2527 true // Default value
2528 ) );
2529
2530 layerOptions.insert( QStringLiteral( "GEOMETRY_NAME" ), new QgsVectorFileWriter::StringOption(
2531 QObject::tr( "Name for the geometry column. Defaults to wkb_geometry "
2532 "for GEOM_TYPE=geometry or the_geog for GEOM_TYPE=geography" ) ) );
2533
2534 layerOptions.insert( QStringLiteral( "SCHEMA" ), new QgsVectorFileWriter::StringOption(
2535 QObject::tr( "Name of schema into which to create the new table" ) ) );
2536
2537 layerOptions.insert( QStringLiteral( "CREATE_SCHEMA" ), new QgsVectorFileWriter::BoolOption(
2538 QObject::tr( "Whether to explicitly emit the CREATE SCHEMA statement to create the specified schema." ),
2539 true // Default value
2540 ) );
2541
2542 layerOptions.insert( QStringLiteral( "CREATE_TABLE" ), new QgsVectorFileWriter::BoolOption(
2543 QObject::tr( "Whether to explicitly recreate the table if necessary." ),
2544 true // Default value
2545 ) );
2546
2547 layerOptions.insert( QStringLiteral( "DROP_TABLE" ), new QgsVectorFileWriter::SetOption(
2548 QObject::tr( "Whether to explicitly destroy tables before recreating them." ),
2549 QStringList()
2550 << QStringLiteral( "YES" )
2551 << QStringLiteral( "NO" )
2552 << QStringLiteral( "IF_EXISTS" ),
2553 QStringLiteral( "YES" ), // Default value
2554 false // Allow None
2555 ) );
2556
2557 layerOptions.insert( QStringLiteral( "SRID" ), new QgsVectorFileWriter::StringOption(
2558 QObject::tr( "Used to force the SRID number of the SRS associated with the layer. "
2559 "When this option isn't specified and that a SRS is associated with the "
2560 "layer, a search is made in the spatial_ref_sys to find a match for the "
2561 "SRS, and, if there is no match, a new entry is inserted for the SRS in "
2562 "the spatial_ref_sys table. When the SRID option is specified, this "
2563 "search (and the eventual insertion of a new entry) will not be done: "
2564 "the specified SRID is used as such." ),
2565 QString() // Default value
2566 ) );
2567
2568 layerOptions.insert( QStringLiteral( "POSTGIS_VERSION" ), new QgsVectorFileWriter::StringOption(
2569 QObject::tr( "Can be set to 2.0 or 2.2 for PostGIS 2.0/2.2 compatibility. "
2570 "Important to set it correctly if using non-linear geometry types" ),
2571 QStringLiteral( "2.2" ) // Default value
2572 ) );
2573
2574 driverMetadata.insert( QStringLiteral( "PGDUMP" ),
2576 QStringLiteral( "PostgreSQL SQL dump" ),
2577 QObject::tr( "PostgreSQL SQL dump" ),
2578 QStringLiteral( "*.sql" ),
2579 QStringLiteral( "sql" ),
2580 datasetOptions,
2581 layerOptions,
2582 QStringLiteral( "UTF-8" )
2583 )
2584 );
2585
2586 }
2587
2588 QgsVectorFileWriterMetadataContainer( const QgsVectorFileWriterMetadataContainer &other ) = delete;
2589 QgsVectorFileWriterMetadataContainer &operator=( const QgsVectorFileWriterMetadataContainer &other ) = delete;
2590 ~QgsVectorFileWriterMetadataContainer()
2591 {
2592 for ( auto it = driverMetadata.constBegin(); it != driverMetadata.constEnd(); ++it )
2593 {
2594 for ( auto optionIt = it.value().driverOptions.constBegin(); optionIt != it.value().driverOptions.constEnd(); ++optionIt )
2595 delete optionIt.value();
2596 for ( auto optionIt = it.value().layerOptions.constBegin(); optionIt != it.value().layerOptions.constEnd(); ++optionIt )
2597 delete optionIt.value();
2598 }
2599 }
2600
2601 QMap<QString, QgsVectorFileWriter::MetaData> driverMetadata;
2602
2603};
2605
2606bool QgsVectorFileWriter::driverMetadata( const QString &driverName, QgsVectorFileWriter::MetaData &driverMetadata )
2607{
2608 static QgsVectorFileWriterMetadataContainer sDriverMetadata;
2609 QMap<QString, MetaData>::ConstIterator it = sDriverMetadata.driverMetadata.constBegin();
2610
2611 for ( ; it != sDriverMetadata.driverMetadata.constEnd(); ++it )
2612 {
2613 if ( it.key() == QLatin1String( "PGDUMP" ) &&
2614 driverName != QLatin1String( "PGDUMP" ) &&
2615 driverName != QLatin1String( "PostgreSQL SQL dump" ) )
2616 {
2617 // We do not want the 'PG' driver to be wrongly identified with PGDUMP
2618 continue;
2619 }
2620 if ( it.key().startsWith( driverName ) || it.value().longName.startsWith( driverName ) )
2621 {
2622 driverMetadata = it.value();
2623 return true;
2624 }
2625 }
2626
2627 return false;
2628}
2629
2630QStringList QgsVectorFileWriter::defaultDatasetOptions( const QString &driverName )
2631{
2632 MetaData metadata;
2633 bool ok = driverMetadata( driverName, metadata );
2634 if ( !ok )
2635 return QStringList();
2636 return concatenateOptions( metadata.driverOptions );
2637}
2638
2639QStringList QgsVectorFileWriter::defaultLayerOptions( const QString &driverName )
2640{
2641 MetaData metadata;
2642 bool ok = driverMetadata( driverName, metadata );
2643 if ( !ok )
2644 return QStringList();
2645 return concatenateOptions( metadata.layerOptions );
2646}
2647
2649{
2650
2651 OGRwkbGeometryType ogrType = static_cast<OGRwkbGeometryType>( type );
2652
2654 {
2655 ogrType = static_cast<OGRwkbGeometryType>( QgsWkbTypes::to25D( type ) );
2656 }
2657 return ogrType;
2658}
2659
2664
2666{
2667 return mErrorMessage;
2668}
2669
2671{
2672 return mOgrDriverName;
2673}
2674
2676{
2677 return mOgrDriverLongName;
2678}
2679
2681{
2682 return mCapabilities;
2683}
2684
2689
2691{
2692 QgsFeatureList::iterator fIt = features.begin();
2693 bool result = true;
2694 for ( ; fIt != features.end(); ++fIt )
2695 {
2696 result = result && addFeatureWithStyle( *fIt, nullptr, Qgis::DistanceUnit::Meters );
2697 }
2698 return result;
2699}
2700
2702{
2703 return mErrorMessage;
2704}
2705
2707{
2708 // create the feature
2709 gdal::ogr_feature_unique_ptr poFeature = createFeature( feature );
2710 if ( !poFeature )
2711 return false;
2712
2713 //add OGR feature style type
2715 {
2716 mRenderContext.expressionContext().setFeature( feature );
2717 //SymbolLayerSymbology: concatenate ogr styles of all symbollayers
2718 QgsSymbolList symbols = renderer->symbolsForFeature( feature, mRenderContext );
2719 QString styleString;
2720 QString currentStyle;
2721
2722 QgsSymbolList::const_iterator symbolIt = symbols.constBegin();
2723 for ( ; symbolIt != symbols.constEnd(); ++symbolIt )
2724 {
2725 int nSymbolLayers = ( *symbolIt )->symbolLayerCount();
2726 for ( int i = 0; i < nSymbolLayers; ++i )
2727 {
2728#if 0
2729 QMap< QgsSymbolLayer *, QString >::const_iterator it = mSymbolLayerTable.find( ( *symbolIt )->symbolLayer( i ) );
2730 if ( it == mSymbolLayerTable.constEnd() )
2731 {
2732 continue;
2733 }
2734#endif
2735 double mmsf = mmScaleFactor( mSymbologyScale, ( *symbolIt )->outputUnit(), outputUnit );
2736 double musf = mapUnitScaleFactor( mSymbologyScale, ( *symbolIt )->outputUnit(), outputUnit );
2737
2738 currentStyle = ( *symbolIt )->symbolLayer( i )->ogrFeatureStyle( mmsf, musf );//"@" + it.value();
2739
2740 switch ( mSymbologyExport )
2741 {
2743 {
2744 if ( symbolIt != symbols.constBegin() || i != 0 )
2745 {
2746 styleString.append( ';' );
2747 }
2748 styleString.append( currentStyle );
2749 break;
2750 }
2752 {
2753 OGR_F_SetStyleString( poFeature.get(), currentStyle.toLocal8Bit().constData() );
2754 if ( !writeFeature( mLayer, poFeature.get() ) )
2755 {
2756 return false;
2757 }
2758 break;
2759 }
2760
2762 break;
2763 }
2764 }
2765 }
2766 OGR_F_SetStyleString( poFeature.get(), styleString.toLocal8Bit().constData() );
2767 }
2768
2769 switch ( mSymbologyExport )
2770 {
2773 {
2774 if ( !writeFeature( mLayer, poFeature.get() ) )
2775 {
2776 return false;
2777 }
2778 break;
2779 }
2780
2782 break;
2783 }
2784
2785 return true;
2786}
2787
2788gdal::ogr_feature_unique_ptr QgsVectorFileWriter::createFeature( const QgsFeature &feature )
2789{
2790 QgsLocaleNumC l; // Make sure the decimal delimiter is a dot
2791 Q_UNUSED( l )
2792
2793 gdal::ogr_feature_unique_ptr poFeature( OGR_F_Create( OGR_L_GetLayerDefn( mLayer ) ) );
2794
2795 // attribute handling
2796 for ( QMap<int, int>::const_iterator it = mAttrIdxToOgrIdx.constBegin(); it != mAttrIdxToOgrIdx.constEnd(); ++it )
2797 {
2798 int fldIdx = it.key();
2799 int ogrField = it.value();
2800
2801 QVariant attrValue = feature.attribute( fldIdx );
2802 QgsField field = mFields.at( fldIdx );
2803
2804 if ( feature.isUnsetValue( fldIdx ) )
2805 {
2806 OGR_F_UnsetField( poFeature.get(), ogrField );
2807 continue;
2808 }
2809 else if ( QgsVariantUtils::isNull( attrValue ) )
2810 {
2811// Starting with GDAL 2.2, there are 2 concepts: unset fields and null fields
2812// whereas previously there was only unset fields. For a GeoJSON output,
2813// leaving a field unset will cause it to not appear at all in the output
2814// feature.
2815// When all features of a layer have a field unset, this would cause the
2816// field to not be present at all in the output, and thus on reading to
2817// have disappeared. #16812
2818#ifdef OGRNullMarker
2819 OGR_F_SetFieldNull( poFeature.get(), ogrField );
2820#endif
2821 continue;
2822 }
2823
2825 {
2826 field = mFieldValueConverter->fieldDefinition( field );
2827 attrValue = mFieldValueConverter->convert( fldIdx, attrValue );
2828 }
2829
2830 // Check type compatibility before passing attribute value to OGR
2831 QString errorMessage;
2832 if ( ! field.convertCompatible( attrValue, &errorMessage ) )
2833 {
2834 mErrorMessage = QObject::tr( "Error converting value (%1) for attribute field %2: %3" )
2835 .arg( feature.attribute( fldIdx ).toString(),
2836 mFields.at( fldIdx ).name(), errorMessage );
2837 QgsMessageLog::logMessage( mErrorMessage, QObject::tr( "OGR" ) );
2839 return nullptr;
2840 }
2841
2842 switch ( field.type() )
2843 {
2844 case QMetaType::Type::Int:
2845 OGR_F_SetFieldInteger( poFeature.get(), ogrField, attrValue.toInt() );
2846 break;
2847 case QMetaType::Type::LongLong:
2848 OGR_F_SetFieldInteger64( poFeature.get(), ogrField, attrValue.toLongLong() );
2849 break;
2850 case QMetaType::Type::Bool:
2851 OGR_F_SetFieldInteger( poFeature.get(), ogrField, attrValue.toInt() );
2852 break;
2853 case QMetaType::Type::QString:
2854 OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( attrValue.toString() ).constData() );
2855 break;
2856 case QMetaType::Type::Double:
2857 OGR_F_SetFieldDouble( poFeature.get(), ogrField, attrValue.toDouble() );
2858 break;
2859 case QMetaType::Type::QDate:
2860 OGR_F_SetFieldDateTime( poFeature.get(), ogrField,
2861 attrValue.toDate().year(),
2862 attrValue.toDate().month(),
2863 attrValue.toDate().day(),
2864 0, 0, 0, 0 );
2865 break;
2866 case QMetaType::Type::QDateTime:
2867 if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
2868 {
2869 OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( attrValue.toDateTime().toString( QStringLiteral( "yyyy/MM/dd hh:mm:ss.zzz" ) ) ).constData() );
2870 }
2871 else
2872 {
2873 const QDateTime dt = attrValue.toDateTime();
2874 const QDate date = dt.date();
2875 const QTime time = dt.time();
2876 OGR_F_SetFieldDateTimeEx( poFeature.get(), ogrField,
2877 date.year(),
2878 date.month(),
2879 date.day(),
2880 time.hour(),
2881 time.minute(),
2882 static_cast<float>( time.second() + static_cast< double >( time.msec() ) / 1000 ),
2884 }
2885 break;
2886 case QMetaType::Type::QTime:
2887 if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
2888 {
2889 OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( attrValue.toString() ).constData() );
2890 }
2891 else
2892 {
2893 const QTime time = attrValue.toTime();
2894 OGR_F_SetFieldDateTimeEx( poFeature.get(), ogrField,
2895 0, 0, 0,
2896 time.hour(),
2897 time.minute(),
2898 static_cast<float>( time.second() + static_cast< double >( time.msec() ) / 1000 ),
2899 0 );
2900 }
2901 break;
2902
2903 case QMetaType::Type::QByteArray:
2904 {
2905 const QByteArray ba = attrValue.toByteArray();
2906 OGR_F_SetFieldBinary( poFeature.get(), ogrField, ba.size(), const_cast< GByte * >( reinterpret_cast< const GByte * >( ba.data() ) ) );
2907 break;
2908 }
2909
2910 case QMetaType::Type::UnknownType:
2911 break;
2912
2913 case QMetaType::Type::QStringList:
2914 {
2915 // handle GPKG conversion to JSON
2916 if ( mOgrDriverName == QLatin1String( "GPKG" ) )
2917 {
2918 const QJsonDocument doc = QJsonDocument::fromVariant( attrValue );
2919 QString jsonString;
2920 if ( !doc.isNull() )
2921 {
2922 jsonString = QString::fromUtf8( doc.toJson( QJsonDocument::Compact ).constData() );
2923 }
2924 OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( jsonString.constData() ) );
2925 break;
2926 }
2927
2928 QStringList list = attrValue.toStringList();
2929 if ( mSupportedListSubTypes.contains( QMetaType::Type::QString ) )
2930 {
2931 int count = list.count();
2932 char **lst = new char *[count + 1];
2933 if ( count > 0 )
2934 {
2935 int pos = 0;
2936 for ( const QString &string : list )
2937 {
2938 lst[pos] = CPLStrdup( mCodec->fromUnicode( string ).data() );
2939 pos++;
2940 }
2941 }
2942 lst[count] = nullptr;
2943 OGR_F_SetFieldStringList( poFeature.get(), ogrField, lst );
2944 CSLDestroy( lst );
2945 }
2946 else
2947 {
2948 OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( list.join( ',' ) ).constData() );
2949 }
2950 break;
2951 }
2952
2953 case QMetaType::Type::QVariantList:
2954 // handle GPKG conversion to JSON
2955 if ( mOgrDriverName == QLatin1String( "GPKG" ) )
2956 {
2957 const QJsonDocument doc = QJsonDocument::fromVariant( attrValue );
2958 QString jsonString;
2959 if ( !doc.isNull() )
2960 {
2961 jsonString = QString::fromUtf8( doc.toJson( QJsonDocument::Compact ).data() );
2962 }
2963 OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( jsonString.constData() ) );
2964 break;
2965 }
2966
2967 // fall through to default for unsupported types
2968 if ( field.subType() == QMetaType::Type::QString )
2969 {
2970 QStringList list = attrValue.toStringList();
2971 if ( mSupportedListSubTypes.contains( QMetaType::Type::QString ) )
2972 {
2973 int count = list.count();
2974 char **lst = new char *[count + 1];
2975 if ( count > 0 )
2976 {
2977 int pos = 0;
2978 for ( const QString &string : list )
2979 {
2980 lst[pos] = CPLStrdup( mCodec->fromUnicode( string ).data() );
2981 pos++;
2982 }
2983 }
2984 lst[count] = nullptr;
2985 OGR_F_SetFieldStringList( poFeature.get(), ogrField, lst );
2986 CSLDestroy( lst );
2987 }
2988 else
2989 {
2990 OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( list.join( ',' ) ).constData() );
2991 }
2992 break;
2993 }
2994 else if ( field.subType() == QMetaType::Type::Int )
2995 {
2996 const QVariantList list = attrValue.toList();
2997 if ( mSupportedListSubTypes.contains( QMetaType::Type::Int ) )
2998 {
2999 const int count = list.count();
3000 int *lst = new int[count];
3001 if ( count > 0 )
3002 {
3003 int pos = 0;
3004 for ( const QVariant &value : list )
3005 {
3006 lst[pos] = value.toInt();
3007 pos++;
3008 }
3009 }
3010 OGR_F_SetFieldIntegerList( poFeature.get(), ogrField, count, lst );
3011 delete [] lst;
3012 }
3013 else
3014 {
3015 QStringList strings;
3016 strings.reserve( list.size() );
3017 for ( const QVariant &value : list )
3018 {
3019 strings << QString::number( value.toInt() );
3020 }
3021 OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( strings.join( ',' ) ).constData() );
3022 }
3023 break;
3024 }
3025 else if ( field.subType() == QMetaType::Type::Double )
3026 {
3027 const QVariantList list = attrValue.toList();
3028 if ( mSupportedListSubTypes.contains( QMetaType::Type::Double ) )
3029 {
3030 const int count = list.count();
3031 double *lst = new double[count];
3032 if ( count > 0 )
3033 {
3034 int pos = 0;
3035 for ( const QVariant &value : list )
3036 {
3037 lst[pos] = value.toDouble();
3038 pos++;
3039 }
3040 }
3041 OGR_F_SetFieldDoubleList( poFeature.get(), ogrField, count, lst );
3042 delete [] lst;
3043 }
3044 else
3045 {
3046 QStringList strings;
3047 strings.reserve( list.size() );
3048 for ( const QVariant &value : list )
3049 {
3050 strings << QString::number( value.toDouble() );
3051 }
3052 OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( strings.join( ',' ) ).constData() );
3053 }
3054 break;
3055 }
3056 else if ( field.subType() == QMetaType::Type::LongLong )
3057 {
3058 const QVariantList list = attrValue.toList();
3059 if ( mSupportedListSubTypes.contains( QMetaType::Type::LongLong ) )
3060 {
3061 const int count = list.count();
3062 long long *lst = new long long[count];
3063 if ( count > 0 )
3064 {
3065 int pos = 0;
3066 for ( const QVariant &value : list )
3067 {
3068 lst[pos] = value.toLongLong();
3069 pos++;
3070 }
3071 }
3072 OGR_F_SetFieldInteger64List( poFeature.get(), ogrField, count, lst );
3073 delete [] lst;
3074 }
3075 else
3076 {
3077 QStringList strings;
3078 strings.reserve( list.size() );
3079 for ( const QVariant &value : list )
3080 {
3081 strings << QString::number( value.toLongLong() );
3082 }
3083 OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( strings.join( ',' ) ).constData() );
3084 }
3085 break;
3086 }
3087 //intentional fall-through
3088 [[fallthrough]];
3089
3090 case QMetaType::Type::QVariantMap:
3091 {
3092 // handle GPKG conversion to JSON
3093 const char *pszDataSubTypes = GDALGetMetadataItem( OGRGetDriverByName( mOgrDriverName.toLocal8Bit().constData() ), GDAL_DMD_CREATIONFIELDDATASUBTYPES, nullptr );
3094 if ( pszDataSubTypes && strstr( pszDataSubTypes, "JSON" ) )
3095 {
3096 const QJsonDocument doc = QJsonDocument::fromVariant( attrValue );
3097 QString jsonString;
3098 if ( !doc.isNull() )
3099 {
3100 const QByteArray json { doc.toJson( QJsonDocument::Compact ) };
3101 jsonString = QString::fromUtf8( json.data() );
3102 }
3103 OGR_F_SetFieldString( poFeature.get(), ogrField, mCodec->fromUnicode( jsonString.constData() ) );
3104 break;
3105 }
3106 }
3107
3108 //intentional fall-through
3109 [[fallthrough]];
3110
3111
3112 default:
3113 mErrorMessage = QObject::tr( "Invalid variant type for field %1[%2]: received %3 with type %4" )
3114 .arg( mFields.at( fldIdx ).name() )
3115 .arg( ogrField )
3116 .arg( attrValue.typeName(),
3117 attrValue.toString() );
3118 QgsMessageLog::logMessage( mErrorMessage, QObject::tr( "OGR" ) );
3120 return nullptr;
3121 }
3122 }
3123
3125 {
3126 if ( feature.hasGeometry() )
3127 {
3128 // build geometry from WKB
3129 QgsGeometry geom = feature.geometry();
3130 if ( mCoordinateTransform )
3131 {
3132 // output dataset requires coordinate transform
3133 try
3134 {
3135 geom.transform( *mCoordinateTransform );
3136 }
3137 catch ( QgsCsException & )
3138 {
3139 QgsLogger::warning( QObject::tr( "Feature geometry failed to transform" ) );
3140 return nullptr;
3141 }
3142 }
3143
3144 // turn single geometry to multi geometry if needed
3147 {
3148 geom.convertToMultiType();
3149 }
3150
3151 if ( geom.wkbType() != mWkbType )
3152 {
3153 OGRGeometryH mGeom2 = nullptr;
3154
3155 // If requested WKB type is 25D and geometry WKB type is 3D,
3156 // we must force the use of 25D.
3158 {
3159 //ND: I suspect there's a bug here, in that this is NOT converting the geometry's WKB type,
3160 //so the exported WKB has a different type to what the OGRGeometry is expecting.
3161 //possibly this is handled already in OGR, but it should be fixed regardless by actually converting
3162 //geom to the correct WKB type
3163 Qgis::WkbType wkbType = geom.wkbType();
3164 if ( wkbType >= Qgis::WkbType::PointZ && wkbType <= Qgis::WkbType::MultiPolygonZ )
3165 {
3166 Qgis::WkbType wkbType25d = static_cast<Qgis::WkbType>( static_cast< quint32>( geom.wkbType() ) - static_cast< quint32>( Qgis::WkbType::PointZ ) + static_cast<quint32>( Qgis::WkbType::Point25D ) );
3167 mGeom2 = createEmptyGeometry( wkbType25d );
3168 }
3169 }
3170
3171 // drop m/z value if not present in output wkb type
3172 if ( !QgsWkbTypes::hasZ( mWkbType ) && QgsWkbTypes::hasZ( geom.wkbType() ) )
3173 geom.get()->dropZValue();
3174 if ( !QgsWkbTypes::hasM( mWkbType ) && QgsWkbTypes::hasM( geom.wkbType() ) )
3175 geom.get()->dropMValue();
3176
3177 // add m/z values if not present in the input wkb type -- this is needed for formats which determine
3178 // geometry type based on features, e.g. geojson
3179 if ( QgsWkbTypes::hasZ( mWkbType ) && !QgsWkbTypes::hasZ( geom.wkbType() ) )
3180 {
3181 if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
3182 geom.get()->addZValue( std::numeric_limits<double>::quiet_NaN() );
3183 else
3184 geom.get()->addZValue( 0 );
3185 }
3186 if ( QgsWkbTypes::hasM( mWkbType ) && !QgsWkbTypes::hasM( geom.wkbType() ) )
3187 {
3188 if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
3189 geom.get()->addMValue( std::numeric_limits<double>::quiet_NaN() );
3190 else
3191 geom.get()->addMValue( 0 );
3192 }
3193
3194 if ( !mGeom2 )
3195 {
3196 // there's a problem when layer type is set as wkbtype Polygon
3197 // although there are also features of type MultiPolygon
3198 // (at least in OGR provider)
3199 // If the feature's wkbtype is different from the layer's wkbtype,
3200 // try to export it too.
3201 //
3202 // Btw. OGRGeometry must be exactly of the type of the geometry which it will receive
3203 // i.e. Polygons can't be imported to OGRMultiPolygon
3204 mGeom2 = createEmptyGeometry( geom.wkbType() );
3205 }
3206
3207 if ( !mGeom2 )
3208 {
3209 mErrorMessage = QObject::tr( "Feature geometry not imported (OGR error: %1)" )
3210 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
3212 QgsMessageLog::logMessage( mErrorMessage, QObject::tr( "OGR" ) );
3213 return nullptr;
3214 }
3215
3217 if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
3219
3220 QByteArray wkb( geom.asWkb( wkbFlags ) );
3221 OGRErr err = OGR_G_ImportFromWkb( mGeom2, reinterpret_cast<unsigned char *>( const_cast<char *>( wkb.constData() ) ), wkb.length() );
3222 if ( err != OGRERR_NONE )
3223 {
3224 mErrorMessage = QObject::tr( "Feature geometry not imported (OGR error: %1)" )
3225 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
3227 QgsMessageLog::logMessage( mErrorMessage, QObject::tr( "OGR" ) );
3228 return nullptr;
3229 }
3230
3231 // pass ownership to geometry
3232 OGR_F_SetGeometryDirectly( poFeature.get(), mGeom2 );
3233 }
3234 else // wkb type matches
3235 {
3237 if ( mOgrDriverName == QLatin1String( "ESRI Shapefile" ) )
3239
3240 QByteArray wkb( geom.asWkb( wkbFlags ) );
3241 OGRGeometryH ogrGeom = createEmptyGeometry( mWkbType );
3242 OGRErr err = OGR_G_ImportFromWkb( ogrGeom, reinterpret_cast<unsigned char *>( const_cast<char *>( wkb.constData() ) ), wkb.length() );
3243 if ( err != OGRERR_NONE )
3244 {
3245 mErrorMessage = QObject::tr( "Feature geometry not imported (OGR error: %1)" )
3246 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
3248 QgsMessageLog::logMessage( mErrorMessage, QObject::tr( "OGR" ) );
3249 return nullptr;
3250 }
3251
3252 // set geometry (ownership is passed to OGR)
3253 OGR_F_SetGeometryDirectly( poFeature.get(), ogrGeom );
3254 }
3255 }
3256 else
3257 {
3258 OGR_F_SetGeometryDirectly( poFeature.get(), createEmptyGeometry( mWkbType ) );
3259 }
3260 }
3261 return poFeature;
3262}
3263
3264void QgsVectorFileWriter::resetMap( const QgsAttributeList &attributes )
3265{
3266 QMap<int, int> omap( mAttrIdxToOgrIdx );
3267 mAttrIdxToOgrIdx.clear();
3268 for ( int i = 0; i < attributes.size(); i++ )
3269 {
3270 if ( omap.find( i ) != omap.end() )
3271 mAttrIdxToOgrIdx.insert( attributes[i], omap[i] );
3272 }
3273}
3274
3275bool QgsVectorFileWriter::writeFeature( OGRLayerH layer, OGRFeatureH feature )
3276{
3277 if ( OGR_L_CreateFeature( layer, feature ) != OGRERR_NONE )
3278 {
3279 mErrorMessage = QObject::tr( "Feature creation error (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
3281 QgsMessageLog::logMessage( mErrorMessage, QObject::tr( "OGR" ) );
3282 return false;
3283 }
3284 return true;
3285}
3286
3288{
3289 if ( mUsingTransaction )
3290 {
3291 if ( OGRERR_NONE != OGR_L_CommitTransaction( mLayer ) )
3292 {
3293 QgsDebugError( QStringLiteral( "Error while committing transaction on OGRLayer." ) );
3294 }
3295 }
3296 mDS.reset();
3297
3298 if ( mOgrRef )
3299 {
3300 OSRRelease( mOgrRef );
3301 }
3302}
3303
3306 const QString &fileName,
3307 const QString &fileEncoding,
3308 const QgsCoordinateReferenceSystem &destCRS,
3309 const QString &driverName,
3310 bool onlySelected,
3311 QString *errorMessage,
3312 const QStringList &datasourceOptions,
3313 const QStringList &layerOptions,
3314 bool skipAttributeCreation,
3315 QString *newFilename,
3316 Qgis::FeatureSymbologyExport symbologyExport,
3317 double symbologyScale,
3318 const QgsRectangle *filterExtent,
3319 Qgis::WkbType overrideGeometryType,
3320 bool forceMulti,
3321 bool includeZ,
3322 const QgsAttributeList &attributes,
3323 FieldValueConverter *fieldValueConverter,
3324 QString *newLayer )
3325{
3327 if ( destCRS.isValid() && layer )
3328 {
3329 ct = QgsCoordinateTransform( layer->crs(), destCRS, layer->transformContext() );
3330 }
3331
3332 SaveVectorOptions options;
3333 options.fileEncoding = fileEncoding;
3334 options.ct = ct;
3335 options.driverName = driverName;
3336 options.onlySelectedFeatures = onlySelected;
3337 options.datasourceOptions = datasourceOptions;
3338 options.layerOptions = layerOptions;
3339 options.skipAttributeCreation = skipAttributeCreation;
3342 if ( filterExtent )
3343 options.filterExtent = *filterExtent;
3344 options.overrideGeometryType = overrideGeometryType;
3345 options.forceMulti = forceMulti;
3346 options.includeZ = includeZ;
3347 options.attributes = attributes;
3348 options.fieldValueConverter = fieldValueConverter;
3349 return writeAsVectorFormatV3( layer, fileName, layer->transformContext(), options, errorMessage, newFilename, newLayer );
3350}
3351
3353 const QString &fileName,
3354 const QString &fileEncoding,
3355 const QgsCoordinateTransform &ct,
3356 const QString &driverName,
3357 bool onlySelected,
3358 QString *errorMessage,
3359 const QStringList &datasourceOptions,
3360 const QStringList &layerOptions,
3361 bool skipAttributeCreation,
3362 QString *newFilename,
3363 Qgis::FeatureSymbologyExport symbologyExport,
3364 double symbologyScale,
3365 const QgsRectangle *filterExtent,
3366 Qgis::WkbType overrideGeometryType,
3367 bool forceMulti,
3368 bool includeZ,
3369 const QgsAttributeList &attributes,
3370 FieldValueConverter *fieldValueConverter,
3371 QString *newLayer )
3372{
3373 SaveVectorOptions options;
3374 options.fileEncoding = fileEncoding;
3375 options.ct = ct;
3376 options.driverName = driverName;
3377 options.onlySelectedFeatures = onlySelected;
3378 options.datasourceOptions = datasourceOptions;
3379 options.layerOptions = layerOptions;
3380 options.skipAttributeCreation = skipAttributeCreation;
3383 if ( filterExtent )
3384 options.filterExtent = *filterExtent;
3385 options.overrideGeometryType = overrideGeometryType;
3386 options.forceMulti = forceMulti;
3387 options.includeZ = includeZ;
3388 options.attributes = attributes;
3389 options.fieldValueConverter = fieldValueConverter;
3390 return writeAsVectorFormatV3( layer, fileName, layer->transformContext(), options, errorMessage, newFilename, newLayer );
3391}
3392
3393
3395 : driverName( QStringLiteral( "GPKG" ) )
3396{
3397}
3398
3399
3400
3401QgsVectorFileWriter::WriterError QgsVectorFileWriter::prepareWriteAsVectorFormat( QgsVectorLayer *layer, const QgsVectorFileWriter::SaveVectorOptions &options, QgsVectorFileWriter::PreparedWriterDetails &details )
3402{
3403 if ( !layer || !layer->isValid() )
3404 {
3405 return ErrInvalidLayer;
3406 }
3407
3408 if ( layer->renderer() )
3409 details.renderer.reset( layer->renderer()->clone() );
3410 details.sourceCrs = layer->crs();
3411 details.sourceWkbType = layer->wkbType();
3412 details.sourceFields = layer->fields();
3413 details.providerType = layer->providerType();
3414 details.featureCount = options.onlySelectedFeatures ? layer->selectedFeatureCount() : layer->featureCount();
3415 if ( layer->dataProvider() )
3416 details.dataSourceUri = layer->dataProvider()->dataSourceUri();
3417 details.storageType = layer->storageType();
3418 details.selectedFeatureIds = layer->selectedFeatureIds();
3419 details.providerUriParams = QgsProviderRegistry::instance()->decodeUri( layer->providerType(), layer->dataProvider()->dataSourceUri() );
3420
3421 if ( details.storageType == QLatin1String( "ESRI Shapefile" ) )
3422 {
3424 if ( options.onlySelectedFeatures )
3425 {
3426 req.setFilterFids( details.selectedFeatureIds );
3427 }
3428 req.setNoAttributes();
3429 details.geometryTypeScanIterator = layer->getFeatures( req );
3430 }
3431
3432 details.expressionContext = QgsExpressionContext( QgsExpressionContextUtils::globalProjectLayerScopes( layer ) );
3433 details.renderContext.setExpressionContext( details.expressionContext );
3434 details.renderContext.setRendererScale( options.symbologyScale );
3435
3436 details.shallTransform = false;
3437 if ( options.ct.isValid() )
3438 {
3439 // This means we should transform
3440 details.outputCrs = options.ct.destinationCrs();
3441 details.shallTransform = true;
3442 }
3443 else
3444 {
3445 // This means we shouldn't transform, use source CRS as output (if defined)
3446 details.outputCrs = details.sourceCrs;
3447 }
3448
3449 details.destWkbType = details.sourceWkbType;
3451 {
3452 details.destWkbType = QgsWkbTypes::flatType( options.overrideGeometryType );
3453 if ( QgsWkbTypes::hasZ( options.overrideGeometryType ) || options.includeZ )
3454 details.destWkbType = QgsWkbTypes::addZ( details.destWkbType );
3455 }
3456 if ( options.forceMulti )
3457 {
3458 details.destWkbType = QgsWkbTypes::multiType( details.destWkbType );
3459 }
3460
3461 details.attributes = options.attributes;
3462 if ( options.skipAttributeCreation )
3463 details.attributes.clear();
3464 else if ( details.attributes.isEmpty() )
3465 {
3466 const QgsAttributeList allAttributes = details.sourceFields.allAttributesList();
3467 for ( int idx : allAttributes )
3468 {
3469 QgsField fld = details.sourceFields.at( idx );
3470 if ( details.providerType == QLatin1String( "oracle" ) && fld.typeName().contains( QLatin1String( "SDO_GEOMETRY" ) ) )
3471 continue;
3472 details.attributes.append( idx );
3473 }
3474 }
3475
3476 if ( !details.attributes.isEmpty() )
3477 {
3478 for ( int attrIdx : std::as_const( details.attributes ) )
3479 {
3480 if ( details.sourceFields.exists( attrIdx ) )
3481 {
3482 QgsField field = details.sourceFields.at( attrIdx );
3483 field.setName( options.attributesExportNames.value( attrIdx, field.name() ) );
3484 details.outputFields.append( field );
3485 }
3486 else
3487 {
3488 QgsDebugError( QStringLiteral( "No such source field with index '%1' available." ).arg( attrIdx ) );
3489 }
3490 }
3491 }
3492
3493 // not ideal - would be nice to avoid this happening in the preparation step if possible,
3494 // but currently requires access to the layer's minimumValue/maximumValue methods
3495 if ( details.providerType == QLatin1String( "spatialite" ) )
3496 {
3497 for ( int i = 0; i < details.outputFields.size(); i++ )
3498 {
3499 if ( details.outputFields.at( i ).type() == QMetaType::Type::LongLong )
3500 {
3501 QVariant min;
3502 QVariant max;
3503 layer->minimumAndMaximumValue( i, min, max );
3504 if ( std::max( std::llabs( min.toLongLong() ), std::llabs( max.toLongLong() ) ) < std::numeric_limits<int>::max() )
3505 {
3506 details.outputFields[i].setType( QMetaType::Type::Int );
3507 }
3508 }
3509 }
3510 }
3511
3512
3513 //add possible attributes needed by renderer
3514 addRendererAttributes( details.renderer.get(), details.renderContext, details.sourceFields, details.attributes );
3515
3517 req.setSubsetOfAttributes( details.attributes );
3518 if ( options.onlySelectedFeatures )
3519 req.setFilterFids( details.selectedFeatureIds );
3520
3521 if ( !options.filterExtent.isNull() )
3522 {
3523 QgsRectangle filterRect = options.filterExtent;
3524 bool useFilterRect = true;
3525 if ( details.shallTransform )
3526 {
3527 try
3528 {
3529 // map filter rect back from destination CRS to layer CRS
3530 QgsCoordinateTransform extentTransform = options.ct;
3531 extentTransform.setBallparkTransformsAreAppropriate( true );
3532 filterRect = extentTransform.transformBoundingBox( filterRect, Qgis::TransformDirection::Reverse );
3533 }
3534 catch ( QgsCsException & )
3535 {
3536 useFilterRect = false;
3537 }
3538 }
3539 if ( useFilterRect )
3540 {
3541 req.setFilterRect( filterRect );
3542 }
3543 details.filterRectGeometry = QgsGeometry::fromRect( options.filterExtent );
3544 details.filterRectEngine.reset( QgsGeometry::createGeometryEngine( details.filterRectGeometry.constGet() ) );
3545 details.filterRectEngine->prepareGeometry();
3546 }
3547 details.sourceFeatureIterator = layer->getFeatures( req );
3548
3549 if ( !options.sourceDatabaseProviderConnection )
3550 {
3551 details.sourceDatabaseProviderConnection.reset( QgsMapLayerUtils::databaseConnection( layer ) );
3552 }
3553
3554 return NoError;
3555}
3556
3557QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormat( PreparedWriterDetails &details, const QString &fileName, const QgsVectorFileWriter::SaveVectorOptions &options, QString *newFilename, QString *errorMessage, QString *newLayer )
3558{
3559 return writeAsVectorFormatV2( details, fileName, QgsCoordinateTransformContext(), options, newFilename, newLayer, errorMessage );
3560}
3561
3562QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormatV2( PreparedWriterDetails &details, const QString &fileName, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QString *newFilename, QString *newLayer, QString *errorMessage, SinkFlags sinkFlags )
3563{
3564 Qgis::WkbType destWkbType = details.destWkbType;
3565
3566 int lastProgressReport = 0;
3567 long long total = details.featureCount;
3568
3569 // Special rules for OGR layers
3570 if ( details.providerType == QLatin1String( "ogr" ) && !details.dataSourceUri.isEmpty() )
3571 {
3572 QString srcFileName( details.providerUriParams.value( QStringLiteral( "path" ) ).toString() );
3573 if ( QFile::exists( srcFileName ) && QFileInfo( fileName ).canonicalFilePath() == QFileInfo( srcFileName ).canonicalFilePath() )
3574 {
3575 // Check the layer name too if it's a GPKG/SpatiaLite/SQLite OGR driver (pay attention: camel case in layerName)
3576 QgsDataSourceUri uri( details.dataSourceUri );
3577 if ( !( ( options.driverName == QLatin1String( "GPKG" ) ||
3578 options.driverName == QLatin1String( "SpatiaLite" ) ||
3579 options.driverName == QLatin1String( "SQLite" ) ) &&
3580 options.layerName != details.providerUriParams.value( QStringLiteral( "layerName" ) ) ) )
3581 {
3582 if ( errorMessage )
3583 *errorMessage = QObject::tr( "Cannot overwrite an OGR layer in place" );
3584 return ErrCreateDataSource;
3585 }
3586 }
3587
3588 // Shapefiles might contain multi types although wkbType() only reports singles
3589 if ( details.storageType == QLatin1String( "ESRI Shapefile" ) && !QgsWkbTypes::isMultiType( destWkbType ) )
3590 {
3591 QgsFeatureIterator fit = details.geometryTypeScanIterator;
3592 QgsFeature fet;
3593 long scanned = 0;
3594 while ( fit.nextFeature( fet ) )
3595 {
3596 if ( options.feedback && options.feedback->isCanceled() )
3597 {
3598 return Canceled;
3599 }
3600 if ( options.feedback )
3601 {
3602 //dedicate first 5% of progress bar to this scan
3603 int newProgress = static_cast<int>( ( 5.0 * scanned ) / total );
3604 if ( newProgress != lastProgressReport )
3605 {
3606 lastProgressReport = newProgress;
3607 options.feedback->setProgress( lastProgressReport );
3608 }
3609 }
3610
3611 if ( fet.hasGeometry() && QgsWkbTypes::isMultiType( fet.geometry().wkbType() ) )
3612 {
3613 destWkbType = QgsWkbTypes::multiType( destWkbType );
3614 break;
3615 }
3616 scanned++;
3617 }
3618 }
3619 }
3620
3621 QString tempNewFilename;
3622 QString tempNewLayer;
3623
3624 QgsVectorFileWriter::SaveVectorOptions newOptions = options;
3625 if ( !newOptions.sourceDatabaseProviderConnection )
3626 {
3627 newOptions.sourceDatabaseProviderConnection = details.sourceDatabaseProviderConnection.get();
3628 }
3629
3630 std::unique_ptr< QgsVectorFileWriter > writer( create( fileName, details.outputFields, destWkbType, details.outputCrs, transformContext, newOptions, sinkFlags, &tempNewFilename, &tempNewLayer ) );
3631 writer->setSymbologyScale( options.symbologyScale );
3632
3633 if ( newFilename )
3634 *newFilename = tempNewFilename;
3635
3636 if ( newLayer )
3637 *newLayer = tempNewLayer;
3638
3639 if ( newFilename )
3640 {
3641 QgsDebugMsgLevel( "newFilename = " + *newFilename, 2 );
3642 }
3643
3644 // check whether file creation was successful
3645 WriterError err = writer->hasError();
3646 if ( err != NoError )
3647 {
3648 if ( errorMessage )
3649 *errorMessage = writer->errorMessage();
3650 return err;
3651 }
3652
3653 if ( errorMessage )
3654 {
3655 errorMessage->clear();
3656 }
3657
3658 QgsFeature fet;
3659
3660 //create symbol table if needed
3661 if ( writer->symbologyExport() != Qgis::FeatureSymbologyExport::NoSymbology )
3662 {
3663 //writer->createSymbolLayerTable( layer, writer->mDS );
3664 }
3665
3666 switch ( writer->symbologyExport() )
3667 {
3669 {
3670 QgsFeatureRenderer *r = details.renderer.get();
3672 && r->usingSymbolLevels() )
3673 {
3674 QgsVectorFileWriter::WriterError error = writer->exportFeaturesSymbolLevels( details, details.sourceFeatureIterator, options.ct, errorMessage );
3675 return ( error == NoError ) ? NoError : ErrFeatureWriteFailed;
3676 }
3677 break;
3678 }
3681 break;
3682 }
3683
3684 int n = 0, errors = 0;
3685
3686 //unit type
3687 Qgis::DistanceUnit mapUnits = details.sourceCrs.mapUnits();
3688 if ( options.ct.isValid() )
3689 {
3690 mapUnits = options.ct.destinationCrs().mapUnits();
3691 }
3692
3693 writer->startRender( details.renderer.get(), details.sourceFields );
3694
3695 writer->resetMap( details.attributes );
3696 // Reset mFields to layer fields, and not just exported fields
3697 writer->mFields = details.sourceFields;
3698
3699 // write all features
3700 long saved = 0;
3701 int initialProgress = lastProgressReport;
3702 while ( details.sourceFeatureIterator.nextFeature( fet ) )
3703 {
3704 if ( options.feedback && options.feedback->isCanceled() )
3705 {
3706 return Canceled;
3707 }
3708
3709 saved++;
3710 if ( options.feedback )
3711 {
3712 //avoid spamming progress reports
3713 int newProgress = static_cast<int>( initialProgress + ( ( 100.0 - initialProgress ) * saved ) / total );
3714 if ( newProgress < 100 && newProgress != lastProgressReport )
3715 {
3716 lastProgressReport = newProgress;
3717 options.feedback->setProgress( lastProgressReport );
3718 }
3719 }
3720
3721 if ( details.shallTransform )
3722 {
3723 try
3724 {
3725 if ( fet.hasGeometry() )
3726 {
3727 QgsGeometry g = fet.geometry();
3728 g.transform( options.ct );
3729 fet.setGeometry( g );
3730 }
3731 }
3732 catch ( QgsCsException &e )
3733 {
3734 const QString msg = QObject::tr( "Failed to transform feature with ID '%1'. Writing stopped. (Exception: %2)" )
3735 .arg( fet.id() ).arg( e.what() );
3736 QgsLogger::warning( msg );
3737 if ( errorMessage )
3738 *errorMessage = msg;
3739
3740 return ErrProjection;
3741 }
3742 }
3743
3744 if ( fet.hasGeometry() && details.filterRectEngine && !details.filterRectEngine->intersects( fet.geometry().constGet() ) )
3745 continue;
3746
3747 if ( details.attributes.empty() && options.skipAttributeCreation )
3748 {
3749 fet.initAttributes( 0 );
3750 }
3751
3752 if ( !writer->addFeatureWithStyle( fet, writer->mRenderer.get(), mapUnits ) )
3753 {
3754 WriterError err = writer->hasError();
3755 if ( err != NoError && errorMessage )
3756 {
3757 if ( errorMessage->isEmpty() )
3758 {
3759 *errorMessage = QObject::tr( "Feature write errors:" );
3760 }
3761 *errorMessage += '\n' + writer->errorMessage();
3762 }
3763 errors++;
3764
3765 if ( errors > 1000 )
3766 {
3767 if ( errorMessage )
3768 {
3769 *errorMessage += QObject::tr( "Stopping after %n error(s)", nullptr, errors );
3770 }
3771
3772 n = -1;
3773 break;
3774 }
3775 }
3776 n++;
3777 }
3778
3779 writer->stopRender();
3780
3781 if ( errors > 0 && errorMessage && n > 0 )
3782 {
3783 *errorMessage += QObject::tr( "\nOnly %1 of %2 features written." ).arg( n - errors ).arg( n );
3784 }
3785
3786 writer.reset();
3787
3788 bool metadataFailure = false;
3789 if ( options.saveMetadata )
3790 {
3791 QString uri = QgsProviderRegistry::instance()->encodeUri( QStringLiteral( "ogr" ), QVariantMap
3792 {
3793 {QStringLiteral( "path" ), tempNewFilename },
3794 {QStringLiteral( "layerName" ), tempNewLayer }
3795 } );
3796
3797 try
3798 {
3799 QString error;
3800 if ( !QgsProviderRegistry::instance()->saveLayerMetadata( QStringLiteral( "ogr" ), uri, options.layerMetadata, error ) )
3801 {
3802 if ( errorMessage )
3803 {
3804 if ( !errorMessage->isEmpty() )
3805 *errorMessage += '\n';
3806 *errorMessage += error;
3807 }
3808 metadataFailure = true;
3809 }
3810 }
3811 catch ( QgsNotSupportedException &e )
3812 {
3813 if ( errorMessage )
3814 {
3815 if ( !errorMessage->isEmpty() )
3816 *errorMessage += '\n';
3817 *errorMessage += e.what();
3818 }
3819 metadataFailure = true;
3820 }
3821 }
3822
3823 return errors == 0 ? ( !metadataFailure ? NoError : ErrSavingMetadata ) : ErrFeatureWriteFailed;
3824}
3825
3827 const QString &fileName,
3828 const SaveVectorOptions &options,
3829 QString *newFilename,
3830 QString *errorMessage,
3831 QString *newLayer )
3832{
3833 QgsVectorFileWriter::PreparedWriterDetails details;
3834 WriterError err = prepareWriteAsVectorFormat( layer, options, details );
3835 if ( err != NoError )
3836 return err;
3837
3838 return writeAsVectorFormatV2( details, fileName, layer->transformContext(), options, newFilename, newLayer, errorMessage );
3839}
3840
3842 const QString &fileName,
3843 const QgsCoordinateTransformContext &transformContext,
3844 const SaveVectorOptions &options,
3845 QString *newFilename,
3846 QString *newLayer,
3847 QString *errorMessage )
3848{
3849 QgsVectorFileWriter::PreparedWriterDetails details;
3850 WriterError err = prepareWriteAsVectorFormat( layer, options, details );
3851 if ( err != NoError )
3852 return err;
3853
3854 return writeAsVectorFormatV2( details, fileName, transformContext, options, newFilename, newLayer, errorMessage );
3855}
3856
3857QgsVectorFileWriter::WriterError QgsVectorFileWriter::writeAsVectorFormatV3( QgsVectorLayer *layer, const QString &fileName, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QString *errorMessage, QString *newFilename, QString *newLayer )
3858{
3859 QgsVectorFileWriter::PreparedWriterDetails details;
3860 WriterError err = prepareWriteAsVectorFormat( layer, options, details );
3861 if ( err != NoError )
3862 return err;
3863
3864 return writeAsVectorFormatV2( details, fileName, transformContext, options, newFilename, newLayer, errorMessage );
3865}
3866
3867bool QgsVectorFileWriter::deleteShapeFile( const QString &fileName )
3868{
3869 QFileInfo fi( fileName );
3870 QDir dir = fi.dir();
3871
3872 QStringList filter;
3873 for ( const char *suffix : { ".shp", ".shx", ".dbf", ".prj", ".qix", ".qpj", ".cpg", ".sbn", ".sbx", ".idm", ".ind" } )
3874 {
3875 filter << fi.completeBaseName() + suffix;
3876 }
3877
3878 bool ok = true;
3879 const auto constEntryList = dir.entryList( filter );
3880 for ( const QString &file : constEntryList )
3881 {
3882 QFile f( dir.canonicalPath() + '/' + file );
3883 if ( !f.remove() )
3884 {
3885 QgsDebugError( QStringLiteral( "Removing file %1 failed: %2" ).arg( file, f.errorString() ) );
3886 ok = false;
3887 }
3888 }
3889
3890 return ok;
3891}
3892
3894{
3895 mSymbologyScale = d;
3896 mRenderContext.setRendererScale( mSymbologyScale );
3897}
3898
3900{
3901 QStringList driverNames;
3902 const QSet< QString > multiLayerExtensions = qgis::listToSet( QgsGdalUtils::multiLayerFileExtensions() );
3903
3904 for ( int i = 0; i < GDALGetDriverCount(); ++i )
3905 {
3906 GDALDriverH driver = GDALGetDriver( i );
3907 if ( !driver )
3908 {
3909 QgsLogger::warning( "unable to get driver " + QString::number( i ) );
3910 continue;
3911 }
3912
3913 const QString driverExtensions = GDALGetMetadataItem( driver, GDAL_DMD_EXTENSIONS, "" );
3914 if ( driverExtensions.isEmpty() )
3915 continue;
3916
3917 const QSet< QString > splitExtensions = qgis::listToSet( driverExtensions.split( ' ', Qt::SkipEmptyParts ) );
3918 if ( splitExtensions.intersects( multiLayerExtensions ) )
3919 {
3920 driverNames << GDALGetDescription( driver );
3921 }
3922 }
3923 return driverNames;
3924}
3925
3926QList< QgsVectorFileWriter::FilterFormatDetails > QgsVectorFileWriter::supportedFiltersAndFormats( const VectorFormatOptions options )
3927{
3928 static QReadWriteLock sFilterLock;
3929 static QMap< VectorFormatOptions, QList< QgsVectorFileWriter::FilterFormatDetails > > sFilters;
3930
3931 QgsReadWriteLocker locker( sFilterLock, QgsReadWriteLocker::Read );
3932
3933 const auto it = sFilters.constFind( options );
3934 if ( it != sFilters.constEnd() )
3935 return it.value();
3936
3938 QList< QgsVectorFileWriter::FilterFormatDetails > results;
3939
3941 int const drvCount = OGRGetDriverCount();
3942
3943 const QStringList multiLayerDrivers = multiLayerFormats();
3944
3945 for ( int i = 0; i < drvCount; ++i )
3946 {
3947 OGRSFDriverH drv = OGRGetDriver( i );
3948 if ( drv )
3949 {
3950 const QString drvName = GDALGetDescription( drv );
3951
3952 if ( options & SupportsMultipleLayers )
3953 {
3954 if ( !multiLayerDrivers.contains( drvName ) )
3955 continue;
3956 }
3957
3958 GDALDriverH gdalDriver = GDALGetDriverByName( drvName.toLocal8Bit().constData() );
3959 bool nonSpatialFormat = false;
3960 if ( gdalDriver )
3961 {
3962 nonSpatialFormat = GDALGetMetadataItem( gdalDriver, GDAL_DCAP_NONSPATIAL, nullptr );
3963 }
3964
3965 if ( OGR_Dr_TestCapability( drv, "CreateDataSource" ) != 0 )
3966 {
3967 if ( options & SkipNonSpatialFormats )
3968 {
3969 // skip non-spatial formats
3970 if ( nonSpatialFormat )
3971 continue;
3972 }
3973
3974 QString filterString = filterForDriver( drvName );
3975 if ( filterString.isEmpty() )
3976 continue;
3977
3978 MetaData metadata;
3979 QStringList globs;
3980 if ( driverMetadata( drvName, metadata ) && !metadata.glob.isEmpty() )
3981 {
3982 globs = metadata.glob.toLower().split( ' ' );
3983 }
3984
3985 FilterFormatDetails details;
3986 details.driverName = drvName;
3987 details.filterString = filterString;
3988 details.globs = globs;
3989
3990 results << details;
3991 }
3992 }
3993 }
3994
3995 std::sort( results.begin(), results.end(), [options]( const FilterFormatDetails & a, const FilterFormatDetails & b ) -> bool
3996 {
3997 if ( options & SortRecommended )
3998 {
3999 if ( a.driverName == QLatin1String( "GPKG" ) )
4000 return true; // Make https://twitter.com/shapefiIe a sad little fellow
4001 else if ( b.driverName == QLatin1String( "GPKG" ) )
4002 return false;
4003 else if ( a.driverName == QLatin1String( "ESRI Shapefile" ) )
4004 return true;
4005 else if ( b.driverName == QLatin1String( "ESRI Shapefile" ) )
4006 return false;
4007 }
4008
4009 return a.filterString.toLower().localeAwareCompare( b.filterString.toLower() ) < 0;
4010 } );
4011
4012 sFilters.insert( options, results );
4013 return results;
4014}
4015
4017{
4018 const auto formats = supportedFiltersAndFormats( options );
4019 QSet< QString > extensions;
4020
4021 const thread_local QRegularExpression rx( QStringLiteral( "\\*\\.(.*)$" ) );
4022
4023 for ( const FilterFormatDetails &format : formats )
4024 {
4025 for ( const QString &glob : format.globs )
4026 {
4027 const QRegularExpressionMatch match = rx.match( glob );
4028 if ( !match.hasMatch() )
4029 continue;
4030
4031 const QString matched = match.captured( 1 );
4032 extensions.insert( matched );
4033 }
4034 }
4035
4036 QStringList extensionList( extensions.constBegin(), extensions.constEnd() );
4037
4038 std::sort( extensionList.begin(), extensionList.end(), [options]( const QString & a, const QString & b ) -> bool
4039 {
4040 if ( options & SortRecommended )
4041 {
4042 if ( a == QLatin1String( "gpkg" ) )
4043 return true; // Make https://twitter.com/shapefiIe a sad little fellow
4044 else if ( b == QLatin1String( "gpkg" ) )
4045 return false;
4046 else if ( a == QLatin1String( "shp" ) )
4047 return true;
4048 else if ( b == QLatin1String( "shp" ) )
4049 return false;
4050 }
4051
4052 return a.toLower().localeAwareCompare( b.toLower() ) < 0;
4053 } );
4054
4055 return extensionList;
4056}
4057
4058QList< QgsVectorFileWriter::DriverDetails > QgsVectorFileWriter::ogrDriverList( const VectorFormatOptions options )
4059{
4060 QList< QgsVectorFileWriter::DriverDetails > results;
4061
4063 const int drvCount = OGRGetDriverCount();
4064
4065 const QStringList multiLayerDrivers = multiLayerFormats();
4066
4067 QStringList writableDrivers;
4068 for ( int i = 0; i < drvCount; ++i )
4069 {
4070 OGRSFDriverH drv = OGRGetDriver( i );
4071 if ( drv )
4072 {
4073 const QString drvName = GDALGetDescription( drv );
4074
4075 if ( options & SupportsMultipleLayers )
4076 {
4077 if ( !multiLayerDrivers.contains( drvName ) )
4078 continue;
4079 }
4080
4081 if ( options & SkipNonSpatialFormats )
4082 {
4083 // skip non-spatial formats
4084 // TODO - use GDAL metadata to determine this, when support exists in GDAL
4085 if ( drvName == QLatin1String( "ODS" ) || drvName == QLatin1String( "XLSX" ) || drvName == QLatin1String( "XLS" ) )
4086 continue;
4087 }
4088
4089 if ( drvName == QLatin1String( "ESRI Shapefile" ) )
4090 {
4091 writableDrivers << QStringLiteral( "DBF file" );
4092 }
4093 if ( OGR_Dr_TestCapability( drv, "CreateDataSource" ) != 0 )
4094 {
4095 // Add separate format for Mapinfo MIF (MITAB is OGR default)
4096 if ( drvName == QLatin1String( "MapInfo File" ) )
4097 {
4098 writableDrivers << QStringLiteral( "MapInfo MIF" );
4099 }
4100 else if ( drvName == QLatin1String( "SQLite" ) )
4101 {
4102 // Unfortunately it seems that there is no simple way to detect if
4103 // OGR SQLite driver is compiled with SpatiaLite support.
4104 // We have HAVE_SPATIALITE in QGIS, but that may differ from OGR
4105 // http://lists.osgeo.org/pipermail/gdal-dev/2012-November/034580.html
4106 // -> test if creation fails
4107 QString option = QStringLiteral( "SPATIALITE=YES" );
4108 char *options[2] = { CPLStrdup( option.toLocal8Bit().constData() ), nullptr };
4109 OGRSFDriverH poDriver;
4111 poDriver = OGRGetDriverByName( drvName.toLocal8Bit().constData() );
4112 if ( poDriver )
4113 {
4114 gdal::ogr_datasource_unique_ptr ds( OGR_Dr_CreateDataSource( poDriver, QStringLiteral( "/vsimem/spatialitetest.sqlite" ).toUtf8().constData(), options ) );
4115 if ( ds )
4116 {
4117 writableDrivers << QStringLiteral( "SpatiaLite" );
4118 OGR_Dr_DeleteDataSource( poDriver, QStringLiteral( "/vsimem/spatialitetest.sqlite" ).toUtf8().constData() );
4119 }
4120 }
4121 CPLFree( options[0] );
4122 }
4123 writableDrivers << drvName;
4124 }
4125 }
4126 }
4127
4128 results.reserve( writableDrivers.count() );
4129 for ( const QString &drvName : std::as_const( writableDrivers ) )
4130 {
4131 MetaData metadata;
4132 if ( driverMetadata( drvName, metadata ) && !metadata.trLongName.isEmpty() )
4133 {
4134 DriverDetails details;
4135 details.driverName = drvName;
4136 details.longName = metadata.trLongName;
4137 results << details;
4138 }
4139 }
4140
4141 std::sort( results.begin(), results.end(), [options]( const DriverDetails & a, const DriverDetails & b ) -> bool
4142 {
4143 if ( options & SortRecommended )
4144 {
4145 if ( a.driverName == QLatin1String( "GPKG" ) )
4146 return true; // Make https://twitter.com/shapefiIe a sad little fellow
4147 else if ( b.driverName == QLatin1String( "GPKG" ) )
4148 return false;
4149 else if ( a.driverName == QLatin1String( "ESRI Shapefile" ) )
4150 return true;
4151 else if ( b.driverName == QLatin1String( "ESRI Shapefile" ) )
4152 return false;
4153 }
4154
4155 return a.longName.toLower().localeAwareCompare( b.longName.toLower() ) < 0;
4156 } );
4157 return results;
4158}
4159
4160QString QgsVectorFileWriter::driverForExtension( const QString &extension )
4161{
4162 QString ext = extension.trimmed();
4163 if ( ext.isEmpty() )
4164 return QString();
4165
4166 if ( ext.startsWith( '.' ) )
4167 ext.remove( 0, 1 );
4168
4169 GDALAllRegister();
4170 int const drvCount = GDALGetDriverCount();
4171
4172 for ( int i = 0; i < drvCount; ++i )
4173 {
4174 GDALDriverH drv = GDALGetDriver( i );
4175 if ( drv )
4176 {
4177 char **driverMetadata = GDALGetMetadata( drv, nullptr );
4178 if ( CSLFetchBoolean( driverMetadata, GDAL_DCAP_CREATE, false ) && CSLFetchBoolean( driverMetadata, GDAL_DCAP_VECTOR, false ) )
4179 {
4180 QString drvName = GDALGetDriverShortName( drv );
4181 QStringList driverExtensions = QString( GDALGetMetadataItem( drv, GDAL_DMD_EXTENSIONS, nullptr ) ).split( ' ' );
4182
4183 const auto constDriverExtensions = driverExtensions;
4184 for ( const QString &driver : constDriverExtensions )
4185 {
4186 if ( driver.compare( ext, Qt::CaseInsensitive ) == 0 )
4187 return drvName;
4188 }
4189 }
4190 }
4191 }
4192 return QString();
4193}
4194
4196{
4197 QString filterString;
4198 const auto driverFormats = supportedFiltersAndFormats( options );
4199 for ( const FilterFormatDetails &details : driverFormats )
4200 {
4201 if ( !filterString.isEmpty() )
4202 filterString += QLatin1String( ";;" );
4203
4204 filterString += details.filterString;
4205 }
4206 return filterString;
4207}
4208
4209QString QgsVectorFileWriter::filterForDriver( const QString &driverName )
4210{
4211 MetaData metadata;
4212 if ( !driverMetadata( driverName, metadata ) || metadata.trLongName.isEmpty() || metadata.glob.isEmpty() )
4213 return QString();
4214
4215 return QStringLiteral( "%1 (%2 %3)" ).arg( metadata.trLongName,
4216 metadata.glob.toLower(),
4217 metadata.glob.toUpper() );
4218}
4219
4221{
4222 if ( codecName == QLatin1String( "System" ) )
4223 return QStringLiteral( "LDID/0" );
4224
4225 const thread_local QRegularExpression re( QRegularExpression::anchoredPattern( QString( "(CP|windows-|ISO[ -])(.+)" ) ), QRegularExpression::CaseInsensitiveOption );
4226 const QRegularExpressionMatch match = re.match( codecName );
4227 if ( match.hasMatch() )
4228 {
4229 QString c = match.captured( 2 ).remove( '-' );
4230 bool isNumber;
4231 ( void ) c.toInt( &isNumber );
4232 if ( isNumber )
4233 return c;
4234 }
4235 return codecName;
4236}
4237
4238void QgsVectorFileWriter::createSymbolLayerTable( QgsVectorLayer *vl, const QgsCoordinateTransform &ct, OGRDataSourceH ds )
4239{
4240 if ( !vl || !ds )
4241 {
4242 return;
4243 }
4244
4245 QgsFeatureRenderer *renderer = vl->renderer();
4246 if ( !renderer )
4247 {
4248 return;
4249 }
4250
4251 //unit type
4252 Qgis::DistanceUnit mapUnits = vl->crs().mapUnits();
4253 if ( ct.isValid() )
4254 {
4255 mapUnits = ct.destinationCrs().mapUnits();
4256 }
4257
4258 mSymbolLayerTable.clear();
4259 OGRStyleTableH ogrStyleTable = OGR_STBL_Create();
4260 OGRStyleMgrH styleManager = OGR_SM_Create( ogrStyleTable );
4261
4262 //get symbols
4263 int nTotalLevels = 0;
4264 QgsSymbolList symbolList = renderer->symbols( mRenderContext );
4265 QgsSymbolList::iterator symbolIt = symbolList.begin();
4266 for ( ; symbolIt != symbolList.end(); ++symbolIt )
4267 {
4268 double mmsf = mmScaleFactor( mSymbologyScale, ( *symbolIt )->outputUnit(), mapUnits );
4269 double musf = mapUnitScaleFactor( mSymbologyScale, ( *symbolIt )->outputUnit(), mapUnits );
4270
4271 int nLevels = ( *symbolIt )->symbolLayerCount();
4272 for ( int i = 0; i < nLevels; ++i )
4273 {
4274 mSymbolLayerTable.insert( ( *symbolIt )->symbolLayer( i ), QString::number( nTotalLevels ) );
4275 OGR_SM_AddStyle( styleManager, QString::number( nTotalLevels ).toLocal8Bit(),
4276 ( *symbolIt )->symbolLayer( i )->ogrFeatureStyle( mmsf, musf ).toLocal8Bit() );
4277 ++nTotalLevels;
4278 }
4279 }
4280 OGR_DS_SetStyleTableDirectly( ds, ogrStyleTable );
4281}
4282
4283QgsVectorFileWriter::WriterError QgsVectorFileWriter::exportFeaturesSymbolLevels( const PreparedWriterDetails &details, QgsFeatureIterator &fit,
4284 const QgsCoordinateTransform &ct, QString *errorMessage )
4285{
4286 if ( !details.renderer )
4287 return ErrInvalidLayer;
4288
4289 mRenderContext.expressionContext() = details.expressionContext;
4290
4291 QHash< QgsSymbol *, QList<QgsFeature> > features;
4292
4293 //unit type
4294 Qgis::DistanceUnit mapUnits = details.sourceCrs.mapUnits();
4295 if ( ct.isValid() )
4296 {
4297 mapUnits = ct.destinationCrs().mapUnits();
4298 }
4299
4300 startRender( details.renderer.get(), details.sourceFields );
4301
4302 //fetch features
4303 QgsFeature fet;
4304 QgsSymbol *featureSymbol = nullptr;
4305 while ( fit.nextFeature( fet ) )
4306 {
4307 if ( ct.isValid() )
4308 {
4309 try
4310 {
4311 if ( fet.hasGeometry() )
4312 {
4313 QgsGeometry g = fet.geometry();
4314 g.transform( ct );
4315 fet.setGeometry( g );
4316 }
4317 }
4318 catch ( QgsCsException &e )
4319 {
4320 QString msg = QObject::tr( "Failed to transform, writing stopped. (Exception: %1)" )
4321 .arg( e.what() );
4322 QgsLogger::warning( msg );
4323 if ( errorMessage )
4324 *errorMessage = msg;
4325
4326 return ErrProjection;
4327 }
4328 }
4329 mRenderContext.expressionContext().setFeature( fet );
4330
4331 featureSymbol = mRenderer->symbolForFeature( fet, mRenderContext );
4332 if ( !featureSymbol )
4333 {
4334 continue;
4335 }
4336
4337 QHash< QgsSymbol *, QList<QgsFeature> >::iterator it = features.find( featureSymbol );
4338 if ( it == features.end() )
4339 {
4340 it = features.insert( featureSymbol, QList<QgsFeature>() );
4341 }
4342 it.value().append( fet );
4343 }
4344
4345 //find out order
4346 QgsSymbolLevelOrder levels;
4347 QgsSymbolList symbols = mRenderer->symbols( mRenderContext );
4348 for ( int i = 0; i < symbols.count(); i++ )
4349 {
4350 QgsSymbol *sym = symbols[i];
4351 for ( int j = 0; j < sym->symbolLayerCount(); j++ )
4352 {
4353 int level = sym->symbolLayer( j )->renderingPass();
4354 if ( level < 0 || level >= 1000 ) // ignore invalid levels
4355 continue;
4356 QgsSymbolLevelItem item( sym, j );
4357 while ( level >= levels.count() ) // append new empty levels
4358 levels.append( QgsSymbolLevel() );
4359 levels[level].append( item );
4360 }
4361 }
4362
4363 int nErrors = 0;
4364 int nTotalFeatures = 0;
4365
4366 //export symbol layers and symbology
4367 for ( int l = 0; l < levels.count(); l++ )
4368 {
4369 QgsSymbolLevel &level = levels[l];
4370 for ( int i = 0; i < level.count(); i++ )
4371 {
4372 QgsSymbolLevelItem &item = level[i];
4373 QHash< QgsSymbol *, QList<QgsFeature> >::iterator levelIt = features.find( item.symbol() );
4374 if ( levelIt == features.end() )
4375 {
4376 ++nErrors;
4377 continue;
4378 }
4379
4380 double mmsf = mmScaleFactor( mSymbologyScale, levelIt.key()->outputUnit(), mapUnits );
4381 double musf = mapUnitScaleFactor( mSymbologyScale, levelIt.key()->outputUnit(), mapUnits );
4382
4383 int llayer = item.layer();
4384 QList<QgsFeature> &featureList = levelIt.value();
4385 QList<QgsFeature>::iterator featureIt = featureList.begin();
4386 for ( ; featureIt != featureList.end(); ++featureIt )
4387 {
4388 ++nTotalFeatures;
4389 gdal::ogr_feature_unique_ptr ogrFeature = createFeature( *featureIt );
4390 if ( !ogrFeature )
4391 {
4392 ++nErrors;
4393 continue;
4394 }
4395
4396 QString styleString = levelIt.key()->symbolLayer( llayer )->ogrFeatureStyle( mmsf, musf );
4397 if ( !styleString.isEmpty() )
4398 {
4399 OGR_F_SetStyleString( ogrFeature.get(), styleString.toLocal8Bit().constData() );
4400 if ( !writeFeature( mLayer, ogrFeature.get() ) )
4401 {
4402 ++nErrors;
4403 }
4404 }
4405 }
4406 }
4407 }
4408
4409 stopRender();
4410
4411 if ( nErrors > 0 && errorMessage )
4412 {
4413 *errorMessage += QObject::tr( "\nOnly %1 of %2 features written." ).arg( nTotalFeatures - nErrors ).arg( nTotalFeatures );
4414 }
4415
4417}
4418
4419double QgsVectorFileWriter::mmScaleFactor( double scale, Qgis::RenderUnit symbolUnits, Qgis::DistanceUnit mapUnits )
4420{
4421 if ( symbolUnits == Qgis::RenderUnit::Millimeters )
4422 {
4423 return 1.0;
4424 }
4425 else
4426 {
4427 //conversion factor map units -> mm
4428 if ( mapUnits == Qgis::DistanceUnit::Meters )
4429 {
4430 return 1000 / scale;
4431 }
4432
4433 }
4434 return 1.0; //todo: map units
4435}
4436
4437double QgsVectorFileWriter::mapUnitScaleFactor( double scale, Qgis::RenderUnit symbolUnits, Qgis::DistanceUnit mapUnits )
4438{
4439 if ( symbolUnits == Qgis::RenderUnit::MapUnits )
4440 {
4441 return 1.0;
4442 }
4443 else
4444 {
4445 if ( symbolUnits == Qgis::RenderUnit::Millimeters && mapUnits == Qgis::DistanceUnit::Meters )
4446 {
4447 return scale / 1000;
4448 }
4449 }
4450 return 1.0;
4451}
4452
4453void QgsVectorFileWriter::startRender( QgsFeatureRenderer *sourceRenderer, const QgsFields &fields )
4454{
4455 mRenderer = createSymbologyRenderer( sourceRenderer );
4456 if ( !mRenderer )
4457 {
4458 return;
4459 }
4460
4461 mRenderer->startRender( mRenderContext, fields );
4462}
4463
4464void QgsVectorFileWriter::stopRender()
4465{
4466 if ( !mRenderer )
4467 {
4468 return;
4469 }
4470
4471 mRenderer->stopRender( mRenderContext );
4472}
4473
4474std::unique_ptr<QgsFeatureRenderer> QgsVectorFileWriter::createSymbologyRenderer( QgsFeatureRenderer *sourceRenderer ) const
4475{
4476 switch ( mSymbologyExport )
4477 {
4479 {
4480 return nullptr;
4481 }
4484 break;
4485 }
4486
4487 if ( !sourceRenderer )
4488 {
4489 return nullptr;
4490 }
4491
4492 return std::unique_ptr< QgsFeatureRenderer >( sourceRenderer->clone() );
4493}
4494
4495void QgsVectorFileWriter::addRendererAttributes( QgsFeatureRenderer *renderer, QgsRenderContext &context, const QgsFields &fields, QgsAttributeList &attList )
4496{
4497 if ( renderer )
4498 {
4499 const QSet<QString> rendererAttributes = renderer->usedAttributes( context );
4500 for ( const QString &attr : rendererAttributes )
4501 {
4502 int index = fields.lookupField( attr );
4503 if ( index != -1 )
4504 {
4505 attList.append( index );
4506 }
4507 }
4508 }
4509}
4510
4511QStringList QgsVectorFileWriter::concatenateOptions( const QMap<QString, QgsVectorFileWriter::Option *> &options )
4512{
4513 QStringList list;
4514 QMap<QString, QgsVectorFileWriter::Option *>::ConstIterator it;
4515
4516 for ( it = options.constBegin(); it != options.constEnd(); ++it )
4517 {
4518 QgsVectorFileWriter::Option *option = it.value();
4519 switch ( option->type )
4520 {
4522 {
4523 QgsVectorFileWriter::IntOption *opt = dynamic_cast<QgsVectorFileWriter::IntOption *>( option );
4524 if ( opt )
4525 {
4526 list.append( QStringLiteral( "%1=%2" ).arg( it.key() ).arg( opt->defaultValue ) );
4527 }
4528 break;
4529 }
4530
4532 {
4533 QgsVectorFileWriter::SetOption *opt = dynamic_cast<QgsVectorFileWriter::SetOption *>( option );
4534 if ( opt && !opt->defaultValue.isEmpty() )
4535 {
4536 list.append( QStringLiteral( "%1=%2" ).arg( it.key(), opt->defaultValue ) );
4537 }
4538 break;
4539 }
4540
4542 {
4544 if ( opt && !opt->defaultValue.isNull() )
4545 {
4546 list.append( QStringLiteral( "%1=%2" ).arg( it.key(), opt->defaultValue ) );
4547 }
4548 break;
4549 }
4550
4553 if ( opt && !opt->mValue.isEmpty() )
4554 {
4555 list.append( QStringLiteral( "%1=%2" ).arg( it.key(), opt->mValue ) );
4556 }
4557 break;
4558 }
4559 }
4560
4561 return list;
4562}
4563
4565{
4566 OGRSFDriverH hDriver = nullptr;
4567 gdal::ogr_datasource_unique_ptr hDS( OGROpen( datasetName.toUtf8().constData(), TRUE, &hDriver ) );
4568 if ( !hDS )
4570 const QString drvName = GDALGetDescription( hDriver );
4572 if ( OGR_DS_TestCapability( hDS.get(), ODsCCreateLayer ) )
4573 {
4574 // Shapefile driver returns True for a "foo.shp" dataset name,
4575 // creating "bar.shp" new layer, but this would be a bit confusing
4576 // for the user, so pretent that it does not support that
4577 if ( !( drvName == QLatin1String( "ESRI Shapefile" ) && QFile::exists( datasetName ) ) )
4578 caps |= CanAddNewLayer;
4579 }
4580 if ( OGR_DS_TestCapability( hDS.get(), ODsCDeleteLayer ) )
4581 {
4582 caps |= CanDeleteLayer;
4583 }
4584 int layer_count = OGR_DS_GetLayerCount( hDS.get() );
4585 if ( layer_count )
4586 {
4587 OGRLayerH hLayer = OGR_DS_GetLayer( hDS.get(), 0 );
4588 if ( hLayer )
4589 {
4590 if ( OGR_L_TestCapability( hLayer, OLCSequentialWrite ) )
4591 {
4593 if ( OGR_L_TestCapability( hLayer, OLCCreateField ) )
4594 {
4596 }
4597 }
4598 }
4599 }
4600 return caps;
4601}
4602
4603bool QgsVectorFileWriter::targetLayerExists( const QString &datasetName,
4604 const QString &layerNameIn )
4605{
4606 OGRSFDriverH hDriver = nullptr;
4607 gdal::ogr_datasource_unique_ptr hDS( OGROpen( datasetName.toUtf8().constData(), TRUE, &hDriver ) );
4608 if ( !hDS )
4609 return false;
4610
4611 QString layerName( layerNameIn );
4612 if ( layerName.isEmpty() )
4613 layerName = QFileInfo( datasetName ).baseName();
4614
4615 return OGR_DS_GetLayerByName( hDS.get(), layerName.toUtf8().constData() );
4616}
4617
4618
4619bool QgsVectorFileWriter::areThereNewFieldsToCreate( const QString &datasetName,
4620 const QString &layerName,
4621 QgsVectorLayer *layer,
4622 const QgsAttributeList &attributes )
4623{
4624 OGRSFDriverH hDriver = nullptr;
4625 gdal::ogr_datasource_unique_ptr hDS( OGROpen( datasetName.toUtf8().constData(), TRUE, &hDriver ) );
4626 if ( !hDS )
4627 return false;
4628 OGRLayerH hLayer = OGR_DS_GetLayerByName( hDS.get(), layerName.toUtf8().constData() );
4629 if ( !hLayer )
4630 {
4631 return false;
4632 }
4633 bool ret = false;
4634 OGRFeatureDefnH defn = OGR_L_GetLayerDefn( hLayer );
4635 const auto constAttributes = attributes;
4636 for ( int idx : constAttributes )
4637 {
4638 QgsField fld = layer->fields().at( idx );
4639 if ( OGR_FD_GetFieldIndex( defn, fld.name().toUtf8().constData() ) < 0 )
4640 {
4641 ret = true;
4642 break;
4643 }
4644 }
4645 return ret;
4646}
@ FieldComments
Writer can support field comments.
@ FieldAliases
Writer can support field aliases.
DistanceUnit
Units of distance.
Definition qgis.h:4894
QFlags< VectorFileWriterCapability > VectorFileWriterCapabilities
Capabilities supported by a QgsVectorFileWriter object.
Definition qgis.h:1047
RenderUnit
Rendering size units.
Definition qgis.h:5064
@ Millimeters
Millimeters.
@ MapUnits
Map units.
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:256
@ LineString
LineString.
@ MultiPolygon25D
MultiPolygon25D.
@ GeometryCollectionZ
GeometryCollectionZ.
@ NoGeometry
No geometry.
@ MultiLineString
MultiLineString.
@ Unknown
Unknown.
@ PointZ
PointZ.
@ MultiPolygonZ
MultiPolygonZ.
@ Point25D
Point25D.
FeatureSymbologyExport
Options for exporting features considering their symbology.
Definition qgis.h:5423
@ PerFeature
Keeps the number of features and export symbology per feature.
@ PerSymbolLayer
Exports one feature per symbol layer (considering symbol levels)
@ NoSymbology
Export only data.
@ Reverse
Reverse/inverse transform (from destination to source)
Provides common functionality for database based connections.
virtual QgsFieldDomain * fieldDomain(const QString &name) const
Returns the field domain with the specified name from the provider.
virtual bool addZValue(double zValue=0)=0
Adds a z-dimension to the geometry, initialized to a preset value.
virtual bool dropMValue()=0
Drops any measure values which exist in the geometry.
QFlags< WkbFlag > WkbFlags
virtual bool addMValue(double mValue=0)=0
Adds a measure to the geometry, initialized to a preset value.
virtual bool dropZValue()=0
Drops any z-dimensions which exist in the geometry.
@ FlagExportTrianglesAsPolygons
Triangles should be exported as polygon geometries.
@ FlagExportNanAsDoubleMin
Use -DOUBLE_MAX to represent NaN.
static void registerOgrDrivers()
Register OGR drivers ensuring this only happens once.
Represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
static Q_INVOKABLE QgsCoordinateReferenceSystem fromEpsgId(long epsg)
Creates a CRS from a given EPSG ID.
Contains information about the context in which a coordinate transform is executed.
Handles coordinate transforms between two coordinate systems.
void setBallparkTransformsAreAppropriate(bool appropriate)
Sets whether approximate "ballpark" results are appropriate for this coordinate transform.
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool handle180Crossover=false) const
Transforms a rectangle from the source CRS to the destination CRS.
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system, which the transform will transform coordinates t...
Custom exception class for Coordinate Reference System related exceptions.
virtual QString dataSourceUri(bool expandAuthConfig=false) const
Gets the data source specification.
Stores the component parts of a data source URI (e.g.
QString what() const
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Abstract base class for all 2D vector feature renderers.
virtual QgsSymbolList symbolsForFeature(const QgsFeature &feature, QgsRenderContext &context) const
Returns list of symbols used for rendering the feature.
virtual QgsSymbolList symbols(QgsRenderContext &context) const
Returns list of symbols used by the renderer.
bool usingSymbolLevels() const
virtual QgsFeatureRenderer::Capabilities capabilities()
Returns details about internals of this renderer.
virtual QSet< QString > usedAttributes(const QgsRenderContext &context) const =0
Returns a list of attributes required by this renderer.
@ SymbolLevels
Rendering with symbol levels (i.e. implements symbols(), symbolForFeature())
virtual QgsFeatureRenderer * clone() const =0
Create a deep copy of this renderer.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets the feature IDs that should be fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
QFlags< SinkFlag > SinkFlags
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
QFlags< Flag > Flags
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
void initAttributes(int fieldCount)
Initialize this feature with the given number of fields.
QgsFeatureId id
Definition qgsfeature.h:66
QgsGeometry geometry
Definition qgsfeature.h:69
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool isUnsetValue(int fieldIdx) const
Returns true if the attribute at the specified index is an unset value.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
QString domainName() const
Returns the associated field domain name, for providers which support field domains.
@ ConstraintNotNull
Field may not be null.
@ ConstraintUnique
Field must have a unique value.
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:53
QMetaType::Type type
Definition qgsfield.h:60
QString typeName() const
Gets the field type.
Definition qgsfield.cpp:162
QString name
Definition qgsfield.h:62
int precision
Definition qgsfield.h:59
int length
Definition qgsfield.h:58
bool convertCompatible(QVariant &v, QString *errorMessage=nullptr) const
Converts the provided variant to a compatible format.
Definition qgsfield.cpp:474
void setName(const QString &name)
Set the field name.
Definition qgsfield.cpp:228
QMetaType::Type subType() const
If the field is a collection, gets its element's type.
Definition qgsfield.cpp:157
QString alias
Definition qgsfield.h:63
QString comment
Definition qgsfield.h:61
QgsFieldConstraints constraints
Definition qgsfield.h:65
Container of fields for a vector layer.
Definition qgsfields.h:46
int count
Definition qgsfields.h:50
int size() const
Returns number of items.
void clear()
Removes all fields.
Definition qgsfields.cpp:58
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
static QStringList multiLayerFileExtensions()
Returns a list of file extensions which potentially contain multiple layers representing GDAL raster ...
A geometry is the spatial representation of a feature.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
QgsAbstractGeometry * get()
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
QByteArray asWkb(QgsAbstractGeometry::WkbFlags flags=QgsAbstractGeometry::WkbFlags()) const
Export the geometry to WKB.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
Sets the current locale to the c locale for the lifetime of the object.
Definition qgslocalec.h:32
static void warning(const QString &msg)
Goes to qWarning.
static QgsAbstractDatabaseProviderConnection * databaseConnection(const QgsMapLayer *layer)
Creates and returns the (possibly nullptr) database connection for a layer.
QString providerType() const
Returns the provider type (provider key) for this layer.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:85
QgsCoordinateTransformContext transformContext() const
Returns the layer data provider coordinate transform context or a default transform context if the la...
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
Custom exception class which is raised when an operation is not supported.
static OGRSpatialReferenceH crsToOGRSpatialReference(const QgsCoordinateReferenceSystem &crs)
Returns a OGRSpatialReferenceH corresponding to the specified crs object.
static std::unique_ptr< QgsFieldDomain > convertFieldDomain(OGRFieldDomainH domain)
Converts an OGR field domain definition to a QgsFieldDomain equivalent.
static int OGRTZFlagFromQt(const QDateTime &datetime)
Gets the value of OGRField::Date::TZFlag from the timezone of a QDateTime.
Custom exception class for provider connection related exceptions.
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Breaks a provider data source URI into its component paths (e.g.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
QString encodeUri(const QString &providerKey, const QVariantMap &parts)
Reassembles a provider data source URI from its component paths (e.g.
bool saveLayerMetadata(const QString &providerKey, const QString &uri, const QgsLayerMetadata &metadata, QString &errorMessage)
Saves metadata to the layer corresponding to the specified uri.
A convenience class that simplifies locking and unlocking QReadWriteLocks.
@ Write
Lock for write.
void changeMode(Mode mode)
Change the mode of the lock to mode.
A rectangle specified with double values.
Contains information about the context of a rendering operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
void setRendererScale(double scale)
Sets the renderer map scale.
Stores settings for use within QGIS.
Definition qgssettings.h:65
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
int renderingPass() const
Specifies the rendering pass in which this symbol layer should be rendered.
Represents a symbol level during vector rendering operations.
Definition qgsrenderer.h:65
int layer() const
The layer of this symbol level.
QgsSymbol * symbol() const
The symbol of this symbol level.
Abstract base class for all rendered symbols.
Definition qgssymbol.h:231
QgsSymbolLayer * symbolLayer(int layer)
Returns the symbol layer at the specified index.
int symbolLayerCount() const
Returns the total number of symbol layers contained in the symbol.
Definition qgssymbol.h:353
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
An available option for configuring file writing for a particular output format, presenting an boolea...
Interface to convert raw field values to their user-friendly values.
virtual QVariant convert(int fieldIdxInLayer, const QVariant &value)
Convert the provided value, for field fieldIdxInLayer.
virtual QgsVectorFileWriter::FieldValueConverter * clone() const
Creates a clone of the FieldValueConverter.
virtual QgsField fieldDefinition(const QgsField &field)
Returns a possibly modified field definition.
A hidden option for file writing for a particular output format.
An available option for configuring file writing for a particular output format, presenting an intege...
Describes an available option for configuring file writing for a particular output format.
QgsVectorFileWriter::OptionType type
Options to pass to QgsVectorFileWriter::writeAsVectorFormat().
bool forceMulti
Sets to true to force creation of multipart geometries.
QgsCoordinateTransform ct
Transform to reproject exported geometries with, or invalid transform for no transformation.
QStringList attributesExportNames
Attributes export names.
QgsLayerMetadata layerMetadata
Layer metadata to save for the exported vector file.
QString layerName
Layer name. If let empty, it will be derived from the filename.
QgsRectangle filterExtent
If not empty, only features intersecting the extent will be saved.
bool includeConstraints
Set to true to transfer field constraints to the exported vector file.
const QgsAbstractDatabaseProviderConnection * sourceDatabaseProviderConnection
Source database provider connection, for field domains.
QgsVectorFileWriter::FieldValueConverter * fieldValueConverter
Field value converter.
QStringList layerOptions
List of OGR layer creation options.
Qgis::WkbType overrideGeometryType
Set to a valid geometry type to override the default geometry type for the layer.
bool includeZ
Sets to true to include z dimension in output. This option is only valid if overrideGeometryType is s...
Qgis::FeatureSymbologyExport symbologyExport
Symbology to export.
bool saveMetadata
Set to true to save layer metadata for the exported vector file.
QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile
Action on existing file.
QgsAttributeList attributes
Attributes to export (empty means all unless skipAttributeCreation is set)
bool onlySelectedFeatures
Write only selected features of layer.
QgsVectorFileWriter::FieldNameSource fieldNameSource
Source for exported field names.
bool skipAttributeCreation
Only write geometries.
bool setFieldDomains
Set to true to transfer field domains to the exported vector file.
QStringList datasourceOptions
List of OGR data source creation options.
QgsFeedback * feedback
Optional feedback object allowing cancellation of layer save.
An available option for configuring file writing for a particular output format, presenting a choice ...
An available option for configuring file writing for a particular output format, presenting a freefor...
A convenience class for writing vector layers to disk based formats (e.g.
static QgsVectorFileWriter::WriterError writeAsVectorFormatV3(QgsVectorLayer *layer, const QString &fileName, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QString *errorMessage=nullptr, QString *newFilename=nullptr, QString *newLayer=nullptr)
Writes a layer out to a vector file.
Qgis::FeatureSymbologyExport mSymbologyExport
QString lastError() const override
Returns the most recent error encountered by the sink, e.g.
@ CanAddNewFieldsToExistingLayer
Flag to indicate that new fields can be added to an existing layer. Imply CanAppendToExistingLayer.
@ CanAppendToExistingLayer
Flag to indicate that new features can be added to an existing layer.
@ CanAddNewLayer
Flag to indicate that a new layer can be added to the dataset.
@ CanDeleteLayer
Flag to indicate that an existing layer can be deleted.
static QgsVectorFileWriter::EditionCapabilities editionCapabilities(const QString &datasetName)
Returns edition capabilities for an existing dataset name.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
static bool supportsFeatureStyles(const QString &driverName)
Returns true if the specified driverName supports feature styles.
Qgis::WkbType mWkbType
Geometry type which is being used.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
double mSymbologyScale
Scale for symbology export (e.g. for symbols units in map units)
QMap< int, int > mAttrIdxToOgrIdx
Map attribute indizes to OGR field indexes.
@ Canceled
Writing was interrupted by manual cancellation.
@ ErrSavingMetadata
Metadata saving failed.
gdal::ogr_datasource_unique_ptr mDS
static Q_DECL_DEPRECATED QgsVectorFileWriter::WriterError writeAsVectorFormatV2(QgsVectorLayer *layer, const QString &fileName, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QString *newFilename=nullptr, QString *newLayer=nullptr, QString *errorMessage=nullptr)
Writes a layer out to a vector file.
OGRGeometryH createEmptyGeometry(Qgis::WkbType wkbType)
QFlags< EditionCapability > EditionCapabilities
Combination of CanAddNewLayer, CanAppendToExistingLayer, CanAddNewFieldsToExistingLayer or CanDeleteL...
~QgsVectorFileWriter() override
Close opened shapefile for writing.
static bool targetLayerExists(const QString &datasetName, const QString &layerName)
Returns whether the target layer already exists.
double symbologyScale() const
Returns the reference scale for output.
static QStringList defaultLayerOptions(const QString &driverName)
Returns a list of the default layer options for a specified driver.
static QString driverForExtension(const QString &extension)
Returns the OGR driver name for a specified file extension.
Qgis::VectorFileWriterCapabilities capabilities() const
Returns the capabilities supported by the writer.
static QList< QgsVectorFileWriter::FilterFormatDetails > supportedFiltersAndFormats(VectorFormatOptions options=SortRecommended)
Returns a list or pairs, with format filter string as first element and OGR format key as second elem...
OGRSpatialReferenceH mOgrRef
static bool driverMetadata(const QString &driverName, MetaData &driverMetadata)
static QgsVectorFileWriter * create(const QString &fileName, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &srs, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QString *newFilename=nullptr, QString *newLayer=nullptr)
Create a new vector file writer.
QString driver() const
Returns the GDAL (short) driver name associated with the output file.
static bool deleteShapeFile(const QString &fileName)
Delete a shapefile (and its accompanying shx / dbf / prj / qix / qpj / cpg / sbn / sbx / idm / ind)
Q_DECL_DEPRECATED QgsVectorFileWriter(const QString &vectorFileName, const QString &fileEncoding, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &srs=QgsCoordinateReferenceSystem(), const QString &driverName="GPKG", const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), QString *newFilename=nullptr, Qgis::FeatureSymbologyExport symbologyExport=Qgis::FeatureSymbologyExport::NoSymbology, QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QString *newLayer=nullptr, const QgsCoordinateTransformContext &transformContext=QgsCoordinateTransformContext(), FieldNameSource fieldNameSource=Original)
Create a new vector file writer.
static Q_DECL_DEPRECATED QgsVectorFileWriter::WriterError writeAsVectorFormat(QgsVectorLayer *layer, const QString &fileName, const QString &fileEncoding, const QgsCoordinateReferenceSystem &destCRS=QgsCoordinateReferenceSystem(), const QString &driverName="GPKG", bool onlySelected=false, QString *errorMessage=nullptr, const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), bool skipAttributeCreation=false, QString *newFilename=nullptr, Qgis::FeatureSymbologyExport symbologyExport=Qgis::FeatureSymbologyExport::NoSymbology, double symbologyScale=1.0, const QgsRectangle *filterExtent=nullptr, Qgis::WkbType overrideGeometryType=Qgis::WkbType::Unknown, bool forceMulti=false, bool includeZ=false, const QgsAttributeList &attributes=QgsAttributeList(), QgsVectorFileWriter::FieldValueConverter *fieldValueConverter=nullptr, QString *newLayer=nullptr)
Write contents of vector layer to an (OGR supported) vector format.
static QString filterForDriver(const QString &driverName)
Creates a filter for an OGR driver key.
QgsVectorFileWriter::WriterError hasError() const
Checks whether there were any errors in constructor.
@ SupportsMultipleLayers
Filter to only formats which support multiple layers.
@ SkipNonSpatialFormats
Filter out any formats which do not have spatial support (e.g. those which cannot save geometries)
static bool areThereNewFieldsToCreate(const QString &datasetName, const QString &layerName, QgsVectorLayer *layer, const QgsAttributeList &attributes)
Returns whether there are among the attributes specified some that do not exist yet in the layer.
static QList< QgsVectorFileWriter::DriverDetails > ogrDriverList(VectorFormatOptions options=SortRecommended)
Returns the driver list that can be used for dialogs.
QString driverLongName() const
Returns the GDAL long driver name associated with the output file.
QFlags< VectorFormatOption > VectorFormatOptions
WriterError mError
Contains error value if construction was not successful.
Qgis::FeatureSymbologyExport symbologyExport() const
Returns the feature symbology export handling for the writer.
FieldNameSource
Source for exported field names.
@ PreferAlias
Use the field alias as the exported field name, wherever one is set. Otherwise use the original field...
@ Original
Use original field names.
bool mIncludeConstraints
Whether to transfer field constraints to output.
static QStringList defaultDatasetOptions(const QString &driverName)
Returns a list of the default dataset options for a specified driver.
bool addFeatureWithStyle(QgsFeature &feature, QgsFeatureRenderer *renderer, Qgis::DistanceUnit outputUnit=Qgis::DistanceUnit::Meters)
Adds a feature to the currently opened data source, using the style from a specified renderer.
static QStringList supportedFormatExtensions(VectorFormatOptions options=SortRecommended)
Returns a list of file extensions for supported formats, e.g "shp", "gpkg".
bool mSetFieldDomains
Whether to set field domains to output.
static QString convertCodecNameForEncodingOption(const QString &codecName)
Converts codec name to string passed to ENCODING layer creation option of OGR Shapefile.
FieldValueConverter * mFieldValueConverter
Field value converter.
QString errorMessage() const
Retrieves error message.
void setSymbologyScale(double scale)
Set reference scale for output.
static OGRwkbGeometryType ogrTypeFromWkbType(Qgis::WkbType type)
Gets the ogr geometry type from an internal QGIS wkb type enum.
QMap< QgsSymbolLayer *, QString > mSymbolLayerTable
static QString fileFilterString(VectorFormatOptions options=SortRecommended)
Returns filter string that can be used for dialogs.
ActionOnExistingFile
Enumeration to describe how to handle existing files.
@ CreateOrOverwriteLayer
Create or overwrite layer.
@ CreateOrOverwriteFile
Create or overwrite file.
@ AppendToLayerNoNewFields
Append features to existing layer, but do not create new fields.
@ AppendToLayerAddFields
Append features to existing layer, and create new fields if needed.
Represents a vector layer which manages a vector based dataset.
long long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
Q_INVOKABLE const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
QString storageType() const
Returns the permanent storage type for this layer as a friendly name.
Q_INVOKABLE Qgis::WkbType wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
QgsFeatureRenderer * renderer()
Returns the feature renderer used for rendering the features in the layer in 2D map views.
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider, it may be nullptr.
void minimumAndMaximumValue(int index, QVariant &minimum, QVariant &maximum) const
Calculates both the minimum and maximum value for an attribute column.
static Qgis::WkbType to25D(Qgis::WkbType type)
Will convert the 25D version of the flat type if supported or Unknown if not supported.
static Qgis::WkbType addZ(Qgis::WkbType type)
Adds the z dimension to a WKB type and returns the new type.
static Q_INVOKABLE bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
static Qgis::WkbType singleType(Qgis::WkbType type)
Returns the single type for a WKB type.
Definition qgswkbtypes.h:53
static Q_INVOKABLE bool hasM(Qgis::WkbType type)
Tests whether a WKB type contains m values.
static Qgis::WkbType multiType(Qgis::WkbType type)
Returns the multi type for a WKB type.
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
static Q_INVOKABLE bool isMultiType(Qgis::WkbType type)
Returns true if the WKB type is a multi type.
std::unique_ptr< std::remove_pointer< OGRFeatureH >::type, OGRFeatureDeleter > ogr_feature_unique_ptr
Scoped OGR feature.
std::unique_ptr< std::remove_pointer< OGRDataSourceH >::type, OGRDataSourceDeleter > ogr_datasource_unique_ptr
Scoped OGR data source.
std::unique_ptr< std::remove_pointer< OGRFieldDefnH >::type, OGRFldDeleter > ogr_field_def_unique_ptr
Scoped OGR field definition.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:6945
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:6944
QList< QgsFeature > QgsFeatureList
QList< int > QgsAttributeList
Definition qgsfield.h:27
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:41
#define QgsDebugError(str)
Definition qgslogger.h:40
QList< QgsSymbolLevel > QgsSymbolLevelOrder
Definition qgsrenderer.h:93
QList< QgsSymbolLevelItem > QgsSymbolLevel
Definition qgsrenderer.h:89
QList< QgsSymbol * > QgsSymbolList
Definition qgsrenderer.h:48
QStringList multiLayerFormats()
Details of available driver formats.
QString longName
Descriptive, user friendly name for the driver.
QString driverName
Unique driver name.
Details of available filters and formats.
QString filterString
Filter string for file picker dialogs.
QStringList globs
Matching glob patterns for format, e.g.
QMap< QString, QgsVectorFileWriter::Option * > driverOptions
QMap< QString, QgsVectorFileWriter::Option * > layerOptions