24#include <cpl_string.h>
29#include <ogr_srs_api.h>
54#include <QJsonDocument>
57#include <QRegularExpression>
63using namespace Qt::StringLiterals;
84 const QString &vectorFileName,
85 const QString &fileEncoding,
89 const QString &driverName,
90 const QStringList &datasourceOptions,
91 const QStringList &layerOptions,
104 init( vectorFileName, fileEncoding, fields, geometryType, srs, driverName, datasourceOptions, layerOptions, newFilename,
nullptr, QString(),
CreateOrOverwriteFile, newLayer, sinkFlags, transformContext, fieldNameSource,
nullptr );
108 const QString &vectorFileName,
109 const QString &fileEncoding,
113 const QString &driverName,
114 const QStringList &datasourceOptions,
115 const QStringList &layerOptions,
116 QString *newFilename,
119 const QString &layerName,
125 bool includeConstraints,
126 bool setFieldDomains,
136 init( vectorFileName, fileEncoding, fields, geometryType, srs, driverName, datasourceOptions, layerOptions, newFilename, fieldValueConverter, layerName, action, newLayer, sinkFlags, transformContext, fieldNameSource, sourceDatabaseProviderConnection );
140 const QString &fileName,
147 QString *newFilename,
175 return std::unique_ptr<QgsVectorFileWriter>( writer );
180 if ( driverName ==
"MapInfo MIF"_L1 )
184 GDALDriverH gdalDriver = GDALGetDriverByName( driverName.toLocal8Bit().constData() );
188 CSLConstList
driverMetadata = GDALGetMetadata( gdalDriver,
nullptr );
192#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 7, 0 )
193 return CSLFetchBoolean(
driverMetadata, GDAL_DCAP_FEATURE_STYLES_WRITE,
false );
195 return CSLFetchBoolean(
driverMetadata, GDAL_DCAP_FEATURE_STYLES,
false );
199void QgsVectorFileWriter::init(
200 QString vectorFileName,
201 QString fileEncoding,
205 const QString &driverName,
206 QStringList datasourceOptions,
207 QStringList layerOptions,
208 QString *newFilename,
209 FieldValueConverter *fieldValueConverter,
210 const QString &layerNameIn,
211 ActionOnExistingFile action,
215 FieldNameSource fieldNameSource,
219#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION( 3, 5, 0 )
220 ( void ) sourceDatabaseProviderConnection;
225 if ( vectorFileName.isEmpty() )
232 if ( driverName ==
"MapInfo MIF"_L1 )
236 else if ( driverName ==
"SpatiaLite"_L1 )
239 if ( !datasourceOptions.contains( u
"SPATIALITE=YES"_s ) )
241 datasourceOptions.append( u
"SPATIALITE=YES"_s );
244 else if ( driverName ==
"DBF file"_L1 )
247 if ( !layerOptions.contains( u
"SHPT=NULL"_s ) )
249 layerOptions.append( u
"SHPT=NULL"_s );
251 srs = QgsCoordinateReferenceSystem();
258#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION( 3, 3, 1 )
259 QString fidFieldName;
262 for (
const QString &layerOption : layerOptions )
264 if ( layerOption.startsWith(
"FID="_L1 ) )
266 fidFieldName = layerOption.mid( 4 );
270 if ( fidFieldName.isEmpty() )
271 fidFieldName = u
"fid"_s;
276 OGRSFDriverH poDriver;
279 poDriver = OGRGetDriverByName(
mOgrDriverName.toLocal8Bit().constData() );
283 mErrorMessage = QObject::tr(
"OGR driver for '%1' not found (OGR error: %2)" ).arg( driverName, QString::fromUtf8( CPLGetLastErrorMsg() ) );
288 mOgrDriverLongName = QString( GDALGetMetadataItem( poDriver, GDAL_DMD_LONGNAME,
nullptr ) );
295 if ( layerOptions.join( QString() ).toUpper().indexOf(
"ENCODING="_L1 ) == -1 )
300 if ( driverName ==
"ESRI Shapefile"_L1 && !vectorFileName.endsWith(
".shp"_L1, Qt::CaseInsensitive ) )
302 vectorFileName +=
".shp"_L1;
304 else if ( driverName ==
"DBF file"_L1 && !vectorFileName.endsWith(
".dbf"_L1, Qt::CaseInsensitive ) )
306 vectorFileName +=
".dbf"_L1;
316 QStringList allExts = metadata.glob.split(
' ', Qt::SkipEmptyParts );
318 const auto constAllExts = allExts;
319 for (
const QString &ext : constAllExts )
322 if ( vectorFileName.endsWith( ext.mid( 1 ), Qt::CaseInsensitive ) )
331 allExts = metadata.ext.split(
' ', Qt::SkipEmptyParts );
332 vectorFileName +=
'.' + allExts[0];
338 if ( vectorFileName.endsWith(
".gdb"_L1, Qt::CaseInsensitive ) )
340 QDir dir( vectorFileName );
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 )
347 QFile::remove( info.absoluteFilePath() );
350 QDir().rmdir( vectorFileName );
354 QFile::remove( vectorFileName );
359 if ( metadataFound && !metadata.compulsoryEncoding.isEmpty() )
361 if ( fileEncoding.compare( metadata.compulsoryEncoding, Qt::CaseInsensitive ) != 0 )
363 QgsDebugMsgLevel( u
"forced %1 encoding for %2"_s.arg( metadata.compulsoryEncoding, driverName ), 2 );
364 fileEncoding = metadata.compulsoryEncoding;
368 char **options =
nullptr;
369 if ( !datasourceOptions.isEmpty() )
371 options =
new char *[datasourceOptions.size() + 1];
372 for (
int i = 0; i < datasourceOptions.size(); i++ )
375 options[i] = CPLStrdup( datasourceOptions[i].toUtf8().constData() );
377 options[datasourceOptions.size()] =
nullptr;
382 mDS.reset( OGR_Dr_CreateDataSource( poDriver, vectorFileName.toUtf8().constData(), options ) );
384 mDS.reset( OGROpen( vectorFileName.toUtf8().constData(), TRUE,
nullptr ) );
388 for (
int i = 0; i < datasourceOptions.size(); i++ )
389 CPLFree( options[i] );
398 mErrorMessage = QObject::tr(
"Creation of data source failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
400 mErrorMessage = QObject::tr(
"Opening of data source in update mode failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
404 QString layerName( layerNameIn );
405 if ( layerName.isEmpty() )
406 layerName = QFileInfo( vectorFileName ).baseName();
410 const int layer_count = OGR_DS_GetLayerCount(
mDS.get() );
411 for (
int i = 0; i < layer_count; i++ )
413 OGRLayerH hLayer = OGR_DS_GetLayer(
mDS.get(), i );
414 if ( EQUAL( OGR_L_GetName( hLayer ), layerName.toUtf8().constData() ) )
416 if ( OGR_DS_DeleteLayer(
mDS.get(), i ) != OGRERR_NONE )
419 mErrorMessage = QObject::tr(
"Overwriting of existing layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
437 mCodec = QTextCodec::codecForName( fileEncoding.toLocal8Bit().constData() );
440 QgsDebugError(
"error finding QTextCodec for " + fileEncoding );
443 mCodec = QTextCodec::codecForName( enc.toLocal8Bit().constData() );
447 mCodec = QTextCodec::codecForLocale();
453 if ( driverName ==
"KML"_L1 || driverName ==
"LIBKML"_L1 || driverName ==
"GPX"_L1 )
455 if ( srs.
authid() !=
"EPSG:4326"_L1 )
459 mCoordinateTransform = std::make_unique<QgsCoordinateTransform>( srs, wgs84, transformContext );
476 int optIndex = layerOptions.indexOf(
"FEATURE_DATASET="_L1 );
477 if ( optIndex != -1 )
479 layerOptions.removeAt( optIndex );
482 if ( !layerOptions.isEmpty() )
484 options =
new char *[layerOptions.size() + 1];
485 for (
int i = 0; i < layerOptions.size(); i++ )
488 options[i] = CPLStrdup( layerOptions[i].toUtf8().constData() );
490 options[layerOptions.size()] =
nullptr;
494 CPLSetConfigOption(
"SHAPE_ENCODING",
"" );
498 mLayer = OGR_DS_CreateLayer(
mDS.get(), layerName.toUtf8().constData(),
mOgrRef, wkbType, options );
501 *newLayer = OGR_L_GetName(
mLayer );
502 if ( driverName ==
"GPX"_L1 )
509 if ( !EQUAL( layerName.toUtf8().constData(),
"track_points" ) && !EQUAL( layerName.toUtf8().constData(),
"route_points" ) )
511 *newLayer = u
"waypoints"_s;
518 const char *pszForceGPXTrack = CSLFetchNameValue( options,
"FORCE_GPX_TRACK" );
519 if ( pszForceGPXTrack && CPLTestBool( pszForceGPXTrack ) )
520 *newLayer = u
"tracks"_s;
522 *newLayer = u
"routes"_s;
528 const char *pszForceGPXRoute = CSLFetchNameValue( options,
"FORCE_GPX_ROUTE" );
529 if ( pszForceGPXRoute && CPLTestBool( pszForceGPXRoute ) )
530 *newLayer = u
"routes"_s;
532 *newLayer = u
"tracks"_s;
542 else if ( driverName ==
"DGN"_L1 )
544 mLayer = OGR_DS_GetLayerByName(
mDS.get(),
"elements" );
548 mLayer = OGR_DS_GetLayerByName(
mDS.get(), layerName.toUtf8().constData() );
553 for (
int i = 0; i < layerOptions.size(); i++ )
554 CPLFree( options[i] );
563 QString layerName = vectorFileName.left( vectorFileName.indexOf(
".shp"_L1, Qt::CaseInsensitive ) );
564 QFile prjFile( layerName +
".qpj" );
565 if ( prjFile.exists() )
573 mErrorMessage = QObject::tr(
"Creation of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
575 mErrorMessage = QObject::tr(
"Opening of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
580 OGRFeatureDefnH defn = OGR_L_GetLayerDefn(
mLayer );
590 QSet<int> existingIdxs;
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 ) )
597 char **papszTokens = CSLTokenizeString2( pszCreateFieldDefnFlags,
" ", 0 );
598 if ( CSLFindString( papszTokens,
"AlternativeName" ) >= 0 )
602 if ( CSLFindString( papszTokens,
"Comment" ) >= 0 )
606 CSLDestroy( papszTokens );
616#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 5, 0 )
617 QSet<QString> existingDestDomainNames;
618 if ( sourceDatabaseProviderConnection )
620 char **domainNames = GDALDatasetGetFieldDomainNames(
mDS.get(),
nullptr );
621 for (
const char *
const *iterDomainNames = domainNames; iterDomainNames && *iterDomainNames; ++iterDomainNames )
623 existingDestDomainNames.insert( QString::fromUtf8( *iterDomainNames ) );
625 CSLDestroy( domainNames );
628#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 6, 0 )
629 QSet< QString > usedAlternativeNames;
632 const QString ogrFidColumnName { OGR_L_GetFIDColumn(
mLayer ) };
633 const int fidNameIndex = OGR_FD_GetFieldIndex( defn, ogrFidColumnName.toUtf8() );
636 const bool promoteFidColumnToAttribute = !ogrFidColumnName.isEmpty() && fidNameIndex < 0 && fields.
lookupField( ogrFidColumnName ) >= 0;
637 int offsetRoomForFid = promoteFidColumnToAttribute ? 1 : 0;
639 for (
int fldIdx = 0; fldIdx < fields.
count(); ++fldIdx )
641 QgsField attrField = fields.
at( fldIdx );
643 if ( fieldValueConverter )
645 attrField = fieldValueConverter->fieldDefinition( fields.
at( fldIdx ) );
650 int ogrIdx = OGR_FD_GetFieldIndex( defn,
mCodec->fromUnicode( attrField.
name() ) );
660 switch ( fieldNameSource )
663 name = attrField.
name();
667 name = !attrField.
alias().isEmpty() ? attrField.
alias() : attrField.
name();
671 OGRFieldType ogrType = OFTString;
672 OGRFieldSubType ogrSubType = OFSTNone;
673 int ogrWidth = attrField.
length();
674 int ogrPrecision = attrField.
precision();
675 if ( ogrPrecision > 0 )
678 switch ( attrField.
type() )
680 case QMetaType::Type::LongLong:
682 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
683 if ( pszDataTypes && strstr( pszDataTypes,
"Integer64" ) )
684 ogrType = OFTInteger64;
687 ogrWidth = ogrWidth > 0 && ogrWidth <= 20 ? ogrWidth : 20;
691 case QMetaType::Type::QString:
693 if ( ( ogrWidth <= 0 || ogrWidth > 255 ) &&
mOgrDriverName ==
"ESRI Shapefile"_L1 )
697 case QMetaType::Type::Int:
698 ogrType = OFTInteger;
699 ogrWidth = ogrWidth > 0 && ogrWidth <= 10 ? ogrWidth : 10;
703 case QMetaType::Type::Bool:
704 ogrType = OFTInteger;
705 ogrSubType = OFSTBoolean;
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 )
715 ogrType = OFTInteger64;
722 case QMetaType::Type::QDate:
726 case QMetaType::Type::QTime:
738 case QMetaType::Type::QDateTime:
746 ogrType = OFTDateTime;
750 case QMetaType::Type::QByteArray:
754 case QMetaType::Type::QStringList:
760 ogrSubType = OFSTJSON;
764 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
765 if ( pszDataTypes && strstr( pszDataTypes,
"StringList" ) )
767 ogrType = OFTStringList;
768 mSupportedListSubTypes.insert( QMetaType::Type::QString );
778 case QMetaType::Type::QVariantMap:
781 const char *pszDataSubTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATASUBTYPES,
nullptr );
782 if ( pszDataSubTypes && strstr( pszDataSubTypes,
"JSON" ) )
785 ogrSubType = OFSTJSON;
793 case QMetaType::Type::QVariantList:
798 ogrSubType = OFSTJSON;
803 if ( attrField.
subType() == QMetaType::Type::QString )
805 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
806 if ( pszDataTypes && strstr( pszDataTypes,
"StringList" ) )
808 ogrType = OFTStringList;
809 mSupportedListSubTypes.insert( QMetaType::Type::QString );
818 else if ( attrField.
subType() == QMetaType::Type::Int )
820 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
821 if ( pszDataTypes && strstr( pszDataTypes,
"IntegerList" ) )
823 ogrType = OFTIntegerList;
824 mSupportedListSubTypes.insert( QMetaType::Type::Int );
833 else if ( attrField.
subType() == QMetaType::Type::Double )
835 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
836 if ( pszDataTypes && strstr( pszDataTypes,
"RealList" ) )
838 ogrType = OFTRealList;
839 mSupportedListSubTypes.insert( QMetaType::Type::Double );
848 else if ( attrField.
subType() == QMetaType::Type::LongLong )
850 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
851 if ( pszDataTypes && strstr( pszDataTypes,
"Integer64List" ) )
853 ogrType = OFTInteger64List;
854 mSupportedListSubTypes.insert( QMetaType::Type::LongLong );
868 mErrorMessage = QObject::tr(
"Unsupported type for field %1" ).arg( attrField.
name() );
873 if (
mOgrDriverName ==
"SQLite"_L1 && name.compare(
"ogc_fid"_L1, Qt::CaseInsensitive ) == 0 )
876 for ( i = 0; i < 10; i++ )
878 name = u
"ogc_fid%1"_s.arg( i );
881 for ( j = 0; j < fields.
size() && name.compare( fields.
at( j ).
name(), Qt::CaseInsensitive ) != 0; j++ )
884 if ( j == fields.
size() )
890 mErrorMessage = QObject::tr(
"No available replacement for internal fieldname ogc_fid found" ).arg( attrField.
name() );
895 QgsMessageLog::logMessage( QObject::tr(
"Reserved attribute name ogc_fid replaced with %1" ).arg( name ), QObject::tr(
"OGR" ) );
902 OGR_Fld_SetWidth( fld.get(), ogrWidth );
905 if ( ogrPrecision >= 0 )
907 OGR_Fld_SetPrecision( fld.get(), ogrPrecision );
910 if ( ogrSubType != OFSTNone )
911 OGR_Fld_SetSubType( fld.get(), ogrSubType );
913#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 6, 0 )
914 if ( !attrField.
alias().isEmpty() )
916 QString alternativeName = attrField.
alias();
918 while ( usedAlternativeNames.contains( alternativeName ) )
921 alternativeName = attrField.
alias() + u
" (%1)"_s.arg( ++counter );
923 OGR_Fld_SetAlternativeName( fld.get(),
mCodec->fromUnicode( alternativeName ).constData() );
924 usedAlternativeNames.insert( alternativeName );
927#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 7, 0 )
928 OGR_Fld_SetComment( fld.get(),
mCodec->fromUnicode( attrField.
comment() ).constData() );
935 OGR_Fld_SetNullable( fld.get(),
false );
939 OGR_Fld_SetUnique( fld.get(),
true );
942#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 5, 0 )
946 if ( !domainName.isEmpty() )
948 bool canSetFieldDomainName =
false;
949 if ( existingDestDomainNames.contains( domainName ) )
953 canSetFieldDomainName =
true;
955 else if ( GDALDatasetTestCapability(
mDS.get(), ODsCAddFieldDomain ) )
965 std::unique_ptr<QgsFieldDomain> domain( sourceDatabaseProviderConnection->
fieldDomain( domainName ) );
971 char *pszFailureReason =
nullptr;
972 if ( GDALDatasetAddFieldDomain(
mDS.get(), hFieldDomain, &pszFailureReason ) )
974 existingDestDomainNames.insert( domainName );
975 canSetFieldDomainName =
true;
979 QgsDebugError( u
"cannot create field domain: %1"_s.arg( pszFailureReason ) );
981 CPLFree( pszFailureReason );
982 OGR_FldDomain_Destroy( hFieldDomain );
986 catch ( QgsProviderConnectionException & )
988 QgsDebugError( u
"Cannot retrieve field domain: %1"_s.arg( domainName ) );
991 if ( canSetFieldDomainName )
993 OGR_Fld_SetDomainName( fld.get(), domainName.toUtf8().toStdString().c_str() );
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 )
1004 mErrorMessage = QObject::tr(
"Creation of field %1 (%2) failed (OGR error: %3)" ).arg( attrField.
name(), QMetaType( attrField.
type() ).name(), QString::fromUtf8( CPLGetLastErrorMsg() ) );
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 ) )
1014 ogrIdx = OGR_FD_GetFieldCount( defn ) - 1;
1019 mErrorMessage = QObject::tr(
"Created field %1 not found (OGR error: %2)" ).arg( attrField.
name(), QString::fromUtf8( CPLGetLastErrorMsg() ) );
1025 existingIdxs.insert( ogrIdx );
1028 if ( promoteFidColumnToAttribute )
1030 if ( ogrFidColumnName.compare( attrField.
name(), Qt::CaseInsensitive ) == 0 )
1033 offsetRoomForFid = 0;
1038 ogrIdx += offsetRoomForFid;
1049 for (
int fldIdx = 0; fldIdx < fields.
count(); ++fldIdx )
1051 QgsField attrField = fields.
at( fldIdx );
1052 QString name( attrField.
name() );
1053 int ogrIdx = OGR_FD_GetFieldIndex( defn,
mCodec->fromUnicode( name ) );
1082 *newFilename = vectorFileName;
1085 mUsingTransaction =
true;
1086 if ( OGRERR_NONE != OGR_L_StartTransaction(
mLayer ) )
1088 mUsingTransaction =
false;
1098class QgsVectorFileWriterMetadataContainer
1101 QgsVectorFileWriterMetadataContainer()
1103 QMap<QString, QgsVectorFileWriter::Option *> datasetOptions;
1104 QMap<QString, QgsVectorFileWriter::Option *> layerOptions;
1107 datasetOptions.clear();
1108 layerOptions.clear();
1110 layerOptions.insert(
1113 QObject::tr(
"Compression method." ),
1114 QStringList() << u
"UNCOMPRESSED"_s << u
"ZSTD"_s << u
"LZ4"_s,
1120 layerOptions.insert(
1121 u
"GEOMETRY_ENCODING"_s,
1123 QObject::tr(
"Geometry encoding." ),
1124 QStringList() << u
"GEOARROW"_s << u
"WKB"_s << u
"WKT"_s,
1130 layerOptions.insert(
1133 QObject::tr(
"Maximum number of rows per batch." ),
1138 layerOptions.insert(
1141 QObject::tr(
"Name for the feature identifier column" ),
1146 layerOptions.insert(
1149 QObject::tr(
"Name for the geometry column" ),
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 ) );
1157 datasetOptions.clear();
1158 layerOptions.clear();
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 ) );
1163 datasetOptions.clear();
1164 layerOptions.clear();
1166 layerOptions.insert(
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."
1175 QStringList() << u
"CRLF"_s << u
"LF"_s,
1181 layerOptions.insert(
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."
1191 QStringList() << u
"AS_WKT"_s << u
"AS_XYZ"_s << u
"AS_XY"_s << u
"AS_YX"_s,
1197 layerOptions.insert(
1200 QObject::tr(
"Name of geometry column. Only used if GEOMETRY=AS_WKT. Defaults to 'WKT'." ),
1205 layerOptions.insert(
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."
1217 layerOptions.insert(
1220 QObject::tr(
"Field separator character." ),
1226#
if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 12, 0 )
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,
1243 layerOptions.insert(
1246 QObject::tr(
"Write a UTF-8 Byte Order Mark (BOM) at the start of the file." ),
1251#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 12, 0 )
1252 layerOptions.insert(
1255 QObject::tr(
"Whether to write a header line with the field names." ),
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 ) );
1264 datasetOptions.clear();
1265 layerOptions.clear();
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 ) );
1270 datasetOptions.clear();
1271 layerOptions.clear();
1273 layerOptions.insert(
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;"
1283 " POINTM, ARCM, POLYGONM or MULTIPOINTM for measured geometries"
1284 " and POINTZM, ARCZM, POLYGONZM or MULTIPOINTZM for 3D measured"
1287 + QObject::tr(
" MULTIPATCH files are supported since GDAL 2.2." )
1306 << u
"MULTIPOINTZM"_s
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." ),
1327 layerOptions.insert(
1330 QObject::tr(
"Set to YES to resize fields to their optimal size." ),
1335 driverMetadata.insert( u
"ESRI"_s,
QgsVectorFileWriter::MetaData( u
"ESRI Shapefile"_s, QObject::tr(
"ESRI Shapefile" ), u
"*.shp"_s, u
"shp"_s, datasetOptions, layerOptions ) );
1338 datasetOptions.clear();
1339 layerOptions.clear();
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 ) );
1344 datasetOptions.clear();
1345 layerOptions.clear();
1347 layerOptions.insert(
1351 "Set to YES to write a bbox property with the bounding box "
1352 "of the geometries at the feature and feature collection level."
1358 layerOptions.insert(
1359 u
"COORDINATE_PRECISION"_s,
1362 "Maximum number of figures after decimal separator to write in coordinates. "
1363 "Defaults to 15. Truncation will occur to remove trailing zeros."
1369 layerOptions.insert(
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)"
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 ) );
1384 datasetOptions.clear();
1385 layerOptions.clear();
1387 layerOptions.insert(
1388 u
"COORDINATE_PRECISION"_s,
1391 "Maximum number of figures after decimal separator to write in coordinates. "
1392 "Defaults to 15. Truncation will occur to remove trailing zeros."
1398 layerOptions.insert(
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)."
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 ) );
1414 datasetOptions.clear();
1415 layerOptions.clear();
1417 datasetOptions.insert(
1421 "whether the document must be in RSS 2.0 or Atom 1.0 format. "
1422 "Default value : RSS"
1424 QStringList() << u
"RSS"_s << u
"ATOM"_s,
1429 datasetOptions.insert(
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."
1437 QStringList() << u
"SIMPLE"_s << u
"GML"_s << u
"W3C_GEO"_s,
1442 datasetOptions.insert(
1443 u
"USE_EXTENSIONS"_s,
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."
1456 datasetOptions.insert(
1457 u
"WRITE_HEADER_AND_FOOTER"_s,
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."
1467 datasetOptions.insert(
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."
1479 datasetOptions.insert(
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."
1490 datasetOptions.insert(
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."
1501 datasetOptions.insert(
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."
1512 datasetOptions.insert(
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."
1524 datasetOptions.insert(
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."
1535 datasetOptions.insert(
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."
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 ) );
1549 datasetOptions.clear();
1550 layerOptions.clear();
1552 datasetOptions.insert(
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."
1565 datasetOptions.insert(
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)."
1575 QStringList() << u
"EXTERNAL"_s << u
"INTERNAL"_s << u
"OFF"_s,
1580 datasetOptions.insert(
1583 QObject::tr(
"This is the prefix for the application target namespace." ),
1588 datasetOptions.insert(
1592 "Can be set to TRUE to avoid writing the prefix of the "
1593 "application target namespace in the GML file."
1599 datasetOptions.insert(
1600 u
"TARGET_NAMESPACE"_s,
1603 "Defaults to 'http://ogr.maptools.org/'. "
1604 "This is the application target namespace."
1606 u
"http://ogr.maptools.org/"_s
1610 datasetOptions.insert(
1613 QObject::tr(
"GML version to use." ),
1614 QStringList() << u
"GML2"_s << u
"GML3"_s << u
"GML3Deegree"_s << u
"GML3.2"_s,
1619 datasetOptions.insert(
1623 "Only valid when FORMAT=GML3/GML3Degree/GML3.2. Default to YES. "
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."
1636 datasetOptions.insert(
1637 u
"WRITE_FEATURE_BOUNDED_BY"_s,
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 "
1648 datasetOptions.insert(
1649 u
"SPACE_INDENTATION"_s,
1652 "Default to YES. If YES, the output will be indented with spaces "
1653 "for more readability, but at the expense of file size."
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 ) );
1664 datasetOptions.clear();
1665 layerOptions.clear();
1667 layerOptions.insert(
1670 QObject::tr(
"Human-readable identifier (e.g. short name) for the layer content" ),
1675 layerOptions.insert(
1678 QObject::tr(
"Human-readable description for the layer content" ),
1683 layerOptions.insert(
1686 QObject::tr(
"Name for the feature identifier column" ),
1691 layerOptions.insert(
1694 QObject::tr(
"Name for the geometry column" ),
1699 layerOptions.insert(
1702 QObject::tr(
"If a spatial index must be created." ),
1707 driverMetadata.insert(
1711 QObject::tr(
"GeoPackage" ),
1712#
if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 7, 0 )
1713 u
"*.gpkg *.gpkg.zip"_s,
1725 datasetOptions.clear();
1726 layerOptions.clear();
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 ) );
1731 datasetOptions.clear();
1732 layerOptions.clear();
1734 layerOptions.insert(
1735 u
"FORCE_GPX_TRACK"_s,
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."
1747 layerOptions.insert(
1748 u
"FORCE_GPX_ROUTE"_s,
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."
1761 datasetOptions.insert(
1762 u
"GPX_USE_EXTENSIONS"_s,
1765 "If GPX_USE_EXTENSIONS=YES is specified, "
1766 "extra fields will be written inside the <extensions> tag."
1772 datasetOptions.insert(
1773 u
"GPX_EXTENSIONS_NS"_s,
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'."
1783 datasetOptions.insert(
1784 u
"GPX_EXTENSIONS_NS_URL"_s,
1787 "Only used if GPX_USE_EXTENSIONS=YES and GPX_EXTENSIONS_NS "
1788 "is set. The namespace URI. By default, 'http://osgeo.org/gdal'."
1790 u
"http://osgeo.org/gdal"_s
1794 datasetOptions.insert(
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)."
1804 QStringList() << u
"CRLF"_s << u
"LF"_s,
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 ) );
1813 datasetOptions.clear();
1814 layerOptions.clear();
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 ) );
1819 datasetOptions.clear();
1820 layerOptions.clear();
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 ) );
1825 datasetOptions.clear();
1826 layerOptions.clear();
1828 datasetOptions.insert(
1831 QObject::tr(
"Allows you to specify the field to use for the KML <name> element." ),
1836 datasetOptions.insert(
1837 u
"DescriptionField"_s,
1839 QObject::tr(
"Allows you to specify the field to use for the KML <description> element." ),
1844 datasetOptions.insert(
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."
1851 QStringList() << u
"clampToGround"_s << u
"relativeToGround"_s << u
"absolute"_s,
1852 u
"relativeToGround"_s
1856 datasetOptions.insert(
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."
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 ) );
1871 datasetOptions.clear();
1872 layerOptions.clear();
1874 auto insertMapInfoOptions = []( QMap<QString, QgsVectorFileWriter::Option *> &datasetOptions, QMap<QString, QgsVectorFileWriter::Option *> &layerOptions ) {
1875 datasetOptions.insert(
1876 u
"SPATIAL_INDEX_MODE"_s,
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."
1883 QStringList() << u
"QUICK"_s << u
"OPTIMIZED"_s,
1889 datasetOptions.insert(
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."
1901 layerOptions.insert(
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."
1913 insertMapInfoOptions( datasetOptions, layerOptions );
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 );
1921 driverMetadata.insert( u
"MapInfo MIF"_s, QgsVectorFileWriter::MetaData( u
"Mapinfo"_s, QObject::tr(
"Mapinfo MIF" ), u
"*.mif"_s, u
"mif"_s, datasetOptions, layerOptions ) );
1924 datasetOptions.clear();
1925 layerOptions.clear();
1927 datasetOptions.insert(
1929 new QgsVectorFileWriter::BoolOption(
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."
1938 datasetOptions.insert(
1940 new QgsVectorFileWriter::StringOption(
1941 QObject::tr(
"Override the seed file to use." ),
1946 datasetOptions.insert(
1947 u
"COPY_WHOLE_SEED_FILE"_s,
1948 new QgsVectorFileWriter::BoolOption(
1950 "Indicate whether the whole seed file should be copied. "
1951 "If not, only the first three elements will be copied."
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." ),
1965 datasetOptions.insert(
1966 u
"MASTER_UNIT_NAME"_s,
1967 new QgsVectorFileWriter::StringOption(
1969 "Override the master unit name from the seed file with "
1970 "the provided one or two character unit name."
1976 datasetOptions.insert(
1978 new QgsVectorFileWriter::StringOption(
1980 "Override the sub unit name from the seed file with the provided "
1981 "one or two character unit name."
1987 datasetOptions.insert(
1988 u
"SUB_UNITS_PER_MASTER_UNIT"_s,
1989 new QgsVectorFileWriter::IntOption(
1991 "Override the number of subunits per master unit. "
1992 "By default the seed file value is used."
1998 datasetOptions.insert(
1999 u
"UOR_PER_SUB_UNIT"_s,
2000 new QgsVectorFileWriter::IntOption(
2002 "Override the number of UORs (Units of Resolution) "
2003 "per sub unit. By default the seed file value is used."
2009 datasetOptions.insert(
2011 new QgsVectorFileWriter::StringOption(
2013 "ORIGIN=x,y,z: Override the origin of the design plane. "
2014 "By default the origin from the seed file is used."
2020 driverMetadata.insert( u
"DGN"_s, QgsVectorFileWriter::MetaData( u
"Microstation DGN"_s, QObject::tr(
"Microstation DGN" ), u
"*.dgn"_s, u
"dgn"_s, datasetOptions, layerOptions ) );
2023 datasetOptions.clear();
2024 layerOptions.clear();
2026 datasetOptions.insert(
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,
2035 datasetOptions.insert(
2036 u
"SPLIT_MULTIPOINT"_s,
2037 new QgsVectorFileWriter::BoolOption(
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."
2048 datasetOptions.insert(
2049 u
"ADD_SOUNDG_DEPTH"_s,
2050 new QgsVectorFileWriter::BoolOption(
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 "
2060 datasetOptions.insert(
2061 u
"RETURN_PRIMITIVES"_s,
2062 new QgsVectorFileWriter::BoolOption(
2064 "Should all the low level geometry primitives be returned as special "
2065 "IsolatedNode, ConnectedNode, Edge and Face layers."
2071 datasetOptions.insert(
2072 u
"PRESERVE_EMPTY_NUMBERS"_s,
2073 new QgsVectorFileWriter::BoolOption(
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."
2083 datasetOptions.insert(
2085 new QgsVectorFileWriter::BoolOption(
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."
2094 datasetOptions.insert(
2095 u
"RETURN_LINKAGES"_s,
2096 new QgsVectorFileWriter::BoolOption(
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."
2106 datasetOptions.insert(
2107 u
"RECODE_BY_DSSI"_s,
2108 new QgsVectorFileWriter::BoolOption(
2110 "Should attribute values be recoded to UTF-8 from the character encoding "
2111 "specified in the S57 DSSI record."
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 ) );
2122 datasetOptions.clear();
2123 layerOptions.clear();
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 ) );
2129 datasetOptions.clear();
2130 layerOptions.clear();
2132 datasetOptions.insert(
2134 new QgsVectorFileWriter::BoolOption(
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."
2145 datasetOptions.insert( u
"SPATIALITE"_s,
new QgsVectorFileWriter::HiddenOption( u
"NO"_s ) );
2148 datasetOptions.insert( u
"INIT_WITH_EPSG"_s,
new QgsVectorFileWriter::HiddenOption( u
"NO"_s ) );
2150 layerOptions.insert(
2152 new QgsVectorFileWriter::SetOption(
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)."
2158 QStringList() << u
"WKB"_s << u
"WKT"_s,
2163 layerOptions.insert(
2165 new QgsVectorFileWriter::BoolOption(
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."
2175 layerOptions.insert( u
"SPATIAL_INDEX"_s,
new QgsVectorFileWriter::HiddenOption( u
"NO"_s ) );
2177 layerOptions.insert( u
"COMPRESS_GEOM"_s,
new QgsVectorFileWriter::HiddenOption( u
"NO"_s ) );
2179 layerOptions.insert( u
"SRID"_s,
new QgsVectorFileWriter::HiddenOption( QString() ) );
2181 layerOptions.insert(
2182 u
"COMPRESS_COLUMNS"_s,
2183 new QgsVectorFileWriter::StringOption(
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."
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 ) );
2202 datasetOptions.clear();
2203 layerOptions.clear();
2205 datasetOptions.insert(
2207 new QgsVectorFileWriter::BoolOption(
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."
2217 datasetOptions.insert( u
"SPATIALITE"_s,
new QgsVectorFileWriter::HiddenOption( u
"YES"_s ) );
2219 datasetOptions.insert(
2220 u
"INIT_WITH_EPSG"_s,
2221 new QgsVectorFileWriter::BoolOption(
2223 "Insert the content of the EPSG CSV files into the spatial_ref_sys table. "
2224 "Set to NO for regular SQLite databases."
2230 layerOptions.insert( u
"FORMAT"_s,
new QgsVectorFileWriter::HiddenOption( u
"SPATIALITE"_s ) );
2232 layerOptions.insert(
2234 new QgsVectorFileWriter::BoolOption(
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."
2244 layerOptions.insert(
2246 new QgsVectorFileWriter::BoolOption(
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."
2256 layerOptions.insert(
2258 new QgsVectorFileWriter::BoolOption(
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."
2268 layerOptions.insert(
2270 new QgsVectorFileWriter::StringOption(
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."
2284 layerOptions.insert(
2285 u
"COMPRESS_COLUMNS"_s,
2286 new QgsVectorFileWriter::StringOption(
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."
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 ) );
2304 datasetOptions.clear();
2305 layerOptions.clear();
2307 datasetOptions.insert(
2309 new QgsVectorFileWriter::StringOption(
2310 QObject::tr(
"Override the header file used - in place of header.dxf." ),
2315 datasetOptions.insert(
2317 new QgsVectorFileWriter::StringOption(
2318 QObject::tr(
"Override the trailer file used - in place of trailer.dxf." ),
2323#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 11, 0 )
2324 datasetOptions.insert(
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,
2333 datasetOptions.insert(
2335 new QgsVectorFileWriter::SetOption(
2337 "Whether the current drawing uses imperial or metric hatch "
2338 "pattern and linetype ($MEASUREMENT system variable)."
2340 QStringList() << u
"HEADER_VALUE"_s << u
"IMPERIAL"_s << u
"METRIC"_s,
2346 driverMetadata.insert( u
"DXF"_s, QgsVectorFileWriter::MetaData( u
"AutoCAD DXF"_s, QObject::tr(
"AutoCAD DXF" ), u
"*.dxf"_s, u
"dxf"_s, datasetOptions, layerOptions ) );
2349 datasetOptions.clear();
2350 layerOptions.clear();
2352 datasetOptions.insert(
2354 new QgsVectorFileWriter::SetOption(
2356 "Indicates the GeoConcept export file extension. "
2357 "TXT was used by earlier releases of GeoConcept. GXT is currently used."
2359 QStringList() << u
"GXT"_s << u
"TXT"_s,
2364 datasetOptions.insert(
2366 new QgsVectorFileWriter::StringOption(
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."
2376 datasetOptions.insert(
2378 new QgsVectorFileWriter::StringOption(
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 "
2389 driverMetadata.insert( u
"Geoconcept"_s, QgsVectorFileWriter::MetaData( u
"Geoconcept"_s, QObject::tr(
"Geoconcept" ), u
"*.gxt *.txt"_s, u
"gxt"_s, datasetOptions, layerOptions ) );
2392 datasetOptions.clear();
2393 layerOptions.clear();
2395#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 9, 0 )
2396 layerOptions.insert(
2397 u
"TARGET_ARCGIS_VERSION"_s,
2398 new QgsVectorFileWriter::SetOption(
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."
2403 QStringList() << u
"ALL"_s << u
"ARCGIS_PRO_3_2_OR_LATER"_s,
2409 layerOptions.insert(
2410 u
"FEATURE_DATASET"_s,
2411 new QgsVectorFileWriter::StringOption(
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."
2420 layerOptions.insert(
2422 new QgsVectorFileWriter::StringOption(
2423 QObject::tr(
"Set layer name alias." ),
2428 layerOptions.insert(
2430 new QgsVectorFileWriter::StringOption(
2431 QObject::tr(
"Set name of geometry column in new layer. Defaults to 'SHAPE'." ),
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'." ),
2444 layerOptions.insert(
2446 new QgsVectorFileWriter::StringOption(
2447 QObject::tr(
"Name of the OID column to create. Defaults to 'OBJECTID'." ),
2464 layerOptions.insert(
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." ),
2472 layerOptions.insert(
2474 new QgsVectorFileWriter::StringOption(
2475 QObject::tr(
"XML documentation for the layer." ),
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 },
2489 layerOptions.insert(
2490 u
"CREATE_SHAPE_AREA_AND_LENGTH_FIELDS"_s,
2491 new QgsVectorFileWriter::BoolOption(
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."
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 ) );
2504#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION( 3, 11, 0 )
2506 datasetOptions.clear();
2507 layerOptions.clear();
2509 layerOptions.insert(
2510 u
"FEATURE_DATASET"_s,
2511 new QgsVectorFileWriter::StringOption(
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."
2520 layerOptions.insert(
2522 new QgsVectorFileWriter::StringOption(
2523 QObject::tr(
"Set name of geometry column in new layer. Defaults to 'SHAPE'." ),
2528 layerOptions.insert(
2530 new QgsVectorFileWriter::StringOption(
2531 QObject::tr(
"Name of the OID column to create. Defaults to 'OBJECTID'." ),
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 ) );
2540 datasetOptions.clear();
2541 layerOptions.clear();
2543 layerOptions.insert(
2544 u
"OGR_XLSX_FIELD_TYPES"_s,
2545 new QgsVectorFileWriter::SetOption(
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."
2550 QStringList() << u
"AUTO"_s << u
"STRING"_s,
2556 layerOptions.insert(
2557 u
"OGR_XLSX_HEADERS"_s,
2558 new QgsVectorFileWriter::SetOption(
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."
2566 QStringList() << u
"FORCE"_s << u
"DISABLE"_s << u
"AUTO"_s,
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 ) );
2576 datasetOptions.clear();
2577 layerOptions.clear();
2579 layerOptions.insert(
2580 u
"OGR_ODS_FIELD_TYPES"_s,
2581 new QgsVectorFileWriter::SetOption(
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."
2586 QStringList() << u
"AUTO"_s << u
"STRING"_s,
2592 layerOptions.insert(
2593 u
"OGR_ODS_HEADERS"_s,
2594 new QgsVectorFileWriter::SetOption(
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."
2602 QStringList() << u
"FORCE"_s << u
"DISABLE"_s << u
"AUTO"_s,
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 ) );
2611 datasetOptions.clear();
2612 layerOptions.clear();
2614 QStringList compressionMethods;
2615 const QStringList searchCompressions = { u
"NONE"_s, u
"SNAPPY"_s, u
"BROTLI"_s, u
"ZSTD"_s };
2617 if ( GDALDriverH hParquetDrv = GDALGetDriverByName(
"PARQUET" ) )
2619 if (
const char *xml = GDALGetMetadataItem( hParquetDrv, GDAL_DS_LAYER_CREATIONOPTIONLIST,
nullptr ) )
2621 for (
const QString &comp : searchCompressions )
2623 QRegularExpression re(
"<Value[^>]*>\\s*" + comp +
"\\s*</Value>" );
2624 if ( re.match( QString::fromUtf8( xml ) ).hasMatch() )
2626 compressionMethods << comp;
2632 layerOptions.insert(
2634 new QgsVectorFileWriter::SetOption(
2635 QObject::tr(
"Compression method." ),
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." ),
2652#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION( 3, 9, 0 )
2653 layerOptions.insert(
2655 new QgsVectorFileWriter::BoolOption(
2656 QObject::tr(
"Whether to sort by spatial location. Enables faster spatial filtering on reading." ),
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." ),
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,
2680 layerOptions.insert(
2681 u
"ROW_GROUP_SIZE"_s,
2682 new QgsVectorFileWriter::IntOption(
2683 QObject::tr(
"Maximum number of rows per group." ),
2688 layerOptions.insert(
2690 new QgsVectorFileWriter::StringOption(
2691 QObject::tr(
"Name for the feature identifier column" ),
2696 layerOptions.insert(
2698 new QgsVectorFileWriter::StringOption(
2699 QObject::tr(
"Name for the geometry column" ),
2704 layerOptions.insert(
2706 new QgsVectorFileWriter::SetOption(
2707 QObject::tr(
"Name of the coordinate system for the edges." ),
2708 QStringList() << u
"PLANAR"_s << u
"SPHERICAL"_s,
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 ) );
2717 datasetOptions.clear();
2718 layerOptions.clear();
2720 datasetOptions.insert(
2722 new QgsVectorFileWriter::SetOption(
2723 QObject::tr(
"Line termination character sequence." ),
2724 QStringList() << u
"CRLF"_s << u
"LF"_s,
2731 layerOptions.insert(
2733 new QgsVectorFileWriter::SetOption(
2734 QObject::tr(
"Format of geometry columns." ),
2735 QStringList() << u
"geometry"_s << u
"geography"_s,
2741 layerOptions.insert(
2743 new QgsVectorFileWriter::BoolOption(
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."
2753 layerOptions.insert(
2755 new QgsVectorFileWriter::StringOption(
2757 "Name for the geometry column. Defaults to wkb_geometry "
2758 "for GEOM_TYPE=geometry or the_geog for GEOM_TYPE=geography"
2763 layerOptions.insert( u
"SCHEMA"_s,
new QgsVectorFileWriter::StringOption( QObject::tr(
"Name of schema into which to create the new table" ) ) );
2765 layerOptions.insert(
2767 new QgsVectorFileWriter::BoolOption(
2768 QObject::tr(
"Whether to explicitly emit the CREATE SCHEMA statement to create the specified schema." ),
2773 layerOptions.insert(
2775 new QgsVectorFileWriter::BoolOption(
2776 QObject::tr(
"Whether to explicitly recreate the table if necessary." ),
2781 layerOptions.insert(
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,
2791 layerOptions.insert(
2793 new QgsVectorFileWriter::StringOption(
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."
2807 layerOptions.insert(
2808 u
"POSTGIS_VERSION"_s,
2809 new QgsVectorFileWriter::StringOption(
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"
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 ) );
2821 QgsVectorFileWriterMetadataContainer(
const QgsVectorFileWriterMetadataContainer &other ) =
delete;
2822 QgsVectorFileWriterMetadataContainer &operator=(
const QgsVectorFileWriterMetadataContainer &other ) =
delete;
2823 ~QgsVectorFileWriterMetadataContainer()
2825 for (
auto it = driverMetadata.constBegin(); it != driverMetadata.constEnd(); ++it )
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();
2834 QMap<QString, QgsVectorFileWriter::MetaData> driverMetadata;
2840 static QgsVectorFileWriterMetadataContainer sDriverMetadata;
2841 QMap<QString, MetaData>::ConstIterator it = sDriverMetadata.driverMetadata.constBegin();
2843 for ( ; it != sDriverMetadata.driverMetadata.constEnd(); ++it )
2845 if ( it.key() ==
"PGDUMP"_L1 && driverName !=
"PGDUMP"_L1 && driverName !=
"PostgreSQL SQL dump"_L1 )
2850 if ( it.key().startsWith( driverName ) || it.value().longName.startsWith( driverName ) )
2865 return QStringList();
2874 return QStringList();
2905 return mCapabilities;
2915 QgsFeatureList::iterator fIt = features.begin();
2917 for ( ; fIt != features.end(); ++fIt )
2939 mRenderContext.expressionContext().setFeature( feature );
2942 QString styleString;
2943 QString currentStyle;
2945 QgsSymbolList::const_iterator symbolIt = symbols.constBegin();
2946 for ( ; symbolIt != symbols.constEnd(); ++symbolIt )
2948 int nSymbolLayers = ( *symbolIt )->symbolLayerCount();
2949 for (
int i = 0; i < nSymbolLayers; ++i )
2952 QMap< QgsSymbolLayer *, QString >::const_iterator it =
mSymbolLayerTable.find( ( *symbolIt )->symbolLayer( i ) );
2958 double mmsf = mmScaleFactor(
mSymbologyScale, ( *symbolIt )->outputUnit(), outputUnit );
2959 double musf = mapUnitScaleFactor(
mSymbologyScale, ( *symbolIt )->outputUnit(), outputUnit );
2961 currentStyle = ( *symbolIt )->symbolLayer( i )->ogrFeatureStyle( mmsf, musf );
2967 if ( symbolIt != symbols.constBegin() || i != 0 )
2969 styleString.append(
';' );
2971 styleString.append( currentStyle );
2976 OGR_F_SetStyleString( poFeature.get(), currentStyle.toLocal8Bit().constData() );
2977 if ( !writeFeature(
mLayer, poFeature.get() ) )
2989 OGR_F_SetStyleString( poFeature.get(), styleString.toLocal8Bit().constData() );
2997 if ( !writeFeature(
mLayer, poFeature.get() ) )
3021 int fldIdx = it.key();
3022 int ogrField = it.value();
3024 QVariant attrValue = feature.
attribute( fldIdx );
3029 OGR_F_UnsetField( poFeature.get(), ogrField );
3042 OGR_F_SetFieldNull( poFeature.get(), ogrField );
3063 switch ( field.
type() )
3065 case QMetaType::Type::Int:
3066 OGR_F_SetFieldInteger( poFeature.get(), ogrField, attrValue.toInt() );
3068 case QMetaType::Type::LongLong:
3069 OGR_F_SetFieldInteger64( poFeature.get(), ogrField, attrValue.toLongLong() );
3071 case QMetaType::Type::Bool:
3072 OGR_F_SetFieldInteger( poFeature.get(), ogrField, attrValue.toInt() );
3074 case QMetaType::Type::QString:
3075 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( attrValue.toString() ).constData() );
3077 case QMetaType::Type::Double:
3078 OGR_F_SetFieldDouble( poFeature.get(), ogrField, attrValue.toDouble() );
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 );
3083 case QMetaType::Type::QDateTime:
3086 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( attrValue.toDateTime().toString( u
"yyyy/MM/dd hh:mm:ss.zzz"_s ) ).constData() );
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 ) );
3096 case QMetaType::Type::QTime:
3099 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( attrValue.toString() ).constData() );
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 );
3108 case QMetaType::Type::QByteArray:
3110 const QByteArray ba = attrValue.toByteArray();
3111 OGR_F_SetFieldBinary( poFeature.get(), ogrField, ba.size(),
const_cast< GByte *
>(
reinterpret_cast< const GByte *
>( ba.data() ) ) );
3115 case QMetaType::Type::UnknownType:
3118 case QMetaType::Type::QStringList:
3123 const QJsonDocument doc = QJsonDocument::fromVariant( attrValue );
3125 if ( !doc.isNull() )
3127 jsonString = QString::fromUtf8( doc.toJson( QJsonDocument::Compact ).constData() );
3129 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( jsonString.constData() ) );
3133 QStringList list = attrValue.toStringList();
3134 if ( mSupportedListSubTypes.contains( QMetaType::Type::QString ) )
3136 int count = list.count();
3137 char **lst =
new char *[count + 1];
3141 for (
const QString &
string : list )
3143 lst[pos] = CPLStrdup(
mCodec->fromUnicode(
string ).data() );
3147 lst[count] =
nullptr;
3148 OGR_F_SetFieldStringList( poFeature.get(), ogrField, lst );
3153 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( list.join(
',' ) ).constData() );
3158 case QMetaType::Type::QVariantList:
3162 const QJsonDocument doc = QJsonDocument::fromVariant( attrValue );
3164 if ( !doc.isNull() )
3166 jsonString = QString::fromUtf8( doc.toJson( QJsonDocument::Compact ).data() );
3168 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( jsonString.constData() ) );
3173 if ( field.
subType() == QMetaType::Type::QString )
3175 QStringList list = attrValue.toStringList();
3176 if ( mSupportedListSubTypes.contains( QMetaType::Type::QString ) )
3178 int count = list.count();
3179 char **lst =
new char *[count + 1];
3183 for (
const QString &
string : list )
3185 lst[pos] = CPLStrdup(
mCodec->fromUnicode(
string ).data() );
3189 lst[count] =
nullptr;
3190 OGR_F_SetFieldStringList( poFeature.get(), ogrField, lst );
3195 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( list.join(
',' ) ).constData() );
3199 else if ( field.
subType() == QMetaType::Type::Int )
3201 const QVariantList list = attrValue.toList();
3202 if ( mSupportedListSubTypes.contains( QMetaType::Type::Int ) )
3204 const int count = list.count();
3205 int *lst =
new int[count];
3209 for (
const QVariant &value : list )
3211 lst[pos] = value.toInt();
3215 OGR_F_SetFieldIntegerList( poFeature.get(), ogrField, count, lst );
3220 QStringList strings;
3221 strings.reserve( list.size() );
3222 for (
const QVariant &value : list )
3224 strings << QString::number( value.toInt() );
3226 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( strings.join(
',' ) ).constData() );
3230 else if ( field.
subType() == QMetaType::Type::Double )
3232 const QVariantList list = attrValue.toList();
3233 if ( mSupportedListSubTypes.contains( QMetaType::Type::Double ) )
3235 const int count = list.count();
3236 double *lst =
new double[count];
3240 for (
const QVariant &value : list )
3242 lst[pos] = value.toDouble();
3246 OGR_F_SetFieldDoubleList( poFeature.get(), ogrField, count, lst );
3251 QStringList strings;
3252 strings.reserve( list.size() );
3253 for (
const QVariant &value : list )
3255 strings << QString::number( value.toDouble() );
3257 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( strings.join(
',' ) ).constData() );
3261 else if ( field.
subType() == QMetaType::Type::LongLong )
3263 const QVariantList list = attrValue.toList();
3264 if ( mSupportedListSubTypes.contains( QMetaType::Type::LongLong ) )
3266 const int count = list.count();
3267 long long *lst =
new long long[count];
3271 for (
const QVariant &value : list )
3273 lst[pos] = value.toLongLong();
3277 OGR_F_SetFieldInteger64List( poFeature.get(), ogrField, count, lst );
3282 QStringList strings;
3283 strings.reserve( list.size() );
3284 for (
const QVariant &value : list )
3286 strings << QString::number( value.toLongLong() );
3288 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( strings.join(
',' ) ).constData() );
3295 case QMetaType::Type::QVariantMap:
3298 const char *pszDataSubTypes = GDALGetMetadataItem( OGRGetDriverByName(
mOgrDriverName.toLocal8Bit().constData() ), GDAL_DMD_CREATIONFIELDDATASUBTYPES,
nullptr );
3299 if ( pszDataSubTypes && strstr( pszDataSubTypes,
"JSON" ) )
3301 const QJsonDocument doc = QJsonDocument::fromVariant( attrValue );
3303 if ( !doc.isNull() )
3305 const QByteArray json { doc.toJson( QJsonDocument::Compact ) };
3306 jsonString = QString::fromUtf8( json.data() );
3308 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( jsonString.constData() ) );
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() );
3330 QgsGeometry geom = feature.
geometry();
3331 if ( mCoordinateTransform )
3336 geom.
transform( *mCoordinateTransform );
3338 catch ( QgsCsException & )
3372 QVector<QgsGeometry> geoms = geom.
coerceToType( coercedType );
3373 if ( geoms.size() == 1 )
3377 OGRGeometryH ogrGeom =
nullptr;
3410 geom.
get()->
addZValue( std::numeric_limits<double>::quiet_NaN() );
3417 geom.
get()->
addMValue( std::numeric_limits<double>::quiet_NaN() );
3437 mErrorMessage = QObject::tr(
"Feature geometry not imported (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
3460 QByteArray wkb( geom.
asWkb( wkbFlags ) );
3461 if ( wkb.length() > std::numeric_limits<int>::max() )
3463 mErrorMessage = QObject::tr(
"Feature geometry not imported (too large geometry)" );
3466 OGR_G_DestroyGeometry( ogrGeom );
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 )
3472 mErrorMessage = QObject::tr(
"Feature geometry not imported (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
3475 OGR_G_DestroyGeometry( ogrGeom );
3480 OGR_F_SetGeometryDirectly( poFeature.get(), ogrGeom );
3494 for (
int i = 0; i < attributes.size(); i++ )
3496 if ( omap.find( i ) != omap.end() )
3501bool QgsVectorFileWriter::writeFeature( OGRLayerH layer, OGRFeatureH feature )
3503 if ( OGR_L_CreateFeature( layer, feature ) != OGRERR_NONE )
3505 mErrorMessage = QObject::tr(
"Feature creation error (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
3515 if ( mUsingTransaction )
3517 if ( OGRERR_NONE != OGR_L_CommitTransaction(
mLayer ) )
3519 QgsDebugError( u
"Error while committing transaction on OGRLayer."_s );
3532 const QString &fileName,
3533 const QString &fileEncoding,
3535 const QString &driverName,
3538 const QStringList &datasourceOptions,
3539 const QStringList &layerOptions,
3540 bool skipAttributeCreation,
3541 QString *newFilename,
3586 const QString &fileName,
3587 const QString &fileEncoding,
3589 const QString &driverName,
3592 const QStringList &datasourceOptions,
3593 const QStringList &layerOptions,
3594 bool skipAttributeCreation,
3595 QString *newFilename,
3637 if ( !layer || !layer->
isValid() )
3644 details.sourceCrs = layer->
crs();
3645 details.sourceWkbType = layer->
wkbType();
3646 details.sourceFields = layer->
fields();
3655 if ( details.storageType ==
"ESRI Shapefile"_L1 )
3663 details.geometryTypeScanIterator = layer->
getFeatures( req );
3670 details.shallTransform =
false;
3675 details.shallTransform =
true;
3680 details.outputCrs = details.sourceCrs;
3683 details.destWkbType = details.sourceWkbType;
3697 details.attributes.clear();
3698 else if ( details.attributes.isEmpty() )
3701 for (
int idx : allAttributes )
3703 QgsField fld = details.sourceFields.
at( idx );
3704 if ( details.providerType ==
"oracle"_L1 && fld.
typeName().contains(
"SDO_GEOMETRY"_L1 ) )
3706 details.attributes.append( idx );
3710 if ( !details.attributes.isEmpty() )
3712 for (
int attrIdx : std::as_const( details.attributes ) )
3714 if ( details.sourceFields.
exists( attrIdx ) )
3716 QgsField field = details.sourceFields.
at( attrIdx );
3718 details.outputFields.
append( field );
3722 QgsDebugError( u
"No such source field with index '%1' available."_s.arg( attrIdx ) );
3729 if ( details.providerType ==
"spatialite"_L1 )
3731 for (
int i = 0; i < details.outputFields.
size(); i++ )
3733 if ( details.outputFields.
at( i ).
type() == QMetaType::Type::LongLong )
3738 if ( std::max( std::llabs( min.toLongLong() ), std::llabs( max.toLongLong() ) ) < std::numeric_limits<int>::max() )
3740 details.outputFields[i].setType( QMetaType::Type::Int );
3748 addRendererAttributes( details.renderer.get(), details.renderContext, details.sourceFields, details.attributes );
3750 QgsFeatureRequest req;
3758 bool useFilterRect =
true;
3759 if ( details.shallTransform )
3764 QgsCoordinateTransform extentTransform = options.
ct;
3768 catch ( QgsCsException & )
3770 useFilterRect =
false;
3773 if ( useFilterRect )
3779 details.filterRectEngine->prepareGeometry();
3781 details.sourceFeatureIterator = layer->
getFeatures( req );
3792 PreparedWriterDetails &details,
const QString &fileName,
const QgsVectorFileWriter::SaveVectorOptions &options, QString *newFilename, QString *
errorMessage, QString *newLayer
3799 PreparedWriterDetails &details,
3800 const QString &fileName,
3801 const QgsCoordinateTransformContext &transformContext,
3802 const QgsVectorFileWriter::SaveVectorOptions &options,
3803 QString *newFilename,
3811 int lastProgressReport = 0;
3812 long long total = details.featureCount;
3815 if ( details.providerType ==
"ogr"_L1 && !details.dataSourceUri.isEmpty() )
3817 QString srcFileName( details.providerUriParams.value( u
"path"_s ).toString() );
3818 if ( QFile::exists( srcFileName ) && QFileInfo( fileName ).canonicalFilePath() == QFileInfo( srcFileName ).canonicalFilePath() )
3821 QgsDataSourceUri uri( details.dataSourceUri );
3823 && options.
layerName != details.providerUriParams.value( u
"layerName"_s ) ) )
3826 *
errorMessage = QObject::tr(
"Cannot overwrite an OGR layer in place" );
3834 QgsFeatureIterator fit = details.geometryTypeScanIterator;
3846 int newProgress =
static_cast<int>( ( 5.0 * scanned ) / total );
3847 if ( newProgress != lastProgressReport )
3849 lastProgressReport = newProgress;
3864 QString tempNewFilename;
3865 QString tempNewLayer;
3867 QgsVectorFileWriter::SaveVectorOptions newOptions = options;
3873 std::unique_ptr< QgsVectorFileWriter > writer(
create( fileName, details.outputFields, destWkbType, details.outputCrs, transformContext, newOptions, sinkFlags, &tempNewFilename, &tempNewLayer ) );
3877 *newFilename = tempNewFilename;
3880 *newLayer = tempNewLayer;
3909 switch ( writer->symbologyExport() )
3913 QgsFeatureRenderer *r = details.renderer.get();
3926 int n = 0, errors = 0;
3935 writer->startRender( details.renderer.get(), details.sourceFields );
3937 writer->resetMap( details.attributes );
3939 writer->mFields = details.sourceFields;
3943 int initialProgress = lastProgressReport;
3944 while ( details.sourceFeatureIterator.nextFeature( fet ) )
3955 int newProgress =
static_cast<int>( initialProgress + ( ( 100.0 - initialProgress ) * saved ) / total );
3956 if ( newProgress < 100 && newProgress != lastProgressReport )
3958 lastProgressReport = newProgress;
3963 if ( details.shallTransform )
3974 catch ( QgsCsException &e )
3976 const QString msg = QObject::tr(
"Failed to transform feature with ID '%1'. Writing stopped. (Exception: %2)" ).arg( fet.
id() ).arg( e.
what() );
3993 if ( !writer->addFeatureWithStyle( fet, writer->mRenderer.get(), mapUnits ) )
4000 *
errorMessage = QObject::tr(
"Feature write errors:" );
4006 if ( errors > 1000 )
4010 *
errorMessage += QObject::tr(
"Stopping after %n error(s)",
nullptr, errors );
4020 writer->stopRender();
4024 *
errorMessage += QObject::tr(
"\nOnly %1 of %2 features written." ).arg( n - errors ).arg( n );
4029 bool metadataFailure =
false;
4045 metadataFailure =
true;
4048 catch ( QgsNotSupportedException &e )
4056 metadataFailure =
true;
4067 QgsVectorFileWriter::PreparedWriterDetails details;
4068 WriterError err = prepareWriteAsVectorFormat( layer, options, details );
4079 QgsVectorFileWriter::PreparedWriterDetails details;
4080 WriterError err = prepareWriteAsVectorFormat( layer, options, details );
4089 const QString &fileName,
4093 QString *newFilename,
4097 QgsVectorFileWriter::PreparedWriterDetails details;
4098 WriterError err = prepareWriteAsVectorFormat( layer, options, details );
4107 QFileInfo fi( fileName );
4108 QDir dir = fi.dir();
4111 for (
const char *suffix : {
".shp",
".shx",
".dbf",
".prj",
".qix",
".qpj",
".cpg",
".sbn",
".sbx",
".idm",
".ind" } )
4113 filter << fi.completeBaseName() + suffix;
4117 const auto constEntryList = dir.entryList( filter );
4118 for (
const QString &file : constEntryList )
4120 QFile f( dir.canonicalPath() +
'/' + file );
4123 QgsDebugError( u
"Removing file %1 failed: %2"_s.arg( file, f.errorString() ) );
4139 QStringList driverNames;
4142 for (
int i = 0; i < GDALGetDriverCount(); ++i )
4144 GDALDriverH
driver = GDALGetDriver( i );
4151 const QString driverExtensions = GDALGetMetadataItem(
driver, GDAL_DMD_EXTENSIONS,
"" );
4152 if ( driverExtensions.isEmpty() )
4155 const QSet< QString > splitExtensions = qgis::listToSet( driverExtensions.split(
' ', Qt::SkipEmptyParts ) );
4156 if ( splitExtensions.intersects( multiLayerExtensions ) )
4158 driverNames << GDALGetDescription(
driver );
4166 static QReadWriteLock sFilterLock;
4167 static QMap< VectorFormatOptions, QList< QgsVectorFileWriter::FilterFormatDetails > > sFilters;
4171 const auto it = sFilters.constFind( options );
4172 if ( it != sFilters.constEnd() )
4176 QList< QgsVectorFileWriter::FilterFormatDetails > results;
4179 int const drvCount = OGRGetDriverCount();
4183 for (
int i = 0; i < drvCount; ++i )
4185 OGRSFDriverH drv = OGRGetDriver( i );
4188 const QString drvName = GDALGetDescription( drv );
4192 if ( !multiLayerDrivers.contains( drvName ) )
4196 GDALDriverH gdalDriver = GDALGetDriverByName( drvName.toLocal8Bit().constData() );
4197 bool nonSpatialFormat =
false;
4200 nonSpatialFormat = GDALGetMetadataItem( gdalDriver, GDAL_DCAP_NONSPATIAL,
nullptr );
4203 if ( OGR_Dr_TestCapability( drv,
"CreateDataSource" ) != 0 )
4208 if ( nonSpatialFormat )
4213 if ( filterString.isEmpty() )
4220 globs = metadata.
glob.toLower().split(
' ' );
4226 details.
globs = globs;
4234 if ( options & SortRecommended )
4236 if ( a.driverName ==
"GPKG"_L1 )
4238 else if ( b.driverName ==
"GPKG"_L1 )
4240 else if ( a.driverName ==
"ESRI Shapefile"_L1 )
4242 else if ( b.driverName ==
"ESRI Shapefile"_L1 )
4249 sFilters.insert( options, results );
4256 QSet< QString > extensions;
4258 const thread_local QRegularExpression rx( u
"\\*\\.(.*)$"_s );
4262 for (
const QString &glob : format.globs )
4264 const QRegularExpressionMatch match = rx.match( glob );
4265 if ( !match.hasMatch() )
4268 const QString matched = match.captured( 1 );
4269 extensions.insert( matched );
4273 QStringList extensionList( extensions.constBegin(), extensions.constEnd() );
4275 std::sort( extensionList.begin(), extensionList.end(), [options](
const QString &a,
const QString &b ) ->
bool {
4276 if ( options & SortRecommended )
4278 if ( a ==
"gpkg"_L1 )
4280 else if ( b ==
"gpkg"_L1 )
4282 else if ( a ==
"shp"_L1 )
4284 else if ( b ==
"shp"_L1 )
4288 return a.toLower().localeAwareCompare( b.toLower() ) < 0;
4291 return extensionList;
4296 QList< QgsVectorFileWriter::DriverDetails > results;
4299 const int drvCount = OGRGetDriverCount();
4303 QStringList writableDrivers;
4304 for (
int i = 0; i < drvCount; ++i )
4306 OGRSFDriverH drv = OGRGetDriver( i );
4309 const QString drvName = GDALGetDescription( drv );
4313 if ( !multiLayerDrivers.contains( drvName ) )
4321 if ( drvName ==
"ODS"_L1 || drvName ==
"XLSX"_L1 || drvName ==
"XLS"_L1 )
4325 if ( drvName ==
"ESRI Shapefile"_L1 )
4327 writableDrivers << u
"DBF file"_s;
4329 if ( OGR_Dr_TestCapability( drv,
"CreateDataSource" ) != 0 )
4332 if ( drvName ==
"MapInfo File"_L1 )
4334 writableDrivers << u
"MapInfo MIF"_s;
4336 else if ( drvName ==
"SQLite"_L1 )
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() );
4353 writableDrivers << u
"SpatiaLite"_s;
4354 OGR_Dr_DeleteDataSource( poDriver, u
"/vsimem/spatialitetest.sqlite"_s.toUtf8().constData() );
4357 CPLFree( options[0] );
4359 writableDrivers << drvName;
4364 results.reserve( writableDrivers.count() );
4365 for (
const QString &drvName : std::as_const( writableDrivers ) )
4378 if ( options & SortRecommended )
4380 if ( a.driverName ==
"GPKG"_L1 )
4382 else if ( b.driverName ==
"GPKG"_L1 )
4384 else if ( a.driverName ==
"ESRI Shapefile"_L1 )
4386 else if ( b.driverName ==
"ESRI Shapefile"_L1 )
4390 return a.
longName.toLower().localeAwareCompare( b.
longName.toLower() ) < 0;
4397 QString ext = extension.trimmed();
4398 if ( ext.isEmpty() )
4401 if ( ext.startsWith(
'.' ) )
4405 int const drvCount = GDALGetDriverCount();
4407 for (
int i = 0; i < drvCount; ++i )
4409 GDALDriverH drv = GDALGetDriver( i );
4415 QString drvName = GDALGetDriverShortName( drv );
4416 QStringList driverExtensions = QString( GDALGetMetadataItem( drv, GDAL_DMD_EXTENSIONS,
nullptr ) ).split(
' ' );
4418 const auto constDriverExtensions = driverExtensions;
4419 for (
const QString &
driver : constDriverExtensions )
4421 if (
driver.compare( ext, Qt::CaseInsensitive ) == 0 )
4432 QString filterString;
4436 if ( !filterString.isEmpty() )
4437 filterString +=
";;"_L1;
4439 filterString += details.filterString;
4441 return filterString;
4450 return u
"%1 (%2 %3)"_s.arg( metadata.
trLongName, metadata.
glob.toLower(), metadata.
glob.toUpper() );
4455 if ( codecName ==
"System"_L1 )
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() )
4462 QString
c = match.captured( 2 ).remove(
'-' );
4464 ( void )
c.toInt( &isNumber );
4478 QgsFeatureRenderer *renderer = vl->
renderer();
4492 OGRStyleTableH ogrStyleTable = OGR_STBL_Create();
4493 OGRStyleMgrH styleManager = OGR_SM_Create( ogrStyleTable );
4496 int nTotalLevels = 0;
4498 QgsSymbolList::iterator symbolIt = symbolList.begin();
4499 for ( ; symbolIt != symbolList.end(); ++symbolIt )
4501 double mmsf = mmScaleFactor(
mSymbologyScale, ( *symbolIt )->outputUnit(), mapUnits );
4502 double musf = mapUnitScaleFactor(
mSymbologyScale, ( *symbolIt )->outputUnit(), mapUnits );
4504 int nLevels = ( *symbolIt )->symbolLayerCount();
4505 for (
int i = 0; i < nLevels; ++i )
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() );
4512 OGR_DS_SetStyleTableDirectly( ds, ogrStyleTable );
4517 if ( !details.renderer )
4520 mRenderContext.expressionContext() = details.expressionContext;
4522 QHash< QgsSymbol *, QList<QgsFeature> > features;
4531 startRender( details.renderer.get(), details.sourceFields );
4535 QgsSymbol *featureSymbol =
nullptr;
4549 catch ( QgsCsException &e )
4551 QString msg = QObject::tr(
"Failed to transform, writing stopped. (Exception: %1)" ).arg( e.
what() );
4559 mRenderContext.expressionContext().setFeature( fet );
4561 featureSymbol = mRenderer->symbolForFeature( fet, mRenderContext );
4562 if ( !featureSymbol )
4567 QHash< QgsSymbol *, QList<QgsFeature> >::iterator it = features.find( featureSymbol );
4568 if ( it == features.end() )
4570 it = features.insert( featureSymbol, QList<QgsFeature>() );
4572 it.value().append( fet );
4577 QgsSymbolList symbols = mRenderer->symbols( mRenderContext );
4578 for (
int i = 0; i < symbols.count(); i++ )
4580 QgsSymbol *sym = symbols[i];
4584 if ( level < 0 || level >= 1000 )
4586 QgsSymbolLevelItem item( sym, j );
4587 while ( level >= levels.count() )
4589 levels[level].append( item );
4594 int nTotalFeatures = 0;
4597 for (
int l = 0; l < levels.count(); l++ )
4600 for (
int i = 0; i < level.count(); i++ )
4602 QgsSymbolLevelItem &item = level[i];
4603 QHash< QgsSymbol *, QList<QgsFeature> >::iterator levelIt = features.find( item.
symbol() );
4604 if ( levelIt == features.end() )
4610 double mmsf = mmScaleFactor(
mSymbologyScale, levelIt.key()->outputUnit(), mapUnits );
4611 double musf = mapUnitScaleFactor(
mSymbologyScale, levelIt.key()->outputUnit(), mapUnits );
4613 int llayer = item.
layer();
4614 QList<QgsFeature> &featureList = levelIt.value();
4615 QList<QgsFeature>::iterator featureIt = featureList.begin();
4616 for ( ; featureIt != featureList.end(); ++featureIt )
4626 QString styleString = levelIt.key()->symbolLayer( llayer )->ogrFeatureStyle( mmsf, musf );
4627 if ( !styleString.isEmpty() )
4629 OGR_F_SetStyleString( ogrFeature.get(), styleString.toLocal8Bit().constData() );
4630 if ( !writeFeature(
mLayer, ogrFeature.get() ) )
4643 *
errorMessage += QObject::tr(
"\nOnly %1 of %2 features written." ).arg( nTotalFeatures - nErrors ).arg( nTotalFeatures );
4660 return 1000 / scale;
4676 return scale / 1000;
4682void QgsVectorFileWriter::startRender( QgsFeatureRenderer *sourceRenderer,
const QgsFields &fields )
4684 mRenderer = createSymbologyRenderer( sourceRenderer );
4690 mRenderer->startRender( mRenderContext, fields );
4693void QgsVectorFileWriter::stopRender()
4700 mRenderer->stopRender( mRenderContext );
4703std::unique_ptr<QgsFeatureRenderer> QgsVectorFileWriter::createSymbologyRenderer( QgsFeatureRenderer *sourceRenderer )
const
4716 if ( !sourceRenderer )
4721 return std::unique_ptr< QgsFeatureRenderer >( sourceRenderer->
clone() );
4724void QgsVectorFileWriter::addRendererAttributes( QgsFeatureRenderer *renderer, QgsRenderContext &context,
const QgsFields &fields,
QgsAttributeList &attList )
4728 const QSet<QString> rendererAttributes = renderer->
usedAttributes( context );
4729 for (
const QString &attr : rendererAttributes )
4734 attList.append( index );
4740QStringList QgsVectorFileWriter::concatenateOptions(
const QMap<QString, QgsVectorFileWriter::Option *> &options )
4743 QMap<QString, QgsVectorFileWriter::Option *>::ConstIterator it;
4745 for ( it = options.constBegin(); it != options.constEnd(); ++it )
4747 QgsVectorFileWriter::Option *option = it.value();
4748 switch ( option->
type )
4752 QgsVectorFileWriter::IntOption *opt =
dynamic_cast<QgsVectorFileWriter::IntOption *
>( option );
4755 list.append( u
"%1=%2"_s.arg( it.key() ).arg( opt->
defaultValue ) );
4762 QgsVectorFileWriter::SetOption *opt =
dynamic_cast<QgsVectorFileWriter::SetOption *
>( option );
4765 list.append( u
"%1=%2"_s.arg( it.key(), opt->
defaultValue ) );
4772 QgsVectorFileWriter::StringOption *opt =
dynamic_cast<QgsVectorFileWriter::StringOption *
>( option );
4775 list.append( u
"%1=%2"_s.arg( it.key(), opt->
defaultValue ) );
4781 QgsVectorFileWriter::HiddenOption *opt =
dynamic_cast<QgsVectorFileWriter::HiddenOption *
>( option );
4782 if ( opt && !opt->
mValue.isEmpty() )
4784 list.append( u
"%1=%2"_s.arg( it.key(), opt->
mValue ) );
4795 OGRSFDriverH hDriver =
nullptr;
4799 const QString drvName = GDALGetDescription( hDriver );
4801 if ( OGR_DS_TestCapability( hDS.get(), ODsCCreateLayer ) )
4806 if ( !( drvName ==
"ESRI Shapefile"_L1 && QFile::exists( datasetName ) ) )
4809 if ( OGR_DS_TestCapability( hDS.get(), ODsCDeleteLayer ) )
4813 int layer_count = OGR_DS_GetLayerCount( hDS.get() );
4816 OGRLayerH hLayer = OGR_DS_GetLayer( hDS.get(), 0 );
4819 if ( OGR_L_TestCapability( hLayer, OLCSequentialWrite ) )
4822 if ( OGR_L_TestCapability( hLayer, OLCCreateField ) )
4834 OGRSFDriverH hDriver =
nullptr;
4839 QString layerName( layerNameIn );
4840 if ( layerName.isEmpty() )
4841 layerName = QFileInfo( datasetName ).baseName();
4843 return OGR_DS_GetLayerByName( hDS.get(), layerName.toUtf8().constData() );
4849 OGRSFDriverH hDriver =
nullptr;
4853 OGRLayerH hLayer = OGR_DS_GetLayerByName( hDS.get(), layerName.toUtf8().constData() );
4859 OGRFeatureDefnH defn = OGR_L_GetLayerDefn( hLayer );
4860 const auto constAttributes = attributes;
4861 for (
int idx : constAttributes )
4864 if ( OGR_FD_GetFieldIndex( defn, fld.
name().toUtf8().constData() ) < 0 )
@ FieldComments
Writer can support field comments.
@ FieldAliases
Writer can support field aliases.
DistanceUnit
Units of distance.
QFlags< VectorFileWriterCapability > VectorFileWriterCapabilities
Capabilities supported by a QgsVectorFileWriter object.
RenderUnit
Rendering size units.
@ Millimeters
Millimeters.
WkbType
The WKB type describes the number of dimensions a geometry has.
@ LineStringM
LineStringM.
@ NurbsCurveM
NurbsCurveM.
@ MultiPolygon25D
MultiPolygon25D.
@ LineStringZM
LineStringZM.
@ MultiLineString
MultiLineString.
@ NurbsCurveZ
NurbsCurveZ.
@ NurbsCurveZM
NurbsCurveZM.
@ MultiPolygonZ
MultiPolygonZ.
@ LineStringZ
LineStringZ.
FeatureSymbologyExport
Options for exporting features considering their symbology.
@ PerFeature
Keeps the number of features and export symbology per feature.
@ PerSymbolLayer
Exports one feature per symbol layer (considering symbol levels).
@ NoSymbology
Export only data.
@ Reverse
Reverse/inverse transform (from destination to source).
Provides common functionality for database based connections.
virtual QgsFieldDomain * fieldDomain(const QString &name) const
Returns the field domain with the specified name from the provider.
virtual bool addZValue(double zValue=0)=0
Adds a z-dimension to the geometry, initialized to a preset value.
virtual bool dropMValue()=0
Drops any measure values which exist in the geometry.
QFlags< WkbFlag > WkbFlags
virtual bool addMValue(double mValue=0)=0
Adds a measure to the geometry, initialized to a preset value.
virtual bool dropZValue()=0
Drops any z-dimensions which exist in the geometry.
@ FlagExportTrianglesAsPolygons
Triangles should be exported as polygon geometries.
@ FlagExportNanAsDoubleMin
Use -DOUBLE_MAX to represent NaN.
static void registerOgrDrivers()
Register OGR drivers ensuring this only happens once.
Represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
static Q_INVOKABLE QgsCoordinateReferenceSystem fromEpsgId(long epsg)
Creates a CRS from a given EPSG ID.
Qgis::DistanceUnit mapUnits
Contains information about the context in which a coordinate transform is executed.
virtual QString dataSourceUri(bool expandAuthConfig=false) const
Gets the data source specification.
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...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
void initAttributes(int fieldCount)
Initialize this feature with the given number of fields.
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.
void setProgress(double progress)
Sets the current progress for the feedback object.
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.
QString typeName() const
Gets the field type.
bool convertCompatible(QVariant &v, QString *errorMessage=nullptr) const
Converts the provided variant to a compatible format.
void setName(const QString &name)
Set the field name.
QMetaType::Type subType() const
If the field is a collection, gets its element's type.
QgsFieldConstraints constraints
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
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.
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
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.
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.
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.
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.
FieldValueConverter()=default
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().
QString fileEncoding
Encoding to use.
bool forceMulti
Sets to true to force creation of multipart geometries.
QString driverName
OGR driver to use.
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.
double symbologyScale
Scale of symbology.
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).
@ ErrAttributeTypeUnsupported
@ Canceled
Writing was interrupted by manual cancellation.
@ ErrAttributeCreationFailed
@ 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)
QString mOgrDriverLongName
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.
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
#define Q_NOWARN_DEPRECATED_PUSH
QList< QgsFeature > QgsFeatureList
QList< int > QgsAttributeList
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
QList< QgsSymbolLevel > QgsSymbolLevelOrder
QList< QgsSymbolLevelItem > QgsSymbolLevel
QList< QgsSymbol * > QgsSymbolList
QStringList multiLayerFormats()
Details of available driver formats.
QString longName
Descriptive, user friendly name for the driver.
QString driverName
Unique driver name.