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