44#include <QRegularExpression>
45#include <QJsonDocument>
51#include <ogr_srs_api.h>
54#include <cpl_string.h>
73 const QString &fileEncoding,
77 const QString &driverName,
78 const QStringList &datasourceOptions,
79 const QStringList &layerOptions,
82 QgsFeatureSink::SinkFlags sinkFlags,
91 init( vectorFileName, fileEncoding, fields, geometryType,
92 srs, driverName, datasourceOptions, layerOptions, newFilename,
nullptr,
97 const QString &fileEncoding,
101 const QString &driverName,
102 const QStringList &datasourceOptions,
103 const QStringList &layerOptions,
104 QString *newFilename,
107 const QString &layerName,
111 QgsFeatureSink::SinkFlags sinkFlags,
113 bool includeConstraints )
115 , mWkbType( geometryType )
116 , mSymbologyExport( symbologyExport )
117 , mSymbologyScale( 1.0 )
118 , mIncludeConstraints( includeConstraints )
120 init( vectorFileName, fileEncoding, fields, geometryType, srs, driverName,
121 datasourceOptions, layerOptions, newFilename, fieldValueConverter,
122 layerName, action, newLayer, sinkFlags, transformContext, fieldNameSource );
126 const QString &fileName,
132 QgsFeatureSink::SinkFlags sinkFlags,
133 QString *newFilename,
147 if ( driverName == QLatin1String(
"MapInfo MIF" ) )
151 GDALDriverH gdalDriver = GDALGetDriverByName( driverName.toLocal8Bit().constData() );
159#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,7,0)
160 return CSLFetchBoolean(
driverMetadata, GDAL_DCAP_FEATURE_STYLES_WRITE,
false );
162 return CSLFetchBoolean(
driverMetadata, GDAL_DCAP_FEATURE_STYLES,
false );
166void QgsVectorFileWriter::init( QString vectorFileName,
167 QString fileEncoding,
171 const QString &driverName,
172 QStringList datasourceOptions,
173 QStringList layerOptions,
174 QString *newFilename,
175 FieldValueConverter *fieldValueConverter,
176 const QString &layerNameIn,
177 ActionOnExistingFile action,
178 QString *newLayer, SinkFlags sinkFlags,
183 if ( vectorFileName.isEmpty() )
190 if ( driverName == QLatin1String(
"MapInfo MIF" ) )
194 else if ( driverName == QLatin1String(
"SpatiaLite" ) )
197 if ( !datasourceOptions.contains( QStringLiteral(
"SPATIALITE=YES" ) ) )
199 datasourceOptions.append( QStringLiteral(
"SPATIALITE=YES" ) );
202 else if ( driverName == QLatin1String(
"DBF file" ) )
205 if ( !layerOptions.contains( QStringLiteral(
"SHPT=NULL" ) ) )
207 layerOptions.append( QStringLiteral(
"SHPT=NULL" ) );
216#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(3,3,1)
217 QString fidFieldName;
220 for (
const QString &layerOption : layerOptions )
222 if ( layerOption.startsWith( QLatin1String(
"FID=" ) ) )
224 fidFieldName = layerOption.mid( 4 );
228 if ( fidFieldName.isEmpty() )
229 fidFieldName = QStringLiteral(
"fid" );
234 OGRSFDriverH poDriver;
237 poDriver = OGRGetDriverByName(
mOgrDriverName.toLocal8Bit().constData() );
241 mErrorMessage = QObject::tr(
"OGR driver for '%1' not found (OGR error: %2)" )
243 QString::fromUtf8( CPLGetLastErrorMsg() ) );
248 mOgrDriverLongName = QString( GDALGetMetadataItem( poDriver, GDAL_DMD_LONGNAME,
nullptr ) );
255 if ( layerOptions.join( QString() ).toUpper().indexOf( QLatin1String(
"ENCODING=" ) ) == -1 )
260 if ( driverName == QLatin1String(
"ESRI Shapefile" ) && !vectorFileName.endsWith( QLatin1String(
".shp" ), Qt::CaseInsensitive ) )
262 vectorFileName += QLatin1String(
".shp" );
264 else if ( driverName == QLatin1String(
"DBF file" ) && !vectorFileName.endsWith( QLatin1String(
".dbf" ), Qt::CaseInsensitive ) )
266 vectorFileName += QLatin1String(
".dbf" );
276#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
277 QStringList allExts = metadata.ext.split(
' ', QString::SkipEmptyParts );
279 QStringList allExts = metadata.ext.split(
' ', Qt::SkipEmptyParts );
282 const auto constAllExts = allExts;
283 for (
const QString &ext : constAllExts )
285 if ( vectorFileName.endsWith(
'.' + ext, Qt::CaseInsensitive ) )
294 vectorFileName +=
'.' + allExts[0];
300 if ( vectorFileName.endsWith( QLatin1String(
".gdb" ), Qt::CaseInsensitive ) )
302 QDir dir( vectorFileName );
305 QFileInfoList fileList = dir.entryInfoList(
306 QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst );
307 const auto constFileList = fileList;
308 for (
const QFileInfo &info : constFileList )
310 QFile::remove( info.absoluteFilePath() );
313 QDir().rmdir( vectorFileName );
317 QFile::remove( vectorFileName );
322 if ( metadataFound && !metadata.compulsoryEncoding.isEmpty() )
324 if ( fileEncoding.compare( metadata.compulsoryEncoding, Qt::CaseInsensitive ) != 0 )
326 QgsDebugMsgLevel( QStringLiteral(
"forced %1 encoding for %2" ).arg( metadata.compulsoryEncoding, driverName ), 2 );
327 fileEncoding = metadata.compulsoryEncoding;
332 char **options =
nullptr;
333 if ( !datasourceOptions.isEmpty() )
335 options =
new char *[ datasourceOptions.size() + 1 ];
336 for (
int i = 0; i < datasourceOptions.size(); i++ )
338 QgsDebugMsgLevel( QStringLiteral(
"-dsco=%1" ).arg( datasourceOptions[i] ), 2 );
339 options[i] = CPLStrdup( datasourceOptions[i].toLocal8Bit().constData() );
341 options[ datasourceOptions.size()] =
nullptr;
348 mDS.reset( OGR_Dr_CreateDataSource( poDriver, vectorFileName.toUtf8().constData(), options ) );
350 mDS.reset( OGROpen( vectorFileName.toUtf8().constData(), TRUE,
nullptr ) );
354 for (
int i = 0; i < datasourceOptions.size(); i++ )
355 CPLFree( options[i] );
364 mErrorMessage = QObject::tr(
"Creation of data source failed (OGR error: %1)" )
365 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
367 mErrorMessage = QObject::tr(
"Opening of data source in update mode failed (OGR error: %1)" )
368 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
372 QString layerName( layerNameIn );
373 if ( layerName.isEmpty() )
374 layerName = QFileInfo( vectorFileName ).baseName();
378 const int layer_count = OGR_DS_GetLayerCount(
mDS.get() );
379 for (
int i = 0; i < layer_count; i++ )
381 OGRLayerH hLayer = OGR_DS_GetLayer(
mDS.get(), i );
382 if ( EQUAL( OGR_L_GetName( hLayer ), layerName.toUtf8().constData() ) )
384 if ( OGR_DS_DeleteLayer(
mDS.get(), i ) != OGRERR_NONE )
387 mErrorMessage = QObject::tr(
"Overwriting of existing layer failed (OGR error: %1)" )
388 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
402 QgsDebugMsgLevel( QStringLiteral(
"Opened data source in update mode" ), 2 );
406 mCodec = QTextCodec::codecForName( fileEncoding.toLocal8Bit().constData() );
409 QgsDebugError(
"error finding QTextCodec for " + fileEncoding );
412 QString enc = settings.
value( QStringLiteral(
"UI/encoding" ),
"System" ).toString();
413 mCodec = QTextCodec::codecForName( enc.toLocal8Bit().constData() );
417 mCodec = QTextCodec::codecForLocale();
423 if ( driverName == QLatin1String(
"KML" ) || driverName == QLatin1String(
"LIBKML" ) || driverName == QLatin1String(
"GPX" ) )
425 if ( srs.
authid() != QLatin1String(
"EPSG:4326" ) )
440 int optIndex = layerOptions.indexOf( QLatin1String(
"FEATURE_DATASET=" ) );
441 if ( optIndex != -1 )
443 layerOptions.removeAt( optIndex );
446 if ( !layerOptions.isEmpty() )
448 options =
new char *[ layerOptions.size() + 1 ];
449 for (
int i = 0; i < layerOptions.size(); i++ )
452 options[i] = CPLStrdup( layerOptions[i].toLocal8Bit().constData() );
454 options[ layerOptions.size()] =
nullptr;
458 CPLSetConfigOption(
"SHAPE_ENCODING",
"" );
462 mLayer = OGR_DS_CreateLayer(
mDS.get(), layerName.toUtf8().constData(),
mOgrRef, wkbType, options );
465 *newLayer = OGR_L_GetName(
mLayer );
466 if ( driverName == QLatin1String(
"GPX" ) )
473 if ( !EQUAL( layerName.toUtf8().constData(),
"track_points" ) &&
474 !EQUAL( layerName.toUtf8().constData(),
"route_points" ) )
476 *newLayer = QStringLiteral(
"waypoints" );
483 const char *pszForceGPXTrack
484 = CSLFetchNameValue( options,
"FORCE_GPX_TRACK" );
485 if ( pszForceGPXTrack && CPLTestBool( pszForceGPXTrack ) )
486 *newLayer = QStringLiteral(
"tracks" );
488 *newLayer = QStringLiteral(
"routes" );
495 const char *pszForceGPXRoute
496 = CSLFetchNameValue( options,
"FORCE_GPX_ROUTE" );
497 if ( pszForceGPXRoute && CPLTestBool( pszForceGPXRoute ) )
498 *newLayer = QStringLiteral(
"routes" );
500 *newLayer = QStringLiteral(
"tracks" );
510 else if ( driverName == QLatin1String(
"DGN" ) )
512 mLayer = OGR_DS_GetLayerByName(
mDS.get(),
"elements" );
516 mLayer = OGR_DS_GetLayerByName(
mDS.get(), layerName.toUtf8().constData() );
521 for (
int i = 0; i < layerOptions.size(); i++ )
522 CPLFree( options[i] );
531 QString layerName = vectorFileName.left( vectorFileName.indexOf( QLatin1String(
".shp" ), Qt::CaseInsensitive ) );
532 QFile prjFile( layerName +
".qpj" );
533 if ( prjFile.exists() )
541 mErrorMessage = QObject::tr(
"Creation of layer failed (OGR error: %1)" )
542 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
544 mErrorMessage = QObject::tr(
"Opening of layer failed (OGR error: %1)" )
545 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
550 OGRFeatureDefnH defn = OGR_L_GetLayerDefn(
mLayer );
559 QSet<int> existingIdxs;
563#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,7,0)
564 if (
const char *pszCreateFieldDefnFlags = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATION_FIELD_DEFN_FLAGS,
nullptr ) )
566 char **papszTokens = CSLTokenizeString2( pszCreateFieldDefnFlags,
" ", 0 );
567 if ( CSLFindString( papszTokens,
"AlternativeName" ) >= 0 )
571 if ( CSLFindString( papszTokens,
"Comment" ) >= 0 )
575 CSLDestroy( papszTokens );
585 for (
int fldIdx = 0; fldIdx < fields.
count(); ++fldIdx )
589 if ( fieldValueConverter )
591 attrField = fieldValueConverter->fieldDefinition( fields.
at( fldIdx ) );
596 int ogrIdx = OGR_FD_GetFieldIndex( defn,
mCodec->fromUnicode( attrField.
name() ) );
605 switch ( fieldNameSource )
608 name = attrField.
name();
612 name = !attrField.
alias().isEmpty() ? attrField.
alias() : attrField.
name();
616 OGRFieldType ogrType = OFTString;
617 OGRFieldSubType ogrSubType = OFSTNone;
618 int ogrWidth = attrField.
length();
619 int ogrPrecision = attrField.
precision();
620 if ( ogrPrecision > 0 )
623 switch ( attrField.
type() )
625 case QVariant::LongLong:
627 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
628 if ( pszDataTypes && strstr( pszDataTypes,
"Integer64" ) )
629 ogrType = OFTInteger64;
632 ogrWidth = ogrWidth > 0 && ogrWidth <= 20 ? ogrWidth : 20;
636 case QVariant::String:
638 if ( ( ogrWidth <= 0 || ogrWidth > 255 ) &&
mOgrDriverName == QLatin1String(
"ESRI Shapefile" ) )
643 ogrType = OFTInteger;
644 ogrWidth = ogrWidth > 0 && ogrWidth <= 10 ? ogrWidth : 10;
649 ogrType = OFTInteger;
650 ogrSubType = OFSTBoolean;
655 case QVariant::Double:
656#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(3,3,1)
657 if (
mOgrDriverName == QLatin1String(
"GPKG" ) && attrField.
precision() == 0 && attrField.
name().compare( fidFieldName, Qt::CaseInsensitive ) == 0 )
660 ogrType = OFTInteger64;
683 case QVariant::DateTime:
691 ogrType = OFTDateTime;
695 case QVariant::ByteArray:
699 case QVariant::StringList:
705 ogrSubType = OFSTJSON;
709 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
710 if ( pszDataTypes && strstr( pszDataTypes,
"StringList" ) )
712 ogrType = OFTStringList;
713 mSupportedListSubTypes.insert( QVariant::String );
726 const char *pszDataSubTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATASUBTYPES,
nullptr );
727 if ( pszDataSubTypes && strstr( pszDataSubTypes,
"JSON" ) )
730 ogrSubType = OFSTJSON;
743 ogrSubType = OFSTJSON;
748 if ( attrField.
subType() == QVariant::String )
750 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
751 if ( pszDataTypes && strstr( pszDataTypes,
"StringList" ) )
753 ogrType = OFTStringList;
754 mSupportedListSubTypes.insert( QVariant::String );
763 else if ( attrField.
subType() == QVariant::Int )
765 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
766 if ( pszDataTypes && strstr( pszDataTypes,
"IntegerList" ) )
768 ogrType = OFTIntegerList;
769 mSupportedListSubTypes.insert( QVariant::Int );
778 else if ( attrField.
subType() == QVariant::Double )
780 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
781 if ( pszDataTypes && strstr( pszDataTypes,
"RealList" ) )
783 ogrType = OFTRealList;
784 mSupportedListSubTypes.insert( QVariant::Double );
793 else if ( attrField.
subType() == QVariant::LongLong )
795 const char *pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES,
nullptr );
796 if ( pszDataTypes && strstr( pszDataTypes,
"Integer64List" ) )
798 ogrType = OFTInteger64List;
799 mSupportedListSubTypes.insert( QVariant::LongLong );
813 mErrorMessage = QObject::tr(
"Unsupported type for field %1" )
814 .arg( attrField.
name() );
819 if (
mOgrDriverName == QLatin1String(
"SQLite" ) && name.compare( QLatin1String(
"ogc_fid" ), Qt::CaseInsensitive ) == 0 )
822 for ( i = 0; i < 10; i++ )
824 name = QStringLiteral(
"ogc_fid%1" ).arg( i );
827 for ( j = 0; j < fields.
size() && name.compare( fields.
at( j ).
name(), Qt::CaseInsensitive ) != 0; j++ )
830 if ( j == fields.
size() )
836 mErrorMessage = QObject::tr(
"No available replacement for internal fieldname ogc_fid found" ).arg( attrField.
name() );
841 QgsMessageLog::logMessage( QObject::tr(
"Reserved attribute name ogc_fid replaced with %1" ).arg( name ), QObject::tr(
"OGR" ) );
848 OGR_Fld_SetWidth( fld.get(), ogrWidth );
851 if ( ogrPrecision >= 0 )
853 OGR_Fld_SetPrecision( fld.get(), ogrPrecision );
856 if ( ogrSubType != OFSTNone )
857 OGR_Fld_SetSubType( fld.get(), ogrSubType );
859#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,6,0)
860 OGR_Fld_SetAlternativeName( fld.get(),
mCodec->fromUnicode( attrField.
alias() ).constData() );
862#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,7,0)
863 OGR_Fld_SetComment( fld.get(),
mCodec->fromUnicode( attrField.
comment() ).constData() );
870 OGR_Fld_SetNullable( fld.get(),
false );
874 OGR_Fld_SetUnique( fld.get(),
true );
880 " type " + QString( QVariant::typeToName( attrField.
type() ) ) +
881 " width " + QString::number( ogrWidth ) +
882 " precision " + QString::number( ogrPrecision ), 2 );
883 if ( OGR_L_CreateField(
mLayer, fld.get(),
true ) != OGRERR_NONE )
886 mErrorMessage = QObject::tr(
"Creation of field %1 failed (OGR error: %2)" )
887 .arg( attrField.
name(),
888 QString::fromUtf8( CPLGetLastErrorMsg() ) );
893 int ogrIdx = OGR_FD_GetFieldIndex( defn,
mCodec->fromUnicode( name ) );
894 QgsDebugMsgLevel( QStringLiteral(
"returned field index for %1: %2" ).arg( name ).arg( ogrIdx ), 2 );
895 if ( ogrIdx < 0 || existingIdxs.contains( ogrIdx ) )
898 ogrIdx = OGR_FD_GetFieldCount( defn ) - 1;
903 mErrorMessage = QObject::tr(
"Created field %1 not found (OGR error: %2)" )
904 .arg( attrField.
name(),
905 QString::fromUtf8( CPLGetLastErrorMsg() ) );
911 existingIdxs.insert( ogrIdx );
919 for (
int fldIdx = 0; fldIdx < fields.
count(); ++fldIdx )
922 QString name( attrField.
name() );
923 int ogrIdx = OGR_FD_GetFieldIndex( defn,
mCodec->fromUnicode( name ) );
935 int fidIdx = fields.
lookupField( QStringLiteral(
"FID" ) );
946 *newFilename = vectorFileName;
949 mUsingTransaction =
true;
950 if ( OGRERR_NONE != OGR_L_StartTransaction(
mLayer ) )
952 mUsingTransaction =
false;
962class QgsVectorFileWriterMetadataContainer
966 QgsVectorFileWriterMetadataContainer()
968 QMap<QString, QgsVectorFileWriter::Option *> datasetOptions;
969 QMap<QString, QgsVectorFileWriter::Option *> layerOptions;
972 datasetOptions.clear();
973 layerOptions.clear();
976 QObject::tr(
"Compression method." ),
978 << QStringLiteral(
"UNCOMPRESSED" )
979 << QStringLiteral(
"ZSTD" )
980 << QStringLiteral(
"LZ4" ),
981 QStringLiteral(
"LZ4" ),
986 QObject::tr(
"Geometry encoding." ),
988 << QStringLiteral(
"GEOARROW" )
989 << QStringLiteral(
"WKB" )
990 << QStringLiteral(
"WKT" ),
991 QStringLiteral(
"GEOARROW" ),
996 QObject::tr(
"Maximum number of rows per batch." ),
1001 QObject::tr(
"Name for the feature identifier column" ),
1006 QObject::tr(
"Name for the geometry column" ),
1007 QStringLiteral(
"geometry" )
1010 driverMetadata.insert( QStringLiteral(
"Arrow" ),
1012 QStringLiteral(
"(Geo)Arrow" ),
1013 QObject::tr(
"(Geo)Arrow" ),
1014 QStringLiteral(
"*.arrow *.feather *.arrows *.ipc" ),
1015 QStringLiteral(
"arrow" ),
1018 QStringLiteral(
"UTF-8" )
1023 datasetOptions.clear();
1024 layerOptions.clear();
1026 driverMetadata.insert( QStringLiteral(
"AVCE00" ),
1028 QStringLiteral(
"Arc/Info ASCII Coverage" ),
1029 QObject::tr(
"Arc/Info ASCII Coverage" ),
1030 QStringLiteral(
"*.e00" ),
1031 QStringLiteral(
"e00" ),
1038#if GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(3,3,0)
1042 datasetOptions.clear();
1043 layerOptions.clear();
1046 QObject::tr(
"New BNA files are created by the "
1047 "systems default line termination conventions. "
1048 "This may be overridden here." ),
1050 << QStringLiteral(
"CRLF" )
1051 << QStringLiteral(
"LF" ),
1057 QObject::tr(
"By default, BNA files are created in multi-line format. "
1058 "For each record, the first line contains the identifiers and the "
1059 "type/number of coordinates to follow. Each following line contains "
1060 "a pair of coordinates." ),
1065 QObject::tr(
"BNA records may contain from 2 to 4 identifiers per record. "
1066 "Some software packages only support a precise number of identifiers. "
1067 "You can override the default value (2) by a precise value." ),
1069 << QStringLiteral(
"2" )
1070 << QStringLiteral(
"3" )
1071 << QStringLiteral(
"4" )
1072 << QStringLiteral(
"NB_SOURCE_FIELDS" ),
1073 QStringLiteral(
"2" )
1077 QObject::tr(
"The BNA writer will try to recognize ellipses and circles when writing a polygon. "
1078 "This will only work if the feature has previously been read from a BNA file. "
1079 "As some software packages do not support ellipses/circles in BNA data file, "
1080 "it may be useful to tell the writer by specifying ELLIPSES_AS_ELLIPSES=NO not "
1081 "to export them as such, but keep them as polygons." ),
1086 QObject::tr(
"Limit the number of coordinate pairs per line in multiline format." ),
1091 QObject::tr(
"Set the number of decimal for coordinates. Default value is 10." ),
1095 driverMetadata.insert( QStringLiteral(
"BNA" ),
1097 QStringLiteral(
"Atlas BNA" ),
1098 QObject::tr(
"Atlas BNA" ),
1099 QStringLiteral(
"*.bna" ),
1100 QStringLiteral(
"bna" ),
1108 datasetOptions.clear();
1109 layerOptions.clear();
1112 QObject::tr(
"By default when creating new .csv files they "
1113 "are created with the line termination conventions "
1114 "of the local platform (CR/LF on Win32 or LF on all other systems). "
1115 "This may be overridden through the use of the LINEFORMAT option." ),
1117 << QStringLiteral(
"CRLF" )
1118 << QStringLiteral(
"LF" ),
1124 QObject::tr(
"By default, the geometry of a feature written to a .csv file is discarded. "
1125 "It is possible to export the geometry in its WKT representation by "
1126 "specifying GEOMETRY=AS_WKT. It is also possible to export point geometries "
1127 "into their X,Y,Z components by specifying GEOMETRY=AS_XYZ, GEOMETRY=AS_XY "
1128 "or GEOMETRY=AS_YX." ),
1130 << QStringLiteral(
"AS_WKT" )
1131 << QStringLiteral(
"AS_XYZ" )
1132 << QStringLiteral(
"AS_XY" )
1133 << QStringLiteral(
"AS_YX" ),
1139 QObject::tr(
"Create the associated .csvt file to describe the type of each "
1140 "column of the layer and its optional width and precision." ),
1145 QObject::tr(
"Field separator character." ),
1147 << QStringLiteral(
"COMMA" )
1148 << QStringLiteral(
"SEMICOLON" )
1149 << QStringLiteral(
"TAB" ),
1150 QStringLiteral(
"COMMA" )
1154 QObject::tr(
"Double-quote strings. IF_AMBIGUOUS means that string values that look like numbers will be quoted." ),
1156 << QStringLiteral(
"IF_NEEDED" )
1157 << QStringLiteral(
"IF_AMBIGUOUS" )
1158 << QStringLiteral(
"ALWAYS" ),
1159 QStringLiteral(
"IF_AMBIGUOUS" )
1163 QObject::tr(
"Write a UTF-8 Byte Order Mark (BOM) at the start of the file." ),
1167 driverMetadata.insert( QStringLiteral(
"CSV" ),
1169 QStringLiteral(
"Comma Separated Value [CSV]" ),
1170 QObject::tr(
"Comma Separated Value [CSV]" ),
1171 QStringLiteral(
"*.csv" ),
1172 QStringLiteral(
"csv" ),
1179 datasetOptions.clear();
1180 layerOptions.clear();
1182 driverMetadata.insert( QStringLiteral(
"FlatGeobuf" ),
1184 QStringLiteral(
"FlatGeobuf" ),
1185 QObject::tr(
"FlatGeobuf" ),
1186 QStringLiteral(
"*.fgb" ),
1187 QStringLiteral(
"fgb" ),
1190 QStringLiteral(
"UTF-8" )
1195 datasetOptions.clear();
1196 layerOptions.clear();
1199 QObject::tr(
"Override the type of shapefile created. "
1200 "Can be one of NULL for a simple .dbf file with no .shp file, POINT, "
1201 "ARC, POLYGON or MULTIPOINT for 2D, or POINTZ, ARCZ, POLYGONZ or "
1202 "MULTIPOINTZ for 3D;" ) +
1203 QObject::tr(
" POINTM, ARCM, POLYGONM or MULTIPOINTM for measured geometries"
1204 " and POINTZM, ARCZM, POLYGONZM or MULTIPOINTZM for 3D measured"
1206 QObject::tr(
" MULTIPATCH files are supported since GDAL 2.2." ) +
1209 << QStringLiteral(
"NULL" )
1210 << QStringLiteral(
"POINT" )
1211 << QStringLiteral(
"ARC" )
1212 << QStringLiteral(
"POLYGON" )
1213 << QStringLiteral(
"MULTIPOINT" )
1214 << QStringLiteral(
"POINTZ" )
1215 << QStringLiteral(
"ARCZ" )
1216 << QStringLiteral(
"POLYGONZ" )
1217 << QStringLiteral(
"MULTIPOINTZ" )
1218 << QStringLiteral(
"POINTM" )
1219 << QStringLiteral(
"ARCM" )
1220 << QStringLiteral(
"POLYGONM" )
1221 << QStringLiteral(
"MULTIPOINTM" )
1222 << QStringLiteral(
"POINTZM" )
1223 << QStringLiteral(
"ARCZM" )
1224 << QStringLiteral(
"POLYGONZM" )
1225 << QStringLiteral(
"MULTIPOINTZM" )
1226 << QStringLiteral(
"MULTIPATCH" )
1236 QObject::tr(
"Set the encoding value in the DBF file. "
1237 "The default value is LDID/87. It is not clear "
1238 "what other values may be appropriate." ),
1246 QObject::tr(
"Set to YES to resize fields to their optimal size." ),
1250 driverMetadata.insert( QStringLiteral(
"ESRI" ),
1252 QStringLiteral(
"ESRI Shapefile" ),
1253 QObject::tr(
"ESRI Shapefile" ),
1254 QStringLiteral(
"*.shp" ),
1255 QStringLiteral(
"shp" ),
1262 datasetOptions.clear();
1263 layerOptions.clear();
1265 driverMetadata.insert( QStringLiteral(
"DBF File" ),
1267 QStringLiteral(
"DBF File" ),
1268 QObject::tr(
"DBF File" ),
1269 QStringLiteral(
"*.dbf" ),
1270 QStringLiteral(
"dbf" ),
1277 datasetOptions.clear();
1278 layerOptions.clear();
1280 driverMetadata.insert( QStringLiteral(
"FMEObjects Gateway" ),
1282 QStringLiteral(
"FMEObjects Gateway" ),
1283 QObject::tr(
"FMEObjects Gateway" ),
1284 QStringLiteral(
"*.fdd" ),
1285 QStringLiteral(
"fdd" ),
1292 datasetOptions.clear();
1293 layerOptions.clear();
1296 QObject::tr(
"Set to YES to write a bbox property with the bounding box "
1297 "of the geometries at the feature and feature collection level." ),
1302 QObject::tr(
"Maximum number of figures after decimal separator to write in coordinates. "
1303 "Defaults to 15. Truncation will occur to remove trailing zeros." ),
1308 QObject::tr(
"Whether to use RFC 7946 standard. "
1309 "If disabled GeoJSON 2008 initial version will be used. "
1310 "Default is NO (thus GeoJSON 2008). See also Documentation (via Help button)" ),
1314 driverMetadata.insert( QStringLiteral(
"GeoJSON" ),
1316 QStringLiteral(
"GeoJSON" ),
1317 QObject::tr(
"GeoJSON" ),
1318 QStringLiteral(
"*.geojson" ),
1319 QStringLiteral(
"geojson" ),
1322 QStringLiteral(
"UTF-8" )
1327 datasetOptions.clear();
1328 layerOptions.clear();
1331 QObject::tr(
"Maximum number of figures after decimal separator to write in coordinates. "
1332 "Defaults to 15. Truncation will occur to remove trailing zeros." ),
1337 QObject::tr(
"Whether to start records with the RS=0x1E character (RFC 8142 standard). "
1338 "Defaults to NO: Newline Delimited JSON (geojsonl). \n"
1339 "If set to YES: RFC 8142 standard: GeoJSON Text Sequences (geojsons)." ),
1343 driverMetadata.insert( QStringLiteral(
"GeoJSONSeq" ),
1345 QStringLiteral(
"GeoJSON - Newline Delimited" ),
1346 QObject::tr(
"GeoJSON - Newline Delimited" ),
1347 QStringLiteral(
"*.geojsonl *.geojsons *.json" ),
1348 QStringLiteral(
"json" ),
1351 QStringLiteral(
"UTF-8" )
1356 datasetOptions.clear();
1357 layerOptions.clear();
1360 QObject::tr(
"whether the document must be in RSS 2.0 or Atom 1.0 format. "
1361 "Default value : RSS" ),
1363 << QStringLiteral(
"RSS" )
1364 << QStringLiteral(
"ATOM" ),
1365 QStringLiteral(
"RSS" )
1369 QObject::tr(
"The encoding of location information. Default value : SIMPLE. "
1370 "W3C_GEO only supports point geometries. "
1371 "SIMPLE or W3C_GEO only support geometries in geographic WGS84 coordinates." ),
1373 << QStringLiteral(
"SIMPLE" )
1374 << QStringLiteral(
"GML" )
1375 << QStringLiteral(
"W3C_GEO" ),
1376 QStringLiteral(
"SIMPLE" )
1380 QObject::tr(
"If defined to YES, extension fields will be written. "
1381 "If the field name not found in the base schema matches "
1382 "the foo_bar pattern, foo will be considered as the namespace "
1383 "of the element, and a <foo:bar> element will be written. "
1384 "Otherwise, elements will be written in the <ogr:> namespace." ),
1389 QObject::tr(
"If defined to NO, only <entry> or <item> elements will be written. "
1390 "The user will have to provide the appropriate header and footer of the document." ),
1395 QObject::tr(
"XML content that will be put between the <channel> element and the "
1396 "first <item> element for a RSS document, or between the xml tag and "
1397 "the first <entry> element for an Atom document." ),
1402 QObject::tr(
"Value put inside the <title> element in the header. "
1403 "If not provided, a dummy value will be used as that element is compulsory." ),
1408 QObject::tr(
"Value put inside the <description> element in the header. "
1409 "If not provided, a dummy value will be used as that element is compulsory." ),
1414 QObject::tr(
"Value put inside the <link> element in the header. "
1415 "If not provided, a dummy value will be used as that element is compulsory." ),
1420 QObject::tr(
"Value put inside the <updated> element in the header. "
1421 "Should be formatted as a XML datetime. "
1422 "If not provided, a dummy value will be used as that element is compulsory." ),
1427 QObject::tr(
"Value put inside the <author><name> element in the header. "
1428 "If not provided, a dummy value will be used as that element is compulsory." ),
1433 QObject::tr(
"Value put inside the <id> element in the header. "
1434 "If not provided, a dummy value will be used as that element is compulsory." ),
1438 driverMetadata.insert( QStringLiteral(
"GeoRSS" ),
1440 QStringLiteral(
"GeoRSS" ),
1441 QObject::tr(
"GeoRSS" ),
1442 QStringLiteral(
"*.xml" ),
1443 QStringLiteral(
"xml" ),
1446 QStringLiteral(
"UTF-8" )
1451 datasetOptions.clear();
1452 layerOptions.clear();
1455 QObject::tr(
"If provided, this URI will be inserted as the schema location. "
1456 "Note that the schema file isn't actually accessed by OGR, so it "
1457 "is up to the user to ensure it will match the schema of the OGR "
1458 "produced GML data file." ),
1463 QObject::tr(
"This writes a GML application schema file to a corresponding "
1464 ".xsd file (with the same basename). If INTERNAL is used the "
1465 "schema is written within the GML file, but this is experimental "
1466 "and almost certainly not valid XML. "
1467 "OFF disables schema generation (and is implicit if XSISCHEMAURI is used)." ),
1469 << QStringLiteral(
"EXTERNAL" )
1470 << QStringLiteral(
"INTERNAL" )
1471 << QStringLiteral(
"OFF" ),
1472 QStringLiteral(
"EXTERNAL" )
1476 QObject::tr(
"This is the prefix for the application target namespace." ),
1477 QStringLiteral(
"ogr" )
1481 QObject::tr(
"Can be set to TRUE to avoid writing the prefix of the "
1482 "application target namespace in the GML file." ),
1487 QObject::tr(
"Defaults to 'http://ogr.maptools.org/'. "
1488 "This is the application target namespace." ),
1489 QStringLiteral(
"http://ogr.maptools.org/" )
1493 QObject::tr(
"GML version to use." ),
1495 << QStringLiteral(
"GML2" )
1496 << QStringLiteral(
"GML3" )
1497 << QStringLiteral(
"GML3Deegree" )
1498 << QStringLiteral(
"GML3.2" ),
1499 QStringLiteral(
"GML3.2" )
1503 QObject::tr(
"Only valid when FORMAT=GML3/GML3Degree/GML3.2. Default to YES. "
1504 "If YES, SRS with EPSG authority will be written with the "
1505 "'urn:ogc:def:crs:EPSG::' prefix. In the case the SRS is a "
1506 "geographic SRS without explicit AXIS order, but that the same "
1507 "SRS authority code imported with ImportFromEPSGA() should be "
1508 "treated as lat/long, then the function will take care of coordinate "
1509 "order swapping. If set to NO, SRS with EPSG authority will be "
1510 "written with the 'EPSG:' prefix, even if they are in lat/long order." ),
1515 QObject::tr(
"only valid when FORMAT=GML3/GML3Degree/GML3.2) Default to YES. "
1516 "If set to NO, the <gml:boundedBy> element will not be written for "
1522 QObject::tr(
"Default to YES. If YES, the output will be indented with spaces "
1523 "for more readability, but at the expense of file size." ),
1528 driverMetadata.insert( QStringLiteral(
"GML" ),
1530 QStringLiteral(
"Geography Markup Language [GML]" ),
1531 QObject::tr(
"Geography Markup Language [GML]" ),
1532 QStringLiteral(
"*.gml" ),
1533 QStringLiteral(
"gml" ),
1536 QStringLiteral(
"UTF-8" )
1541 datasetOptions.clear();
1542 layerOptions.clear();
1545 QObject::tr(
"Human-readable identifier (e.g. short name) for the layer content" ),
1550 QObject::tr(
"Human-readable description for the layer content" ),
1555 QObject::tr(
"Name for the feature identifier column" ),
1556 QStringLiteral(
"fid" )
1560 QObject::tr(
"Name for the geometry column" ),
1561 QStringLiteral(
"geom" )
1565 QObject::tr(
"If a spatial index must be created." ),
1569 driverMetadata.insert( QStringLiteral(
"GPKG" ),
1571 QStringLiteral(
"GeoPackage" ),
1572 QObject::tr(
"GeoPackage" ),
1573 QStringLiteral(
"*.gpkg" ),
1574 QStringLiteral(
"gpkg" ),
1577 QStringLiteral(
"UTF-8" )
1582 datasetOptions.clear();
1583 layerOptions.clear();
1585 driverMetadata.insert( QStringLiteral(
"GMT" ),
1587 QStringLiteral(
"Generic Mapping Tools [GMT]" ),
1588 QObject::tr(
"Generic Mapping Tools [GMT]" ),
1589 QStringLiteral(
"*.gmt" ),
1590 QStringLiteral(
"gmt" ),
1597 datasetOptions.clear();
1598 layerOptions.clear();
1601 QObject::tr(
"By default when writing a layer whose features are of "
1602 "type wkbLineString, the GPX driver chooses to write "
1603 "them as routes. If FORCE_GPX_TRACK=YES is specified, "
1604 "they will be written as tracks." ),
1609 QObject::tr(
"By default when writing a layer whose features are of "
1610 "type wkbMultiLineString, the GPX driver chooses to write "
1611 "them as tracks. If FORCE_GPX_ROUTE=YES is specified, "
1612 "they will be written as routes, provided that the multilines "
1613 "are composed of only one single line." ),
1618 QObject::tr(
"If GPX_USE_EXTENSIONS=YES is specified, "
1619 "extra fields will be written inside the <extensions> tag." ),
1624 QObject::tr(
"Only used if GPX_USE_EXTENSIONS=YES and GPX_EXTENSIONS_NS_URL "
1625 "is set. The namespace value used for extension tags. By default, 'ogr'." ),
1626 QStringLiteral(
"ogr" )
1630 QObject::tr(
"Only used if GPX_USE_EXTENSIONS=YES and GPX_EXTENSIONS_NS "
1631 "is set. The namespace URI. By default, 'http://osgeo.org/gdal'." ),
1632 QStringLiteral(
"http://osgeo.org/gdal" )
1636 QObject::tr(
"By default files are created with the line termination "
1637 "conventions of the local platform (CR/LF on win32 or LF "
1638 "on all other systems). This may be overridden through use "
1639 "of the LINEFORMAT layer creation option which may have a value "
1640 "of CRLF (DOS format) or LF (Unix format)." ),
1642 << QStringLiteral(
"CRLF" )
1643 << QStringLiteral(
"LF" ),
1648 driverMetadata.insert( QStringLiteral(
"GPX" ),
1650 QStringLiteral(
"GPS eXchange Format [GPX]" ),
1651 QObject::tr(
"GPS eXchange Format [GPX]" ),
1652 QStringLiteral(
"*.gpx" ),
1653 QStringLiteral(
"gpx" ),
1656 QStringLiteral(
"UTF-8" )
1661 datasetOptions.clear();
1662 layerOptions.clear();
1664 driverMetadata.insert( QStringLiteral(
"Interlis 1" ),
1666 QStringLiteral(
"INTERLIS 1" ),
1667 QObject::tr(
"INTERLIS 1" ),
1668 QStringLiteral(
"*.itf *.xml *.ili" ),
1669 QStringLiteral(
"ili" ),
1676 datasetOptions.clear();
1677 layerOptions.clear();
1679 driverMetadata.insert( QStringLiteral(
"Interlis 2" ),
1681 QStringLiteral(
"INTERLIS 2" ),
1682 QObject::tr(
"INTERLIS 2" ),
1683 QStringLiteral(
"*.xtf *.xml *.ili" ),
1684 QStringLiteral(
"ili" ),
1691 datasetOptions.clear();
1692 layerOptions.clear();
1695 QObject::tr(
"Allows you to specify the field to use for the KML <name> element." ),
1696 QStringLiteral(
"Name" )
1700 QObject::tr(
"Allows you to specify the field to use for the KML <description> element." ),
1701 QStringLiteral(
"Description" )
1705 QObject::tr(
"Allows you to specify the AltitudeMode to use for KML geometries. "
1706 "This will only affect 3D geometries and must be one of the valid KML options." ),
1708 << QStringLiteral(
"clampToGround" )
1709 << QStringLiteral(
"relativeToGround" )
1710 << QStringLiteral(
"absolute" ),
1711 QStringLiteral(
"relativeToGround" )
1715 QObject::tr(
"The DOCUMENT_ID datasource creation option can be used to specified "
1716 "the id of the root <Document> node. The default value is root_doc." ),
1717 QStringLiteral(
"root_doc" )
1720 driverMetadata.insert( QStringLiteral(
"KML" ),
1722 QStringLiteral(
"Keyhole Markup Language [KML]" ),
1723 QObject::tr(
"Keyhole Markup Language [KML]" ),
1724 QStringLiteral(
"*.kml" ),
1725 QStringLiteral(
"kml" ),
1728 QStringLiteral(
"UTF-8" )
1733 datasetOptions.clear();
1734 layerOptions.clear();
1736 auto insertMapInfoOptions = []( QMap<QString, QgsVectorFileWriter::Option *> &datasetOptions, QMap<QString, QgsVectorFileWriter::Option *> &layerOptions )
1739 QObject::tr(
"Use this to turn on 'quick spatial index mode'. "
1740 "In this mode writing files can be about 5 times faster, "
1741 "but spatial queries can be up to 30 times slower." ),
1743 << QStringLiteral(
"QUICK" )
1744 << QStringLiteral(
"OPTIMIZED" ),
1745 QStringLiteral(
"QUICK" ),
1750 QObject::tr(
"(multiples of 512): Block size for .map files. Defaults "
1751 "to 512. MapInfo 15.2 and above creates .tab files with a "
1752 "blocksize of 16384 bytes. Any MapInfo version should be "
1753 "able to handle block sizes from 512 to 32256." ),
1757 QObject::tr(
"xmin,ymin,xmax,ymax: Define custom layer bounds to increase the "
1758 "accuracy of the coordinates. Note: the geometry of written "
1759 "features must be within the defined box." ),
1763 insertMapInfoOptions( datasetOptions, layerOptions );
1765 driverMetadata.insert( QStringLiteral(
"MapInfo File" ),
1767 QStringLiteral(
"Mapinfo" ),
1768 QObject::tr(
"Mapinfo TAB" ),
1769 QStringLiteral(
"*.tab" ),
1770 QStringLiteral(
"tab" ),
1775 datasetOptions.clear();
1776 layerOptions.clear();
1777 insertMapInfoOptions( datasetOptions, layerOptions );
1780 driverMetadata.insert( QStringLiteral(
"MapInfo MIF" ),
1782 QStringLiteral(
"Mapinfo" ),
1783 QObject::tr(
"Mapinfo MIF" ),
1784 QStringLiteral(
"*.mif" ),
1785 QStringLiteral(
"mif" ),
1792 datasetOptions.clear();
1793 layerOptions.clear();
1796 QObject::tr(
"Determine whether 2D (seed_2d.dgn) or 3D (seed_3d.dgn) "
1797 "seed file should be used. This option is ignored if the SEED option is provided." ),
1802 QObject::tr(
"Override the seed file to use." ),
1807 QObject::tr(
"Indicate whether the whole seed file should be copied. "
1808 "If not, only the first three elements will be copied." ),
1813 QObject::tr(
"Indicates whether the color table should be copied from the seed file." ),
1818 QObject::tr(
"Override the master unit name from the seed file with "
1819 "the provided one or two character unit name." ),
1824 QObject::tr(
"Override the sub unit name from the seed file with the provided "
1825 "one or two character unit name." ),
1830 QObject::tr(
"Override the number of subunits per master unit. "
1831 "By default the seed file value is used." ),
1836 QObject::tr(
"Override the number of UORs (Units of Resolution) "
1837 "per sub unit. By default the seed file value is used." ),
1842 QObject::tr(
"ORIGIN=x,y,z: Override the origin of the design plane. "
1843 "By default the origin from the seed file is used." ),
1847 driverMetadata.insert( QStringLiteral(
"DGN" ),
1849 QStringLiteral(
"Microstation DGN" ),
1850 QObject::tr(
"Microstation DGN" ),
1851 QStringLiteral(
"*.dgn" ),
1852 QStringLiteral(
"dgn" ),
1859 datasetOptions.clear();
1860 layerOptions.clear();
1863 QObject::tr(
"Should update files be incorporated into the base data on the fly." ),
1865 << QStringLiteral(
"APPLY" )
1866 << QStringLiteral(
"IGNORE" ),
1867 QStringLiteral(
"APPLY" )
1871 QObject::tr(
"Should multipoint soundings be split into many single point sounding features. "
1872 "Multipoint geometries are not well handled by many formats, "
1873 "so it can be convenient to split single sounding features with many points "
1874 "into many single point features." ),
1879 QObject::tr(
"Should a DEPTH attribute be added on SOUNDG features and assign the depth "
1880 "of the sounding. This should only be enabled when SPLIT_MULTIPOINT is "
1886 QObject::tr(
"Should all the low level geometry primitives be returned as special "
1887 "IsolatedNode, ConnectedNode, Edge and Face layers." ),
1892 QObject::tr(
"If enabled, numeric attributes assigned an empty string as a value will "
1893 "be preserved as a special numeric value. This option should not generally "
1894 "be needed, but may be useful when translated S-57 to S-57 losslessly." ),
1899 QObject::tr(
"Should LNAM and LNAM_REFS fields be attached to features capturing "
1900 "the feature to feature relationships in the FFPT group of the S-57 file." ),
1905 QObject::tr(
"Should additional attributes relating features to their underlying "
1906 "geometric primitives be attached. These are the values of the FSPT group, "
1907 "and are primarily needed when doing S-57 to S-57 translations." ),
1912 QObject::tr(
"Should attribute values be recoded to UTF-8 from the character encoding "
1913 "specified in the S57 DSSI record." ),
1919 driverMetadata.insert( QStringLiteral(
"S57" ),
1921 QStringLiteral(
"S-57 Base file" ),
1922 QObject::tr(
"S-57 Base file" ),
1923 QStringLiteral(
"*.000" ),
1924 QStringLiteral(
"000" ),
1931 datasetOptions.clear();
1932 layerOptions.clear();
1934 driverMetadata.insert( QStringLiteral(
"SDTS" ),
1936 QStringLiteral(
"Spatial Data Transfer Standard [SDTS]" ),
1937 QObject::tr(
"Spatial Data Transfer Standard [SDTS]" ),
1938 QStringLiteral(
"*catd.ddf" ),
1939 QStringLiteral(
"ddf" ),
1946 datasetOptions.clear();
1947 layerOptions.clear();
1950 QObject::tr(
"Can be used to avoid creating the geometry_columns and spatial_ref_sys "
1951 "tables in a new database. By default these metadata tables are created "
1952 "when a new database is created." ),
1958 QStringLiteral(
"NO" )
1963 QStringLiteral(
"NO" )
1967 QObject::tr(
"Controls the format used for the geometry column. Defaults to WKB. "
1968 "This is generally more space and processing efficient, but harder "
1969 "to inspect or use in simple applications than WKT (Well Known Text)." ),
1971 << QStringLiteral(
"WKB" )
1972 << QStringLiteral(
"WKT" ),
1973 QStringLiteral(
"WKB" )
1977 QObject::tr(
"Controls whether layer and field names will be laundered for easier use "
1978 "in SQLite. Laundered names will be converted to lower case and some special "
1979 "characters(' - #) will be changed to underscores." ),
1984 QStringLiteral(
"NO" )
1988 QStringLiteral(
"NO" )
1996 QObject::tr(
"column_name1[,column_name2, …] A list of (String) columns that "
1997 "must be compressed with ZLib DEFLATE algorithm. This might be beneficial "
1998 "for databases that have big string blobs. However, use with care, since "
1999 "the value of such columns will be seen as compressed binary content with "
2000 "other SQLite utilities (or previous OGR versions). With OGR, when inserting, "
2001 "modifying or querying compressed columns, compression/decompression is "
2002 "done transparently. However, such columns cannot be (easily) queried with "
2003 "an attribute filter or WHERE clause. Note: in table definition, such columns "
2004 "have the 'VARCHAR_deflate' declaration type." ),
2008 driverMetadata.insert( QStringLiteral(
"SQLite" ),
2010 QStringLiteral(
"SQLite" ),
2011 QObject::tr(
"SQLite" ),
2012 QStringLiteral(
"*.sqlite" ),
2013 QStringLiteral(
"sqlite" ),
2016 QStringLiteral(
"UTF-8" )
2021 datasetOptions.clear();
2022 layerOptions.clear();
2025 QObject::tr(
"Can be used to avoid creating the geometry_columns and spatial_ref_sys "
2026 "tables in a new database. By default these metadata tables are created "
2027 "when a new database is created." ),
2032 QStringLiteral(
"YES" )
2036 QObject::tr(
"Insert the content of the EPSG CSV files into the spatial_ref_sys table. "
2037 "Set to NO for regular SQLite databases." ),
2042 QStringLiteral(
"SPATIALITE" )
2046 QObject::tr(
"Controls whether layer and field names will be laundered for easier use "
2047 "in SQLite. Laundered names will be converted to lower case and some special "
2048 "characters(' - #) will be changed to underscores." ),
2053 QObject::tr(
"If the database is of the SpatiaLite flavor, and if OGR is linked "
2054 "against libspatialite, this option can be used to control if a spatial "
2055 "index must be created." ),
2060 QObject::tr(
"If the format of the geometry BLOB is of the SpatiaLite flavor, "
2061 "this option can be used to control if the compressed format for "
2062 "geometries (LINESTRINGs, POLYGONs) must be used." ),
2067 QObject::tr(
"Used to force the SRID number of the SRS associated with the layer. "
2068 "When this option isn't specified and that a SRS is associated with the "
2069 "layer, a search is made in the spatial_ref_sys to find a match for the "
2070 "SRS, and, if there is no match, a new entry is inserted for the SRS in "
2071 "the spatial_ref_sys table. When the SRID option is specified, this "
2072 "search (and the eventual insertion of a new entry) will not be done: "
2073 "the specified SRID is used as such." ),
2078 QObject::tr(
"column_name1[,column_name2, …] A list of (String) columns that "
2079 "must be compressed with ZLib DEFLATE algorithm. This might be beneficial "
2080 "for databases that have big string blobs. However, use with care, since "
2081 "the value of such columns will be seen as compressed binary content with "
2082 "other SQLite utilities (or previous OGR versions). With OGR, when inserting, "
2083 "modifying or queryings compressed columns, compression/decompression is "
2084 "done transparently. However, such columns cannot be (easily) queried with "
2085 "an attribute filter or WHERE clause. Note: in table definition, such columns "
2086 "have the 'VARCHAR_deflate' declaration type." ),
2090 driverMetadata.insert( QStringLiteral(
"SpatiaLite" ),
2092 QStringLiteral(
"SpatiaLite" ),
2093 QObject::tr(
"SpatiaLite" ),
2094 QStringLiteral(
"*.sqlite" ),
2095 QStringLiteral(
"sqlite" ),
2098 QStringLiteral(
"UTF-8" )
2102 datasetOptions.clear();
2103 layerOptions.clear();
2106 QObject::tr(
"Override the header file used - in place of header.dxf." ),
2111 QObject::tr(
"Override the trailer file used - in place of trailer.dxf." ),
2115 driverMetadata.insert( QStringLiteral(
"DXF" ),
2117 QStringLiteral(
"AutoCAD DXF" ),
2118 QObject::tr(
"AutoCAD DXF" ),
2119 QStringLiteral(
"*.dxf" ),
2120 QStringLiteral(
"dxf" ),
2127 datasetOptions.clear();
2128 layerOptions.clear();
2131 QObject::tr(
"Indicates the GeoConcept export file extension. "
2132 "TXT was used by earlier releases of GeoConcept. GXT is currently used." ),
2134 << QStringLiteral(
"GXT" )
2135 << QStringLiteral(
"TXT" ),
2136 QStringLiteral(
"GXT" )
2140 QObject::tr(
"Path to the GCT: the GCT file describes the GeoConcept types definitions: "
2141 "In this file, every line must start with //# followed by a keyword. "
2142 "Lines starting with // are comments." ),
2147 QObject::tr(
"Defines the feature to be created. The TYPE corresponds to one of the Name "
2148 "found in the GCT file for a type section. The SUBTYPE corresponds to one of "
2149 "the Name found in the GCT file for a sub-type section within the previous "
2154 driverMetadata.insert( QStringLiteral(
"Geoconcept" ),
2156 QStringLiteral(
"Geoconcept" ),
2157 QObject::tr(
"Geoconcept" ),
2158 QStringLiteral(
"*.gxt *.txt" ),
2159 QStringLiteral(
"gxt" ),
2166 datasetOptions.clear();
2167 layerOptions.clear();
2170 QObject::tr(
"When this option is set, the new layer will be created inside the named "
2171 "FeatureDataset folder. If the folder does not already exist, it will be created." ),
2176 QObject::tr(
"Set layer name alias." ),
2181 QObject::tr(
"Set name of geometry column in new layer. Defaults to 'SHAPE'." ),
2182 QStringLiteral(
"SHAPE" )
2186 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'." ),
2191 QObject::tr(
"Name of the OID column to create. Defaults to 'OBJECTID'." ),
2192 QStringLiteral(
"OBJECTID" )
2208 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." ),
2213 QObject::tr(
"XML documentation for the layer." ),
2217 QObject::tr(
"Customize how data is stored. By default text in UTF-8 and data up to 1TB." ),
2218 {QStringLiteral(
"DEFAULTS" ), QStringLiteral(
"MAX_FILE_SIZE_4GB" ), QStringLiteral(
"MAX_FILE_SIZE_256TB" )},
2219 QStringLiteral(
"DEFAULTS" ),
2224 QObject::tr(
" Defaults to NO (through CreateLayer() API). When this option is set, a Shape_Area and Shape_Length special fields will be created for polygonal layers (Shape_Length only for linear layers). These fields will automatically be populated with the feature’s area or length whenever a new feature is added to the dataset or an existing feature is amended. When using ogr2ogr with a source layer that has Shape_Area/Shape_Length special fields, and this option is not explicitly specified, it will be automatically set, so that the resulting FileGeodatabase has those fields properly tagged." ),
2228 driverMetadata.insert( QStringLiteral(
"OpenFileGDB" ),
2230 QStringLiteral(
"ESRI File Geodatabase" ),
2231 QObject::tr(
"ESRI File Geodatabase" ),
2232 QStringLiteral(
"*.gdb" ),
2233 QStringLiteral(
"gdb" ),
2236 QStringLiteral(
"UTF-8" )
2241 datasetOptions.clear();
2242 layerOptions.clear();
2245 QObject::tr(
"When this option is set, the new layer will be created inside the named "
2246 "FeatureDataset folder. If the folder does not already exist, it will be created." ),
2251 QObject::tr(
"Set name of geometry column in new layer. Defaults to 'SHAPE'." ),
2252 QStringLiteral(
"SHAPE" )
2256 QObject::tr(
"Name of the OID column to create. Defaults to 'OBJECTID'." ),
2257 QStringLiteral(
"OBJECTID" )
2260 driverMetadata.insert( QStringLiteral(
"FileGDB" ),
2262 QStringLiteral(
"ESRI FileGDB" ),
2263 QObject::tr(
"ESRI FileGDB" ),
2264 QStringLiteral(
"*.gdb" ),
2265 QStringLiteral(
"gdb" ),
2268 QStringLiteral(
"UTF-8" )
2273 datasetOptions.clear();
2274 layerOptions.clear();
2277 QObject::tr(
"By default, the driver will try to detect the data type of fields. If set "
2278 "to STRING, all fields will be of String type." ),
2280 << QStringLiteral(
"AUTO" )
2281 << QStringLiteral(
"STRING" ),
2282 QStringLiteral(
"AUTO" ),
2287 QObject::tr(
"By default, the driver will read the first lines of each sheet to detect "
2288 "if the first line might be the name of columns. If set to FORCE, the driver "
2289 "will consider the first line as the header line. If set to "
2290 "DISABLE, it will be considered as the first feature. Otherwise "
2291 "auto-detection will occur." ),
2293 << QStringLiteral(
"FORCE" )
2294 << QStringLiteral(
"DISABLE" )
2295 << QStringLiteral(
"AUTO" ),
2296 QStringLiteral(
"AUTO" ),
2300 driverMetadata.insert( QStringLiteral(
"XLSX" ),
2302 QStringLiteral(
"MS Office Open XML spreadsheet" ),
2303 QObject::tr(
"MS Office Open XML spreadsheet [XLSX]" ),
2304 QStringLiteral(
"*.xlsx" ),
2305 QStringLiteral(
"xlsx" ),
2308 QStringLiteral(
"UTF-8" )
2313 datasetOptions.clear();
2314 layerOptions.clear();
2317 QObject::tr(
"By default, the driver will try to detect the data type of fields. If set "
2318 "to STRING, all fields will be of String type." ),
2320 << QStringLiteral(
"AUTO" )
2321 << QStringLiteral(
"STRING" ),
2322 QStringLiteral(
"AUTO" ),
2327 QObject::tr(
"By default, the driver will read the first lines of each sheet to detect "
2328 "if the first line might be the name of columns. If set to FORCE, the driver "
2329 "will consider the first line as the header line. If set to "
2330 "DISABLE, it will be considered as the first feature. Otherwise "
2331 "auto-detection will occur." ),
2333 << QStringLiteral(
"FORCE" )
2334 << QStringLiteral(
"DISABLE" )
2335 << QStringLiteral(
"AUTO" ),
2336 QStringLiteral(
"AUTO" ),
2340 driverMetadata.insert( QStringLiteral(
"ODS" ),
2342 QStringLiteral(
"Open Document Spreadsheet" ),
2343 QObject::tr(
"Open Document Spreadsheet [ODS]" ),
2344 QStringLiteral(
"*.ods" ),
2345 QStringLiteral(
"ods" ),
2348 QStringLiteral(
"UTF-8" )
2353 datasetOptions.clear();
2354 layerOptions.clear();
2357 QObject::tr(
"Compression method." ),
2359 << QStringLiteral(
"UNCOMPRESSED" )
2360 << QStringLiteral(
"SNAPPY" ),
2361 QStringLiteral(
"SNAPPY" ),
2366 QObject::tr(
"Geometry encoding." ),
2368 << QStringLiteral(
"WKB" )
2369 << QStringLiteral(
"WKT" )
2370 << QStringLiteral(
"GEOARROW" ),
2371 QStringLiteral(
"WKB" ),
2376 QObject::tr(
"Maximum number of rows per group." ),
2381 QObject::tr(
"Name for the feature identifier column" ),
2386 QObject::tr(
"Name for the geometry column" ),
2387 QStringLiteral(
"geometry" )
2391 QObject::tr(
"Name of the coordinate system for the edges." ),
2393 << QStringLiteral(
"PLANAR" )
2394 << QStringLiteral(
"SPHERICAL" ),
2395 QStringLiteral(
"PLANAR" ),
2399 driverMetadata.insert( QStringLiteral(
"Parquet" ),
2401 QStringLiteral(
"(Geo)Parquet" ),
2402 QObject::tr(
"(Geo)Parquet" ),
2403 QStringLiteral(
"*.parquet" ),
2404 QStringLiteral(
"parquet" ),
2407 QStringLiteral(
"UTF-8" )
2412 datasetOptions.clear();
2413 layerOptions.clear();
2416 QObject::tr(
"Line termination character sequence." ),
2418 << QStringLiteral(
"CRLF" )
2419 << QStringLiteral(
"LF" ),
2420 QStringLiteral(
"LF" ),
2426 QObject::tr(
"Format of geometry columns." ),
2428 << QStringLiteral(
"geometry" )
2429 << QStringLiteral(
"geography" ),
2430 QStringLiteral(
"geometry" ),
2435 QObject::tr(
"Controls whether layer and field names will be laundered for easier use. "
2436 "Laundered names will be converted to lower case and some special "
2437 "characters(' - #) will be changed to underscores." ),
2442 QObject::tr(
"Name for the geometry column. Defaults to wkb_geometry "
2443 "for GEOM_TYPE=geometry or the_geog for GEOM_TYPE=geography" ) ) );
2446 QObject::tr(
"Name of schema into which to create the new table" ) ) );
2449 QObject::tr(
"Whether to explicitly emit the CREATE SCHEMA statement to create the specified schema." ),
2454 QObject::tr(
"Whether to explicitly recreate the table if necessary." ),
2459 QObject::tr(
"Whether to explicitly destroy tables before recreating them." ),
2461 << QStringLiteral(
"YES" )
2462 << QStringLiteral(
"NO" )
2463 << QStringLiteral(
"IF_EXISTS" ),
2464 QStringLiteral(
"YES" ),
2469 QObject::tr(
"Used to force the SRID number of the SRS associated with the layer. "
2470 "When this option isn't specified and that a SRS is associated with the "
2471 "layer, a search is made in the spatial_ref_sys to find a match for the "
2472 "SRS, and, if there is no match, a new entry is inserted for the SRS in "
2473 "the spatial_ref_sys table. When the SRID option is specified, this "
2474 "search (and the eventual insertion of a new entry) will not be done: "
2475 "the specified SRID is used as such." ),
2480 QObject::tr(
"Can be set to 2.0 or 2.2 for PostGIS 2.0/2.2 compatibility. "
2481 "Important to set it correctly if using non-linear geometry types" ),
2482 QStringLiteral(
"2.2" )
2485 driverMetadata.insert( QStringLiteral(
"PGDUMP" ),
2487 QStringLiteral(
"PostgreSQL SQL dump" ),
2488 QObject::tr(
"PostgreSQL SQL dump" ),
2489 QStringLiteral(
"*.sql" ),
2490 QStringLiteral(
"sql" ),
2493 QStringLiteral(
"UTF-8" )
2499 QgsVectorFileWriterMetadataContainer(
const QgsVectorFileWriterMetadataContainer &other ) =
delete;
2500 QgsVectorFileWriterMetadataContainer &operator=(
const QgsVectorFileWriterMetadataContainer &other ) =
delete;
2501 ~QgsVectorFileWriterMetadataContainer()
2503 for (
auto it = driverMetadata.constBegin(); it != driverMetadata.constEnd(); ++it )
2505 for (
auto optionIt = it.value().driverOptions.constBegin(); optionIt != it.value().driverOptions.constEnd(); ++optionIt )
2506 delete optionIt.value();
2507 for (
auto optionIt = it.value().layerOptions.constBegin(); optionIt != it.value().layerOptions.constEnd(); ++optionIt )
2508 delete optionIt.value();
2512 QMap<QString, QgsVectorFileWriter::MetaData> driverMetadata;
2519 static QgsVectorFileWriterMetadataContainer sDriverMetadata;
2520 QMap<QString, MetaData>::ConstIterator it = sDriverMetadata.driverMetadata.constBegin();
2522 for ( ; it != sDriverMetadata.driverMetadata.constEnd(); ++it )
2524 if ( it.key() == QLatin1String(
"PGDUMP" ) &&
2525 driverName != QLatin1String(
"PGDUMP" ) &&
2526 driverName != QLatin1String(
"PostgreSQL SQL dump" ) )
2531 if ( it.key().startsWith( driverName ) || it.value().longName.startsWith( driverName ) )
2546 return QStringList();
2555 return QStringList();
2562 OGRwkbGeometryType ogrType =
static_cast<OGRwkbGeometryType
>( type );
2593 return mCapabilities;
2603 QgsFeatureList::iterator fIt = features.begin();
2605 for ( ; fIt != features.end(); ++fIt )
2630 QString styleString;
2631 QString currentStyle;
2633 QgsSymbolList::const_iterator symbolIt = symbols.constBegin();
2634 for ( ; symbolIt != symbols.constEnd(); ++symbolIt )
2636 int nSymbolLayers = ( *symbolIt )->symbolLayerCount();
2637 for (
int i = 0; i < nSymbolLayers; ++i )
2640 QMap< QgsSymbolLayer *, QString >::const_iterator it =
mSymbolLayerTable.find( ( *symbolIt )->symbolLayer( i ) );
2646 double mmsf = mmScaleFactor(
mSymbologyScale, ( *symbolIt )->outputUnit(), outputUnit );
2647 double musf = mapUnitScaleFactor(
mSymbologyScale, ( *symbolIt )->outputUnit(), outputUnit );
2649 currentStyle = ( *symbolIt )->symbolLayer( i )->ogrFeatureStyle( mmsf, musf );
2655 if ( symbolIt != symbols.constBegin() || i != 0 )
2657 styleString.append(
';' );
2659 styleString.append( currentStyle );
2664 OGR_F_SetStyleString( poFeature.get(), currentStyle.toLocal8Bit().constData() );
2665 if ( !writeFeature(
mLayer, poFeature.get() ) )
2677 OGR_F_SetStyleString( poFeature.get(), styleString.toLocal8Bit().constData() );
2685 if ( !writeFeature(
mLayer, poFeature.get() ) )
2709 int fldIdx = it.key();
2710 int ogrField = it.value();
2712 QVariant attrValue = feature.
attribute( fldIdx );
2717 OGR_F_UnsetField( poFeature.get(), ogrField );
2730 OGR_F_SetFieldNull( poFeature.get(), ogrField );
2745 mErrorMessage = QObject::tr(
"Error converting value (%1) for attribute field %2: %3" )
2746 .arg( feature.
attribute( fldIdx ).toString(),
2753 switch ( field.
type() )
2756 OGR_F_SetFieldInteger( poFeature.get(), ogrField, attrValue.toInt() );
2758 case QVariant::LongLong:
2759 OGR_F_SetFieldInteger64( poFeature.get(), ogrField, attrValue.toLongLong() );
2761 case QVariant::Bool:
2762 OGR_F_SetFieldInteger( poFeature.get(), ogrField, attrValue.toInt() );
2764 case QVariant::String:
2765 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( attrValue.toString() ).constData() );
2767 case QVariant::Double:
2768 OGR_F_SetFieldDouble( poFeature.get(), ogrField, attrValue.toDouble() );
2770 case QVariant::Date:
2771 OGR_F_SetFieldDateTime( poFeature.get(), ogrField,
2772 attrValue.toDate().year(),
2773 attrValue.toDate().month(),
2774 attrValue.toDate().day(),
2777 case QVariant::DateTime:
2780 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( attrValue.toDateTime().toString( QStringLiteral(
"yyyy/MM/dd hh:mm:ss.zzz" ) ) ).constData() );
2784 const QDateTime dt = attrValue.toDateTime();
2785 const QDate date = dt.date();
2786 const QTime time = dt.time();
2787 OGR_F_SetFieldDateTimeEx( poFeature.get(), ogrField,
2793 static_cast<float>( time.second() +
static_cast< double >( time.msec() ) / 1000 ),
2797 case QVariant::Time:
2800 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( attrValue.toString() ).constData() );
2804 const QTime time = attrValue.toTime();
2805 OGR_F_SetFieldDateTimeEx( poFeature.get(), ogrField,
2809 static_cast<float>( time.second() +
static_cast< double >( time.msec() ) / 1000 ),
2814 case QVariant::ByteArray:
2816 const QByteArray ba = attrValue.toByteArray();
2817 OGR_F_SetFieldBinary( poFeature.get(), ogrField, ba.size(),
const_cast< GByte *
>(
reinterpret_cast< const GByte *
>( ba.data() ) ) );
2821 case QVariant::Invalid:
2824 case QVariant::StringList:
2829 const QJsonDocument doc = QJsonDocument::fromVariant( attrValue );
2831 if ( !doc.isNull() )
2833 jsonString = QString::fromUtf8( doc.toJson( QJsonDocument::Compact ).constData() );
2835 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( jsonString.constData() ) );
2839 QStringList list = attrValue.toStringList();
2840 if ( mSupportedListSubTypes.contains( QVariant::String ) )
2842 int count = list.count();
2843 char **lst =
new char *[count + 1];
2847 for (
const QString &
string : list )
2849 lst[pos] = CPLStrdup(
mCodec->fromUnicode(
string ).data() );
2853 lst[count] =
nullptr;
2854 OGR_F_SetFieldStringList( poFeature.get(), ogrField, lst );
2859 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( list.join(
',' ) ).constData() );
2864 case QVariant::List:
2868 const QJsonDocument doc = QJsonDocument::fromVariant( attrValue );
2870 if ( !doc.isNull() )
2872 jsonString = QString::fromUtf8( doc.toJson( QJsonDocument::Compact ).data() );
2874 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( jsonString.constData() ) );
2879 if ( field.
subType() == QVariant::String )
2881 QStringList list = attrValue.toStringList();
2882 if ( mSupportedListSubTypes.contains( QVariant::String ) )
2884 int count = list.count();
2885 char **lst =
new char *[count + 1];
2889 for (
const QString &
string : list )
2891 lst[pos] = CPLStrdup(
mCodec->fromUnicode(
string ).data() );
2895 lst[count] =
nullptr;
2896 OGR_F_SetFieldStringList( poFeature.get(), ogrField, lst );
2901 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( list.join(
',' ) ).constData() );
2905 else if ( field.
subType() == QVariant::Int )
2907 const QVariantList list = attrValue.toList();
2908 if ( mSupportedListSubTypes.contains( QVariant::Int ) )
2910 const int count = list.count();
2911 int *lst =
new int[count];
2915 for (
const QVariant &value : list )
2917 lst[pos] = value.toInt();
2921 OGR_F_SetFieldIntegerList( poFeature.get(), ogrField, count, lst );
2926 QStringList strings;
2927 strings.reserve( list.size() );
2928 for (
const QVariant &value : list )
2930 strings << QString::number( value.toInt() );
2932 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( strings.join(
',' ) ).constData() );
2936 else if ( field.
subType() == QVariant::Double )
2938 const QVariantList list = attrValue.toList();
2939 if ( mSupportedListSubTypes.contains( QVariant::Double ) )
2941 const int count = list.count();
2942 double *lst =
new double[count];
2946 for (
const QVariant &value : list )
2948 lst[pos] = value.toDouble();
2952 OGR_F_SetFieldDoubleList( poFeature.get(), ogrField, count, lst );
2957 QStringList strings;
2958 strings.reserve( list.size() );
2959 for (
const QVariant &value : list )
2961 strings << QString::number( value.toDouble() );
2963 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( strings.join(
',' ) ).constData() );
2967 else if ( field.
subType() == QVariant::LongLong )
2969 const QVariantList list = attrValue.toList();
2970 if ( mSupportedListSubTypes.contains( QVariant::LongLong ) )
2972 const int count = list.count();
2973 long long *lst =
new long long[count];
2977 for (
const QVariant &value : list )
2979 lst[pos] = value.toLongLong();
2983 OGR_F_SetFieldInteger64List( poFeature.get(), ogrField, count, lst );
2988 QStringList strings;
2989 strings.reserve( list.size() );
2990 for (
const QVariant &value : list )
2992 strings << QString::number( value.toLongLong() );
2994 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( strings.join(
',' ) ).constData() );
3004 const char *pszDataSubTypes = GDALGetMetadataItem( OGRGetDriverByName(
mOgrDriverName.toLocal8Bit().constData() ), GDAL_DMD_CREATIONFIELDDATASUBTYPES,
nullptr );
3005 if ( pszDataSubTypes && strstr( pszDataSubTypes,
"JSON" ) )
3007 const QJsonDocument doc = QJsonDocument::fromVariant( attrValue );
3009 if ( !doc.isNull() )
3011 const QByteArray json { doc.toJson( QJsonDocument::Compact ) };
3012 jsonString = QString::fromUtf8( json.data() );
3014 OGR_F_SetFieldString( poFeature.get(), ogrField,
mCodec->fromUnicode( jsonString.constData() ) );
3024 mErrorMessage = QObject::tr(
"Invalid variant type for field %1[%2]: received %3 with type %4" )
3027 .arg( attrValue.typeName(),
3028 attrValue.toString() );
3041 if ( mCoordinateTransform )
3046 geom.
transform( *mCoordinateTransform );
3064 OGRGeometryH mGeom2 =
nullptr;
3093 geom.
get()->
addZValue( std::numeric_limits<double>::quiet_NaN() );
3100 geom.
get()->
addMValue( std::numeric_limits<double>::quiet_NaN() );
3120 mErrorMessage = QObject::tr(
"Feature geometry not imported (OGR error: %1)" )
3121 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
3127 QgsAbstractGeometry::WkbFlags wkbFlags;
3131 QByteArray wkb( geom.
asWkb( wkbFlags ) );
3132 OGRErr err = OGR_G_ImportFromWkb( mGeom2,
reinterpret_cast<unsigned char *
>(
const_cast<char *
>( wkb.constData() ) ), wkb.length() );
3133 if ( err != OGRERR_NONE )
3135 mErrorMessage = QObject::tr(
"Feature geometry not imported (OGR error: %1)" )
3136 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
3143 OGR_F_SetGeometryDirectly( poFeature.get(), mGeom2 );
3151 QByteArray wkb( geom.
asWkb( wkbFlags ) );
3153 OGRErr err = OGR_G_ImportFromWkb( ogrGeom,
reinterpret_cast<unsigned char *
>(
const_cast<char *
>( wkb.constData() ) ), wkb.length() );
3154 if ( err != OGRERR_NONE )
3156 mErrorMessage = QObject::tr(
"Feature geometry not imported (OGR error: %1)" )
3157 .arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
3164 OGR_F_SetGeometryDirectly( poFeature.get(), ogrGeom );
3179 for (
int i = 0; i < attributes.size(); i++ )
3181 if ( omap.find( i ) != omap.end() )
3186bool QgsVectorFileWriter::writeFeature( OGRLayerH layer, OGRFeatureH feature )
3188 if ( OGR_L_CreateFeature( layer, feature ) != OGRERR_NONE )
3190 mErrorMessage = QObject::tr(
"Feature creation error (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) );
3200 if ( mUsingTransaction )
3202 if ( OGRERR_NONE != OGR_L_CommitTransaction(
mLayer ) )
3204 QgsDebugError( QStringLiteral(
"Error while committing transaction on OGRLayer." ) );
3217 const QString &fileName,
3218 const QString &fileEncoding,
3220 const QString &driverName,
3222 QString *errorMessage,
3223 const QStringList &datasourceOptions,
3224 const QStringList &layerOptions,
3225 bool skipAttributeCreation,
3226 QString *newFilename,
3228 double symbologyScale,
3238 if ( destCRS.
isValid() && layer )
3264 const QString &fileName,
3265 const QString &fileEncoding,
3267 const QString &driverName,
3269 QString *errorMessage,
3270 const QStringList &datasourceOptions,
3271 const QStringList &layerOptions,
3272 bool skipAttributeCreation,
3273 QString *newFilename,
3275 double symbologyScale,
3306 : driverName( QStringLiteral(
"GPKG" ) )
3314 if ( !layer || !layer->
isValid() )
3321 details.sourceCrs = layer->
crs();
3322 details.sourceWkbType = layer->
wkbType();
3323 details.sourceFields = layer->
fields();
3332 if ( details.storageType == QLatin1String(
"ESRI Shapefile" ) )
3340 details.geometryTypeScanIterator = layer->
getFeatures( req );
3344 details.renderContext.setExpressionContext( details.expressionContext );
3345 details.renderContext.setRendererScale( options.
symbologyScale );
3347 details.shallTransform =
false;
3352 details.shallTransform =
true;
3357 details.outputCrs = details.sourceCrs;
3360 details.destWkbType = details.sourceWkbType;
3374 details.attributes.clear();
3375 else if ( details.attributes.isEmpty() )
3377 const QgsAttributeList allAttributes = details.sourceFields.allAttributesList();
3378 for (
int idx : allAttributes )
3380 QgsField fld = details.sourceFields.at( idx );
3381 if ( details.providerType == QLatin1String(
"oracle" ) && fld.
typeName().contains( QLatin1String(
"SDO_GEOMETRY" ) ) )
3383 details.attributes.append( idx );
3387 if ( !details.attributes.isEmpty() )
3389 for (
int attrIdx : std::as_const( details.attributes ) )
3391 if ( details.sourceFields.exists( attrIdx ) )
3393 QgsField field = details.sourceFields.at( attrIdx );
3395 details.outputFields.append( field );
3399 QgsDebugError( QStringLiteral(
"No such source field with index '%1' available." ).arg( attrIdx ) );
3406 if ( details.providerType == QLatin1String(
"spatialite" ) )
3408 for (
int i = 0; i < details.outputFields.size(); i++ )
3410 if ( details.outputFields.at( i ).type() == QVariant::LongLong )
3415 if ( std::max( std::llabs( min.toLongLong() ), std::llabs( max.toLongLong() ) ) < std::numeric_limits<int>::max() )
3417 details.outputFields[i].setType( QVariant::Int );
3425 addRendererAttributes( details.renderer.get(), details.renderContext, details.sourceFields, details.attributes );
3435 bool useFilterRect =
true;
3436 if ( details.shallTransform )
3447 useFilterRect =
false;
3450 if ( useFilterRect )
3456 details.filterRectEngine->prepareGeometry();
3458 details.sourceFeatureIterator = layer->
getFeatures( req );
3472 int lastProgressReport = 0;
3473 long long total = details.featureCount;
3476 if ( details.providerType == QLatin1String(
"ogr" ) && !details.dataSourceUri.isEmpty() )
3478 QString srcFileName( details.providerUriParams.value( QStringLiteral(
"path" ) ).toString() );
3479 if ( QFile::exists( srcFileName ) && QFileInfo( fileName ).canonicalFilePath() == QFileInfo( srcFileName ).canonicalFilePath() )
3483 if ( !( ( options.
driverName == QLatin1String(
"GPKG" ) ||
3484 options.
driverName == QLatin1String(
"SpatiaLite" ) ||
3485 options.
driverName == QLatin1String(
"SQLite" ) ) &&
3486 options.
layerName != details.providerUriParams.value( QStringLiteral(
"layerName" ) ) ) )
3489 *
errorMessage = QObject::tr(
"Cannot overwrite a OGR layer in place" );
3509 int newProgress =
static_cast<int>( ( 5.0 * scanned ) / total );
3510 if ( newProgress != lastProgressReport )
3512 lastProgressReport = newProgress;
3527 QString tempNewFilename;
3528 QString tempNewLayer;
3530 std::unique_ptr< QgsVectorFileWriter > writer(
create( fileName, details.outputFields, destWkbType, details.outputCrs, transformContext, options, QgsFeatureSink::SinkFlags(), &tempNewFilename, &tempNewLayer ) );
3534 *newFilename = tempNewFilename;
3537 *newLayer = tempNewLayer;
3566 switch ( writer->symbologyExport() )
3584 int n = 0, errors = 0;
3593 writer->startRender( details.renderer.get(), details.sourceFields );
3595 writer->resetMap( details.attributes );
3597 writer->mFields = details.sourceFields;
3601 int initialProgress = lastProgressReport;
3602 while ( details.sourceFeatureIterator.nextFeature( fet ) )
3613 int newProgress =
static_cast<int>( initialProgress + ( ( 100.0 - initialProgress ) * saved ) / total );
3614 if ( newProgress < 100 && newProgress != lastProgressReport )
3616 lastProgressReport = newProgress;
3621 if ( details.shallTransform )
3634 QString msg = QObject::tr(
"Failed to transform a point while drawing a feature with ID '%1'. Writing stopped. (Exception: %2)" )
3635 .arg( fet.
id() ).arg( e.
what() );
3652 if ( !writer->addFeatureWithStyle( fet, writer->mRenderer.get(), mapUnits ) )
3659 *
errorMessage = QObject::tr(
"Feature write errors:" );
3665 if ( errors > 1000 )
3669 *
errorMessage += QObject::tr(
"Stopping after %n error(s)",
nullptr, errors );
3679 writer->stopRender();
3683 *
errorMessage += QObject::tr(
"\nOnly %1 of %2 features written." ).arg( n - errors ).arg( n );
3688 bool metadataFailure =
false;
3693 {QStringLiteral(
"path" ), tempNewFilename },
3694 {QStringLiteral(
"layerName" ), tempNewLayer }
3708 metadataFailure =
true;
3719 metadataFailure =
true;
3727 const QString &fileName,
3729 QString *newFilename,
3733 QgsVectorFileWriter::PreparedWriterDetails details;
3734 WriterError err = prepareWriteAsVectorFormat( layer, options, details );
3742 const QString &fileName,
3745 QString *newFilename,
3749 QgsVectorFileWriter::PreparedWriterDetails details;
3750 WriterError err = prepareWriteAsVectorFormat( layer, options, details );
3759 QgsVectorFileWriter::PreparedWriterDetails details;
3760 WriterError err = prepareWriteAsVectorFormat( layer, options, details );
3769 QFileInfo fi( fileName );
3770 QDir dir = fi.dir();
3773 for (
const char *suffix : {
".shp",
".shx",
".dbf",
".prj",
".qix",
".qpj",
".cpg",
".sbn",
".sbx",
".idm",
".ind" } )
3775 filter << fi.completeBaseName() + suffix;
3779 const auto constEntryList = dir.entryList( filter );
3780 for (
const QString &file : constEntryList )
3782 QFile f( dir.canonicalPath() +
'/' + file );
3785 QgsDebugError( QStringLiteral(
"Removing file %1 failed: %2" ).arg( file, f.errorString() ) );
3801 QStringList driverNames;
3804 for (
int i = 0; i < GDALGetDriverCount(); ++i )
3806 GDALDriverH
driver = GDALGetDriver( i );
3813 const QString driverExtensions = GDALGetMetadataItem(
driver, GDAL_DMD_EXTENSIONS,
"" );
3814 if ( driverExtensions.isEmpty() )
3817 const QSet< QString > splitExtensions = qgis::listToSet( driverExtensions.split(
' ', Qt::SkipEmptyParts ) );
3818 if ( splitExtensions.intersects( multiLayerExtensions ) )
3820 driverNames << OGR_Dr_GetName(
driver );
3828 static QReadWriteLock sFilterLock;
3829 static QMap< VectorFormatOptions, QList< QgsVectorFileWriter::FilterFormatDetails > > sFilters;
3833 const auto it = sFilters.constFind( options );
3834 if ( it != sFilters.constEnd() )
3838 QList< QgsVectorFileWriter::FilterFormatDetails > results;
3841 int const drvCount = OGRGetDriverCount();
3845 for (
int i = 0; i < drvCount; ++i )
3847 OGRSFDriverH drv = OGRGetDriver( i );
3850 const QString drvName = OGR_Dr_GetName( drv );
3854 if ( !multiLayerDrivers.contains( drvName ) )
3858 GDALDriverH gdalDriver = GDALGetDriverByName( drvName.toLocal8Bit().constData() );
3859 char **metadata =
nullptr;
3862 metadata = GDALGetMetadata( gdalDriver,
nullptr );
3865 bool nonSpatialFormat = CSLFetchBoolean( metadata, GDAL_DCAP_NONSPATIAL,
false );
3867 if ( OGR_Dr_TestCapability( drv,
"CreateDataSource" ) != 0 )
3872 if ( nonSpatialFormat )
3877 if ( filterString.isEmpty() )
3884 globs = metadata.
glob.toLower().split(
' ' );
3890 details.
globs = globs;
3899 if ( options & SortRecommended )
3901 if ( a.driverName == QLatin1String(
"GPKG" ) )
3903 else if ( b.driverName == QLatin1String(
"GPKG" ) )
3905 else if ( a.driverName == QLatin1String(
"ESRI Shapefile" ) )
3907 else if ( b.driverName == QLatin1String(
"ESRI Shapefile" ) )
3914 sFilters.insert( options, results );
3921 QSet< QString > extensions;
3923 const thread_local QRegularExpression rx( QStringLiteral(
"\\*\\.(.*)$" ) );
3927 for (
const QString &glob : format.globs )
3929 const QRegularExpressionMatch match = rx.match( glob );
3930 if ( !match.hasMatch() )
3933 const QString matched = match.captured( 1 );
3934 extensions.insert( matched );
3938 QStringList extensionList( extensions.constBegin(), extensions.constEnd() );
3940 std::sort( extensionList.begin(), extensionList.end(), [options](
const QString & a,
const QString & b ) ->
bool
3942 if ( options & SortRecommended )
3944 if ( a == QLatin1String(
"gpkg" ) )
3946 else if ( b == QLatin1String(
"gpkg" ) )
3948 else if ( a == QLatin1String(
"shp" ) )
3950 else if ( b == QLatin1String(
"shp" ) )
3954 return a.toLower().localeAwareCompare( b.toLower() ) < 0;
3957 return extensionList;
3962 QList< QgsVectorFileWriter::DriverDetails > results;
3965 const int drvCount = OGRGetDriverCount();
3969 QStringList writableDrivers;
3970 for (
int i = 0; i < drvCount; ++i )
3972 OGRSFDriverH drv = OGRGetDriver( i );
3975 const QString drvName = OGR_Dr_GetName( drv );
3979 if ( !multiLayerDrivers.contains( drvName ) )
3987 if ( drvName == QLatin1String(
"ODS" ) || drvName == QLatin1String(
"XLSX" ) || drvName == QLatin1String(
"XLS" ) )
3991 if ( drvName == QLatin1String(
"ESRI Shapefile" ) )
3993 writableDrivers << QStringLiteral(
"DBF file" );
3995 if ( OGR_Dr_TestCapability( drv,
"CreateDataSource" ) != 0 )
3998 if ( drvName == QLatin1String(
"MapInfo File" ) )
4000 writableDrivers << QStringLiteral(
"MapInfo MIF" );
4002 else if ( drvName == QLatin1String(
"SQLite" ) )
4009 QString option = QStringLiteral(
"SPATIALITE=YES" );
4010 char *options[2] = { CPLStrdup( option.toLocal8Bit().constData() ),
nullptr };
4011 OGRSFDriverH poDriver;
4013 poDriver = OGRGetDriverByName( drvName.toLocal8Bit().constData() );
4016 gdal::ogr_datasource_unique_ptr ds( OGR_Dr_CreateDataSource( poDriver, QStringLiteral(
"/vsimem/spatialitetest.sqlite" ).toUtf8().constData(), options ) );
4019 writableDrivers << QStringLiteral(
"SpatiaLite" );
4020 OGR_Dr_DeleteDataSource( poDriver, QStringLiteral(
"/vsimem/spatialitetest.sqlite" ).toUtf8().constData() );
4023 CPLFree( options[0] );
4025 writableDrivers << drvName;
4030 results.reserve( writableDrivers.count() );
4031 for (
const QString &drvName : std::as_const( writableDrivers ) )
4045 if ( options & SortRecommended )
4047 if ( a.driverName == QLatin1String(
"GPKG" ) )
4049 else if ( b.driverName == QLatin1String(
"GPKG" ) )
4051 else if ( a.driverName == QLatin1String(
"ESRI Shapefile" ) )
4053 else if ( b.driverName == QLatin1String(
"ESRI Shapefile" ) )
4057 return a.
longName.toLower().localeAwareCompare( b.
longName.toLower() ) < 0;
4064 QString ext = extension.trimmed();
4065 if ( ext.isEmpty() )
4068 if ( ext.startsWith(
'.' ) )
4072 int const drvCount = GDALGetDriverCount();
4074 for (
int i = 0; i < drvCount; ++i )
4076 GDALDriverH drv = GDALGetDriver( i );
4082 QString drvName = GDALGetDriverShortName( drv );
4083 QStringList driverExtensions = QString( GDALGetMetadataItem( drv, GDAL_DMD_EXTENSIONS,
nullptr ) ).split(
' ' );
4085 const auto constDriverExtensions = driverExtensions;
4086 for (
const QString &
driver : constDriverExtensions )
4088 if (
driver.compare( ext, Qt::CaseInsensitive ) == 0 )
4099 QString filterString;
4103 if ( !filterString.isEmpty() )
4104 filterString += QLatin1String(
";;" );
4106 filterString += details.filterString;
4108 return filterString;
4117 return QStringLiteral(
"%1 (%2 %3)" ).arg( metadata.
trLongName,
4118 metadata.
glob.toLower(),
4119 metadata.
glob.toUpper() );
4124 if ( codecName == QLatin1String(
"System" ) )
4125 return QStringLiteral(
"LDID/0" );
4127 const thread_local QRegularExpression re( QRegularExpression::anchoredPattern( QString(
"(CP|windows-|ISO[ -])(.+)" ) ), QRegularExpression::CaseInsensitiveOption );
4128 const QRegularExpressionMatch match = re.match( codecName );
4129 if ( match.hasMatch() )
4131 QString
c = match.captured( 2 ).remove(
'-' );
4133 ( void )
c.toInt( &isNumber );
4161 OGRStyleTableH ogrStyleTable = OGR_STBL_Create();
4162 OGRStyleMgrH styleManager = OGR_SM_Create( ogrStyleTable );
4165 int nTotalLevels = 0;
4167 QgsSymbolList::iterator symbolIt = symbolList.begin();
4168 for ( ; symbolIt != symbolList.end(); ++symbolIt )
4170 double mmsf = mmScaleFactor(
mSymbologyScale, ( *symbolIt )->outputUnit(), mapUnits );
4171 double musf = mapUnitScaleFactor(
mSymbologyScale, ( *symbolIt )->outputUnit(), mapUnits );
4173 int nLevels = ( *symbolIt )->symbolLayerCount();
4174 for (
int i = 0; i < nLevels; ++i )
4176 mSymbolLayerTable.insert( ( *symbolIt )->symbolLayer( i ), QString::number( nTotalLevels ) );
4177 OGR_SM_AddStyle( styleManager, QString::number( nTotalLevels ).toLocal8Bit(),
4178 ( *symbolIt )->symbolLayer( i )->ogrFeatureStyle( mmsf, musf ).toLocal8Bit() );
4182 OGR_DS_SetStyleTableDirectly( ds, ogrStyleTable );
4188 if ( !details.renderer )
4193 QHash< QgsSymbol *, QList<QgsFeature> > features;
4202 startRender( details.renderer.get(), details.sourceFields );
4222 QString msg = QObject::tr(
"Failed to transform, writing stopped. (Exception: %1)" )
4233 featureSymbol = mRenderer->symbolForFeature( fet, mRenderContext );
4234 if ( !featureSymbol )
4239 QHash< QgsSymbol *, QList<QgsFeature> >::iterator it = features.find( featureSymbol );
4240 if ( it == features.end() )
4242 it = features.insert( featureSymbol, QList<QgsFeature>() );
4244 it.value().append( fet );
4249 QgsSymbolList symbols = mRenderer->symbols( mRenderContext );
4250 for (
int i = 0; i < symbols.count(); i++ )
4256 if ( level < 0 || level >= 1000 )
4259 while ( level >= levels.count() )
4261 levels[level].append( item );
4266 int nTotalFeatures = 0;
4269 for (
int l = 0; l < levels.count(); l++ )
4272 for (
int i = 0; i < level.count(); i++ )
4275 QHash< QgsSymbol *, QList<QgsFeature> >::iterator levelIt = features.find( item.
symbol() );
4276 if ( levelIt == features.end() )
4282 double mmsf = mmScaleFactor(
mSymbologyScale, levelIt.key()->outputUnit(), mapUnits );
4283 double musf = mapUnitScaleFactor(
mSymbologyScale, levelIt.key()->outputUnit(), mapUnits );
4285 int llayer = item.
layer();
4286 QList<QgsFeature> &featureList = levelIt.value();
4287 QList<QgsFeature>::iterator featureIt = featureList.begin();
4288 for ( ; featureIt != featureList.end(); ++featureIt )
4298 QString styleString = levelIt.key()->symbolLayer( llayer )->ogrFeatureStyle( mmsf, musf );
4299 if ( !styleString.isEmpty() )
4301 OGR_F_SetStyleString( ogrFeature.get(), styleString.toLocal8Bit().constData() );
4302 if ( !writeFeature(
mLayer, ogrFeature.get() ) )
4315 *
errorMessage += QObject::tr(
"\nOnly %1 of %2 features written." ).arg( nTotalFeatures - nErrors ).arg( nTotalFeatures );
4332 return 1000 / scale;
4349 return scale / 1000;
4357 mRenderer = createSymbologyRenderer( sourceRenderer );
4363 mRenderer->startRender( mRenderContext, fields );
4366void QgsVectorFileWriter::stopRender()
4373 mRenderer->stopRender( mRenderContext );
4376std::unique_ptr<QgsFeatureRenderer> QgsVectorFileWriter::createSymbologyRenderer(
QgsFeatureRenderer *sourceRenderer )
const
4389 if ( !sourceRenderer )
4394 return std::unique_ptr< QgsFeatureRenderer >( sourceRenderer->
clone() );
4401 const QSet<QString> rendererAttributes = renderer->
usedAttributes( context );
4402 for (
const QString &attr : rendererAttributes )
4407 attList.append( index );
4413QStringList QgsVectorFileWriter::concatenateOptions(
const QMap<QString, QgsVectorFileWriter::Option *> &options )
4416 QMap<QString, QgsVectorFileWriter::Option *>::ConstIterator it;
4418 for ( it = options.constBegin(); it != options.constEnd(); ++it )
4421 switch ( option->
type )
4428 list.append( QStringLiteral(
"%1=%2" ).arg( it.key() ).arg( opt->
defaultValue ) );
4438 list.append( QStringLiteral(
"%1=%2" ).arg( it.key(), opt->
defaultValue ) );
4448 list.append( QStringLiteral(
"%1=%2" ).arg( it.key(), opt->
defaultValue ) );
4455 if ( opt && !opt->
mValue.isEmpty() )
4457 list.append( QStringLiteral(
"%1=%2" ).arg( it.key(), opt->
mValue ) );
4468 OGRSFDriverH hDriver =
nullptr;
4471 return QgsVectorFileWriter::EditionCapabilities();
4472 QString drvName = OGR_Dr_GetName( hDriver );
4473 QgsVectorFileWriter::EditionCapabilities caps = QgsVectorFileWriter::EditionCapabilities();
4474 if ( OGR_DS_TestCapability( hDS.get(), ODsCCreateLayer ) )
4479 if ( !( drvName == QLatin1String(
"ESRI Shapefile" ) && QFile::exists( datasetName ) ) )
4482 if ( OGR_DS_TestCapability( hDS.get(), ODsCDeleteLayer ) )
4486 int layer_count = OGR_DS_GetLayerCount( hDS.get() );
4489 OGRLayerH hLayer = OGR_DS_GetLayer( hDS.get(), 0 );
4492 if ( OGR_L_TestCapability( hLayer, OLCSequentialWrite ) )
4495 if ( OGR_L_TestCapability( hLayer, OLCCreateField ) )
4506 const QString &layerNameIn )
4508 OGRSFDriverH hDriver =
nullptr;
4513 QString layerName( layerNameIn );
4514 if ( layerName.isEmpty() )
4515 layerName = QFileInfo( datasetName ).baseName();
4517 return OGR_DS_GetLayerByName( hDS.get(), layerName.toUtf8().constData() );
4522 const QString &layerName,
4526 OGRSFDriverH hDriver =
nullptr;
4530 OGRLayerH hLayer = OGR_DS_GetLayerByName( hDS.get(), layerName.toUtf8().constData() );
4536 OGRFeatureDefnH defn = OGR_L_GetLayerDefn( hLayer );
4537 const auto constAttributes = attributes;
4538 for (
int idx : constAttributes )
4541 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.
RenderUnit
Rendering size units.
@ Millimeters
Millimeters.
WkbType
The WKB type describes the number of dimensions a geometry has.
@ MultiPolygon25D
MultiPolygon25D.
@ GeometryCollectionZ
GeometryCollectionZ.
@ MultiLineString
MultiLineString.
@ MultiPolygonZ
MultiPolygonZ.
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)
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.
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 (since QGIS 3.30)
static void registerOgrDrivers()
Register OGR drivers ensuring this only happens once.
This class 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.
Custom exception class for Coordinate Reference System related exceptions.
virtual QString dataSourceUri(bool expandAuthConfig=false) const
Gets the data source specification.
Class for storing the component parts of a RDBMS data source URI (e.g.
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
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.
This class 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.
@ 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.
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.
@ 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.
QVariant::Type subType() const
If the field is a collection, gets its element's type.
QgsFieldConstraints constraints
Container of fields for a vector layer.
int count() const
Returns number of items.
int size() const
Returns number of items.
void clear()
Removes all fields.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
static QStringList multiLayerFileExtensions()
Returns a list of file extensions which potentially contain multiple layers representing GDAL raster ...
A geometry is the spatial representation of a feature.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
QgsAbstractGeometry * get()
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine representing the specified geometry.
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
QByteArray asWkb(QgsAbstractGeometry::WkbFlags flags=QgsAbstractGeometry::WkbFlags()) const
Export the geometry to WKB.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
static void warning(const QString &msg)
Goes to qWarning.
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)
Adds a message to the log instance (and creates it if necessary).
Custom exception class which is raised when an operation is not supported.
static OGRSpatialReferenceH crsToOGRSpatialReference(const QgsCoordinateReferenceSystem &crs)
Returns a OGRSpatialReferenceH corresponding to the specified crs object.
static 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.
bool saveLayerMetadata(const QString &providerKey, const QString &uri, const QgsLayerMetadata &metadata, QString &errorMessage)
Saves metadata to the layer corresponding to the specified uri.
The QgsReadWriteLocker class is a convenience class that simplifies locking and unlocking QReadWriteL...
void changeMode(Mode mode)
Change the mode of the lock to mode.
A rectangle specified with double values.
bool isNull() const
Test if the rectangle is null (holding no spatial information).
Contains information about the context of a rendering operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
void setRendererScale(double scale)
Sets the renderer map scale.
This class is a composition of two QSettings instances:
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
int renderingPass() const
Specifies the rendering pass in which this symbol layer should be rendered.
int layer() const
The layer of this symbol level.
QgsSymbol * symbol() const
The symbol of this symbol level.
Abstract base class for all rendered symbols.
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)
Returns true if the specified variant should be considered a NULL value.
Interface to convert raw field values to their user-friendly value.
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.
QgsVectorFileWriter::OptionType type
Options to pass to writeAsVectorFormat()
QString fileEncoding
Encoding to use.
bool forceMulti
Sets to true to force creation of multi* geometries.
FieldNameSource fieldNameSource
Source for exported field names.
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.
SaveVectorOptions()
Constructor.
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.
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.
bool skipAttributeCreation
Only write geometries.
double symbologyScale
Scale of symbology.
QStringList datasourceOptions
List of OGR data source creation options.
QgsFeedback * feedback
Optional feedback object allowing cancellation of layer save.
A convenience class for writing vector layers to disk based formats (e.g.
static QgsVectorFileWriter::WriterError writeAsVectorFormatV3(QgsVectorLayer *layer, const QString &fileName, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QString *errorMessage=nullptr, QString *newFilename=nullptr, QString *newLayer=nullptr)
Writes a layer out to a vector file.
Qgis::FeatureSymbologyExport mSymbologyExport
QString lastError() const override
Returns the most recent error encountered by the sink, e.g.
@ CanAddNewFieldsToExistingLayer
Flag to indicate that new fields can be added to an existing layer. Imply CanAppendToExistingLayer.
@ CanAppendToExistingLayer
Flag to indicate that new features can be added to an existing layer.
@ CanAddNewLayer
Flag to indicate that a new layer can be added to the dataset.
@ CanDeleteLayer
Flag to indicate that an existing layer can be deleted.
static QgsVectorFileWriter::EditionCapabilities editionCapabilities(const QString &datasetName)
Returns edition capabilities for an existing dataset name.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a single feature to the sink.
static bool supportsFeatureStyles(const QString &driverName)
Returns true if the specified driverName supports feature styles.
Qgis::WkbType mWkbType
Geometry type which is being used.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
double mSymbologyScale
Scale for symbology export (e.g. for symbols units in map units)
QMap< int, int > mAttrIdxToOgrIdx
Map attribute indizes to OGR field indexes.
@ 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
~QgsVectorFileWriter() override
Close opened shapefile for writing.
static bool targetLayerExists(const QString &datasetName, const QString &layerName)
Returns whether the target layer already exists.
double symbologyScale() const
Returns the reference scale for output.
static QStringList defaultLayerOptions(const QString &driverName)
Returns a list of the default layer options for a specified driver.
static QString driverForExtension(const QString &extension)
Returns the OGR driver name for a specified file extension.
Qgis::VectorFileWriterCapabilities capabilities() const
Returns the capabilities supported by the writer.
static QList< QgsVectorFileWriter::FilterFormatDetails > supportedFiltersAndFormats(VectorFormatOptions options=SortRecommended)
Returns a list or pairs, with format filter string as first element and OGR format key as second elem...
OGRSpatialReferenceH mOgrRef
static bool driverMetadata(const QString &driverName, MetaData &driverMetadata)
static QgsVectorFileWriter * create(const QString &fileName, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &srs, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QString *newFilename=nullptr, QString *newLayer=nullptr)
Create a new vector file writer.
QString driver() const
Returns the GDAL (short) driver name associated with the output file.
static bool deleteShapeFile(const QString &fileName)
Delete a shapefile (and its accompanying shx / dbf / prj / qix / qpj / cpg / sbn / sbx / idm / ind)
Q_DECL_DEPRECATED QgsVectorFileWriter(const QString &vectorFileName, const QString &fileEncoding, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &srs=QgsCoordinateReferenceSystem(), const QString &driverName="GPKG", const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), QString *newFilename=nullptr, Qgis::FeatureSymbologyExport symbologyExport=Qgis::FeatureSymbologyExport::NoSymbology, QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QString *newLayer=nullptr, const QgsCoordinateTransformContext &transformContext=QgsCoordinateTransformContext(), FieldNameSource fieldNameSource=Original)
Create a new vector file writer.
static Q_DECL_DEPRECATED QgsVectorFileWriter::WriterError writeAsVectorFormat(QgsVectorLayer *layer, const QString &fileName, const QString &fileEncoding, const QgsCoordinateReferenceSystem &destCRS=QgsCoordinateReferenceSystem(), const QString &driverName="GPKG", bool onlySelected=false, QString *errorMessage=nullptr, const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), bool skipAttributeCreation=false, QString *newFilename=nullptr, Qgis::FeatureSymbologyExport symbologyExport=Qgis::FeatureSymbologyExport::NoSymbology, double symbologyScale=1.0, const QgsRectangle *filterExtent=nullptr, Qgis::WkbType overrideGeometryType=Qgis::WkbType::Unknown, bool forceMulti=false, bool includeZ=false, const QgsAttributeList &attributes=QgsAttributeList(), QgsVectorFileWriter::FieldValueConverter *fieldValueConverter=nullptr, QString *newLayer=nullptr)
Write contents of vector layer to an (OGR supported) vector format.
static QString filterForDriver(const QString &driverName)
Creates a filter for an OGR driver key.
QgsVectorFileWriter::WriterError hasError() const
Checks whether there were any errors in constructor.
@ SupportsMultipleLayers
Filter to only formats which support multiple layers (since QGIS 3.32)
@ 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.
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".
static QString convertCodecNameForEncodingOption(const QString &codecName)
Converts codec name to string passed to ENCODING layer creation option of OGR Shapefile.
FieldValueConverter * mFieldValueConverter
Field value converter.
QString errorMessage() const
Retrieves error message.
void setSymbologyScale(double scale)
Set reference scale for output.
static OGRwkbGeometryType ogrTypeFromWkbType(Qgis::WkbType type)
Gets the ogr geometry type from an internal QGIS wkb type enum.
QMap< QgsSymbolLayer *, QString > mSymbolLayerTable
static QString fileFilterString(VectorFormatOptions options=SortRecommended)
Returns filter string that can be used for dialogs.
ActionOnExistingFile
Combination of CanAddNewLayer, CanAppendToExistingLayer, CanAddNewFieldsToExistingLayer or CanDeleteL...
@ 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 data sets.
long long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
Q_INVOKABLE const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
QString storageType() const
Returns the permanent storage type for this layer as a friendly name.
Q_INVOKABLE Qgis::WkbType wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
QgsFeatureRenderer * renderer()
Returns the feature renderer used for rendering the features in the layer in 2D map views.
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider, it may be nullptr.
void minimumAndMaximumValue(int index, QVariant &minimum, QVariant &maximum) const
Calculates both the minimum and maximum value for an attribute column.
static Qgis::WkbType to25D(Qgis::WkbType type)
Will convert the 25D version of the flat type if supported or Unknown if not supported.
static bool isMultiType(Qgis::WkbType type)
Returns true if the WKB type is a multi type.
static Qgis::WkbType addZ(Qgis::WkbType type)
Adds the z dimension to a WKB type and returns the new type.
static Qgis::WkbType singleType(Qgis::WkbType type)
Returns the single type for a WKB type.
static bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
static 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.
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.