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