LCOV - code coverage report
Current view: top level - apps - ogr2ogr_lib.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 3249 4030 80.6 %
Date: 2026-03-26 23:25:44 Functions: 114 151 75.5 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  OpenGIS Simple Features Reference Implementation
       4             :  * Purpose:  Simple client for translating between formats.
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 1999, Frank Warmerdam
       9             :  * Copyright (c) 2008-2015, Even Rouault <even dot rouault at spatialys.com>
      10             :  * Copyright (c) 2015, Faza Mahamood
      11             :  *
      12             :  * SPDX-License-Identifier: MIT
      13             :  ****************************************************************************/
      14             : 
      15             : #include "cpl_port.h"
      16             : #include "gdal_utils.h"
      17             : #include "gdal_utils_priv.h"
      18             : #include "gdalargumentparser.h"
      19             : 
      20             : #include <cassert>
      21             : #include <climits>
      22             : #include <cstdio>
      23             : #include <cstdlib>
      24             : #include <cstring>
      25             : 
      26             : #include <algorithm>
      27             : #include <atomic>
      28             : #include <future>
      29             : #include <limits>
      30             : #include <map>
      31             : #include <memory>
      32             : #include <mutex>
      33             : #include <set>
      34             : #include <unordered_set>
      35             : #include <string>
      36             : #include <utility>
      37             : #include <vector>
      38             : 
      39             : #include "commonutils.h"
      40             : #include "cpl_conv.h"
      41             : #include "cpl_error.h"
      42             : #include "cpl_multiproc.h"
      43             : #include "cpl_progress.h"
      44             : #include "cpl_string.h"
      45             : #include "cpl_time.h"
      46             : #include "cpl_vsi.h"
      47             : #include "gdal.h"
      48             : #include "gdal_alg.h"
      49             : #include "gdal_alg_priv.h"
      50             : #include "gdal_priv.h"
      51             : #include "gdal_thread_pool.h"
      52             : #include "ogr_api.h"
      53             : #include "ogr_core.h"
      54             : #include "ogr_feature.h"
      55             : #include "ogr_featurestyle.h"
      56             : #include "ogr_geometry.h"
      57             : #include "ogr_p.h"
      58             : #include "ogr_recordbatch.h"
      59             : #include "ogr_spatialref.h"
      60             : #include "ogrlayerarrow.h"
      61             : #include "ogrlayerdecorator.h"
      62             : #include "ogrsf_frmts.h"
      63             : #include "ogr_wkb.h"
      64             : #include "ogrct_priv.h"
      65             : 
      66             : typedef enum
      67             : {
      68             :     GEOMOP_NONE,
      69             :     GEOMOP_SEGMENTIZE,
      70             :     GEOMOP_SIMPLIFY_PRESERVE_TOPOLOGY,
      71             : } GeomOperation;
      72             : 
      73             : typedef enum
      74             : {
      75             :     GTC_DEFAULT,
      76             :     GTC_PROMOTE_TO_MULTI,
      77             :     GTC_CONVERT_TO_LINEAR,
      78             :     GTC_CONVERT_TO_CURVE,
      79             :     GTC_PROMOTE_TO_MULTI_AND_CONVERT_TO_LINEAR,
      80             : } GeomTypeConversion;
      81             : 
      82             : #define GEOMTYPE_UNCHANGED -2
      83             : 
      84             : #define COORD_DIM_UNCHANGED -1
      85             : #define COORD_DIM_LAYER_DIM -2
      86             : #define COORD_DIM_XYM -3
      87             : 
      88             : #define TZ_OFFSET_INVALID INT_MIN
      89             : 
      90             : /************************************************************************/
      91             : /*                      GDALVectorTranslateOptions                      */
      92             : /************************************************************************/
      93             : 
      94             : /** Options for use with GDALVectorTranslate(). GDALVectorTranslateOptions* must
      95             :  * be allocated and freed with GDALVectorTranslateOptionsNew() and
      96             :  * GDALVectorTranslateOptionsFree() respectively.
      97             :  */
      98             : struct GDALVectorTranslateOptions
      99             : {
     100             :     // All arguments passed to GDALVectorTranslate() except the positional
     101             :     // ones (that is dataset names and layer names)
     102             :     CPLStringList aosArguments{};
     103             : 
     104             :     /*! continue after a failure, skipping the failed feature */
     105             :     bool bSkipFailures = false;
     106             : 
     107             :     /*! use layer level transaction. If set to FALSE, then it is interpreted as
     108             :      * dataset level transaction. */
     109             :     int nLayerTransaction = -1;
     110             : 
     111             :     /*! force the use of particular transaction type based on
     112             :      * GDALVectorTranslate::nLayerTransaction */
     113             :     bool bForceTransaction = false;
     114             : 
     115             :     /*! group nGroupTransactions features per transaction.
     116             :        Increase the value for better performance when writing into DBMS drivers
     117             :        that have transaction support. nGroupTransactions can be set to -1 to
     118             :        load the data into a single transaction */
     119             :     int nGroupTransactions = 100 * 1000;
     120             : 
     121             :     /*! If provided, only the feature with this feature id will be reported.
     122             :        Operates exclusive of the spatial or attribute queries. Note: if you want
     123             :        to select several features based on their feature id, you can also use
     124             :        the fact the 'fid' is a special field recognized by OGR SQL. So
     125             :        GDALVectorTranslateOptions::pszWHERE = "fid in (1,3,5)" would select
     126             :        features 1, 3 and 5. */
     127             :     GIntBig nFIDToFetch = OGRNullFID;
     128             : 
     129             :     /*! allow or suppress progress monitor and other non-error output */
     130             :     bool bQuiet = false;
     131             : 
     132             :     /*! output file format name */
     133             :     std::string osFormat{};
     134             : 
     135             :     /*! list of layers of the source dataset which needs to be selected */
     136             :     CPLStringList aosLayers{};
     137             : 
     138             :     /*! dataset creation option (format specific) */
     139             :     CPLStringList aosDSCO{};
     140             : 
     141             :     /*! layer creation option (format specific) */
     142             :     CPLStringList aosLCO{};
     143             : 
     144             :     /*! access modes */
     145             :     GDALVectorTranslateAccessMode eAccessMode = ACCESS_CREATION;
     146             : 
     147             :     /*! whether to use UpsertFeature() instead of CreateFeature() */
     148             :     bool bUpsert = false;
     149             : 
     150             :     /*! It has the effect of adding, to existing target layers, the new fields
     151             :        found in source layers. This option is useful when merging files that
     152             :        have non-strictly identical structures. This might not work for output
     153             :        formats that don't support adding fields to existing non-empty layers. */
     154             :     bool bAddMissingFields = false;
     155             : 
     156             :     /*! It must be set to true to trigger reprojection, otherwise only SRS
     157             :      * assignment is done. */
     158             :     bool bTransform = false;
     159             : 
     160             :     /*! output SRS. GDALVectorTranslateOptions::bTransform must be set to true
     161             :        to trigger reprojection, otherwise only SRS assignment is done. */
     162             :     std::string osOutputSRSDef{};
     163             : 
     164             :     /*! Coordinate epoch of source SRS */
     165             :     double dfSourceCoordinateEpoch = 0;
     166             : 
     167             :     /*! Coordinate epoch of output SRS */
     168             :     double dfOutputCoordinateEpoch = 0;
     169             : 
     170             :     /*! override source SRS */
     171             :     std::string osSourceSRSDef{};
     172             : 
     173             :     /*! PROJ pipeline */
     174             :     std::string osCTPipeline{};
     175             : 
     176             :     /*! Transform options. */
     177             :     CPLStringList aosCTOptions{};
     178             : 
     179             :     bool bNullifyOutputSRS = false;
     180             : 
     181             :     /*! If set to false, then field name matching between source and existing
     182             :        target layer is done in a more relaxed way if the target driver has an
     183             :        implementation for it. */
     184             :     bool bExactFieldNameMatch = true;
     185             : 
     186             :     /*! an alternate name to the new layer */
     187             :     std::string osNewLayerName{};
     188             : 
     189             :     /*! attribute query (like SQL WHERE) */
     190             :     std::string osWHERE{};
     191             : 
     192             :     /*! name of the geometry field on which the spatial filter operates on. */
     193             :     std::string osGeomField{};
     194             : 
     195             :     /*! whether osGeomField is set (useful for empty strings) */
     196             :     bool bGeomFieldSet = false;
     197             : 
     198             :     /*! whether -select has been specified. This is of course true when
     199             :      * !aosSelFields.empty(), but this can also be set when an empty string
     200             :      * has been to disable fields. */
     201             :     bool bSelFieldsSet = false;
     202             : 
     203             :     /*! list of fields from input layer to copy to the new layer.
     204             :      * Geometry fields can also be specified in the list. */
     205             :     CPLStringList aosSelFields{};
     206             : 
     207             :     /*! SQL statement to execute. The resulting table/layer will be saved to the
     208             :      * output. */
     209             :     std::string osSQLStatement{};
     210             : 
     211             :     /*! SQL dialect. In some cases can be used to use (unoptimized) OGR SQL
     212             :        instead of the native SQL of an RDBMS by using "OGRSQL". The "SQLITE"
     213             :        dialect can also be used with any datasource. */
     214             :     std::string osDialect{};
     215             : 
     216             :     /*! the geometry type for the created layer */
     217             :     int eGType = GEOMTYPE_UNCHANGED;
     218             : 
     219             :     GeomTypeConversion eGeomTypeConversion = GTC_DEFAULT;
     220             : 
     221             :     /*! Geometric operation to perform */
     222             :     GeomOperation eGeomOp = GEOMOP_NONE;
     223             : 
     224             :     /*! the parameter to geometric operation */
     225             :     double dfGeomOpParam = 0;
     226             : 
     227             :     /*! Whether to run MakeValid */
     228             :     bool bMakeValid = false;
     229             : 
     230             :     /*! Whether to run OGRGeometry::IsValid */
     231             :     bool bSkipInvalidGeom = false;
     232             : 
     233             :     /*! list of field types to convert to a field of type string in the
     234             :        destination layer. Valid types are: Integer, Integer64, Real, String,
     235             :        Date, Time, DateTime, Binary, IntegerList, Integer64List, RealList,
     236             :        StringList. Special value "All" can be used to convert all fields to
     237             :        strings. This is an alternate way to using the CAST operator of OGR SQL,
     238             :        that may avoid typing a long SQL query. Note that this does not influence
     239             :        the field types used by the source driver, and is only an afterwards
     240             :         conversion. */
     241             :     CPLStringList aosFieldTypesToString{};
     242             : 
     243             :     /*! list of field types and the field type after conversion in the
     244             :        destination layer.
     245             :         ("srctype1=dsttype1","srctype2=dsttype2",...).
     246             :         Valid types are : Integer, Integer64, Real, String, Date, Time,
     247             :        DateTime, Binary, IntegerList, Integer64List, RealList, StringList. Types
     248             :        can also include subtype between parenthesis, such as Integer(Boolean),
     249             :        Real(Float32), ... Special value "All" can be used to convert all fields
     250             :        to another type. This is an alternate way to using the CAST operator of
     251             :        OGR SQL, that may avoid typing a long SQL query. This is a generalization
     252             :        of GDALVectorTranslateOptions::papszFieldTypeToString. Note that this
     253             :        does not influence the field types used by the source driver, and is only
     254             :        an afterwards conversion. */
     255             :     CPLStringList aosMapFieldType{};
     256             : 
     257             :     /*! set field width and precision to 0 */
     258             :     bool bUnsetFieldWidth = false;
     259             : 
     260             :     /*! display progress on terminal. Only works if input layers have the "fast
     261             :     feature count" capability */
     262             :     bool bDisplayProgress = false;
     263             : 
     264             :     /*! split geometries crossing the dateline meridian */
     265             :     bool bWrapDateline = false;
     266             : 
     267             :     /*! offset from dateline in degrees (default long. = +/- 10deg, geometries
     268             :     within 170deg to -170deg will be split) */
     269             :     double dfDateLineOffset = 10.0;
     270             : 
     271             :     /*! clip geometries when it is set to true */
     272             :     bool bClipSrc = false;
     273             : 
     274             :     std::shared_ptr<OGRGeometry> poClipSrc{};
     275             : 
     276             :     /*! clip datasource */
     277             :     std::string osClipSrcDS{};
     278             : 
     279             :     /*! select desired geometries using an SQL query */
     280             :     std::string osClipSrcSQL{};
     281             : 
     282             :     /*! selected named layer from the source clip datasource */
     283             :     std::string osClipSrcLayer{};
     284             : 
     285             :     /*! restrict desired geometries based on attribute query */
     286             :     std::string osClipSrcWhere{};
     287             : 
     288             :     std::shared_ptr<OGRGeometry> poClipDst{};
     289             : 
     290             :     /*! destination clip datasource */
     291             :     std::string osClipDstDS{};
     292             : 
     293             :     /*! select desired geometries using an SQL query */
     294             :     std::string osClipDstSQL{};
     295             : 
     296             :     /*! selected named layer from the destination clip datasource */
     297             :     std::string osClipDstLayer{};
     298             : 
     299             :     /*! restrict desired geometries based on attribute query */
     300             :     std::string osClipDstWhere{};
     301             : 
     302             :     /*! split fields of type StringList, RealList or IntegerList into as many
     303             :        fields of type String, Real or Integer as necessary. */
     304             :     bool bSplitListFields = false;
     305             : 
     306             :     /*! limit the number of subfields created for each split field. */
     307             :     int nMaxSplitListSubFields = -1;
     308             : 
     309             :     /*! produce one feature for each geometry in any kind of geometry collection
     310             :        in the source file */
     311             :     bool bExplodeCollections = false;
     312             : 
     313             :     /*! uses the specified field to fill the Z coordinates of geometries */
     314             :     std::string osZField{};
     315             : 
     316             :     /*! the list of field indexes to be copied from the source to the
     317             :        destination. The (n)th value specified in the list is the index of the
     318             :        field in the target layer definition in which the n(th) field of the
     319             :        source layer must be copied. Index count starts at zero. There must be
     320             :         exactly as many values in the list as the count of the fields in the
     321             :        source layer. We can use the "identity" option to specify that the fields
     322             :        should be transferred by using the same order. This option should be used
     323             :        along with the GDALVectorTranslateOptions::eAccessMode = ACCESS_APPEND
     324             :        option. */
     325             :     CPLStringList aosFieldMap{};
     326             : 
     327             :     /*! force the coordinate dimension to nCoordDim (valid values are 2 or 3).
     328             :        This affects both the layer geometry type, and feature geometries. */
     329             :     int nCoordDim = COORD_DIM_UNCHANGED;
     330             : 
     331             :     /*! destination dataset open option (format specific), only valid in update
     332             :      * mode */
     333             :     CPLStringList aosDestOpenOptions{};
     334             : 
     335             :     /*! If set to true, does not propagate not-nullable constraints to target
     336             :        layer if they exist in source layer */
     337             :     bool bForceNullable = false;
     338             : 
     339             :     /*! If set to true, for each field with a coded field domains, create a
     340             :        field that contains the description of the coded value. */
     341             :     bool bResolveDomains = false;
     342             : 
     343             :     /*! If set to true, empty string values will be treated as null */
     344             :     bool bEmptyStrAsNull = false;
     345             : 
     346             :     /*! If set to true, does not propagate default field values to target layer
     347             :        if they exist in source layer */
     348             :     bool bUnsetDefault = false;
     349             : 
     350             :     /*! to prevent the new default behavior that consists in, if the output
     351             :        driver has a FID layer creation option and we are not in append mode, to
     352             :        preserve the name of the source FID column and source feature IDs */
     353             :     bool bUnsetFid = false;
     354             : 
     355             :     /*! use the FID of the source features instead of letting the output driver
     356             :        to automatically assign a new one. If not in append mode, this behavior
     357             :        becomes the default if the output driver has a FID layer creation option.
     358             :        In which case the name of the source FID column will be used and source
     359             :        feature IDs will be attempted to be preserved. This behavior can be
     360             :         disabled by option GDALVectorTranslateOptions::bUnsetFid */
     361             :     bool bPreserveFID = false;
     362             : 
     363             :     /*! set it to false to disable copying of metadata from source dataset and
     364             :        layers into target dataset and layers, when supported by output driver.
     365             :      */
     366             :     bool bCopyMD = true;
     367             : 
     368             :     /*! list of metadata key and value to set on the output dataset, when
     369             :        supported by output driver.
     370             :         ("META-TAG1=VALUE1","META-TAG2=VALUE2") */
     371             :     CPLStringList aosMetadataOptions{};
     372             : 
     373             :     /*! override spatial filter SRS */
     374             :     std::string osSpatSRSDef{};
     375             : 
     376             :     /*! list of ground control points to be added */
     377             :     std::vector<gdal::GCP> asGCPs{};
     378             : 
     379             :     /*! order of polynomial used for warping (1 to 3). The default is to select
     380             :        a polynomial order based on the number of GCPs */
     381             :     int nTransformOrder = 0;
     382             : 
     383             :     /*! spatial query extents, in the SRS of the source layer(s) (or the one
     384             :        specified with GDALVectorTranslateOptions::pszSpatSRSDef). Only features
     385             :        whose geometry intersects the extents will be selected. The geometries
     386             :        will not be clipped unless GDALVectorTranslateOptions::bClipSrc is true.
     387             :      */
     388             :     std::shared_ptr<OGRGeometry> poSpatialFilter{};
     389             : 
     390             :     /*! the progress function to use */
     391             :     GDALProgressFunc pfnProgress = nullptr;
     392             : 
     393             :     /*! pointer to the progress data variable */
     394             :     void *pProgressData = nullptr;
     395             : 
     396             :     /*! Whether layer and feature native data must be transferred. */
     397             :     bool bNativeData = true;
     398             : 
     399             :     /*! Maximum number of features, or -1 if no limit. */
     400             :     GIntBig nLimit = -1;
     401             : 
     402             :     /*! Wished offset w.r.t UTC of dateTime */
     403             :     int nTZOffsetInSec = TZ_OFFSET_INVALID;
     404             : 
     405             :     /*! Geometry X,Y coordinate resolution */
     406             :     double dfXYRes = OGRGeomCoordinatePrecision::UNKNOWN;
     407             : 
     408             :     /*! Unit of dXYRes. empty string, "m", "mm" or "deg" */
     409             :     std::string osXYResUnit{};
     410             : 
     411             :     /*! Geometry Z coordinate resolution */
     412             :     double dfZRes = OGRGeomCoordinatePrecision::UNKNOWN;
     413             : 
     414             :     /*! Unit of dfZRes. empty string, "m" or "mm" */
     415             :     std::string osZResUnit{};
     416             : 
     417             :     /*! Geometry M coordinate resolution */
     418             :     double dfMRes = OGRGeomCoordinatePrecision::UNKNOWN;
     419             : 
     420             :     /*! Whether to unset geometry coordinate precision */
     421             :     bool bUnsetCoordPrecision = false;
     422             : 
     423             :     /*! set to true to prevent overwriting existing dataset */
     424             :     bool bNoOverwrite = false;
     425             : 
     426             :     /*! set to true to customize error messages when called from "new" (GDAL 3.11) CLI or Algorithm API */
     427             :     bool bInvokedFromGdalAlgorithm = false;
     428             : };
     429             : 
     430             : struct TargetLayerInfo
     431             : {
     432             :     OGRLayer *m_poSrcLayer = nullptr;
     433             :     GIntBig m_nFeaturesRead = 0;
     434             :     bool m_bPerFeatureCT = 0;
     435             :     OGRLayer *m_poDstLayer = nullptr;
     436             :     bool m_bUseWriteArrowBatch = false;
     437             : 
     438             :     struct ReprojectionInfo
     439             :     {
     440             :         std::unique_ptr<OGRCoordinateTransformation> m_poCT{};
     441             :         CPLStringList m_aosTransformOptions{};
     442             :         bool m_bCanInvalidateValidity = true;
     443             :         bool m_bWarnAboutDifferentCoordinateOperations = false;
     444             :         double m_dfLeftX = std::numeric_limits<double>::max();
     445             :         double m_dfLeftY = 0;
     446             :         double m_dfLeftZ = 0;
     447             :         double m_dfRightX = -std::numeric_limits<double>::max();
     448             :         double m_dfRightY = 0;
     449             :         double m_dfRightZ = 0;
     450             :         double m_dfBottomX = 0;
     451             :         double m_dfBottomY = std::numeric_limits<double>::max();
     452             :         double m_dfBottomZ = 0;
     453             :         double m_dfTopX = 0;
     454             :         double m_dfTopY = -std::numeric_limits<double>::max();
     455             :         double m_dfTopZ = 0;
     456             : 
     457       13076 :         void UpdateExtremePoints(double dfX, double dfY, double dfZ)
     458             :         {
     459       13076 :             if (dfX < m_dfLeftX)
     460             :             {
     461         237 :                 m_dfLeftX = dfX;
     462         237 :                 m_dfLeftY = dfY;
     463         237 :                 m_dfLeftZ = dfZ;
     464             :             }
     465       13076 :             if (dfX > m_dfRightX)
     466             :             {
     467       10373 :                 m_dfRightX = dfX;
     468       10373 :                 m_dfRightY = dfY;
     469       10373 :                 m_dfRightZ = dfZ;
     470             :             }
     471       13076 :             if (dfY < m_dfBottomY)
     472             :             {
     473         411 :                 m_dfBottomX = dfX;
     474         411 :                 m_dfBottomY = dfY;
     475         411 :                 m_dfBottomZ = dfZ;
     476             :             }
     477       13076 :             if (dfY > m_dfTopY)
     478             :             {
     479       10219 :                 m_dfTopX = dfX;
     480       10219 :                 m_dfTopY = dfY;
     481       10219 :                 m_dfTopZ = 0;
     482             :             }
     483       13076 :         }
     484             :     };
     485             : 
     486             :     std::vector<ReprojectionInfo> m_aoReprojectionInfo{};
     487             : 
     488             :     std::vector<int> m_anMap{};
     489             : 
     490             :     struct ResolvedInfo
     491             :     {
     492             :         int nSrcField;
     493             :         const OGRFieldDomain *poDomain;
     494             :     };
     495             : 
     496             :     std::map<int, ResolvedInfo> m_oMapResolved{};
     497             :     std::map<const OGRFieldDomain *, std::map<std::string, std::string>>
     498             :         m_oMapDomainToKV{};
     499             :     int m_iSrcZField = -1;
     500             :     int m_iSrcFIDField = -1;
     501             :     int m_iRequestedSrcGeomField = -1;
     502             :     bool m_bPreserveFID = false;
     503             :     const char *m_pszCTPipeline = nullptr;
     504             :     CPLStringList m_aosCTOptions{};
     505             :     bool m_bCanAvoidSetFrom = false;
     506             :     const char *m_pszSpatSRSDef = nullptr;
     507             :     OGRGeometryH m_hSpatialFilter = nullptr;
     508             :     const char *m_pszGeomField = nullptr;
     509             :     std::vector<int> m_anDateTimeFieldIdx{};
     510             :     bool m_bSupportCurves = false;
     511             :     bool m_bSupportZ = false;
     512             :     bool m_bSupportM = false;
     513             :     bool m_bHasWarnedAboutCurves = false;
     514             :     bool m_bHasWarnedAboutZ = false;
     515             :     bool m_bHasWarnedAboutM = false;
     516             :     OGRArrowArrayStream m_sArrowArrayStream{};
     517             : 
     518             :     void CheckSameCoordinateOperation() const;
     519             : };
     520             : 
     521             : struct AssociatedLayers
     522             : {
     523             :     OGRLayer *poSrcLayer = nullptr;
     524             :     std::unique_ptr<TargetLayerInfo> psInfo{};
     525             : };
     526             : 
     527             : class SetupTargetLayer
     528             : {
     529             :   public:
     530             :     GDALDataset *m_poSrcDS = nullptr;
     531             :     GDALDataset *m_poDstDS = nullptr;
     532             :     CSLConstList m_papszLCO = nullptr;
     533             :     const OGRSpatialReference *m_poUserSourceSRS = nullptr;
     534             :     const OGRSpatialReference *m_poOutputSRS = nullptr;
     535             :     bool m_bTransform = false;
     536             :     bool m_bNullifyOutputSRS = false;
     537             :     bool m_bSelFieldsSet = false;
     538             :     CSLConstList m_papszSelFields = nullptr;
     539             :     bool m_bAppend = false;
     540             :     bool m_bAddMissingFields = false;
     541             :     int m_eGType = 0;
     542             :     GeomTypeConversion m_eGeomTypeConversion = GTC_DEFAULT;
     543             :     int m_nCoordDim = 0;
     544             :     bool m_bOverwrite = false;
     545             :     CSLConstList m_papszFieldTypesToString = nullptr;
     546             :     CSLConstList m_papszMapFieldType = nullptr;
     547             :     bool m_bUnsetFieldWidth = false;
     548             :     bool m_bExplodeCollections = false;
     549             :     const char *m_pszZField = nullptr;
     550             :     CSLConstList m_papszFieldMap = nullptr;
     551             :     const char *m_pszWHERE = nullptr;
     552             :     bool m_bExactFieldNameMatch = false;
     553             :     bool m_bQuiet = false;
     554             :     bool m_bForceNullable = false;
     555             :     bool m_bResolveDomains = false;
     556             :     bool m_bUnsetDefault = false;
     557             :     bool m_bUnsetFid = false;
     558             :     bool m_bPreserveFID = false;
     559             :     bool m_bCopyMD = false;
     560             :     bool m_bNativeData = false;
     561             :     bool m_bNewDataSource = false;
     562             :     const char *m_pszCTPipeline = nullptr;
     563             :     CPLStringList m_aosCTOptions{};
     564             : 
     565             :     std::unique_ptr<TargetLayerInfo>
     566             :     Setup(OGRLayer *poSrcLayer, const char *pszNewLayerName,
     567             :           GDALVectorTranslateOptions *psOptions, GIntBig &nTotalEventsDone);
     568             : 
     569             :   private:
     570             :     bool CanUseWriteArrowBatch(OGRLayer *poSrcLayer, OGRLayer *poDstLayer,
     571             :                                bool bJustCreatedLayer,
     572             :                                const GDALVectorTranslateOptions *psOptions,
     573             :                                bool bPreserveFID, bool &bError,
     574             :                                OGRArrowArrayStream &streamSrc);
     575             : 
     576             :     void SetIgnoredFields(OGRLayer *poSrcLayer);
     577             : };
     578             : 
     579             : class LayerTranslator
     580             : {
     581             :     bool TranslateArrow(TargetLayerInfo *psInfo, GIntBig nCountLayerFeatures,
     582             :                         GIntBig *pnReadFeatureCount,
     583             :                         GDALProgressFunc pfnProgress, void *pProgressArg,
     584             :                         const GDALVectorTranslateOptions *psOptions);
     585             : 
     586             :   public:
     587             :     GDALDataset *m_poSrcDS = nullptr;
     588             :     GDALDataset *m_poODS = nullptr;
     589             :     bool m_bTransform = false;
     590             :     bool m_bWrapDateline = false;
     591             :     CPLString m_osDateLineOffset{};
     592             :     const OGRSpatialReference *m_poOutputSRS = nullptr;
     593             :     bool m_bNullifyOutputSRS = false;
     594             :     const OGRSpatialReference *m_poUserSourceSRS = nullptr;
     595             :     OGRCoordinateTransformation *m_poGCPCoordTrans = nullptr;
     596             :     int m_eGType = -1;
     597             :     GeomTypeConversion m_eGeomTypeConversion = GTC_DEFAULT;
     598             :     bool m_bMakeValid = false;
     599             :     bool m_bSkipInvalidGeom = false;
     600             :     int m_nCoordDim = 0;
     601             :     GeomOperation m_eGeomOp = GEOMOP_NONE;
     602             :     double m_dfGeomOpParam = 0;
     603             : 
     604             :     OGRGeometry *m_poClipSrcOri = nullptr;
     605             :     bool m_bWarnedClipSrcSRS = false;
     606             :     std::unique_ptr<OGRGeometry> m_poClipSrcReprojectedToSrcSRS{};
     607             :     const OGRSpatialReference *m_poClipSrcReprojectedToSrcSRS_SRS = nullptr;
     608             :     OGREnvelope m_oClipSrcEnv{};
     609             :     bool m_bClipSrcIsRectangle = false;
     610             : 
     611             :     OGRGeometry *m_poClipDstOri = nullptr;
     612             :     bool m_bWarnedClipDstSRS = false;
     613             :     std::unique_ptr<OGRGeometry> m_poClipDstReprojectedToDstSRS{};
     614             :     const OGRSpatialReference *m_poClipDstReprojectedToDstSRS_SRS = nullptr;
     615             :     OGREnvelope m_oClipDstEnv{};
     616             :     bool m_bClipDstIsRectangle = false;
     617             : 
     618             :     bool m_bExplodeCollections = false;
     619             :     bool m_bNativeData = false;
     620             :     GIntBig m_nLimit = -1;
     621             :     OGRGeometryFactory::TransformWithOptionsCache m_transformWithOptionsCache{};
     622             : 
     623             :     bool Translate(std::unique_ptr<OGRFeature> poFeatureIn,
     624             :                    TargetLayerInfo *psInfo, GIntBig nCountLayerFeatures,
     625             :                    GIntBig *pnReadFeatureCount, GIntBig &nTotalEventsDone,
     626             :                    GDALProgressFunc pfnProgress, void *pProgressArg,
     627             :                    const GDALVectorTranslateOptions *psOptions);
     628             : 
     629             :   private:
     630             :     struct ClipGeomDesc
     631             :     {
     632             :         const OGRGeometry *poGeom = nullptr;
     633             :         const OGREnvelope *poEnv = nullptr;
     634             :         bool bGeomIsRectangle = false;
     635             :     };
     636             : 
     637             :     ClipGeomDesc GetDstClipGeom(const OGRSpatialReference *poGeomSRS);
     638             :     ClipGeomDesc GetSrcClipGeom(const OGRSpatialReference *poGeomSRS);
     639             : };
     640             : 
     641             : static OGRLayer *GetLayerAndOverwriteIfNecessary(GDALDataset *poDstDS,
     642             :                                                  const char *pszNewLayerName,
     643             :                                                  bool bOverwrite,
     644             :                                                  bool *pbErrorOccurred,
     645             :                                                  bool *pbOverwriteActuallyDone,
     646             :                                                  bool *pbAddOverwriteLCO);
     647             : 
     648             : /************************************************************************/
     649             : /*                            LoadGeometry()                            */
     650             : /************************************************************************/
     651             : 
     652          20 : static std::unique_ptr<OGRGeometry> LoadGeometry(const std::string &osDS,
     653             :                                                  const std::string &osSQL,
     654             :                                                  const std::string &osLyr,
     655             :                                                  const std::string &osWhere,
     656             :                                                  bool bMakeValid)
     657             : {
     658             :     auto poDS = std::unique_ptr<GDALDataset>(
     659          40 :         GDALDataset::Open(osDS.c_str(), GDAL_OF_VECTOR));
     660          20 :     if (poDS == nullptr)
     661           3 :         return nullptr;
     662             : 
     663          17 :     OGRLayer *poLyr = nullptr;
     664          17 :     if (!osSQL.empty())
     665           3 :         poLyr = poDS->ExecuteSQL(osSQL.c_str(), nullptr, nullptr);
     666          14 :     else if (!osLyr.empty())
     667           2 :         poLyr = poDS->GetLayerByName(osLyr.c_str());
     668             :     else
     669          12 :         poLyr = poDS->GetLayer(0);
     670             : 
     671          17 :     if (poLyr == nullptr)
     672             :     {
     673           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     674             :                  "Failed to identify source layer from datasource.");
     675           0 :         return nullptr;
     676             :     }
     677             : 
     678          17 :     if (!osWhere.empty())
     679           7 :         poLyr->SetAttributeFilter(osWhere.c_str());
     680             : 
     681          34 :     OGRGeometryCollection oGC;
     682             : 
     683          17 :     const auto poSRSSrc = poLyr->GetSpatialRef();
     684          17 :     if (poSRSSrc)
     685             :     {
     686           2 :         auto poSRSClone = poSRSSrc->Clone();
     687           2 :         oGC.assignSpatialReference(poSRSClone);
     688           2 :         poSRSClone->Release();
     689             :     }
     690             : 
     691          34 :     for (auto &poFeat : poLyr)
     692             :     {
     693          17 :         auto poSrcGeom = std::unique_ptr<OGRGeometry>(poFeat->StealGeometry());
     694          17 :         if (poSrcGeom)
     695             :         {
     696             :             // Only take into account areal geometries.
     697          17 :             if (poSrcGeom->getDimension() == 2)
     698             :             {
     699          17 :                 if (!poSrcGeom->IsValid())
     700             :                 {
     701           4 :                     if (!bMakeValid)
     702             :                     {
     703           2 :                         CPLError(CE_Failure, CPLE_AppDefined,
     704             :                                  "Geometry of feature " CPL_FRMT_GIB " of %s "
     705             :                                  "is invalid. You can try to make it valid by "
     706             :                                  "specifying -makevalid, but the results of "
     707             :                                  "the operation should be manually inspected.",
     708             :                                  poFeat->GetFID(), osDS.c_str());
     709           2 :                         oGC.empty();
     710           2 :                         break;
     711             :                     }
     712             :                     auto poValid =
     713           2 :                         std::unique_ptr<OGRGeometry>(poSrcGeom->MakeValid());
     714           2 :                     if (poValid)
     715             :                     {
     716           2 :                         CPLError(CE_Warning, CPLE_AppDefined,
     717             :                                  "Geometry of feature " CPL_FRMT_GIB " of %s "
     718             :                                  "was invalid and has been made valid, "
     719             :                                  "but the results of the operation "
     720             :                                  "should be manually inspected.",
     721             :                                  poFeat->GetFID(), osDS.c_str());
     722             : 
     723           2 :                         oGC.addGeometry(std::move(poValid));
     724             :                     }
     725             :                     else
     726             :                     {
     727           0 :                         CPLError(CE_Failure, CPLE_AppDefined,
     728             :                                  "Geometry of feature " CPL_FRMT_GIB " of %s "
     729             :                                  "is invalid, and could not be made valid.",
     730             :                                  poFeat->GetFID(), osDS.c_str());
     731           0 :                         oGC.empty();
     732           0 :                         break;
     733             :                     }
     734             :                 }
     735             :                 else
     736             :                 {
     737          13 :                     oGC.addGeometry(std::move(poSrcGeom));
     738             :                 }
     739             :             }
     740             :         }
     741             :     }
     742             : 
     743          17 :     if (!osSQL.empty())
     744           3 :         poDS->ReleaseResultSet(poLyr);
     745             : 
     746          17 :     if (oGC.IsEmpty())
     747           2 :         return nullptr;
     748             : 
     749          15 :     return std::unique_ptr<OGRGeometry>(oGC.UnaryUnion());
     750             : }
     751             : 
     752             : /************************************************************************/
     753             : /*                        OGRSplitListFieldLayer                        */
     754             : /************************************************************************/
     755             : 
     756             : class OGRSplitListFieldLayer : public OGRLayer
     757             : {
     758             :     struct ListFieldDesc
     759             :     {
     760             :         int iSrcIndex = -1;
     761             :         OGRFieldType eType = OFTMaxType;
     762             :         int nMaxOccurrences = 0;
     763             :         int nWidth = 0;
     764             :     };
     765             : 
     766             :     OGRLayer *poSrcLayer = nullptr;
     767             :     OGRFeatureDefn *poFeatureDefn = nullptr;
     768             :     std::vector<ListFieldDesc> asListFields{};
     769             :     const int nMaxSplitListSubFields;
     770             : 
     771             :     std::unique_ptr<OGRFeature>
     772             :     TranslateFeature(std::unique_ptr<OGRFeature> poSrcFeature) const;
     773             : 
     774             :     CPL_DISALLOW_COPY_ASSIGN(OGRSplitListFieldLayer)
     775             : 
     776             :   public:
     777             :     OGRSplitListFieldLayer(OGRLayer *poSrcLayer, int nMaxSplitListSubFields);
     778             :     ~OGRSplitListFieldLayer() override;
     779             : 
     780             :     bool BuildLayerDefn(GDALProgressFunc pfnProgress, void *pProgressArg);
     781             : 
     782             :     OGRFeature *GetNextFeature() override;
     783             :     OGRFeature *GetFeature(GIntBig nFID) override;
     784             :     const OGRFeatureDefn *GetLayerDefn() const override;
     785             : 
     786           1 :     void ResetReading() override
     787             :     {
     788           1 :         poSrcLayer->ResetReading();
     789           1 :     }
     790             : 
     791           1 :     int TestCapability(const char *) const override
     792             :     {
     793           1 :         return FALSE;
     794             :     }
     795             : 
     796           0 :     GIntBig GetFeatureCount(int bForce = TRUE) override
     797             :     {
     798           0 :         return poSrcLayer->GetFeatureCount(bForce);
     799             :     }
     800             : 
     801           1 :     const OGRSpatialReference *GetSpatialRef() const override
     802             :     {
     803           1 :         return poSrcLayer->GetSpatialRef();
     804             :     }
     805             : 
     806           0 :     OGRGeometry *GetSpatialFilter() override
     807             :     {
     808           0 :         return poSrcLayer->GetSpatialFilter();
     809             :     }
     810             : 
     811           1 :     OGRStyleTable *GetStyleTable() override
     812             :     {
     813           1 :         return poSrcLayer->GetStyleTable();
     814             :     }
     815             : 
     816           0 :     virtual OGRErr ISetSpatialFilter(int iGeom,
     817             :                                      const OGRGeometry *poGeom) override
     818             :     {
     819           0 :         return poSrcLayer->SetSpatialFilter(iGeom, poGeom);
     820             :     }
     821             : 
     822           0 :     OGRErr SetAttributeFilter(const char *pszFilter) override
     823             :     {
     824           0 :         return poSrcLayer->SetAttributeFilter(pszFilter);
     825             :     }
     826             : };
     827             : 
     828             : /************************************************************************/
     829             : /*                       OGRSplitListFieldLayer()                       */
     830             : /************************************************************************/
     831             : 
     832           1 : OGRSplitListFieldLayer::OGRSplitListFieldLayer(OGRLayer *poSrcLayerIn,
     833           1 :                                                int nMaxSplitListSubFieldsIn)
     834             :     : poSrcLayer(poSrcLayerIn),
     835             :       nMaxSplitListSubFields(
     836           1 :           nMaxSplitListSubFieldsIn < 0 ? INT_MAX : nMaxSplitListSubFieldsIn)
     837             : {
     838           1 : }
     839             : 
     840             : /************************************************************************/
     841             : /*                      ~OGRSplitListFieldLayer()                       */
     842             : /************************************************************************/
     843             : 
     844           2 : OGRSplitListFieldLayer::~OGRSplitListFieldLayer()
     845             : {
     846           1 :     if (poFeatureDefn)
     847           1 :         poFeatureDefn->Release();
     848           2 : }
     849             : 
     850             : /************************************************************************/
     851             : /*                           BuildLayerDefn()                           */
     852             : /************************************************************************/
     853             : 
     854           1 : bool OGRSplitListFieldLayer::BuildLayerDefn(GDALProgressFunc pfnProgress,
     855             :                                             void *pProgressArg)
     856             : {
     857           1 :     CPLAssert(poFeatureDefn == nullptr);
     858             : 
     859           1 :     const OGRFeatureDefn *poSrcFeatureDefn = poSrcLayer->GetLayerDefn();
     860             : 
     861           1 :     const int nSrcFields = poSrcFeatureDefn->GetFieldCount();
     862           1 :     asListFields.reserve(nSrcFields);
     863             : 
     864             :     /* Establish the list of fields of list type */
     865           6 :     for (int i = 0; i < nSrcFields; ++i)
     866             :     {
     867           5 :         OGRFieldType eType = poSrcFeatureDefn->GetFieldDefn(i)->GetType();
     868           5 :         if (eType == OFTIntegerList || eType == OFTInteger64List ||
     869           3 :             eType == OFTRealList || eType == OFTStringList)
     870             :         {
     871           3 :             asListFields.resize(asListFields.size() + 1);
     872           3 :             asListFields.back().iSrcIndex = i;
     873           3 :             asListFields.back().eType = eType;
     874           3 :             if (nMaxSplitListSubFields == 1)
     875           0 :                 asListFields.back().nMaxOccurrences = 1;
     876             :         }
     877             :     }
     878             : 
     879           1 :     if (asListFields.empty())
     880           0 :         return false;
     881             : 
     882             :     /* No need for full scan if the limit is 1. We just to have to create */
     883             :     /* one and a single one field */
     884           1 :     if (nMaxSplitListSubFields != 1)
     885             :     {
     886           1 :         poSrcLayer->ResetReading();
     887             : 
     888             :         const GIntBig nFeatureCount =
     889           1 :             poSrcLayer->TestCapability(OLCFastFeatureCount)
     890           1 :                 ? poSrcLayer->GetFeatureCount()
     891           1 :                 : 0;
     892           1 :         GIntBig nFeatureIndex = 0;
     893             : 
     894             :         /* Scan the whole layer to compute the maximum number of */
     895             :         /* items for each field of list type */
     896           2 :         for (const auto &poSrcFeature : poSrcLayer)
     897             :         {
     898           4 :             for (auto &sListField : asListFields)
     899             :             {
     900           3 :                 int nCount = 0;
     901             :                 const OGRField *psField =
     902           3 :                     poSrcFeature->GetRawFieldRef(sListField.iSrcIndex);
     903           3 :                 switch (sListField.eType)
     904             :                 {
     905           1 :                     case OFTIntegerList:
     906           1 :                         nCount = psField->IntegerList.nCount;
     907           1 :                         break;
     908           1 :                     case OFTRealList:
     909           1 :                         nCount = psField->RealList.nCount;
     910           1 :                         break;
     911           1 :                     case OFTStringList:
     912             :                     {
     913           1 :                         nCount = psField->StringList.nCount;
     914           1 :                         char **paList = psField->StringList.paList;
     915           3 :                         for (int j = 0; j < nCount; j++)
     916             :                         {
     917           2 :                             int nWidth = static_cast<int>(strlen(paList[j]));
     918           2 :                             if (nWidth > sListField.nWidth)
     919           1 :                                 sListField.nWidth = nWidth;
     920             :                         }
     921           1 :                         break;
     922             :                     }
     923           0 :                     default:
     924             :                         // cppcheck-suppress knownConditionTrueFalse
     925           0 :                         CPLAssert(false);
     926             :                         break;
     927             :                 }
     928           3 :                 if (nCount > sListField.nMaxOccurrences)
     929             :                 {
     930           3 :                     if (nCount > nMaxSplitListSubFields)
     931           0 :                         nCount = nMaxSplitListSubFields;
     932           3 :                     sListField.nMaxOccurrences = nCount;
     933             :                 }
     934             :             }
     935             : 
     936           1 :             nFeatureIndex++;
     937           1 :             if (pfnProgress != nullptr && nFeatureCount != 0)
     938           0 :                 pfnProgress(nFeatureIndex * 1.0 / nFeatureCount, "",
     939             :                             pProgressArg);
     940             :         }
     941             :     }
     942             : 
     943             :     /* Now let's build the target feature definition */
     944             : 
     945           1 :     poFeatureDefn =
     946           1 :         OGRFeatureDefn::CreateFeatureDefn(poSrcFeatureDefn->GetName());
     947           1 :     poFeatureDefn->Reference();
     948           1 :     poFeatureDefn->SetGeomType(wkbNone);
     949             : 
     950           1 :     for (const auto poSrcGeomFieldDefn : poSrcFeatureDefn->GetGeomFields())
     951             :     {
     952           0 :         poFeatureDefn->AddGeomFieldDefn(poSrcGeomFieldDefn);
     953             :     }
     954             : 
     955           1 :     int iListField = 0;
     956           6 :     for (const auto poSrcFieldDefn : poSrcFeatureDefn->GetFields())
     957             :     {
     958           5 :         const OGRFieldType eType = poSrcFieldDefn->GetType();
     959           5 :         if (eType == OFTIntegerList || eType == OFTInteger64List ||
     960           3 :             eType == OFTRealList || eType == OFTStringList)
     961             :         {
     962             :             const int nMaxOccurrences =
     963           3 :                 asListFields[iListField].nMaxOccurrences;
     964           3 :             const int nWidth = asListFields[iListField].nWidth;
     965           3 :             iListField++;
     966           3 :             if (nMaxOccurrences == 1)
     967             :             {
     968             :                 OGRFieldDefn oFieldDefn(poSrcFieldDefn->GetNameRef(),
     969             :                                         (eType == OFTIntegerList) ? OFTInteger
     970             :                                         : (eType == OFTInteger64List)
     971           0 :                                             ? OFTInteger64
     972           0 :                                         : (eType == OFTRealList) ? OFTReal
     973           0 :                                                                  : OFTString);
     974           0 :                 poFeatureDefn->AddFieldDefn(&oFieldDefn);
     975             :             }
     976             :             else
     977             :             {
     978           9 :                 for (int j = 0; j < nMaxOccurrences; j++)
     979             :                 {
     980          12 :                     CPLString osFieldName;
     981             :                     osFieldName.Printf("%s%d", poSrcFieldDefn->GetNameRef(),
     982           6 :                                        j + 1);
     983             :                     OGRFieldDefn oFieldDefn(
     984             :                         osFieldName.c_str(),
     985             :                         (eType == OFTIntegerList)     ? OFTInteger
     986           8 :                         : (eType == OFTInteger64List) ? OFTInteger64
     987           4 :                         : (eType == OFTRealList)      ? OFTReal
     988          16 :                                                       : OFTString);
     989           6 :                     oFieldDefn.SetWidth(nWidth);
     990           6 :                     poFeatureDefn->AddFieldDefn(&oFieldDefn);
     991             :                 }
     992           3 :             }
     993             :         }
     994             :         else
     995             :         {
     996           2 :             poFeatureDefn->AddFieldDefn(poSrcFieldDefn);
     997             :         }
     998             :     }
     999             : 
    1000           1 :     return true;
    1001             : }
    1002             : 
    1003             : /************************************************************************/
    1004             : /*                          TranslateFeature()                          */
    1005             : /************************************************************************/
    1006             : 
    1007           2 : std::unique_ptr<OGRFeature> OGRSplitListFieldLayer::TranslateFeature(
    1008             :     std::unique_ptr<OGRFeature> poSrcFeature) const
    1009             : {
    1010           2 :     if (poSrcFeature == nullptr)
    1011           1 :         return nullptr;
    1012           1 :     if (poFeatureDefn == nullptr)
    1013           0 :         return poSrcFeature;
    1014             : 
    1015           2 :     auto poFeature = std::make_unique<OGRFeature>(poFeatureDefn);
    1016           1 :     poFeature->SetFID(poSrcFeature->GetFID());
    1017           1 :     for (int i = 0; i < poFeature->GetGeomFieldCount(); i++)
    1018             :     {
    1019           0 :         poFeature->SetGeomFieldDirectly(i, poSrcFeature->StealGeometry(i));
    1020             :     }
    1021           1 :     poFeature->SetStyleString(poFeature->GetStyleString());
    1022             : 
    1023           1 :     const OGRFeatureDefn *poSrcFieldDefn = poSrcLayer->GetLayerDefn();
    1024           1 :     const int nSrcFields = poSrcFeature->GetFieldCount();
    1025           1 :     int iDstField = 0;
    1026           1 :     int iListField = 0;
    1027             : 
    1028           6 :     for (int iSrcField = 0; iSrcField < nSrcFields; ++iSrcField)
    1029             :     {
    1030             :         const OGRFieldType eType =
    1031           5 :             poSrcFieldDefn->GetFieldDefn(iSrcField)->GetType();
    1032           5 :         const OGRField *psField = poSrcFeature->GetRawFieldRef(iSrcField);
    1033           5 :         switch (eType)
    1034             :         {
    1035           1 :             case OFTIntegerList:
    1036             :             {
    1037           1 :                 const int nCount = std::min(nMaxSplitListSubFields,
    1038           1 :                                             psField->IntegerList.nCount);
    1039           1 :                 const int *paList = psField->IntegerList.paList;
    1040           3 :                 for (int j = 0; j < nCount; ++j)
    1041           2 :                     poFeature->SetField(iDstField + j, paList[j]);
    1042           1 :                 iDstField += asListFields[iListField].nMaxOccurrences;
    1043           1 :                 iListField++;
    1044           1 :                 break;
    1045             :             }
    1046           0 :             case OFTInteger64List:
    1047             :             {
    1048           0 :                 const int nCount = std::min(nMaxSplitListSubFields,
    1049           0 :                                             psField->Integer64List.nCount);
    1050           0 :                 const GIntBig *paList = psField->Integer64List.paList;
    1051           0 :                 for (int j = 0; j < nCount; ++j)
    1052           0 :                     poFeature->SetField(iDstField + j, paList[j]);
    1053           0 :                 iDstField += asListFields[iListField].nMaxOccurrences;
    1054           0 :                 iListField++;
    1055           0 :                 break;
    1056             :             }
    1057           1 :             case OFTRealList:
    1058             :             {
    1059             :                 const int nCount =
    1060           1 :                     std::min(nMaxSplitListSubFields, psField->RealList.nCount);
    1061           1 :                 const double *paList = psField->RealList.paList;
    1062           3 :                 for (int j = 0; j < nCount; ++j)
    1063           2 :                     poFeature->SetField(iDstField + j, paList[j]);
    1064           1 :                 iDstField += asListFields[iListField].nMaxOccurrences;
    1065           1 :                 iListField++;
    1066           1 :                 break;
    1067             :             }
    1068           1 :             case OFTStringList:
    1069             :             {
    1070           1 :                 const int nCount = std::min(nMaxSplitListSubFields,
    1071           1 :                                             psField->StringList.nCount);
    1072           1 :                 CSLConstList paList = psField->StringList.paList;
    1073           3 :                 for (int j = 0; j < nCount; ++j)
    1074           2 :                     poFeature->SetField(iDstField + j, paList[j]);
    1075           1 :                 iDstField += asListFields[iListField].nMaxOccurrences;
    1076           1 :                 iListField++;
    1077           1 :                 break;
    1078             :             }
    1079           2 :             default:
    1080             :             {
    1081           2 :                 poFeature->SetField(iDstField, psField);
    1082           2 :                 iDstField++;
    1083           2 :                 break;
    1084             :             }
    1085             :         }
    1086             :     }
    1087             : 
    1088           1 :     return poFeature;
    1089             : }
    1090             : 
    1091             : /************************************************************************/
    1092             : /*                           GetNextFeature()                           */
    1093             : /************************************************************************/
    1094             : 
    1095           2 : OGRFeature *OGRSplitListFieldLayer::GetNextFeature()
    1096             : {
    1097           4 :     return TranslateFeature(
    1098           4 :                std::unique_ptr<OGRFeature>(poSrcLayer->GetNextFeature()))
    1099           4 :         .release();
    1100             : }
    1101             : 
    1102             : /************************************************************************/
    1103             : /*                             GetFeature()                             */
    1104             : /************************************************************************/
    1105             : 
    1106           0 : OGRFeature *OGRSplitListFieldLayer::GetFeature(GIntBig nFID)
    1107             : {
    1108           0 :     return TranslateFeature(
    1109           0 :                std::unique_ptr<OGRFeature>(poSrcLayer->GetFeature(nFID)))
    1110           0 :         .release();
    1111             : }
    1112             : 
    1113             : /************************************************************************/
    1114             : /*                            GetLayerDefn()                            */
    1115             : /************************************************************************/
    1116             : 
    1117           3 : const OGRFeatureDefn *OGRSplitListFieldLayer::GetLayerDefn() const
    1118             : {
    1119           3 :     if (poFeatureDefn == nullptr)
    1120           0 :         return poSrcLayer->GetLayerDefn();
    1121           3 :     return poFeatureDefn;
    1122             : }
    1123             : 
    1124             : /************************************************************************/
    1125             : /*                            GCPCoordTransformation()                  */
    1126             : /*                                                                      */
    1127             : /*      Apply GCP Transform to points                                   */
    1128             : /************************************************************************/
    1129             : 
    1130             : class GCPCoordTransformation final : public OGRCoordinateTransformation
    1131             : {
    1132           0 :     GCPCoordTransformation(const GCPCoordTransformation &other)
    1133           0 :         : bUseTPS(other.bUseTPS), poSRS(other.poSRS)
    1134             :     {
    1135           0 :         hTransformArg.reset(GDALCloneTransformer(other.hTransformArg.get()));
    1136           0 :         if (poSRS)
    1137           0 :             poSRS->Reference();
    1138           0 :     }
    1139             : 
    1140             :     GCPCoordTransformation &operator=(const GCPCoordTransformation &) = delete;
    1141             : 
    1142             :   public:
    1143             :     std::unique_ptr<void, decltype(&GDALDestroyTransformer)> hTransformArg{
    1144           0 :         nullptr, GDALDestroyTransformer};
    1145             :     const bool bUseTPS;
    1146             :     OGRSpatialReference *const poSRS;
    1147             : 
    1148           7 :     GCPCoordTransformation(int nGCPCount, const GDAL_GCP *pasGCPList,
    1149             :                            int nReqOrder, OGRSpatialReference *poSRSIn)
    1150           7 :         : bUseTPS(nReqOrder < 0), poSRS(poSRSIn)
    1151             :     {
    1152           7 :         if (nReqOrder < 0)
    1153             :         {
    1154           1 :             hTransformArg.reset(
    1155             :                 GDALCreateTPSTransformer(nGCPCount, pasGCPList, FALSE));
    1156             :         }
    1157             :         else
    1158             :         {
    1159           6 :             hTransformArg.reset(GDALCreateGCPTransformer(nGCPCount, pasGCPList,
    1160             :                                                          nReqOrder, FALSE));
    1161             :         }
    1162           7 :         if (poSRS)
    1163           2 :             poSRS->Reference();
    1164           7 :     }
    1165             : 
    1166           0 :     OGRCoordinateTransformation *Clone() const override
    1167             :     {
    1168           0 :         return new GCPCoordTransformation(*this);
    1169             :     }
    1170             : 
    1171           7 :     bool IsValid() const
    1172             :     {
    1173           7 :         return hTransformArg != nullptr;
    1174             :     }
    1175             : 
    1176             :     ~GCPCoordTransformation() override;
    1177             : 
    1178          11 :     const OGRSpatialReference *GetSourceCS() const override
    1179             :     {
    1180          11 :         return poSRS;
    1181             :     }
    1182             : 
    1183          18 :     const OGRSpatialReference *GetTargetCS() const override
    1184             :     {
    1185          18 :         return poSRS;
    1186             :     }
    1187             : 
    1188          11 :     virtual int Transform(size_t nCount, double *x, double *y, double *z,
    1189             :                           double * /* t */, int *pabSuccess) override
    1190             :     {
    1191          11 :         CPLAssert(nCount <=
    1192             :                   static_cast<size_t>(std::numeric_limits<int>::max()));
    1193          11 :         if (bUseTPS)
    1194           2 :             return GDALTPSTransform(hTransformArg.get(), FALSE,
    1195             :                                     static_cast<int>(nCount), x, y, z,
    1196           2 :                                     pabSuccess);
    1197             :         else
    1198           9 :             return GDALGCPTransform(hTransformArg.get(), FALSE,
    1199             :                                     static_cast<int>(nCount), x, y, z,
    1200           9 :                                     pabSuccess);
    1201             :     }
    1202             : 
    1203           0 :     OGRCoordinateTransformation *GetInverse() const override
    1204             :     {
    1205             :         static std::once_flag flag;
    1206           0 :         std::call_once(flag,
    1207           0 :                        []()
    1208             :                        {
    1209           0 :                            CPLDebug("OGR2OGR",
    1210             :                                     "GCPCoordTransformation::GetInverse() "
    1211             :                                     "called, but not implemented");
    1212           0 :                        });
    1213           0 :         return nullptr;
    1214             :     }
    1215             : };
    1216             : 
    1217          14 : GCPCoordTransformation::~GCPCoordTransformation()
    1218             : {
    1219           7 :     if (poSRS)
    1220           2 :         poSRS->Dereference();
    1221          14 : }
    1222             : 
    1223             : /************************************************************************/
    1224             : /*                             CompositeCT                              */
    1225             : /************************************************************************/
    1226             : 
    1227          12 : class CompositeCT final : public OGRCoordinateTransformation
    1228             : {
    1229             :     std::unique_ptr<OGRCoordinateTransformation> poOwnedCT1{};
    1230             :     OGRCoordinateTransformation *const poCT1;
    1231             :     std::unique_ptr<OGRCoordinateTransformation> poOwnedCT2{};
    1232             :     OGRCoordinateTransformation *const poCT2;
    1233             : 
    1234             :     // Working buffer
    1235             :     std::vector<int> m_anErrorCode{};
    1236             : 
    1237             :     CompositeCT &operator=(const CompositeCT &) = delete;
    1238             : 
    1239             :   public:
    1240           5 :     CompositeCT(OGRCoordinateTransformation *poCT1In,
    1241             :                 OGRCoordinateTransformation *poCT2In)
    1242           5 :         : poCT1(poCT1In), poCT2(poCT2In)
    1243             :     {
    1244           5 :     }
    1245             : 
    1246           0 :     CompositeCT(std::unique_ptr<OGRCoordinateTransformation> poCT1In,
    1247             :                 OGRCoordinateTransformation *poCT2In)
    1248           0 :         : poOwnedCT1(std::move(poCT1In)), poCT1(poOwnedCT1.get()),
    1249           0 :           poCT2(poCT2In)
    1250             :     {
    1251           0 :     }
    1252             : 
    1253           0 :     CompositeCT(std::unique_ptr<OGRCoordinateTransformation> poCT1In,
    1254             :                 std::unique_ptr<OGRCoordinateTransformation> poCT2In)
    1255           0 :         : poOwnedCT1(std::move(poCT1In)), poCT1(poOwnedCT1.get()),
    1256           0 :           poOwnedCT2(std::move(poCT2In)), poCT2(poOwnedCT2.get())
    1257             :     {
    1258           0 :     }
    1259             : 
    1260           1 :     CompositeCT(OGRCoordinateTransformation *poCT1In,
    1261             :                 std::unique_ptr<OGRCoordinateTransformation> poCT2In)
    1262           2 :         : poCT1(poCT1In), poOwnedCT2(std::move(poCT2In)),
    1263           1 :           poCT2(poOwnedCT2.get())
    1264             :     {
    1265           1 :     }
    1266             : 
    1267           0 :     CompositeCT(const CompositeCT &other)
    1268           0 :         : poOwnedCT1(other.poCT1 ? other.poCT1->Clone() : nullptr),
    1269           0 :           poCT1(poOwnedCT1.get()),
    1270           0 :           poOwnedCT2(other.poCT2 ? other.poCT2->Clone() : nullptr),
    1271           0 :           poCT2(poOwnedCT2.get()), m_anErrorCode({})
    1272             :     {
    1273           0 :     }
    1274             : 
    1275             :     ~CompositeCT() override;
    1276             : 
    1277           0 :     OGRCoordinateTransformation *Clone() const override
    1278             :     {
    1279           0 :         return std::make_unique<CompositeCT>(*this).release();
    1280             :     }
    1281             : 
    1282          11 :     const OGRSpatialReference *GetSourceCS() const override
    1283             :     {
    1284          11 :         return poCT1   ? poCT1->GetSourceCS()
    1285           0 :                : poCT2 ? poCT2->GetSourceCS()
    1286          11 :                        : nullptr;
    1287             :     }
    1288             : 
    1289          22 :     const OGRSpatialReference *GetTargetCS() const override
    1290             :     {
    1291          40 :         return poCT2   ? poCT2->GetTargetCS()
    1292          18 :                : poCT1 ? poCT1->GetTargetCS()
    1293          22 :                        : nullptr;
    1294             :     }
    1295             : 
    1296           0 :     bool GetEmitErrors() const override
    1297             :     {
    1298           0 :         if (poCT1)
    1299           0 :             return poCT1->GetEmitErrors();
    1300           0 :         if (poCT2)
    1301           0 :             return poCT2->GetEmitErrors();
    1302           0 :         return true;
    1303             :     }
    1304             : 
    1305           0 :     void SetEmitErrors(bool bEmitErrors) override
    1306             :     {
    1307           0 :         if (poCT1)
    1308           0 :             poCT1->SetEmitErrors(bEmitErrors);
    1309           0 :         if (poCT2)
    1310           0 :             poCT2->SetEmitErrors(bEmitErrors);
    1311           0 :     }
    1312             : 
    1313          11 :     virtual int Transform(size_t nCount, double *x, double *y, double *z,
    1314             :                           double *t, int *pabSuccess) override
    1315             :     {
    1316          11 :         int nResult = TRUE;
    1317          11 :         if (poCT1)
    1318          11 :             nResult = poCT1->Transform(nCount, x, y, z, t, pabSuccess);
    1319          11 :         if (nResult && poCT2)
    1320           2 :             nResult = poCT2->Transform(nCount, x, y, z, t, pabSuccess);
    1321          11 :         return nResult;
    1322             :     }
    1323             : 
    1324           0 :     virtual int TransformWithErrorCodes(size_t nCount, double *x, double *y,
    1325             :                                         double *z, double *t,
    1326             :                                         int *panErrorCodes) override
    1327             :     {
    1328           0 :         if (poCT1 && poCT2 && panErrorCodes)
    1329             :         {
    1330           0 :             m_anErrorCode.resize(nCount);
    1331           0 :             int nResult = poCT1->TransformWithErrorCodes(nCount, x, y, z, t,
    1332           0 :                                                          m_anErrorCode.data());
    1333           0 :             if (nResult)
    1334           0 :                 nResult = poCT2->TransformWithErrorCodes(nCount, x, y, z, t,
    1335           0 :                                                          panErrorCodes);
    1336           0 :             for (size_t i = 0; i < nCount; ++i)
    1337             :             {
    1338           0 :                 if (m_anErrorCode[i])
    1339           0 :                     panErrorCodes[i] = m_anErrorCode[i];
    1340             :             }
    1341           0 :             return nResult;
    1342             :         }
    1343           0 :         int nResult = TRUE;
    1344           0 :         if (poCT1)
    1345           0 :             nResult = poCT1->TransformWithErrorCodes(nCount, x, y, z, t,
    1346           0 :                                                      panErrorCodes);
    1347           0 :         if (nResult && poCT2)
    1348           0 :             nResult = poCT2->TransformWithErrorCodes(nCount, x, y, z, t,
    1349           0 :                                                      panErrorCodes);
    1350           0 :         return nResult;
    1351             :     }
    1352             : 
    1353           0 :     OGRCoordinateTransformation *GetInverse() const override
    1354             :     {
    1355           0 :         if (!poCT1 && !poCT2)
    1356           0 :             return nullptr;
    1357           0 :         if (!poCT2)
    1358           0 :             return poCT1->GetInverse();
    1359           0 :         if (!poCT1)
    1360           0 :             return poCT2->GetInverse();
    1361             :         auto poInvCT1 =
    1362           0 :             std::unique_ptr<OGRCoordinateTransformation>(poCT1->GetInverse());
    1363             :         auto poInvCT2 =
    1364           0 :             std::unique_ptr<OGRCoordinateTransformation>(poCT2->GetInverse());
    1365           0 :         if (!poInvCT1 || !poInvCT2)
    1366           0 :             return nullptr;
    1367           0 :         return std::make_unique<CompositeCT>(std::move(poInvCT2),
    1368           0 :                                              std::move(poInvCT1))
    1369           0 :             .release();
    1370             :     }
    1371             : };
    1372             : 
    1373             : CompositeCT::~CompositeCT() = default;
    1374             : 
    1375             : /************************************************************************/
    1376             : /*                 AxisMappingCoordinateTransformation                  */
    1377             : /************************************************************************/
    1378             : 
    1379           0 : class AxisMappingCoordinateTransformation : public OGRCoordinateTransformation
    1380             : {
    1381             :     bool bSwapXY = false;
    1382             : 
    1383           0 :     AxisMappingCoordinateTransformation(
    1384             :         const AxisMappingCoordinateTransformation &) = default;
    1385             :     AxisMappingCoordinateTransformation &
    1386             :     operator=(const AxisMappingCoordinateTransformation &) = delete;
    1387             :     AxisMappingCoordinateTransformation(
    1388             :         AxisMappingCoordinateTransformation &&) = delete;
    1389             :     AxisMappingCoordinateTransformation &
    1390             :     operator=(AxisMappingCoordinateTransformation &&) = delete;
    1391             : 
    1392             :   public:
    1393           0 :     explicit AxisMappingCoordinateTransformation(bool bSwapXYIn)
    1394           0 :         : bSwapXY(bSwapXYIn)
    1395             :     {
    1396           0 :     }
    1397             : 
    1398           0 :     AxisMappingCoordinateTransformation(const std::vector<int> &mappingIn,
    1399             :                                         const std::vector<int> &mappingOut)
    1400           0 :     {
    1401           0 :         if (mappingIn.size() >= 2 && mappingIn[0] == 1 && mappingIn[1] == 2 &&
    1402           0 :             mappingOut.size() >= 2 && mappingOut[0] == 2 && mappingOut[1] == 1)
    1403             :         {
    1404           0 :             bSwapXY = true;
    1405             :         }
    1406           0 :         else if (mappingIn.size() >= 2 && mappingIn[0] == 2 &&
    1407           0 :                  mappingIn[1] == 1 && mappingOut.size() >= 2 &&
    1408           0 :                  mappingOut[0] == 1 && mappingOut[1] == 2)
    1409             :         {
    1410           0 :             bSwapXY = true;
    1411             :         }
    1412             :         else
    1413             :         {
    1414           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    1415             :                      "Unsupported axis transformation");
    1416             :         }
    1417           0 :     }
    1418             : 
    1419             :     ~AxisMappingCoordinateTransformation() override;
    1420             : 
    1421           0 :     OGRCoordinateTransformation *Clone() const override
    1422             :     {
    1423           0 :         return new AxisMappingCoordinateTransformation(*this);
    1424             :     }
    1425             : 
    1426           0 :     const OGRSpatialReference *GetSourceCS() const override
    1427             :     {
    1428           0 :         return nullptr;
    1429             :     }
    1430             : 
    1431           0 :     const OGRSpatialReference *GetTargetCS() const override
    1432             :     {
    1433           0 :         return nullptr;
    1434             :     }
    1435             : 
    1436           0 :     virtual int Transform(size_t nCount, double *x, double *y, double * /*z*/,
    1437             :                           double * /*t*/, int *pabSuccess) override
    1438             :     {
    1439           0 :         for (size_t i = 0; i < nCount; i++)
    1440             :         {
    1441           0 :             if (pabSuccess)
    1442           0 :                 pabSuccess[i] = true;
    1443           0 :             if (bSwapXY)
    1444           0 :                 std::swap(x[i], y[i]);
    1445             :         }
    1446           0 :         return true;
    1447             :     }
    1448             : 
    1449           0 :     virtual int TransformWithErrorCodes(size_t nCount, double *x, double *y,
    1450             :                                         double * /*z*/, double * /*t*/,
    1451             :                                         int *panErrorCodes) override
    1452             :     {
    1453           0 :         for (size_t i = 0; i < nCount; i++)
    1454             :         {
    1455           0 :             if (panErrorCodes)
    1456           0 :                 panErrorCodes[i] = 0;
    1457           0 :             if (bSwapXY)
    1458           0 :                 std::swap(x[i], y[i]);
    1459             :         }
    1460           0 :         return true;
    1461             :     }
    1462             : 
    1463           0 :     OGRCoordinateTransformation *GetInverse() const override
    1464             :     {
    1465           0 :         return std::make_unique<AxisMappingCoordinateTransformation>(bSwapXY)
    1466           0 :             .release();
    1467             :     }
    1468             : };
    1469             : 
    1470             : AxisMappingCoordinateTransformation::~AxisMappingCoordinateTransformation() =
    1471             :     default;
    1472             : 
    1473             : /************************************************************************/
    1474             : /*                         ApplySpatialFilter()                         */
    1475             : /************************************************************************/
    1476             : 
    1477        1174 : static void ApplySpatialFilter(OGRLayer *poLayer, OGRGeometry *poSpatialFilter,
    1478             :                                const OGRSpatialReference *poSpatSRS,
    1479             :                                const char *pszGeomField,
    1480             :                                const OGRSpatialReference *poSourceSRS)
    1481             : {
    1482        1174 :     if (poSpatialFilter == nullptr)
    1483        1166 :         return;
    1484             : 
    1485           8 :     std::unique_ptr<OGRGeometry> poSpatialFilterReprojected;
    1486           8 :     if (poSpatSRS)
    1487             :     {
    1488           4 :         poSpatialFilterReprojected.reset(poSpatialFilter->clone());
    1489           4 :         poSpatialFilterReprojected->assignSpatialReference(poSpatSRS);
    1490             :         const OGRSpatialReference *poSpatialFilterTargetSRS =
    1491           4 :             poSourceSRS ? poSourceSRS : poLayer->GetSpatialRef();
    1492           4 :         if (poSpatialFilterTargetSRS)
    1493             :         {
    1494             :             // When transforming the spatial filter from its spat_srs to the
    1495             :             // layer SRS, make sure to densify it sufficiently to avoid issues
    1496           4 :             constexpr double SEGMENT_DISTANCE_METRE = 10 * 1000;
    1497           4 :             if (poSpatSRS->IsGeographic())
    1498             :             {
    1499             :                 const double LENGTH_OF_ONE_DEGREE =
    1500           1 :                     poSpatSRS->GetSemiMajor(nullptr) * M_PI / 180.0;
    1501           1 :                 poSpatialFilterReprojected->segmentize(SEGMENT_DISTANCE_METRE /
    1502           1 :                                                        LENGTH_OF_ONE_DEGREE);
    1503             :             }
    1504           3 :             else if (poSpatSRS->IsProjected())
    1505             :             {
    1506           3 :                 poSpatialFilterReprojected->segmentize(
    1507             :                     SEGMENT_DISTANCE_METRE /
    1508           3 :                     poSpatSRS->GetLinearUnits(nullptr));
    1509             :             }
    1510           4 :             poSpatialFilterReprojected->transformTo(poSpatialFilterTargetSRS);
    1511             :         }
    1512             :         else
    1513           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    1514             :                      "cannot determine layer SRS for %s.",
    1515           0 :                      poLayer->GetDescription());
    1516             :     }
    1517             : 
    1518           8 :     if (pszGeomField != nullptr)
    1519             :     {
    1520             :         const int iGeomField =
    1521           1 :             poLayer->GetLayerDefn()->GetGeomFieldIndex(pszGeomField);
    1522           1 :         if (iGeomField >= 0)
    1523           1 :             poLayer->SetSpatialFilter(iGeomField,
    1524             :                                       poSpatialFilterReprojected
    1525           0 :                                           ? poSpatialFilterReprojected.get()
    1526           1 :                                           : poSpatialFilter);
    1527             :         else
    1528           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    1529             :                      "Cannot find geometry field %s.", pszGeomField);
    1530             :     }
    1531             :     else
    1532             :     {
    1533          11 :         poLayer->SetSpatialFilter(poSpatialFilterReprojected
    1534           4 :                                       ? poSpatialFilterReprojected.get()
    1535           7 :                                       : poSpatialFilter);
    1536             :     }
    1537             : }
    1538             : 
    1539             : /************************************************************************/
    1540             : /*                            GetFieldType()                            */
    1541             : /************************************************************************/
    1542             : 
    1543          12 : static int GetFieldType(const char *pszArg, int *pnSubFieldType)
    1544             : {
    1545          12 :     *pnSubFieldType = OFSTNone;
    1546          12 :     const char *pszOpenParenthesis = strchr(pszArg, '(');
    1547          12 :     const int nLengthBeforeParenthesis =
    1548          12 :         pszOpenParenthesis ? static_cast<int>(pszOpenParenthesis - pszArg)
    1549          11 :                            : static_cast<int>(strlen(pszArg));
    1550          72 :     for (int iType = 0; iType <= static_cast<int>(OFTMaxType); iType++)
    1551             :     {
    1552             :         const char *pszFieldTypeName =
    1553          72 :             OGRFieldDefn::GetFieldTypeName(static_cast<OGRFieldType>(iType));
    1554          72 :         if (EQUALN(pszArg, pszFieldTypeName, nLengthBeforeParenthesis) &&
    1555          12 :             pszFieldTypeName[nLengthBeforeParenthesis] == '\0')
    1556             :         {
    1557          12 :             if (pszOpenParenthesis != nullptr)
    1558             :             {
    1559           1 :                 *pnSubFieldType = -1;
    1560           2 :                 CPLString osArgSubType = pszOpenParenthesis + 1;
    1561           1 :                 if (!osArgSubType.empty() && osArgSubType.back() == ')')
    1562           1 :                     osArgSubType.pop_back();
    1563           2 :                 for (int iSubType = 0;
    1564           2 :                      iSubType <= static_cast<int>(OFSTMaxSubType); iSubType++)
    1565             :                 {
    1566             :                     const char *pszFieldSubTypeName =
    1567           2 :                         OGRFieldDefn::GetFieldSubTypeName(
    1568             :                             static_cast<OGRFieldSubType>(iSubType));
    1569           2 :                     if (EQUAL(pszFieldSubTypeName, osArgSubType))
    1570             :                     {
    1571           1 :                         *pnSubFieldType = iSubType;
    1572           1 :                         break;
    1573             :                     }
    1574             :                 }
    1575             :             }
    1576          12 :             return iType;
    1577             :         }
    1578             :     }
    1579           0 :     return -1;
    1580             : }
    1581             : 
    1582             : /************************************************************************/
    1583             : /*                            IsFieldType()                             */
    1584             : /************************************************************************/
    1585             : 
    1586           8 : static bool IsFieldType(const char *pszArg)
    1587             : {
    1588             :     int iSubType;
    1589           8 :     return GetFieldType(pszArg, &iSubType) >= 0 && iSubType >= 0;
    1590             : }
    1591             : 
    1592             : class GDALVectorTranslateWrappedDataset final : public GDALDataset
    1593             : {
    1594             :     std::unique_ptr<GDALDriver> m_poDriverToFree{};
    1595             :     GDALDataset *m_poBase = nullptr;
    1596             :     OGRSpatialReference *m_poOutputSRS = nullptr;
    1597             :     const bool m_bTransform = false;
    1598             : 
    1599             :     std::vector<std::unique_ptr<OGRLayer>> m_apoLayers{};
    1600             :     std::vector<std::unique_ptr<OGRLayer>> m_apoHiddenLayers{};
    1601             : 
    1602             :     GDALVectorTranslateWrappedDataset(GDALDataset *poBase,
    1603             :                                       OGRSpatialReference *poOutputSRS,
    1604             :                                       bool bTransform);
    1605             : 
    1606             :     CPL_DISALLOW_COPY_ASSIGN(GDALVectorTranslateWrappedDataset)
    1607             : 
    1608             :   public:
    1609           3 :     int GetLayerCount() const override
    1610             :     {
    1611           3 :         return static_cast<int>(m_apoLayers.size());
    1612             :     }
    1613             : 
    1614             :     OGRLayer *GetLayer(int nIdx) const override;
    1615             :     OGRLayer *GetLayerByName(const char *pszName) override;
    1616             : 
    1617             :     OGRLayer *ExecuteSQL(const char *pszStatement, OGRGeometry *poSpatialFilter,
    1618             :                          const char *pszDialect) override;
    1619             :     void ReleaseResultSet(OGRLayer *poResultsSet) override;
    1620             : 
    1621             :     static std::unique_ptr<GDALVectorTranslateWrappedDataset>
    1622             :     New(GDALDataset *poBase, OGRSpatialReference *poOutputSRS, bool bTransform);
    1623             : };
    1624             : 
    1625             : class GDALVectorTranslateWrappedLayer final : public OGRLayerDecorator
    1626             : {
    1627             :     std::vector<std::unique_ptr<OGRCoordinateTransformation>> m_apoCT{};
    1628             :     OGRFeatureDefn *m_poFDefn = nullptr;
    1629             : 
    1630             :     GDALVectorTranslateWrappedLayer(OGRLayer *poBaseLayer, bool bOwnBaseLayer);
    1631             :     std::unique_ptr<OGRFeature>
    1632             :     TranslateFeature(std::unique_ptr<OGRFeature> poSrcFeat);
    1633             : 
    1634             :     CPL_DISALLOW_COPY_ASSIGN(GDALVectorTranslateWrappedLayer)
    1635             : 
    1636             :   public:
    1637             :     ~GDALVectorTranslateWrappedLayer() override;
    1638             : 
    1639         379 :     const OGRFeatureDefn *GetLayerDefn() const override
    1640             :     {
    1641         379 :         return m_poFDefn;
    1642             :     }
    1643             : 
    1644             :     OGRFeature *GetNextFeature() override;
    1645             :     OGRFeature *GetFeature(GIntBig nFID) override;
    1646             : 
    1647             :     static std::unique_ptr<GDALVectorTranslateWrappedLayer>
    1648             :     New(OGRLayer *poBaseLayer, bool bOwnBaseLayer,
    1649             :         OGRSpatialReference *poOutputSRS, bool bTransform);
    1650             : };
    1651             : 
    1652          79 : GDALVectorTranslateWrappedLayer::GDALVectorTranslateWrappedLayer(
    1653          79 :     OGRLayer *poBaseLayer, bool bOwnBaseLayer)
    1654             :     : OGRLayerDecorator(poBaseLayer, bOwnBaseLayer),
    1655          79 :       m_apoCT(poBaseLayer->GetLayerDefn()->GetGeomFieldCount())
    1656             : {
    1657          79 : }
    1658             : 
    1659             : std::unique_ptr<GDALVectorTranslateWrappedLayer>
    1660          79 : GDALVectorTranslateWrappedLayer::New(OGRLayer *poBaseLayer, bool bOwnBaseLayer,
    1661             :                                      OGRSpatialReference *poOutputSRS,
    1662             :                                      bool bTransform)
    1663             : {
    1664             :     auto poNew = std::unique_ptr<GDALVectorTranslateWrappedLayer>(
    1665         158 :         new GDALVectorTranslateWrappedLayer(poBaseLayer, bOwnBaseLayer));
    1666          79 :     poNew->m_poFDefn = poBaseLayer->GetLayerDefn()->Clone();
    1667          79 :     poNew->m_poFDefn->Reference();
    1668          79 :     if (!poOutputSRS)
    1669           0 :         return poNew;
    1670             : 
    1671          94 :     for (int i = 0; i < poNew->m_poFDefn->GetGeomFieldCount(); i++)
    1672             :     {
    1673          15 :         if (bTransform)
    1674             :         {
    1675           0 :             const OGRSpatialReference *poSourceSRS = poBaseLayer->GetLayerDefn()
    1676           0 :                                                          ->GetGeomFieldDefn(i)
    1677           0 :                                                          ->GetSpatialRef();
    1678           0 :             if (poSourceSRS == nullptr)
    1679             :             {
    1680           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1681             :                          "Layer %s has no source SRS for geometry field %s",
    1682           0 :                          poBaseLayer->GetName(),
    1683           0 :                          poBaseLayer->GetLayerDefn()
    1684           0 :                              ->GetGeomFieldDefn(i)
    1685             :                              ->GetNameRef());
    1686           0 :                 return nullptr;
    1687             :             }
    1688             :             else
    1689             :             {
    1690           0 :                 poNew->m_apoCT[i] =
    1691           0 :                     std::unique_ptr<OGRCoordinateTransformation>(
    1692             :                         OGRCreateCoordinateTransformation(poSourceSRS,
    1693           0 :                                                           poOutputSRS));
    1694           0 :                 if (poNew->m_apoCT[i] == nullptr)
    1695             :                 {
    1696           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1697             :                              "Failed to create coordinate transformation "
    1698             :                              "between the\n"
    1699             :                              "following coordinate systems.  This may be "
    1700             :                              "because they\n"
    1701             :                              "are not transformable.");
    1702             : 
    1703           0 :                     char *pszWKT = nullptr;
    1704           0 :                     poSourceSRS->exportToPrettyWkt(&pszWKT, FALSE);
    1705           0 :                     CPLError(CE_Failure, CPLE_AppDefined, "Source:\n%s",
    1706             :                              pszWKT);
    1707           0 :                     CPLFree(pszWKT);
    1708             : 
    1709           0 :                     poOutputSRS->exportToPrettyWkt(&pszWKT, FALSE);
    1710           0 :                     CPLError(CE_Failure, CPLE_AppDefined, "Target:\n%s",
    1711             :                              pszWKT);
    1712           0 :                     CPLFree(pszWKT);
    1713             : 
    1714           0 :                     return nullptr;
    1715             :                 }
    1716             :             }
    1717             :         }
    1718          15 :         poNew->m_poFDefn->GetGeomFieldDefn(i)->SetSpatialRef(poOutputSRS);
    1719             :     }
    1720             : 
    1721          79 :     return poNew;
    1722             : }
    1723             : 
    1724         158 : GDALVectorTranslateWrappedLayer::~GDALVectorTranslateWrappedLayer()
    1725             : {
    1726          79 :     if (m_poFDefn)
    1727          79 :         m_poFDefn->Release();
    1728         158 : }
    1729             : 
    1730         641 : OGRFeature *GDALVectorTranslateWrappedLayer::GetNextFeature()
    1731             : {
    1732        1282 :     return TranslateFeature(
    1733        1282 :                std::unique_ptr<OGRFeature>(OGRLayerDecorator::GetNextFeature()))
    1734        1282 :         .release();
    1735             : }
    1736             : 
    1737           0 : OGRFeature *GDALVectorTranslateWrappedLayer::GetFeature(GIntBig nFID)
    1738             : {
    1739           0 :     return TranslateFeature(
    1740           0 :                std::unique_ptr<OGRFeature>(OGRLayerDecorator::GetFeature(nFID)))
    1741           0 :         .release();
    1742             : }
    1743             : 
    1744         641 : std::unique_ptr<OGRFeature> GDALVectorTranslateWrappedLayer::TranslateFeature(
    1745             :     std::unique_ptr<OGRFeature> poSrcFeat)
    1746             : {
    1747         641 :     if (poSrcFeat == nullptr)
    1748          93 :         return nullptr;
    1749        1096 :     auto poNewFeat = std::make_unique<OGRFeature>(m_poFDefn);
    1750         548 :     poNewFeat->SetFrom(poSrcFeat.get());
    1751         548 :     poNewFeat->SetFID(poSrcFeat->GetFID());
    1752         563 :     for (int i = 0; i < poNewFeat->GetGeomFieldCount(); i++)
    1753             :     {
    1754          15 :         OGRGeometry *poGeom = poNewFeat->GetGeomFieldRef(i);
    1755          15 :         if (poGeom)
    1756             :         {
    1757          13 :             if (m_apoCT[i])
    1758           0 :                 poGeom->transform(m_apoCT[i].get());
    1759          13 :             poGeom->assignSpatialReference(
    1760          13 :                 m_poFDefn->GetGeomFieldDefn(i)->GetSpatialRef());
    1761             :         }
    1762             :     }
    1763         548 :     return poNewFeat;
    1764             : }
    1765             : 
    1766           3 : GDALVectorTranslateWrappedDataset::GDALVectorTranslateWrappedDataset(
    1767           3 :     GDALDataset *poBase, OGRSpatialReference *poOutputSRS, bool bTransform)
    1768           3 :     : m_poBase(poBase), m_poOutputSRS(poOutputSRS), m_bTransform(bTransform)
    1769             : {
    1770           3 :     SetDescription(poBase->GetDescription());
    1771           3 :     if (poBase->GetDriver())
    1772             :     {
    1773           6 :         auto poNewDriver = std::make_unique<GDALDriver>();
    1774           3 :         poNewDriver->SetDescription(poBase->GetDriver()->GetDescription());
    1775           3 :         m_poDriverToFree = std::move(poNewDriver);
    1776             :     }
    1777           3 : }
    1778             : 
    1779             : std::unique_ptr<GDALVectorTranslateWrappedDataset>
    1780           3 : GDALVectorTranslateWrappedDataset::New(GDALDataset *poBase,
    1781             :                                        OGRSpatialReference *poOutputSRS,
    1782             :                                        bool bTransform)
    1783             : {
    1784             :     auto poNew = std::unique_ptr<GDALVectorTranslateWrappedDataset>(
    1785           6 :         new GDALVectorTranslateWrappedDataset(poBase, poOutputSRS, bTransform));
    1786          70 :     for (int i = 0; i < poBase->GetLayerCount(); i++)
    1787             :     {
    1788             :         auto poLayer = GDALVectorTranslateWrappedLayer::New(
    1789             :             poBase->GetLayer(i), /* bOwnBaseLayer = */ false, poOutputSRS,
    1790          67 :             bTransform);
    1791          67 :         if (poLayer == nullptr)
    1792             :         {
    1793           0 :             return nullptr;
    1794             :         }
    1795          67 :         poNew->m_apoLayers.push_back(std::move(poLayer));
    1796             :     }
    1797           3 :     return poNew;
    1798             : }
    1799             : 
    1800           0 : OGRLayer *GDALVectorTranslateWrappedDataset::GetLayer(int i) const
    1801             : {
    1802           0 :     if (i < 0 || i >= static_cast<int>(m_apoLayers.size()))
    1803           0 :         return nullptr;
    1804           0 :     return m_apoLayers[i].get();
    1805             : }
    1806             : 
    1807          68 : OGRLayer *GDALVectorTranslateWrappedDataset::GetLayerByName(const char *pszName)
    1808             : {
    1809        1008 :     for (const auto &poLayer : m_apoLayers)
    1810             :     {
    1811        1008 :         if (strcmp(poLayer->GetName(), pszName) == 0)
    1812          68 :             return poLayer.get();
    1813             :     }
    1814           0 :     for (const auto &poLayer : m_apoHiddenLayers)
    1815             :     {
    1816           0 :         if (strcmp(poLayer->GetName(), pszName) == 0)
    1817           0 :             return poLayer.get();
    1818             :     }
    1819           0 :     for (const auto &poLayer : m_apoLayers)
    1820             :     {
    1821           0 :         if (EQUAL(poLayer->GetName(), pszName))
    1822           0 :             return poLayer.get();
    1823             :     }
    1824           0 :     for (const auto &poLayer : m_apoHiddenLayers)
    1825             :     {
    1826           0 :         if (EQUAL(poLayer->GetName(), pszName))
    1827           0 :             return poLayer.get();
    1828             :     }
    1829             : 
    1830           0 :     OGRLayer *poLayer = m_poBase->GetLayerByName(pszName);
    1831           0 :     if (poLayer == nullptr)
    1832           0 :         return nullptr;
    1833             : 
    1834             :     auto poNewLayer = GDALVectorTranslateWrappedLayer::New(
    1835           0 :         poLayer, /* bOwnBaseLayer = */ false, m_poOutputSRS, m_bTransform);
    1836           0 :     if (poNewLayer == nullptr)
    1837           0 :         return nullptr;
    1838             : 
    1839             :     // Replicate source dataset behavior: if the fact of calling
    1840             :     // GetLayerByName() on a initially hidden layer makes it visible through
    1841             :     // GetLayerCount()/GetLayer(), do the same. Otherwise we are going to
    1842             :     // maintain it hidden as well.
    1843           0 :     for (int i = 0; i < m_poBase->GetLayerCount(); i++)
    1844             :     {
    1845           0 :         if (m_poBase->GetLayer(i) == poLayer)
    1846             :         {
    1847           0 :             m_apoLayers.push_back(std::move(poNewLayer));
    1848           0 :             return m_apoLayers.back().get();
    1849             :         }
    1850             :     }
    1851           0 :     m_apoHiddenLayers.push_back(std::move(poNewLayer));
    1852           0 :     return m_apoHiddenLayers.back().get();
    1853             : }
    1854             : 
    1855             : OGRLayer *
    1856          12 : GDALVectorTranslateWrappedDataset::ExecuteSQL(const char *pszStatement,
    1857             :                                               OGRGeometry *poSpatialFilter,
    1858             :                                               const char *pszDialect)
    1859             : {
    1860             :     OGRLayer *poLayer =
    1861          12 :         m_poBase->ExecuteSQL(pszStatement, poSpatialFilter, pszDialect);
    1862          12 :     if (poLayer == nullptr)
    1863           0 :         return nullptr;
    1864          12 :     return GDALVectorTranslateWrappedLayer::New(
    1865          12 :                poLayer, /* bOwnBaseLayer = */ true, m_poOutputSRS, m_bTransform)
    1866          12 :         .release();
    1867             : }
    1868             : 
    1869          12 : void GDALVectorTranslateWrappedDataset::ReleaseResultSet(OGRLayer *poResultsSet)
    1870             : {
    1871          12 :     delete poResultsSet;
    1872          12 : }
    1873             : 
    1874             : /************************************************************************/
    1875             : /*                    OGR2OGRSpatialReferenceHolder                     */
    1876             : /************************************************************************/
    1877             : 
    1878             : class OGR2OGRSpatialReferenceHolder
    1879             : {
    1880             :     OGRSpatialReference *m_poSRS = nullptr;
    1881             : 
    1882             :     CPL_DISALLOW_COPY_ASSIGN(OGR2OGRSpatialReferenceHolder)
    1883             : 
    1884             :   public:
    1885             :     OGR2OGRSpatialReferenceHolder() = default;
    1886             : 
    1887        1006 :     ~OGR2OGRSpatialReferenceHolder()
    1888        1006 :     {
    1889        1006 :         if (m_poSRS)
    1890         147 :             m_poSRS->Release();
    1891        1006 :     }
    1892             : 
    1893         147 :     void assignNoRefIncrease(OGRSpatialReference *poSRS)
    1894             :     {
    1895         147 :         CPLAssert(m_poSRS == nullptr);
    1896         147 :         m_poSRS = poSRS;
    1897         147 :     }
    1898             : 
    1899        2416 :     OGRSpatialReference *get()
    1900             :     {
    1901        2416 :         return m_poSRS;
    1902             :     }
    1903             : };
    1904             : 
    1905             : /************************************************************************/
    1906             : /*                   GDALVectorTranslateCreateCopy()                    */
    1907             : /************************************************************************/
    1908             : 
    1909             : static GDALDataset *
    1910          22 : GDALVectorTranslateCreateCopy(GDALDriver *poDriver, const char *pszDest,
    1911             :                               GDALDataset *poDS,
    1912             :                               const GDALVectorTranslateOptions *psOptions)
    1913             : {
    1914          22 :     const char *const szErrorMsg = "%s not supported by this output driver";
    1915             : 
    1916          22 :     if (psOptions->bSkipFailures)
    1917             :     {
    1918           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-skipfailures");
    1919           0 :         return nullptr;
    1920             :     }
    1921          22 :     if (psOptions->nLayerTransaction >= 0)
    1922             :     {
    1923           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg,
    1924             :                  "-lyr_transaction or -ds_transaction");
    1925           0 :         return nullptr;
    1926             :     }
    1927          22 :     if (psOptions->nFIDToFetch >= 0)
    1928             :     {
    1929           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-fid");
    1930           0 :         return nullptr;
    1931             :     }
    1932          22 :     if (!psOptions->aosLCO.empty())
    1933             :     {
    1934           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-lco");
    1935           0 :         return nullptr;
    1936             :     }
    1937          22 :     if (psOptions->bAddMissingFields)
    1938             :     {
    1939           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-addfields");
    1940           0 :         return nullptr;
    1941             :     }
    1942          22 :     if (!psOptions->osSourceSRSDef.empty())
    1943             :     {
    1944           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-s_srs");
    1945           0 :         return nullptr;
    1946             :     }
    1947          22 :     if (!psOptions->bExactFieldNameMatch)
    1948             :     {
    1949           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg,
    1950             :                  "-relaxedFieldNameMatch");
    1951           0 :         return nullptr;
    1952             :     }
    1953          22 :     if (!psOptions->osNewLayerName.empty())
    1954             :     {
    1955           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-nln");
    1956           0 :         return nullptr;
    1957             :     }
    1958          22 :     if (psOptions->bSelFieldsSet)
    1959             :     {
    1960           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-select");
    1961           0 :         return nullptr;
    1962             :     }
    1963          22 :     if (!psOptions->osSQLStatement.empty())
    1964             :     {
    1965           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-sql");
    1966           0 :         return nullptr;
    1967             :     }
    1968          22 :     if (!psOptions->osDialect.empty())
    1969             :     {
    1970           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-dialect");
    1971           0 :         return nullptr;
    1972             :     }
    1973          22 :     if (psOptions->eGType != GEOMTYPE_UNCHANGED ||
    1974          22 :         psOptions->eGeomTypeConversion != GTC_DEFAULT)
    1975             :     {
    1976           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-nlt");
    1977           0 :         return nullptr;
    1978             :     }
    1979          22 :     if (!psOptions->aosFieldTypesToString.empty())
    1980             :     {
    1981           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg,
    1982             :                  "-fieldTypeToString");
    1983           0 :         return nullptr;
    1984             :     }
    1985          22 :     if (!psOptions->aosMapFieldType.empty())
    1986             :     {
    1987           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-mapFieldType");
    1988           0 :         return nullptr;
    1989             :     }
    1990          22 :     if (psOptions->bUnsetFieldWidth)
    1991             :     {
    1992           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-unsetFieldWidth");
    1993           0 :         return nullptr;
    1994             :     }
    1995          22 :     if (psOptions->bWrapDateline)
    1996             :     {
    1997           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-wrapdateline");
    1998           0 :         return nullptr;
    1999             :     }
    2000          22 :     if (psOptions->bClipSrc)
    2001             :     {
    2002           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-clipsrc");
    2003           0 :         return nullptr;
    2004             :     }
    2005          22 :     if (!psOptions->osClipSrcSQL.empty())
    2006             :     {
    2007           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-clipsrcsql");
    2008           0 :         return nullptr;
    2009             :     }
    2010          22 :     if (!psOptions->osClipSrcLayer.empty())
    2011             :     {
    2012           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-clipsrclayer");
    2013           0 :         return nullptr;
    2014             :     }
    2015          22 :     if (!psOptions->osClipSrcWhere.empty())
    2016             :     {
    2017           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-clipsrcwhere");
    2018           0 :         return nullptr;
    2019             :     }
    2020          22 :     if (!psOptions->osClipDstDS.empty() || psOptions->poClipDst)
    2021             :     {
    2022           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-clipdst");
    2023           0 :         return nullptr;
    2024             :     }
    2025          22 :     if (!psOptions->osClipDstSQL.empty())
    2026             :     {
    2027           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-clipdstsql");
    2028           0 :         return nullptr;
    2029             :     }
    2030          22 :     if (!psOptions->osClipDstLayer.empty())
    2031             :     {
    2032           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-clipdstlayer");
    2033           0 :         return nullptr;
    2034             :     }
    2035          22 :     if (!psOptions->osClipDstWhere.empty())
    2036             :     {
    2037           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-clipdstwhere");
    2038           0 :         return nullptr;
    2039             :     }
    2040          22 :     if (psOptions->bSplitListFields)
    2041             :     {
    2042           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-splitlistfields");
    2043           0 :         return nullptr;
    2044             :     }
    2045          22 :     if (psOptions->nMaxSplitListSubFields >= 0)
    2046             :     {
    2047           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-maxsubfields");
    2048           0 :         return nullptr;
    2049             :     }
    2050          22 :     if (psOptions->bExplodeCollections)
    2051             :     {
    2052           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg,
    2053             :                  "-explodecollections");
    2054           0 :         return nullptr;
    2055             :     }
    2056          22 :     if (!psOptions->osZField.empty())
    2057             :     {
    2058           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-zfield");
    2059           0 :         return nullptr;
    2060             :     }
    2061          22 :     if (!psOptions->asGCPs.empty())
    2062             :     {
    2063           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-gcp");
    2064           0 :         return nullptr;
    2065             :     }
    2066          22 :     if (!psOptions->aosFieldMap.empty())
    2067             :     {
    2068           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-fieldmap");
    2069           0 :         return nullptr;
    2070             :     }
    2071          22 :     if (psOptions->bForceNullable)
    2072             :     {
    2073           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-forceNullable");
    2074           0 :         return nullptr;
    2075             :     }
    2076          22 :     if (psOptions->bResolveDomains)
    2077             :     {
    2078           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-forceNullable");
    2079           0 :         return nullptr;
    2080             :     }
    2081          22 :     if (psOptions->bEmptyStrAsNull)
    2082             :     {
    2083           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-emptyStrAsNull");
    2084           0 :         return nullptr;
    2085             :     }
    2086          22 :     if (psOptions->bUnsetDefault)
    2087             :     {
    2088           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-unsetDefault");
    2089           0 :         return nullptr;
    2090             :     }
    2091          22 :     if (psOptions->bUnsetFid)
    2092             :     {
    2093           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-unsetFid");
    2094           0 :         return nullptr;
    2095             :     }
    2096          22 :     if (!psOptions->bCopyMD)
    2097             :     {
    2098           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-nomd");
    2099           0 :         return nullptr;
    2100             :     }
    2101          22 :     if (!psOptions->bNativeData)
    2102             :     {
    2103           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-noNativeData");
    2104           0 :         return nullptr;
    2105             :     }
    2106          22 :     if (psOptions->nLimit >= 0)
    2107             :     {
    2108           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-limit");
    2109           0 :         return nullptr;
    2110             :     }
    2111          22 :     if (!psOptions->aosMetadataOptions.empty())
    2112             :     {
    2113           0 :         CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-mo");
    2114           0 :         return nullptr;
    2115             :     }
    2116             : 
    2117          22 :     GDALDataset *poWrkSrcDS = poDS;
    2118          22 :     std::unique_ptr<GDALDataset> poWrkSrcDSToFree;
    2119          22 :     OGR2OGRSpatialReferenceHolder oOutputSRSHolder;
    2120             : 
    2121          22 :     if (!psOptions->osOutputSRSDef.empty())
    2122             :     {
    2123           3 :         oOutputSRSHolder.assignNoRefIncrease(new OGRSpatialReference());
    2124           3 :         oOutputSRSHolder.get()->SetAxisMappingStrategy(
    2125             :             OAMS_TRADITIONAL_GIS_ORDER);
    2126           3 :         if (oOutputSRSHolder.get()->SetFromUserInput(
    2127           3 :                 psOptions->osOutputSRSDef.c_str()) != OGRERR_NONE)
    2128             :         {
    2129           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2130             :                      "Failed to process SRS definition: %s",
    2131             :                      psOptions->osOutputSRSDef.c_str());
    2132           0 :             return nullptr;
    2133             :         }
    2134           3 :         oOutputSRSHolder.get()->SetCoordinateEpoch(
    2135           3 :             psOptions->dfOutputCoordinateEpoch);
    2136             : 
    2137           6 :         poWrkSrcDSToFree = GDALVectorTranslateWrappedDataset::New(
    2138           6 :             poDS, oOutputSRSHolder.get(), psOptions->bTransform);
    2139           3 :         if (poWrkSrcDSToFree == nullptr)
    2140           0 :             return nullptr;
    2141           3 :         poWrkSrcDS = poWrkSrcDSToFree.get();
    2142             :     }
    2143             : 
    2144          22 :     if (!psOptions->osWHERE.empty())
    2145             :     {
    2146             :         // Hack for GMLAS driver
    2147           0 :         if (EQUAL(poDriver->GetDescription(), "GMLAS"))
    2148             :         {
    2149           0 :             if (psOptions->aosLayers.empty())
    2150             :             {
    2151           0 :                 CPLError(CE_Failure, CPLE_NotSupported,
    2152             :                          "-where not supported by this output driver "
    2153             :                          "without explicit layer name(s)");
    2154           0 :                 return nullptr;
    2155             :             }
    2156             :             else
    2157             :             {
    2158           0 :                 for (const char *pszLayer : psOptions->aosLayers)
    2159             :                 {
    2160           0 :                     OGRLayer *poSrcLayer = poDS->GetLayerByName(pszLayer);
    2161           0 :                     if (poSrcLayer != nullptr)
    2162             :                     {
    2163           0 :                         poSrcLayer->SetAttributeFilter(
    2164           0 :                             psOptions->osWHERE.c_str());
    2165             :                     }
    2166             :                 }
    2167             :             }
    2168             :         }
    2169             :         else
    2170             :         {
    2171           0 :             CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg, "-where");
    2172           0 :             return nullptr;
    2173             :         }
    2174             :     }
    2175             : 
    2176          22 :     if (psOptions->poSpatialFilter)
    2177             :     {
    2178           0 :         for (int i = 0; i < poWrkSrcDS->GetLayerCount(); ++i)
    2179             :         {
    2180           0 :             OGRLayer *poSrcLayer = poWrkSrcDS->GetLayer(i);
    2181           0 :             if (poSrcLayer &&
    2182           0 :                 poSrcLayer->GetLayerDefn()->GetGeomFieldCount() > 0 &&
    2183           0 :                 (psOptions->aosLayers.empty() ||
    2184           0 :                  psOptions->aosLayers.FindString(poSrcLayer->GetName()) >= 0))
    2185             :             {
    2186           0 :                 if (psOptions->bGeomFieldSet)
    2187             :                 {
    2188             :                     const int iGeomField =
    2189           0 :                         poSrcLayer->GetLayerDefn()->GetGeomFieldIndex(
    2190           0 :                             psOptions->osGeomField.c_str());
    2191           0 :                     if (iGeomField >= 0)
    2192           0 :                         poSrcLayer->SetSpatialFilter(
    2193           0 :                             iGeomField, psOptions->poSpatialFilter.get());
    2194             :                     else
    2195           0 :                         CPLError(CE_Warning, CPLE_AppDefined,
    2196             :                                  "Cannot find geometry field %s in layer %s. "
    2197             :                                  "Applying to first geometry field",
    2198             :                                  psOptions->osGeomField.c_str(),
    2199           0 :                                  poSrcLayer->GetName());
    2200             :                 }
    2201             :                 else
    2202             :                 {
    2203           0 :                     poSrcLayer->SetSpatialFilter(
    2204           0 :                         psOptions->poSpatialFilter.get());
    2205             :                 }
    2206             :             }
    2207             :         }
    2208             :     }
    2209             : 
    2210          44 :     CPLStringList aosDSCO(psOptions->aosDSCO);
    2211          22 :     if (!psOptions->aosLayers.empty())
    2212             :     {
    2213             :         // Hack for GMLAS driver
    2214           0 :         if (EQUAL(poDriver->GetDescription(), "GMLAS"))
    2215             :         {
    2216           0 :             CPLString osLayers;
    2217           0 :             for (const char *pszLayer : psOptions->aosLayers)
    2218             :             {
    2219           0 :                 if (!osLayers.empty())
    2220           0 :                     osLayers += ",";
    2221           0 :                 osLayers += pszLayer;
    2222             :             }
    2223           0 :             aosDSCO.SetNameValue("LAYERS", osLayers);
    2224             :         }
    2225             :         else
    2226             :         {
    2227           0 :             CPLError(CE_Failure, CPLE_NotSupported, szErrorMsg,
    2228             :                      "Specifying layers");
    2229           0 :             return nullptr;
    2230             :         }
    2231             :     }
    2232             : 
    2233             :     // Hack for GMLAS driver (this speed up deletion by avoiding the GML
    2234             :     // driver to try parsing a pre-existing file). Could be potentially
    2235             :     // removed if the GML driver implemented fast dataset opening (ie
    2236             :     // without parsing) and GetFileList()
    2237          22 :     if (EQUAL(poDriver->GetDescription(), "GMLAS"))
    2238             :     {
    2239          22 :         GDALDriverH hIdentifyingDriver = GDALIdentifyDriver(pszDest, nullptr);
    2240          23 :         if (hIdentifyingDriver != nullptr &&
    2241           1 :             EQUAL(GDALGetDescription(hIdentifyingDriver), "GML"))
    2242             :         {
    2243           0 :             VSIUnlink(pszDest);
    2244           0 :             VSIUnlink(CPLResetExtensionSafe(pszDest, "gfs").c_str());
    2245             :         }
    2246             :     }
    2247             : 
    2248             :     GDALDataset *poOut =
    2249          22 :         poDriver->CreateCopy(pszDest, poWrkSrcDS, FALSE, aosDSCO.List(),
    2250          22 :                              psOptions->pfnProgress, psOptions->pProgressData);
    2251             : 
    2252          22 :     return poOut;
    2253             : }
    2254             : 
    2255             : /************************************************************************/
    2256             : /*                         CopyRelationships()                          */
    2257             : /************************************************************************/
    2258             : 
    2259         983 : static void CopyRelationships(GDALDataset *poODS, GDALDataset *poDS)
    2260             : {
    2261         983 :     if (!poODS->GetDriver()->GetMetadataItem(GDAL_DCAP_CREATE_RELATIONSHIP))
    2262         978 :         return;
    2263             : 
    2264         397 :     const auto aosRelationshipNames = poDS->GetRelationshipNames();
    2265         397 :     if (aosRelationshipNames.empty())
    2266         392 :         return;
    2267             : 
    2268             :     // Collect target layer names
    2269          10 :     std::set<std::string> oSetDestLayerNames;
    2270          30 :     for (const auto &poLayer : poDS->GetLayers())
    2271             :     {
    2272          25 :         oSetDestLayerNames.insert(poLayer->GetName());
    2273             :     }
    2274             : 
    2275             :     // Iterate over all source relationships
    2276          20 :     for (const auto &osRelationshipName : aosRelationshipNames)
    2277             :     {
    2278             :         const auto poSrcRelationship =
    2279          15 :             poDS->GetRelationship(osRelationshipName);
    2280          15 :         if (!poSrcRelationship)
    2281           0 :             continue;
    2282             : 
    2283             :         // Skip existing relationship of the same name
    2284          15 :         if (poODS->GetRelationship(osRelationshipName))
    2285           0 :             continue;
    2286             : 
    2287          15 :         bool canAdd = true;
    2288          15 :         const auto &osLeftTableName = poSrcRelationship->GetLeftTableName();
    2289          30 :         if (!osLeftTableName.empty() &&
    2290          15 :             !cpl::contains(oSetDestLayerNames, osLeftTableName))
    2291             :         {
    2292           1 :             CPLDebug("GDALVectorTranslate",
    2293             :                      "Skipping relationship %s because its left table (%s) "
    2294             :                      "does not exist in target dataset",
    2295             :                      osRelationshipName.c_str(), osLeftTableName.c_str());
    2296           1 :             canAdd = false;
    2297             :         }
    2298             : 
    2299          15 :         const auto &osRightTableName = poSrcRelationship->GetRightTableName();
    2300          30 :         if (!osRightTableName.empty() &&
    2301          15 :             !cpl::contains(oSetDestLayerNames, osRightTableName))
    2302             :         {
    2303           0 :             CPLDebug("GDALVectorTranslate",
    2304             :                      "Skipping relationship %s because its right table (%s) "
    2305             :                      "does not exist in target dataset",
    2306             :                      osRelationshipName.c_str(), osRightTableName.c_str());
    2307           0 :             canAdd = false;
    2308             :         }
    2309             : 
    2310             :         const auto &osMappingTableName =
    2311          15 :             poSrcRelationship->GetMappingTableName();
    2312          21 :         if (!osMappingTableName.empty() &&
    2313           6 :             !cpl::contains(oSetDestLayerNames, osMappingTableName))
    2314             :         {
    2315           0 :             CPLDebug("GDALVectorTranslate",
    2316             :                      "Skipping relationship %s because its mapping table (%s) "
    2317             :                      "does not exist in target dataset",
    2318             :                      osRelationshipName.c_str(), osMappingTableName.c_str());
    2319           0 :             canAdd = false;
    2320             :         }
    2321             : 
    2322          15 :         if (canAdd)
    2323             :         {
    2324          28 :             std::string osFailureReason;
    2325          14 :             if (!poODS->AddRelationship(
    2326          14 :                     std::make_unique<GDALRelationship>(*poSrcRelationship),
    2327          14 :                     osFailureReason))
    2328             :             {
    2329           3 :                 CPLDebug("GDALVectorTranslate",
    2330             :                          "Cannot add relationship %s: %s",
    2331             :                          osRelationshipName.c_str(), osFailureReason.c_str());
    2332             :             }
    2333             :         }
    2334             :     }
    2335             : }
    2336             : 
    2337             : /************************************************************************/
    2338             : /*                        GDALVectorTranslate()                         */
    2339             : /************************************************************************/
    2340             : /**
    2341             :  * Converts vector data between file formats.
    2342             :  *
    2343             :  * This is the equivalent of the <a href="/programs/ogr2ogr.html">ogr2ogr</a>
    2344             :  * utility.
    2345             :  *
    2346             :  * GDALVectorTranslateOptions* must be allocated and freed with
    2347             :  * GDALVectorTranslateOptionsNew() and GDALVectorTranslateOptionsFree()
    2348             :  * respectively. pszDest and hDstDS cannot be used at the same time.
    2349             :  *
    2350             :  * @param pszDest the destination dataset path or NULL.
    2351             :  * @param hDstDS the destination dataset or NULL.
    2352             :  * @param nSrcCount the number of input datasets (only 1 supported currently)
    2353             :  * @param pahSrcDS the list of input datasets.
    2354             :  * @param psOptionsIn the options struct returned by
    2355             :  * GDALVectorTranslateOptionsNew() or NULL.
    2356             :  * @param pbUsageError pointer to a integer output variable to store if any
    2357             :  * usage error has occurred, or NULL.
    2358             :  * @return the output dataset (new dataset that must be closed using
    2359             :  * GDALClose(), or hDstDS is not NULL) or NULL in case of error.
    2360             :  *
    2361             :  * @since GDAL 2.1
    2362             :  */
    2363             : 
    2364        1030 : GDALDatasetH GDALVectorTranslate(const char *pszDest, GDALDatasetH hDstDS,
    2365             :                                  int nSrcCount, GDALDatasetH *pahSrcDS,
    2366             :                                  const GDALVectorTranslateOptions *psOptionsIn,
    2367             :                                  int *pbUsageError)
    2368             : 
    2369             : {
    2370        1030 :     if (pszDest == nullptr && hDstDS == nullptr)
    2371             :     {
    2372           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2373             :                  "pszDest == NULL && hDstDS == NULL");
    2374             : 
    2375           0 :         if (pbUsageError)
    2376           0 :             *pbUsageError = TRUE;
    2377           0 :         return nullptr;
    2378             :     }
    2379        1030 :     if (nSrcCount != 1)
    2380             :     {
    2381           0 :         CPLError(CE_Failure, CPLE_AppDefined, "nSrcCount != 1");
    2382             : 
    2383           0 :         if (pbUsageError)
    2384           0 :             *pbUsageError = TRUE;
    2385           0 :         return nullptr;
    2386             :     }
    2387             : 
    2388        1030 :     GDALDatasetH hSrcDS = pahSrcDS[0];
    2389        1030 :     if (hSrcDS == nullptr)
    2390             :     {
    2391           0 :         CPLError(CE_Failure, CPLE_AppDefined, "hSrcDS == NULL");
    2392             : 
    2393           0 :         if (pbUsageError)
    2394           0 :             *pbUsageError = TRUE;
    2395           0 :         return nullptr;
    2396             :     }
    2397             : 
    2398             :     auto psOptions =
    2399             :         psOptionsIn ? std::make_unique<GDALVectorTranslateOptions>(*psOptionsIn)
    2400        2060 :                     : std::make_unique<GDALVectorTranslateOptions>();
    2401             : 
    2402        1030 :     bool bAppend = false;
    2403        1030 :     bool bUpdate = false;
    2404        1030 :     bool bOverwrite = false;
    2405             : 
    2406        1030 :     if (psOptions->eAccessMode == ACCESS_UPDATE)
    2407             :     {
    2408           5 :         bUpdate = true;
    2409             :     }
    2410        1025 :     else if (psOptions->eAccessMode == ACCESS_APPEND)
    2411             :     {
    2412          44 :         bAppend = true;
    2413          44 :         bUpdate = true;
    2414             :     }
    2415         981 :     else if (psOptions->eAccessMode == ACCESS_OVERWRITE)
    2416             :     {
    2417          18 :         bOverwrite = true;
    2418          18 :         bUpdate = true;
    2419             :     }
    2420         963 :     else if (hDstDS != nullptr)
    2421             :     {
    2422           9 :         bUpdate = true;
    2423             :     }
    2424             : 
    2425        1030 :     if (psOptions->bPreserveFID && psOptions->bExplodeCollections)
    2426             :     {
    2427           1 :         CPLError(CE_Failure, CPLE_IllegalArg,
    2428             :                  "cannot use -preserve_fid and -explodecollections at the same "
    2429             :                  "time.");
    2430           1 :         if (pbUsageError)
    2431           1 :             *pbUsageError = TRUE;
    2432           1 :         return nullptr;
    2433             :     }
    2434             : 
    2435        1029 :     if (!psOptions->aosFieldMap.empty() && !bAppend)
    2436             :     {
    2437           0 :         CPLError(CE_Failure, CPLE_IllegalArg,
    2438             :                  "if -fieldmap is specified, -append must also be specified");
    2439           0 :         if (pbUsageError)
    2440           0 :             *pbUsageError = TRUE;
    2441           0 :         return nullptr;
    2442             :     }
    2443             : 
    2444        1029 :     if (!psOptions->aosFieldMap.empty() && psOptions->bAddMissingFields)
    2445             :     {
    2446           0 :         CPLError(CE_Failure, CPLE_IllegalArg,
    2447             :                  "if -addfields is specified, -fieldmap cannot be used.");
    2448           0 :         if (pbUsageError)
    2449           0 :             *pbUsageError = TRUE;
    2450           0 :         return nullptr;
    2451             :     }
    2452             : 
    2453        1029 :     if (psOptions->bSelFieldsSet && bAppend && !psOptions->bAddMissingFields)
    2454             :     {
    2455           1 :         CPLError(CE_Failure, CPLE_IllegalArg,
    2456             :                  "if -append is specified, -select cannot be used "
    2457             :                  "(use -fieldmap or -sql instead).");
    2458           1 :         if (pbUsageError)
    2459           1 :             *pbUsageError = TRUE;
    2460           1 :         return nullptr;
    2461             :     }
    2462             : 
    2463        1028 :     if (!psOptions->aosFieldTypesToString.empty() &&
    2464           0 :         !psOptions->aosMapFieldType.empty())
    2465             :     {
    2466           0 :         CPLError(CE_Failure, CPLE_IllegalArg,
    2467             :                  "-fieldTypeToString and -mapFieldType are exclusive.");
    2468           0 :         if (pbUsageError)
    2469           0 :             *pbUsageError = TRUE;
    2470           0 :         return nullptr;
    2471             :     }
    2472             : 
    2473        1036 :     if (!psOptions->osSourceSRSDef.empty() &&
    2474        1036 :         psOptions->osOutputSRSDef.empty() && psOptions->osSpatSRSDef.empty())
    2475             :     {
    2476           0 :         CPLError(CE_Failure, CPLE_IllegalArg,
    2477             :                  "if -s_srs is specified, -t_srs and/or -spat_srs must also be "
    2478             :                  "specified.");
    2479           0 :         if (pbUsageError)
    2480           0 :             *pbUsageError = TRUE;
    2481           0 :         return nullptr;
    2482             :     }
    2483             : 
    2484             :     /* -------------------------------------------------------------------- */
    2485             :     /*      Parse spatial filter SRS if needed.                             */
    2486             :     /* -------------------------------------------------------------------- */
    2487        1028 :     std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSpatSRS;
    2488        1028 :     if (psOptions->poSpatialFilter && !psOptions->osSpatSRSDef.empty())
    2489             :     {
    2490           4 :         if (!psOptions->osSQLStatement.empty())
    2491             :         {
    2492           0 :             CPLError(CE_Failure, CPLE_IllegalArg,
    2493             :                      "-spat_srs not compatible with -sql.");
    2494           0 :             return nullptr;
    2495             :         }
    2496           4 :         OGREnvelope sEnvelope;
    2497           4 :         psOptions->poSpatialFilter->getEnvelope(&sEnvelope);
    2498           4 :         poSpatSRS.reset(new OGRSpatialReference());
    2499           4 :         poSpatSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    2500           4 :         if (poSpatSRS->SetFromUserInput(psOptions->osSpatSRSDef.c_str()) !=
    2501             :             OGRERR_NONE)
    2502             :         {
    2503           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2504             :                      "Failed to process SRS definition: %s",
    2505           0 :                      psOptions->osSpatSRSDef.c_str());
    2506           0 :             return nullptr;
    2507             :         }
    2508             :     }
    2509             : 
    2510        1028 :     if (!psOptions->poClipSrc && !psOptions->osClipSrcDS.empty())
    2511             :     {
    2512          10 :         psOptions->poClipSrc =
    2513          20 :             LoadGeometry(psOptions->osClipSrcDS, psOptions->osClipSrcSQL,
    2514          10 :                          psOptions->osClipSrcLayer, psOptions->osClipSrcWhere,
    2515          20 :                          psOptions->bMakeValid);
    2516          10 :         if (psOptions->poClipSrc == nullptr)
    2517             :         {
    2518           2 :             CPLError(CE_Failure, CPLE_IllegalArg,
    2519             :                      "cannot load source clip geometry");
    2520           2 :             return nullptr;
    2521             :         }
    2522             :     }
    2523        1019 :     else if (psOptions->bClipSrc && !psOptions->poClipSrc &&
    2524           1 :              psOptions->poSpatialFilter)
    2525             :     {
    2526           1 :         psOptions->poClipSrc.reset(psOptions->poSpatialFilter->clone());
    2527           1 :         if (poSpatSRS)
    2528             :         {
    2529           0 :             psOptions->poClipSrc->assignSpatialReference(poSpatSRS.get());
    2530             :         }
    2531             :     }
    2532        1017 :     else if (psOptions->bClipSrc && !psOptions->poClipSrc)
    2533             :     {
    2534           0 :         CPLError(CE_Failure, CPLE_IllegalArg,
    2535             :                  "-clipsrc must be used with -spat option or a\n"
    2536             :                  "bounding box, WKT string or datasource must be specified");
    2537           0 :         if (pbUsageError)
    2538           0 :             *pbUsageError = TRUE;
    2539           0 :         return nullptr;
    2540             :     }
    2541        1026 :     if (psOptions->poClipSrc && !psOptions->poClipSrc->IsValid())
    2542             :     {
    2543           2 :         if (!psOptions->bMakeValid)
    2544             :         {
    2545           1 :             CPLError(CE_Failure, CPLE_IllegalArg,
    2546             :                      "-clipsrc geometry is invalid. You can try to make it "
    2547             :                      "valid with -makevalid, but the results of the operation "
    2548             :                      "should be manually inspected.");
    2549           1 :             return nullptr;
    2550             :         }
    2551             :         auto poValid =
    2552           1 :             std::unique_ptr<OGRGeometry>(psOptions->poClipSrc->MakeValid());
    2553           1 :         if (!poValid)
    2554             :         {
    2555           0 :             CPLError(CE_Failure, CPLE_IllegalArg,
    2556             :                      "-clipsrc geometry is invalid and cannot be made valid.");
    2557           0 :             return nullptr;
    2558             :         }
    2559           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    2560             :                  "-clipsrc geometry was invalid and has been made valid, "
    2561             :                  "but the results of the operation "
    2562             :                  "should be manually inspected.");
    2563           1 :         psOptions->poClipSrc = std::move(poValid);
    2564             :     }
    2565             : 
    2566        1025 :     if (!psOptions->osClipDstDS.empty())
    2567             :     {
    2568          10 :         psOptions->poClipDst =
    2569          20 :             LoadGeometry(psOptions->osClipDstDS, psOptions->osClipDstSQL,
    2570          10 :                          psOptions->osClipDstLayer, psOptions->osClipDstWhere,
    2571          20 :                          psOptions->bMakeValid);
    2572          10 :         if (psOptions->poClipDst == nullptr)
    2573             :         {
    2574           3 :             CPLError(CE_Failure, CPLE_IllegalArg,
    2575             :                      "cannot load dest clip geometry");
    2576           3 :             return nullptr;
    2577             :         }
    2578             :     }
    2579        1022 :     if (psOptions->poClipDst && !psOptions->poClipDst->IsValid())
    2580             :     {
    2581           2 :         if (!psOptions->bMakeValid)
    2582             :         {
    2583           1 :             CPLError(CE_Failure, CPLE_IllegalArg,
    2584             :                      "-clipdst geometry is invalid. You can try to make it "
    2585             :                      "valid with -makevalid, but the results of the operation "
    2586             :                      "should be manually inspected.");
    2587           1 :             return nullptr;
    2588             :         }
    2589             :         auto poValid =
    2590           1 :             std::unique_ptr<OGRGeometry>(psOptions->poClipDst->MakeValid());
    2591           1 :         if (!poValid)
    2592             :         {
    2593           0 :             CPLError(CE_Failure, CPLE_IllegalArg,
    2594             :                      "-clipdst geometry is invalid and cannot be made valid.");
    2595           0 :             return nullptr;
    2596             :         }
    2597           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    2598             :                  "-clipdst geometry was invalid and has been made valid, "
    2599             :                  "but the results of the operation "
    2600             :                  "should be manually inspected.");
    2601           1 :         psOptions->poClipDst = std::move(poValid);
    2602             :     }
    2603             : 
    2604        1021 :     GDALDataset *poDS = GDALDataset::FromHandle(hSrcDS);
    2605        1021 :     GDALDataset *poODS = nullptr;
    2606        1021 :     GDALDriver *poDriver = nullptr;
    2607        2042 :     CPLString osDestFilename;
    2608             : 
    2609        1021 :     if (hDstDS)
    2610             :     {
    2611          31 :         poODS = GDALDataset::FromHandle(hDstDS);
    2612          31 :         osDestFilename = poODS->GetDescription();
    2613             :     }
    2614             :     else
    2615             :     {
    2616         990 :         osDestFilename = pszDest;
    2617             :     }
    2618             : 
    2619             :     /* Various tests to avoid overwriting the source layer(s) */
    2620             :     /* or to avoid appending a layer to itself */
    2621          75 :     if (bUpdate && strcmp(osDestFilename, poDS->GetDescription()) == 0 &&
    2622           6 :         !EQUAL(poDS->GetDriverName(), "MEM") &&
    2623        1096 :         !EQUAL(poDS->GetDriverName(), "Memory") && (bOverwrite || bAppend))
    2624             :     {
    2625           2 :         bool bError = false;
    2626           2 :         if (psOptions->osNewLayerName.empty())
    2627           1 :             bError = true;
    2628           1 :         else if (psOptions->aosLayers.size() == 1)
    2629           1 :             bError = strcmp(psOptions->osNewLayerName.c_str(),
    2630           1 :                             psOptions->aosLayers[0]) == 0;
    2631           0 :         else if (psOptions->osSQLStatement.empty())
    2632             :         {
    2633           0 :             if (psOptions->aosLayers.empty() && poDS->GetLayerCount() == 1)
    2634             :             {
    2635           0 :                 bError = strcmp(psOptions->osNewLayerName.c_str(),
    2636           0 :                                 poDS->GetLayer(0)->GetName()) == 0;
    2637             :             }
    2638             :             else
    2639             :             {
    2640           0 :                 bError = true;
    2641             :             }
    2642             :         }
    2643           2 :         if (bError)
    2644             :         {
    2645           1 :             if (psOptions->bInvokedFromGdalAlgorithm)
    2646             :             {
    2647           1 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    2648             :                          "--output-layer name must be specified combined with "
    2649             :                          "a single source layer name and it "
    2650             :                          "must be different from an existing layer.");
    2651             :             }
    2652             :             else
    2653             :             {
    2654           0 :                 CPLError(
    2655             :                     CE_Failure, CPLE_IllegalArg,
    2656             :                     "-nln name must be specified combined with "
    2657             :                     "a single source layer name,\nor a -sql statement, and "
    2658             :                     "name must be different from an existing layer.");
    2659             :             }
    2660           1 :             return nullptr;
    2661             :         }
    2662             :     }
    2663        1264 :     else if (!bUpdate && strcmp(osDestFilename, poDS->GetDescription()) == 0 &&
    2664         123 :              (psOptions->osFormat.empty() ||
    2665         122 :               (!EQUAL(psOptions->osFormat.c_str(), "MEM") &&
    2666           0 :                !EQUAL(psOptions->osFormat.c_str(), "Memory"))))
    2667             :     {
    2668           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    2669             :                  "Source and destination datasets must be different "
    2670             :                  "in non-update mode.");
    2671           1 :         return nullptr;
    2672             :     }
    2673             : 
    2674             :     /* -------------------------------------------------------------------- */
    2675             :     /*      Try opening the output datasource as an existing, writable      */
    2676             :     /* -------------------------------------------------------------------- */
    2677        2038 :     std::vector<std::string> aoDrivers;
    2678        1019 :     if (poODS == nullptr && psOptions->osFormat.empty())
    2679             :     {
    2680         413 :         const auto nErrorCount = CPLGetErrorCounter();
    2681         413 :         aoDrivers = CPLStringList(GDALGetOutputDriversForDatasetName(
    2682             :             pszDest, GDAL_OF_VECTOR, /* bSingleMatch = */ true,
    2683         413 :             /* bWarn = */ true));
    2684         413 :         if (!bUpdate && aoDrivers.size() == 1)
    2685             :         {
    2686         366 :             GDALDriverH hDriver = GDALGetDriverByName(aoDrivers[0].c_str());
    2687         366 :             const char *pszPrefix = GDALGetMetadataItem(
    2688             :                 hDriver, GDAL_DMD_CONNECTION_PREFIX, nullptr);
    2689         366 :             if (pszPrefix && STARTS_WITH_CI(pszDest, pszPrefix))
    2690             :             {
    2691           4 :                 bUpdate = true;
    2692             :             }
    2693             :         }
    2694          48 :         else if (aoDrivers.empty() && CPLGetErrorCounter() > nErrorCount &&
    2695           1 :                  CPLGetLastErrorType() == CE_Failure)
    2696             :         {
    2697           1 :             return nullptr;
    2698             :         }
    2699             :     }
    2700             : 
    2701        1018 :     if (bUpdate && poODS == nullptr)
    2702             :     {
    2703          48 :         poODS = GDALDataset::Open(
    2704             :             osDestFilename, GDAL_OF_UPDATE | GDAL_OF_VECTOR, nullptr,
    2705          48 :             psOptions->aosDestOpenOptions.List(), nullptr);
    2706             : 
    2707          48 :         if (poODS == nullptr)
    2708             :         {
    2709           3 :             if (bOverwrite || bAppend)
    2710             :             {
    2711           3 :                 poODS = GDALDataset::Open(
    2712             :                     osDestFilename, GDAL_OF_VECTOR, nullptr,
    2713           3 :                     psOptions->aosDestOpenOptions.List(), nullptr);
    2714           3 :                 if (poODS == nullptr)
    2715             :                 {
    2716             :                     /* OK the datasource doesn't exist at all */
    2717           3 :                     bUpdate = false;
    2718             :                 }
    2719             :                 else
    2720             :                 {
    2721           0 :                     poDriver = poODS->GetDriver();
    2722           0 :                     GDALClose(poODS);
    2723           0 :                     poODS = nullptr;
    2724             :                 }
    2725             :             }
    2726             : 
    2727           3 :             if (bUpdate)
    2728             :             {
    2729           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2730             :                          "Unable to open existing output datasource `%s'.",
    2731             :                          osDestFilename.c_str());
    2732           0 :                 return nullptr;
    2733             :             }
    2734             :         }
    2735          45 :         else if (psOptions->aosDSCO.size() > 0)
    2736             :         {
    2737           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2738             :                      "Datasource creation options ignored since an existing "
    2739             :                      "datasource\n"
    2740             :                      "         being updated.");
    2741             :         }
    2742             :     }
    2743             : 
    2744        1018 :     if (poODS)
    2745          75 :         poDriver = poODS->GetDriver();
    2746             : 
    2747             :     /* -------------------------------------------------------------------- */
    2748             :     /*      Find the output driver.                                         */
    2749             :     /* -------------------------------------------------------------------- */
    2750        1018 :     bool bNewDataSource = false;
    2751        1018 :     if (!bUpdate)
    2752             :     {
    2753         943 :         GDALDriverManager *poDM = GetGDALDriverManager();
    2754             : 
    2755         943 :         if (psOptions->bNoOverwrite && !EQUAL(pszDest, ""))
    2756             :         {
    2757         153 :             const char *pszType = "";
    2758         153 :             if (GDALDoesFileOrDatasetExist(pszDest, &pszType))
    2759             :             {
    2760           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2761             :                          "%s '%s' already exists. Specify the --overwrite "
    2762             :                          "option to overwrite it.",
    2763             :                          pszType, pszDest);
    2764           0 :                 return nullptr;
    2765             :             }
    2766             :         }
    2767             : 
    2768         943 :         if (psOptions->osFormat.empty())
    2769             :         {
    2770         377 :             if (aoDrivers.empty())
    2771             :             {
    2772          23 :                 if (CPLGetExtensionSafe(pszDest).empty() &&
    2773          11 :                     !psOptions->bInvokedFromGdalAlgorithm)
    2774             :                 {
    2775          10 :                     psOptions->osFormat = "ESRI Shapefile";
    2776             :                 }
    2777             :                 else
    2778             :                 {
    2779           2 :                     CPLError(CE_Failure, CPLE_AppDefined,
    2780             :                              "Cannot guess driver for %s", pszDest);
    2781           2 :                     return nullptr;
    2782             :                 }
    2783             :             }
    2784             :             else
    2785             :             {
    2786         365 :                 psOptions->osFormat = aoDrivers[0];
    2787             :             }
    2788         375 :             CPLDebug("GDAL", "Using %s driver", psOptions->osFormat.c_str());
    2789             :         }
    2790             : 
    2791         941 :         CPLString osOGRCompatFormat(psOptions->osFormat);
    2792             :         // Special processing for non-unified drivers that have the same name
    2793             :         // as GDAL and OGR drivers. GMT should become OGR_GMT.
    2794             :         // Other candidates could be VRT, SDTS and PDS, but they don't
    2795             :         // have write capabilities. But do the substitution to get a sensible
    2796             :         // error message
    2797         941 :         if (EQUAL(osOGRCompatFormat, "GMT") ||
    2798         940 :             EQUAL(osOGRCompatFormat, "VRT") ||
    2799        1881 :             EQUAL(osOGRCompatFormat, "SDTS") || EQUAL(osOGRCompatFormat, "PDS"))
    2800             :         {
    2801           1 :             osOGRCompatFormat = "OGR_" + osOGRCompatFormat;
    2802             :         }
    2803         941 :         poDriver = poDM->GetDriverByName(osOGRCompatFormat);
    2804         941 :         if (poDriver == nullptr)
    2805             :         {
    2806           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Unable to find driver `%s'.",
    2807           0 :                      psOptions->osFormat.c_str());
    2808           0 :             return nullptr;
    2809             :         }
    2810             : 
    2811         941 :         CSLConstList papszDriverMD = poDriver->GetMetadata();
    2812         941 :         if (!CPLTestBool(
    2813             :                 CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_VECTOR, "FALSE")))
    2814             :         {
    2815           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2816             :                      "%s driver has no vector capabilities.",
    2817           0 :                      psOptions->osFormat.c_str());
    2818           0 :             return nullptr;
    2819             :         }
    2820             : 
    2821         941 :         if (poDriver->CanVectorTranslateFrom(
    2822         941 :                 pszDest, poDS, psOptions->aosArguments.List(), nullptr))
    2823             :         {
    2824           4 :             return poDriver->VectorTranslateFrom(
    2825           4 :                 pszDest, poDS, psOptions->aosArguments.List(),
    2826           8 :                 psOptions->pfnProgress, psOptions->pProgressData);
    2827             :         }
    2828             : 
    2829         937 :         if (!CPLTestBool(
    2830             :                 CSLFetchNameValueDef(papszDriverMD, GDAL_DCAP_CREATE, "FALSE")))
    2831             :         {
    2832          22 :             if (CPLTestBool(CSLFetchNameValueDef(
    2833             :                     papszDriverMD, GDAL_DCAP_CREATECOPY, "FALSE")))
    2834             :             {
    2835          22 :                 poODS = GDALVectorTranslateCreateCopy(poDriver, pszDest, poDS,
    2836          22 :                                                       psOptions.get());
    2837          22 :                 return poODS;
    2838             :             }
    2839             : 
    2840           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2841             :                      "%s driver does not support data source creation.",
    2842           0 :                      psOptions->osFormat.c_str());
    2843           0 :             return nullptr;
    2844             :         }
    2845             : 
    2846         915 :         if (!psOptions->aosDestOpenOptions.empty())
    2847             :         {
    2848           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2849             :                      "-doo ignored when creating the output datasource.");
    2850             :         }
    2851             : 
    2852             :         const bool bSingleLayer =
    2853         915 :             (!psOptions->osSQLStatement.empty() ||
    2854        1810 :              psOptions->aosLayers.size() == 1 ||
    2855         895 :              (psOptions->aosLayers.empty() && poDS->GetLayerCount() == 1));
    2856             : 
    2857             :         bool bOutputDirectory =
    2858         997 :             !bSingleLayer && CPLGetExtensionSafe(osDestFilename).empty() &&
    2859          30 :             poDriver->GetMetadataItem(
    2860         945 :                 GDAL_DCAP_MULTIPLE_VECTOR_LAYERS_IN_DIRECTORY);
    2861             : 
    2862             :         /* ------------------------------------------------------------------ */
    2863             :         /*   Special case to improve user experience when translating         */
    2864             :         /*   a datasource with multiple layers into a shapefile. If the       */
    2865             :         /*   user gives a target datasource with .shp and it does not exist,  */
    2866             :         /*   the shapefile driver will try to create a file, but this is not  */
    2867             :         /*   appropriate because here we have several layers, so create       */
    2868             :         /*   a directory instead.                                             */
    2869             :         /* ------------------------------------------------------------------ */
    2870             : 
    2871             :         VSIStatBufL sStat;
    2872        2877 :         if (EQUAL(poDriver->GetDescription(), "ESRI Shapefile") &&
    2873         132 :             !bSingleLayer && psOptions->osNewLayerName.empty() &&
    2874        1048 :             EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "SHP") &&
    2875           1 :             VSIStatL(osDestFilename, &sStat) != 0)
    2876             :         {
    2877           1 :             if (VSIMkdir(osDestFilename, 0755) != 0)
    2878             :             {
    2879           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2880             :                          "Failed to create directory %s\n"
    2881             :                          "for shapefile datastore.",
    2882             :                          osDestFilename.c_str());
    2883           0 :                 return nullptr;
    2884             :             }
    2885           1 :             bOutputDirectory = true;
    2886             :         }
    2887             : 
    2888        1135 :         if (psOptions->bInvokedFromGdalAlgorithm && !bSingleLayer &&
    2889        1150 :             !bOutputDirectory &&
    2890          15 :             !poDriver->GetMetadataItem(GDAL_DCAP_MULTIPLE_VECTOR_LAYERS))
    2891             :         {
    2892           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    2893             :                      "%s driver does not support multiple layers.",
    2894           1 :                      poDriver->GetDescription());
    2895           1 :             return nullptr;
    2896             :         }
    2897             : 
    2898         914 :         CPLStringList aosDSCO(psOptions->aosDSCO);
    2899             : 
    2900         914 :         if (!aosDSCO.FetchNameValue("SINGLE_LAYER"))
    2901             :         {
    2902             :             // Informs the target driver (e.g. JSONFG) if a single layer
    2903             :             // will be created
    2904             :             const char *pszCOList =
    2905         914 :                 poDriver->GetMetadataItem(GDAL_DMD_CREATIONOPTIONLIST);
    2906         914 :             if (bSingleLayer && pszCOList && strstr(pszCOList, "SINGLE_LAYER"))
    2907             :             {
    2908           4 :                 aosDSCO.SetNameValue("SINGLE_LAYER", "YES");
    2909             :             }
    2910             :         }
    2911             : 
    2912             :         /* --------------------------------------------------------------------
    2913             :          */
    2914             :         /*      Create the output data source. */
    2915             :         /* --------------------------------------------------------------------
    2916             :          */
    2917         914 :         poODS = poDriver->Create(osDestFilename, 0, 0, 0, GDT_Unknown,
    2918         914 :                                  aosDSCO.List());
    2919         914 :         if (poODS == nullptr)
    2920             :         {
    2921           6 :             CPLError(CE_Failure, CPLE_AppDefined,
    2922             :                      "%s driver failed to create %s",
    2923           3 :                      psOptions->osFormat.c_str(), osDestFilename.c_str());
    2924           3 :             return nullptr;
    2925             :         }
    2926         911 :         bNewDataSource = true;
    2927             : 
    2928         911 :         if (psOptions->bCopyMD)
    2929             :         {
    2930        1814 :             const CPLStringList aosDomains(poDS->GetMetadataDomainList());
    2931         949 :             for (const char *pszMD : aosDomains)
    2932             :             {
    2933          42 :                 if (CSLConstList papszMD = poDS->GetMetadata(pszMD))
    2934          10 :                     poODS->SetMetadata(papszMD, pszMD);
    2935             :             }
    2936             :         }
    2937           2 :         for (const auto &[pszKey, pszValue] :
    2938         913 :              cpl::IterateNameValue(psOptions->aosMetadataOptions))
    2939             :         {
    2940           1 :             poODS->SetMetadataItem(pszKey, pszValue);
    2941             :         }
    2942             : 
    2943             :         // When writing to GeoJSON and using -nln, set the @NAME layer
    2944             :         // creation option to avoid the GeoJSON driver to potentially reuse
    2945             :         // the source feature collection name if the input is also GeoJSON.
    2946         923 :         if (!psOptions->osNewLayerName.empty() &&
    2947          12 :             EQUAL(psOptions->osFormat.c_str(), "GeoJSON"))
    2948             :         {
    2949           1 :             psOptions->aosLCO.SetNameValue("@NAME",
    2950           1 :                                            psOptions->osNewLayerName.c_str());
    2951             :         }
    2952             :     }
    2953             :     else
    2954             :     {
    2955          79 :         if (psOptions->bUpsert &&
    2956           4 :             poDriver->GetMetadataItem(GDAL_DCAP_UPSERT) == nullptr)
    2957             :         {
    2958           2 :             CPLError(CE_Failure, CPLE_NotSupported,
    2959             :                      "%s driver does not support upsert",
    2960           2 :                      poODS->GetDriver()->GetDescription());
    2961           2 :             return nullptr;
    2962             :         }
    2963             :     }
    2964             : 
    2965             :     // Automatically close poODS on error, if it has been created by this
    2966             :     // method.
    2967        1968 :     GDALDatasetUniquePtr poODSUniquePtr(hDstDS == nullptr ? poODS : nullptr);
    2968             : 
    2969             :     // Some syntactic sugar to make "ogr2ogr [-f PostgreSQL] PG:dbname=....
    2970             :     // source [srclayer] -lco OVERWRITE=YES" work like "ogr2ogr -overwrite
    2971             :     // PG:dbname=.... source [srclayer]" The former syntax used to work at
    2972             :     // GDAL 1.1.8 time when it was documented in the PG driver, but was broken
    2973             :     // starting with GDAL 1.3.2
    2974             :     // (https://github.com/OSGeo/gdal/commit/29c108a6c9f651dfebae6d1313ba0e707a77c1aa)
    2975             :     // This could probably be generalized to other drivers that support the
    2976             :     // OVERWRITE layer creation option, but we'd need to make sure that they
    2977             :     // just do a DeleteLayer() call. The CARTO driver is an exception regarding
    2978             :     // that.
    2979        1002 :     if (EQUAL(poODS->GetDriver()->GetDescription(), "PostgreSQL") &&
    2980          18 :         CPLTestBool(psOptions->aosLCO.FetchNameValueDef("OVERWRITE", "NO")))
    2981             :     {
    2982           0 :         if (bAppend)
    2983             :         {
    2984           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2985             :                      "-append and -lco OVERWRITE=YES are mutually exclusive");
    2986           0 :             return nullptr;
    2987             :         }
    2988           0 :         bOverwrite = true;
    2989             :     }
    2990             : 
    2991             :     /* -------------------------------------------------------------------- */
    2992             :     /*      For random reading                                              */
    2993             :     /* -------------------------------------------------------------------- */
    2994             :     const bool bRandomLayerReading =
    2995         984 :         CPL_TO_BOOL(poDS->TestCapability(ODsCRandomLayerRead));
    2996          17 :     if (bRandomLayerReading && !poODS->TestCapability(ODsCRandomLayerWrite) &&
    2997        1001 :         psOptions->aosLayers.size() != 1 && psOptions->osSQLStatement.empty() &&
    2998           0 :         !psOptions->bQuiet)
    2999             :     {
    3000           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    3001             :                  "Input datasource uses random layer reading, but "
    3002             :                  "output datasource does not support random layer writing");
    3003             :     }
    3004             : 
    3005         984 :     if (psOptions->nLayerTransaction < 0)
    3006             :     {
    3007         983 :         if (bRandomLayerReading)
    3008          17 :             psOptions->nLayerTransaction = FALSE;
    3009             :         else
    3010         966 :             psOptions->nLayerTransaction =
    3011         966 :                 !poODS->TestCapability(ODsCTransactions);
    3012             :     }
    3013           1 :     else if (psOptions->nLayerTransaction && bRandomLayerReading)
    3014             :     {
    3015           0 :         psOptions->nLayerTransaction = false;
    3016             :     }
    3017             : 
    3018             :     /* -------------------------------------------------------------------- */
    3019             :     /*      Parse the output SRS definition if possible.                    */
    3020             :     /* -------------------------------------------------------------------- */
    3021         984 :     OGR2OGRSpatialReferenceHolder oOutputSRSHolder;
    3022         984 :     if (!psOptions->osOutputSRSDef.empty())
    3023             :     {
    3024         144 :         oOutputSRSHolder.assignNoRefIncrease(new OGRSpatialReference());
    3025         144 :         oOutputSRSHolder.get()->SetAxisMappingStrategy(
    3026             :             OAMS_TRADITIONAL_GIS_ORDER);
    3027         288 :         if (oOutputSRSHolder.get()->SetFromUserInput(
    3028         288 :                 psOptions->osOutputSRSDef.c_str()) != OGRERR_NONE)
    3029             :         {
    3030           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3031             :                      "Failed to process SRS definition: %s",
    3032           0 :                      psOptions->osOutputSRSDef.c_str());
    3033           0 :             return nullptr;
    3034             :         }
    3035         288 :         oOutputSRSHolder.get()->SetCoordinateEpoch(
    3036         144 :             psOptions->dfOutputCoordinateEpoch);
    3037             :     }
    3038             : 
    3039             :     /* -------------------------------------------------------------------- */
    3040             :     /*      Parse the source SRS definition if possible.                    */
    3041             :     /* -------------------------------------------------------------------- */
    3042        1968 :     OGRSpatialReference oSourceSRS;
    3043         984 :     OGRSpatialReference *poSourceSRS = nullptr;
    3044         984 :     if (!psOptions->osSourceSRSDef.empty())
    3045             :     {
    3046           8 :         oSourceSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    3047           8 :         if (oSourceSRS.SetFromUserInput(psOptions->osSourceSRSDef.c_str()) !=
    3048             :             OGRERR_NONE)
    3049             :         {
    3050           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3051             :                      "Failed to process SRS definition: %s",
    3052           0 :                      psOptions->osSourceSRSDef.c_str());
    3053           0 :             return nullptr;
    3054             :         }
    3055           8 :         oSourceSRS.SetCoordinateEpoch(psOptions->dfSourceCoordinateEpoch);
    3056           8 :         poSourceSRS = &oSourceSRS;
    3057             :     }
    3058             : 
    3059             :     /* -------------------------------------------------------------------- */
    3060             :     /*      Create a transformation object from the source to               */
    3061             :     /*      destination coordinate system.                                  */
    3062             :     /* -------------------------------------------------------------------- */
    3063         984 :     std::unique_ptr<GCPCoordTransformation> poGCPCoordTrans;
    3064         984 :     if (!psOptions->asGCPs.empty())
    3065             :     {
    3066           7 :         poGCPCoordTrans = std::make_unique<GCPCoordTransformation>(
    3067           7 :             static_cast<int>(psOptions->asGCPs.size()),
    3068           7 :             gdal::GCP::c_ptr(psOptions->asGCPs), psOptions->nTransformOrder,
    3069          14 :             poSourceSRS ? poSourceSRS : oOutputSRSHolder.get());
    3070           7 :         if (!(poGCPCoordTrans->IsValid()))
    3071             :         {
    3072           1 :             return nullptr;
    3073             :         }
    3074             :     }
    3075             : 
    3076             :     /* -------------------------------------------------------------------- */
    3077             :     /*      Create layer setup and transformer objects.                     */
    3078             :     /* -------------------------------------------------------------------- */
    3079        1966 :     SetupTargetLayer oSetup;
    3080         983 :     oSetup.m_poSrcDS = poDS;
    3081         983 :     oSetup.m_poDstDS = poODS;
    3082         983 :     oSetup.m_papszLCO = psOptions->aosLCO.List();
    3083         983 :     oSetup.m_poOutputSRS = oOutputSRSHolder.get();
    3084         983 :     oSetup.m_bTransform = psOptions->bTransform;
    3085         983 :     oSetup.m_bNullifyOutputSRS = psOptions->bNullifyOutputSRS;
    3086         983 :     oSetup.m_poUserSourceSRS = poSourceSRS;
    3087         983 :     oSetup.m_bSelFieldsSet = psOptions->bSelFieldsSet;
    3088         983 :     oSetup.m_papszSelFields = psOptions->aosSelFields.List();
    3089         983 :     oSetup.m_bAppend = bAppend;
    3090         983 :     oSetup.m_bAddMissingFields = psOptions->bAddMissingFields;
    3091         983 :     oSetup.m_eGType = psOptions->eGType;
    3092         983 :     oSetup.m_eGeomTypeConversion = psOptions->eGeomTypeConversion;
    3093         983 :     oSetup.m_nCoordDim = psOptions->nCoordDim;
    3094         983 :     oSetup.m_bOverwrite = bOverwrite;
    3095         983 :     oSetup.m_papszFieldTypesToString = psOptions->aosFieldTypesToString.List();
    3096         983 :     oSetup.m_papszMapFieldType = psOptions->aosMapFieldType.List();
    3097         983 :     oSetup.m_bUnsetFieldWidth = psOptions->bUnsetFieldWidth;
    3098         983 :     oSetup.m_bExplodeCollections = psOptions->bExplodeCollections;
    3099         983 :     oSetup.m_pszZField =
    3100         983 :         psOptions->osZField.empty() ? nullptr : psOptions->osZField.c_str();
    3101         983 :     oSetup.m_papszFieldMap = psOptions->aosFieldMap.List();
    3102         983 :     oSetup.m_pszWHERE =
    3103         983 :         psOptions->osWHERE.empty() ? nullptr : psOptions->osWHERE.c_str();
    3104         983 :     oSetup.m_bExactFieldNameMatch = psOptions->bExactFieldNameMatch;
    3105         983 :     oSetup.m_bQuiet = psOptions->bQuiet;
    3106         983 :     oSetup.m_bForceNullable = psOptions->bForceNullable;
    3107         983 :     oSetup.m_bResolveDomains = psOptions->bResolveDomains;
    3108         983 :     oSetup.m_bUnsetDefault = psOptions->bUnsetDefault;
    3109         983 :     oSetup.m_bUnsetFid = psOptions->bUnsetFid;
    3110         983 :     oSetup.m_bPreserveFID = psOptions->bPreserveFID;
    3111         983 :     oSetup.m_bCopyMD = psOptions->bCopyMD;
    3112         983 :     oSetup.m_bNativeData = psOptions->bNativeData;
    3113         983 :     oSetup.m_bNewDataSource = bNewDataSource;
    3114         983 :     oSetup.m_pszCTPipeline = psOptions->osCTPipeline.empty()
    3115         983 :                                  ? nullptr
    3116           4 :                                  : psOptions->osCTPipeline.c_str();
    3117         983 :     oSetup.m_aosCTOptions = psOptions->aosCTOptions;
    3118             : 
    3119        1966 :     LayerTranslator oTranslator;
    3120         983 :     oTranslator.m_poSrcDS = poDS;
    3121         983 :     oTranslator.m_poODS = poODS;
    3122         983 :     oTranslator.m_bTransform = psOptions->bTransform;
    3123         983 :     oTranslator.m_bWrapDateline = psOptions->bWrapDateline;
    3124             :     oTranslator.m_osDateLineOffset =
    3125         983 :         CPLOPrintf("%g", psOptions->dfDateLineOffset);
    3126         983 :     oTranslator.m_poOutputSRS = oOutputSRSHolder.get();
    3127         983 :     oTranslator.m_bNullifyOutputSRS = psOptions->bNullifyOutputSRS;
    3128         983 :     oTranslator.m_poUserSourceSRS = poSourceSRS;
    3129         983 :     oTranslator.m_poGCPCoordTrans = poGCPCoordTrans.get();
    3130         983 :     oTranslator.m_eGType = psOptions->eGType;
    3131         983 :     oTranslator.m_eGeomTypeConversion = psOptions->eGeomTypeConversion;
    3132         983 :     oTranslator.m_bMakeValid = psOptions->bMakeValid;
    3133         983 :     oTranslator.m_bSkipInvalidGeom = psOptions->bSkipInvalidGeom;
    3134         983 :     oTranslator.m_nCoordDim = psOptions->nCoordDim;
    3135         983 :     oTranslator.m_eGeomOp = psOptions->eGeomOp;
    3136         983 :     oTranslator.m_dfGeomOpParam = psOptions->dfGeomOpParam;
    3137             :     // Do not emit warning if the user specified directly the clip source geom
    3138         983 :     if (psOptions->osClipSrcDS.empty())
    3139         975 :         oTranslator.m_bWarnedClipSrcSRS = true;
    3140         983 :     oTranslator.m_poClipSrcOri = psOptions->poClipSrc.get();
    3141             :     // Do not emit warning if the user specified directly the clip dest geom
    3142         983 :     if (psOptions->osClipDstDS.empty())
    3143         976 :         oTranslator.m_bWarnedClipDstSRS = true;
    3144         983 :     oTranslator.m_poClipDstOri = psOptions->poClipDst.get();
    3145         983 :     oTranslator.m_bExplodeCollections = psOptions->bExplodeCollections;
    3146         983 :     oTranslator.m_bNativeData = psOptions->bNativeData;
    3147         983 :     oTranslator.m_nLimit = psOptions->nLimit;
    3148             : 
    3149         983 :     if (psOptions->nGroupTransactions)
    3150             :     {
    3151         982 :         if (!psOptions->nLayerTransaction)
    3152         173 :             poODS->StartTransaction(psOptions->bForceTransaction);
    3153             :     }
    3154             : 
    3155         983 :     GIntBig nTotalEventsDone = 0;
    3156             : 
    3157             :     /* -------------------------------------------------------------------- */
    3158             :     /*      Special case for -sql clause.  No source layers required.       */
    3159             :     /* -------------------------------------------------------------------- */
    3160         983 :     int nRetCode = 0;
    3161             : 
    3162         983 :     if (!psOptions->osSQLStatement.empty())
    3163             :     {
    3164             :         /* Special case: if output=input, then we must likely destroy the */
    3165             :         /* old table before to avoid transaction issues. */
    3166          17 :         if (poDS == poODS && !psOptions->osNewLayerName.empty() && bOverwrite)
    3167           0 :             GetLayerAndOverwriteIfNecessary(
    3168           0 :                 poODS, psOptions->osNewLayerName.c_str(), bOverwrite, nullptr,
    3169             :                 nullptr, nullptr);
    3170             : 
    3171          17 :         if (!psOptions->osWHERE.empty())
    3172           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    3173             :                      "-where clause ignored in combination with -sql.");
    3174          17 :         if (psOptions->aosLayers.size() > 0)
    3175           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    3176             :                      "layer names ignored in combination with -sql.");
    3177             : 
    3178          34 :         OGRLayer *poResultSet = poDS->ExecuteSQL(
    3179          17 :             psOptions->osSQLStatement.c_str(),
    3180          17 :             (!psOptions->bGeomFieldSet) ? psOptions->poSpatialFilter.get()
    3181             :                                         : nullptr,
    3182          17 :             psOptions->osDialect.empty() ? nullptr
    3183          23 :                                          : psOptions->osDialect.c_str());
    3184             : 
    3185          17 :         if (poResultSet != nullptr)
    3186             :         {
    3187          17 :             if (psOptions->poSpatialFilter && psOptions->bGeomFieldSet)
    3188             :             {
    3189           0 :                 int iGeomField = poResultSet->GetLayerDefn()->GetGeomFieldIndex(
    3190           0 :                     psOptions->osGeomField.c_str());
    3191           0 :                 if (iGeomField >= 0)
    3192           0 :                     poResultSet->SetSpatialFilter(
    3193           0 :                         iGeomField, psOptions->poSpatialFilter.get());
    3194             :                 else
    3195           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    3196             :                              "Cannot find geometry field %s.",
    3197           0 :                              psOptions->osGeomField.c_str());
    3198             :             }
    3199             : 
    3200          17 :             GIntBig nCountLayerFeatures = 0;
    3201          17 :             GDALProgressFunc pfnProgress = nullptr;
    3202          17 :             void *pProgressArg = nullptr;
    3203          17 :             if (psOptions->bDisplayProgress)
    3204             :             {
    3205           1 :                 if (bRandomLayerReading)
    3206             :                 {
    3207           1 :                     pfnProgress = psOptions->pfnProgress;
    3208           1 :                     pProgressArg = psOptions->pProgressData;
    3209             :                 }
    3210           0 :                 else if (!poResultSet->TestCapability(OLCFastFeatureCount))
    3211             :                 {
    3212           0 :                     if (!psOptions->bInvokedFromGdalAlgorithm)
    3213             :                     {
    3214           0 :                         CPLError(
    3215             :                             CE_Warning, CPLE_AppDefined,
    3216             :                             "Progress turned off as fast feature count is not "
    3217             :                             "available.");
    3218             :                     }
    3219           0 :                     psOptions->bDisplayProgress = false;
    3220             :                 }
    3221             :                 else
    3222             :                 {
    3223           0 :                     nCountLayerFeatures = poResultSet->GetFeatureCount();
    3224           0 :                     pfnProgress = psOptions->pfnProgress;
    3225           0 :                     pProgressArg = psOptions->pProgressData;
    3226             :                 }
    3227             :             }
    3228             : 
    3229          17 :             std::unique_ptr<OGRLayer> poLayerToFree;
    3230          17 :             OGRLayer *poPassedLayer = poResultSet;
    3231          17 :             if (psOptions->bSplitListFields)
    3232             :             {
    3233             :                 auto poLayer = std::make_unique<OGRSplitListFieldLayer>(
    3234           0 :                     poPassedLayer, psOptions->nMaxSplitListSubFields);
    3235           0 :                 int nRet = poLayer->BuildLayerDefn(nullptr, nullptr);
    3236           0 :                 if (nRet)
    3237             :                 {
    3238           0 :                     poLayerToFree = std::move(poLayer);
    3239           0 :                     poPassedLayer = poLayerToFree.get();
    3240             :                 }
    3241             :             }
    3242             : 
    3243             :             /* --------------------------------------------------------------------
    3244             :              */
    3245             :             /*      Special case to improve user experience when translating
    3246             :              * into   */
    3247             :             /*      single file shapefile and source has only one layer, and
    3248             :              * that   */
    3249             :             /*      the layer name isn't specified */
    3250             :             /* --------------------------------------------------------------------
    3251             :              */
    3252             :             VSIStatBufL sStat;
    3253           3 :             if (EQUAL(poDriver->GetDescription(), "ESRI Shapefile") &&
    3254           3 :                 psOptions->osNewLayerName.empty() &&
    3255           3 :                 VSIStatL(osDestFilename, &sStat) == 0 &&
    3256          20 :                 VSI_ISREG(sStat.st_mode) &&
    3257          17 :                 (EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shp") ||
    3258          17 :                  EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shz") ||
    3259          17 :                  EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "dbf")))
    3260             :             {
    3261           0 :                 psOptions->osNewLayerName = CPLGetBasenameSafe(osDestFilename);
    3262             :             }
    3263             : 
    3264             :             auto psInfo = oSetup.Setup(poPassedLayer,
    3265          17 :                                        psOptions->osNewLayerName.empty()
    3266             :                                            ? nullptr
    3267           3 :                                            : psOptions->osNewLayerName.c_str(),
    3268          54 :                                        psOptions.get(), nTotalEventsDone);
    3269             : 
    3270          17 :             poPassedLayer->ResetReading();
    3271             : 
    3272          32 :             if (psInfo == nullptr ||
    3273          32 :                 !oTranslator.Translate(nullptr, psInfo.get(),
    3274             :                                        nCountLayerFeatures, nullptr,
    3275             :                                        nTotalEventsDone, pfnProgress,
    3276          15 :                                        pProgressArg, psOptions.get()))
    3277             :             {
    3278           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3279             :                          "Terminating translation prematurely after failed\n"
    3280             :                          "translation from sql statement.");
    3281             : 
    3282           2 :                 nRetCode = 1;
    3283             :             }
    3284             :             else
    3285             :             {
    3286          15 :                 psInfo->CheckSameCoordinateOperation();
    3287             :             }
    3288             : 
    3289          17 :             poDS->ReleaseResultSet(poResultSet);
    3290             :         }
    3291             :         else
    3292             :         {
    3293           0 :             if (CPLGetLastErrorNo() != 0)
    3294           0 :                 nRetCode = 1;
    3295             :         }
    3296             :     }
    3297             : 
    3298             :     /* -------------------------------------------------------------------- */
    3299             :     /*      Special case for layer interleaving mode.                       */
    3300             :     /* -------------------------------------------------------------------- */
    3301         966 :     else if (bRandomLayerReading)
    3302             :     {
    3303          16 :         if (psOptions->bSplitListFields)
    3304             :         {
    3305           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3306             :                      "-splitlistfields not supported in this mode");
    3307           0 :             return nullptr;
    3308             :         }
    3309             : 
    3310             :         // Make sure to probe all layers in case some are by default invisible
    3311          28 :         for (const char *pszLayer : psOptions->aosLayers)
    3312             :         {
    3313          12 :             OGRLayer *poLayer = poDS->GetLayerByName(pszLayer);
    3314             : 
    3315          12 :             if (poLayer == nullptr)
    3316             :             {
    3317           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3318             :                          "Couldn't fetch requested layer %s!", pszLayer);
    3319           0 :                 return nullptr;
    3320             :             }
    3321             :         }
    3322             : 
    3323          16 :         const int nSrcLayerCount = poDS->GetLayerCount();
    3324          16 :         std::vector<AssociatedLayers> pasAssocLayers(nSrcLayerCount);
    3325             : 
    3326             :         /* --------------------------------------------------------------------
    3327             :          */
    3328             :         /*      Special case to improve user experience when translating into */
    3329             :         /*      single file shapefile and source has only one layer, and that */
    3330             :         /*      the layer name isn't specified */
    3331             :         /* --------------------------------------------------------------------
    3332             :          */
    3333             :         VSIStatBufL sStat;
    3334          53 :         if (EQUAL(poDriver->GetDescription(), "ESRI Shapefile") &&
    3335           5 :             (psOptions->aosLayers.size() == 1 || nSrcLayerCount == 1) &&
    3336           0 :             psOptions->osNewLayerName.empty() &&
    3337          21 :             VSIStatL(osDestFilename, &sStat) == 0 && VSI_ISREG(sStat.st_mode) &&
    3338          16 :             (EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shp") ||
    3339          16 :              EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shz") ||
    3340          16 :              EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "dbf")))
    3341             :         {
    3342           0 :             psOptions->osNewLayerName = CPLGetBasenameSafe(osDestFilename);
    3343             :         }
    3344             : 
    3345          16 :         GDALProgressFunc pfnProgress = nullptr;
    3346          16 :         void *pProgressArg = nullptr;
    3347          16 :         if (!psOptions->bQuiet)
    3348             :         {
    3349          16 :             pfnProgress = psOptions->pfnProgress;
    3350          16 :             pProgressArg = psOptions->pProgressData;
    3351             :         }
    3352             : 
    3353             :         /* --------------------------------------------------------------------
    3354             :          */
    3355             :         /*      If no target layer specified, use all source layers. */
    3356             :         /* --------------------------------------------------------------------
    3357             :          */
    3358          16 :         if (psOptions->aosLayers.empty())
    3359             :         {
    3360         148 :             for (int iLayer = 0; iLayer < nSrcLayerCount; iLayer++)
    3361             :             {
    3362         135 :                 OGRLayer *poLayer = poDS->GetLayer(iLayer);
    3363             : 
    3364         135 :                 if (poLayer == nullptr)
    3365             :                 {
    3366           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    3367             :                              "Couldn't fetch advertised layer %d!", iLayer);
    3368           0 :                     return nullptr;
    3369             :                 }
    3370             : 
    3371         135 :                 psOptions->aosLayers.AddString(poLayer->GetName());
    3372             :             }
    3373             :         }
    3374             :         else
    3375             :         {
    3376           3 :             const bool bSrcIsOSM = (strcmp(poDS->GetDriverName(), "OSM") == 0);
    3377           3 :             if (bSrcIsOSM)
    3378             :             {
    3379           6 :                 CPLString osInterestLayers = "SET interest_layers =";
    3380          15 :                 for (int iLayer = 0; iLayer < psOptions->aosLayers.size();
    3381             :                      iLayer++)
    3382             :                 {
    3383          12 :                     if (iLayer != 0)
    3384           9 :                         osInterestLayers += ",";
    3385          12 :                     osInterestLayers += psOptions->aosLayers[iLayer];
    3386             :                 }
    3387             : 
    3388           3 :                 poDS->ExecuteSQL(osInterestLayers.c_str(), nullptr, nullptr);
    3389             :             }
    3390             :         }
    3391             : 
    3392             :         /* --------------------------------------------------------------------
    3393             :          */
    3394             :         /*      First pass to set filters. */
    3395             :         /* --------------------------------------------------------------------
    3396             :          */
    3397          16 :         std::map<OGRLayer *, int> oMapLayerToIdx;
    3398             : 
    3399         166 :         for (int iLayer = 0; iLayer < nSrcLayerCount; iLayer++)
    3400             :         {
    3401         150 :             OGRLayer *poLayer = poDS->GetLayer(iLayer);
    3402         150 :             if (poLayer == nullptr)
    3403             :             {
    3404           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3405             :                          "Couldn't fetch advertised layer %d!", iLayer);
    3406           0 :                 return nullptr;
    3407             :             }
    3408             : 
    3409         150 :             pasAssocLayers[iLayer].poSrcLayer = poLayer;
    3410             : 
    3411         150 :             if (psOptions->aosLayers.FindString(poLayer->GetName()) >= 0)
    3412             :             {
    3413         147 :                 if (!psOptions->osWHERE.empty())
    3414             :                 {
    3415           0 :                     if (poLayer->SetAttributeFilter(
    3416           0 :                             psOptions->osWHERE.c_str()) != OGRERR_NONE)
    3417             :                     {
    3418           0 :                         CPLError(CE_Failure, CPLE_AppDefined,
    3419             :                                  "SetAttributeFilter(%s) on layer '%s' failed.",
    3420           0 :                                  psOptions->osWHERE.c_str(),
    3421           0 :                                  poLayer->GetName());
    3422           0 :                         if (!psOptions->bSkipFailures)
    3423             :                         {
    3424           0 :                             return nullptr;
    3425             :                         }
    3426             :                     }
    3427             :                 }
    3428             : 
    3429         294 :                 ApplySpatialFilter(
    3430         147 :                     poLayer, psOptions->poSpatialFilter.get(), poSpatSRS.get(),
    3431         147 :                     psOptions->bGeomFieldSet ? psOptions->osGeomField.c_str()
    3432             :                                              : nullptr,
    3433             :                     poSourceSRS);
    3434             : 
    3435         147 :                 oMapLayerToIdx[poLayer] = iLayer;
    3436             :             }
    3437             :         }
    3438             : 
    3439             :         /* --------------------------------------------------------------------
    3440             :          */
    3441             :         /*      Second pass to process features in a interleaved layer mode. */
    3442             :         /* --------------------------------------------------------------------
    3443             :          */
    3444          16 :         bool bTargetLayersHaveBeenCreated = false;
    3445             :         while (true)
    3446             :         {
    3447         991 :             OGRLayer *poFeatureLayer = nullptr;
    3448             :             auto poFeature = std::unique_ptr<OGRFeature>(poDS->GetNextFeature(
    3449         991 :                 &poFeatureLayer, nullptr, pfnProgress, pProgressArg));
    3450         991 :             if (poFeature == nullptr)
    3451          16 :                 break;
    3452             :             std::map<OGRLayer *, int>::const_iterator oIter =
    3453         975 :                 oMapLayerToIdx.find(poFeatureLayer);
    3454         975 :             if (oIter == oMapLayerToIdx.end())
    3455             :             {
    3456             :                 // Feature in a layer that is not a layer of interest.
    3457             :                 // nothing to do
    3458             :             }
    3459             :             else
    3460             :             {
    3461         975 :                 if (!bTargetLayersHaveBeenCreated)
    3462             :                 {
    3463             :                     // We defer target layer creation at the first feature
    3464             :                     // retrieved since getting the layer definition can be
    3465             :                     // costly (case of the GMLAS driver) and thus we'd better
    3466             :                     // taking advantage from the progress callback of
    3467             :                     // GetNextFeature.
    3468          15 :                     bTargetLayersHaveBeenCreated = true;
    3469         160 :                     for (int iLayer = 0; iLayer < nSrcLayerCount; iLayer++)
    3470             :                     {
    3471         145 :                         OGRLayer *poLayer = poDS->GetLayer(iLayer);
    3472         290 :                         if (psOptions->aosLayers.FindString(
    3473         290 :                                 poLayer->GetName()) < 0)
    3474           3 :                             continue;
    3475             : 
    3476             :                         auto psInfo = oSetup.Setup(
    3477             :                             poLayer,
    3478         142 :                             psOptions->osNewLayerName.empty()
    3479             :                                 ? nullptr
    3480           0 :                                 : psOptions->osNewLayerName.c_str(),
    3481         284 :                             psOptions.get(), nTotalEventsDone);
    3482             : 
    3483         142 :                         if (psInfo == nullptr && !psOptions->bSkipFailures)
    3484             :                         {
    3485           0 :                             return nullptr;
    3486             :                         }
    3487             : 
    3488         142 :                         pasAssocLayers[iLayer].psInfo = std::move(psInfo);
    3489             :                     }
    3490          15 :                     if (nRetCode)
    3491           0 :                         break;
    3492             :                 }
    3493             : 
    3494         975 :                 int iLayer = oIter->second;
    3495         975 :                 TargetLayerInfo *psInfo = pasAssocLayers[iLayer].psInfo.get();
    3496        2923 :                 if ((psInfo == nullptr ||
    3497        1949 :                      !oTranslator.Translate(std::move(poFeature), psInfo, 0,
    3498             :                                             nullptr, nTotalEventsDone, nullptr,
    3499        1950 :                                             nullptr, psOptions.get())) &&
    3500           1 :                     !psOptions->bSkipFailures)
    3501             :                 {
    3502           0 :                     if (psOptions->bInvokedFromGdalAlgorithm)
    3503             :                     {
    3504           0 :                         CPLError(
    3505             :                             CE_Failure, CPLE_AppDefined,
    3506             :                             "Failed to write layer '%s'. Use --skip-errors to "
    3507             :                             "ignore errors and continue writing.",
    3508           0 :                             poFeatureLayer->GetName());
    3509             :                     }
    3510             :                     else
    3511             :                     {
    3512           0 :                         CPLError(
    3513             :                             CE_Failure, CPLE_AppDefined,
    3514             :                             "Terminating translation prematurely after failed\n"
    3515             :                             "translation of layer %s (use -skipfailures to "
    3516             :                             "skip "
    3517             :                             "errors)",
    3518           0 :                             poFeatureLayer->GetName());
    3519             :                     }
    3520             : 
    3521           0 :                     nRetCode = 1;
    3522           0 :                     break;
    3523             :                 }
    3524             :             }
    3525         975 :         }  // while true
    3526             : 
    3527          16 :         if (pfnProgress)
    3528             :         {
    3529           0 :             pfnProgress(1.0, "", pProgressArg);
    3530             :         }
    3531             : 
    3532         166 :         for (int iLayer = 0; iLayer < nSrcLayerCount; iLayer++)
    3533             :         {
    3534         150 :             if (pasAssocLayers[iLayer].psInfo)
    3535         141 :                 pasAssocLayers[iLayer].psInfo->CheckSameCoordinateOperation();
    3536             :         }
    3537             : 
    3538          16 :         if (!bTargetLayersHaveBeenCreated)
    3539             :         {
    3540             :             // bTargetLayersHaveBeenCreated not used after here.
    3541             :             // bTargetLayersHaveBeenCreated = true;
    3542           6 :             for (int iLayer = 0; iLayer < nSrcLayerCount; iLayer++)
    3543             :             {
    3544           5 :                 OGRLayer *poLayer = poDS->GetLayer(iLayer);
    3545           5 :                 if (psOptions->aosLayers.FindString(poLayer->GetName()) < 0)
    3546           0 :                     continue;
    3547             : 
    3548             :                 auto psInfo =
    3549             :                     oSetup.Setup(poLayer,
    3550           5 :                                  psOptions->osNewLayerName.empty()
    3551             :                                      ? nullptr
    3552           0 :                                      : psOptions->osNewLayerName.c_str(),
    3553          10 :                                  psOptions.get(), nTotalEventsDone);
    3554             : 
    3555           5 :                 if (psInfo == nullptr && !psOptions->bSkipFailures)
    3556             :                 {
    3557           0 :                     return nullptr;
    3558             :                 }
    3559             : 
    3560           5 :                 pasAssocLayers[iLayer].psInfo = std::move(psInfo);
    3561             :             }
    3562             :         }
    3563             :     }
    3564             : 
    3565             :     else
    3566             :     {
    3567         950 :         std::vector<OGRLayer *> apoLayers;
    3568             : 
    3569             :         /* --------------------------------------------------------------------
    3570             :          */
    3571             :         /*      Process each data source layer. */
    3572             :         /* --------------------------------------------------------------------
    3573             :          */
    3574         950 :         if (psOptions->aosLayers.empty())
    3575             :         {
    3576         938 :             const int nLayerCount = poDS->GetLayerCount();
    3577             : 
    3578        1944 :             for (int iLayer = 0; iLayer < nLayerCount; iLayer++)
    3579             :             {
    3580        1006 :                 OGRLayer *poLayer = poDS->GetLayer(iLayer);
    3581             : 
    3582        1006 :                 if (poLayer == nullptr)
    3583             :                 {
    3584           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    3585             :                              "Couldn't fetch advertised layer %d!", iLayer);
    3586           0 :                     return nullptr;
    3587             :                 }
    3588        1006 :                 if (!poDS->IsLayerPrivate(iLayer))
    3589             :                 {
    3590        1006 :                     apoLayers.push_back(poLayer);
    3591             :                 }
    3592             :             }
    3593             :         }
    3594             :         /* --------------------------------------------------------------------
    3595             :          */
    3596             :         /*      Process specified data source layers. */
    3597             :         /* --------------------------------------------------------------------
    3598             :          */
    3599             :         else
    3600             :         {
    3601             : 
    3602          33 :             for (int iLayer = 0; psOptions->aosLayers[iLayer] != nullptr;
    3603             :                  iLayer++)
    3604             :             {
    3605             :                 OGRLayer *poLayer =
    3606          21 :                     poDS->GetLayerByName(psOptions->aosLayers[iLayer]);
    3607             : 
    3608          21 :                 if (poLayer == nullptr)
    3609             :                 {
    3610           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    3611             :                              "Couldn't fetch requested layer '%s'!",
    3612           0 :                              psOptions->aosLayers[iLayer]);
    3613           0 :                     if (!psOptions->bSkipFailures)
    3614             :                     {
    3615           0 :                         return nullptr;
    3616             :                     }
    3617             :                 }
    3618             : 
    3619          21 :                 apoLayers.emplace_back(poLayer);
    3620             :             }
    3621             :         }
    3622             : 
    3623             :         /* --------------------------------------------------------------------
    3624             :          */
    3625             :         /*      Special case to improve user experience when translating into */
    3626             :         /*      single file shapefile and source has only one layer, and that */
    3627             :         /*      the layer name isn't specified */
    3628             :         /* --------------------------------------------------------------------
    3629             :          */
    3630             :         VSIStatBufL sStat;
    3631         950 :         const int nLayerCount = static_cast<int>(apoLayers.size());
    3632         146 :         if (EQUAL(poDriver->GetDescription(), "ESRI Shapefile") &&
    3633         142 :             nLayerCount == 1 && psOptions->osNewLayerName.empty() &&
    3634        1107 :             VSIStatL(osDestFilename, &sStat) == 0 && VSI_ISREG(sStat.st_mode) &&
    3635         961 :             (EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shp") ||
    3636         952 :              EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "shz") ||
    3637         951 :              EQUAL(CPLGetExtensionSafe(osDestFilename).c_str(), "dbf")))
    3638             :         {
    3639          10 :             psOptions->osNewLayerName = CPLGetBasenameSafe(osDestFilename);
    3640             :         }
    3641             : 
    3642         950 :         std::vector<GIntBig> anLayerCountFeatures(nLayerCount);
    3643         950 :         GIntBig nCountLayersFeatures = 0;
    3644         950 :         GIntBig nAccCountFeatures = 0;
    3645             : 
    3646             :         /* First pass to apply filters and count all features if necessary */
    3647        1977 :         for (int iLayer = 0; iLayer < nLayerCount; iLayer++)
    3648             :         {
    3649        1027 :             OGRLayer *poLayer = apoLayers[iLayer];
    3650        1027 :             if (poLayer == nullptr)
    3651           0 :                 continue;
    3652             : 
    3653        1027 :             if (!psOptions->osWHERE.empty())
    3654             :             {
    3655           8 :                 if (poLayer->SetAttributeFilter(psOptions->osWHERE.c_str()) !=
    3656             :                     OGRERR_NONE)
    3657             :                 {
    3658           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    3659             :                              "SetAttributeFilter(%s) on layer '%s' failed.",
    3660           0 :                              psOptions->osWHERE.c_str(), poLayer->GetName());
    3661           0 :                     if (!psOptions->bSkipFailures)
    3662             :                     {
    3663           0 :                         return nullptr;
    3664             :                     }
    3665             :                 }
    3666             :             }
    3667             : 
    3668        2053 :             ApplySpatialFilter(
    3669        1027 :                 poLayer, psOptions->poSpatialFilter.get(), poSpatSRS.get(),
    3670        1027 :                 psOptions->bGeomFieldSet ? psOptions->osGeomField.c_str()
    3671             :                                          : nullptr,
    3672             :                 poSourceSRS);
    3673             : 
    3674        1027 :             if (psOptions->bDisplayProgress)
    3675             :             {
    3676          16 :                 if (!poLayer->TestCapability(OLCFastFeatureCount))
    3677             :                 {
    3678           1 :                     if (!psOptions->bInvokedFromGdalAlgorithm)
    3679             :                     {
    3680           0 :                         CPLError(
    3681             :                             CE_Warning, CPLE_NotSupported,
    3682             :                             "Progress turned off as fast feature count is not "
    3683             :                             "available.");
    3684             :                     }
    3685           1 :                     psOptions->bDisplayProgress = false;
    3686             :                 }
    3687             :                 else
    3688             :                 {
    3689          15 :                     anLayerCountFeatures[iLayer] = poLayer->GetFeatureCount();
    3690          15 :                     if (psOptions->nLimit >= 0)
    3691           0 :                         anLayerCountFeatures[iLayer] = std::min(
    3692           0 :                             anLayerCountFeatures[iLayer], psOptions->nLimit);
    3693          30 :                     if (anLayerCountFeatures[iLayer] >= 0 &&
    3694          15 :                         anLayerCountFeatures[iLayer] <=
    3695          15 :                             std::numeric_limits<GIntBig>::max() -
    3696             :                                 nCountLayersFeatures)
    3697             :                     {
    3698          14 :                         nCountLayersFeatures += anLayerCountFeatures[iLayer];
    3699             :                     }
    3700             :                     else
    3701             :                     {
    3702           1 :                         nCountLayersFeatures = 0;
    3703           1 :                         psOptions->bDisplayProgress = false;
    3704             :                     }
    3705             :                 }
    3706             :             }
    3707             :         }
    3708             : 
    3709             :         /* Second pass to do the real job */
    3710        1977 :         for (int iLayer = 0; iLayer < nLayerCount && nRetCode == 0; iLayer++)
    3711             :         {
    3712        1027 :             OGRLayer *poLayer = apoLayers[iLayer];
    3713        1027 :             if (poLayer == nullptr)
    3714           0 :                 continue;
    3715             : 
    3716        1027 :             std::unique_ptr<OGRLayer> poLayerToFree;
    3717        1027 :             OGRLayer *poPassedLayer = poLayer;
    3718        1027 :             if (psOptions->bSplitListFields)
    3719             :             {
    3720             :                 auto poSLFLayer = std::make_unique<OGRSplitListFieldLayer>(
    3721           2 :                     poPassedLayer, psOptions->nMaxSplitListSubFields);
    3722             : 
    3723           1 :                 GDALProgressFunc pfnProgress = nullptr;
    3724             :                 std::unique_ptr<void, decltype(&GDALDestroyScaledProgress)>
    3725           2 :                     pProgressArg(nullptr, GDALDestroyScaledProgress);
    3726             : 
    3727           1 :                 if (psOptions->bDisplayProgress &&
    3728           1 :                     psOptions->nMaxSplitListSubFields != 1 &&
    3729             :                     nCountLayersFeatures != 0)
    3730             :                 {
    3731           0 :                     pfnProgress = GDALScaledProgress;
    3732           0 :                     pProgressArg.reset(GDALCreateScaledProgress(
    3733             :                         nAccCountFeatures * 1.0 / nCountLayersFeatures,
    3734           0 :                         (nAccCountFeatures + anLayerCountFeatures[iLayer] / 2) *
    3735             :                             1.0 / nCountLayersFeatures,
    3736           0 :                         psOptions->pfnProgress, psOptions->pProgressData));
    3737             :                 }
    3738             : 
    3739             :                 int nRet =
    3740           1 :                     poSLFLayer->BuildLayerDefn(pfnProgress, pProgressArg.get());
    3741           1 :                 if (nRet)
    3742             :                 {
    3743           1 :                     poLayerToFree = std::move(poSLFLayer);
    3744           1 :                     poPassedLayer = poLayerToFree.get();
    3745             :                 }
    3746             :             }
    3747             : 
    3748        1027 :             GDALProgressFunc pfnProgress = nullptr;
    3749             :             std::unique_ptr<void, decltype(&GDALDestroyScaledProgress)>
    3750        2054 :                 pProgressArg(nullptr, GDALDestroyScaledProgress);
    3751             : 
    3752        1027 :             if (psOptions->bDisplayProgress)
    3753             :             {
    3754          13 :                 if (nCountLayersFeatures != 0)
    3755             :                 {
    3756          13 :                     pfnProgress = GDALScaledProgress;
    3757          13 :                     GIntBig nStart = 0;
    3758          13 :                     if (poPassedLayer != poLayer &&
    3759           0 :                         psOptions->nMaxSplitListSubFields != 1)
    3760           0 :                         nStart = anLayerCountFeatures[iLayer] / 2;
    3761          13 :                     pProgressArg.reset(GDALCreateScaledProgress(
    3762          13 :                         (nAccCountFeatures + nStart) * 1.0 /
    3763             :                             nCountLayersFeatures,
    3764          13 :                         (nAccCountFeatures + anLayerCountFeatures[iLayer]) *
    3765             :                             1.0 / nCountLayersFeatures,
    3766          13 :                         psOptions->pfnProgress, psOptions->pProgressData));
    3767             :                 }
    3768             : 
    3769          13 :                 nAccCountFeatures += anLayerCountFeatures[iLayer];
    3770             :             }
    3771             : 
    3772             :             auto psInfo = oSetup.Setup(poPassedLayer,
    3773        1027 :                                        psOptions->osNewLayerName.empty()
    3774             :                                            ? nullptr
    3775          37 :                                            : psOptions->osNewLayerName.c_str(),
    3776        3118 :                                        psOptions.get(), nTotalEventsDone);
    3777             : 
    3778        1027 :             poPassedLayer->ResetReading();
    3779             : 
    3780        4104 :             if ((psInfo == nullptr ||
    3781        3077 :                  !oTranslator.Translate(nullptr, psInfo.get(),
    3782        1025 :                                         anLayerCountFeatures[iLayer], nullptr,
    3783             :                                         nTotalEventsDone, pfnProgress,
    3784        2054 :                                         pProgressArg.get(), psOptions.get())) &&
    3785          17 :                 !psOptions->bSkipFailures)
    3786             :             {
    3787          16 :                 if (psOptions->bInvokedFromGdalAlgorithm)
    3788             :                 {
    3789           9 :                     CPLError(CE_Failure, CPLE_AppDefined,
    3790             :                              "Failed to write layer '%s'. Use --skip-errors to "
    3791             :                              "ignore errors and continue writing.",
    3792           9 :                              poLayer->GetName());
    3793             :                 }
    3794             :                 else
    3795             :                 {
    3796           7 :                     CPLError(
    3797             :                         CE_Failure, CPLE_AppDefined,
    3798             :                         "Terminating translation prematurely after failed\n"
    3799             :                         "translation of layer %s (use -skipfailures to skip "
    3800             :                         "errors)",
    3801           7 :                         poLayer->GetName());
    3802             :                 }
    3803             : 
    3804          16 :                 nRetCode = 1;
    3805             :             }
    3806             : 
    3807        1027 :             if (psInfo)
    3808        1025 :                 psInfo->CheckSameCoordinateOperation();
    3809             :         }
    3810             :     }
    3811             : 
    3812         983 :     CopyRelationships(poODS, poDS);
    3813             : 
    3814             :     /* -------------------------------------------------------------------- */
    3815             :     /*      Process DS style table                                          */
    3816             :     /* -------------------------------------------------------------------- */
    3817             : 
    3818         983 :     poODS->SetStyleTable(poDS->GetStyleTable());
    3819             : 
    3820         983 :     if (psOptions->nGroupTransactions)
    3821             :     {
    3822         982 :         if (!psOptions->nLayerTransaction)
    3823             :         {
    3824         173 :             if (nRetCode != 0 && !psOptions->bSkipFailures)
    3825           8 :                 poODS->RollbackTransaction();
    3826             :             else
    3827             :             {
    3828         165 :                 OGRErr eRet = poODS->CommitTransaction();
    3829         165 :                 if (eRet != OGRERR_NONE && eRet != OGRERR_UNSUPPORTED_OPERATION)
    3830             :                 {
    3831           1 :                     nRetCode = 1;
    3832             :                 }
    3833             :             }
    3834             :         }
    3835             :     }
    3836             : 
    3837             :     // Note: this guarantees that the file can be opened in a consistent state,
    3838             :     // without requiring to close poODS, only if the driver declares
    3839             :     // DCAP_FLUSHCACHE_CONSISTENT_STATE
    3840         983 :     if (poODS->FlushCache() != CE_None)
    3841           0 :         nRetCode = 1;
    3842             : 
    3843         983 :     if (nRetCode == 0)
    3844             :     {
    3845         964 :         if (hDstDS)
    3846          28 :             return hDstDS;
    3847             :         else
    3848         936 :             return GDALDataset::ToHandle(poODSUniquePtr.release());
    3849             :     }
    3850             : 
    3851          19 :     return nullptr;
    3852             : }
    3853             : 
    3854             : /************************************************************************/
    3855             : /*                                SetZ()                                */
    3856             : /************************************************************************/
    3857             : 
    3858             : namespace
    3859             : {
    3860             : class SetZVisitor : public OGRDefaultGeometryVisitor
    3861             : {
    3862             :     double m_dfZ;
    3863             : 
    3864             :   public:
    3865          30 :     explicit SetZVisitor(double dfZ) : m_dfZ(dfZ)
    3866             :     {
    3867          30 :     }
    3868             : 
    3869             :     using OGRDefaultGeometryVisitor::visit;
    3870             : 
    3871         735 :     void visit(OGRPoint *poPoint) override
    3872             :     {
    3873         735 :         poPoint->setZ(m_dfZ);
    3874         735 :     }
    3875             : };
    3876             : }  // namespace
    3877             : 
    3878          30 : static void SetZ(OGRGeometry *poGeom, double dfZ)
    3879             : {
    3880          30 :     if (poGeom == nullptr)
    3881           0 :         return;
    3882          60 :     SetZVisitor visitor(dfZ);
    3883          30 :     poGeom->set3D(true);
    3884          30 :     poGeom->accept(&visitor);
    3885             : }
    3886             : 
    3887             : /************************************************************************/
    3888             : /*                        ForceCoordDimension()                         */
    3889             : /************************************************************************/
    3890             : 
    3891        1323 : static int ForceCoordDimension(int eGType, int nCoordDim)
    3892             : {
    3893        1323 :     if (nCoordDim == 2 && eGType != wkbNone)
    3894           3 :         return wkbFlatten(eGType);
    3895        1320 :     else if (nCoordDim == 3 && eGType != wkbNone)
    3896           3 :         return wkbSetZ(wkbFlatten(eGType));
    3897        1317 :     else if (nCoordDim == COORD_DIM_XYM && eGType != wkbNone)
    3898           2 :         return wkbSetM(wkbFlatten(eGType));
    3899        1315 :     else if (nCoordDim == 4 && eGType != wkbNone)
    3900           2 :         return OGR_GT_SetModifier(static_cast<OGRwkbGeometryType>(eGType), TRUE,
    3901           2 :                                   TRUE);
    3902             :     else
    3903        1313 :         return eGType;
    3904             : }
    3905             : 
    3906             : /************************************************************************/
    3907             : /*                  GetLayerAndOverwriteIfNecessary()                   */
    3908             : /************************************************************************/
    3909             : 
    3910        1191 : static OGRLayer *GetLayerAndOverwriteIfNecessary(GDALDataset *poDstDS,
    3911             :                                                  const char *pszNewLayerName,
    3912             :                                                  bool bOverwrite,
    3913             :                                                  bool *pbErrorOccurred,
    3914             :                                                  bool *pbOverwriteActuallyDone,
    3915             :                                                  bool *pbAddOverwriteLCO)
    3916             : {
    3917        1191 :     if (pbErrorOccurred)
    3918        1191 :         *pbErrorOccurred = false;
    3919        1191 :     if (pbOverwriteActuallyDone)
    3920        1191 :         *pbOverwriteActuallyDone = false;
    3921        1191 :     if (pbAddOverwriteLCO)
    3922        1191 :         *pbAddOverwriteLCO = false;
    3923             : 
    3924             :     /* GetLayerByName() can instantiate layers that would have been */
    3925             :     /* 'hidden' otherwise, for example, non-spatial tables in a */
    3926             :     /* PostGIS-enabled database, so this apparently useless command is */
    3927             :     /* not useless. (#4012) */
    3928        1191 :     CPLPushErrorHandler(CPLQuietErrorHandler);
    3929        1191 :     OGRLayer *poDstLayer = poDstDS->GetLayerByName(pszNewLayerName);
    3930        1191 :     CPLPopErrorHandler();
    3931        1191 :     CPLErrorReset();
    3932             : 
    3933        1191 :     int iLayer = -1;
    3934        1191 :     if (poDstLayer != nullptr)
    3935             :     {
    3936          65 :         const int nLayerCount = poDstDS->GetLayerCount();
    3937         379 :         for (iLayer = 0; iLayer < nLayerCount; iLayer++)
    3938             :         {
    3939         379 :             OGRLayer *poLayer = poDstDS->GetLayer(iLayer);
    3940         379 :             if (poLayer == poDstLayer)
    3941          65 :                 break;
    3942             :         }
    3943             : 
    3944          65 :         if (iLayer == nLayerCount)
    3945             :             /* should not happen with an ideal driver */
    3946           0 :             poDstLayer = nullptr;
    3947             :     }
    3948             : 
    3949             :     /* -------------------------------------------------------------------- */
    3950             :     /*      If the user requested overwrite, and we have the layer in       */
    3951             :     /*      question we need to delete it now so it will get recreated      */
    3952             :     /*      (overwritten).                                                  */
    3953             :     /* -------------------------------------------------------------------- */
    3954        1191 :     if (poDstLayer != nullptr && bOverwrite)
    3955             :     {
    3956             :         /* When using the CARTO driver we don't want to delete the layer if */
    3957             :         /* it's going to be recreated. Instead we mark it to be overwritten */
    3958             :         /* when the new creation is requested */
    3959          16 :         if (poDstDS->GetDriver()->GetMetadataItem(
    3960          32 :                 GDAL_DS_LAYER_CREATIONOPTIONLIST) != nullptr &&
    3961          32 :             strstr(poDstDS->GetDriver()->GetMetadataItem(
    3962          16 :                        GDAL_DS_LAYER_CREATIONOPTIONLIST),
    3963             :                    "CARTODBFY") != nullptr)
    3964             :         {
    3965           0 :             if (pbAddOverwriteLCO)
    3966           0 :                 *pbAddOverwriteLCO = true;
    3967           0 :             if (pbOverwriteActuallyDone)
    3968           0 :                 *pbOverwriteActuallyDone = true;
    3969             :         }
    3970          16 :         else if (poDstDS->DeleteLayer(iLayer) != OGRERR_NONE)
    3971             :         {
    3972           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3973             :                      "DeleteLayer() failed when overwrite requested.");
    3974           0 :             if (pbErrorOccurred)
    3975           0 :                 *pbErrorOccurred = true;
    3976             :         }
    3977             :         else
    3978             :         {
    3979          16 :             if (pbOverwriteActuallyDone)
    3980          16 :                 *pbOverwriteActuallyDone = true;
    3981             :         }
    3982          16 :         poDstLayer = nullptr;
    3983             :     }
    3984             : 
    3985        1191 :     return poDstLayer;
    3986             : }
    3987             : 
    3988             : /************************************************************************/
    3989             : /*                            ConvertType()                             */
    3990             : /************************************************************************/
    3991             : 
    3992        1314 : static OGRwkbGeometryType ConvertType(GeomTypeConversion eGeomTypeConversion,
    3993             :                                       OGRwkbGeometryType eGType)
    3994             : {
    3995        1314 :     OGRwkbGeometryType eRetType = eGType;
    3996             : 
    3997        1314 :     if (eGeomTypeConversion == GTC_CONVERT_TO_LINEAR ||
    3998             :         eGeomTypeConversion == GTC_PROMOTE_TO_MULTI_AND_CONVERT_TO_LINEAR)
    3999             :     {
    4000          13 :         eRetType = OGR_GT_GetLinear(eRetType);
    4001             :     }
    4002             : 
    4003        1314 :     if (eGeomTypeConversion == GTC_PROMOTE_TO_MULTI ||
    4004             :         eGeomTypeConversion == GTC_PROMOTE_TO_MULTI_AND_CONVERT_TO_LINEAR)
    4005             :     {
    4006          12 :         if (eRetType == wkbTriangle || eRetType == wkbTIN ||
    4007             :             eRetType == wkbPolyhedralSurface)
    4008             :         {
    4009           0 :             eRetType = wkbMultiPolygon;
    4010             :         }
    4011          12 :         else if (!OGR_GT_IsSubClassOf(eRetType, wkbGeometryCollection))
    4012             :         {
    4013           8 :             eRetType = OGR_GT_GetCollection(eRetType);
    4014             :         }
    4015             :     }
    4016             : 
    4017        1314 :     if (eGeomTypeConversion == GTC_CONVERT_TO_CURVE)
    4018           2 :         eRetType = OGR_GT_GetCurve(eRetType);
    4019             : 
    4020        1314 :     return eRetType;
    4021             : }
    4022             : 
    4023             : /************************************************************************/
    4024             : /*                       DoFieldTypeConversion()                        */
    4025             : /************************************************************************/
    4026             : 
    4027        3744 : static void DoFieldTypeConversion(GDALDataset *poDstDS,
    4028             :                                   OGRFieldDefn &oFieldDefn,
    4029             :                                   CSLConstList papszFieldTypesToString,
    4030             :                                   CSLConstList papszMapFieldType,
    4031             :                                   bool bUnsetFieldWidth, bool bQuiet,
    4032             :                                   bool bForceNullable, bool bUnsetDefault)
    4033             : {
    4034        3744 :     if (papszFieldTypesToString != nullptr)
    4035             :     {
    4036           0 :         CPLString osLookupString;
    4037             :         osLookupString.Printf(
    4038             :             "%s(%s)", OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()),
    4039           0 :             OGRFieldDefn::GetFieldSubTypeName(oFieldDefn.GetSubType()));
    4040             : 
    4041           0 :         int iIdx = CSLFindString(papszFieldTypesToString, osLookupString);
    4042           0 :         if (iIdx < 0)
    4043           0 :             iIdx = CSLFindString(
    4044             :                 papszFieldTypesToString,
    4045             :                 OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()));
    4046           0 :         if (iIdx < 0)
    4047           0 :             iIdx = CSLFindString(papszFieldTypesToString, "All");
    4048           0 :         if (iIdx >= 0)
    4049             :         {
    4050           0 :             oFieldDefn.SetSubType(OFSTNone);
    4051           0 :             oFieldDefn.SetType(OFTString);
    4052             :         }
    4053             :     }
    4054        3744 :     else if (papszMapFieldType != nullptr)
    4055             :     {
    4056          28 :         CPLString osLookupString;
    4057             :         osLookupString.Printf(
    4058             :             "%s(%s)", OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()),
    4059          14 :             OGRFieldDefn::GetFieldSubTypeName(oFieldDefn.GetSubType()));
    4060             : 
    4061             :         const char *pszType =
    4062          14 :             CSLFetchNameValue(papszMapFieldType, osLookupString);
    4063          14 :         if (pszType == nullptr)
    4064          13 :             pszType = CSLFetchNameValue(
    4065             :                 papszMapFieldType,
    4066             :                 OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()));
    4067          14 :         if (pszType == nullptr)
    4068          10 :             pszType = CSLFetchNameValue(papszMapFieldType, "All");
    4069          14 :         if (pszType != nullptr)
    4070             :         {
    4071             :             int iSubType;
    4072           4 :             int iType = GetFieldType(pszType, &iSubType);
    4073           4 :             if (iType >= 0 && iSubType >= 0)
    4074             :             {
    4075           4 :                 oFieldDefn.SetSubType(OFSTNone);
    4076           4 :                 oFieldDefn.SetType(static_cast<OGRFieldType>(iType));
    4077           4 :                 oFieldDefn.SetSubType(static_cast<OGRFieldSubType>(iSubType));
    4078           4 :                 if (iType == OFTInteger)
    4079           1 :                     oFieldDefn.SetWidth(0);
    4080             :             }
    4081             :         }
    4082             :     }
    4083        3744 :     if (bUnsetFieldWidth)
    4084             :     {
    4085           6 :         oFieldDefn.SetWidth(0);
    4086           6 :         oFieldDefn.SetPrecision(0);
    4087             :     }
    4088        3744 :     if (bForceNullable)
    4089           4 :         oFieldDefn.SetNullable(TRUE);
    4090        3744 :     if (bUnsetDefault)
    4091           2 :         oFieldDefn.SetDefault(nullptr);
    4092             : 
    4093        3744 :     const auto poDstDriver = poDstDS->GetDriver();
    4094             :     const char *pszCreationFieldDataTypes =
    4095             :         poDstDriver
    4096        3744 :             ? poDstDriver->GetMetadataItem(GDAL_DMD_CREATIONFIELDDATATYPES)
    4097        3744 :             : nullptr;
    4098             :     const char *pszCreationFieldDataSubtypes =
    4099             :         poDstDriver
    4100        3744 :             ? poDstDriver->GetMetadataItem(GDAL_DMD_CREATIONFIELDDATASUBTYPES)
    4101        3744 :             : nullptr;
    4102        7373 :     if (pszCreationFieldDataTypes &&
    4103        3629 :         strstr(pszCreationFieldDataTypes,
    4104             :                OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType())) == nullptr)
    4105             :     {
    4106          30 :         if (pszCreationFieldDataSubtypes &&
    4107          58 :             (oFieldDefn.GetType() == OFTIntegerList ||
    4108          55 :              oFieldDefn.GetType() == OFTInteger64List ||
    4109          53 :              oFieldDefn.GetType() == OFTRealList ||
    4110          88 :              oFieldDefn.GetType() == OFTStringList) &&
    4111          25 :             strstr(pszCreationFieldDataSubtypes, "JSON"))
    4112             :         {
    4113           5 :             if (!bQuiet)
    4114             :             {
    4115           5 :                 CPLError(
    4116             :                     CE_Warning, CPLE_AppDefined,
    4117             :                     "The output driver does not seem to natively support %s "
    4118             :                     "type for field %s. Converting it to String(JSON) instead. "
    4119             :                     "-mapFieldType can be used to control field type "
    4120             :                     "conversion.",
    4121             :                     OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()),
    4122             :                     oFieldDefn.GetNameRef());
    4123             :             }
    4124           5 :             oFieldDefn.SetSubType(OFSTNone);
    4125           5 :             oFieldDefn.SetType(OFTString);
    4126           5 :             oFieldDefn.SetSubType(OFSTJSON);
    4127             :         }
    4128          27 :         else if (oFieldDefn.GetType() == OFTInteger64)
    4129             :         {
    4130           1 :             if (!bQuiet)
    4131             :             {
    4132           1 :                 CPLError(
    4133             :                     CE_Warning, CPLE_AppDefined,
    4134             :                     "The output driver does not seem to natively support %s "
    4135             :                     "type for field %s. Converting it to Real instead. "
    4136             :                     "-mapFieldType can be used to control field type "
    4137             :                     "conversion.",
    4138             :                     OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()),
    4139             :                     oFieldDefn.GetNameRef());
    4140             :             }
    4141           1 :             oFieldDefn.SetType(OFTReal);
    4142             :         }
    4143          30 :         else if (oFieldDefn.GetType() == OFTDateTime && poDstDriver &&
    4144           4 :                  EQUAL(poDstDriver->GetDescription(), "ESRI Shapefile"))
    4145             :         {
    4146             :             // Just be silent. The shapefile driver will itself emit a
    4147             :             // warning mentioning it converts DateTime to String.
    4148             :         }
    4149          25 :         else if (!bQuiet)
    4150             :         {
    4151          25 :             CPLError(
    4152             :                 CE_Warning, CPLE_AppDefined,
    4153             :                 "The output driver does not natively support %s type for "
    4154             :                 "field %s. Misconversion can happen. "
    4155             :                 "-mapFieldType can be used to control field type conversion.",
    4156             :                 OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()),
    4157             :                 oFieldDefn.GetNameRef());
    4158             :         }
    4159             :     }
    4160        3712 :     else if (!pszCreationFieldDataTypes)
    4161             :     {
    4162             :         // All drivers supporting OFTInteger64 should advertise it theoretically
    4163         115 :         if (oFieldDefn.GetType() == OFTInteger64)
    4164             :         {
    4165           1 :             if (!bQuiet)
    4166             :             {
    4167           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    4168             :                          "The output driver does not seem to natively support "
    4169             :                          "%s type "
    4170             :                          "for field %s. Converting it to Real instead. "
    4171             :                          "-mapFieldType can be used to control field type "
    4172             :                          "conversion.",
    4173             :                          OGRFieldDefn::GetFieldTypeName(oFieldDefn.GetType()),
    4174             :                          oFieldDefn.GetNameRef());
    4175             :             }
    4176           1 :             oFieldDefn.SetType(OFTReal);
    4177             :         }
    4178             :     }
    4179        3744 : }
    4180             : 
    4181             : /************************************************************************/
    4182             : /*                       GetArrowGeomFieldIndex()                       */
    4183             : /************************************************************************/
    4184             : 
    4185          24 : static int GetArrowGeomFieldIndex(const struct ArrowSchema *psLayerSchema,
    4186             :                                   const char *pszFieldName)
    4187             : {
    4188          24 :     if (strcmp(psLayerSchema->format, "+s") == 0)  // struct
    4189             :     {
    4190          82 :         for (int i = 0; i < psLayerSchema->n_children; ++i)
    4191             :         {
    4192          82 :             const auto psSchema = psLayerSchema->children[i];
    4193          82 :             if (strcmp(psSchema->format, "z") == 0)  // binary
    4194             :             {
    4195          24 :                 if (strcmp(psSchema->name, pszFieldName) == 0)
    4196             :                 {
    4197          22 :                     return i;
    4198             :                 }
    4199             :                 else
    4200             :                 {
    4201             :                     // Check if ARROW:extension:name = ogc.wkb or geoarrow.wkb
    4202           2 :                     const char *pabyMetadata = psSchema->metadata;
    4203           2 :                     if (pabyMetadata)
    4204             :                     {
    4205             :                         const auto oMetadata =
    4206           2 :                             OGRParseArrowMetadata(pabyMetadata);
    4207           2 :                         auto oIter = oMetadata.find(ARROW_EXTENSION_NAME_KEY);
    4208           4 :                         if (oIter != oMetadata.end() &&
    4209           2 :                             (oIter->second == EXTENSION_NAME_OGC_WKB ||
    4210           0 :                              oIter->second == EXTENSION_NAME_GEOARROW_WKB))
    4211             :                         {
    4212           2 :                             return i;
    4213             :                         }
    4214             :                     }
    4215             :                 }
    4216             :             }
    4217             :         }
    4218             :     }
    4219           0 :     return -1;
    4220             : }
    4221             : 
    4222             : /************************************************************************/
    4223             : /*                     BuildGetArrowStreamOptions()                     */
    4224             : /************************************************************************/
    4225             : 
    4226             : static CPLStringList
    4227         167 : BuildGetArrowStreamOptions(OGRLayer *poSrcLayer, OGRLayer *poDstLayer,
    4228             :                            const GDALVectorTranslateOptions *psOptions,
    4229             :                            bool bPreserveFID)
    4230             : {
    4231         167 :     CPLStringList aosOptionsGetArrowStream;
    4232         167 :     aosOptionsGetArrowStream.SetNameValue("SILENCE_GET_SCHEMA_ERROR", "YES");
    4233         167 :     aosOptionsGetArrowStream.SetNameValue("GEOMETRY_ENCODING", "WKB");
    4234         167 :     if (!bPreserveFID)
    4235         137 :         aosOptionsGetArrowStream.SetNameValue("INCLUDE_FID", "NO");
    4236         167 :     if (psOptions->nLimit >= 0)
    4237             :     {
    4238             :         aosOptionsGetArrowStream.SetNameValue(
    4239             :             "MAX_FEATURES_IN_BATCH",
    4240             :             CPLSPrintf(CPL_FRMT_GIB,
    4241           2 :                        std::min<GIntBig>(psOptions->nLimit,
    4242           2 :                                          (psOptions->nGroupTransactions > 0
    4243           4 :                                               ? psOptions->nGroupTransactions
    4244           2 :                                               : 65536))));
    4245             :     }
    4246         165 :     else if (psOptions->nGroupTransactions > 0)
    4247             :     {
    4248             :         aosOptionsGetArrowStream.SetNameValue(
    4249             :             "MAX_FEATURES_IN_BATCH",
    4250         165 :             CPLSPrintf("%d", psOptions->nGroupTransactions));
    4251             :     }
    4252             : 
    4253         167 :     auto poSrcDS = poSrcLayer->GetDataset();
    4254         167 :     auto poDstDS = poDstLayer->GetDataset();
    4255         167 :     if (poSrcDS && poDstDS)
    4256             :     {
    4257         163 :         auto poSrcDriver = poSrcDS->GetDriver();
    4258         163 :         auto poDstDriver = poDstDS->GetDriver();
    4259             : 
    4260         206 :         const auto IsArrowNativeDriver = [](GDALDriver *poDriver)
    4261             :         {
    4262         206 :             return EQUAL(poDriver->GetDescription(), "ARROW") ||
    4263         289 :                    EQUAL(poDriver->GetDescription(), "PARQUET") ||
    4264         289 :                    EQUAL(poDriver->GetDescription(), "ADBC");
    4265             :         };
    4266             : 
    4267         206 :         if (poSrcDriver && poDstDriver && !IsArrowNativeDriver(poSrcDriver) &&
    4268          43 :             !IsArrowNativeDriver(poDstDriver))
    4269             :         {
    4270             :             // For non-Arrow-native drivers, request DateTime as string, to
    4271             :             // allow mix of timezones
    4272             :             aosOptionsGetArrowStream.SetNameValue(GAS_OPT_DATETIME_AS_STRING,
    4273          40 :                                                   "YES");
    4274             :         }
    4275             :     }
    4276             : 
    4277         167 :     return aosOptionsGetArrowStream;
    4278             : }
    4279             : 
    4280             : /************************************************************************/
    4281             : /*              SetupTargetLayer::CanUseWriteArrowBatch()               */
    4282             : /************************************************************************/
    4283             : 
    4284        1187 : bool SetupTargetLayer::CanUseWriteArrowBatch(
    4285             :     OGRLayer *poSrcLayer, OGRLayer *poDstLayer, bool bJustCreatedLayer,
    4286             :     const GDALVectorTranslateOptions *psOptions, bool bPreserveFID,
    4287             :     bool &bError, OGRArrowArrayStream &streamSrc)
    4288             : {
    4289        1187 :     bError = false;
    4290             : 
    4291             :     // Check if we can use the Arrow interface to get and write features
    4292             :     // as it will be faster if the input driver has a fast
    4293             :     // implementation of GetArrowStream().
    4294             :     // We also can only do that only if using ogr2ogr without options that
    4295             :     // alter features.
    4296             :     // OGR2OGR_USE_ARROW_API config option is mostly for testing purposes
    4297             :     // or as a safety belt if things turned bad...
    4298        1187 :     bool bUseWriteArrowBatch = false;
    4299        1187 :     if (((poSrcLayer->TestCapability(OLCFastGetArrowStream) &&
    4300             :           // As we don't control the input array size when the input or output
    4301             :           // drivers are Arrow/Parquet (as they don't use the generic
    4302             :           // implementation), we can't guarantee that ROW_GROUP_SIZE/BATCH_SIZE
    4303             :           // layer creation options will be honored.
    4304         175 :           !psOptions->aosLCO.FetchNameValue("ROW_GROUP_SIZE") &&
    4305         173 :           !psOptions->aosLCO.FetchNameValue("BATCH_SIZE") &&
    4306         170 :           CPLTestBool(CPLGetConfigOption("OGR2OGR_USE_ARROW_API", "YES"))) ||
    4307        1018 :          CPLTestBool(CPLGetConfigOption("OGR2OGR_USE_ARROW_API", "NO"))) &&
    4308         180 :         !psOptions->bUpsert && !psOptions->bSkipFailures &&
    4309         348 :         !psOptions->poClipSrc && !psOptions->poClipDst &&
    4310         340 :         psOptions->asGCPs.empty() && !psOptions->bWrapDateline &&
    4311         170 :         !m_bAddMissingFields && m_eGType == GEOMTYPE_UNCHANGED &&
    4312         169 :         psOptions->eGeomOp == GEOMOP_NONE &&
    4313         169 :         m_eGeomTypeConversion == GTC_DEFAULT && m_nCoordDim < 0 &&
    4314         169 :         !m_papszFieldTypesToString && !m_papszMapFieldType &&
    4315         169 :         !m_bUnsetFieldWidth && !m_bExplodeCollections && !m_pszZField &&
    4316         168 :         m_bExactFieldNameMatch && !m_bForceNullable && !m_bResolveDomains &&
    4317         168 :         !m_bUnsetDefault && psOptions->nFIDToFetch == OGRNullFID &&
    4318         168 :         psOptions->dfXYRes == OGRGeomCoordinatePrecision::UNKNOWN &&
    4319        2374 :         !psOptions->bMakeValid && !psOptions->bSkipInvalidGeom)
    4320             :     {
    4321         168 :         if (psOptions->bTransform)
    4322             :         {
    4323             :             // To simplify implementation for now
    4324          26 :             if (poSrcLayer->GetLayerDefn()->GetGeomFieldCount() != 1 ||
    4325          13 :                 poDstLayer->GetLayerDefn()->GetGeomFieldCount() != 1)
    4326             :             {
    4327           1 :                 return false;
    4328             :             }
    4329          13 :             const auto poSrcSRS = m_poUserSourceSRS ? m_poUserSourceSRS
    4330          12 :                                                     : poSrcLayer->GetLayerDefn()
    4331          12 :                                                           ->GetGeomFieldDefn(0)
    4332          12 :                                                           ->GetSpatialRef();
    4333          13 :             if (!OGRGeometryFactory::isTransformWithOptionsRegularTransform(
    4334             :                     poSrcSRS, m_poOutputSRS, nullptr))
    4335             :             {
    4336           1 :                 return false;
    4337             :             }
    4338             :         }
    4339             : 
    4340         167 :         if (m_bSelFieldsSet)
    4341             :         {
    4342           2 :             SetIgnoredFields(poSrcLayer);
    4343             :         }
    4344             : 
    4345             :         const CPLStringList aosGetArrowStreamOptions(BuildGetArrowStreamOptions(
    4346         167 :             poSrcLayer, poDstLayer, psOptions, bPreserveFID));
    4347         167 :         if (poSrcLayer->GetArrowStream(streamSrc.get(),
    4348         167 :                                        aosGetArrowStreamOptions.List()))
    4349             :         {
    4350             :             struct ArrowSchema schemaSrc;
    4351         167 :             if (streamSrc.get_schema(&schemaSrc) == 0)
    4352             :             {
    4353         179 :                 if (psOptions->bTransform &&
    4354          12 :                     GetArrowGeomFieldIndex(&schemaSrc,
    4355          12 :                                            poSrcLayer->GetGeometryColumn()) < 0)
    4356             :                 {
    4357           0 :                     schemaSrc.release(&schemaSrc);
    4358           0 :                     streamSrc.clear();
    4359           0 :                     return false;
    4360             :                 }
    4361             : 
    4362         167 :                 std::string osErrorMsg;
    4363         167 :                 if (poDstLayer->IsArrowSchemaSupported(&schemaSrc, nullptr,
    4364         167 :                                                        osErrorMsg))
    4365             :                 {
    4366             :                     const OGRFeatureDefn *poSrcFDefn =
    4367         167 :                         poSrcLayer->GetLayerDefn();
    4368             :                     const OGRFeatureDefn *poDstFDefn =
    4369         167 :                         poDstLayer->GetLayerDefn();
    4370         165 :                     if (bJustCreatedLayer && poDstFDefn &&
    4371         497 :                         poDstFDefn->GetFieldCount() == 0 &&
    4372         165 :                         poDstFDefn->GetGeomFieldCount() ==
    4373         165 :                             poSrcFDefn->GetGeomFieldCount())
    4374             :                     {
    4375             :                         // Create output fields using CreateFieldFromArrowSchema()
    4376        1273 :                         for (int i = 0; i < schemaSrc.n_children; ++i)
    4377             :                         {
    4378        1108 :                             const char *pszFieldName =
    4379        1108 :                                 schemaSrc.children[i]->name;
    4380             : 
    4381             :                             const auto iSrcField =
    4382        1108 :                                 poSrcFDefn->GetFieldIndex(pszFieldName);
    4383        1108 :                             if (iSrcField >= 0)
    4384             :                             {
    4385             :                                 const auto poSrcFieldDefn =
    4386         910 :                                     poSrcFDefn->GetFieldDefn(iSrcField);
    4387             :                                 // Create field domain in output dataset if not already existing.
    4388             :                                 const std::string osDomainName(
    4389        1820 :                                     poSrcFieldDefn->GetDomainName());
    4390         910 :                                 if (!osDomainName.empty())
    4391             :                                 {
    4392          33 :                                     if (m_poDstDS->TestCapability(
    4393          22 :                                             ODsCAddFieldDomain) &&
    4394          11 :                                         m_poDstDS->GetFieldDomain(
    4395          11 :                                             osDomainName) == nullptr)
    4396             :                                     {
    4397             :                                         const auto poSrcDomain =
    4398          22 :                                             m_poSrcDS->GetFieldDomain(
    4399          11 :                                                 osDomainName);
    4400          11 :                                         if (poSrcDomain)
    4401             :                                         {
    4402          22 :                                             std::string failureReason;
    4403          11 :                                             if (!m_poDstDS->AddFieldDomain(
    4404          22 :                                                     std::unique_ptr<
    4405             :                                                         OGRFieldDomain>(
    4406          11 :                                                         poSrcDomain->Clone()),
    4407          11 :                                                     failureReason))
    4408             :                                             {
    4409           0 :                                                 CPLDebug("OGR2OGR",
    4410             :                                                          "Cannot create domain "
    4411             :                                                          "%s: %s",
    4412             :                                                          osDomainName.c_str(),
    4413             :                                                          failureReason.c_str());
    4414             :                                             }
    4415             :                                         }
    4416             :                                         else
    4417             :                                         {
    4418           0 :                                             CPLDebug("OGR2OGR",
    4419             :                                                      "Cannot find domain %s in "
    4420             :                                                      "source dataset",
    4421             :                                                      osDomainName.c_str());
    4422             :                                         }
    4423             :                                     }
    4424             :                                 }
    4425             :                             }
    4426             : 
    4427        3324 :                             if (!EQUAL(pszFieldName, "OGC_FID") &&
    4428        1108 :                                 !EQUAL(pszFieldName, "wkb_geometry") &&
    4429        1100 :                                 !EQUAL(pszFieldName,
    4430        1070 :                                        poSrcLayer->GetFIDColumn()) &&
    4431        1070 :                                 poSrcFDefn->GetGeomFieldIndex(pszFieldName) <
    4432        2216 :                                     0 &&
    4433         919 :                                 !poDstLayer->CreateFieldFromArrowSchema(
    4434         919 :                                     schemaSrc.children[i], nullptr))
    4435             :                             {
    4436           0 :                                 CPLError(CE_Failure, CPLE_AppDefined,
    4437             :                                          "Cannot create field %s",
    4438             :                                          pszFieldName);
    4439           0 :                                 schemaSrc.release(&schemaSrc);
    4440           0 :                                 streamSrc.clear();
    4441           0 :                                 return false;
    4442             :                             }
    4443             :                         }
    4444         165 :                         bUseWriteArrowBatch = true;
    4445             :                     }
    4446           2 :                     else if (!bJustCreatedLayer)
    4447             :                     {
    4448             :                         // If the layer already exist, get its schema, and
    4449             :                         // check that it looks to be the same as the source
    4450             :                         // one
    4451             :                         struct ArrowArrayStream streamDst;
    4452           2 :                         if (poDstLayer->GetArrowStream(
    4453           2 :                                 &streamDst, aosGetArrowStreamOptions.List()))
    4454             :                         {
    4455             :                             struct ArrowSchema schemaDst;
    4456           2 :                             if (streamDst.get_schema(&streamDst, &schemaDst) ==
    4457             :                                 0)
    4458             :                             {
    4459           2 :                                 if (schemaDst.n_children ==
    4460           2 :                                     schemaSrc.n_children)
    4461             :                                 {
    4462           2 :                                     bUseWriteArrowBatch = true;
    4463             :                                 }
    4464           2 :                                 schemaDst.release(&schemaDst);
    4465             :                             }
    4466           2 :                             streamDst.release(&streamDst);
    4467             :                         }
    4468             :                     }
    4469         167 :                     if (bUseWriteArrowBatch)
    4470             :                     {
    4471         167 :                         CPLDebug("OGR2OGR", "Using WriteArrowBatch()");
    4472             :                     }
    4473             :                 }
    4474             :                 else
    4475             :                 {
    4476           0 :                     CPLDebug("OGR2OGR",
    4477             :                              "Cannot use WriteArrowBatch() because "
    4478             :                              "input layer schema is not supported by output "
    4479             :                              "layer: %s",
    4480             :                              osErrorMsg.c_str());
    4481             :                 }
    4482         167 :                 schemaSrc.release(&schemaSrc);
    4483             :             }
    4484         167 :             if (!bUseWriteArrowBatch)
    4485           0 :                 streamSrc.clear();
    4486             :         }
    4487             :     }
    4488        1186 :     return bUseWriteArrowBatch;
    4489             : }
    4490             : 
    4491             : /************************************************************************/
    4492             : /*                 SetupTargetLayer::SetIgnoredFields()                 */
    4493             : /************************************************************************/
    4494             : 
    4495          12 : void SetupTargetLayer::SetIgnoredFields(OGRLayer *poSrcLayer)
    4496             : {
    4497          12 :     bool bUseIgnoredFields = true;
    4498          24 :     CPLStringList aosWHEREUsedFields;
    4499          12 :     const auto poSrcFDefn = poSrcLayer->GetLayerDefn();
    4500             : 
    4501          12 :     if (m_pszWHERE)
    4502             :     {
    4503             :         /* We must not ignore fields used in the -where expression
    4504             :          * (#4015) */
    4505           4 :         OGRFeatureQuery oFeatureQuery;
    4506           2 :         if (oFeatureQuery.Compile(poSrcFDefn, m_pszWHERE, FALSE, nullptr) ==
    4507             :             OGRERR_NONE)
    4508             :         {
    4509           0 :             aosWHEREUsedFields = oFeatureQuery.GetUsedFields();
    4510             :         }
    4511             :         else
    4512             :         {
    4513           2 :             bUseIgnoredFields = false;
    4514             :         }
    4515             :     }
    4516             : 
    4517          24 :     CPLStringList aosIgnoredFields;
    4518          40 :     for (int iSrcField = 0;
    4519          40 :          bUseIgnoredFields && iSrcField < poSrcFDefn->GetFieldCount();
    4520             :          iSrcField++)
    4521             :     {
    4522             :         const char *pszFieldName =
    4523          28 :             poSrcFDefn->GetFieldDefn(iSrcField)->GetNameRef();
    4524             :         bool bFieldRequested =
    4525          28 :             CSLFindString(m_papszSelFields, pszFieldName) >= 0;
    4526          28 :         bFieldRequested |= aosWHEREUsedFields.FindString(pszFieldName) >= 0;
    4527          28 :         bFieldRequested |=
    4528          28 :             (m_pszZField != nullptr && EQUAL(pszFieldName, m_pszZField));
    4529             : 
    4530             :         // If the source field is not requested, add it to the list of ignored
    4531             :         // fields.
    4532          28 :         if (!bFieldRequested)
    4533          15 :             aosIgnoredFields.push_back(pszFieldName);
    4534             :     }
    4535          12 :     if (bUseIgnoredFields)
    4536          10 :         poSrcLayer->SetIgnoredFields(
    4537          10 :             const_cast<const char **>(aosIgnoredFields.List()));
    4538          12 : }
    4539             : 
    4540             : /************************************************************************/
    4541             : /*                      SetupTargetLayer::Setup()                       */
    4542             : /************************************************************************/
    4543             : 
    4544             : std::unique_ptr<TargetLayerInfo>
    4545        1191 : SetupTargetLayer::Setup(OGRLayer *poSrcLayer, const char *pszNewLayerName,
    4546             :                         GDALVectorTranslateOptions *psOptions,
    4547             :                         GIntBig &nTotalEventsDone)
    4548             : {
    4549        1191 :     int eGType = m_eGType;
    4550        1191 :     bool bPreserveFID = m_bPreserveFID;
    4551        1191 :     bool bAppend = m_bAppend;
    4552             : 
    4553        1191 :     if (pszNewLayerName == nullptr)
    4554        1151 :         pszNewLayerName = poSrcLayer->GetName();
    4555             : 
    4556             :     /* -------------------------------------------------------------------- */
    4557             :     /*      Get other info.                                                 */
    4558             :     /* -------------------------------------------------------------------- */
    4559        1191 :     const OGRFeatureDefn *poSrcFDefn = poSrcLayer->GetLayerDefn();
    4560             : 
    4561             :     /* -------------------------------------------------------------------- */
    4562             :     /*      Find requested geometry fields.                                 */
    4563             :     /* -------------------------------------------------------------------- */
    4564        2382 :     std::vector<int> anRequestedGeomFields;
    4565        1191 :     const int nSrcGeomFieldCount = poSrcFDefn->GetGeomFieldCount();
    4566        1191 :     if (m_bSelFieldsSet && !bAppend)
    4567             :     {
    4568          44 :         for (int iField = 0; m_papszSelFields && m_papszSelFields[iField];
    4569             :              iField++)
    4570             :         {
    4571          27 :             int iSrcField = poSrcFDefn->GetFieldIndex(m_papszSelFields[iField]);
    4572          27 :             if (iSrcField >= 0)
    4573             :             {
    4574             :                 /* do nothing */
    4575             :             }
    4576             :             else
    4577             :             {
    4578           3 :                 iSrcField =
    4579           3 :                     poSrcFDefn->GetGeomFieldIndex(m_papszSelFields[iField]);
    4580           3 :                 if (iSrcField >= 0)
    4581             :                 {
    4582           3 :                     anRequestedGeomFields.push_back(iSrcField);
    4583             :                 }
    4584             :                 else
    4585             :                 {
    4586           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    4587             :                              "Field '%s' not found in source layer.",
    4588           0 :                              m_papszSelFields[iField]);
    4589           0 :                     if (!psOptions->bSkipFailures)
    4590           0 :                         return nullptr;
    4591             :                 }
    4592             :             }
    4593             :         }
    4594             : 
    4595          18 :         if (anRequestedGeomFields.size() > 1 &&
    4596           1 :             !m_poDstDS->TestCapability(ODsCCreateGeomFieldAfterCreateLayer))
    4597             :         {
    4598           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    4599             :                      "Several geometry fields requested, but output "
    4600             :                      "datasource does not support multiple geometry "
    4601             :                      "fields.");
    4602           0 :             if (!psOptions->bSkipFailures)
    4603           0 :                 return nullptr;
    4604             :             else
    4605           0 :                 anRequestedGeomFields.resize(0);
    4606             :         }
    4607             :     }
    4608             : 
    4609        1191 :     const OGRSpatialReference *poOutputSRS = m_poOutputSRS;
    4610        1191 :     if (poOutputSRS == nullptr && !m_bNullifyOutputSRS)
    4611             :     {
    4612        1043 :         if (nSrcGeomFieldCount == 1 || anRequestedGeomFields.empty())
    4613        1041 :             poOutputSRS = poSrcLayer->GetSpatialRef();
    4614           2 :         else if (anRequestedGeomFields.size() == 1)
    4615             :         {
    4616           1 :             int iSrcGeomField = anRequestedGeomFields[0];
    4617             :             poOutputSRS =
    4618           1 :                 poSrcFDefn->GetGeomFieldDefn(iSrcGeomField)->GetSpatialRef();
    4619             :         }
    4620             :     }
    4621             : 
    4622        1191 :     int iSrcZField = -1;
    4623        1191 :     if (m_pszZField != nullptr)
    4624             :     {
    4625           4 :         iSrcZField = poSrcFDefn->GetFieldIndex(m_pszZField);
    4626           4 :         if (iSrcZField < 0)
    4627             :         {
    4628           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    4629             :                      "zfield '%s' does not exist in layer %s", m_pszZField,
    4630           1 :                      poSrcLayer->GetName());
    4631             :         }
    4632             :     }
    4633             : 
    4634             :     /* -------------------------------------------------------------------- */
    4635             :     /*      Find the layer.                                                 */
    4636             :     /* -------------------------------------------------------------------- */
    4637             : 
    4638             :     bool bErrorOccurred;
    4639             :     bool bOverwriteActuallyDone;
    4640             :     bool bAddOverwriteLCO;
    4641        2382 :     OGRLayer *poDstLayer = GetLayerAndOverwriteIfNecessary(
    4642        1191 :         m_poDstDS, pszNewLayerName, m_bOverwrite, &bErrorOccurred,
    4643             :         &bOverwriteActuallyDone, &bAddOverwriteLCO);
    4644        1191 :     const bool bJustCreatedLayer = (poDstLayer == nullptr);
    4645        1191 :     if (bErrorOccurred)
    4646           0 :         return nullptr;
    4647             : 
    4648             :     /* -------------------------------------------------------------------- */
    4649             :     /*      If the layer does not exist, then create it.                    */
    4650             :     /* -------------------------------------------------------------------- */
    4651        1191 :     if (poDstLayer == nullptr)
    4652             :     {
    4653        1142 :         if (!m_poDstDS->TestCapability(ODsCCreateLayer))
    4654             :         {
    4655           0 :             CPLError(
    4656             :                 CE_Failure, CPLE_AppDefined,
    4657             :                 "Layer '%s' does not already exist in the output dataset, and "
    4658             :                 "cannot be created by the output driver.",
    4659             :                 pszNewLayerName);
    4660           4 :             return nullptr;
    4661             :         }
    4662             : 
    4663        1142 :         bool bForceGType = (eGType != GEOMTYPE_UNCHANGED);
    4664        1142 :         if (!bForceGType)
    4665             :         {
    4666        1122 :             if (anRequestedGeomFields.empty())
    4667             :             {
    4668        1120 :                 eGType = poSrcFDefn->GetGeomType();
    4669             :             }
    4670           2 :             else if (anRequestedGeomFields.size() == 1)
    4671             :             {
    4672           1 :                 int iSrcGeomField = anRequestedGeomFields[0];
    4673           1 :                 eGType = poSrcFDefn->GetGeomFieldDefn(iSrcGeomField)->GetType();
    4674             :             }
    4675             :             else
    4676             :             {
    4677           1 :                 eGType = wkbNone;
    4678             :             }
    4679             : 
    4680             :             bool bHasZ =
    4681        1122 :                 CPL_TO_BOOL(wkbHasZ(static_cast<OGRwkbGeometryType>(eGType)));
    4682        1122 :             eGType = ConvertType(m_eGeomTypeConversion,
    4683             :                                  static_cast<OGRwkbGeometryType>(eGType));
    4684             : 
    4685        1122 :             if (m_bExplodeCollections)
    4686             :             {
    4687          12 :                 const OGRwkbGeometryType eFGType = wkbFlatten(eGType);
    4688          12 :                 if (eFGType == wkbMultiPoint)
    4689             :                 {
    4690           1 :                     eGType = wkbPoint;
    4691             :                 }
    4692          11 :                 else if (eFGType == wkbMultiLineString)
    4693             :                 {
    4694           0 :                     eGType = wkbLineString;
    4695             :                 }
    4696          11 :                 else if (eFGType == wkbMultiPolygon)
    4697             :                 {
    4698           0 :                     eGType = wkbPolygon;
    4699             :                 }
    4700          11 :                 else if (eFGType == wkbGeometryCollection ||
    4701          11 :                          eFGType == wkbMultiCurve || eFGType == wkbMultiSurface)
    4702             :                 {
    4703           0 :                     eGType = wkbUnknown;
    4704             :                 }
    4705             :             }
    4706             : 
    4707        1122 :             if (bHasZ || (iSrcZField >= 0 && eGType != wkbNone))
    4708         114 :                 eGType = wkbSetZ(static_cast<OGRwkbGeometryType>(eGType));
    4709             :         }
    4710             : 
    4711        1142 :         eGType = ForceCoordDimension(eGType, m_nCoordDim);
    4712             : 
    4713        1142 :         CPLErrorReset();
    4714             : 
    4715        1142 :         CPLStringList aosLCOTemp(CSLDuplicate(m_papszLCO));
    4716             :         const char *pszDestCreationOptions =
    4717        1142 :             m_poDstDS->GetDriver()->GetMetadataItem(
    4718        1142 :                 GDAL_DS_LAYER_CREATIONOPTIONLIST);
    4719             : 
    4720        1142 :         int eGCreateLayerType = eGType;
    4721        1155 :         if (anRequestedGeomFields.empty() && nSrcGeomFieldCount > 1 &&
    4722          13 :             m_poDstDS->TestCapability(ODsCCreateGeomFieldAfterCreateLayer))
    4723             :         {
    4724          12 :             eGCreateLayerType = wkbNone;
    4725             :         }
    4726             :         // If the source layer has a single geometry column that is not nullable
    4727             :         // and that ODsCCreateGeomFieldAfterCreateLayer is available, use it
    4728             :         // so as to be able to set the not null constraint (if the driver
    4729             :         // supports it) and that the output driver has no GEOMETRY_NULLABLE
    4730             :         // layer creation option. Same if the source geometry column has a non
    4731             :         // empty name that is not overridden, and that the output driver has no
    4732             :         // GEOMETRY_NAME layer creation option, but no LAUNDER option (if
    4733             :         // laundering is available, then we might want to launder the geometry
    4734             :         // column name as well)
    4735         932 :         else if (eGType != wkbNone && anRequestedGeomFields.empty() &&
    4736         928 :                  nSrcGeomFieldCount == 1 &&
    4737         928 :                  m_poDstDS->TestCapability(
    4738        3280 :                      ODsCCreateGeomFieldAfterCreateLayer) &&
    4739         290 :                  ((!poSrcFDefn->GetGeomFieldDefn(0)->IsNullable() &&
    4740           2 :                    CSLFetchNameValue(m_papszLCO, "GEOMETRY_NULLABLE") ==
    4741           2 :                        nullptr &&
    4742           2 :                    (pszDestCreationOptions == nullptr ||
    4743           2 :                     strstr(pszDestCreationOptions, "GEOMETRY_NULLABLE") !=
    4744           0 :                         nullptr) &&
    4745           0 :                    !m_bForceNullable) ||
    4746         290 :                   (poSrcLayer->GetGeometryColumn() != nullptr &&
    4747         290 :                    CSLFetchNameValue(m_papszLCO, "GEOMETRY_NAME") == nullptr &&
    4748         290 :                    !EQUAL(poSrcLayer->GetGeometryColumn(), "") &&
    4749          49 :                    (pszDestCreationOptions == nullptr ||
    4750          49 :                     strstr(pszDestCreationOptions, "GEOMETRY_NAME") ==
    4751           8 :                         nullptr ||
    4752           8 :                     strstr(pszDestCreationOptions, "LAUNDER") != nullptr) &&
    4753          49 :                    poSrcFDefn->GetFieldIndex(poSrcLayer->GetGeometryColumn()) <
    4754             :                        0)))
    4755             :         {
    4756          49 :             anRequestedGeomFields.push_back(0);
    4757          49 :             eGCreateLayerType = wkbNone;
    4758             :         }
    4759        1082 :         else if (anRequestedGeomFields.size() == 1 &&
    4760           1 :                  m_poDstDS->TestCapability(ODsCCreateGeomFieldAfterCreateLayer))
    4761             :         {
    4762           0 :             eGCreateLayerType = wkbNone;
    4763             :         }
    4764             : 
    4765        1142 :         OGRGeomCoordinatePrecision oCoordPrec;
    4766        1142 :         std::string osGeomFieldName;
    4767        1142 :         bool bGeomFieldNullable = true;
    4768             : 
    4769             :         {
    4770        1142 :             int iSrcGeomField = -1;
    4771        1354 :             if (anRequestedGeomFields.empty() &&
    4772         212 :                 (nSrcGeomFieldCount == 1 ||
    4773         212 :                  (!m_poDstDS->TestCapability(
    4774         281 :                       ODsCCreateGeomFieldAfterCreateLayer) &&
    4775             :                   nSrcGeomFieldCount > 1)))
    4776             :             {
    4777         880 :                 iSrcGeomField = 0;
    4778             :             }
    4779         262 :             else if (anRequestedGeomFields.size() == 1)
    4780             :             {
    4781          50 :                 iSrcGeomField = anRequestedGeomFields[0];
    4782             :             }
    4783             : 
    4784        1142 :             if (iSrcGeomField >= 0)
    4785             :             {
    4786             :                 const auto poSrcGeomFieldDefn =
    4787         930 :                     poSrcFDefn->GetGeomFieldDefn(iSrcGeomField);
    4788         930 :                 if (!psOptions->bUnsetCoordPrecision)
    4789             :                 {
    4790         929 :                     oCoordPrec = poSrcGeomFieldDefn->GetCoordinatePrecision()
    4791        1858 :                                      .ConvertToOtherSRS(
    4792         929 :                                          poSrcGeomFieldDefn->GetSpatialRef(),
    4793         929 :                                          poOutputSRS);
    4794             :                 }
    4795             : 
    4796             :                 bGeomFieldNullable =
    4797         930 :                     CPL_TO_BOOL(poSrcGeomFieldDefn->IsNullable());
    4798             : 
    4799         930 :                 const char *pszGFldName = poSrcGeomFieldDefn->GetNameRef();
    4800        1167 :                 if (pszGFldName != nullptr && !EQUAL(pszGFldName, "") &&
    4801         237 :                     poSrcFDefn->GetFieldIndex(pszGFldName) < 0)
    4802             :                 {
    4803         236 :                     osGeomFieldName = pszGFldName;
    4804             : 
    4805             :                     // Use source geometry field name as much as possible
    4806         236 :                     if (eGType != wkbNone && pszDestCreationOptions &&
    4807         236 :                         strstr(pszDestCreationOptions, "GEOMETRY_NAME") !=
    4808         472 :                             nullptr &&
    4809         172 :                         CSLFetchNameValue(m_papszLCO, "GEOMETRY_NAME") ==
    4810             :                             nullptr)
    4811             :                     {
    4812         172 :                         aosLCOTemp.SetNameValue("GEOMETRY_NAME", pszGFldName);
    4813             :                     }
    4814             :                 }
    4815             :             }
    4816             :         }
    4817             : 
    4818             :         // If the source feature first geometry column is not nullable
    4819             :         // and that GEOMETRY_NULLABLE creation option is available, use it
    4820             :         // so as to be able to set the not null constraint (if the driver
    4821             :         // supports it)
    4822         944 :         if (eGType != wkbNone && anRequestedGeomFields.empty() &&
    4823         892 :             nSrcGeomFieldCount >= 1 &&
    4824         892 :             !poSrcFDefn->GetGeomFieldDefn(0)->IsNullable() &&
    4825           0 :             pszDestCreationOptions != nullptr &&
    4826           0 :             strstr(pszDestCreationOptions, "GEOMETRY_NULLABLE") != nullptr &&
    4827        2086 :             CSLFetchNameValue(m_papszLCO, "GEOMETRY_NULLABLE") == nullptr &&
    4828           0 :             !m_bForceNullable)
    4829             :         {
    4830           0 :             bGeomFieldNullable = false;
    4831           0 :             aosLCOTemp.SetNameValue("GEOMETRY_NULLABLE", "NO");
    4832           0 :             CPLDebug("GDALVectorTranslate", "Using GEOMETRY_NULLABLE=NO");
    4833             :         }
    4834             : 
    4835        1142 :         if (psOptions->dfXYRes != OGRGeomCoordinatePrecision::UNKNOWN)
    4836             :         {
    4837           7 :             if (m_poDstDS->GetDriver()->GetMetadataItem(
    4838           8 :                     GDAL_DCAP_HONOR_GEOM_COORDINATE_PRECISION) == nullptr &&
    4839           1 :                 !OGRGeometryFactory::haveGEOS())
    4840             :             {
    4841           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    4842             :                          "-xyRes specified, but driver does not expose the "
    4843             :                          "DCAP_HONOR_GEOM_COORDINATE_PRECISION capability, "
    4844             :                          "and this build has no GEOS support");
    4845             :             }
    4846             : 
    4847           7 :             oCoordPrec.dfXYResolution = psOptions->dfXYRes;
    4848           7 :             if (!psOptions->osXYResUnit.empty())
    4849             :             {
    4850           5 :                 if (!poOutputSRS)
    4851             :                 {
    4852           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    4853             :                              "Unit suffix for -xyRes cannot be used with an "
    4854             :                              "unknown destination SRS");
    4855           1 :                     return nullptr;
    4856             :                 }
    4857             : 
    4858           4 :                 if (psOptions->osXYResUnit == "mm")
    4859             :                 {
    4860           1 :                     oCoordPrec.dfXYResolution *= 1e-3;
    4861             :                 }
    4862           3 :                 else if (psOptions->osXYResUnit == "deg")
    4863             :                 {
    4864             :                     double dfFactorDegToMeter =
    4865           2 :                         poOutputSRS->GetSemiMajor(nullptr) * M_PI / 180;
    4866           2 :                     oCoordPrec.dfXYResolution *= dfFactorDegToMeter;
    4867             :                 }
    4868             :                 else
    4869             :                 {
    4870             :                     // Checked at argument parsing time
    4871           1 :                     CPLAssert(psOptions->osXYResUnit == "m");
    4872             :                 }
    4873             : 
    4874           4 :                 OGRGeomCoordinatePrecision tmp;
    4875           4 :                 tmp.SetFromMeter(poOutputSRS, oCoordPrec.dfXYResolution, 0, 0);
    4876           4 :                 oCoordPrec.dfXYResolution = tmp.dfXYResolution;
    4877             :             }
    4878             :         }
    4879             : 
    4880        1141 :         if (psOptions->dfZRes != OGRGeomCoordinatePrecision::UNKNOWN)
    4881             :         {
    4882           4 :             if (m_poDstDS->GetDriver()->GetMetadataItem(
    4883           4 :                     GDAL_DCAP_HONOR_GEOM_COORDINATE_PRECISION) == nullptr)
    4884             :             {
    4885           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    4886             :                          "-zRes specified, but driver does not expose the "
    4887             :                          "DCAP_HONOR_GEOM_COORDINATE_PRECISION capability");
    4888             :             }
    4889             : 
    4890           4 :             oCoordPrec.dfZResolution = psOptions->dfZRes;
    4891           4 :             if (!psOptions->osZResUnit.empty())
    4892             :             {
    4893           3 :                 if (!poOutputSRS)
    4894             :                 {
    4895           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    4896             :                              "Unit suffix for -zRes cannot be used with an "
    4897             :                              "unknown destination SRS");
    4898           1 :                     return nullptr;
    4899             :                 }
    4900             : 
    4901           2 :                 if (psOptions->osZResUnit == "mm")
    4902             :                 {
    4903           1 :                     oCoordPrec.dfZResolution *= 1e-3;
    4904             :                 }
    4905             :                 else
    4906             :                 {
    4907             :                     // Checked at argument parsing time
    4908           1 :                     CPLAssert(psOptions->osZResUnit == "m");
    4909             :                 }
    4910             : 
    4911           2 :                 OGRGeomCoordinatePrecision tmp;
    4912           2 :                 tmp.SetFromMeter(poOutputSRS, 0, oCoordPrec.dfZResolution, 0);
    4913           2 :                 oCoordPrec.dfZResolution = tmp.dfZResolution;
    4914             :             }
    4915             :         }
    4916             : 
    4917        1140 :         if (psOptions->dfMRes != OGRGeomCoordinatePrecision::UNKNOWN)
    4918             :         {
    4919           3 :             if (m_poDstDS->GetDriver()->GetMetadataItem(
    4920           3 :                     GDAL_DCAP_HONOR_GEOM_COORDINATE_PRECISION) == nullptr)
    4921             :             {
    4922           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    4923             :                          "-mRes specified, but driver does not expose the "
    4924             :                          "DCAP_HONOR_GEOM_COORDINATE_PRECISION capability");
    4925             :             }
    4926             : 
    4927           3 :             oCoordPrec.dfMResolution = psOptions->dfMRes;
    4928             :         }
    4929             : 
    4930             :         // For JSONFG
    4931        1140 :         CSLConstList papszMeasures = poSrcLayer->GetMetadata("MEASURES");
    4932        1140 :         if (papszMeasures && pszDestCreationOptions)
    4933             :         {
    4934           6 :             for (const char *pszItem : {"UNIT", "DESCRIPTION"})
    4935             :             {
    4936             :                 const char *pszValue =
    4937           4 :                     CSLFetchNameValue(papszMeasures, pszItem);
    4938           4 :                 if (pszValue)
    4939             :                 {
    4940             :                     const std::string osOptionName =
    4941          12 :                         std::string("MEASURE_").append(pszItem);
    4942           8 :                     if (strstr(pszDestCreationOptions, osOptionName.c_str()) &&
    4943           4 :                         CSLFetchNameValue(m_papszLCO, osOptionName.c_str()) ==
    4944             :                             nullptr)
    4945             :                     {
    4946           4 :                         aosLCOTemp.SetNameValue(osOptionName.c_str(), pszValue);
    4947             :                     }
    4948             :                 }
    4949             :             }
    4950             :         }
    4951             : 
    4952        1140 :         auto poSrcDriver = m_poSrcDS->GetDriver();
    4953             : 
    4954             :         // Force FID column as 64 bit if the source feature has a 64 bit FID,
    4955             :         // the target driver supports 64 bit FID and the user didn't set it
    4956             :         // manually.
    4957        1140 :         if (poSrcLayer->GetMetadataItem(OLMD_FID64) != nullptr &&
    4958           1 :             EQUAL(poSrcLayer->GetMetadataItem(OLMD_FID64), "YES") &&
    4959           1 :             pszDestCreationOptions &&
    4960        1141 :             strstr(pszDestCreationOptions, "FID64") != nullptr &&
    4961           0 :             CSLFetchNameValue(m_papszLCO, "FID64") == nullptr)
    4962             :         {
    4963           0 :             aosLCOTemp.SetNameValue("FID64", "YES");
    4964           0 :             CPLDebug("GDALVectorTranslate", "Using FID64=YES");
    4965             :         }
    4966             : 
    4967             :         // If output driver supports FID layer creation option, set it with
    4968             :         // the FID column name of the source layer
    4969        1138 :         if (!m_bUnsetFid && !bAppend && poSrcLayer->GetFIDColumn() != nullptr &&
    4970        1136 :             !EQUAL(poSrcLayer->GetFIDColumn(), "") &&
    4971          71 :             pszDestCreationOptions != nullptr &&
    4972          71 :             (strstr(pszDestCreationOptions, "='FID'") != nullptr ||
    4973        2280 :              strstr(pszDestCreationOptions, "=\"FID\"") != nullptr) &&
    4974          64 :             CSLFetchNameValue(m_papszLCO, "FID") == nullptr)
    4975             :         {
    4976          64 :             aosLCOTemp.SetNameValue("FID", poSrcLayer->GetFIDColumn());
    4977          64 :             if (!psOptions->bExplodeCollections)
    4978             :             {
    4979          63 :                 CPLDebug("GDALVectorTranslate",
    4980             :                          "Using FID=%s and -preserve_fid",
    4981          63 :                          poSrcLayer->GetFIDColumn());
    4982          63 :                 bPreserveFID = true;
    4983             :             }
    4984             :             else
    4985             :             {
    4986           1 :                 CPLDebug("GDALVectorTranslate",
    4987             :                          "Using FID=%s and disable -preserve_fid because not "
    4988             :                          "compatible with -explodecollection",
    4989           1 :                          poSrcLayer->GetFIDColumn());
    4990           1 :                 bPreserveFID = false;
    4991             :             }
    4992             :         }
    4993             :         // Detect scenario of converting from GPX to a format like GPKG
    4994             :         // Cf https://github.com/OSGeo/gdal/issues/9225
    4995        1071 :         else if (!bPreserveFID && !m_bUnsetFid && !bAppend && poSrcDriver &&
    4996         901 :                  EQUAL(poSrcDriver->GetDescription(), "GPX") &&
    4997           5 :                  pszDestCreationOptions &&
    4998           5 :                  (strstr(pszDestCreationOptions, "='FID'") != nullptr ||
    4999        2147 :                   strstr(pszDestCreationOptions, "=\"FID\"") != nullptr) &&
    5000           5 :                  CSLFetchNameValue(m_papszLCO, "FID") == nullptr)
    5001             :         {
    5002           5 :             CPLDebug("GDALVectorTranslate",
    5003             :                      "Forcing -preserve_fid because source is GPX and layers "
    5004             :                      "have FID cross references");
    5005           5 :             bPreserveFID = true;
    5006             :         }
    5007             :         // Detect scenario of converting GML2 with fid attribute to GPKG
    5008        1165 :         else if (EQUAL(m_poDstDS->GetDriver()->GetDescription(), "GPKG") &&
    5009          94 :                  CSLFetchNameValue(m_papszLCO, "FID") == nullptr)
    5010             :         {
    5011          92 :             int nFieldIdx = poSrcLayer->GetLayerDefn()->GetFieldIndex("fid");
    5012          93 :             if (nFieldIdx >= 0 && poSrcLayer->GetLayerDefn()
    5013           1 :                                           ->GetFieldDefn(nFieldIdx)
    5014           1 :                                           ->GetType() == OFTString)
    5015             :             {
    5016           1 :                 CPLDebug("GDALVectorTranslate",
    5017             :                          "Source layer has a non-string 'fid' column. Using "
    5018             :                          "FID=gpkg_fid for GeoPackage");
    5019           1 :                 aosLCOTemp.SetNameValue("FID", "gpkg_fid");
    5020             :             }
    5021             :         }
    5022             : 
    5023             :         // For a MapInfo -> MapInfo translation, preserve the layer bounds.
    5024        1140 :         if (m_poSrcDS->GetDriver() == m_poDstDS->GetDriver() &&
    5025         447 :             EQUAL(m_poDstDS->GetDriver()->GetDescription(), "MapInfo File") &&
    5026        1590 :             (m_poOutputSRS == nullptr || !m_bTransform) &&
    5027           3 :             CSLFetchNameValue(m_papszLCO, "BOUNDS") == nullptr)
    5028             :         {
    5029           3 :             if (const char *pszBounds = poSrcLayer->GetMetadataItem("BOUNDS"))
    5030             :             {
    5031           3 :                 CPLDebug("GDALVectorTranslate", "Setting -lco BOUNDS=%s",
    5032             :                          pszBounds);
    5033           3 :                 aosLCOTemp.SetNameValue("BOUNDS", pszBounds);
    5034             :             }
    5035             :         }
    5036             : 
    5037             :         // If bAddOverwriteLCO is ON (set up when overwriting a CARTO layer),
    5038             :         // set OVERWRITE to YES so the new layer overwrites the old one
    5039        1140 :         if (bAddOverwriteLCO)
    5040             :         {
    5041           0 :             aosLCOTemp.SetNameValue("OVERWRITE", "ON");
    5042           0 :             CPLDebug("GDALVectorTranslate", "Using OVERWRITE=ON");
    5043             :         }
    5044             : 
    5045        3419 :         if (m_bNativeData &&
    5046        1139 :             poSrcLayer->GetMetadataItem("NATIVE_DATA", "NATIVE_DATA") !=
    5047          25 :                 nullptr &&
    5048          25 :             poSrcLayer->GetMetadataItem("NATIVE_MEDIA_TYPE", "NATIVE_DATA") !=
    5049          25 :                 nullptr &&
    5050          25 :             pszDestCreationOptions != nullptr &&
    5051        2304 :             strstr(pszDestCreationOptions, "NATIVE_DATA") != nullptr &&
    5052          25 :             strstr(pszDestCreationOptions, "NATIVE_MEDIA_TYPE") != nullptr)
    5053             :         {
    5054             :             aosLCOTemp.SetNameValue(
    5055             :                 "NATIVE_DATA",
    5056          25 :                 poSrcLayer->GetMetadataItem("NATIVE_DATA", "NATIVE_DATA"));
    5057             :             aosLCOTemp.SetNameValue("NATIVE_MEDIA_TYPE",
    5058             :                                     poSrcLayer->GetMetadataItem(
    5059          25 :                                         "NATIVE_MEDIA_TYPE", "NATIVE_DATA"));
    5060          25 :             CPLDebug("GDALVectorTranslate", "Transferring layer NATIVE_DATA");
    5061             :         }
    5062             : 
    5063             :         // For FileGeodatabase, automatically set
    5064             :         // CREATE_SHAPE_AREA_AND_LENGTH_FIELDS=YES creation option if the source
    5065             :         // layer has a Shape_Area/Shape_Length field
    5066        2257 :         if (pszDestCreationOptions &&
    5067        1117 :             strstr(pszDestCreationOptions,
    5068        2257 :                    "CREATE_SHAPE_AREA_AND_LENGTH_FIELDS") != nullptr &&
    5069          28 :             CSLFetchNameValue(m_papszLCO,
    5070             :                               "CREATE_SHAPE_AREA_AND_LENGTH_FIELDS") == nullptr)
    5071             :         {
    5072          28 :             const auto poSrcLayerDefn = poSrcLayer->GetLayerDefn();
    5073             :             const int nIdxShapeArea =
    5074          28 :                 poSrcLayerDefn->GetFieldIndex("Shape_Area");
    5075             :             const int nIdxShapeLength =
    5076          28 :                 poSrcLayerDefn->GetFieldIndex("Shape_Length");
    5077          30 :             if ((nIdxShapeArea >= 0 &&
    5078           2 :                  poSrcLayerDefn->GetFieldDefn(nIdxShapeArea)->GetDefault() !=
    5079           2 :                      nullptr &&
    5080           2 :                  EQUAL(
    5081             :                      poSrcLayerDefn->GetFieldDefn(nIdxShapeArea)->GetDefault(),
    5082           2 :                      "FILEGEODATABASE_SHAPE_AREA") &&
    5083           2 :                  (m_papszSelFields == nullptr ||
    5084          31 :                   CSLFindString(m_papszSelFields, "Shape_Area") >= 0)) ||
    5085           1 :                 (nIdxShapeLength >= 0 &&
    5086           1 :                  poSrcLayerDefn->GetFieldDefn(nIdxShapeLength)->GetDefault() !=
    5087           1 :                      nullptr &&
    5088           1 :                  EQUAL(poSrcLayerDefn->GetFieldDefn(nIdxShapeLength)
    5089             :                            ->GetDefault(),
    5090           1 :                        "FILEGEODATABASE_SHAPE_LENGTH") &&
    5091           1 :                  (m_papszSelFields == nullptr ||
    5092           0 :                   CSLFindString(m_papszSelFields, "Shape_Length") >= 0)))
    5093             :             {
    5094             :                 aosLCOTemp.SetNameValue("CREATE_SHAPE_AREA_AND_LENGTH_FIELDS",
    5095           3 :                                         "YES");
    5096           3 :                 CPLDebug("GDALVectorTranslate",
    5097             :                          "Setting CREATE_SHAPE_AREA_AND_LENGTH_FIELDS=YES");
    5098             :             }
    5099             :         }
    5100             : 
    5101             :         // Use case of https://github.com/OSGeo/gdal/issues/11057#issuecomment-2495479779
    5102             :         // Conversion from GPKG to OCI.
    5103             :         // OCI distinguishes between TIMESTAMP and TIMESTAMP WITH TIME ZONE
    5104             :         // GeoPackage is supposed to have DateTime in UTC, so we set
    5105             :         // TIMESTAMP_WITH_TIME_ZONE=YES
    5106         973 :         if (poSrcDriver && pszDestCreationOptions &&
    5107         950 :             strstr(pszDestCreationOptions, "TIMESTAMP_WITH_TIME_ZONE") &&
    5108           0 :             CSLFetchNameValue(m_papszLCO, "TIMESTAMP_WITH_TIME_ZONE") ==
    5109        2113 :                 nullptr &&
    5110           0 :             EQUAL(poSrcDriver->GetDescription(), "GPKG"))
    5111             :         {
    5112           0 :             aosLCOTemp.SetNameValue("TIMESTAMP_WITH_TIME_ZONE", "YES");
    5113           0 :             CPLDebug("GDALVectorTranslate",
    5114             :                      "Setting TIMESTAMP_WITH_TIME_ZONE=YES");
    5115             :         }
    5116             : 
    5117             :         OGRGeomFieldDefn oGeomFieldDefn(
    5118             :             osGeomFieldName.c_str(),
    5119        1140 :             static_cast<OGRwkbGeometryType>(eGCreateLayerType));
    5120        1140 :         oGeomFieldDefn.SetSpatialRef(poOutputSRS);
    5121        1140 :         oGeomFieldDefn.SetCoordinatePrecision(oCoordPrec);
    5122        1140 :         oGeomFieldDefn.SetNullable(bGeomFieldNullable);
    5123        1140 :         poDstLayer = m_poDstDS->CreateLayer(
    5124             :             pszNewLayerName,
    5125             :             eGCreateLayerType == wkbNone ? nullptr : &oGeomFieldDefn,
    5126        1140 :             aosLCOTemp.List());
    5127             : 
    5128        1140 :         if (poDstLayer == nullptr)
    5129             :         {
    5130           2 :             return nullptr;
    5131             :         }
    5132             : 
    5133             :         // Cf https://github.com/OSGeo/gdal/issues/6859
    5134             :         // warn if the user requests -t_srs but the driver uses a different SRS.
    5135        1174 :         if (m_poOutputSRS != nullptr && m_bTransform && !psOptions->bQuiet &&
    5136             :             // MapInfo is somewhat lossy regarding SRS, so do not warn
    5137          36 :             !EQUAL(m_poDstDS->GetDriver()->GetDescription(), "MapInfo File"))
    5138             :         {
    5139          35 :             auto poCreatedSRS = poDstLayer->GetSpatialRef();
    5140          35 :             if (poCreatedSRS != nullptr)
    5141             :             {
    5142          21 :                 const char *const apszOptions[] = {
    5143             :                     "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES",
    5144             :                     "CRITERION=EQUIVALENT", nullptr};
    5145          21 :                 if (!poCreatedSRS->IsSame(m_poOutputSRS, apszOptions))
    5146             :                 {
    5147           1 :                     const char *pszTargetSRSName = m_poOutputSRS->GetName();
    5148           1 :                     const char *pszCreatedSRSName = poCreatedSRS->GetName();
    5149           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    5150             :                              "Target SRS %s not taken into account as target "
    5151             :                              "driver likely implements on-the-fly reprojection "
    5152             :                              "to %s",
    5153             :                              pszTargetSRSName ? pszTargetSRSName : "",
    5154             :                              pszCreatedSRSName ? pszCreatedSRSName : "");
    5155             :                 }
    5156             :             }
    5157             :         }
    5158             : 
    5159        1138 :         if (m_bCopyMD)
    5160             :         {
    5161        2268 :             const CPLStringList aosDomains(poSrcLayer->GetMetadataDomainList());
    5162        1715 :             for (const char *pszMD : aosDomains)
    5163             :             {
    5164         581 :                 if (!EQUAL(pszMD, "IMAGE_STRUCTURE") &&
    5165         581 :                     !EQUAL(pszMD, "SUBDATASETS"))
    5166             :                 {
    5167         581 :                     if (CSLConstList papszMD = poSrcLayer->GetMetadata(pszMD))
    5168             :                     {
    5169             :                         // MapInfo: Avoid overwriting the "BOUNDS" metadata on the output layer
    5170             :                         // with the value from the source layer. If the value should be
    5171             :                         // propagated, it will have been done via a layer creation option already.
    5172         773 :                         if (pszMD[0] == '\0' &&
    5173         256 :                             EQUAL(m_poDstDS->GetDriverName(), "MapInfo File"))
    5174             :                         {
    5175             :                             const char *pszBounds =
    5176           8 :                                 aosLCOTemp.FetchNameValue("BOUNDS");
    5177          16 :                             CPLStringList aosTmpMD(CSLDuplicate(papszMD), true);
    5178           8 :                             aosTmpMD.SetNameValue("BOUNDS", pszBounds);
    5179           8 :                             poDstLayer->SetMetadata(aosTmpMD.List(), pszMD);
    5180             :                         }
    5181             :                         else
    5182             :                         {
    5183         509 :                             poDstLayer->SetMetadata(papszMD, pszMD);
    5184             :                         }
    5185             :                     }
    5186             :                 }
    5187             :             }
    5188             :         }
    5189             : 
    5190        1151 :         if (anRequestedGeomFields.empty() && nSrcGeomFieldCount > 1 &&
    5191          13 :             m_poDstDS->TestCapability(ODsCCreateGeomFieldAfterCreateLayer))
    5192             :         {
    5193         143 :             for (int i = 0; i < nSrcGeomFieldCount; i++)
    5194             :             {
    5195         131 :                 anRequestedGeomFields.push_back(i);
    5196             :             }
    5197             :         }
    5198             : 
    5199        2313 :         if (anRequestedGeomFields.size() > 1 ||
    5200        1125 :             (anRequestedGeomFields.size() == 1 &&
    5201          50 :              m_poDstDS->TestCapability(ODsCCreateGeomFieldAfterCreateLayer)))
    5202             :         {
    5203         244 :             for (int i = 0; i < static_cast<int>(anRequestedGeomFields.size());
    5204             :                  i++)
    5205             :             {
    5206         182 :                 const int iSrcGeomField = anRequestedGeomFields[i];
    5207             :                 OGRGeomFieldDefn oGFldDefn(
    5208         364 :                     poSrcFDefn->GetGeomFieldDefn(iSrcGeomField));
    5209         182 :                 if (m_poOutputSRS != nullptr)
    5210             :                 {
    5211          13 :                     auto poOutputSRSClone = m_poOutputSRS->Clone();
    5212          13 :                     oGFldDefn.SetSpatialRef(poOutputSRSClone);
    5213          13 :                     poOutputSRSClone->Release();
    5214             :                 }
    5215         182 :                 if (bForceGType)
    5216             :                 {
    5217           1 :                     oGFldDefn.SetType(static_cast<OGRwkbGeometryType>(eGType));
    5218             :                 }
    5219             :                 else
    5220             :                 {
    5221         181 :                     eGType = oGFldDefn.GetType();
    5222         181 :                     eGType =
    5223         181 :                         ConvertType(m_eGeomTypeConversion,
    5224             :                                     static_cast<OGRwkbGeometryType>(eGType));
    5225         181 :                     eGType = ForceCoordDimension(eGType, m_nCoordDim);
    5226         181 :                     oGFldDefn.SetType(static_cast<OGRwkbGeometryType>(eGType));
    5227             :                 }
    5228         182 :                 if (m_bForceNullable)
    5229           2 :                     oGFldDefn.SetNullable(TRUE);
    5230         182 :                 poDstLayer->CreateGeomField(&oGFldDefn);
    5231             :             }
    5232             :         }
    5233             : 
    5234        1138 :         bAppend = false;
    5235             :     }
    5236             : 
    5237             :     /* -------------------------------------------------------------------- */
    5238             :     /*      Otherwise we will append to it, if append was requested.        */
    5239             :     /* -------------------------------------------------------------------- */
    5240          49 :     else if (!bAppend && !m_bNewDataSource)
    5241             :     {
    5242           0 :         if (psOptions->bInvokedFromGdalAlgorithm)
    5243             :         {
    5244           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5245             :                      "Layer %s already exists, and --append not specified. "
    5246             :                      "Consider using --append, or --overwrite-layer.",
    5247             :                      pszNewLayerName);
    5248             :         }
    5249             :         else
    5250             :         {
    5251           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5252             :                      "Layer %s already exists, and -append not specified.\n"
    5253             :                      "        Consider using -append, or -overwrite.",
    5254             :                      pszNewLayerName);
    5255             :         }
    5256           0 :         return nullptr;
    5257             :     }
    5258             :     else
    5259             :     {
    5260          49 :         if (CSLCount(m_papszLCO) > 0)
    5261             :         {
    5262           0 :             CPLError(
    5263             :                 CE_Warning, CPLE_AppDefined,
    5264             :                 "Layer creation options ignored since an existing layer is\n"
    5265             :                 "         being appended to.");
    5266             :         }
    5267             :     }
    5268             : 
    5269             :     /* -------------------------------------------------------------------- */
    5270             :     /*      Process Layer style table                                       */
    5271             :     /* -------------------------------------------------------------------- */
    5272             : 
    5273        1187 :     poDstLayer->SetStyleTable(poSrcLayer->GetStyleTable());
    5274             :     /* -------------------------------------------------------------------- */
    5275             :     /*      Add fields.  Default to copy all field.                         */
    5276             :     /*      If only a subset of all fields requested, then output only      */
    5277             :     /*      the selected fields, and in the order that they were            */
    5278             :     /*      selected.                                                       */
    5279             :     /* -------------------------------------------------------------------- */
    5280        1187 :     const int nSrcFieldCount = poSrcFDefn->GetFieldCount();
    5281        1187 :     int iSrcFIDField = -1;
    5282             : 
    5283             :     // Initialize the index-to-index map to -1's
    5284        2374 :     std::vector<int> anMap(nSrcFieldCount, -1);
    5285             : 
    5286        2374 :     std::map<int, TargetLayerInfo::ResolvedInfo> oMapResolved;
    5287             : 
    5288             :     /* Determine if NUMERIC field width narrowing is allowed */
    5289        1187 :     auto poSrcDriver = m_poSrcDS->GetDriver();
    5290             :     const char *pszSrcWidthIncludesDecimalSeparator{
    5291        2206 :         poSrcDriver ? poSrcDriver->GetMetadataItem(
    5292        1019 :                           "DMD_NUMERIC_FIELD_WIDTH_INCLUDES_DECIMAL_SEPARATOR")
    5293        1187 :                     : nullptr};
    5294        1187 :     const bool bSrcWidthIncludesDecimalSeparator{
    5295        1502 :         pszSrcWidthIncludesDecimalSeparator &&
    5296         315 :         EQUAL(pszSrcWidthIncludesDecimalSeparator, "YES")};
    5297             :     const char *pszDstWidthIncludesDecimalSeparator{
    5298        1187 :         m_poDstDS->GetDriver()->GetMetadataItem(
    5299        1187 :             "DMD_NUMERIC_FIELD_WIDTH_INCLUDES_DECIMAL_SEPARATOR")};
    5300        1187 :     const bool bDstWidthIncludesDecimalSeparator{
    5301        1410 :         pszDstWidthIncludesDecimalSeparator &&
    5302         223 :         EQUAL(pszDstWidthIncludesDecimalSeparator, "YES")};
    5303             :     const char *pszSrcWidthIncludesMinusSign{
    5304        2206 :         poSrcDriver ? poSrcDriver->GetMetadataItem(
    5305        1019 :                           "DMD_NUMERIC_FIELD_WIDTH_INCLUDES_SIGN")
    5306        1187 :                     : nullptr};
    5307        1187 :     const bool bSrcWidthIncludesMinusSign{
    5308        1502 :         pszSrcWidthIncludesMinusSign &&
    5309         315 :         EQUAL(pszSrcWidthIncludesMinusSign, "YES")};
    5310             :     const char *pszDstWidthIncludesMinusSign{
    5311        1187 :         m_poDstDS->GetDriver()->GetMetadataItem(
    5312        1187 :             "DMD_NUMERIC_FIELD_WIDTH_INCLUDES_SIGN")};
    5313        1187 :     const bool bDstWidthIncludesMinusSign{
    5314        1410 :         pszDstWidthIncludesMinusSign &&
    5315         223 :         EQUAL(pszDstWidthIncludesMinusSign, "YES")};
    5316             : 
    5317             :     // Calculate width delta
    5318        1187 :     int iChangeWidthBy{0};
    5319             : 
    5320        1187 :     if (bSrcWidthIncludesDecimalSeparator && !bDstWidthIncludesDecimalSeparator)
    5321             :     {
    5322         183 :         iChangeWidthBy--;
    5323             :     }
    5324        1004 :     else if (!bSrcWidthIncludesDecimalSeparator &&
    5325             :              bDstWidthIncludesDecimalSeparator)
    5326             :     {
    5327          91 :         iChangeWidthBy++;
    5328             :     }
    5329             : 
    5330             :     // We cannot assume there is no minus sign, we can only inflate here
    5331        1187 :     if (!bSrcWidthIncludesMinusSign && bDstWidthIncludesMinusSign)
    5332             :     {
    5333          91 :         iChangeWidthBy++;
    5334             :     }
    5335             : 
    5336        1187 :     bool bError = false;
    5337        2374 :     OGRArrowArrayStream streamSrc;
    5338             : 
    5339             :     const bool bUseWriteArrowBatch =
    5340        2374 :         !EQUAL(m_poDstDS->GetDriver()->GetDescription(), "OCI") &&
    5341        1187 :         CanUseWriteArrowBatch(poSrcLayer, poDstLayer, bJustCreatedLayer,
    5342        1187 :                               psOptions, bPreserveFID, bError, streamSrc);
    5343        1187 :     if (bError)
    5344           0 :         return nullptr;
    5345             : 
    5346             :     /* Caution : at the time of writing, the MapInfo driver */
    5347             :     /* returns NULL until a field has been added */
    5348        1187 :     OGRFeatureDefn *poDstFDefn = poDstLayer->GetLayerDefn();
    5349             : 
    5350        1187 :     if (bUseWriteArrowBatch)
    5351             :     {
    5352             :         // Fields created above
    5353             :     }
    5354        1020 :     else if (m_papszFieldMap && bAppend)
    5355             :     {
    5356           2 :         bool bIdentity = false;
    5357             : 
    5358           2 :         if (EQUAL(m_papszFieldMap[0], "identity"))
    5359           1 :             bIdentity = true;
    5360           1 :         else if (CSLCount(m_papszFieldMap) != nSrcFieldCount)
    5361             :         {
    5362           0 :             CPLError(
    5363             :                 CE_Failure, CPLE_AppDefined,
    5364             :                 "Field map should contain the value 'identity' or "
    5365             :                 "the same number of integer values as the source field count.");
    5366           0 :             return nullptr;
    5367             :         }
    5368             : 
    5369          32 :         for (int iField = 0; iField < nSrcFieldCount; iField++)
    5370             :         {
    5371          30 :             anMap[iField] = bIdentity ? iField : atoi(m_papszFieldMap[iField]);
    5372          30 :             if (anMap[iField] >= poDstFDefn->GetFieldCount())
    5373             :             {
    5374           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    5375           0 :                          "Invalid destination field index %d.", anMap[iField]);
    5376           0 :                 return nullptr;
    5377             :             }
    5378           2 :         }
    5379             :     }
    5380        1018 :     else if (m_bSelFieldsSet && !bAppend)
    5381             :     {
    5382          15 :         int nDstFieldCount = poDstFDefn ? poDstFDefn->GetFieldCount() : 0;
    5383          40 :         for (int iField = 0; m_papszSelFields && m_papszSelFields[iField];
    5384             :              iField++)
    5385             :         {
    5386             :             const int iSrcField =
    5387          25 :                 poSrcFDefn->GetFieldIndex(m_papszSelFields[iField]);
    5388          25 :             if (iSrcField >= 0)
    5389             :             {
    5390             :                 const OGRFieldDefn *poSrcFieldDefn =
    5391          22 :                     poSrcFDefn->GetFieldDefn(iSrcField);
    5392          22 :                 OGRFieldDefn oFieldDefn(poSrcFieldDefn);
    5393             : 
    5394          22 :                 DoFieldTypeConversion(
    5395             :                     m_poDstDS, oFieldDefn, m_papszFieldTypesToString,
    5396          22 :                     m_papszMapFieldType, m_bUnsetFieldWidth, psOptions->bQuiet,
    5397          22 :                     m_bForceNullable, m_bUnsetDefault);
    5398             : 
    5399          22 :                 if (iChangeWidthBy != 0 && oFieldDefn.GetType() == OFTReal &&
    5400           0 :                     oFieldDefn.GetWidth() != 0)
    5401             :                 {
    5402           0 :                     oFieldDefn.SetWidth(oFieldDefn.GetWidth() + iChangeWidthBy);
    5403             :                 }
    5404             : 
    5405             :                 /* The field may have been already created at layer creation */
    5406             :                 const int iDstField =
    5407             :                     poDstFDefn
    5408          22 :                         ? poDstFDefn->GetFieldIndex(oFieldDefn.GetNameRef())
    5409          22 :                         : -1;
    5410          22 :                 if (iDstField >= 0)
    5411             :                 {
    5412           0 :                     anMap[iSrcField] = iDstField;
    5413             :                 }
    5414          22 :                 else if (poDstLayer->CreateField(&oFieldDefn) == OGRERR_NONE)
    5415             :                 {
    5416             :                     /* now that we've created a field, GetLayerDefn() won't
    5417             :                      * return NULL */
    5418          22 :                     if (poDstFDefn == nullptr)
    5419           0 :                         poDstFDefn = poDstLayer->GetLayerDefn();
    5420             : 
    5421             :                     /* Sanity check : if it fails, the driver is buggy */
    5422          44 :                     if (poDstFDefn != nullptr &&
    5423          22 :                         poDstFDefn->GetFieldCount() != nDstFieldCount + 1)
    5424             :                     {
    5425           0 :                         CPLError(CE_Warning, CPLE_AppDefined,
    5426             :                                  "The output driver has claimed to have added "
    5427             :                                  "the %s field, but it did not!",
    5428             :                                  oFieldDefn.GetNameRef());
    5429             :                     }
    5430             :                     else
    5431             :                     {
    5432          22 :                         anMap[iSrcField] = nDstFieldCount;
    5433          22 :                         nDstFieldCount++;
    5434             :                     }
    5435             :                 }
    5436           0 :                 else if (!psOptions->bSkipFailures)
    5437           0 :                     return nullptr;
    5438             :             }
    5439             :         }
    5440             : 
    5441             :         /* --------------------------------------------------------------------
    5442             :          */
    5443             :         /* Use SetIgnoredFields() on source layer if available */
    5444             :         /* --------------------------------------------------------------------
    5445             :          */
    5446          15 :         if (m_bSelFieldsSet && poSrcLayer->TestCapability(OLCIgnoreFields))
    5447             :         {
    5448          10 :             SetIgnoredFields(poSrcLayer);
    5449          15 :         }
    5450             :     }
    5451        1003 :     else if (!bAppend || m_bAddMissingFields)
    5452             :     {
    5453         968 :         int nDstFieldCount = poDstFDefn ? poDstFDefn->GetFieldCount() : 0;
    5454             : 
    5455             :         const bool caseInsensitive =
    5456         968 :             !EQUAL(m_poDstDS->GetDriver()->GetDescription(), "GeoJSON");
    5457       14786 :         const auto formatName = [caseInsensitive](const char *name)
    5458             :         {
    5459       14786 :             if (caseInsensitive)
    5460             :             {
    5461       28844 :                 return CPLString(name).toupper();
    5462             :             }
    5463             :             else
    5464             :             {
    5465         364 :                 return CPLString(name);
    5466             :             }
    5467         968 :         };
    5468             : 
    5469             :         /* Save the map of existing fields, before creating new ones */
    5470             :         /* This helps when converting a source layer that has duplicated field
    5471             :          * names */
    5472             :         /* which is a bad idea */
    5473         968 :         std::map<CPLString, int> oMapPreExistingFields;
    5474         968 :         std::unordered_set<std::string> oSetDstFieldNames;
    5475        1126 :         for (int iField = 0; iField < nDstFieldCount; iField++)
    5476             :         {
    5477             :             const char *pszFieldName =
    5478         158 :                 poDstFDefn->GetFieldDefn(iField)->GetNameRef();
    5479         316 :             CPLString osUpperFieldName(formatName(pszFieldName));
    5480         158 :             oSetDstFieldNames.insert(osUpperFieldName);
    5481         158 :             if (oMapPreExistingFields.find(osUpperFieldName) ==
    5482         316 :                 oMapPreExistingFields.end())
    5483         158 :                 oMapPreExistingFields[osUpperFieldName] = iField;
    5484             :             /*else
    5485             :                 CPLError(CE_Warning, CPLE_AppDefined,
    5486             :                          "The target layer has already a duplicated field name
    5487             :                '%s' before " "adding the fields of the source layer",
    5488             :                pszFieldName); */
    5489             :         }
    5490             : 
    5491         968 :         const char *pszFIDColumn = poDstLayer->GetFIDColumn();
    5492             : 
    5493         968 :         std::vector<int> anSrcFieldIndices;
    5494         968 :         if (m_bSelFieldsSet)
    5495             :         {
    5496           2 :             for (int iField = 0; m_papszSelFields && m_papszSelFields[iField];
    5497             :                  iField++)
    5498             :             {
    5499             :                 const int iSrcField =
    5500           1 :                     poSrcFDefn->GetFieldIndex(m_papszSelFields[iField]);
    5501           1 :                 if (iSrcField >= 0)
    5502             :                 {
    5503           1 :                     anSrcFieldIndices.push_back(iSrcField);
    5504             :                 }
    5505             :             }
    5506             :         }
    5507             :         else
    5508             :         {
    5509        4689 :             for (int iField = 0; iField < nSrcFieldCount; iField++)
    5510             :             {
    5511        3722 :                 anSrcFieldIndices.push_back(iField);
    5512             :             }
    5513             :         }
    5514             : 
    5515         968 :         std::unordered_set<std::string> oSetSrcFieldNames;
    5516        4692 :         for (int i = 0; i < poSrcFDefn->GetFieldCount(); i++)
    5517             :         {
    5518             :             oSetSrcFieldNames.insert(
    5519        3724 :                 formatName(poSrcFDefn->GetFieldDefn(i)->GetNameRef()));
    5520             :         }
    5521             : 
    5522             :         // For each source field name, memorize the last number suffix to have
    5523             :         // unique field names in the target. Let's imagine we have a source
    5524             :         // layer with the field name foo repeated twice After dealing the first
    5525             :         // field, oMapFieldNameToLastSuffix["foo"] will be 1, so when starting a
    5526             :         // unique name for the second field, we'll be able to start at 2. This
    5527             :         // avoids quadratic complexity if a big number of source field names are
    5528             :         // identical. Like in
    5529             :         // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=37768
    5530         968 :         std::map<std::string, int> oMapFieldNameToLastSuffix;
    5531             : 
    5532        4689 :         for (size_t i = 0; i < anSrcFieldIndices.size(); i++)
    5533             :         {
    5534        3723 :             const int iField = anSrcFieldIndices[i];
    5535             :             const OGRFieldDefn *poSrcFieldDefn =
    5536        3723 :                 poSrcFDefn->GetFieldDefn(iField);
    5537        3723 :             OGRFieldDefn oFieldDefn(poSrcFieldDefn);
    5538             : 
    5539             :             // Avoid creating a field with the same name as the FID column
    5540        7447 :             if (pszFIDColumn != nullptr &&
    5541        3724 :                 EQUAL(pszFIDColumn, oFieldDefn.GetNameRef()) &&
    5542           1 :                 (oFieldDefn.GetType() == OFTInteger ||
    5543           0 :                  oFieldDefn.GetType() == OFTInteger64))
    5544             :             {
    5545           1 :                 iSrcFIDField = iField;
    5546           1 :                 continue;
    5547             :             }
    5548             : 
    5549        3722 :             DoFieldTypeConversion(
    5550             :                 m_poDstDS, oFieldDefn, m_papszFieldTypesToString,
    5551        3722 :                 m_papszMapFieldType, m_bUnsetFieldWidth, psOptions->bQuiet,
    5552        3722 :                 m_bForceNullable, m_bUnsetDefault);
    5553             : 
    5554        3933 :             if (iChangeWidthBy != 0 && oFieldDefn.GetType() == OFTReal &&
    5555         211 :                 oFieldDefn.GetWidth() != 0)
    5556             :             {
    5557         158 :                 oFieldDefn.SetWidth(oFieldDefn.GetWidth() + iChangeWidthBy);
    5558             :             }
    5559             : 
    5560             :             /* The field may have been already created at layer creation */
    5561             :             {
    5562             :                 const auto oIter = oMapPreExistingFields.find(
    5563        3722 :                     formatName(oFieldDefn.GetNameRef()));
    5564        3722 :                 if (oIter != oMapPreExistingFields.end())
    5565             :                 {
    5566         120 :                     anMap[iField] = oIter->second;
    5567         120 :                     continue;
    5568             :                 }
    5569             :             }
    5570             : 
    5571        3602 :             bool bHasRenamed = false;
    5572             :             /* In case the field name already exists in the target layer, */
    5573             :             /* build a unique field name */
    5574        3602 :             if (oSetDstFieldNames.find(formatName(oFieldDefn.GetNameRef())) !=
    5575        7204 :                 oSetDstFieldNames.end())
    5576             :             {
    5577             :                 const CPLString osTmpNameRaddixUC(
    5578           4 :                     formatName(oFieldDefn.GetNameRef()));
    5579           2 :                 int nTry = 1;
    5580             :                 const auto oIter =
    5581           2 :                     oMapFieldNameToLastSuffix.find(osTmpNameRaddixUC);
    5582           2 :                 if (oIter != oMapFieldNameToLastSuffix.end())
    5583           1 :                     nTry = oIter->second;
    5584           2 :                 CPLString osTmpNameUC = osTmpNameRaddixUC;
    5585           2 :                 osTmpNameUC.reserve(osTmpNameUC.size() + 10);
    5586             :                 while (true)
    5587             :                 {
    5588           3 :                     ++nTry;
    5589             :                     char szTry[32];
    5590           3 :                     snprintf(szTry, sizeof(szTry), "%d", nTry);
    5591             :                     osTmpNameUC.replace(osTmpNameRaddixUC.size(),
    5592           3 :                                         std::string::npos, szTry);
    5593             : 
    5594             :                     /* Check that the proposed name doesn't exist either in the
    5595             :                      * already */
    5596             :                     /* created fields or in the source fields */
    5597           3 :                     if (oSetDstFieldNames.find(osTmpNameUC) ==
    5598           9 :                             oSetDstFieldNames.end() &&
    5599           3 :                         oSetSrcFieldNames.find(osTmpNameUC) ==
    5600           6 :                             oSetSrcFieldNames.end())
    5601             :                     {
    5602           2 :                         bHasRenamed = true;
    5603           2 :                         oFieldDefn.SetName(
    5604           4 :                             (CPLString(oFieldDefn.GetNameRef()) + szTry)
    5605             :                                 .c_str());
    5606           2 :                         oMapFieldNameToLastSuffix[osTmpNameRaddixUC] = nTry;
    5607           2 :                         break;
    5608             :                     }
    5609           1 :                 }
    5610             :             }
    5611             : 
    5612             :             // Create field domain in output dataset if not already existing.
    5613        3602 :             const std::string osDomainName(oFieldDefn.GetDomainName());
    5614        3602 :             if (!osDomainName.empty())
    5615             :             {
    5616          26 :                 if (m_poDstDS->TestCapability(ODsCAddFieldDomain) &&
    5617          13 :                     m_poDstDS->GetFieldDomain(osDomainName) == nullptr)
    5618             :                 {
    5619             :                     const auto poSrcDomain =
    5620          13 :                         m_poSrcDS->GetFieldDomain(osDomainName);
    5621          13 :                     if (poSrcDomain)
    5622             :                     {
    5623          22 :                         std::string failureReason;
    5624          11 :                         if (!m_poDstDS->AddFieldDomain(
    5625          22 :                                 std::unique_ptr<OGRFieldDomain>(
    5626          11 :                                     poSrcDomain->Clone()),
    5627          11 :                                 failureReason))
    5628             :                         {
    5629           0 :                             oFieldDefn.SetDomainName(std::string());
    5630           0 :                             CPLDebug("OGR2OGR", "Cannot create domain %s: %s",
    5631             :                                      osDomainName.c_str(),
    5632             :                                      failureReason.c_str());
    5633             :                         }
    5634             :                     }
    5635             :                     else
    5636             :                     {
    5637           2 :                         CPLDebug("OGR2OGR",
    5638             :                                  "Cannot find domain %s in source dataset",
    5639             :                                  osDomainName.c_str());
    5640             :                     }
    5641             :                 }
    5642          13 :                 if (m_poDstDS->GetFieldDomain(osDomainName) == nullptr)
    5643             :                 {
    5644           2 :                     oFieldDefn.SetDomainName(std::string());
    5645             :                 }
    5646             :             }
    5647             : 
    5648        3602 :             if (poDstLayer->CreateField(&oFieldDefn) == OGRERR_NONE)
    5649             :             {
    5650             :                 /* now that we've created a field, GetLayerDefn() won't return
    5651             :                  * NULL */
    5652        3578 :                 if (poDstFDefn == nullptr)
    5653           0 :                     poDstFDefn = poDstLayer->GetLayerDefn();
    5654             : 
    5655             :                 /* Sanity check : if it fails, the driver is buggy */
    5656        7156 :                 if (poDstFDefn != nullptr &&
    5657        3578 :                     poDstFDefn->GetFieldCount() != nDstFieldCount + 1)
    5658             :                 {
    5659           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    5660             :                              "The output driver has claimed to have added the "
    5661             :                              "%s field, but it did not!",
    5662             :                              oFieldDefn.GetNameRef());
    5663             :                 }
    5664             :                 else
    5665             :                 {
    5666        3578 :                     if (poDstFDefn != nullptr)
    5667             :                     {
    5668             :                         const char *pszNewFieldName =
    5669        3578 :                             poDstFDefn->GetFieldDefn(nDstFieldCount)
    5670        3578 :                                 ->GetNameRef();
    5671        3578 :                         if (bHasRenamed)
    5672             :                         {
    5673           2 :                             CPLError(CE_Warning, CPLE_AppDefined,
    5674             :                                      "Field '%s' already exists. Renaming it "
    5675             :                                      "as '%s'",
    5676             :                                      poSrcFieldDefn->GetNameRef(),
    5677             :                                      pszNewFieldName);
    5678             :                         }
    5679        3578 :                         oSetDstFieldNames.insert(formatName(pszNewFieldName));
    5680             :                     }
    5681             : 
    5682        3578 :                     anMap[iField] = nDstFieldCount;
    5683        3578 :                     nDstFieldCount++;
    5684             :                 }
    5685             :             }
    5686          24 :             else if (!psOptions->bSkipFailures)
    5687           2 :                 return nullptr;
    5688             : 
    5689        3600 :             if (m_bResolveDomains && !osDomainName.empty())
    5690             :             {
    5691             :                 const auto poSrcDomain =
    5692           3 :                     m_poSrcDS->GetFieldDomain(osDomainName);
    5693           3 :                 if (poSrcDomain && poSrcDomain->GetDomainType() == OFDT_CODED)
    5694             :                 {
    5695             :                     OGRFieldDefn oResolvedField(
    5696             :                         CPLSPrintf("%s_resolved", oFieldDefn.GetNameRef()),
    5697           1 :                         OFTString);
    5698           1 :                     if (poDstLayer->CreateField(&oResolvedField) == OGRERR_NONE)
    5699             :                     {
    5700             :                         TargetLayerInfo::ResolvedInfo resolvedInfo;
    5701           1 :                         resolvedInfo.nSrcField = iField;
    5702           1 :                         resolvedInfo.poDomain = poSrcDomain;
    5703           1 :                         oMapResolved[nDstFieldCount] = resolvedInfo;
    5704           1 :                         nDstFieldCount++;
    5705             :                     }
    5706           0 :                     else if (!psOptions->bSkipFailures)
    5707           0 :                         return nullptr;
    5708             :                 }
    5709             :             }
    5710         966 :         }
    5711             :     }
    5712             :     else
    5713             :     {
    5714             :         /* For an existing layer, build the map by fetching the index in the
    5715             :          * destination */
    5716             :         /* layer for each source field */
    5717          35 :         if (poDstFDefn == nullptr)
    5718             :         {
    5719           0 :             CPLError(CE_Failure, CPLE_AppDefined, "poDstFDefn == NULL.");
    5720           0 :             return nullptr;
    5721             :         }
    5722             : 
    5723         118 :         for (int iField = 0; iField < nSrcFieldCount; iField++)
    5724             :         {
    5725             :             const OGRFieldDefn *poSrcFieldDefn =
    5726          83 :                 poSrcFDefn->GetFieldDefn(iField);
    5727          83 :             const int iDstField = poDstLayer->FindFieldIndex(
    5728          83 :                 poSrcFieldDefn->GetNameRef(), m_bExactFieldNameMatch);
    5729          83 :             if (iDstField >= 0)
    5730          79 :                 anMap[iField] = iDstField;
    5731             :             else
    5732             :             {
    5733           4 :                 if (m_bExactFieldNameMatch)
    5734             :                 {
    5735           4 :                     const int iDstFieldCandidate = poDstLayer->FindFieldIndex(
    5736           4 :                         poSrcFieldDefn->GetNameRef(), false);
    5737           4 :                     if (iDstFieldCandidate >= 0)
    5738             :                     {
    5739           1 :                         CPLError(CE_Warning, CPLE_AppDefined,
    5740             :                                  "Source field '%s' could have been identified "
    5741             :                                  "with existing field '%s' of destination "
    5742             :                                  "layer '%s' if the -relaxedFieldNameMatch "
    5743             :                                  "option had been specified.",
    5744             :                                  poSrcFieldDefn->GetNameRef(),
    5745           1 :                                  poDstLayer->GetLayerDefn()
    5746           1 :                                      ->GetFieldDefn(iDstFieldCandidate)
    5747             :                                      ->GetNameRef(),
    5748           1 :                                  poDstLayer->GetName());
    5749             :                     }
    5750             :                 }
    5751             : 
    5752           4 :                 CPLDebug(
    5753             :                     "GDALVectorTranslate",
    5754             :                     "Skipping field '%s' not found in destination layer '%s'.",
    5755           4 :                     poSrcFieldDefn->GetNameRef(), poDstLayer->GetName());
    5756             :             }
    5757             :         }
    5758             :     }
    5759             : 
    5760          16 :     if (bOverwriteActuallyDone && !bAddOverwriteLCO &&
    5761          16 :         EQUAL(m_poDstDS->GetDriver()->GetDescription(), "PostgreSQL") &&
    5762        1207 :         !psOptions->nLayerTransaction && psOptions->nGroupTransactions > 0 &&
    5763           6 :         CPLTestBool(CPLGetConfigOption("PG_COMMIT_WHEN_OVERWRITING", "YES")))
    5764             :     {
    5765           6 :         CPLDebug("GDALVectorTranslate",
    5766             :                  "Forcing transaction commit as table overwriting occurred");
    5767             :         // Commit when overwriting as this consumes a lot of PG resources
    5768             :         // and could result in """out of shared memory.
    5769             :         // You might need to increase max_locks_per_transaction."""" errors
    5770          12 :         if (m_poDstDS->CommitTransaction() == OGRERR_FAILURE ||
    5771           6 :             m_poDstDS->StartTransaction(psOptions->bForceTransaction) ==
    5772             :                 OGRERR_FAILURE)
    5773             :         {
    5774           0 :             return nullptr;
    5775             :         }
    5776           6 :         nTotalEventsDone = 0;
    5777             :     }
    5778             : 
    5779        2370 :     auto psInfo = std::make_unique<TargetLayerInfo>();
    5780        1185 :     psInfo->m_bUseWriteArrowBatch = bUseWriteArrowBatch;
    5781        1185 :     psInfo->m_nFeaturesRead = 0;
    5782        1185 :     psInfo->m_bPerFeatureCT = false;
    5783        1185 :     psInfo->m_poSrcLayer = poSrcLayer;
    5784        1185 :     psInfo->m_poDstLayer = poDstLayer;
    5785        1185 :     psInfo->m_aoReprojectionInfo.resize(
    5786        1185 :         poDstLayer->GetLayerDefn()->GetGeomFieldCount());
    5787        1185 :     psInfo->m_anMap = std::move(anMap);
    5788        1185 :     psInfo->m_iSrcZField = iSrcZField;
    5789        1185 :     psInfo->m_iSrcFIDField = iSrcFIDField;
    5790        1185 :     if (anRequestedGeomFields.size() == 1)
    5791          50 :         psInfo->m_iRequestedSrcGeomField = anRequestedGeomFields[0];
    5792             :     else
    5793        1135 :         psInfo->m_iRequestedSrcGeomField = -1;
    5794        1185 :     psInfo->m_bPreserveFID = bPreserveFID;
    5795        1185 :     psInfo->m_pszCTPipeline = m_pszCTPipeline;
    5796        1185 :     psInfo->m_aosCTOptions = m_aosCTOptions;
    5797        1185 :     psInfo->m_oMapResolved = std::move(oMapResolved);
    5798        1186 :     for (const auto &kv : psInfo->m_oMapResolved)
    5799             :     {
    5800           1 :         const auto poDomain = kv.second.poDomain;
    5801             :         const auto poCodedDomain =
    5802           1 :             cpl::down_cast<const OGRCodedFieldDomain *>(poDomain);
    5803           1 :         const auto enumeration = poCodedDomain->GetEnumeration();
    5804           2 :         std::map<std::string, std::string> oMapCodeValue;
    5805           4 :         for (int i = 0; enumeration[i].pszCode != nullptr; ++i)
    5806             :         {
    5807           6 :             oMapCodeValue[enumeration[i].pszCode] =
    5808           6 :                 enumeration[i].pszValue ? enumeration[i].pszValue : "";
    5809             :         }
    5810           1 :         psInfo->m_oMapDomainToKV[poDomain] = std::move(oMapCodeValue);
    5811             :     }
    5812             : 
    5813             :     // Detect if we can directly pass the source feature to the CreateFeature()
    5814             :     // method of the target layer, without doing any copying of field content.
    5815        1185 :     psInfo->m_bCanAvoidSetFrom = false;
    5816        1185 :     if (!m_bExplodeCollections && iSrcZField == -1 && poDstFDefn != nullptr)
    5817             :     {
    5818        1170 :         psInfo->m_bCanAvoidSetFrom = true;
    5819        1170 :         const int nDstGeomFieldCount = poDstFDefn->GetGeomFieldCount();
    5820        1170 :         if (nSrcFieldCount != poDstFDefn->GetFieldCount() ||
    5821             :             nSrcGeomFieldCount != nDstGeomFieldCount)
    5822             :         {
    5823         169 :             psInfo->m_bCanAvoidSetFrom = false;
    5824             :         }
    5825             :         else
    5826             :         {
    5827        4360 :             for (int i = 0; i < nSrcFieldCount; ++i)
    5828             :             {
    5829        3401 :                 auto poSrcFieldDefn = poSrcFDefn->GetFieldDefn(i);
    5830        3401 :                 auto poDstFieldDefn = poDstFDefn->GetFieldDefn(i);
    5831        6792 :                 if (poSrcFieldDefn->GetType() != poDstFieldDefn->GetType() ||
    5832        3391 :                     psInfo->m_anMap[i] != i)
    5833             :                 {
    5834          42 :                     psInfo->m_bCanAvoidSetFrom = false;
    5835          42 :                     break;
    5836             :                 }
    5837             :             }
    5838        1001 :             if (!psInfo->m_bCanAvoidSetFrom && nSrcGeomFieldCount > 1)
    5839             :             {
    5840           4 :                 for (int i = 0; i < nSrcGeomFieldCount; ++i)
    5841             :                 {
    5842           3 :                     auto poSrcGeomFieldDefn = poSrcFDefn->GetGeomFieldDefn(i);
    5843           3 :                     auto poDstGeomFieldDefn = poDstFDefn->GetGeomFieldDefn(i);
    5844           3 :                     if (!EQUAL(poSrcGeomFieldDefn->GetNameRef(),
    5845             :                                poDstGeomFieldDefn->GetNameRef()))
    5846             :                     {
    5847           1 :                         psInfo->m_bCanAvoidSetFrom = false;
    5848           1 :                         break;
    5849             :                     }
    5850             :                 }
    5851             :             }
    5852             :         }
    5853             :     }
    5854             : 
    5855        2370 :     psInfo->m_pszSpatSRSDef = psOptions->osSpatSRSDef.empty()
    5856        1185 :                                   ? nullptr
    5857           4 :                                   : psOptions->osSpatSRSDef.c_str();
    5858        1185 :     psInfo->m_hSpatialFilter =
    5859        1185 :         OGRGeometry::ToHandle(psOptions->poSpatialFilter.get());
    5860        1185 :     psInfo->m_pszGeomField =
    5861        1185 :         psOptions->bGeomFieldSet ? psOptions->osGeomField.c_str() : nullptr;
    5862             : 
    5863        1185 :     if (psOptions->nTZOffsetInSec != TZ_OFFSET_INVALID && poDstFDefn)
    5864             :     {
    5865          15 :         for (int i = 0; i < poDstFDefn->GetFieldCount(); ++i)
    5866             :         {
    5867          10 :             if (poDstFDefn->GetFieldDefn(i)->GetType() == OFTDateTime)
    5868             :             {
    5869           5 :                 psInfo->m_anDateTimeFieldIdx.push_back(i);
    5870             :             }
    5871             :         }
    5872             :     }
    5873             : 
    5874        1185 :     psInfo->m_bSupportCurves =
    5875        1185 :         CPL_TO_BOOL(poDstLayer->TestCapability(OLCCurveGeometries));
    5876        1185 :     psInfo->m_bSupportZ =
    5877        1185 :         CPL_TO_BOOL(poDstLayer->TestCapability(OLCZGeometries));
    5878        1185 :     psInfo->m_bSupportM =
    5879        1185 :         CPL_TO_BOOL(poDstLayer->TestCapability(OLCMeasuredGeometries));
    5880             : 
    5881        1185 :     psInfo->m_sArrowArrayStream = std::move(streamSrc);
    5882             : 
    5883        1185 :     return psInfo;
    5884             : }
    5885             : 
    5886             : /************************************************************************/
    5887             : /*                              SetupCT()                               */
    5888             : /************************************************************************/
    5889             : 
    5890             : static bool
    5891         947 : SetupCT(TargetLayerInfo *psInfo, OGRLayer *poSrcLayer, bool bTransform,
    5892             :         bool bWrapDateline, const CPLString &osDateLineOffset,
    5893             :         const OGRSpatialReference *poUserSourceSRS, OGRFeature *poFeature,
    5894             :         const OGRSpatialReference *poOutputSRS,
    5895             :         OGRCoordinateTransformation *poGCPCoordTrans, bool bVerboseError)
    5896             : {
    5897         947 :     OGRLayer *poDstLayer = psInfo->m_poDstLayer;
    5898             :     const int nDstGeomFieldCount =
    5899         947 :         poDstLayer->GetLayerDefn()->GetGeomFieldCount();
    5900        1831 :     for (int iGeom = 0; iGeom < nDstGeomFieldCount; iGeom++)
    5901             :     {
    5902             :         /* --------------------------------------------------------------------
    5903             :          */
    5904             :         /*      Setup coordinate transformation if we need it. */
    5905             :         /* --------------------------------------------------------------------
    5906             :          */
    5907         885 :         const OGRSpatialReference *poSourceSRS = nullptr;
    5908         885 :         OGRCoordinateTransformation *poCT = nullptr;
    5909         885 :         char **papszTransformOptions = nullptr;
    5910             : 
    5911             :         int iSrcGeomField;
    5912             :         auto poDstGeomFieldDefn =
    5913         885 :             poDstLayer->GetLayerDefn()->GetGeomFieldDefn(iGeom);
    5914         885 :         if (psInfo->m_iRequestedSrcGeomField >= 0)
    5915             :         {
    5916          39 :             iSrcGeomField = psInfo->m_iRequestedSrcGeomField;
    5917             :         }
    5918             :         else
    5919             :         {
    5920        1692 :             iSrcGeomField = poSrcLayer->GetLayerDefn()->GetGeomFieldIndex(
    5921         846 :                 poDstGeomFieldDefn->GetNameRef());
    5922         846 :             if (iSrcGeomField < 0)
    5923             :             {
    5924         360 :                 if (nDstGeomFieldCount == 1 &&
    5925         180 :                     poSrcLayer->GetLayerDefn()->GetGeomFieldCount() > 0)
    5926             :                 {
    5927         172 :                     iSrcGeomField = 0;
    5928             :                 }
    5929             :                 else
    5930             :                 {
    5931           8 :                     continue;
    5932             :                 }
    5933             :             }
    5934             :         }
    5935             : 
    5936         877 :         if (psInfo->m_nFeaturesRead == 0)
    5937             :         {
    5938         876 :             poSourceSRS = poUserSourceSRS;
    5939         876 :             if (poSourceSRS == nullptr)
    5940             :             {
    5941         868 :                 if (iSrcGeomField > 0)
    5942         121 :                     poSourceSRS = poSrcLayer->GetLayerDefn()
    5943         121 :                                       ->GetGeomFieldDefn(iSrcGeomField)
    5944         121 :                                       ->GetSpatialRef();
    5945             :                 else
    5946         747 :                     poSourceSRS = poSrcLayer->GetSpatialRef();
    5947             :             }
    5948             :         }
    5949         877 :         if (poSourceSRS == nullptr)
    5950             :         {
    5951         362 :             if (poFeature == nullptr)
    5952             :             {
    5953           1 :                 if (bVerboseError)
    5954             :                 {
    5955           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    5956             :                              "Non-null feature expected to set transformation");
    5957             :                 }
    5958           1 :                 return false;
    5959             :             }
    5960             :             OGRGeometry *poSrcGeometry =
    5961         361 :                 poFeature->GetGeomFieldRef(iSrcGeomField);
    5962         361 :             if (poSrcGeometry)
    5963         289 :                 poSourceSRS = poSrcGeometry->getSpatialReference();
    5964         361 :             psInfo->m_bPerFeatureCT = (bTransform || bWrapDateline);
    5965             :         }
    5966             : 
    5967         876 :         if (bTransform)
    5968             :         {
    5969          39 :             if (poSourceSRS == nullptr && psInfo->m_pszCTPipeline == nullptr)
    5970             :             {
    5971           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    5972             :                          "Can't transform coordinates, source layer has no\n"
    5973             :                          "coordinate system.  Use -s_srs to set one.");
    5974             : 
    5975           0 :                 return false;
    5976             :             }
    5977             : 
    5978          39 :             if (psInfo->m_pszCTPipeline == nullptr)
    5979             :             {
    5980          35 :                 CPLAssert(nullptr != poSourceSRS);
    5981          35 :                 CPLAssert(nullptr != poOutputSRS);
    5982             :             }
    5983             : 
    5984          39 :             if (psInfo->m_nFeaturesRead == 0 && !psInfo->m_bPerFeatureCT)
    5985             :             {
    5986             :                 const auto &supportedSRSList =
    5987          37 :                     poSrcLayer->GetSupportedSRSList(iGeom);
    5988          37 :                 if (!supportedSRSList.empty())
    5989             :                 {
    5990           1 :                     const char *const apszOptions[] = {
    5991             :                         "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES", nullptr};
    5992           1 :                     for (const auto &poSRS : supportedSRSList)
    5993             :                     {
    5994           1 :                         if (poSRS->IsSame(poOutputSRS, apszOptions))
    5995             :                         {
    5996           2 :                             OGRSpatialReference oSourceSRSBackup;
    5997           1 :                             if (poSourceSRS)
    5998           1 :                                 oSourceSRSBackup = *poSourceSRS;
    5999           1 :                             if (poSrcLayer->SetActiveSRS(iGeom, poSRS.get()) ==
    6000             :                                 OGRERR_NONE)
    6001             :                             {
    6002           1 :                                 CPLDebug("ogr2ogr",
    6003             :                                          "Switching layer active SRS to %s",
    6004             :                                          poSRS->GetName());
    6005             : 
    6006           1 :                                 if (psInfo->m_hSpatialFilter != nullptr &&
    6007           0 :                                     ((psInfo->m_iRequestedSrcGeomField < 0 &&
    6008           0 :                                       iGeom == 0) ||
    6009             :                                      (iGeom ==
    6010           0 :                                       psInfo->m_iRequestedSrcGeomField)))
    6011             :                                 {
    6012           0 :                                     OGRSpatialReference oSpatSRS;
    6013           0 :                                     oSpatSRS.SetAxisMappingStrategy(
    6014             :                                         OAMS_TRADITIONAL_GIS_ORDER);
    6015           0 :                                     if (psInfo->m_pszSpatSRSDef)
    6016           0 :                                         oSpatSRS.SetFromUserInput(
    6017             :                                             psInfo->m_pszSpatSRSDef);
    6018           0 :                                     ApplySpatialFilter(
    6019             :                                         poSrcLayer,
    6020             :                                         OGRGeometry::FromHandle(
    6021             :                                             psInfo->m_hSpatialFilter),
    6022           0 :                                         !oSpatSRS.IsEmpty() ? &oSpatSRS
    6023           0 :                                         : !oSourceSRSBackup.IsEmpty()
    6024             :                                             ? &oSourceSRSBackup
    6025             :                                             : nullptr,
    6026             :                                         psInfo->m_pszGeomField, poOutputSRS);
    6027             :                                 }
    6028             : 
    6029           1 :                                 bTransform = false;
    6030             :                             }
    6031           1 :                             break;
    6032             :                         }
    6033             :                     }
    6034             :                 }
    6035             :             }
    6036             : 
    6037          39 :             if (!bTransform)
    6038             :             {
    6039             :                 // do nothing
    6040             :             }
    6041          39 :             else if (psInfo->m_aoReprojectionInfo[iGeom].m_poCT != nullptr &&
    6042           1 :                      psInfo->m_aoReprojectionInfo[iGeom]
    6043           1 :                              .m_poCT->GetSourceCS() == poSourceSRS)
    6044             :             {
    6045           0 :                 poCT = psInfo->m_aoReprojectionInfo[iGeom].m_poCT.get();
    6046             :             }
    6047             :             else
    6048             :             {
    6049          38 :                 OGRCoordinateTransformationOptions options;
    6050          38 :                 if (psInfo->m_pszCTPipeline)
    6051             :                 {
    6052           4 :                     options.SetCoordinateOperation(psInfo->m_pszCTPipeline,
    6053             :                                                    false);
    6054             :                 }
    6055             : 
    6056             :                 bool bWarnAboutDifferentCoordinateOperations =
    6057          75 :                     poGCPCoordTrans == nullptr &&
    6058          37 :                     !(poSourceSRS && poSourceSRS->IsGeocentric());
    6059             : 
    6060           0 :                 for (const auto &[key, value] :
    6061          38 :                      cpl::IterateNameValue(psInfo->m_aosCTOptions))
    6062             :                 {
    6063           0 :                     if (EQUAL(key, "ALLOW_BALLPARK"))
    6064             :                     {
    6065           0 :                         options.SetBallparkAllowed(CPLTestBool(value));
    6066             :                     }
    6067           0 :                     else if (EQUAL(key, "ONLY_BEST"))
    6068             :                     {
    6069           0 :                         options.SetOnlyBest(CPLTestBool(value));
    6070             :                     }
    6071           0 :                     else if (EQUAL(key, "WARN_ABOUT_DIFFERENT_COORD_OP"))
    6072             :                     {
    6073           0 :                         if (!CPLTestBool(value))
    6074           0 :                             bWarnAboutDifferentCoordinateOperations = false;
    6075             :                     }
    6076             :                     else
    6077             :                     {
    6078           0 :                         CPLError(CE_Warning, CPLE_AppDefined,
    6079             :                                  "Unknown coordinate transform option: %s",
    6080             :                                  key);
    6081             :                     }
    6082             :                 }
    6083             : 
    6084             :                 auto poNewCT = std::unique_ptr<OGRCoordinateTransformation>(
    6085             :                     OGRCreateCoordinateTransformation(poSourceSRS, poOutputSRS,
    6086          38 :                                                       options));
    6087          38 :                 if (poNewCT == nullptr)
    6088             :                 {
    6089           0 :                     char *pszWKT = nullptr;
    6090             : 
    6091           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    6092             :                              "Failed to create coordinate transformation "
    6093             :                              "between the\n"
    6094             :                              "following coordinate systems.  This may be "
    6095             :                              "because they\n"
    6096             :                              "are not transformable.");
    6097             : 
    6098           0 :                     if (poSourceSRS)
    6099             :                     {
    6100           0 :                         poSourceSRS->exportToPrettyWkt(&pszWKT, FALSE);
    6101           0 :                         CPLError(CE_Failure, CPLE_AppDefined, "Source:\n%s",
    6102             :                                  pszWKT);
    6103           0 :                         CPLFree(pszWKT);
    6104             :                     }
    6105             : 
    6106           0 :                     if (poOutputSRS)
    6107             :                     {
    6108           0 :                         poOutputSRS->exportToPrettyWkt(&pszWKT, FALSE);
    6109           0 :                         CPLError(CE_Failure, CPLE_AppDefined, "Target:\n%s",
    6110             :                                  pszWKT);
    6111           0 :                         CPLFree(pszWKT);
    6112             :                     }
    6113             : 
    6114           0 :                     return false;
    6115             :                 }
    6116          38 :                 if (poGCPCoordTrans)
    6117             :                 {
    6118           2 :                     poNewCT = std::make_unique<CompositeCT>(poGCPCoordTrans,
    6119           2 :                                                             std::move(poNewCT));
    6120             :                 }
    6121             :                 else
    6122             :                 {
    6123          37 :                     psInfo->m_aoReprojectionInfo[iGeom]
    6124          37 :                         .m_bWarnAboutDifferentCoordinateOperations =
    6125             :                         bWarnAboutDifferentCoordinateOperations;
    6126             :                 }
    6127          38 :                 psInfo->m_aoReprojectionInfo[iGeom].m_poCT = std::move(poNewCT);
    6128          38 :                 poCT = psInfo->m_aoReprojectionInfo[iGeom].m_poCT.get();
    6129          38 :                 psInfo->m_aoReprojectionInfo[iGeom].m_bCanInvalidateValidity =
    6130          75 :                     !(poGCPCoordTrans == nullptr && poSourceSRS &&
    6131          37 :                       poSourceSRS->IsGeographic() && poOutputSRS &&
    6132           4 :                       poOutputSRS->IsGeographic());
    6133             :             }
    6134             :         }
    6135             :         else
    6136             :         {
    6137         837 :             const char *const apszOptions[] = {
    6138             :                 "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES",
    6139             :                 "CRITERION=EQUIVALENT", nullptr};
    6140             :             auto poDstGeomFieldDefnSpatialRef =
    6141         837 :                 poDstGeomFieldDefn->GetSpatialRef();
    6142         478 :             if (poSourceSRS && poDstGeomFieldDefnSpatialRef &&
    6143         392 :                 poSourceSRS->GetDataAxisToSRSAxisMapping() !=
    6144             :                     poDstGeomFieldDefnSpatialRef
    6145        1315 :                         ->GetDataAxisToSRSAxisMapping() &&
    6146           3 :                 poSourceSRS->IsSame(poDstGeomFieldDefnSpatialRef, apszOptions))
    6147             :             {
    6148           0 :                 psInfo->m_aoReprojectionInfo[iGeom].m_poCT =
    6149           0 :                     std::make_unique<CompositeCT>(
    6150           0 :                         std::make_unique<AxisMappingCoordinateTransformation>(
    6151             :                             poSourceSRS->GetDataAxisToSRSAxisMapping(),
    6152             :                             poDstGeomFieldDefnSpatialRef
    6153             :                                 ->GetDataAxisToSRSAxisMapping()),
    6154           0 :                         poGCPCoordTrans);
    6155           0 :                 poCT = psInfo->m_aoReprojectionInfo[iGeom].m_poCT.get();
    6156             :             }
    6157         837 :             else if (poGCPCoordTrans)
    6158             :             {
    6159           5 :                 psInfo->m_aoReprojectionInfo[iGeom].m_poCT =
    6160          10 :                     std::make_unique<CompositeCT>(poGCPCoordTrans, nullptr);
    6161           5 :                 poCT = psInfo->m_aoReprojectionInfo[iGeom].m_poCT.get();
    6162             :             }
    6163             :         }
    6164             : 
    6165         876 :         if (bWrapDateline)
    6166             :         {
    6167           2 :             if (bTransform && poCT != nullptr && poOutputSRS != nullptr &&
    6168           8 :                 poOutputSRS->IsGeographic() &&
    6169           1 :                 !poOutputSRS->IsDerivedGeographic())
    6170             :             {
    6171             :                 papszTransformOptions =
    6172           1 :                     CSLAddString(papszTransformOptions, "WRAPDATELINE=YES");
    6173           1 :                 if (!osDateLineOffset.empty())
    6174             :                 {
    6175           1 :                     CPLString soOffset("DATELINEOFFSET=");
    6176           1 :                     soOffset += osDateLineOffset;
    6177             :                     papszTransformOptions =
    6178           1 :                         CSLAddString(papszTransformOptions, soOffset);
    6179             :                 }
    6180             :             }
    6181           8 :             else if (poSourceSRS != nullptr && poSourceSRS->IsGeographic() &&
    6182           4 :                      !poSourceSRS->IsDerivedGeographic())
    6183             :             {
    6184             :                 papszTransformOptions =
    6185           4 :                     CSLAddString(papszTransformOptions, "WRAPDATELINE=YES");
    6186           4 :                 if (!osDateLineOffset.empty())
    6187             :                 {
    6188           4 :                     CPLString soOffset("DATELINEOFFSET=");
    6189           4 :                     soOffset += osDateLineOffset;
    6190             :                     papszTransformOptions =
    6191           4 :                         CSLAddString(papszTransformOptions, soOffset);
    6192             :                 }
    6193             :             }
    6194             :             else
    6195             :             {
    6196           0 :                 CPLErrorOnce(CE_Failure, CPLE_IllegalArg,
    6197             :                              "-wrapdateline option only works when "
    6198             :                              "reprojecting to a geographic SRS");
    6199             :             }
    6200             : 
    6201           5 :             psInfo->m_aoReprojectionInfo[iGeom].m_aosTransformOptions.Assign(
    6202           5 :                 papszTransformOptions);
    6203             :         }
    6204             :     }
    6205         946 :     return true;
    6206             : }
    6207             : 
    6208             : /************************************************************************/
    6209             : /*                  LayerTranslator::TranslateArrow()                   */
    6210             : /************************************************************************/
    6211             : 
    6212         167 : bool LayerTranslator::TranslateArrow(
    6213             :     TargetLayerInfo *psInfo, GIntBig nCountLayerFeatures,
    6214             :     GIntBig *pnReadFeatureCount, GDALProgressFunc pfnProgress,
    6215             :     void *pProgressArg, const GDALVectorTranslateOptions *psOptions)
    6216             : {
    6217             :     struct ArrowSchema schema;
    6218         334 :     CPLStringList aosOptionsWriteArrowBatch;
    6219         167 :     if (psInfo->m_bPreserveFID)
    6220             :     {
    6221             :         aosOptionsWriteArrowBatch.SetNameValue(
    6222          30 :             "FID", psInfo->m_poSrcLayer->GetFIDColumn());
    6223             :         aosOptionsWriteArrowBatch.SetNameValue("IF_FID_NOT_PRESERVED",
    6224          30 :                                                "WARNING");
    6225             :     }
    6226             : 
    6227         167 :     if (psInfo->m_sArrowArrayStream.get_schema(&schema) != 0)
    6228             :     {
    6229           0 :         CPLError(CE_Failure, CPLE_AppDefined, "stream.get_schema() failed");
    6230           0 :         return false;
    6231             :     }
    6232             : 
    6233         167 :     int iArrowGeomFieldIndex = -1;
    6234         167 :     if (m_bTransform)
    6235             :     {
    6236          12 :         iArrowGeomFieldIndex = GetArrowGeomFieldIndex(
    6237          12 :             &schema, psInfo->m_poSrcLayer->GetGeometryColumn());
    6238          12 :         if (!SetupCT(psInfo, psInfo->m_poSrcLayer, m_bTransform,
    6239          12 :                      m_bWrapDateline, m_osDateLineOffset, m_poUserSourceSRS,
    6240             :                      nullptr, m_poOutputSRS, m_poGCPCoordTrans, false))
    6241             :         {
    6242           0 :             return false;
    6243             :         }
    6244             :     }
    6245             : 
    6246         167 :     bool bRet = true;
    6247             : 
    6248         167 :     GIntBig nCount = 0;
    6249         167 :     bool bGoOn = true;
    6250         167 :     std::vector<GByte> abyModifiedWKB;
    6251         167 :     const int nNumReprojectionThreads = []()
    6252             :     {
    6253         167 :         const char *pszNumThreads = nullptr;
    6254             :         int nVal =
    6255         167 :             GDALGetNumThreads(GDAL_DEFAULT_MAX_THREAD_COUNT,
    6256             :                               /* bDefaultToAllCPUs = */ false, &pszNumThreads);
    6257         167 :         if (!pszNumThreads)
    6258           0 :             nVal = std::max(1, CPLGetNumCPUs() / 2);
    6259         167 :         return nVal;
    6260         167 :     }();
    6261             : 
    6262             :     // Somewhat arbitrary threshold (config option only/mostly for autotest purposes)
    6263         167 :     const int MIN_FEATURES_FOR_THREADED_REPROJ = atoi(CPLGetConfigOption(
    6264             :         "OGR2OGR_MIN_FEATURES_FOR_THREADED_REPROJ", "10000"));
    6265             : 
    6266         325 :     while (bGoOn)
    6267             :     {
    6268             :         struct ArrowArray array;
    6269             :         // Acquire source batch
    6270         323 :         if (psInfo->m_sArrowArrayStream.get_next(&array) != 0)
    6271             :         {
    6272           0 :             CPLError(CE_Failure, CPLE_AppDefined, "stream.get_next() failed");
    6273           0 :             bRet = false;
    6274         165 :             break;
    6275             :         }
    6276             : 
    6277         323 :         if (array.release == nullptr)
    6278             :         {
    6279             :             // End of stream
    6280         165 :             break;
    6281             :         }
    6282             : 
    6283             :         // Limit number of features in batch if needed
    6284         158 :         if (psOptions->nLimit >= 0 &&
    6285           2 :             nCount + array.length >= psOptions->nLimit)
    6286             :         {
    6287           2 :             const auto nAdjustedLength = psOptions->nLimit - nCount;
    6288          14 :             for (int i = 0; i < array.n_children; ++i)
    6289             :             {
    6290          12 :                 if (array.children[i]->length == array.length)
    6291          12 :                     array.children[i]->length = nAdjustedLength;
    6292             :             }
    6293           2 :             array.length = nAdjustedLength;
    6294           2 :             nCount = psOptions->nLimit;
    6295           2 :             bGoOn = false;
    6296             :         }
    6297             :         else
    6298             :         {
    6299         156 :             nCount += array.length;
    6300             :         }
    6301             : 
    6302         158 :         const auto nArrayLength = array.length;
    6303             : 
    6304             :         // Coordinate reprojection
    6305         158 :         if (m_bTransform)
    6306             :         {
    6307             :             struct GeomArrayReleaser
    6308             :             {
    6309             :                 const void *origin_buffers_2 = nullptr;
    6310             :                 void (*origin_release)(struct ArrowArray *) = nullptr;
    6311             :                 void *origin_private_data = nullptr;
    6312             : 
    6313          11 :                 static void init(struct ArrowArray *psGeomArray)
    6314             :                 {
    6315          11 :                     GeomArrayReleaser *releaser = new GeomArrayReleaser();
    6316          11 :                     CPLAssert(psGeomArray->n_buffers >= 3);
    6317          11 :                     releaser->origin_buffers_2 = psGeomArray->buffers[2];
    6318          11 :                     releaser->origin_private_data = psGeomArray->private_data;
    6319          11 :                     releaser->origin_release = psGeomArray->release;
    6320          11 :                     psGeomArray->release = GeomArrayReleaser::release;
    6321          11 :                     psGeomArray->private_data = releaser;
    6322          11 :                 }
    6323             : 
    6324          11 :                 static void release(struct ArrowArray *psGeomArray)
    6325             :                 {
    6326          11 :                     GeomArrayReleaser *releaser =
    6327             :                         static_cast<GeomArrayReleaser *>(
    6328             :                             psGeomArray->private_data);
    6329          11 :                     psGeomArray->buffers[2] = releaser->origin_buffers_2;
    6330          11 :                     psGeomArray->private_data = releaser->origin_private_data;
    6331          11 :                     psGeomArray->release = releaser->origin_release;
    6332          11 :                     if (psGeomArray->release)
    6333          11 :                         psGeomArray->release(psGeomArray);
    6334          11 :                     delete releaser;
    6335          11 :                 }
    6336             :             };
    6337             : 
    6338          11 :             auto *psGeomArray = array.children[iArrowGeomFieldIndex];
    6339          11 :             GeomArrayReleaser::init(psGeomArray);
    6340             : 
    6341          11 :             GByte *pabyWKB = static_cast<GByte *>(
    6342          11 :                 const_cast<void *>(psGeomArray->buffers[2]));
    6343          11 :             const uint32_t *panOffsets =
    6344          11 :                 static_cast<const uint32_t *>(psGeomArray->buffers[1]);
    6345          11 :             auto poCT = psInfo->m_aoReprojectionInfo[0].m_poCT.get();
    6346             : 
    6347             :             try
    6348             :             {
    6349          11 :                 abyModifiedWKB.resize(panOffsets[nArrayLength]);
    6350             :             }
    6351           0 :             catch (const std::exception &)
    6352             :             {
    6353           0 :                 CPLError(CE_Failure, CPLE_OutOfMemory, "Out of memory");
    6354           0 :                 bRet = false;
    6355           0 :                 if (array.release)
    6356           0 :                     array.release(&array);
    6357           0 :                 break;
    6358             :             }
    6359          11 :             memcpy(abyModifiedWKB.data(), pabyWKB, panOffsets[nArrayLength]);
    6360          11 :             psGeomArray->buffers[2] = abyModifiedWKB.data();
    6361             : 
    6362             :             // Collect left-most, right-most, top-most, bottom-most coordinates.
    6363          11 :             if (psInfo->m_aoReprojectionInfo[0]
    6364          11 :                     .m_bWarnAboutDifferentCoordinateOperations)
    6365             :             {
    6366             :                 struct OGRWKBPointVisitor final : public OGRWKBPointUpdater
    6367             :                 {
    6368             :                     TargetLayerInfo::ReprojectionInfo &m_info;
    6369             : 
    6370          11 :                     explicit OGRWKBPointVisitor(
    6371             :                         TargetLayerInfo::ReprojectionInfo &info)
    6372          11 :                         : m_info(info)
    6373             :                     {
    6374          11 :                     }
    6375             : 
    6376       10262 :                     bool update(bool bNeedSwap, void *x, void *y, void *z,
    6377             :                                 void * /* m */) override
    6378             :                     {
    6379             :                         double dfX, dfY, dfZ;
    6380       10262 :                         memcpy(&dfX, x, sizeof(double));
    6381       10262 :                         memcpy(&dfY, y, sizeof(double));
    6382       10262 :                         if (bNeedSwap)
    6383             :                         {
    6384           0 :                             CPL_SWAP64PTR(&dfX);
    6385           0 :                             CPL_SWAP64PTR(&dfY);
    6386             :                         }
    6387       10262 :                         if (z)
    6388             :                         {
    6389           0 :                             memcpy(&dfZ, z, sizeof(double));
    6390           0 :                             if (bNeedSwap)
    6391             :                             {
    6392           0 :                                 CPL_SWAP64PTR(&dfZ);
    6393             :                             }
    6394             :                         }
    6395             :                         else
    6396       10262 :                             dfZ = 0;
    6397       10262 :                         m_info.UpdateExtremePoints(dfX, dfY, dfZ);
    6398       10262 :                         return true;
    6399             :                     }
    6400             :                 };
    6401             : 
    6402          22 :                 OGRWKBPointVisitor oVisitor(psInfo->m_aoReprojectionInfo[0]);
    6403          11 :                 const GByte *pabyValidity =
    6404          11 :                     static_cast<const GByte *>(psGeomArray->buffers[0]);
    6405             : 
    6406       10046 :                 for (size_t i = 0; i < static_cast<size_t>(nArrayLength); ++i)
    6407             :                 {
    6408       10035 :                     const size_t iShifted =
    6409       10035 :                         static_cast<size_t>(i + psGeomArray->offset);
    6410       10035 :                     if (!pabyValidity || (pabyValidity[iShifted >> 8] &
    6411          24 :                                           (1 << (iShifted % 8))) != 0)
    6412             :                     {
    6413       10027 :                         const auto nWKBSize =
    6414       10027 :                             panOffsets[iShifted + 1] - panOffsets[iShifted];
    6415       10027 :                         OGRWKBUpdatePoints(abyModifiedWKB.data() +
    6416       10027 :                                                panOffsets[iShifted],
    6417             :                                            nWKBSize, oVisitor);
    6418             :                     }
    6419             :                 }
    6420             :             }
    6421             : 
    6422          11 :             std::atomic<bool> atomicRet{true};
    6423             :             const auto oReprojectionLambda =
    6424          11 :                 [psGeomArray, nArrayLength, panOffsets, &atomicRet,
    6425       40138 :                  &abyModifiedWKB, &poCT](int iThread, int nThreads)
    6426             :             {
    6427             :                 OGRWKBTransformCache oCache;
    6428          11 :                 OGREnvelope3D sEnv3D;
    6429             :                 auto poThisCT =
    6430          11 :                     std::unique_ptr<OGRCoordinateTransformation>(poCT->Clone());
    6431          11 :                 if (!poThisCT)
    6432             :                 {
    6433           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    6434             :                              "Cannot clone OGRCoordinateTransformation");
    6435           0 :                     atomicRet = false;
    6436           0 :                     return;
    6437             :                 }
    6438             : 
    6439          11 :                 const GByte *pabyValidity =
    6440          11 :                     static_cast<const GByte *>(psGeomArray->buffers[0]);
    6441          11 :                 const size_t iStart =
    6442          11 :                     static_cast<size_t>(iThread * nArrayLength / nThreads);
    6443          11 :                 const size_t iMax = static_cast<size_t>(
    6444          11 :                     (iThread + 1) * nArrayLength / nThreads);
    6445       10046 :                 for (size_t i = iStart; i < iMax; ++i)
    6446             :                 {
    6447       10035 :                     const size_t iShifted =
    6448       10035 :                         static_cast<size_t>(i + psGeomArray->offset);
    6449       10035 :                     if (!pabyValidity || (pabyValidity[iShifted >> 8] &
    6450          24 :                                           (1 << (iShifted % 8))) != 0)
    6451             :                     {
    6452       10027 :                         const auto nWKBSize =
    6453       10027 :                             panOffsets[iShifted + 1] - panOffsets[iShifted];
    6454       20054 :                         if (!OGRWKBTransform(
    6455       10027 :                                 abyModifiedWKB.data() + panOffsets[iShifted],
    6456             :                                 nWKBSize, poThisCT.get(), oCache, sEnv3D))
    6457             :                         {
    6458           0 :                             CPLError(CE_Failure, CPLE_AppDefined,
    6459             :                                      "Reprojection failed");
    6460           0 :                             atomicRet = false;
    6461           0 :                             break;
    6462             :                         }
    6463             :                     }
    6464             :                 }
    6465          11 :             };
    6466             : 
    6467          11 :             if (nArrayLength >= MIN_FEATURES_FOR_THREADED_REPROJ &&
    6468           5 :                 nNumReprojectionThreads >= 2)
    6469             :             {
    6470           0 :                 std::vector<std::future<void>> oTasks;
    6471           0 :                 for (int iThread = 0; iThread < nNumReprojectionThreads;
    6472             :                      ++iThread)
    6473             :                 {
    6474           0 :                     oTasks.emplace_back(std::async(std::launch::async,
    6475             :                                                    oReprojectionLambda, iThread,
    6476           0 :                                                    nNumReprojectionThreads));
    6477             :                 }
    6478           0 :                 for (auto &oTask : oTasks)
    6479             :                 {
    6480           0 :                     oTask.get();
    6481           0 :                 }
    6482             :             }
    6483             :             else
    6484             :             {
    6485          11 :                 oReprojectionLambda(0, 1);
    6486             :             }
    6487             : 
    6488          11 :             bRet = atomicRet;
    6489          11 :             if (!bRet)
    6490             :             {
    6491           0 :                 if (array.release)
    6492           0 :                     array.release(&array);
    6493           0 :                 break;
    6494             :             }
    6495             :         }
    6496             : 
    6497             :         // Write batch to target layer
    6498         158 :         const bool bWriteOK = psInfo->m_poDstLayer->WriteArrowBatch(
    6499         158 :             &schema, &array, aosOptionsWriteArrowBatch.List());
    6500             : 
    6501         158 :         if (array.release)
    6502          38 :             array.release(&array);
    6503             : 
    6504         158 :         if (!bWriteOK)
    6505             :         {
    6506           0 :             CPLError(CE_Failure, CPLE_AppDefined, "WriteArrowBatch() failed");
    6507           0 :             bRet = false;
    6508           0 :             break;
    6509             :         }
    6510             : 
    6511             :         /* Report progress */
    6512         158 :         if (pfnProgress)
    6513             :         {
    6514           0 :             if (!pfnProgress(nCountLayerFeatures
    6515           0 :                                  ? nCount * 1.0 / nCountLayerFeatures
    6516             :                                  : 1.0,
    6517             :                              "", pProgressArg))
    6518             :             {
    6519           0 :                 bGoOn = false;
    6520           0 :                 bRet = false;
    6521             :             }
    6522             :         }
    6523             : 
    6524         158 :         if (pnReadFeatureCount)
    6525           0 :             *pnReadFeatureCount = nCount;
    6526             :     }
    6527             : 
    6528         167 :     schema.release(&schema);
    6529             : 
    6530         167 :     return bRet;
    6531             : }
    6532             : 
    6533             : /************************************************************************/
    6534             : /*                     LayerTranslator::Translate()                     */
    6535             : /************************************************************************/
    6536             : 
    6537        2014 : bool LayerTranslator::Translate(
    6538             :     std::unique_ptr<OGRFeature> poFeatureIn, TargetLayerInfo *psInfo,
    6539             :     GIntBig nCountLayerFeatures, GIntBig *pnReadFeatureCount,
    6540             :     GIntBig &nTotalEventsDone, GDALProgressFunc pfnProgress, void *pProgressArg,
    6541             :     const GDALVectorTranslateOptions *psOptions)
    6542             : {
    6543        2014 :     if (psInfo->m_bUseWriteArrowBatch)
    6544             :     {
    6545         167 :         return TranslateArrow(psInfo, nCountLayerFeatures, pnReadFeatureCount,
    6546         167 :                               pfnProgress, pProgressArg, psOptions);
    6547             :     }
    6548             : 
    6549        1847 :     const int eGType = m_eGType;
    6550        1847 :     const OGRSpatialReference *poOutputSRS = m_poOutputSRS;
    6551             : 
    6552        1847 :     OGRLayer *poSrcLayer = psInfo->m_poSrcLayer;
    6553        1847 :     OGRLayer *poDstLayer = psInfo->m_poDstLayer;
    6554        1847 :     const int *const panMap = psInfo->m_anMap.data();
    6555        1847 :     const int iSrcZField = psInfo->m_iSrcZField;
    6556        1847 :     const bool bPreserveFID = psInfo->m_bPreserveFID;
    6557        1847 :     const auto poSrcFDefn = poSrcLayer->GetLayerDefn();
    6558        1847 :     const auto poDstFDefn = poDstLayer->GetLayerDefn();
    6559        1847 :     const int nSrcGeomFieldCount = poSrcFDefn->GetGeomFieldCount();
    6560        1847 :     const int nDstGeomFieldCount = poDstFDefn->GetGeomFieldCount();
    6561        1847 :     const bool bExplodeCollections =
    6562        1847 :         m_bExplodeCollections && nDstGeomFieldCount <= 1;
    6563        1847 :     const int iRequestedSrcGeomField = psInfo->m_iRequestedSrcGeomField;
    6564             : 
    6565        1847 :     if (poOutputSRS == nullptr && !m_bNullifyOutputSRS)
    6566             :     {
    6567        1814 :         if (nSrcGeomFieldCount == 1)
    6568             :         {
    6569         773 :             poOutputSRS = poSrcLayer->GetSpatialRef();
    6570             :         }
    6571        1041 :         else if (iRequestedSrcGeomField > 0)
    6572             :         {
    6573           1 :             poOutputSRS = poSrcLayer->GetLayerDefn()
    6574           1 :                               ->GetGeomFieldDefn(iRequestedSrcGeomField)
    6575           1 :                               ->GetSpatialRef();
    6576             :         }
    6577             :     }
    6578             : 
    6579             :     /* -------------------------------------------------------------------- */
    6580             :     /*      Transfer features.                                              */
    6581             :     /* -------------------------------------------------------------------- */
    6582        1847 :     if (psOptions->nGroupTransactions)
    6583             :     {
    6584        1846 :         if (psOptions->nLayerTransaction)
    6585             :         {
    6586         724 :             if (poDstLayer->StartTransaction() == OGRERR_FAILURE)
    6587             :             {
    6588           0 :                 return false;
    6589             :             }
    6590             :         }
    6591             :     }
    6592             : 
    6593        1847 :     std::unique_ptr<OGRFeature> poFeature;
    6594        3694 :     auto poDstFeature = std::make_unique<OGRFeature>(poDstFDefn);
    6595        1847 :     int nFeaturesInTransaction = 0;
    6596        1847 :     GIntBig nCount = 0; /* written + failed */
    6597        1847 :     GIntBig nFeaturesWritten = 0;
    6598        1847 :     bool bRunSetPrecisionEvaluated = false;
    6599        1847 :     bool bRunSetPrecision = false;
    6600             : 
    6601        1847 :     bool bRet = true;
    6602        1847 :     CPLErrorReset();
    6603             : 
    6604        1847 :     bool bSetupCTOK = false;
    6605        1847 :     if (m_bTransform && psInfo->m_nFeaturesRead == 0 &&
    6606          26 :         !psInfo->m_bPerFeatureCT)
    6607             :     {
    6608          26 :         bSetupCTOK = SetupCT(psInfo, poSrcLayer, m_bTransform, m_bWrapDateline,
    6609          26 :                              m_osDateLineOffset, m_poUserSourceSRS, nullptr,
    6610             :                              poOutputSRS, m_poGCPCoordTrans, false);
    6611             :     }
    6612             : 
    6613        1847 :     const bool bSingleIteration = poFeatureIn != nullptr;
    6614             :     while (true)
    6615             :     {
    6616       15305 :         if (m_nLimit >= 0 && psInfo->m_nFeaturesRead >= m_nLimit)
    6617             :         {
    6618           9 :             break;
    6619             :         }
    6620             : 
    6621       15296 :         if (poFeatureIn != nullptr)
    6622         974 :             poFeature = std::move(poFeatureIn);
    6623       14322 :         else if (psOptions->nFIDToFetch != OGRNullFID)
    6624           5 :             poFeature.reset(poSrcLayer->GetFeature(psOptions->nFIDToFetch));
    6625             :         else
    6626       14317 :             poFeature.reset(poSrcLayer->GetNextFeature());
    6627             : 
    6628       15296 :         if (poFeature == nullptr)
    6629             :         {
    6630         852 :             if (CPLGetLastErrorType() == CE_Failure)
    6631             :             {
    6632           8 :                 bRet = false;
    6633             :             }
    6634         852 :             break;
    6635             :         }
    6636             : 
    6637       14444 :         if (!bSetupCTOK &&
    6638       14333 :             (psInfo->m_nFeaturesRead == 0 || psInfo->m_bPerFeatureCT))
    6639             :         {
    6640        1818 :             if (!SetupCT(psInfo, poSrcLayer, m_bTransform, m_bWrapDateline,
    6641         909 :                          m_osDateLineOffset, m_poUserSourceSRS, poFeature.get(),
    6642             :                          poOutputSRS, m_poGCPCoordTrans, true))
    6643             :             {
    6644           6 :                 return false;
    6645             :             }
    6646             :         }
    6647             : 
    6648       14444 :         psInfo->m_nFeaturesRead++;
    6649             : 
    6650       14444 :         int nIters = 1;
    6651           0 :         std::unique_ptr<OGRGeometryCollection> poCollToExplode;
    6652       14444 :         int iGeomCollToExplode = -1;
    6653       14444 :         OGRGeometry *poSrcGeometry = nullptr;
    6654       14444 :         if (bExplodeCollections)
    6655             :         {
    6656          13 :             if (iRequestedSrcGeomField >= 0)
    6657             :                 poSrcGeometry =
    6658           0 :                     poFeature->GetGeomFieldRef(iRequestedSrcGeomField);
    6659             :             else
    6660          13 :                 poSrcGeometry = poFeature->GetGeometryRef();
    6661          26 :             if (poSrcGeometry &&
    6662          13 :                 OGR_GT_IsSubClassOf(poSrcGeometry->getGeometryType(),
    6663             :                                     wkbGeometryCollection))
    6664             :             {
    6665             :                 const int nParts =
    6666          12 :                     poSrcGeometry->toGeometryCollection()->getNumGeometries();
    6667          21 :                 if (nParts > 0 ||
    6668           9 :                     wkbFlatten(poSrcGeometry->getGeometryType()) !=
    6669             :                         wkbGeometryCollection)
    6670             :                 {
    6671          11 :                     iGeomCollToExplode = iRequestedSrcGeomField >= 0
    6672             :                                              ? iRequestedSrcGeomField
    6673             :                                              : 0;
    6674          11 :                     poCollToExplode.reset(
    6675             :                         poFeature->StealGeometry(iGeomCollToExplode)
    6676             :                             ->toGeometryCollection());
    6677          11 :                     nIters = std::max(1, nParts);
    6678             :                 }
    6679             :             }
    6680             :         }
    6681             : 
    6682       14444 :         const GIntBig nSrcFID = poFeature->GetFID();
    6683       14444 :         GIntBig nDesiredFID = OGRNullFID;
    6684       14444 :         if (bPreserveFID)
    6685        1164 :             nDesiredFID = nSrcFID;
    6686       13281 :         else if (psInfo->m_iSrcFIDField >= 0 &&
    6687           1 :                  poFeature->IsFieldSetAndNotNull(psInfo->m_iSrcFIDField))
    6688             :             nDesiredFID =
    6689           1 :                 poFeature->GetFieldAsInteger64(psInfo->m_iSrcFIDField);
    6690             : 
    6691       28885 :         for (int iPart = 0; iPart < nIters; iPart++)
    6692             :         {
    6693       20544 :             if (psOptions->nLayerTransaction &&
    6694        6097 :                 ++nFeaturesInTransaction == psOptions->nGroupTransactions)
    6695             :             {
    6696          36 :                 if (poDstLayer->CommitTransaction() == OGRERR_FAILURE ||
    6697          18 :                     poDstLayer->StartTransaction() == OGRERR_FAILURE)
    6698             :                 {
    6699           0 :                     return false;
    6700             :                 }
    6701          18 :                 nFeaturesInTransaction = 0;
    6702             :             }
    6703       37208 :             else if (!psOptions->nLayerTransaction &&
    6704       22759 :                      psOptions->nGroupTransactions > 0 &&
    6705        8330 :                      ++nTotalEventsDone >= psOptions->nGroupTransactions)
    6706             :             {
    6707          80 :                 if (m_poODS->CommitTransaction() == OGRERR_FAILURE ||
    6708          40 :                     m_poODS->StartTransaction(psOptions->bForceTransaction) ==
    6709             :                         OGRERR_FAILURE)
    6710             :                 {
    6711           0 :                     return false;
    6712             :                 }
    6713          40 :                 nTotalEventsDone = 0;
    6714             :             }
    6715             : 
    6716       14447 :             CPLErrorReset();
    6717       14447 :             if (psInfo->m_bCanAvoidSetFrom)
    6718             :             {
    6719       14148 :                 poDstFeature = std::move(poFeature);
    6720             :                 // From now on, poFeature is null !
    6721       14148 :                 poDstFeature->SetFDefnUnsafe(poDstFDefn);
    6722       14148 :                 poDstFeature->SetFID(nDesiredFID);
    6723             :             }
    6724             :             else
    6725             :             {
    6726             :                 /* Optimization to avoid duplicating the source geometry in the
    6727             :                  */
    6728             :                 /* target feature : we steal it from the source feature for
    6729             :                  * now... */
    6730           0 :                 std::unique_ptr<OGRGeometry> poStolenGeometry;
    6731         299 :                 if (!bExplodeCollections && nSrcGeomFieldCount == 1 &&
    6732         104 :                     (nDstGeomFieldCount == 1 ||
    6733         104 :                      (nDstGeomFieldCount == 0 && m_poClipSrcOri)))
    6734             :                 {
    6735         134 :                     poStolenGeometry.reset(poFeature->StealGeometry());
    6736             :                 }
    6737         165 :                 else if (!bExplodeCollections && iRequestedSrcGeomField >= 0)
    6738             :                 {
    6739           0 :                     poStolenGeometry.reset(
    6740             :                         poFeature->StealGeometry(iRequestedSrcGeomField));
    6741             :                 }
    6742             : 
    6743         299 :                 if (nDstGeomFieldCount == 0 && poStolenGeometry &&
    6744           0 :                     m_poClipSrcOri)
    6745             :                 {
    6746           0 :                     if (poStolenGeometry->IsEmpty())
    6747           0 :                         goto end_loop;
    6748             : 
    6749             :                     const auto clipGeomDesc =
    6750           0 :                         GetSrcClipGeom(poStolenGeometry->getSpatialReference());
    6751             : 
    6752           0 :                     if (clipGeomDesc.poGeom && clipGeomDesc.poEnv)
    6753             :                     {
    6754           0 :                         OGREnvelope oEnv;
    6755           0 :                         poStolenGeometry->getEnvelope(&oEnv);
    6756           0 :                         if (!clipGeomDesc.poEnv->Contains(oEnv) &&
    6757           0 :                             !(clipGeomDesc.poEnv->Intersects(oEnv) &&
    6758           0 :                               clipGeomDesc.poGeom->Intersects(
    6759           0 :                                   poStolenGeometry.get())))
    6760             :                         {
    6761           0 :                             goto end_loop;
    6762             :                         }
    6763             :                     }
    6764             :                 }
    6765             : 
    6766         299 :                 poDstFeature->Reset();
    6767             : 
    6768         598 :                 if (poDstFeature->SetFrom(
    6769         299 :                         poFeature.get(), panMap, /* bForgiving = */ TRUE,
    6770         299 :                         /* bUseISO8601ForDateTimeAsString = */ true) !=
    6771             :                     OGRERR_NONE)
    6772             :                 {
    6773           0 :                     if (psOptions->nGroupTransactions)
    6774             :                     {
    6775           0 :                         if (psOptions->nLayerTransaction)
    6776             :                         {
    6777           0 :                             if (poDstLayer->CommitTransaction() != OGRERR_NONE)
    6778             :                             {
    6779           0 :                                 return false;
    6780             :                             }
    6781             :                         }
    6782             :                     }
    6783             : 
    6784           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    6785             :                              "Unable to translate feature " CPL_FRMT_GIB
    6786             :                              " from layer %s.",
    6787           0 :                              nSrcFID, poSrcLayer->GetName());
    6788             : 
    6789           0 :                     return false;
    6790             :                 }
    6791             : 
    6792             :                 /* ... and now we can attach the stolen geometry */
    6793         299 :                 if (poStolenGeometry)
    6794             :                 {
    6795         127 :                     poDstFeature->SetGeometryDirectly(
    6796             :                         poStolenGeometry.release());
    6797             :                 }
    6798             : 
    6799         299 :                 if (!psInfo->m_oMapResolved.empty())
    6800             :                 {
    6801           4 :                     for (const auto &kv : psInfo->m_oMapResolved)
    6802             :                     {
    6803           2 :                         const int nDstField = kv.first;
    6804           2 :                         const int nSrcField = kv.second.nSrcField;
    6805           2 :                         if (poFeature->IsFieldSetAndNotNull(nSrcField))
    6806             :                         {
    6807           2 :                             const auto poDomain = kv.second.poDomain;
    6808             :                             const auto &oMapKV =
    6809           2 :                                 psInfo->m_oMapDomainToKV[poDomain];
    6810             :                             const auto iter = oMapKV.find(
    6811           2 :                                 poFeature->GetFieldAsString(nSrcField));
    6812           2 :                             if (iter != oMapKV.end())
    6813             :                             {
    6814           2 :                                 poDstFeature->SetField(nDstField,
    6815           1 :                                                        iter->second.c_str());
    6816             :                             }
    6817             :                         }
    6818             :                     }
    6819             :                 }
    6820             : 
    6821         299 :                 if (nDesiredFID != OGRNullFID)
    6822           2 :                     poDstFeature->SetFID(nDesiredFID);
    6823             :             }
    6824             : 
    6825       14447 :             if (psOptions->bEmptyStrAsNull)
    6826             :             {
    6827           2 :                 for (int i = 0; i < poDstFeature->GetFieldCount(); i++)
    6828             :                 {
    6829           1 :                     if (!poDstFeature->IsFieldSetAndNotNull(i))
    6830           0 :                         continue;
    6831           1 :                     auto fieldDef = poDstFeature->GetFieldDefnRef(i);
    6832           1 :                     if (fieldDef->GetType() != OGRFieldType::OFTString)
    6833           0 :                         continue;
    6834           1 :                     auto str = poDstFeature->GetFieldAsString(i);
    6835           1 :                     if (strcmp(str, "") == 0)
    6836           1 :                         poDstFeature->SetFieldNull(i);
    6837             :                 }
    6838             :             }
    6839             : 
    6840       14447 :             if (!psInfo->m_anDateTimeFieldIdx.empty())
    6841             :             {
    6842          40 :                 for (int i : psInfo->m_anDateTimeFieldIdx)
    6843             :                 {
    6844          20 :                     if (!poDstFeature->IsFieldSetAndNotNull(i))
    6845          11 :                         continue;
    6846          15 :                     auto psField = poDstFeature->GetRawFieldRef(i);
    6847          15 :                     if (psField->Date.TZFlag == 0 || psField->Date.TZFlag == 1)
    6848           5 :                         continue;
    6849             : 
    6850          10 :                     const int nTZOffsetInSec =
    6851          10 :                         (psField->Date.TZFlag - 100) * 15 * 60;
    6852          10 :                     if (nTZOffsetInSec == psOptions->nTZOffsetInSec)
    6853           1 :                         continue;
    6854             : 
    6855             :                     struct tm brokendowntime;
    6856           9 :                     memset(&brokendowntime, 0, sizeof(brokendowntime));
    6857           9 :                     brokendowntime.tm_year = psField->Date.Year - 1900;
    6858           9 :                     brokendowntime.tm_mon = psField->Date.Month - 1;
    6859           9 :                     brokendowntime.tm_mday = psField->Date.Day;
    6860           9 :                     GIntBig nUnixTime = CPLYMDHMSToUnixTime(&brokendowntime);
    6861           9 :                     int nSec = psField->Date.Hour * 3600 +
    6862           9 :                                psField->Date.Minute * 60 +
    6863           9 :                                static_cast<int>(psField->Date.Second);
    6864           9 :                     nSec += psOptions->nTZOffsetInSec - nTZOffsetInSec;
    6865           9 :                     nUnixTime += nSec;
    6866           9 :                     CPLUnixTimeToYMDHMS(nUnixTime, &brokendowntime);
    6867             : 
    6868           9 :                     psField->Date.Year =
    6869           9 :                         static_cast<GInt16>(brokendowntime.tm_year + 1900);
    6870           9 :                     psField->Date.Month =
    6871           9 :                         static_cast<GByte>(brokendowntime.tm_mon + 1);
    6872           9 :                     psField->Date.Day =
    6873           9 :                         static_cast<GByte>(brokendowntime.tm_mday);
    6874           9 :                     psField->Date.Hour =
    6875           9 :                         static_cast<GByte>(brokendowntime.tm_hour);
    6876           9 :                     psField->Date.Minute =
    6877           9 :                         static_cast<GByte>(brokendowntime.tm_min);
    6878           9 :                     psField->Date.Second = static_cast<float>(
    6879           9 :                         brokendowntime.tm_sec + fmod(psField->Date.Second, 1));
    6880           9 :                     psField->Date.TZFlag = static_cast<GByte>(
    6881           9 :                         100 + psOptions->nTZOffsetInSec / (15 * 60));
    6882             :                 }
    6883             :             }
    6884             : 
    6885             :             /* Erase native data if asked explicitly */
    6886       14447 :             if (!m_bNativeData)
    6887             :             {
    6888           1 :                 poDstFeature->SetNativeData(nullptr);
    6889           1 :                 poDstFeature->SetNativeMediaType(nullptr);
    6890             :             }
    6891             : 
    6892       22856 :             for (int iGeom = 0; iGeom < nDstGeomFieldCount; iGeom++)
    6893             :             {
    6894           0 :                 std::unique_ptr<OGRGeometry> poDstGeometry;
    6895             : 
    6896        8456 :                 if (poCollToExplode && iGeom == iGeomCollToExplode)
    6897             :                 {
    6898          14 :                     if (poSrcGeometry && poCollToExplode->IsEmpty())
    6899             :                     {
    6900             :                         const OGRwkbGeometryType eSrcType =
    6901           8 :                             poSrcGeometry->getGeometryType();
    6902             :                         const OGRwkbGeometryType eSrcFlattenType =
    6903           8 :                             wkbFlatten(eSrcType);
    6904           8 :                         OGRwkbGeometryType eDstType = eSrcType;
    6905           8 :                         switch (eSrcFlattenType)
    6906             :                         {
    6907           4 :                             case wkbMultiPoint:
    6908           4 :                                 eDstType = wkbPoint;
    6909           4 :                                 break;
    6910           1 :                             case wkbMultiLineString:
    6911           1 :                                 eDstType = wkbLineString;
    6912           1 :                                 break;
    6913           1 :                             case wkbMultiPolygon:
    6914           1 :                                 eDstType = wkbPolygon;
    6915           1 :                                 break;
    6916           1 :                             case wkbMultiCurve:
    6917           1 :                                 eDstType = wkbCompoundCurve;
    6918           1 :                                 break;
    6919           1 :                             case wkbMultiSurface:
    6920           1 :                                 eDstType = wkbCurvePolygon;
    6921           1 :                                 break;
    6922           0 :                             default:
    6923           0 :                                 break;
    6924             :                         }
    6925             :                         eDstType =
    6926           8 :                             OGR_GT_SetModifier(eDstType, OGR_GT_HasZ(eSrcType),
    6927             :                                                OGR_GT_HasM(eSrcType));
    6928           8 :                         poDstGeometry.reset(
    6929             :                             OGRGeometryFactory::createGeometry(eDstType));
    6930             :                     }
    6931             :                     else
    6932             :                     {
    6933             :                         OGRGeometry *poPart =
    6934           6 :                             poCollToExplode->getGeometryRef(0);
    6935           6 :                         poCollToExplode->removeGeometry(0, FALSE);
    6936           6 :                         poDstGeometry.reset(poPart);
    6937             :                     }
    6938             :                 }
    6939             :                 else
    6940             :                 {
    6941        8442 :                     poDstGeometry.reset(poDstFeature->StealGeometry(iGeom));
    6942             :                 }
    6943        8456 :                 if (poDstGeometry == nullptr)
    6944         676 :                     continue;
    6945             : 
    6946             :                 // poFeature hasn't been moved if iSrcZField != -1
    6947             :                 // cppcheck-suppress accessMoved
    6948        7780 :                 if (iSrcZField != -1 && poFeature != nullptr)
    6949             :                 {
    6950          30 :                     SetZ(poDstGeometry.get(),
    6951             :                          poFeature->GetFieldAsDouble(iSrcZField));
    6952             :                     /* This will correct the coordinate dimension to 3 */
    6953          30 :                     poDstGeometry.reset(poDstGeometry->clone());
    6954             :                 }
    6955             : 
    6956        7780 :                 if (m_nCoordDim == 2 || m_nCoordDim == 3)
    6957             :                 {
    6958          24 :                     poDstGeometry->setCoordinateDimension(m_nCoordDim);
    6959             :                 }
    6960        7756 :                 else if (m_nCoordDim == 4)
    6961             :                 {
    6962           2 :                     poDstGeometry->set3D(TRUE);
    6963           2 :                     poDstGeometry->setMeasured(TRUE);
    6964             :                 }
    6965        7754 :                 else if (m_nCoordDim == COORD_DIM_XYM)
    6966             :                 {
    6967           2 :                     poDstGeometry->set3D(FALSE);
    6968           2 :                     poDstGeometry->setMeasured(TRUE);
    6969             :                 }
    6970        7752 :                 else if (m_nCoordDim == COORD_DIM_LAYER_DIM)
    6971             :                 {
    6972             :                     const OGRwkbGeometryType eDstLayerGeomType =
    6973           2 :                         poDstLayer->GetLayerDefn()
    6974           2 :                             ->GetGeomFieldDefn(iGeom)
    6975           2 :                             ->GetType();
    6976           2 :                     poDstGeometry->set3D(wkbHasZ(eDstLayerGeomType));
    6977           2 :                     poDstGeometry->setMeasured(wkbHasM(eDstLayerGeomType));
    6978             :                 }
    6979             : 
    6980        7780 :                 if (m_eGeomOp == GEOMOP_SEGMENTIZE)
    6981             :                 {
    6982          20 :                     if (m_dfGeomOpParam > 0)
    6983          20 :                         poDstGeometry->segmentize(m_dfGeomOpParam);
    6984             :                 }
    6985        7760 :                 else if (m_eGeomOp == GEOMOP_SIMPLIFY_PRESERVE_TOPOLOGY)
    6986             :                 {
    6987           1 :                     if (m_dfGeomOpParam > 0)
    6988             :                     {
    6989             :                         auto poNewGeom = std::unique_ptr<OGRGeometry>(
    6990             :                             poDstGeometry->SimplifyPreserveTopology(
    6991           2 :                                 m_dfGeomOpParam));
    6992           1 :                         if (poNewGeom)
    6993             :                         {
    6994           1 :                             poDstGeometry = std::move(poNewGeom);
    6995             :                         }
    6996             :                     }
    6997             :                 }
    6998             : 
    6999        7780 :                 if (m_poClipSrcOri)
    7000             :                 {
    7001          50 :                     if (poDstGeometry->IsEmpty())
    7002          26 :                         goto end_loop;
    7003             : 
    7004             :                     const auto clipGeomDesc =
    7005          50 :                         GetSrcClipGeom(poDstGeometry->getSpatialReference());
    7006             : 
    7007          50 :                     if (!(clipGeomDesc.poGeom && clipGeomDesc.poEnv))
    7008           0 :                         goto end_loop;
    7009             : 
    7010          50 :                     OGREnvelope oDstEnv;
    7011          50 :                     poDstGeometry->getEnvelope(&oDstEnv);
    7012             : 
    7013          50 :                     if (!(clipGeomDesc.bGeomIsRectangle &&
    7014           0 :                           clipGeomDesc.poEnv->Contains(oDstEnv)))
    7015             :                     {
    7016           0 :                         std::unique_ptr<OGRGeometry> poClipped;
    7017          50 :                         if (clipGeomDesc.poEnv->Intersects(oDstEnv))
    7018             :                         {
    7019          30 :                             poClipped.reset(clipGeomDesc.poGeom->Intersection(
    7020          30 :                                 poDstGeometry.get()));
    7021             :                         }
    7022          50 :                         if (poClipped == nullptr || poClipped->IsEmpty())
    7023             :                         {
    7024          25 :                             goto end_loop;
    7025             :                         }
    7026             : 
    7027          25 :                         const int nDim = poDstGeometry->getDimension();
    7028          26 :                         if (poClipped->getDimension() < nDim &&
    7029           1 :                             wkbFlatten(poDstFDefn->GetGeomFieldDefn(iGeom)
    7030             :                                            ->GetType()) != wkbUnknown)
    7031             :                         {
    7032           3 :                             CPLDebug(
    7033             :                                 "OGR2OGR",
    7034             :                                 "Discarding feature " CPL_FRMT_GIB
    7035             :                                 " of layer %s, "
    7036             :                                 "as its intersection with -clipsrc is a %s "
    7037             :                                 "whereas the input is a %s",
    7038           1 :                                 nSrcFID, poSrcLayer->GetName(),
    7039           1 :                                 OGRToOGCGeomType(poClipped->getGeometryType()),
    7040             :                                 OGRToOGCGeomType(
    7041           1 :                                     poDstGeometry->getGeometryType()));
    7042           1 :                             goto end_loop;
    7043             :                         }
    7044             : 
    7045          72 :                         poDstGeometry = OGRGeometryFactory::makeCompatibleWith(
    7046          24 :                             std::move(poClipped),
    7047          48 :                             poDstFDefn->GetGeomFieldDefn(iGeom)->GetType());
    7048             :                     }
    7049             :                 }
    7050             : 
    7051             :                 OGRCoordinateTransformation *const poCT =
    7052        7754 :                     psInfo->m_aoReprojectionInfo[iGeom].m_poCT.get();
    7053             :                 char **const papszTransformOptions =
    7054        7754 :                     psInfo->m_aoReprojectionInfo[iGeom]
    7055        7754 :                         .m_aosTransformOptions.List();
    7056             :                 const bool bReprojCanInvalidateValidity =
    7057        7754 :                     psInfo->m_aoReprojectionInfo[iGeom]
    7058        7754 :                         .m_bCanInvalidateValidity;
    7059             : 
    7060        7754 :                 if (poCT != nullptr || papszTransformOptions != nullptr)
    7061             :                 {
    7062             :                     // If we need to change the geometry type to linear, and
    7063             :                     // we have a geometry with curves, then convert it to
    7064             :                     // linear first, to avoid invalidities due to the fact
    7065             :                     // that validity of arc portions isn't always kept while
    7066             :                     // reprojecting and then discretizing.
    7067         124 :                     if (bReprojCanInvalidateValidity &&
    7068         122 :                         (!psInfo->m_bSupportCurves ||
    7069          51 :                          m_eGeomTypeConversion == GTC_CONVERT_TO_LINEAR ||
    7070          49 :                          m_eGeomTypeConversion ==
    7071             :                              GTC_PROMOTE_TO_MULTI_AND_CONVERT_TO_LINEAR))
    7072             :                     {
    7073          73 :                         if (poDstGeometry->hasCurveGeometry(TRUE))
    7074             :                         {
    7075           4 :                             OGRwkbGeometryType eTargetType = OGR_GT_GetLinear(
    7076           4 :                                 poDstGeometry->getGeometryType());
    7077           8 :                             poDstGeometry = OGRGeometryFactory::forceTo(
    7078           8 :                                 std::move(poDstGeometry), eTargetType);
    7079          73 :                         }
    7080             :                     }
    7081          49 :                     else if (bReprojCanInvalidateValidity &&
    7082           2 :                              eGType != GEOMTYPE_UNCHANGED &&
    7083           2 :                              !OGR_GT_IsNonLinear(
    7084         100 :                                  static_cast<OGRwkbGeometryType>(eGType)) &&
    7085           2 :                              poDstGeometry->hasCurveGeometry(TRUE))
    7086             :                     {
    7087           4 :                         poDstGeometry = OGRGeometryFactory::forceTo(
    7088           2 :                             std::move(poDstGeometry),
    7089           2 :                             static_cast<OGRwkbGeometryType>(eGType));
    7090             :                     }
    7091             : 
    7092             :                     // Collect left-most, right-most, top-most, bottom-most coordinates.
    7093         124 :                     if (psInfo->m_aoReprojectionInfo[iGeom]
    7094         124 :                             .m_bWarnAboutDifferentCoordinateOperations)
    7095             :                     {
    7096             :                         struct Visitor : public OGRDefaultConstGeometryVisitor
    7097             :                         {
    7098             :                             TargetLayerInfo::ReprojectionInfo &m_info;
    7099             : 
    7100         110 :                             explicit Visitor(
    7101             :                                 TargetLayerInfo::ReprojectionInfo &info)
    7102         110 :                                 : m_info(info)
    7103             :                             {
    7104         110 :                             }
    7105             : 
    7106             :                             using OGRDefaultConstGeometryVisitor::visit;
    7107             : 
    7108        2814 :                             void visit(const OGRPoint *point) override
    7109             :                             {
    7110        2814 :                                 m_info.UpdateExtremePoints(point->getX(),
    7111             :                                                            point->getY(),
    7112             :                                                            point->getZ());
    7113        2814 :                             }
    7114             :                         };
    7115             : 
    7116         220 :                         Visitor oVisit(psInfo->m_aoReprojectionInfo[iGeom]);
    7117         110 :                         poDstGeometry->accept(&oVisit);
    7118             :                     }
    7119             : 
    7120         125 :                     for (int iIter = 0; iIter < 2; ++iIter)
    7121             :                     {
    7122             :                         auto poReprojectedGeom = std::unique_ptr<OGRGeometry>(
    7123             :                             OGRGeometryFactory::transformWithOptions(
    7124         125 :                                 poDstGeometry.get(), poCT,
    7125             :                                 papszTransformOptions,
    7126         125 :                                 m_transformWithOptionsCache));
    7127         125 :                         if (poReprojectedGeom == nullptr)
    7128             :                         {
    7129           0 :                             if (psOptions->nGroupTransactions)
    7130             :                             {
    7131           0 :                                 if (psOptions->nLayerTransaction)
    7132             :                                 {
    7133           0 :                                     if (poDstLayer->CommitTransaction() !=
    7134           0 :                                             OGRERR_NONE &&
    7135           0 :                                         !psOptions->bSkipFailures)
    7136             :                                     {
    7137           0 :                                         return false;
    7138             :                                     }
    7139             :                                 }
    7140             :                             }
    7141             : 
    7142           0 :                             CPLError(CE_Failure, CPLE_AppDefined,
    7143             :                                      "Failed to reproject feature " CPL_FRMT_GIB
    7144             :                                      " (geometry probably out of source or "
    7145             :                                      "destination SRS).",
    7146             :                                      nSrcFID);
    7147           0 :                             if (!psOptions->bSkipFailures)
    7148             :                             {
    7149           0 :                                 return false;
    7150             :                             }
    7151             :                         }
    7152             : 
    7153             :                         // Check if a curve geometry is no longer valid after
    7154             :                         // reprojection
    7155         125 :                         const auto eType = poDstGeometry->getGeometryType();
    7156         125 :                         const auto eFlatType = wkbFlatten(eType);
    7157             : 
    7158           4 :                         const auto IsValid = [](const OGRGeometry *poGeom)
    7159             :                         {
    7160             :                             CPLErrorHandlerPusher oErrorHandler(
    7161           8 :                                 CPLQuietErrorHandler);
    7162           8 :                             return poGeom->IsValid();
    7163             :                         };
    7164             : 
    7165         124 :                         if (iIter == 0 && bReprojCanInvalidateValidity &&
    7166         122 :                             OGRGeometryFactory::haveGEOS() &&
    7167         120 :                             (eFlatType == wkbCurvePolygon ||
    7168         120 :                              eFlatType == wkbCompoundCurve ||
    7169         120 :                              eFlatType == wkbMultiCurve ||
    7170           2 :                              eFlatType == wkbMultiSurface) &&
    7171         251 :                             poDstGeometry->hasCurveGeometry(TRUE) &&
    7172           2 :                             IsValid(poDstGeometry.get()))
    7173             :                         {
    7174           2 :                             OGRwkbGeometryType eTargetType = OGR_GT_GetLinear(
    7175           2 :                                 poDstGeometry->getGeometryType());
    7176             :                             auto poDstGeometryTmp = OGRGeometryFactory::forceTo(
    7177           2 :                                 std::unique_ptr<OGRGeometry>(
    7178           2 :                                     poReprojectedGeom->clone()),
    7179           2 :                                 eTargetType);
    7180           2 :                             if (!IsValid(poDstGeometryTmp.get()))
    7181             :                             {
    7182           1 :                                 CPLDebug("OGR2OGR",
    7183             :                                          "Curve geometry no longer valid after "
    7184             :                                          "reprojection: transforming it into "
    7185             :                                          "linear one before reprojecting");
    7186           2 :                                 poDstGeometry = OGRGeometryFactory::forceTo(
    7187           2 :                                     std::move(poDstGeometry), eTargetType);
    7188           2 :                                 poDstGeometry = OGRGeometryFactory::forceTo(
    7189           2 :                                     std::move(poDstGeometry), eType);
    7190             :                             }
    7191             :                             else
    7192             :                             {
    7193           1 :                                 poDstGeometry = std::move(poReprojectedGeom);
    7194           1 :                                 break;
    7195             :                             }
    7196             :                         }
    7197             :                         else
    7198             :                         {
    7199         123 :                             poDstGeometry = std::move(poReprojectedGeom);
    7200         123 :                             break;
    7201             :                         }
    7202         124 :                     }
    7203             :                 }
    7204        7630 :                 else if (poOutputSRS != nullptr)
    7205             :                 {
    7206        6480 :                     poDstGeometry->assignSpatialReference(poOutputSRS);
    7207             :                 }
    7208             : 
    7209        7754 :                 if (poDstGeometry != nullptr)
    7210             :                 {
    7211        7754 :                     if (m_poClipDstOri)
    7212             :                     {
    7213          40 :                         if (poDstGeometry->IsEmpty())
    7214          20 :                             goto end_loop;
    7215             : 
    7216             :                         const auto clipGeomDesc = GetDstClipGeom(
    7217          40 :                             poDstGeometry->getSpatialReference());
    7218          40 :                         if (!clipGeomDesc.poGeom || !clipGeomDesc.poEnv)
    7219             :                         {
    7220           0 :                             goto end_loop;
    7221             :                         }
    7222             : 
    7223          40 :                         OGREnvelope oDstEnv;
    7224          40 :                         poDstGeometry->getEnvelope(&oDstEnv);
    7225             : 
    7226          74 :                         if (!(clipGeomDesc.bGeomIsRectangle &&
    7227          34 :                               clipGeomDesc.poEnv->Contains(oDstEnv)))
    7228             :                         {
    7229           0 :                             std::unique_ptr<OGRGeometry> poClipped;
    7230          35 :                             if (clipGeomDesc.poEnv->Intersects(oDstEnv))
    7231             :                             {
    7232          20 :                                 poClipped.reset(
    7233          20 :                                     clipGeomDesc.poGeom->Intersection(
    7234          20 :                                         poDstGeometry.get()));
    7235             :                             }
    7236             : 
    7237          35 :                             if (poClipped == nullptr || poClipped->IsEmpty())
    7238             :                             {
    7239          19 :                                 goto end_loop;
    7240             :                             }
    7241             : 
    7242          16 :                             const int nDim = poDstGeometry->getDimension();
    7243          17 :                             if (poClipped->getDimension() < nDim &&
    7244           1 :                                 wkbFlatten(poDstFDefn->GetGeomFieldDefn(iGeom)
    7245             :                                                ->GetType()) != wkbUnknown)
    7246             :                             {
    7247           3 :                                 CPLDebug(
    7248             :                                     "OGR2OGR",
    7249             :                                     "Discarding feature " CPL_FRMT_GIB
    7250             :                                     " of layer %s, "
    7251             :                                     "as its intersection with -clipdst is a %s "
    7252             :                                     "whereas the input is a %s",
    7253           1 :                                     nSrcFID, poSrcLayer->GetName(),
    7254             :                                     OGRToOGCGeomType(
    7255           1 :                                         poClipped->getGeometryType()),
    7256             :                                     OGRToOGCGeomType(
    7257           1 :                                         poDstGeometry->getGeometryType()));
    7258           1 :                                 goto end_loop;
    7259             :                             }
    7260             : 
    7261             :                             poDstGeometry =
    7262          45 :                                 OGRGeometryFactory::makeCompatibleWith(
    7263          15 :                                     std::move(poClipped),
    7264          15 :                                     poDstFDefn->GetGeomFieldDefn(iGeom)
    7265          15 :                                         ->GetType());
    7266             :                         }
    7267             :                     }
    7268             : 
    7269       15468 :                     if (psOptions->dfXYRes !=
    7270           1 :                             OGRGeomCoordinatePrecision::UNKNOWN &&
    7271        7735 :                         OGRGeometryFactory::haveGEOS() &&
    7272           1 :                         !poDstGeometry->hasCurveGeometry())
    7273             :                     {
    7274             :                         // OGR_APPLY_GEOM_SET_PRECISION default value for
    7275             :                         // OGRLayer::CreateFeature() purposes, but here in the
    7276             :                         // ogr2ogr -xyRes context, we force calling SetPrecision(),
    7277             :                         // unless the user explicitly asks not to do it by
    7278             :                         // setting the config option to NO.
    7279           1 :                         if (!bRunSetPrecisionEvaluated)
    7280             :                         {
    7281           1 :                             bRunSetPrecisionEvaluated = true;
    7282           1 :                             bRunSetPrecision = CPLTestBool(CPLGetConfigOption(
    7283             :                                 "OGR_APPLY_GEOM_SET_PRECISION", "YES"));
    7284             :                         }
    7285           1 :                         if (bRunSetPrecision)
    7286             :                         {
    7287             :                             auto poNewGeom = std::unique_ptr<OGRGeometry>(
    7288           1 :                                 poDstGeometry->SetPrecision(psOptions->dfXYRes,
    7289           1 :                                                             /* nFlags = */ 0));
    7290           1 :                             if (!poNewGeom)
    7291           0 :                                 goto end_loop;
    7292           1 :                             poDstGeometry = std::move(poNewGeom);
    7293             :                         }
    7294             :                     }
    7295             : 
    7296        7734 :                     if (m_bMakeValid)
    7297             :                     {
    7298             :                         const bool bIsGeomCollection =
    7299           7 :                             wkbFlatten(poDstGeometry->getGeometryType()) ==
    7300           7 :                             wkbGeometryCollection;
    7301             :                         auto poNewGeom = std::unique_ptr<OGRGeometry>(
    7302           7 :                             poDstGeometry->MakeValid());
    7303           7 :                         if (!poNewGeom)
    7304           0 :                             goto end_loop;
    7305           7 :                         poDstGeometry = std::move(poNewGeom);
    7306           7 :                         if (!bIsGeomCollection)
    7307             :                         {
    7308           6 :                             poDstGeometry.reset(
    7309             :                                 OGRGeometryFactory::
    7310             :                                     removeLowerDimensionSubGeoms(
    7311           6 :                                         poDstGeometry.get()));
    7312             :                         }
    7313             :                     }
    7314             : 
    7315        7734 :                     if (m_bSkipInvalidGeom && !poDstGeometry->IsValid())
    7316           1 :                         goto end_loop;
    7317             : 
    7318        7733 :                     if (m_eGeomTypeConversion != GTC_DEFAULT)
    7319             :                     {
    7320             :                         OGRwkbGeometryType eTargetType =
    7321          11 :                             poDstGeometry->getGeometryType();
    7322             :                         eTargetType =
    7323          11 :                             ConvertType(m_eGeomTypeConversion, eTargetType);
    7324          22 :                         poDstGeometry = OGRGeometryFactory::forceTo(
    7325          22 :                             std::move(poDstGeometry), eTargetType);
    7326             :                     }
    7327        7722 :                     else if (eGType != GEOMTYPE_UNCHANGED)
    7328             :                     {
    7329         118 :                         poDstGeometry = OGRGeometryFactory::forceTo(
    7330          59 :                             std::move(poDstGeometry),
    7331          59 :                             static_cast<OGRwkbGeometryType>(eGType));
    7332             :                     }
    7333             :                 }
    7334             : 
    7335        7733 :                 if (poDstGeometry && !psOptions->bQuiet)
    7336             :                 {
    7337       23171 :                     if (!psInfo->m_bHasWarnedAboutCurves &&
    7338       10606 :                         !psInfo->m_bSupportCurves &&
    7339        2882 :                         OGR_GT_IsNonLinear(poDstGeometry->getGeometryType()))
    7340             :                     {
    7341           3 :                         CPLError(CE_Warning, CPLE_AppDefined,
    7342             :                                  "Attempt to write curve geometries to layer "
    7343             :                                  "%s that does not support them. They will be "
    7344             :                                  "linearized",
    7345           3 :                                  poDstLayer->GetDescription());
    7346           3 :                         psInfo->m_bHasWarnedAboutCurves = true;
    7347             :                     }
    7348        8677 :                     if (!psInfo->m_bHasWarnedAboutZ && !psInfo->m_bSupportZ &&
    7349         953 :                         OGR_GT_HasZ(poDstGeometry->getGeometryType()))
    7350             :                     {
    7351           3 :                         CPLError(CE_Warning, CPLE_AppDefined,
    7352             :                                  "Attempt to write Z geometries to layer %s "
    7353             :                                  "that does not support them. Z component will "
    7354             :                                  "be discarded",
    7355           3 :                                  poDstLayer->GetDescription());
    7356           3 :                         psInfo->m_bHasWarnedAboutZ = true;
    7357             :                     }
    7358        8761 :                     if (!psInfo->m_bHasWarnedAboutM && !psInfo->m_bSupportM &&
    7359        1037 :                         OGR_GT_HasM(poDstGeometry->getGeometryType()))
    7360             :                     {
    7361           1 :                         CPLError(CE_Warning, CPLE_AppDefined,
    7362             :                                  "Attempt to write M geometries to layer %s "
    7363             :                                  "that does not support them. M component will "
    7364             :                                  "be discarded",
    7365           1 :                                  poDstLayer->GetDescription());
    7366           1 :                         psInfo->m_bHasWarnedAboutM = true;
    7367             :                     }
    7368             :                 }
    7369             : 
    7370        7733 :                 poDstFeature->SetGeomField(iGeom, std::move(poDstGeometry));
    7371             :             }
    7372             : 
    7373       14400 :             CPLErrorReset();
    7374       28800 :             if ((psOptions->bUpsert
    7375       14400 :                      ? poDstLayer->UpsertFeature(poDstFeature.get())
    7376       14400 :                      : poDstLayer->CreateFeature(poDstFeature.get())) ==
    7377             :                 OGRERR_NONE)
    7378             :             {
    7379       14391 :                 nFeaturesWritten++;
    7380       15548 :                 if (nDesiredFID != OGRNullFID &&
    7381        1157 :                     poDstFeature->GetFID() != nDesiredFID)
    7382             :                 {
    7383           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    7384             :                              "Feature id " CPL_FRMT_GIB " not preserved",
    7385             :                              nDesiredFID);
    7386             :                 }
    7387             :             }
    7388           9 :             else if (!psOptions->bSkipFailures)
    7389             :             {
    7390           6 :                 if (psOptions->nGroupTransactions)
    7391             :                 {
    7392           6 :                     if (psOptions->nLayerTransaction)
    7393           2 :                         poDstLayer->RollbackTransaction();
    7394             :                 }
    7395             : 
    7396           6 :                 CPLError(CE_Failure, CPLE_AppDefined,
    7397             :                          "Unable to write feature " CPL_FRMT_GIB
    7398             :                          " from layer %s.",
    7399           6 :                          nSrcFID, poSrcLayer->GetName());
    7400             : 
    7401           6 :                 return false;
    7402             :             }
    7403             :             else
    7404             :             {
    7405           3 :                 CPLDebug("GDALVectorTranslate",
    7406             :                          "Unable to write feature " CPL_FRMT_GIB
    7407             :                          " into layer %s.",
    7408           3 :                          nSrcFID, poSrcLayer->GetName());
    7409           3 :                 if (psOptions->nGroupTransactions)
    7410             :                 {
    7411           3 :                     if (psOptions->nLayerTransaction)
    7412             :                     {
    7413           2 :                         poDstLayer->RollbackTransaction();
    7414           2 :                         CPL_IGNORE_RET_VAL(poDstLayer->StartTransaction());
    7415             :                     }
    7416             :                     else
    7417             :                     {
    7418           1 :                         m_poODS->RollbackTransaction();
    7419           1 :                         m_poODS->StartTransaction(psOptions->bForceTransaction);
    7420             :                     }
    7421             :                 }
    7422             :             }
    7423             : 
    7424       14441 :         end_loop:;  // nothing
    7425             :         }
    7426             : 
    7427             :         /* Report progress */
    7428       14438 :         nCount++;
    7429       14438 :         bool bGoOn = true;
    7430       14438 :         if (pfnProgress)
    7431             :         {
    7432        5295 :             bGoOn = pfnProgress(nCountLayerFeatures
    7433        2646 :                                     ? nCount * 1.0 / nCountLayerFeatures
    7434             :                                     : 1.0,
    7435             :                                 "", pProgressArg) != FALSE;
    7436             :         }
    7437       14438 :         if (!bGoOn)
    7438             :         {
    7439           1 :             bRet = false;
    7440           1 :             break;
    7441             :         }
    7442             : 
    7443       14437 :         if (pnReadFeatureCount)
    7444           0 :             *pnReadFeatureCount = nCount;
    7445             : 
    7446       14437 :         if (psOptions->nFIDToFetch != OGRNullFID)
    7447           5 :             break;
    7448       14432 :         if (bSingleIteration)
    7449         974 :             break;
    7450       13458 :     }
    7451             : 
    7452        1841 :     if (psOptions->nGroupTransactions)
    7453             :     {
    7454        1840 :         if (psOptions->nLayerTransaction)
    7455             :         {
    7456         722 :             if (poDstLayer->CommitTransaction() != OGRERR_NONE)
    7457           0 :                 bRet = false;
    7458             :         }
    7459             :     }
    7460             : 
    7461        1841 :     if (!bSingleIteration)
    7462             :     {
    7463         867 :         CPLDebug("GDALVectorTranslate",
    7464             :                  CPL_FRMT_GIB " features written in layer '%s'",
    7465         867 :                  nFeaturesWritten, poDstLayer->GetName());
    7466             :     }
    7467             : 
    7468        1841 :     return bRet;
    7469             : }
    7470             : 
    7471             : /************************************************************************/
    7472             : /*                  LayerTranslator::GetDstClipGeom()                   */
    7473             : /************************************************************************/
    7474             : 
    7475             : /** Returns the destination clip geometry and its envelope
    7476             :  *
    7477             :  * @param poGeomSRS The SRS into which the destination clip geometry should be
    7478             :  *                  expressed.
    7479             :  * @return the destination clip geometry and its envelope, or (nullptr, nullptr)
    7480             :  */
    7481             : LayerTranslator::ClipGeomDesc
    7482          40 : LayerTranslator::GetDstClipGeom(const OGRSpatialReference *poGeomSRS)
    7483             : {
    7484          40 :     if (m_poClipDstReprojectedToDstSRS_SRS != poGeomSRS)
    7485             :     {
    7486          36 :         auto poClipDstSRS = m_poClipDstOri->getSpatialReference();
    7487          36 :         if (poClipDstSRS && poGeomSRS && !poClipDstSRS->IsSame(poGeomSRS))
    7488             :         {
    7489             :             // Transform clip geom to geometry SRS
    7490           1 :             m_poClipDstReprojectedToDstSRS.reset(m_poClipDstOri->clone());
    7491           1 :             if (m_poClipDstReprojectedToDstSRS->transformTo(poGeomSRS) !=
    7492             :                 OGRERR_NONE)
    7493             :             {
    7494           0 :                 return ClipGeomDesc();
    7495             :             }
    7496           1 :             m_poClipDstReprojectedToDstSRS_SRS = poGeomSRS;
    7497             :         }
    7498          35 :         else if (!poClipDstSRS && poGeomSRS)
    7499             :         {
    7500          35 :             if (!m_bWarnedClipDstSRS)
    7501             :             {
    7502           2 :                 m_bWarnedClipDstSRS = true;
    7503           2 :                 CPLError(CE_Warning, CPLE_AppDefined,
    7504             :                          "Clip destination geometry has no "
    7505             :                          "attached SRS, but the feature's "
    7506             :                          "geometry has one. Assuming clip "
    7507             :                          "destination geometry SRS is the "
    7508             :                          "same as the feature's geometry");
    7509             :             }
    7510             :         }
    7511          36 :         m_oClipDstEnv = OGREnvelope();
    7512             :     }
    7513             : 
    7514             :     const auto poGeom = m_poClipDstReprojectedToDstSRS
    7515          40 :                             ? m_poClipDstReprojectedToDstSRS.get()
    7516          40 :                             : m_poClipDstOri;
    7517          40 :     if (poGeom && !m_oClipDstEnv.IsInit())
    7518             :     {
    7519          40 :         poGeom->getEnvelope(&m_oClipDstEnv);
    7520          40 :         m_bClipDstIsRectangle = poGeom->IsRectangle();
    7521             :     }
    7522          40 :     ClipGeomDesc ret;
    7523          40 :     ret.poGeom = poGeom;
    7524          40 :     ret.poEnv = poGeom ? &m_oClipDstEnv : nullptr;
    7525          40 :     ret.bGeomIsRectangle = m_bClipDstIsRectangle;
    7526          40 :     return ret;
    7527             : }
    7528             : 
    7529             : /************************************************************************/
    7530             : /*                  LayerTranslator::GetSrcClipGeom()                   */
    7531             : /************************************************************************/
    7532             : 
    7533             : /** Returns the source clip geometry and its envelope
    7534             :  *
    7535             :  * @param poGeomSRS The SRS into which the source clip geometry should be
    7536             :  *                  expressed.
    7537             :  * @return the source clip geometry and its envelope, or (nullptr, nullptr)
    7538             :  */
    7539             : LayerTranslator::ClipGeomDesc
    7540          50 : LayerTranslator::GetSrcClipGeom(const OGRSpatialReference *poGeomSRS)
    7541             : {
    7542          50 :     if (m_poClipSrcReprojectedToSrcSRS_SRS != poGeomSRS)
    7543             :     {
    7544          42 :         auto poClipSrcSRS = m_poClipSrcOri->getSpatialReference();
    7545          42 :         if (poClipSrcSRS && poGeomSRS && !poClipSrcSRS->IsSame(poGeomSRS))
    7546             :         {
    7547             :             // Transform clip geom to geometry SRS
    7548           1 :             m_poClipSrcReprojectedToSrcSRS.reset(m_poClipSrcOri->clone());
    7549           1 :             if (m_poClipSrcReprojectedToSrcSRS->transformTo(poGeomSRS) !=
    7550             :                 OGRERR_NONE)
    7551             :             {
    7552           0 :                 return ClipGeomDesc();
    7553             :             }
    7554           1 :             m_poClipSrcReprojectedToSrcSRS_SRS = poGeomSRS;
    7555             :         }
    7556          41 :         else if (!poClipSrcSRS && poGeomSRS)
    7557             :         {
    7558          41 :             if (!m_bWarnedClipSrcSRS)
    7559             :             {
    7560           3 :                 m_bWarnedClipSrcSRS = true;
    7561           3 :                 CPLError(CE_Warning, CPLE_AppDefined,
    7562             :                          "Clip source geometry has no attached SRS, "
    7563             :                          "but the feature's geometry has one. "
    7564             :                          "Assuming clip source geometry SRS is the "
    7565             :                          "same as the feature's geometry");
    7566             :             }
    7567             :         }
    7568          42 :         m_oClipSrcEnv = OGREnvelope();
    7569             :     }
    7570             : 
    7571             :     const auto poGeom = m_poClipSrcReprojectedToSrcSRS
    7572          50 :                             ? m_poClipSrcReprojectedToSrcSRS.get()
    7573          50 :                             : m_poClipSrcOri;
    7574          50 :     if (poGeom && !m_oClipSrcEnv.IsInit())
    7575             :     {
    7576          50 :         poGeom->getEnvelope(&m_oClipSrcEnv);
    7577          50 :         m_bClipSrcIsRectangle = poGeom->IsRectangle();
    7578             :     }
    7579          50 :     ClipGeomDesc ret;
    7580          50 :     ret.poGeom = poGeom;
    7581          50 :     ret.poEnv = poGeom ? &m_oClipSrcEnv : nullptr;
    7582          50 :     ret.bGeomIsRectangle = m_bClipDstIsRectangle;
    7583          50 :     return ret;
    7584             : }
    7585             : 
    7586             : /************************************************************************/
    7587             : /*           TargetLayerInfo::CheckSameCoordinateOperation()            */
    7588             : /************************************************************************/
    7589             : 
    7590        1181 : void TargetLayerInfo::CheckSameCoordinateOperation() const
    7591             : {
    7592        2266 :     for (auto &info : m_aoReprojectionInfo)
    7593             :     {
    7594        1085 :         if (info.m_bWarnAboutDifferentCoordinateOperations &&
    7595          36 :             info.m_dfLeftX <= info.m_dfRightX)
    7596             :         {
    7597             :             // Start recording if different coordinate operations are
    7598             :             // going to be used
    7599          35 :             OGRProjCTDifferentOperationsStart(info.m_poCT.get());
    7600             : 
    7601             :             {
    7602          70 :                 CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
    7603             :                 {
    7604          35 :                     double dfX = info.m_dfLeftX;
    7605          35 :                     double dfY = info.m_dfLeftY;
    7606          35 :                     double dfZ = info.m_dfLeftZ;
    7607          35 :                     info.m_poCT->Transform(1, &dfX, &dfY, &dfZ);
    7608             :                 }
    7609             : 
    7610             :                 {
    7611          35 :                     double dfX = info.m_dfRightX;
    7612          35 :                     double dfY = info.m_dfRightY;
    7613          35 :                     double dfZ = info.m_dfRightZ;
    7614          35 :                     info.m_poCT->Transform(1, &dfX, &dfY, &dfZ);
    7615             :                 }
    7616             : 
    7617             :                 {
    7618          35 :                     double dfX = info.m_dfTopX;
    7619          35 :                     double dfY = info.m_dfTopY;
    7620          35 :                     double dfZ = info.m_dfTopZ;
    7621          35 :                     info.m_poCT->Transform(1, &dfX, &dfY, &dfZ);
    7622             :                 }
    7623             : 
    7624             :                 {
    7625          35 :                     double dfX = info.m_dfBottomX;
    7626          35 :                     double dfY = info.m_dfBottomY;
    7627          35 :                     double dfZ = info.m_dfBottomZ;
    7628          35 :                     info.m_poCT->Transform(1, &dfX, &dfY, &dfZ);
    7629             :                 }
    7630             :             }
    7631             : 
    7632          35 :             if (OGRProjCTDifferentOperationsUsed(info.m_poCT.get()))
    7633             :             {
    7634           0 :                 CPLError(
    7635             :                     CE_Warning, CPLE_AppDefined,
    7636             :                     "Several coordinate operations have been used to transform "
    7637             :                     "layer %s. Artifacts may appear. You may consider "
    7638             :                     "using the -ct_opt ALLOW_BALLPARK=NO and/or "
    7639             :                     "-ct_opt ONLY_BEST=YES warping options, or specify "
    7640             :                     "a particular coordinate operation with -ct. "
    7641             :                     "This warning can be silenced with "
    7642             :                     "-ct_opt WARN_ABOUT_DIFFERENT_COORD_OP=NO.",
    7643           0 :                     m_poSrcLayer->GetName());
    7644             :             }
    7645             : 
    7646             :             // Stop recording
    7647          35 :             OGRProjCTDifferentOperationsStop(info.m_poCT.get());
    7648             :         }
    7649             :     }
    7650        1181 : }
    7651             : 
    7652             : /************************************************************************/
    7653             : /*                GDALVectorTranslateOptionsGetParser()                 */
    7654             : /************************************************************************/
    7655             : 
    7656        1068 : static std::unique_ptr<GDALArgumentParser> GDALVectorTranslateOptionsGetParser(
    7657             :     GDALVectorTranslateOptions *psOptions,
    7658             :     GDALVectorTranslateOptionsForBinary *psOptionsForBinary, int nCountClipSrc,
    7659             :     int nCountClipDst)
    7660             : {
    7661             :     auto argParser = std::make_unique<GDALArgumentParser>(
    7662        1068 :         "ogr2ogr", /* bForBinary=*/psOptionsForBinary != nullptr);
    7663             : 
    7664        1068 :     argParser->add_description(
    7665        1068 :         _("Converts simple features data between file formats."));
    7666             : 
    7667        1068 :     argParser->add_epilog(
    7668        1068 :         _("For more details, consult https://gdal.org/programs/ogr2ogr.html"));
    7669             : 
    7670        1068 :     argParser->add_output_format_argument(psOptions->osFormat);
    7671             : 
    7672        1068 :     argParser->add_dataset_creation_options_argument(psOptions->aosDSCO);
    7673             : 
    7674        1068 :     argParser->add_layer_creation_options_argument(psOptions->aosLCO);
    7675             : 
    7676        1068 :     argParser->add_usage_newline();
    7677             : 
    7678             :     {
    7679        1068 :         auto &group = argParser->add_mutually_exclusive_group();
    7680        1068 :         group.add_argument("-append")
    7681        1068 :             .flag()
    7682          39 :             .action([psOptions](const std::string &)
    7683        1068 :                     { psOptions->eAccessMode = ACCESS_APPEND; })
    7684        1068 :             .help(_("Append to existing layer instead of creating new."));
    7685             : 
    7686        1068 :         group.add_argument("-upsert")
    7687        1068 :             .flag()
    7688             :             .action(
    7689           4 :                 [psOptions](const std::string &)
    7690             :                 {
    7691           4 :                     psOptions->eAccessMode = ACCESS_APPEND;
    7692           4 :                     psOptions->bUpsert = true;
    7693        1068 :                 })
    7694             :             .help(_("Variant of -append where the UpsertFeature() operation is "
    7695        1068 :                     "used to insert or update features."));
    7696             : 
    7697        1068 :         group.add_argument("-overwrite")
    7698        1068 :             .flag()
    7699          18 :             .action([psOptions](const std::string &)
    7700        1068 :                     { psOptions->eAccessMode = ACCESS_OVERWRITE; })
    7701        1068 :             .help(_("Delete the output layer and recreate it empty."));
    7702             :     }
    7703             : 
    7704        1068 :     argParser->add_argument("-update")
    7705        1068 :         .flag()
    7706             :         .action(
    7707          22 :             [psOptions](const std::string &)
    7708             :             {
    7709             :                 /* Don't reset -append or -overwrite */
    7710           8 :                 if (psOptions->eAccessMode != ACCESS_APPEND &&
    7711           7 :                     psOptions->eAccessMode != ACCESS_OVERWRITE)
    7712           7 :                     psOptions->eAccessMode = ACCESS_UPDATE;
    7713        1068 :             })
    7714             :         .help(_("Open existing output datasource in update mode rather than "
    7715        1068 :                 "trying to create a new one."));
    7716             : 
    7717        1068 :     argParser->add_argument("-sql")
    7718        2136 :         .metavar("<statement>|@<filename>")
    7719             :         .action(
    7720          34 :             [psOptions](const std::string &s)
    7721             :             {
    7722          17 :                 GByte *pabyRet = nullptr;
    7723          20 :                 if (!s.empty() && s.front() == '@' &&
    7724           3 :                     VSIIngestFile(nullptr, s.c_str() + 1, &pabyRet, nullptr,
    7725             :                                   10 * 1024 * 1024))
    7726             :                 {
    7727           3 :                     GDALRemoveBOM(pabyRet);
    7728           3 :                     char *pszSQLStatement = reinterpret_cast<char *>(pabyRet);
    7729             :                     psOptions->osSQLStatement =
    7730           3 :                         CPLRemoveSQLComments(pszSQLStatement);
    7731           3 :                     VSIFree(pszSQLStatement);
    7732             :                 }
    7733             :                 else
    7734             :                 {
    7735          14 :                     psOptions->osSQLStatement = s;
    7736             :                 }
    7737        1085 :             })
    7738        1068 :         .help(_("SQL statement to execute."));
    7739             : 
    7740        1068 :     argParser->add_argument("-dialect")
    7741        2136 :         .metavar("<dialect>")
    7742        1068 :         .store_into(psOptions->osDialect)
    7743        1068 :         .help(_("SQL dialect."));
    7744             : 
    7745        1068 :     argParser->add_argument("-spat")
    7746        2136 :         .metavar("<xmin> <ymin> <xmax> <ymax>")
    7747        1068 :         .nargs(4)
    7748        1068 :         .scan<'g', double>()
    7749             :         .help(_("Spatial query extents, in the SRS of the source layer(s) (or "
    7750        1068 :                 "the one specified with -spat_srs."));
    7751             : 
    7752        1068 :     argParser->add_argument("-where")
    7753        2136 :         .metavar("<restricted_where>|@<filename>")
    7754             :         .action(
    7755          16 :             [psOptions](const std::string &s)
    7756             :             {
    7757           8 :                 GByte *pabyRet = nullptr;
    7758           9 :                 if (!s.empty() && s.front() == '@' &&
    7759           1 :                     VSIIngestFile(nullptr, s.c_str() + 1, &pabyRet, nullptr,
    7760             :                                   10 * 1024 * 1024))
    7761             :                 {
    7762           1 :                     GDALRemoveBOM(pabyRet);
    7763           1 :                     char *pszWHERE = reinterpret_cast<char *>(pabyRet);
    7764           1 :                     psOptions->osWHERE = pszWHERE;
    7765           1 :                     VSIFree(pszWHERE);
    7766             :                 }
    7767             :                 else
    7768             :                 {
    7769           7 :                     psOptions->osWHERE = s;
    7770             :                 }
    7771        1076 :             })
    7772        1068 :         .help(_("Attribute query (like SQL WHERE)."));
    7773             : 
    7774        1068 :     argParser->add_argument("-select")
    7775        2136 :         .metavar("<field_list>")
    7776             :         .action(
    7777          38 :             [psOptions](const std::string &s)
    7778             :             {
    7779          19 :                 psOptions->bSelFieldsSet = true;
    7780             :                 psOptions->aosSelFields =
    7781          19 :                     CSLTokenizeStringComplex(s.c_str(), ",", TRUE, FALSE);
    7782        1068 :             })
    7783             :         .help(_("Comma-delimited list of fields from input layer to copy to "
    7784        1068 :                 "the new layer."));
    7785             : 
    7786        1068 :     argParser->add_argument("-nln")
    7787        2136 :         .metavar("<name>")
    7788        1068 :         .store_into(psOptions->osNewLayerName)
    7789        1068 :         .help(_("Assign an alternate name to the new layer."));
    7790             : 
    7791        1068 :     argParser->add_argument("-nlt")
    7792        2136 :         .metavar("<type>")
    7793        1068 :         .append()
    7794             :         .action(
    7795         243 :             [psOptions](const std::string &osGeomNameIn)
    7796             :             {
    7797          53 :                 bool bIs3D = false;
    7798         106 :                 std::string osGeomName(osGeomNameIn);
    7799         106 :                 if (osGeomName.size() > 3 &&
    7800          53 :                     STARTS_WITH_CI(osGeomName.c_str() + osGeomName.size() - 3,
    7801             :                                    "25D"))
    7802             :                 {
    7803           1 :                     bIs3D = true;
    7804           1 :                     osGeomName.resize(osGeomName.size() - 3);
    7805             :                 }
    7806         104 :                 else if (osGeomName.size() > 1 &&
    7807          52 :                          STARTS_WITH_CI(
    7808             :                              osGeomName.c_str() + osGeomName.size() - 1, "Z"))
    7809             :                 {
    7810           0 :                     bIs3D = true;
    7811           0 :                     osGeomName.pop_back();
    7812             :                 }
    7813          53 :                 if (EQUAL(osGeomName.c_str(), "NONE"))
    7814             :                 {
    7815           1 :                     if (psOptions->eGType != GEOMTYPE_UNCHANGED)
    7816             :                     {
    7817             :                         throw std::invalid_argument(
    7818           0 :                             "Unsupported combination of -nlt arguments.");
    7819             :                     }
    7820           1 :                     psOptions->eGType = wkbNone;
    7821             :                 }
    7822          52 :                 else if (EQUAL(osGeomName.c_str(), "GEOMETRY"))
    7823             :                 {
    7824           4 :                     if (psOptions->eGType != GEOMTYPE_UNCHANGED)
    7825             :                     {
    7826             :                         throw std::invalid_argument(
    7827           0 :                             "Unsupported combination of -nlt arguments.");
    7828             :                     }
    7829           4 :                     psOptions->eGType = wkbUnknown;
    7830             :                 }
    7831          48 :                 else if (EQUAL(osGeomName.c_str(), "PROMOTE_TO_MULTI"))
    7832             :                 {
    7833           8 :                     if (psOptions->eGeomTypeConversion == GTC_CONVERT_TO_LINEAR)
    7834           2 :                         psOptions->eGeomTypeConversion =
    7835             :                             GTC_PROMOTE_TO_MULTI_AND_CONVERT_TO_LINEAR;
    7836           6 :                     else if (psOptions->eGeomTypeConversion == GTC_DEFAULT)
    7837           5 :                         psOptions->eGeomTypeConversion = GTC_PROMOTE_TO_MULTI;
    7838             :                     else
    7839             :                     {
    7840             :                         throw std::invalid_argument(
    7841           1 :                             "Unsupported combination of -nlt arguments.");
    7842             :                     }
    7843             :                 }
    7844          40 :                 else if (EQUAL(osGeomName.c_str(), "CONVERT_TO_LINEAR"))
    7845             :                 {
    7846          12 :                     if (psOptions->eGeomTypeConversion == GTC_PROMOTE_TO_MULTI)
    7847           2 :                         psOptions->eGeomTypeConversion =
    7848             :                             GTC_PROMOTE_TO_MULTI_AND_CONVERT_TO_LINEAR;
    7849          10 :                     else if (psOptions->eGeomTypeConversion == GTC_DEFAULT)
    7850           9 :                         psOptions->eGeomTypeConversion = GTC_CONVERT_TO_LINEAR;
    7851             :                     else
    7852             :                     {
    7853             :                         throw std::invalid_argument(
    7854           1 :                             "Unsupported combination of -nlt arguments.");
    7855             :                     }
    7856             :                 }
    7857          28 :                 else if (EQUAL(osGeomName.c_str(), "CONVERT_TO_CURVE"))
    7858             :                 {
    7859           7 :                     if (psOptions->eGeomTypeConversion == GTC_DEFAULT)
    7860           5 :                         psOptions->eGeomTypeConversion = GTC_CONVERT_TO_CURVE;
    7861             :                     else
    7862             :                     {
    7863             :                         throw std::invalid_argument(
    7864           2 :                             "Unsupported combination of -nlt arguments.");
    7865             :                     }
    7866             :                 }
    7867             :                 else
    7868             :                 {
    7869          21 :                     if (psOptions->eGType != GEOMTYPE_UNCHANGED)
    7870             :                     {
    7871             :                         throw std::invalid_argument(
    7872           3 :                             "Unsupported combination of -nlt arguments.");
    7873             :                     }
    7874          18 :                     psOptions->eGType = OGRFromOGCGeomType(osGeomName.c_str());
    7875          18 :                     if (psOptions->eGType == wkbUnknown)
    7876             :                     {
    7877             :                         throw std::invalid_argument(
    7878             :                             CPLSPrintf("-nlt %s: type not recognised.",
    7879           0 :                                        osGeomName.c_str()));
    7880             :                     }
    7881             :                 }
    7882          46 :                 if (psOptions->eGType != GEOMTYPE_UNCHANGED &&
    7883          27 :                     psOptions->eGType != wkbNone && bIs3D)
    7884           1 :                     psOptions->eGType = wkbSetZ(
    7885             :                         static_cast<OGRwkbGeometryType>(psOptions->eGType));
    7886        1114 :             })
    7887        1068 :         .help(_("Define the geometry type for the created layer."));
    7888             : 
    7889        1068 :     argParser->add_argument("-s_srs")
    7890        2136 :         .metavar("<srs_def>")
    7891        1068 :         .store_into(psOptions->osSourceSRSDef)
    7892        1068 :         .help(_("Set/override source SRS."));
    7893             : 
    7894             :     {
    7895        1068 :         auto &group = argParser->add_mutually_exclusive_group();
    7896        1068 :         group.add_argument("-a_srs")
    7897        2136 :             .metavar("<srs_def>")
    7898             :             .action(
    7899         353 :                 [psOptions](const std::string &osOutputSRSDef)
    7900             :                 {
    7901         115 :                     psOptions->osOutputSRSDef = osOutputSRSDef;
    7902         230 :                     if (EQUAL(psOptions->osOutputSRSDef.c_str(), "NULL") ||
    7903         115 :                         EQUAL(psOptions->osOutputSRSDef.c_str(), "NONE"))
    7904             :                     {
    7905           4 :                         psOptions->osOutputSRSDef.clear();
    7906           4 :                         psOptions->bNullifyOutputSRS = true;
    7907             :                     }
    7908        1068 :                 })
    7909        1068 :             .help(_("Assign an output SRS, but without reprojecting."));
    7910             : 
    7911        1068 :         group.add_argument("-t_srs")
    7912        2136 :             .metavar("<srs_def>")
    7913             :             .action(
    7914          72 :                 [psOptions](const std::string &osOutputSRSDef)
    7915             :                 {
    7916          36 :                     psOptions->osOutputSRSDef = osOutputSRSDef;
    7917          36 :                     psOptions->bTransform = true;
    7918        1068 :                 })
    7919             :             .help(_("Reproject/transform to this SRS on output, and assign it "
    7920        1068 :                     "as output SRS."));
    7921             :     }
    7922             : 
    7923             :     ///////////////////////////////////////////////////////////////////////
    7924        1068 :     argParser->add_group("Field related options");
    7925             : 
    7926        1068 :     argParser->add_argument("-addfields")
    7927        1068 :         .flag()
    7928             :         .action(
    7929           4 :             [psOptions](const std::string &)
    7930             :             {
    7931           4 :                 psOptions->bAddMissingFields = true;
    7932           4 :                 psOptions->eAccessMode = ACCESS_APPEND;
    7933        1068 :             })
    7934        1068 :         .help(_("Same as append, but add also any new fields."));
    7935             : 
    7936        1068 :     argParser->add_argument("-relaxedFieldNameMatch")
    7937        1068 :         .flag()
    7938           1 :         .action([psOptions](const std::string &)
    7939        1068 :                 { psOptions->bExactFieldNameMatch = false; })
    7940             :         .help(_("Do field name matching between source and existing target "
    7941        1068 :                 "layer in a more relaxed way."));
    7942             : 
    7943        1068 :     argParser->add_argument("-fieldTypeToString")
    7944        2136 :         .metavar("All|<type1>[,<type2>]...")
    7945             :         .action(
    7946           0 :             [psOptions](const std::string &s)
    7947             :             {
    7948             :                 psOptions->aosFieldTypesToString =
    7949           0 :                     CSLTokenizeStringComplex(s.c_str(), " ,", FALSE, FALSE);
    7950           0 :                 CSLConstList iter = psOptions->aosFieldTypesToString.List();
    7951           0 :                 while (*iter)
    7952             :                 {
    7953           0 :                     if (IsFieldType(*iter))
    7954             :                     {
    7955             :                         /* Do nothing */
    7956             :                     }
    7957           0 :                     else if (EQUAL(*iter, "All"))
    7958             :                     {
    7959           0 :                         psOptions->aosFieldTypesToString.Clear();
    7960           0 :                         psOptions->aosFieldTypesToString.AddString("All");
    7961           0 :                         break;
    7962             :                     }
    7963             :                     else
    7964             :                     {
    7965             :                         throw std::invalid_argument(CPLSPrintf(
    7966             :                             "Unhandled type for fieldTypeToString option : %s",
    7967           0 :                             *iter));
    7968             :                     }
    7969           0 :                     iter++;
    7970             :                 }
    7971        1068 :             })
    7972             :         .help(_("Converts any field of the specified type to a field of type "
    7973        1068 :                 "string in the destination layer."));
    7974             : 
    7975        1068 :     argParser->add_argument("-mapFieldType")
    7976        2136 :         .metavar("<srctype>|All=<dsttype>[,<srctype2>=<dsttype2>]...")
    7977             :         .action(
    7978          12 :             [psOptions](const std::string &s)
    7979             :             {
    7980             :                 psOptions->aosMapFieldType =
    7981           4 :                     CSLTokenizeStringComplex(s.c_str(), " ,", FALSE, FALSE);
    7982           4 :                 CSLConstList iter = psOptions->aosMapFieldType.List();
    7983           8 :                 while (*iter)
    7984             :                 {
    7985           4 :                     char *pszKey = nullptr;
    7986           4 :                     const char *pszValue = CPLParseNameValue(*iter, &pszKey);
    7987           4 :                     if (pszKey && pszValue)
    7988             :                     {
    7989           8 :                         if (!((IsFieldType(pszKey) || EQUAL(pszKey, "All")) &&
    7990           4 :                               IsFieldType(pszValue)))
    7991             :                         {
    7992           0 :                             CPLFree(pszKey);
    7993             :                             throw std::invalid_argument(CPLSPrintf(
    7994           0 :                                 "Invalid value for -mapFieldType : %s", *iter));
    7995             :                         }
    7996             :                     }
    7997           4 :                     CPLFree(pszKey);
    7998           4 :                     iter++;
    7999             :                 }
    8000        1072 :             })
    8001        1068 :         .help(_("Converts any field of the specified type to another type."));
    8002             : 
    8003        1068 :     argParser->add_argument("-fieldmap")
    8004        2136 :         .metavar("<field_1>[,<field_2>]...")
    8005             :         .action(
    8006           4 :             [psOptions](const std::string &s)
    8007             :             {
    8008             :                 psOptions->aosFieldMap =
    8009           2 :                     CSLTokenizeStringComplex(s.c_str(), ",", FALSE, FALSE);
    8010        1068 :             })
    8011             :         .help(_("Specifies the list of field indexes to be copied from the "
    8012        1068 :                 "source to the destination."));
    8013             : 
    8014        1068 :     argParser->add_argument("-splitlistfields")
    8015        1068 :         .store_into(psOptions->bSplitListFields)
    8016             :         .help(_("Split fields of type list type into as many fields of scalar "
    8017        1068 :                 "type as necessary."));
    8018             : 
    8019        1068 :     argParser->add_argument("-maxsubfields")
    8020        2136 :         .metavar("<n>")
    8021        1068 :         .scan<'i', int>()
    8022             :         .action(
    8023           0 :             [psOptions](const std::string &s)
    8024             :             {
    8025           0 :                 const int nVal = atoi(s.c_str());
    8026           0 :                 if (nVal > 0)
    8027             :                 {
    8028           0 :                     psOptions->nMaxSplitListSubFields = nVal;
    8029             :                 }
    8030        1068 :             })
    8031             :         .help(_("To be combined with -splitlistfields to limit the number of "
    8032        1068 :                 "subfields created for each split field."));
    8033             : 
    8034        1068 :     argParser->add_argument("-emptyStrAsNull")
    8035        1068 :         .store_into(psOptions->bEmptyStrAsNull)
    8036        1068 :         .help(_("Treat empty string values as null."));
    8037             : 
    8038        1068 :     argParser->add_argument("-forceNullable")
    8039        1068 :         .store_into(psOptions->bForceNullable)
    8040             :         .help(_("Do not propagate not-nullable constraints to target layer if "
    8041        1068 :                 "they exist in source layer."));
    8042             : 
    8043        1068 :     argParser->add_argument("-unsetFieldWidth")
    8044        1068 :         .store_into(psOptions->bUnsetFieldWidth)
    8045        1068 :         .help(_("Set field width and precision to 0."));
    8046             : 
    8047        1068 :     argParser->add_argument("-unsetDefault")
    8048        1068 :         .store_into(psOptions->bUnsetDefault)
    8049             :         .help(_("Do not propagate default field values to target layer if they "
    8050        1068 :                 "exist in source layer."));
    8051             : 
    8052        1068 :     argParser->add_argument("-resolveDomains")
    8053        1068 :         .store_into(psOptions->bResolveDomains)
    8054             :         .help(_("Cause any selected field that is linked to a coded field "
    8055        1068 :                 "domain will be accompanied by an additional field."));
    8056             : 
    8057        1068 :     argParser->add_argument("-dateTimeTo")
    8058        2136 :         .metavar("UTC|UTC(+|-)<HH>|UTC(+|-)<HH>:<MM>")
    8059             :         .action(
    8060          33 :             [psOptions](const std::string &s)
    8061             :             {
    8062          13 :                 const char *pszFormat = s.c_str();
    8063          13 :                 if (EQUAL(pszFormat, "UTC"))
    8064             :                 {
    8065           1 :                     psOptions->nTZOffsetInSec = 0;
    8066             :                 }
    8067          12 :                 else if (STARTS_WITH_CI(pszFormat, "UTC") &&
    8068          11 :                          (strlen(pszFormat) == strlen("UTC+HH") ||
    8069           9 :                           strlen(pszFormat) == strlen("UTC+HH:MM")) &&
    8070           7 :                          (pszFormat[3] == '+' || pszFormat[3] == '-'))
    8071             :                 {
    8072           6 :                     const int nHour = atoi(pszFormat + strlen("UTC+"));
    8073           6 :                     if (nHour < 0 || nHour > 14)
    8074             :                     {
    8075           1 :                         throw std::invalid_argument("Invalid UTC hour offset.");
    8076             :                     }
    8077           5 :                     else if (strlen(pszFormat) == strlen("UTC+HH"))
    8078             :                     {
    8079           0 :                         psOptions->nTZOffsetInSec = nHour * 3600;
    8080           0 :                         if (pszFormat[3] == '-')
    8081           0 :                             psOptions->nTZOffsetInSec =
    8082           0 :                                 -psOptions->nTZOffsetInSec;
    8083             :                     }
    8084             :                     else  // if( strlen(pszFormat) == strlen("UTC+HH:MM") )
    8085             :                     {
    8086           5 :                         const int nMin = atoi(pszFormat + strlen("UTC+HH:"));
    8087           5 :                         if (nMin == 0 || nMin == 15 || nMin == 30 || nMin == 45)
    8088             :                         {
    8089           4 :                             psOptions->nTZOffsetInSec =
    8090           4 :                                 nHour * 3600 + nMin * 60;
    8091           4 :                             if (pszFormat[3] == '-')
    8092           3 :                                 psOptions->nTZOffsetInSec =
    8093           3 :                                     -psOptions->nTZOffsetInSec;
    8094             :                         }
    8095             :                     }
    8096             :                 }
    8097          12 :                 if (psOptions->nTZOffsetInSec == TZ_OFFSET_INVALID)
    8098             :                 {
    8099             :                     throw std::invalid_argument(
    8100             :                         "Value of -dateTimeTo should be UTC, UTC(+|-)HH or "
    8101           7 :                         "UTC(+|-)HH:MM with HH in [0,14] and MM=00,15,30,45");
    8102             :                 }
    8103        1073 :             })
    8104             :         .help(_("Converts date time values from the timezone specified in the "
    8105        1068 :                 "source value to the target timezone."));
    8106             : 
    8107        1068 :     argParser->add_argument("-noNativeData")
    8108        1068 :         .flag()
    8109           1 :         .action([psOptions](const std::string &)
    8110        1068 :                 { psOptions->bNativeData = false; })
    8111        1068 :         .help(_("Disable copying of native data."));
    8112             : 
    8113             :     ///////////////////////////////////////////////////////////////////////
    8114        1068 :     argParser->add_group("Advanced geometry and SRS related options");
    8115             : 
    8116        1068 :     argParser->add_argument("-dim")
    8117        2136 :         .metavar("layer_dim|2|XY|3|XYZ|XYM|XYZM")
    8118             :         .action(
    8119          24 :             [psOptions](const std::string &osDim)
    8120             :             {
    8121          12 :                 if (EQUAL(osDim.c_str(), "layer_dim"))
    8122           2 :                     psOptions->nCoordDim = COORD_DIM_LAYER_DIM;
    8123          18 :                 else if (EQUAL(osDim.c_str(), "XY") ||
    8124           8 :                          EQUAL(osDim.c_str(), "2"))
    8125           3 :                     psOptions->nCoordDim = 2;
    8126          12 :                 else if (EQUAL(osDim.c_str(), "XYZ") ||
    8127           5 :                          EQUAL(osDim.c_str(), "3"))
    8128           3 :                     psOptions->nCoordDim = 3;
    8129           4 :                 else if (EQUAL(osDim.c_str(), "XYM"))
    8130           2 :                     psOptions->nCoordDim = COORD_DIM_XYM;
    8131           2 :                 else if (EQUAL(osDim.c_str(), "XYZM"))
    8132           2 :                     psOptions->nCoordDim = 4;
    8133             :                 else
    8134             :                 {
    8135             :                     throw std::invalid_argument(CPLSPrintf(
    8136           0 :                         "-dim %s: value not handled.", osDim.c_str()));
    8137             :                 }
    8138        1080 :             })
    8139        1068 :         .help(_("Force the coordinate dimension."));
    8140             : 
    8141        1068 :     argParser->add_argument("-s_coord_epoch")
    8142        2136 :         .metavar("<epoch>")
    8143        1068 :         .store_into(psOptions->dfSourceCoordinateEpoch)
    8144        1068 :         .help(_("Assign a coordinate epoch, linked with the source SRS."));
    8145             : 
    8146        1068 :     argParser->add_argument("-a_coord_epoch")
    8147        2136 :         .metavar("<epoch>")
    8148        1068 :         .store_into(psOptions->dfOutputCoordinateEpoch)
    8149             :         .help(_("Assign a coordinate epoch, linked with the output SRS when "
    8150        1068 :                 "-a_srs is used."));
    8151             : 
    8152        1068 :     argParser->add_argument("-t_coord_epoch")
    8153        2136 :         .metavar("<epoch>")
    8154        1068 :         .store_into(psOptions->dfOutputCoordinateEpoch)
    8155             :         .help(_("Assign a coordinate epoch, linked with the output SRS when "
    8156        1068 :                 "-t_srs is used."));
    8157             : 
    8158        1068 :     argParser->add_argument("-ct")
    8159        2136 :         .metavar("<pipeline_def>")
    8160             :         .action(
    8161           8 :             [psOptions](const std::string &s)
    8162             :             {
    8163           4 :                 psOptions->osCTPipeline = s;
    8164           4 :                 psOptions->bTransform = true;
    8165        1068 :             })
    8166             :         .help(_("Override the default transformation from the source to the "
    8167        1068 :                 "target CRS."));
    8168             : 
    8169        1068 :     argParser->add_argument("-ct_opt")
    8170        2136 :         .metavar("<NAME>=<VALUE>")
    8171        1068 :         .append()
    8172           0 :         .action([psOptions](const std::string &s)
    8173        1068 :                 { psOptions->aosCTOptions.AddString(s.c_str()); })
    8174        1068 :         .help(_("Coordinate transform option(s)."));
    8175             : 
    8176        1068 :     argParser->add_argument("-spat_srs")
    8177        2136 :         .metavar("<srs_def>")
    8178        1068 :         .store_into(psOptions->osSpatSRSDef)
    8179        1068 :         .help(_("Override spatial filter SRS."));
    8180             : 
    8181        1068 :     argParser->add_argument("-geomfield")
    8182        2136 :         .metavar("<name>")
    8183             :         .action(
    8184           2 :             [psOptions](const std::string &s)
    8185             :             {
    8186           1 :                 psOptions->osGeomField = s;
    8187           1 :                 psOptions->bGeomFieldSet = true;
    8188        1068 :             })
    8189             :         .help(_("Name of the geometry field on which the spatial filter "
    8190        1068 :                 "operates on."));
    8191             : 
    8192        1068 :     argParser->add_argument("-segmentize")
    8193        2136 :         .metavar("<max_dist>")
    8194        1068 :         .store_into(psOptions->dfGeomOpParam)
    8195           2 :         .action([psOptions](const std::string &)
    8196        1068 :                 { psOptions->eGeomOp = GEOMOP_SEGMENTIZE; })
    8197        1068 :         .help(_("Maximum distance between 2 nodes."));
    8198             : 
    8199        1068 :     argParser->add_argument("-simplify")
    8200        2136 :         .metavar("<tolerance>")
    8201        1068 :         .store_into(psOptions->dfGeomOpParam)
    8202           1 :         .action([psOptions](const std::string &)
    8203        1068 :                 { psOptions->eGeomOp = GEOMOP_SIMPLIFY_PRESERVE_TOPOLOGY; })
    8204        1068 :         .help(_("Distance tolerance for simplification."));
    8205             : 
    8206        1068 :     argParser->add_argument("-makevalid")
    8207        1068 :         .flag()
    8208             :         .action(
    8209          10 :             [psOptions](const std::string &)
    8210             :             {
    8211           5 :                 if (!OGRGeometryFactory::haveGEOS())
    8212             :                 {
    8213             :                     throw std::invalid_argument(
    8214           0 :                         "-makevalid only supported for builds against GEOS");
    8215             :                 }
    8216           5 :                 psOptions->bMakeValid = true;
    8217        1073 :             })
    8218             :         .help(_("Fix geometries to be valid regarding the rules of the Simple "
    8219        1068 :                 "Features specification."));
    8220             : 
    8221        1068 :     argParser->add_argument("-skipinvalid")
    8222        1068 :         .flag()
    8223             :         .action(
    8224           2 :             [psOptions](const std::string &)
    8225             :             {
    8226           1 :                 if (!OGRGeometryFactory::haveGEOS())
    8227             :                 {
    8228             :                     throw std::invalid_argument(
    8229           0 :                         "-skipinvalid only supported for builds against GEOS");
    8230             :                 }
    8231           1 :                 psOptions->bSkipInvalidGeom = true;
    8232        1069 :             })
    8233             :         .help(_("Whether to skip features with invalid geometries regarding the"
    8234        1068 :                 "rules of the Simple Features specification."));
    8235             : 
    8236        1068 :     argParser->add_argument("-wrapdateline")
    8237        1068 :         .store_into(psOptions->bWrapDateline)
    8238        1068 :         .help(_("Split geometries crossing the dateline meridian."));
    8239             : 
    8240        1068 :     argParser->add_argument("-datelineoffset")
    8241        2136 :         .metavar("<val_in_degree>")
    8242        1068 :         .default_value(psOptions->dfDateLineOffset)
    8243        1068 :         .store_into(psOptions->dfDateLineOffset)
    8244        1068 :         .help(_("Offset from dateline in degrees."));
    8245             : 
    8246             :     auto &clipsrcArg =
    8247        1068 :         argParser->add_argument("-clipsrc")
    8248             :             .metavar(
    8249        2136 :                 "[<xmin> <ymin> <xmax> <ymax>]|<WKT>|<datasource>|spat_extent")
    8250        1068 :             .help(_("Clip geometries (in source SRS)."));
    8251        1068 :     if (nCountClipSrc > 1)
    8252           1 :         clipsrcArg.nargs(nCountClipSrc);
    8253             : 
    8254        1068 :     argParser->add_argument("-clipsrcsql")
    8255        2136 :         .metavar("<sql_statement>")
    8256        1068 :         .store_into(psOptions->osClipSrcSQL)
    8257             :         .help(_("Select desired geometries from the source clip datasource "
    8258        1068 :                 "using an SQL query."));
    8259             : 
    8260        1068 :     argParser->add_argument("-clipsrclayer")
    8261        2136 :         .metavar("<layername>")
    8262        1068 :         .store_into(psOptions->osClipSrcLayer)
    8263        1068 :         .help(_("Select the named layer from the source clip datasource."));
    8264             : 
    8265        1068 :     argParser->add_argument("-clipsrcwhere")
    8266        2136 :         .metavar("<expression>")
    8267        1068 :         .store_into(psOptions->osClipSrcWhere)
    8268             :         .help(_("Restrict desired geometries from the source clip layer based "
    8269        1068 :                 "on an attribute query."));
    8270             : 
    8271             :     auto &clipdstArg =
    8272        1068 :         argParser->add_argument("-clipdst")
    8273        2136 :             .metavar("[<xmin> <ymin> <xmax> <ymax>]|<WKT>|<datasource>")
    8274        1068 :             .help(_("Clip geometries (in target SRS)."));
    8275        1068 :     if (nCountClipDst > 1)
    8276           2 :         clipdstArg.nargs(nCountClipDst);
    8277             : 
    8278        1068 :     argParser->add_argument("-clipdstsql")
    8279        2136 :         .metavar("<sql_statement>")
    8280        1068 :         .store_into(psOptions->osClipDstSQL)
    8281             :         .help(_("Select desired geometries from the destination clip "
    8282        1068 :                 "datasource using an SQL query."));
    8283             : 
    8284        1068 :     argParser->add_argument("-clipdstlayer")
    8285        2136 :         .metavar("<layername>")
    8286        1068 :         .store_into(psOptions->osClipDstLayer)
    8287             :         .help(
    8288        1068 :             _("Select the named layer from the destination clip datasource."));
    8289             : 
    8290        1068 :     argParser->add_argument("-clipdstwhere")
    8291        2136 :         .metavar("<expression>")
    8292        1068 :         .store_into(psOptions->osClipDstWhere)
    8293             :         .help(_("Restrict desired geometries from the destination clip layer "
    8294        1068 :                 "based on an attribute query."));
    8295             : 
    8296        1068 :     argParser->add_argument("-explodecollections")
    8297        1068 :         .store_into(psOptions->bExplodeCollections)
    8298             :         .help(_("Produce one feature for each geometry in any kind of geometry "
    8299        1068 :                 "collection in the source file."));
    8300             : 
    8301        1068 :     argParser->add_argument("-zfield")
    8302        2136 :         .metavar("<name>")
    8303        1068 :         .store_into(psOptions->osZField)
    8304             :         .help(_("Uses the specified field to fill the Z coordinate of "
    8305        1068 :                 "geometries."));
    8306             : 
    8307        1068 :     argParser->add_argument("-gcp")
    8308             :         .metavar(
    8309        2136 :             "<ungeoref_x> <ungeoref_y> <georef_x> <georef_y> [<elevation>]")
    8310        1068 :         .nargs(4, 5)
    8311        1068 :         .append()
    8312        1068 :         .scan<'g', double>()
    8313        1068 :         .help(_("Add the indicated ground control point."));
    8314             : 
    8315        1068 :     argParser->add_argument("-tps")
    8316        1068 :         .flag()
    8317           1 :         .action([psOptions](const std::string &)
    8318        1068 :                 { psOptions->nTransformOrder = -1; })
    8319             :         .help(_("Force use of thin plate spline transformer based on available "
    8320        1068 :                 "GCPs."));
    8321             : 
    8322        1068 :     argParser->add_argument("-order")
    8323        2136 :         .metavar("1|2|3")
    8324        1068 :         .store_into(psOptions->nTransformOrder)
    8325        1068 :         .help(_("Order of polynomial used for warping."));
    8326             : 
    8327        1068 :     argParser->add_argument("-xyRes")
    8328        2136 :         .metavar("<val>[ m|mm|deg]")
    8329             :         .action(
    8330          25 :             [psOptions](const std::string &s)
    8331             :             {
    8332           9 :                 const char *pszVal = s.c_str();
    8333             : 
    8334           9 :                 char *endptr = nullptr;
    8335           9 :                 psOptions->dfXYRes = CPLStrtodM(pszVal, &endptr);
    8336           9 :                 if (!endptr)
    8337             :                 {
    8338             :                     throw std::invalid_argument(
    8339             :                         "Invalid value for -xyRes. Must be of the form "
    8340           0 :                         "{numeric_value}[ ]?[m|mm|deg]?");
    8341             :                 }
    8342           9 :                 if (*endptr == ' ')
    8343           6 :                     ++endptr;
    8344           9 :                 if (*endptr != 0 && strcmp(endptr, "m") != 0 &&
    8345           5 :                     strcmp(endptr, "mm") != 0 && strcmp(endptr, "deg") != 0)
    8346             :                 {
    8347             :                     throw std::invalid_argument(
    8348             :                         "Invalid value for -xyRes. Must be of the form "
    8349           2 :                         "{numeric_value}[ ]?[m|mm|deg]?");
    8350             :                 }
    8351           7 :                 psOptions->osXYResUnit = endptr;
    8352        1075 :             })
    8353        1068 :         .help(_("Set/override the geometry X/Y coordinate resolution."));
    8354             : 
    8355        1068 :     argParser->add_argument("-zRes")
    8356        2136 :         .metavar("<val>[ m|mm]")
    8357             :         .action(
    8358          16 :             [psOptions](const std::string &s)
    8359             :             {
    8360           6 :                 const char *pszVal = s.c_str();
    8361             : 
    8362           6 :                 char *endptr = nullptr;
    8363           6 :                 psOptions->dfZRes = CPLStrtodM(pszVal, &endptr);
    8364           6 :                 if (!endptr)
    8365             :                 {
    8366             :                     throw std::invalid_argument(
    8367             :                         "Invalid value for -zRes. Must be of the form "
    8368           0 :                         "{numeric_value}[ ]?[m|mm]?");
    8369             :                 }
    8370           6 :                 if (*endptr == ' ')
    8371           4 :                     ++endptr;
    8372           6 :                 if (*endptr != 0 && strcmp(endptr, "m") != 0 &&
    8373           3 :                     strcmp(endptr, "mm") != 0 && strcmp(endptr, "deg") != 0)
    8374             :                 {
    8375             :                     throw std::invalid_argument(
    8376             :                         "Invalid value for -zRes. Must be of the form "
    8377           2 :                         "{numeric_value}[ ]?[m|mm]?");
    8378             :                 }
    8379           4 :                 psOptions->osZResUnit = endptr;
    8380        1072 :             })
    8381        1068 :         .help(_("Set/override the geometry Z coordinate resolution."));
    8382             : 
    8383        1068 :     argParser->add_argument("-mRes")
    8384        2136 :         .metavar("<val>")
    8385        1068 :         .store_into(psOptions->dfMRes)
    8386        1068 :         .help(_("Set/override the geometry M coordinate resolution."));
    8387             : 
    8388        1068 :     argParser->add_argument("-unsetCoordPrecision")
    8389        1068 :         .store_into(psOptions->bUnsetCoordPrecision)
    8390             :         .help(_("Prevent the geometry coordinate resolution from being set on "
    8391        1068 :                 "target layer(s)."));
    8392             : 
    8393             :     ///////////////////////////////////////////////////////////////////////
    8394        1068 :     argParser->add_group("Other options");
    8395             : 
    8396        1068 :     argParser->add_quiet_argument(&psOptions->bQuiet);
    8397             : 
    8398        1068 :     argParser->add_argument("-progress")
    8399        1068 :         .store_into(psOptions->bDisplayProgress)
    8400             :         .help(_("Display progress on terminal. Only works if input layers have "
    8401        1068 :                 "the 'fast feature count' capability."));
    8402             : 
    8403             :     argParser->add_input_format_argument(
    8404             :         psOptionsForBinary ? &psOptionsForBinary->aosAllowInputDrivers
    8405        1068 :                            : nullptr);
    8406             : 
    8407             :     argParser->add_open_options_argument(
    8408        1068 :         psOptionsForBinary ? &(psOptionsForBinary->aosOpenOptions) : nullptr);
    8409             : 
    8410        1068 :     argParser->add_argument("-doo")
    8411        2136 :         .metavar("<NAME>=<VALUE>")
    8412        1068 :         .append()
    8413           0 :         .action([psOptions](const std::string &s)
    8414        1068 :                 { psOptions->aosDestOpenOptions.AddString(s.c_str()); })
    8415        1068 :         .help(_("Open option(s) for output dataset."));
    8416             : 
    8417        1068 :     argParser->add_usage_newline();
    8418             : 
    8419        1068 :     argParser->add_argument("-fid")
    8420        2136 :         .metavar("<FID>")
    8421        1068 :         .store_into(psOptions->nFIDToFetch)
    8422             :         .help(_("If provided, only the feature with the specified feature id "
    8423        1068 :                 "will be processed."));
    8424             : 
    8425        1068 :     argParser->add_argument("-preserve_fid")
    8426        1068 :         .store_into(psOptions->bPreserveFID)
    8427             :         .help(_("Use the FID of the source features instead of letting the "
    8428        1068 :                 "output driver automatically assign a new one."));
    8429             : 
    8430        1068 :     argParser->add_argument("-unsetFid")
    8431        1068 :         .store_into(psOptions->bUnsetFid)
    8432             :         .help(_("Prevent the name of the source FID column and source feature "
    8433        1068 :                 "IDs from being reused."));
    8434             : 
    8435             :     {
    8436        1068 :         auto &group = argParser->add_mutually_exclusive_group();
    8437        1068 :         group.add_argument("-skip", "-skipfailures")
    8438        1068 :             .flag()
    8439             :             .action(
    8440          12 :                 [psOptions](const std::string &)
    8441             :                 {
    8442          12 :                     psOptions->bSkipFailures = true;
    8443          12 :                     psOptions->nGroupTransactions = 1; /* #2409 */
    8444        1068 :                 })
    8445        1068 :             .help(_("Continue after a failure, skipping the failed feature."));
    8446             : 
    8447        1068 :         auto &arg = group.add_argument("-gt")
    8448        2136 :                         .metavar("<n>|unlimited")
    8449             :                         .action(
    8450           8 :                             [psOptions](const std::string &s)
    8451             :                             {
    8452             :                                 /* If skipfailures is already set we should not
    8453             :                modify nGroupTransactions = 1  #2409 */
    8454           4 :                                 if (!psOptions->bSkipFailures)
    8455             :                                 {
    8456           4 :                                     if (EQUAL(s.c_str(), "unlimited"))
    8457           1 :                                         psOptions->nGroupTransactions = -1;
    8458             :                                     else
    8459           3 :                                         psOptions->nGroupTransactions =
    8460           3 :                                             atoi(s.c_str());
    8461             :                                 }
    8462        1068 :                             })
    8463        1068 :                         .help(_("Group <n> features per transaction "));
    8464             : 
    8465        1068 :         argParser->add_hidden_alias_for(arg, "tg");
    8466             :     }
    8467             : 
    8468        1068 :     argParser->add_argument("-limit")
    8469        2136 :         .metavar("<nb_features>")
    8470        1068 :         .store_into(psOptions->nLimit)
    8471        1068 :         .help(_("Limit the number of features per layer."));
    8472             : 
    8473        1068 :     argParser->add_argument("-ds_transaction")
    8474        1068 :         .flag()
    8475             :         .action(
    8476           1 :             [psOptions](const std::string &)
    8477             :             {
    8478           1 :                 psOptions->nLayerTransaction = FALSE;
    8479           1 :                 psOptions->bForceTransaction = true;
    8480        1068 :             })
    8481        1068 :         .help(_("Force the use of a dataset level transaction."));
    8482             : 
    8483             :     /* Undocumented. Just a provision. Default behavior should be OK */
    8484        1068 :     argParser->add_argument("-lyr_transaction")
    8485        1068 :         .flag()
    8486        1068 :         .hidden()
    8487           0 :         .action([psOptions](const std::string &)
    8488        1068 :                 { psOptions->nLayerTransaction = TRUE; })
    8489        1068 :         .help(_("Force the use of a layer level transaction."));
    8490             : 
    8491             :     argParser->add_metadata_item_options_argument(
    8492        1068 :         psOptions->aosMetadataOptions);
    8493             : 
    8494        1068 :     argParser->add_argument("-nomd")
    8495        1068 :         .flag()
    8496           4 :         .action([psOptions](const std::string &)
    8497        1068 :                 { psOptions->bCopyMD = false; })
    8498             :         .help(_("Disable copying of metadata from source dataset and layers "
    8499        1068 :                 "into target dataset and layers."));
    8500             : 
    8501             :     // Undocumented option used by gdal vector convert
    8502        1068 :     argParser->add_argument("--no-overwrite")
    8503        1068 :         .store_into(psOptions->bNoOverwrite)
    8504        1068 :         .hidden();
    8505             : 
    8506             :     // Undocumented option used by gdal vector * algorithms
    8507        1068 :     argParser->add_argument("--invoked-from-gdal-algorithm")
    8508        1068 :         .store_into(psOptions->bInvokedFromGdalAlgorithm)
    8509        1068 :         .hidden();
    8510             : 
    8511        1068 :     if (psOptionsForBinary)
    8512             :     {
    8513         133 :         argParser->add_argument("dst_dataset_name")
    8514         266 :             .metavar("<dst_dataset_name>")
    8515         133 :             .store_into(psOptionsForBinary->osDestDataSource)
    8516         133 :             .help(_("Output dataset."));
    8517             : 
    8518         133 :         argParser->add_argument("src_dataset_name")
    8519         266 :             .metavar("<src_dataset_name>")
    8520         133 :             .store_into(psOptionsForBinary->osDataSource)
    8521         133 :             .help(_("Input dataset."));
    8522             :     }
    8523             : 
    8524        1068 :     argParser->add_argument("layer")
    8525        1068 :         .remaining()
    8526        2136 :         .metavar("<layer_name>")
    8527        1068 :         .help(_("Layer name"));
    8528        1068 :     return argParser;
    8529             : }
    8530             : 
    8531             : /************************************************************************/
    8532             : /*                 GDALVectorTranslateGetParserUsage()                  */
    8533             : /************************************************************************/
    8534             : 
    8535           1 : std::string GDALVectorTranslateGetParserUsage()
    8536             : {
    8537             :     try
    8538             :     {
    8539           2 :         GDALVectorTranslateOptions sOptions;
    8540           2 :         GDALVectorTranslateOptionsForBinary sOptionsForBinary;
    8541             :         auto argParser = GDALVectorTranslateOptionsGetParser(
    8542           2 :             &sOptions, &sOptionsForBinary, 1, 1);
    8543           1 :         return argParser->usage();
    8544             :     }
    8545           0 :     catch (const std::exception &err)
    8546             :     {
    8547           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unexpected exception: %s",
    8548           0 :                  err.what());
    8549           0 :         return std::string();
    8550             :     }
    8551             : }
    8552             : 
    8553             : /************************************************************************/
    8554             : /*                  CHECK_HAS_ENOUGH_ADDITIONAL_ARGS()                  */
    8555             : /************************************************************************/
    8556             : 
    8557             : #ifndef CheckHasEnoughAdditionalArgs_defined
    8558             : #define CheckHasEnoughAdditionalArgs_defined
    8559             : 
    8560          57 : static bool CheckHasEnoughAdditionalArgs(CSLConstList papszArgv, int i,
    8561             :                                          int nExtraArg, int nArgc)
    8562             : {
    8563          57 :     if (i + nExtraArg >= nArgc)
    8564             :     {
    8565           2 :         CPLError(CE_Failure, CPLE_IllegalArg,
    8566           2 :                  "%s option requires %d argument%s", papszArgv[i], nExtraArg,
    8567             :                  nExtraArg == 1 ? "" : "s");
    8568           2 :         return false;
    8569             :     }
    8570          55 :     return true;
    8571             : }
    8572             : #endif
    8573             : 
    8574             : #define CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(nExtraArg)                            \
    8575             :     if (!CheckHasEnoughAdditionalArgs(papszArgv, i, nExtraArg, nArgc))         \
    8576             :     {                                                                          \
    8577             :         return nullptr;                                                        \
    8578             :     }
    8579             : 
    8580             : /************************************************************************/
    8581             : /*                   GDALVectorTranslateOptionsNew()                    */
    8582             : /************************************************************************/
    8583             : 
    8584             : /**
    8585             :  * allocates a GDALVectorTranslateOptions struct.
    8586             :  *
    8587             :  * @param papszArgv NULL terminated list of options (potentially including
    8588             :  * filename and open options too), or NULL. The accepted options are the ones of
    8589             :  * the <a href="/programs/ogr2ogr.html">ogr2ogr</a> utility.
    8590             :  * @param psOptionsForBinary (output) may be NULL (and should generally be
    8591             :  * NULL), otherwise (gdal_translate_bin.cpp use case) must be allocated with
    8592             :  *                           GDALVectorTranslateOptionsForBinaryNew() prior to
    8593             :  * this function. Will be filled with potentially present filename, open
    8594             :  * options,...
    8595             :  * @return pointer to the allocated GDALVectorTranslateOptions struct. Must be
    8596             :  * freed with GDALVectorTranslateOptionsFree().
    8597             :  *
    8598             :  * @since GDAL 2.1
    8599             :  */
    8600        1071 : GDALVectorTranslateOptions *GDALVectorTranslateOptionsNew(
    8601             :     char **papszArgv, GDALVectorTranslateOptionsForBinary *psOptionsForBinary)
    8602             : {
    8603        2142 :     auto psOptions = std::make_unique<GDALVectorTranslateOptions>();
    8604             : 
    8605             :     /* -------------------------------------------------------------------- */
    8606             :     /*      Pre-processing for custom syntax that ArgumentParser does not   */
    8607             :     /*      support.                                                        */
    8608             :     /* -------------------------------------------------------------------- */
    8609             : 
    8610        2142 :     CPLStringList aosArgv;
    8611        1071 :     const int nArgc = CSLCount(papszArgv);
    8612        1071 :     int nCountClipSrc = 0;
    8613        1071 :     int nCountClipDst = 0;
    8614        4920 :     for (int i = 0;
    8615        4920 :          i < nArgc && papszArgv != nullptr && papszArgv[i] != nullptr; i++)
    8616             :     {
    8617        3853 :         if (EQUAL(papszArgv[i], "-gcp"))
    8618             :         {
    8619             :             // repeated argument of varying size: not handled by argparse.
    8620             : 
    8621          18 :             CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(4);
    8622          18 :             char *endptr = nullptr;
    8623             :             /* -gcp pixel line easting northing [elev] */
    8624             : 
    8625          18 :             psOptions->asGCPs.resize(psOptions->asGCPs.size() + 1);
    8626          18 :             auto &sGCP = psOptions->asGCPs.back();
    8627             : 
    8628          18 :             sGCP.Pixel() = CPLAtof(papszArgv[++i]);
    8629          18 :             sGCP.Line() = CPLAtof(papszArgv[++i]);
    8630          18 :             sGCP.X() = CPLAtof(papszArgv[++i]);
    8631          18 :             sGCP.Y() = CPLAtof(papszArgv[++i]);
    8632          33 :             if (papszArgv[i + 1] != nullptr &&
    8633          15 :                 (CPLStrtod(papszArgv[i + 1], &endptr) != 0.0 ||
    8634          15 :                  papszArgv[i + 1][0] == '0'))
    8635             :             {
    8636             :                 /* Check that last argument is really a number and not a
    8637             :                  * filename */
    8638             :                 /* looking like a number (see ticket #863) */
    8639           0 :                 if (endptr && *endptr == 0)
    8640           0 :                     sGCP.Z() = CPLAtof(papszArgv[++i]);
    8641             :             }
    8642             : 
    8643             :             /* should set id and info? */
    8644             :         }
    8645             : 
    8646        3835 :         else if (EQUAL(papszArgv[i], "-clipsrc"))
    8647             :         {
    8648          23 :             if (nCountClipSrc)
    8649             :             {
    8650           1 :                 CPLError(CE_Failure, CPLE_AppDefined, "Duplicate argument %s",
    8651           1 :                          papszArgv[i]);
    8652           1 :                 return nullptr;
    8653             :             }
    8654             :             // argparse doesn't handle well variable number of values
    8655             :             // just before the positional arguments, so we have to detect
    8656             :             // it manually and set the correct number.
    8657          22 :             nCountClipSrc = 1;
    8658          22 :             CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
    8659          24 :             if (CPLGetValueType(papszArgv[i + 1]) != CPL_VALUE_STRING &&
    8660           3 :                 i + 4 < nArgc)
    8661             :             {
    8662           2 :                 nCountClipSrc = 4;
    8663             :             }
    8664             : 
    8665          69 :             for (int j = 0; j < 1 + nCountClipSrc; ++j)
    8666             :             {
    8667          48 :                 aosArgv.AddString(papszArgv[i]);
    8668          48 :                 ++i;
    8669             :             }
    8670          21 :             --i;
    8671             :         }
    8672             : 
    8673        3812 :         else if (EQUAL(papszArgv[i], "-clipdst"))
    8674             :         {
    8675          18 :             if (nCountClipDst)
    8676             :             {
    8677           1 :                 CPLError(CE_Failure, CPLE_AppDefined, "Duplicate argument %s",
    8678           1 :                          papszArgv[i]);
    8679           1 :                 return nullptr;
    8680             :             }
    8681             :             // argparse doesn't handle well variable number of values
    8682             :             // just before the positional arguments, so we have to detect
    8683             :             // it manually and set the correct number.
    8684          17 :             nCountClipDst = 1;
    8685          17 :             CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
    8686          20 :             if (CPLGetValueType(papszArgv[i + 1]) != CPL_VALUE_STRING &&
    8687           4 :                 i + 4 < nArgc)
    8688             :             {
    8689           3 :                 nCountClipDst = 4;
    8690             :             }
    8691             : 
    8692          57 :             for (int j = 0; j < 1 + nCountClipDst; ++j)
    8693             :             {
    8694          41 :                 aosArgv.AddString(papszArgv[i]);
    8695          41 :                 ++i;
    8696             :             }
    8697          16 :             --i;
    8698             :         }
    8699             : 
    8700             :         else
    8701             :         {
    8702        3794 :             aosArgv.AddString(papszArgv[i]);
    8703             :         }
    8704             :     }
    8705             : 
    8706             :     try
    8707             :     {
    8708             :         auto argParser = GDALVectorTranslateOptionsGetParser(
    8709        2134 :             psOptions.get(), psOptionsForBinary, nCountClipSrc, nCountClipDst);
    8710             : 
    8711             :         // Collect non-positional arguments for VectorTranslateFrom() case
    8712        1066 :         psOptions->aosArguments =
    8713        2133 :             argParser->get_non_positional_arguments(aosArgv);
    8714             : 
    8715        1066 :         argParser->parse_args_without_binary_name(aosArgv.List());
    8716             : 
    8717        1043 :         if (psOptionsForBinary)
    8718         131 :             psOptionsForBinary->bQuiet = psOptions->bQuiet;
    8719             : 
    8720        1051 :         if (auto oSpat = argParser->present<std::vector<double>>("-spat"))
    8721             :         {
    8722           8 :             const double dfMinX = (*oSpat)[0];
    8723           8 :             const double dfMinY = (*oSpat)[1];
    8724           8 :             const double dfMaxX = (*oSpat)[2];
    8725           8 :             const double dfMaxY = (*oSpat)[3];
    8726             : 
    8727             :             auto poSpatialFilter =
    8728          16 :                 std::make_shared<OGRPolygon>(dfMinX, dfMinY, dfMaxX, dfMaxY);
    8729           8 :             psOptions->poSpatialFilter = poSpatialFilter;
    8730             :         }
    8731             : 
    8732        1043 :         if (auto oClipSrc =
    8733        1043 :                 argParser->present<std::vector<std::string>>("-clipsrc"))
    8734             :         {
    8735          20 :             const std::string &osVal = (*oClipSrc)[0];
    8736             : 
    8737          20 :             psOptions->poClipSrc.reset();
    8738          20 :             psOptions->osClipSrcDS.clear();
    8739             : 
    8740             :             VSIStatBufL sStat;
    8741          20 :             psOptions->bClipSrc = true;
    8742          20 :             if (oClipSrc->size() == 4)
    8743             :             {
    8744           1 :                 const double dfMinX = CPLAtofM((*oClipSrc)[0].c_str());
    8745           1 :                 const double dfMinY = CPLAtofM((*oClipSrc)[1].c_str());
    8746           1 :                 const double dfMaxX = CPLAtofM((*oClipSrc)[2].c_str());
    8747           1 :                 const double dfMaxY = CPLAtofM((*oClipSrc)[3].c_str());
    8748             : 
    8749           2 :                 OGRLinearRing oRing;
    8750             : 
    8751           1 :                 oRing.addPoint(dfMinX, dfMinY);
    8752           1 :                 oRing.addPoint(dfMinX, dfMaxY);
    8753           1 :                 oRing.addPoint(dfMaxX, dfMaxY);
    8754           1 :                 oRing.addPoint(dfMaxX, dfMinY);
    8755           1 :                 oRing.addPoint(dfMinX, dfMinY);
    8756             : 
    8757           2 :                 auto poPoly = std::make_shared<OGRPolygon>();
    8758           1 :                 psOptions->poClipSrc = poPoly;
    8759           1 :                 poPoly->addRing(&oRing);
    8760             :             }
    8761          19 :             else if ((STARTS_WITH_CI(osVal.c_str(), "POLYGON") ||
    8762          27 :                       STARTS_WITH_CI(osVal.c_str(), "MULTIPOLYGON")) &&
    8763           8 :                      VSIStatL(osVal.c_str(), &sStat) != 0)
    8764             :             {
    8765           8 :                 psOptions->poClipSrc =
    8766          16 :                     OGRGeometryFactory::createFromWkt(osVal.c_str()).first;
    8767           8 :                 if (psOptions->poClipSrc == nullptr)
    8768             :                 {
    8769           0 :                     CPLError(
    8770             :                         CE_Failure, CPLE_IllegalArg,
    8771             :                         "Invalid -clipsrc geometry. Must be a valid POLYGON or "
    8772             :                         "MULTIPOLYGON WKT");
    8773           0 :                     return nullptr;
    8774             :                 }
    8775             :             }
    8776          11 :             else if (EQUAL(osVal.c_str(), "spat_extent"))
    8777             :             {
    8778             :                 // Nothing to do
    8779             :             }
    8780             :             else
    8781             :             {
    8782          10 :                 psOptions->osClipSrcDS = osVal;
    8783             :             }
    8784             :         }
    8785             : 
    8786        1043 :         if (auto oClipDst =
    8787        1043 :                 argParser->present<std::vector<std::string>>("-clipdst"))
    8788             :         {
    8789          15 :             const std::string &osVal = (*oClipDst)[0];
    8790             : 
    8791          15 :             psOptions->poClipDst.reset();
    8792          15 :             psOptions->osClipDstDS.clear();
    8793             : 
    8794             :             VSIStatBufL sStat;
    8795          15 :             if (oClipDst->size() == 4)
    8796             :             {
    8797           2 :                 const double dfMinX = CPLAtofM((*oClipDst)[0].c_str());
    8798           2 :                 const double dfMinY = CPLAtofM((*oClipDst)[1].c_str());
    8799           2 :                 const double dfMaxX = CPLAtofM((*oClipDst)[2].c_str());
    8800           2 :                 const double dfMaxY = CPLAtofM((*oClipDst)[3].c_str());
    8801             : 
    8802             :                 auto poPoly = std::make_shared<OGRPolygon>(dfMinX, dfMinY,
    8803           4 :                                                            dfMaxX, dfMaxY);
    8804           2 :                 psOptions->poClipDst = poPoly;
    8805             :             }
    8806          13 :             else if ((STARTS_WITH_CI(osVal.c_str(), "POLYGON") ||
    8807          16 :                       STARTS_WITH_CI(osVal.c_str(), "MULTIPOLYGON")) &&
    8808           3 :                      VSIStatL(osVal.c_str(), &sStat) != 0)
    8809             :             {
    8810           3 :                 psOptions->poClipDst =
    8811           6 :                     OGRGeometryFactory::createFromWkt(osVal.c_str()).first;
    8812           3 :                 if (psOptions->poClipDst == nullptr)
    8813             :                 {
    8814           0 :                     CPLError(
    8815             :                         CE_Failure, CPLE_IllegalArg,
    8816             :                         "Invalid -clipdst geometry. Must be a valid POLYGON or "
    8817             :                         "MULTIPOLYGON WKT");
    8818           0 :                     return nullptr;
    8819             :                 }
    8820             :             }
    8821             :             else
    8822             :             {
    8823          10 :                 psOptions->osClipDstDS = osVal;
    8824             :             }
    8825             :         }
    8826             : 
    8827        2086 :         auto layers = argParser->present<std::vector<std::string>>("layer");
    8828        1043 :         if (layers)
    8829             :         {
    8830          58 :             for (const auto &layer : *layers)
    8831             :             {
    8832          40 :                 psOptions->aosLayers.AddString(layer.c_str());
    8833             :             }
    8834             :         }
    8835        1043 :         if (psOptionsForBinary)
    8836             :         {
    8837         131 :             psOptionsForBinary->eAccessMode = psOptions->eAccessMode;
    8838         131 :             psOptionsForBinary->osFormat = psOptions->osFormat;
    8839             : 
    8840         131 :             if (!(CPLTestBool(
    8841             :                     psOptionsForBinary->aosOpenOptions.FetchNameValueDef(
    8842             :                         "NATIVE_DATA",
    8843             :                         psOptionsForBinary->aosOpenOptions.FetchNameValueDef(
    8844             :                             "@NATIVE_DATA", "TRUE")))))
    8845             :             {
    8846           0 :                 psOptions->bNativeData = false;
    8847             :             }
    8848             : 
    8849         131 :             if (psOptions->bNativeData &&
    8850         130 :                 psOptionsForBinary->aosOpenOptions.FetchNameValue(
    8851         261 :                     "NATIVE_DATA") == nullptr &&
    8852         130 :                 psOptionsForBinary->aosOpenOptions.FetchNameValue(
    8853             :                     "@NATIVE_DATA") == nullptr)
    8854             :             {
    8855             :                 psOptionsForBinary->aosOpenOptions.AddString(
    8856         130 :                     "@NATIVE_DATA=YES");
    8857             :             }
    8858             :         }
    8859             : 
    8860        1043 :         return psOptions.release();
    8861             :     }
    8862          24 :     catch (const std::exception &err)
    8863             :     {
    8864          24 :         CPLError(CE_Failure, CPLE_AppDefined, "%s", err.what());
    8865          24 :         if (psOptionsForBinary)
    8866           1 :             psOptionsForBinary->bShowUsageIfError = true;
    8867          24 :         return nullptr;
    8868             :     }
    8869             : }
    8870             : 
    8871             : /************************************************************************/
    8872             : /*                   GDALVectorTranslateOptionsFree()                   */
    8873             : /************************************************************************/
    8874             : 
    8875             : /**
    8876             :  * Frees the GDALVectorTranslateOptions struct.
    8877             :  *
    8878             :  * @param psOptions the options struct for GDALVectorTranslate().
    8879             :  * @since GDAL 2.1
    8880             :  */
    8881             : 
    8882        1041 : void GDALVectorTranslateOptionsFree(GDALVectorTranslateOptions *psOptions)
    8883             : {
    8884        1041 :     delete psOptions;
    8885        1041 : }
    8886             : 
    8887             : /************************************************************************/
    8888             : /*               GDALVectorTranslateOptionsSetProgress()                */
    8889             : /************************************************************************/
    8890             : 
    8891             : /**
    8892             :  * Set a progress function.
    8893             :  *
    8894             :  * @param psOptions the options struct for GDALVectorTranslate().
    8895             :  * @param pfnProgress the progress callback.
    8896             :  * @param pProgressData the user data for the progress callback.
    8897             :  *
    8898             :  * @since GDAL 2.1
    8899             :  */
    8900             : 
    8901         368 : void GDALVectorTranslateOptionsSetProgress(
    8902             :     GDALVectorTranslateOptions *psOptions, GDALProgressFunc pfnProgress,
    8903             :     void *pProgressData)
    8904             : {
    8905         368 :     psOptions->pfnProgress = pfnProgress ? pfnProgress : GDALDummyProgress;
    8906         368 :     psOptions->pProgressData = pProgressData;
    8907         368 :     if (pfnProgress == GDALTermProgress)
    8908         129 :         psOptions->bQuiet = false;
    8909         368 : }
    8910             : 
    8911             : #undef CHECK_HAS_ENOUGH_ADDITIONAL_ARGS

Generated by: LCOV version 1.14