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