LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/generic - ogrlayer.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1668 2122 78.6 %
Date: 2026-11-18 01:45:17 Functions: 133 153 86.9 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  OpenGIS Simple Features Reference Implementation
       4             :  * Purpose:  The generic portions of the OGRSFLayer class.
       5             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 1999,  Les Technologies SoftMap Inc.
       9             :  * Copyright (c) 2008-2014, Even Rouault <even dot rouault at spatialys.com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "ogrsf_frmts.h"
      15             : #include "ogr_api.h"
      16             : #include "ogr_p.h"
      17             : #include "ogr_attrind.h"
      18             : #include "ogr_swq.h"
      19             : #include "ograpispy.h"
      20             : #include "ogr_wkb.h"
      21             : #include "ogrlayer_private.h"
      22             : 
      23             : #include "cpl_time.h"
      24             : #include <cassert>
      25             : #include <cmath>
      26             : #include <limits>
      27             : #include <memory>
      28             : #include <set>
      29             : 
      30             : /************************************************************************/
      31             : /*                              OGRLayer()                              */
      32             : /************************************************************************/
      33             : 
      34       79299 : OGRLayer::OGRLayer()
      35       79299 :     : m_poPrivate(new Private()), m_bFilterIsEnvelope(FALSE),
      36             :       m_poFilterGeom(nullptr), m_pPreparedFilterGeom(nullptr),
      37             :       m_sFilterEnvelope{}, m_iGeomFieldFilter(0), m_poStyleTable(nullptr),
      38             :       m_poAttrQuery(nullptr), m_pszAttrQueryString(nullptr),
      39      158598 :       m_poAttrIndex(nullptr), m_nRefCount(0), m_nFeaturesRead(0)
      40             : {
      41       79299 : }
      42             : 
      43             : /************************************************************************/
      44             : /*                             ~OGRLayer()                              */
      45             : /************************************************************************/
      46             : 
      47       79279 : OGRLayer::~OGRLayer()
      48             : 
      49             : {
      50       79279 :     if (m_poStyleTable)
      51             :     {
      52          12 :         delete m_poStyleTable;
      53          12 :         m_poStyleTable = nullptr;
      54             :     }
      55             : 
      56       79279 :     if (m_poAttrIndex != nullptr)
      57             :     {
      58         177 :         delete m_poAttrIndex;
      59         177 :         m_poAttrIndex = nullptr;
      60             :     }
      61             : 
      62       79279 :     if (m_poAttrQuery != nullptr)
      63             :     {
      64         671 :         delete m_poAttrQuery;
      65         671 :         m_poAttrQuery = nullptr;
      66             :     }
      67             : 
      68       79279 :     CPLFree(m_pszAttrQueryString);
      69             : 
      70       79279 :     if (m_poFilterGeom)
      71             :     {
      72        1165 :         delete m_poFilterGeom;
      73        1165 :         m_poFilterGeom = nullptr;
      74             :     }
      75             : 
      76       79279 :     if (m_pPreparedFilterGeom != nullptr)
      77             :     {
      78        1165 :         OGRDestroyPreparedGeometry(m_pPreparedFilterGeom);
      79        1165 :         m_pPreparedFilterGeom = nullptr;
      80             :     }
      81             : 
      82       79279 :     if (m_poSharedArrowArrayStreamPrivateData != nullptr)
      83             :     {
      84         797 :         m_poSharedArrowArrayStreamPrivateData->m_poLayer = nullptr;
      85             :     }
      86       79279 : }
      87             : 
      88             : /************************************************************************/
      89             : /*                             Reference()                              */
      90             : /************************************************************************/
      91             : 
      92             : /**
      93             : \brief Increment layer reference count.
      94             : 
      95             : This method is the same as the C function OGR_L_Reference().
      96             : 
      97             : @return the reference count after incrementing.
      98             : */
      99           0 : int OGRLayer::Reference()
     100             : 
     101             : {
     102           0 :     return ++m_nRefCount;
     103             : }
     104             : 
     105             : /************************************************************************/
     106             : /*                          OGR_L_Reference()                           */
     107             : /************************************************************************/
     108             : 
     109           0 : int OGR_L_Reference(OGRLayerH hLayer)
     110             : 
     111             : {
     112           0 :     VALIDATE_POINTER1(hLayer, "OGR_L_Reference", 0);
     113             : 
     114           0 :     return OGRLayer::FromHandle(hLayer)->Reference();
     115             : }
     116             : 
     117             : /************************************************************************/
     118             : /*                            Dereference()                             */
     119             : /************************************************************************/
     120             : 
     121             : /**
     122             : \brief Decrement layer reference count.
     123             : 
     124             : This method is the same as the C function OGR_L_Dereference().
     125             : 
     126             : @return the reference count after decrementing.
     127             : */
     128             : 
     129           0 : int OGRLayer::Dereference()
     130             : 
     131             : {
     132           0 :     return --m_nRefCount;
     133             : }
     134             : 
     135             : /************************************************************************/
     136             : /*                         OGR_L_Dereference()                          */
     137             : /************************************************************************/
     138             : 
     139           0 : int OGR_L_Dereference(OGRLayerH hLayer)
     140             : 
     141             : {
     142           0 :     VALIDATE_POINTER1(hLayer, "OGR_L_Dereference", 0);
     143             : 
     144           0 :     return OGRLayer::FromHandle(hLayer)->Dereference();
     145             : }
     146             : 
     147             : /************************************************************************/
     148             : /*                            GetRefCount()                             */
     149             : /************************************************************************/
     150             : 
     151             : /**
     152             : \brief Fetch reference count.
     153             : 
     154             : This method is the same as the C function OGR_L_GetRefCount().
     155             : 
     156             : @return the current reference count for the layer object itself.
     157             : */
     158             : 
     159           0 : int OGRLayer::GetRefCount() const
     160             : 
     161             : {
     162           0 :     return m_nRefCount;
     163             : }
     164             : 
     165             : /************************************************************************/
     166             : /*                         OGR_L_GetRefCount()                          */
     167             : /************************************************************************/
     168             : 
     169           0 : int OGR_L_GetRefCount(OGRLayerH hLayer)
     170             : 
     171             : {
     172           0 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetRefCount", 0);
     173             : 
     174           0 :     return OGRLayer::FromHandle(hLayer)->GetRefCount();
     175             : }
     176             : 
     177             : /************************************************************************/
     178             : /*                          GetFeatureCount()                           */
     179             : /************************************************************************/
     180             : 
     181             : /**
     182             :  \brief Fetch the feature count in this layer.
     183             : 
     184             :  Returns the number of features in the layer.  For dynamic databases the
     185             :  count may not be exact.  If bForce is FALSE, and it would be expensive
     186             :  to establish the feature count a value of -1 may be returned indicating
     187             :  that the count isn't know.  If bForce is TRUE some implementations will
     188             :  actually scan the entire layer once to count objects.
     189             : 
     190             :  The returned count takes the spatial filter into account.
     191             : 
     192             :  Note that some implementations of this method may alter the read cursor
     193             :  of the layer.
     194             : 
     195             :  This method is the same as the C function OGR_L_GetFeatureCount().
     196             : 
     197             : 
     198             :  @param bForce Flag indicating whether the count should be computed even
     199             :  if it is expensive.
     200             : 
     201             :  @return feature count, -1 if count not known.
     202             : */
     203             : 
     204       14804 : GIntBig OGRLayer::GetFeatureCount(int bForce)
     205             : 
     206             : {
     207       14804 :     if (!bForce)
     208           1 :         return -1;
     209             : 
     210       14803 :     GIntBig nFeatureCount = 0;
     211       57718 :     for (auto &&poFeature : *this)
     212             :     {
     213       42915 :         CPL_IGNORE_RET_VAL(poFeature.get());
     214       42915 :         nFeatureCount++;
     215             :     }
     216       14803 :     ResetReading();
     217             : 
     218       14803 :     return nFeatureCount;
     219             : }
     220             : 
     221             : /************************************************************************/
     222             : /*                       OGR_L_GetFeatureCount()                        */
     223             : /************************************************************************/
     224             : 
     225             : /**
     226             :  \brief Fetch the feature count in this layer.
     227             : 
     228             :  Returns the number of features in the layer.  For dynamic databases the
     229             :  count may not be exact.  If bForce is FALSE, and it would be expensive
     230             :  to establish the feature count a value of -1 may be returned indicating
     231             :  that the count isn't know.  If bForce is TRUE some implementations will
     232             :  actually scan the entire layer once to count objects.
     233             : 
     234             :  The returned count takes the spatial filter into account.
     235             : 
     236             :  Note that some implementations of this method may alter the read cursor
     237             :  of the layer.
     238             : 
     239             :  This function is the same as the CPP OGRLayer::GetFeatureCount().
     240             : 
     241             : 
     242             :  @param hLayer handle to the layer that owned the features.
     243             :  @param bForce Flag indicating whether the count should be computed even
     244             :  if it is expensive.
     245             : 
     246             :  @return feature count, -1 if count not known.
     247             : */
     248             : 
     249       37529 : GIntBig OGR_L_GetFeatureCount(OGRLayerH hLayer, int bForce)
     250             : 
     251             : {
     252       37529 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetFeatureCount", 0);
     253             : 
     254             : #ifdef OGRAPISPY_ENABLED
     255       37529 :     if (bOGRAPISpyEnabled)
     256           2 :         OGRAPISpy_L_GetFeatureCount(hLayer, bForce);
     257             : #endif
     258             : 
     259       37529 :     return OGRLayer::FromHandle(hLayer)->GetFeatureCount(bForce);
     260             : }
     261             : 
     262             : /************************************************************************/
     263             : /*                             GetExtent()                              */
     264             : /************************************************************************/
     265             : 
     266             : /**
     267             :  \brief Fetch the extent of this layer.
     268             : 
     269             :  Returns the extent (MBR) of the data in the layer.  If bForce is FALSE,
     270             :  and it would be expensive to establish the extent then OGRERR_FAILURE
     271             :  will be returned indicating that the extent isn't know.  If bForce is
     272             :  TRUE then some implementations will actually scan the entire layer once
     273             :  to compute the MBR of all the features in the layer.
     274             : 
     275             :  Depending on the drivers, the returned extent may or may not take the
     276             :  spatial filter into account.  So it is safer to call GetExtent() without
     277             :  setting a spatial filter.
     278             : 
     279             :  Layers without any geometry may return OGRERR_FAILURE just indicating that
     280             :  no meaningful extents could be collected.
     281             : 
     282             :  Note that some implementations of this method may alter the read cursor
     283             :  of the layer.
     284             : 
     285             :  This method is the same as the C function OGR_L_GetExtent().
     286             : 
     287             :  @param psExtent the structure in which the extent value will be returned.
     288             :  @param bForce Flag indicating whether the extent should be computed even
     289             :  if it is expensive.
     290             : 
     291             :  @return OGRERR_NONE on success, OGRERR_FAILURE if extent not known.
     292             : */
     293             : 
     294       15487 : OGRErr OGRLayer::GetExtent(OGREnvelope *psExtent, bool bForce)
     295             : {
     296       15487 :     return GetExtent(0, psExtent, bForce);
     297             : }
     298             : 
     299             : /**
     300             :  \brief Fetch the extent of this layer, on the specified geometry field.
     301             : 
     302             :  Returns the extent (MBR) of the data in the layer.  If bForce is FALSE,
     303             :  and it would be expensive to establish the extent then OGRERR_FAILURE
     304             :  will be returned indicating that the extent isn't know.  If bForce is
     305             :  TRUE then some implementations will actually scan the entire layer once
     306             :  to compute the MBR of all the features in the layer.
     307             : 
     308             :  Depending on the drivers, the returned extent may or may not take the
     309             :  spatial filter into account.  So it is safer to call GetExtent() without
     310             :  setting a spatial filter.
     311             : 
     312             :  Layers without any geometry may return OGRERR_FAILURE just indicating that
     313             :  no meaningful extents could be collected.
     314             : 
     315             :  Note that some implementations of this method may alter the read cursor
     316             :  of the layer.
     317             : 
     318             :  This method is the same as the C function OGR_L_GetExtentEx().
     319             : 
     320             :  @param iGeomField the index of the geometry field on which to compute the extent.
     321             :  @param psExtent the structure in which the extent value will be returned.
     322             :  @param bForce Flag indicating whether the extent should be computed even
     323             :  if it is expensive.
     324             : 
     325             :  @return OGRERR_NONE on success, OGRERR_FAILURE if extent not known.
     326             : 
     327             : */
     328             : 
     329       17973 : OGRErr OGRLayer::GetExtent(int iGeomField, OGREnvelope *psExtent, bool bForce)
     330             : {
     331       17973 :     psExtent->MinX = 0.0;
     332       17973 :     psExtent->MaxX = 0.0;
     333       17973 :     psExtent->MinY = 0.0;
     334       17973 :     psExtent->MaxY = 0.0;
     335             : 
     336             :     /* -------------------------------------------------------------------- */
     337             :     /*      If this layer has a none geometry type, then we can             */
     338             :     /*      reasonably assume there are not extents available.              */
     339             :     /* -------------------------------------------------------------------- */
     340       35008 :     if (iGeomField < 0 || iGeomField >= GetLayerDefn()->GetGeomFieldCount() ||
     341       17035 :         GetLayerDefn()->GetGeomFieldDefn(iGeomField)->GetType() == wkbNone)
     342             :     {
     343         938 :         if (iGeomField != 0)
     344             :         {
     345         760 :             CPLError(CE_Failure, CPLE_AppDefined,
     346             :                      "Invalid geometry field index : %d", iGeomField);
     347             :         }
     348         938 :         return OGRERR_FAILURE;
     349             :     }
     350             : 
     351       17035 :     return IGetExtent(iGeomField, psExtent, bForce);
     352             : }
     353             : 
     354             : /************************************************************************/
     355             : /*                             IGetExtent()                             */
     356             : /************************************************************************/
     357             : 
     358             : /**
     359             :  \brief Fetch the extent of this layer, on the specified geometry field.
     360             : 
     361             :  Virtual method implemented by drivers since 3.11. In previous versions,
     362             :  GetExtent() itself was the virtual method.
     363             : 
     364             :  Driver implementations, when wanting to call the base method, must take
     365             :  care of calling OGRLayer::IGetExtent() (and note the public method without
     366             :  the leading I).
     367             : 
     368             :  @param iGeomField 0-based index of the geometry field to consider.
     369             :  @param psExtent the computed extent of the layer.
     370             :  @param bForce if TRUE, the extent will be computed even if all the
     371             :         layer features have to be fetched.
     372             :  @return OGRERR_NONE on success or an error code in case of failure.
     373             :  @since GDAL 3.11
     374             : */
     375             : 
     376         592 : OGRErr OGRLayer::IGetExtent(int iGeomField, OGREnvelope *psExtent, bool bForce)
     377             : 
     378             : {
     379             :     /* -------------------------------------------------------------------- */
     380             :     /*      If not forced, we should avoid having to scan all the           */
     381             :     /*      features and just return a failure.                             */
     382             :     /* -------------------------------------------------------------------- */
     383         592 :     if (!bForce)
     384           2 :         return OGRERR_FAILURE;
     385             : 
     386             :     /* -------------------------------------------------------------------- */
     387             :     /*      OK, we hate to do this, but go ahead and read through all       */
     388             :     /*      the features to collect geometries and build extents.           */
     389             :     /* -------------------------------------------------------------------- */
     390         590 :     OGREnvelope oEnv;
     391         590 :     bool bExtentSet = false;
     392             : 
     393       10272 :     for (auto &&poFeature : *this)
     394             :     {
     395        9682 :         OGRGeometry *poGeom = poFeature->GetGeomFieldRef(iGeomField);
     396        9682 :         if (poGeom == nullptr || poGeom->IsEmpty())
     397             :         {
     398             :             /* Do nothing */
     399             :         }
     400        9379 :         else if (!bExtentSet)
     401             :         {
     402         537 :             poGeom->getEnvelope(psExtent);
     403        1074 :             if (!(std::isnan(psExtent->MinX) || std::isnan(psExtent->MinY) ||
     404         537 :                   std::isnan(psExtent->MaxX) || std::isnan(psExtent->MaxY)))
     405             :             {
     406         537 :                 bExtentSet = true;
     407             :             }
     408             :         }
     409             :         else
     410             :         {
     411        8842 :             poGeom->getEnvelope(&oEnv);
     412        8842 :             if (oEnv.MinX < psExtent->MinX)
     413         363 :                 psExtent->MinX = oEnv.MinX;
     414        8842 :             if (oEnv.MinY < psExtent->MinY)
     415         405 :                 psExtent->MinY = oEnv.MinY;
     416        8842 :             if (oEnv.MaxX > psExtent->MaxX)
     417         983 :                 psExtent->MaxX = oEnv.MaxX;
     418        8842 :             if (oEnv.MaxY > psExtent->MaxY)
     419         959 :                 psExtent->MaxY = oEnv.MaxY;
     420             :         }
     421             :     }
     422         590 :     ResetReading();
     423             : 
     424         590 :     return bExtentSet ? OGRERR_NONE : OGRERR_FAILURE;
     425             : }
     426             : 
     427             : /************************************************************************/
     428             : /*                          OGR_L_GetExtent()                           */
     429             : /************************************************************************/
     430             : 
     431             : /**
     432             :  \brief Fetch the extent of this layer.
     433             : 
     434             :  Returns the extent (MBR) of the data in the layer.  If bForce is FALSE,
     435             :  and it would be expensive to establish the extent then OGRERR_FAILURE
     436             :  will be returned indicating that the extent isn't know.  If bForce is
     437             :  TRUE then some implementations will actually scan the entire layer once
     438             :  to compute the MBR of all the features in the layer.
     439             : 
     440             :  Depending on the drivers, the returned extent may or may not take the
     441             :  spatial filter into account.  So it is safer to call OGR_L_GetExtent() without
     442             :  setting a spatial filter.
     443             : 
     444             :  Layers without any geometry may return OGRERR_FAILURE just indicating that
     445             :  no meaningful extents could be collected.
     446             : 
     447             :  Note that some implementations of this method may alter the read cursor
     448             :  of the layer.
     449             : 
     450             :  This function is the same as the C++ method OGRLayer::GetExtent().
     451             : 
     452             :  @param hLayer handle to the layer from which to get extent.
     453             :  @param psExtent the structure in which the extent value will be returned.
     454             :  @param bForce Flag indicating whether the extent should be computed even
     455             :  if it is expensive.
     456             : 
     457             :  @return OGRERR_NONE on success, OGRERR_FAILURE if extent not known.
     458             : 
     459             : */
     460             : 
     461          49 : OGRErr OGR_L_GetExtent(OGRLayerH hLayer, OGREnvelope *psExtent, int bForce)
     462             : 
     463             : {
     464          49 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetExtent", OGRERR_INVALID_HANDLE);
     465             : 
     466             : #ifdef OGRAPISPY_ENABLED
     467          49 :     if (bOGRAPISpyEnabled)
     468           0 :         OGRAPISpy_L_GetExtent(hLayer, bForce);
     469             : #endif
     470             : 
     471          49 :     return OGRLayer::FromHandle(hLayer)->GetExtent(0, psExtent,
     472          49 :                                                    bForce != FALSE);
     473             : }
     474             : 
     475             : /************************************************************************/
     476             : /*                         OGR_L_GetExtentEx()                          */
     477             : /************************************************************************/
     478             : 
     479             : /**
     480             :  \brief Fetch the extent of this layer, on the specified geometry field.
     481             : 
     482             :  Returns the extent (MBR) of the data in the layer.  If bForce is FALSE,
     483             :  and it would be expensive to establish the extent then OGRERR_FAILURE
     484             :  will be returned indicating that the extent isn't know.  If bForce is
     485             :  TRUE then some implementations will actually scan the entire layer once
     486             :  to compute the MBR of all the features in the layer.
     487             : 
     488             :  Depending on the drivers, the returned extent may or may not take the
     489             :  spatial filter into account.  So it is safer to call OGR_L_GetExtent() without
     490             :  setting a spatial filter.
     491             : 
     492             :  Layers without any geometry may return OGRERR_FAILURE just indicating that
     493             :  no meaningful extents could be collected.
     494             : 
     495             :  Note that some implementations of this method may alter the read cursor
     496             :  of the layer.
     497             : 
     498             :  This function is the same as the C++ method OGRLayer::GetExtent().
     499             : 
     500             :  @param hLayer handle to the layer from which to get extent.
     501             :  @param iGeomField the index of the geometry field on which to compute the extent.
     502             :  @param psExtent the structure in which the extent value will be returned.
     503             :  @param bForce Flag indicating whether the extent should be computed even
     504             :  if it is expensive.
     505             : 
     506             :  @return OGRERR_NONE on success, OGRERR_FAILURE if extent not known.
     507             : 
     508             : */
     509         385 : OGRErr OGR_L_GetExtentEx(OGRLayerH hLayer, int iGeomField,
     510             :                          OGREnvelope *psExtent, int bForce)
     511             : 
     512             : {
     513         385 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetExtentEx", OGRERR_INVALID_HANDLE);
     514             : 
     515             : #ifdef OGRAPISPY_ENABLED
     516         385 :     if (bOGRAPISpyEnabled)
     517           4 :         OGRAPISpy_L_GetExtentEx(hLayer, iGeomField, bForce);
     518             : #endif
     519             : 
     520         385 :     return OGRLayer::FromHandle(hLayer)->GetExtent(iGeomField, psExtent,
     521         385 :                                                    bForce != FALSE);
     522             : }
     523             : 
     524             : /************************************************************************/
     525             : /*                            GetExtent3D()                             */
     526             : /************************************************************************/
     527             : 
     528             : /**
     529             :  \brief Fetch the 3D extent of this layer, on the specified geometry field.
     530             : 
     531             :  Returns the 3D extent (MBR) of the data in the layer.  If bForce is FALSE,
     532             :  and it would be expensive to establish the extent then OGRERR_FAILURE
     533             :  will be returned indicating that the extent isn't know.  If bForce is
     534             :  TRUE then some implementations will actually scan the entire layer once
     535             :  to compute the MBR of all the features in the layer.
     536             : 
     537             :  (Contrary to GetExtent() 2D), the returned extent will always take into
     538             :  account the attribute and spatial filters that may be installed.
     539             : 
     540             :  Layers without any geometry may return OGRERR_FAILURE just indicating that
     541             :  no meaningful extents could be collected.
     542             : 
     543             :  For layers that have no 3D geometries, the psExtent3D->MinZ and psExtent3D->MaxZ
     544             :  fields will be respectively set to +Infinity and -Infinity.
     545             : 
     546             :  Note that some implementations of this method may alter the read cursor
     547             :  of the layer.
     548             : 
     549             :  This function is the same as the C function OGR_L_GetExtent3D().
     550             : 
     551             :  @param iGeomField 0-based index of the geometry field to consider.
     552             :  @param psExtent3D the computed 3D extent of the layer.
     553             :  @param bForce if TRUE, the extent will be computed even if all the
     554             :         layer features have to be fetched.
     555             :  @return OGRERR_NONE on success or an error code in case of failure.
     556             :  @since GDAL 3.9
     557             : */
     558             : 
     559          68 : OGRErr OGRLayer::GetExtent3D(int iGeomField, OGREnvelope3D *psExtent3D,
     560             :                              bool bForce)
     561             : 
     562             : {
     563          68 :     psExtent3D->MinX = 0.0;
     564          68 :     psExtent3D->MaxX = 0.0;
     565          68 :     psExtent3D->MinY = 0.0;
     566          68 :     psExtent3D->MaxY = 0.0;
     567          68 :     psExtent3D->MinZ = std::numeric_limits<double>::infinity();
     568          68 :     psExtent3D->MaxZ = -std::numeric_limits<double>::infinity();
     569             : 
     570             :     /* -------------------------------------------------------------------- */
     571             :     /*      If this layer has a none geometry type, then we can             */
     572             :     /*      reasonably assume there are not extents available.              */
     573             :     /* -------------------------------------------------------------------- */
     574         135 :     if (iGeomField < 0 || iGeomField >= GetLayerDefn()->GetGeomFieldCount() ||
     575          67 :         GetLayerDefn()->GetGeomFieldDefn(iGeomField)->GetType() == wkbNone)
     576             :     {
     577           1 :         if (iGeomField != 0)
     578             :         {
     579           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     580             :                      "Invalid geometry field index : %d", iGeomField);
     581             :         }
     582           1 :         return OGRERR_FAILURE;
     583             :     }
     584             : 
     585          67 :     return IGetExtent3D(iGeomField, psExtent3D, bForce);
     586             : }
     587             : 
     588             : /************************************************************************/
     589             : /*                            IGetExtent3D()                            */
     590             : /************************************************************************/
     591             : 
     592             : /**
     593             :  \brief Fetch the 3D extent of this layer, on the specified geometry field.
     594             : 
     595             :  See GetExtent3D() documentation.
     596             : 
     597             :  Virtual method implemented by drivers since 3.11. In previous versions,
     598             :  GetExtent3D() itself was the virtual method.
     599             : 
     600             :  Driver implementations, when wanting to call the base method, must take
     601             :  care of calling OGRLayer::IGetExtent3D() (and note the public method without
     602             :  the leading I).
     603             : 
     604             :  @param iGeomField 0-based index of the geometry field to consider.
     605             :  @param psExtent3D the computed 3D extent of the layer.
     606             :  @param bForce if TRUE, the extent will be computed even if all the
     607             :         layer features have to be fetched.
     608             :  @return OGRERR_NONE on success or an error code in case of failure.
     609             :  @since GDAL 3.11
     610             : */
     611             : 
     612          27 : OGRErr OGRLayer::IGetExtent3D(int iGeomField, OGREnvelope3D *psExtent3D,
     613             :                               bool bForce)
     614             : 
     615             : {
     616             :     /* -------------------------------------------------------------------- */
     617             :     /*      If not forced, we should avoid having to scan all the           */
     618             :     /*      features and just return a failure.                             */
     619             :     /* -------------------------------------------------------------------- */
     620          27 :     if (!bForce)
     621           0 :         return OGRERR_FAILURE;
     622             : 
     623             :     /* -------------------------------------------------------------------- */
     624             :     /*      OK, we hate to do this, but go ahead and read through all       */
     625             :     /*      the features to collect geometries and build extents.           */
     626             :     /* -------------------------------------------------------------------- */
     627          27 :     OGREnvelope3D oEnv;
     628          27 :     bool bExtentSet = false;
     629             : 
     630         133 :     for (auto &&poFeature : *this)
     631             :     {
     632         106 :         OGRGeometry *poGeom = poFeature->GetGeomFieldRef(iGeomField);
     633         106 :         if (poGeom == nullptr || poGeom->IsEmpty())
     634             :         {
     635             :             /* Do nothing */
     636             :         }
     637          89 :         else if (!bExtentSet)
     638             :         {
     639          27 :             poGeom->getEnvelope(psExtent3D);
     640             :             // This is required because getEnvelope initializes Z to 0 for 2D geometries
     641          27 :             if (!poGeom->Is3D())
     642             :             {
     643          20 :                 psExtent3D->MinZ = std::numeric_limits<double>::infinity();
     644          20 :                 psExtent3D->MaxZ = -std::numeric_limits<double>::infinity();
     645             :             }
     646          27 :             bExtentSet = true;
     647             :         }
     648             :         else
     649             :         {
     650          62 :             poGeom->getEnvelope(&oEnv);
     651             :             // This is required because getEnvelope initializes Z to 0 for 2D geometries
     652          62 :             if (!poGeom->Is3D())
     653             :             {
     654          53 :                 oEnv.MinZ = std::numeric_limits<double>::infinity();
     655          53 :                 oEnv.MaxZ = -std::numeric_limits<double>::infinity();
     656             :             }
     657             :             // Merge handles infinity correctly
     658          62 :             psExtent3D->Merge(oEnv);
     659             :         }
     660             :     }
     661          27 :     ResetReading();
     662             : 
     663          27 :     return bExtentSet ? OGRERR_NONE : OGRERR_FAILURE;
     664             : }
     665             : 
     666             : /************************************************************************/
     667             : /*                         OGR_L_GetExtent3D()                          */
     668             : /************************************************************************/
     669             : 
     670             : /**
     671             :  \brief Fetch the 3D extent of this layer, on the specified geometry field.
     672             : 
     673             :  Returns the 3D extent (MBR) of the data in the layer.  If bForce is FALSE,
     674             :  and it would be expensive to establish the extent then OGRERR_FAILURE
     675             :  will be returned indicating that the extent isn't know.  If bForce is
     676             :  TRUE then some implementations will actually scan the entire layer once
     677             :  to compute the MBR of all the features in the layer.
     678             : 
     679             :  (Contrary to GetExtent() 2D), the returned extent will always take into
     680             :  account the attribute and spatial filters that may be installed.
     681             : 
     682             :  Layers without any geometry may return OGRERR_FAILURE just indicating that
     683             :  no meaningful extents could be collected.
     684             : 
     685             :  For layers that have no 3D geometries, the psExtent3D->MinZ and psExtent3D->MaxZ
     686             :  fields will be respectively set to +Infinity and -Infinity.
     687             : 
     688             :  Note that some implementations of this method may alter the read cursor
     689             :  of the layer.
     690             : 
     691             :  This function is the same as the C++ method OGRLayer::GetExtent3D().
     692             : 
     693             :  @param hLayer the layer to consider.
     694             :  @param iGeomField 0-based index of the geometry field to consider.
     695             :  @param psExtent3D the computed 3D extent of the layer.
     696             :  @param bForce if TRUE, the extent will be computed even if all the
     697             :         layer features have to be fetched.
     698             :  @return OGRERR_NONE on success or an error code in case of failure.
     699             :  @since GDAL 3.9
     700             : */
     701             : 
     702          62 : OGRErr OGR_L_GetExtent3D(OGRLayerH hLayer, int iGeomField,
     703             :                          OGREnvelope3D *psExtent3D, int bForce)
     704             : 
     705             : {
     706          62 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetExtent3D", OGRERR_INVALID_HANDLE);
     707             : 
     708             : #ifdef OGRAPISPY_ENABLED
     709          62 :     if (bOGRAPISpyEnabled)
     710           0 :         OGRAPISpy_L_GetExtent3D(hLayer, iGeomField, bForce);
     711             : #endif
     712             : 
     713          62 :     return OGRLayer::FromHandle(hLayer)->GetExtent3D(iGeomField, psExtent3D,
     714          62 :                                                      bForce != FALSE);
     715             : }
     716             : 
     717             : /************************************************************************/
     718             : /*                         SetAttributeFilter()                         */
     719             : /************************************************************************/
     720             : 
     721             : /**
     722             :  \brief Set a new attribute query.
     723             : 
     724             :  This method sets the attribute query string to be used when
     725             :  fetching features via the GetNextFeature() method.  Only features for which
     726             :  the query evaluates as true will be returned.
     727             : 
     728             :  The query string should be in the format of an SQL WHERE clause.  For
     729             :  instance "population > 1000000 and population < 5000000" where population
     730             :  is an attribute in the layer. The query format is normally a SQL WHERE clause
     731             :  as described in the
     732             :  <a href="https://gdal.org/user/ogr_sql_dialect.html#where">"WHERE"</a> section
     733             :  of the OGR SQL dialect documentation.
     734             :  In some cases (RDBMS backed drivers, SQLite, GeoPackage) the native
     735             :  capabilities of the database may be used to to interpret the WHERE clause, in
     736             :  which case the capabilities will be broader than those of OGR SQL.
     737             : 
     738             :  Note that installing a query string will generally result in resetting
     739             :  the current reading position (ala ResetReading()).
     740             : 
     741             :  This method is the same as the C function OGR_L_SetAttributeFilter().
     742             : 
     743             :  @param pszQuery query in restricted SQL WHERE format, or NULL to clear the
     744             :  current query.
     745             : 
     746             :  @see GetAttrQueryString() to retrieve the currently installed query string.
     747             : 
     748             :  @return OGRERR_NONE if successfully installed, or an error code if the
     749             :  query expression is in error, or some other failure occurs.
     750             :  */
     751             : 
     752       18064 : OGRErr OGRLayer::SetAttributeFilter(const char *pszQuery)
     753             : 
     754             : {
     755       18064 :     CPLFree(m_pszAttrQueryString);
     756       18064 :     m_pszAttrQueryString = (pszQuery) ? CPLStrdup(pszQuery) : nullptr;
     757             : 
     758             :     /* -------------------------------------------------------------------- */
     759             :     /*      Are we just clearing any existing query?                        */
     760             :     /* -------------------------------------------------------------------- */
     761       18064 :     if (pszQuery == nullptr || strlen(pszQuery) == 0)
     762             :     {
     763       12005 :         if (m_poAttrQuery)
     764             :         {
     765        3620 :             delete m_poAttrQuery;
     766        3620 :             m_poAttrQuery = nullptr;
     767        3620 :             ResetReading();
     768             :         }
     769       12005 :         return OGRERR_NONE;
     770             :     }
     771             : 
     772             :     /* -------------------------------------------------------------------- */
     773             :     /*      Or are we installing a new query?                               */
     774             :     /* -------------------------------------------------------------------- */
     775             :     OGRErr eErr;
     776             : 
     777        6059 :     if (!m_poAttrQuery)
     778        4349 :         m_poAttrQuery = new OGRFeatureQuery();
     779             : 
     780        6059 :     eErr = m_poAttrQuery->Compile(this, pszQuery);
     781        6059 :     if (eErr != OGRERR_NONE)
     782             :     {
     783           3 :         delete m_poAttrQuery;
     784           3 :         m_poAttrQuery = nullptr;
     785             :     }
     786             : 
     787        6059 :     ResetReading();
     788             : 
     789        6059 :     return eErr;
     790             : }
     791             : 
     792             : /************************************************************************/
     793             : /*                      ContainGeomSpecialField()                       */
     794             : /************************************************************************/
     795             : 
     796         326 : static int ContainGeomSpecialField(swq_expr_node *expr, int nLayerFieldCount,
     797             :                                    int nLayerGeomFieldCount)
     798             : {
     799         326 :     if (expr->eNodeType == SNT_COLUMN)
     800             :     {
     801          77 :         if (expr->table_index == 0 && expr->field_index != -1)
     802             :         {
     803          77 :             int nSpecialFieldIdx = expr->field_index - nLayerFieldCount;
     804          77 :             if (nSpecialFieldIdx == SPF_OGR_GEOMETRY ||
     805          74 :                 nSpecialFieldIdx == SPF_OGR_GEOM_WKT ||
     806             :                 nSpecialFieldIdx == SPF_OGR_GEOM_AREA)
     807           4 :                 return TRUE;
     808          73 :             int iFirstGeomField = nLayerFieldCount + SPECIAL_FIELD_COUNT;
     809          73 :             if (expr->field_index >= iFirstGeomField &&
     810           4 :                 expr->field_index < iFirstGeomField + nLayerGeomFieldCount)
     811           4 :                 return TRUE;
     812          69 :             return FALSE;
     813             :         }
     814             :     }
     815         249 :     else if (expr->eNodeType == SNT_OPERATION)
     816             :     {
     817         371 :         for (int i = 0; i < expr->nSubExprCount; i++)
     818             :         {
     819         246 :             if (ContainGeomSpecialField(expr->papoSubExpr[i], nLayerFieldCount,
     820         246 :                                         nLayerGeomFieldCount))
     821           9 :                 return TRUE;
     822             :         }
     823             :     }
     824         240 :     return FALSE;
     825             : }
     826             : 
     827             : /************************************************************************/
     828             : /*               AttributeFilterEvaluationNeedsGeometry()               */
     829             : /************************************************************************/
     830             : 
     831             : //! @cond Doxygen_Suppress
     832          81 : int OGRLayer::AttributeFilterEvaluationNeedsGeometry()
     833             : {
     834          81 :     if (!m_poAttrQuery)
     835           1 :         return FALSE;
     836             : 
     837             :     swq_expr_node *expr =
     838          80 :         static_cast<swq_expr_node *>(m_poAttrQuery->GetSWQExpr());
     839          80 :     const auto poLayerDefn = GetLayerDefn();
     840          80 :     int nLayerFieldCount = poLayerDefn->GetFieldCount();
     841          80 :     int nLayerGeomFieldCount = poLayerDefn->GetGeomFieldCount();
     842             : 
     843          80 :     return ContainGeomSpecialField(expr, nLayerFieldCount,
     844          80 :                                    nLayerGeomFieldCount);
     845             : }
     846             : 
     847             : //! @endcond
     848             : 
     849             : /************************************************************************/
     850             : /*                      OGR_L_SetAttributeFilter()                      */
     851             : /************************************************************************/
     852             : 
     853             : /**
     854             :  \brief Set a new attribute query.
     855             : 
     856             :  This function sets the attribute query string to be used when
     857             :  fetching features via the OGR_L_GetNextFeature() function.
     858             :  Only features for which the query evaluates as true will be returned.
     859             : 
     860             :  The query string should be in the format of an SQL WHERE clause.  For
     861             :  instance "population > 1000000 and population < 5000000" where population
     862             :  is an attribute in the layer. The query format is normally a SQL WHERE clause
     863             :  as described in the
     864             :  <a href="https://gdal.org/user/ogr_sql_dialect.html#where">"WHERE"</a> section
     865             :  of the OGR SQL dialect documentation.
     866             :  In some cases (RDBMS backed drivers, SQLite, GeoPackage) the native
     867             :  capabilities of the database may be used to to interpret the WHERE clause, in
     868             :  which case the capabilities will be broader than those of OGR SQL.
     869             : 
     870             :  Note that installing a query string will generally result in resetting
     871             :  the current reading position (ala OGR_L_ResetReading()).
     872             : 
     873             :  This function is the same as the C++ method OGRLayer::SetAttributeFilter().
     874             : 
     875             :  @param hLayer handle to the layer on which attribute query will be executed.
     876             :  @param pszQuery query in restricted SQL WHERE format, or NULL to clear the
     877             :  current query.
     878             : 
     879             :  @return OGRERR_NONE if successfully installed, or an error code if the
     880             :  query expression is in error, or some other failure occurs.
     881             :  */
     882             : 
     883        1480 : OGRErr OGR_L_SetAttributeFilter(OGRLayerH hLayer, const char *pszQuery)
     884             : 
     885             : {
     886        1480 :     VALIDATE_POINTER1(hLayer, "OGR_L_SetAttributeFilter",
     887             :                       OGRERR_INVALID_HANDLE);
     888             : 
     889             : #ifdef OGRAPISPY_ENABLED
     890        1480 :     if (bOGRAPISpyEnabled)
     891           4 :         OGRAPISpy_L_SetAttributeFilter(hLayer, pszQuery);
     892             : #endif
     893             : 
     894        1480 :     return OGRLayer::FromHandle(hLayer)->SetAttributeFilter(pszQuery);
     895             : }
     896             : 
     897             : /************************************************************************/
     898             : /*                      OGR_L_GetAttributeFilter()                      */
     899             : /************************************************************************/
     900             : 
     901             : /**
     902             :  * @brief Fetch the current attribute query string.
     903             :  *
     904             :  * This function is the same as the C++ method OGRLayer::GetAttrQueryString().
     905             :  *
     906             :  * @return the current attribute query string, or NULL if no attribute query is
     907             :  * currently installed. The returned string is short lived and owned by the layer
     908             :  * and should not be modified or freed by the caller.
     909             :  *
     910             :  * @see OGR_L_SetAttributeFilter() to set a new attribute query string.
     911             :  * @since GDAL 3.13
     912             :  */
     913           3 : const char *OGR_L_GetAttributeFilter(OGRLayerH hLayer)
     914             : {
     915           3 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetAttributeFilter", nullptr);
     916             : 
     917           3 :     return OGRLayer::FromHandle(hLayer)->GetAttrQueryString();
     918             : }
     919             : 
     920             : /************************************************************************/
     921             : /*                             GetFeature()                             */
     922             : /************************************************************************/
     923             : 
     924             : /**
     925             :  \brief Fetch a feature by its identifier.
     926             : 
     927             :  This function will attempt to read the identified feature.  The nFID
     928             :  value cannot be OGRNullFID.  Success or failure of this operation is
     929             :  unaffected by the spatial or attribute filters (and specialized implementations
     930             :  in drivers should make sure that they do not take into account spatial or
     931             :  attribute filters).
     932             : 
     933             :  If this method returns a non-NULL feature, it is guaranteed that its
     934             :  feature id (OGRFeature::GetFID()) will be the same as nFID.
     935             : 
     936             :  Use OGRLayer::TestCapability(OLCRandomRead) to establish if this layer
     937             :  supports efficient random access reading via GetFeature(); however, the
     938             :  call should always work if the feature exists as a fallback implementation
     939             :  just scans all the features in the layer looking for the desired feature.
     940             : 
     941             :  Sequential reads (with GetNextFeature()) are generally considered interrupted
     942             :  by a GetFeature() call.
     943             : 
     944             :  The returned feature should be free with OGRFeature::DestroyFeature().
     945             : 
     946             :  This method is the same as the C function OGR_L_GetFeature().
     947             : 
     948             :  @param nFID the feature id of the feature to read.
     949             : 
     950             :  @return a feature now owned by the caller, or NULL on failure.
     951             : */
     952             : 
     953        1101 : OGRFeature *OGRLayer::GetFeature(GIntBig nFID)
     954             : 
     955             : {
     956             :     /* Save old attribute and spatial filters */
     957             :     char *pszOldFilter =
     958        1101 :         m_pszAttrQueryString ? CPLStrdup(m_pszAttrQueryString) : nullptr;
     959             :     OGRGeometry *poOldFilterGeom =
     960        1101 :         (m_poFilterGeom != nullptr) ? m_poFilterGeom->clone() : nullptr;
     961        1101 :     int iOldGeomFieldFilter = m_iGeomFieldFilter;
     962             :     /* Unset filters */
     963        1101 :     SetAttributeFilter(nullptr);
     964        1101 :     SetSpatialFilter(0, nullptr);
     965             : 
     966        1101 :     OGRFeatureUniquePtr poFeature;
     967       14947 :     for (auto &&poFeatureIter : *this)
     968             :     {
     969       13846 :         if (poFeatureIter->GetFID() == nFID)
     970             :         {
     971         723 :             poFeature.swap(poFeatureIter);
     972         723 :             break;
     973             :         }
     974             :     }
     975             : 
     976             :     /* Restore filters */
     977        1101 :     SetAttributeFilter(pszOldFilter);
     978        1101 :     CPLFree(pszOldFilter);
     979        1101 :     SetSpatialFilter(iOldGeomFieldFilter, poOldFilterGeom);
     980        1101 :     delete poOldFilterGeom;
     981             : 
     982        2202 :     return poFeature.release();
     983             : }
     984             : 
     985             : /************************************************************************/
     986             : /*                          OGR_L_GetFeature()                          */
     987             : /************************************************************************/
     988             : 
     989             : /**
     990             :  \brief Fetch a feature by its identifier.
     991             : 
     992             :  This function will attempt to read the identified feature.  The nFID
     993             :  value cannot be OGRNullFID.  Success or failure of this operation is
     994             :  unaffected by the spatial or attribute filters (and specialized implementations
     995             :  in drivers should make sure that they do not take into account spatial or
     996             :  attribute filters).
     997             : 
     998             :  If this function returns a non-NULL feature, it is guaranteed that its
     999             :  feature id (OGR_F_GetFID()) will be the same as nFID.
    1000             : 
    1001             :  Use OGR_L_TestCapability(OLCRandomRead) to establish if this layer
    1002             :  supports efficient random access reading via OGR_L_GetFeature(); however,
    1003             :  the call should always work if the feature exists as a fallback
    1004             :  implementation just scans all the features in the layer looking for the
    1005             :  desired feature.
    1006             : 
    1007             :  Sequential reads (with OGR_L_GetNextFeature()) are generally considered interrupted by a
    1008             :  OGR_L_GetFeature() call.
    1009             : 
    1010             :  The returned feature should be free with OGR_F_Destroy().
    1011             : 
    1012             :  This function is the same as the C++ method OGRLayer::GetFeature( ).
    1013             : 
    1014             :  @param hLayer handle to the layer that owned the feature.
    1015             :  @param nFeatureId the feature id of the feature to read.
    1016             : 
    1017             :  @return a handle to a feature now owned by the caller, or NULL on failure.
    1018             : */
    1019             : 
    1020        2621 : OGRFeatureH OGR_L_GetFeature(OGRLayerH hLayer, GIntBig nFeatureId)
    1021             : 
    1022             : {
    1023        2621 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetFeature", nullptr);
    1024             : 
    1025             : #ifdef OGRAPISPY_ENABLED
    1026        2621 :     if (bOGRAPISpyEnabled)
    1027           2 :         OGRAPISpy_L_GetFeature(hLayer, nFeatureId);
    1028             : #endif
    1029             : 
    1030        2621 :     return OGRFeature::ToHandle(
    1031        5242 :         OGRLayer::FromHandle(hLayer)->GetFeature(nFeatureId));
    1032             : }
    1033             : 
    1034             : /************************************************************************/
    1035             : /*                           SetNextByIndex()                           */
    1036             : /************************************************************************/
    1037             : 
    1038             : /**
    1039             :  \brief Move read cursor to the nIndex'th feature in the current resultset.
    1040             : 
    1041             :  This method allows positioning of a layer such that the GetNextFeature()
    1042             :  call will read the requested feature, where nIndex is an absolute index
    1043             :  into the current result set.   So, setting it to 3 would mean the next
    1044             :  feature read with GetNextFeature() would have been the 4th feature to have
    1045             :  been read if sequential reading took place from the beginning of the layer,
    1046             :  including accounting for spatial and attribute filters.
    1047             : 
    1048             :  Only in rare circumstances is SetNextByIndex() efficiently implemented.
    1049             :  In all other cases the default implementation which calls ResetReading()
    1050             :  and then calls GetNextFeature() nIndex times is used.  To determine if
    1051             :  fast seeking is available on the current layer use the TestCapability()
    1052             :  method with a value of OLCFastSetNextByIndex.
    1053             : 
    1054             :  Starting with GDAL 3.12, when implementations can detect that nIndex is
    1055             :  invalid (at the minimum all should detect negative indices), they should
    1056             :  return OGRERR_NON_EXISTING_FEATURE, and following calls to GetNextFeature()
    1057             :  should return nullptr, until ResetReading() or a valid call to
    1058             :  SetNextByIndex() is done.
    1059             : 
    1060             :  This method is the same as the C function OGR_L_SetNextByIndex().
    1061             : 
    1062             :  @param nIndex the index indicating how many steps into the result set
    1063             :  to seek.
    1064             : 
    1065             :  @return OGRERR_NONE on success or an error code.
    1066             : */
    1067             : 
    1068        1265 : OGRErr OGRLayer::SetNextByIndex(GIntBig nIndex)
    1069             : 
    1070             : {
    1071        1265 :     if (nIndex < 0)
    1072         278 :         nIndex = GINTBIG_MAX;
    1073             : 
    1074        1265 :     ResetReading();
    1075             : 
    1076      133456 :     while (nIndex-- > 0)
    1077             :     {
    1078      132747 :         auto poFeature = std::unique_ptr<OGRFeature>(GetNextFeature());
    1079      132747 :         if (poFeature == nullptr)
    1080         556 :             return OGRERR_NON_EXISTING_FEATURE;
    1081             :     }
    1082             : 
    1083         709 :     return OGRERR_NONE;
    1084             : }
    1085             : 
    1086             : /************************************************************************/
    1087             : /*                        OGR_L_SetNextByIndex()                        */
    1088             : /************************************************************************/
    1089             : 
    1090             : /**
    1091             :  \brief Move read cursor to the nIndex'th feature in the current resultset.
    1092             : 
    1093             :  This method allows positioning of a layer such that the GetNextFeature()
    1094             :  call will read the requested feature, where nIndex is an absolute index
    1095             :  into the current result set.   So, setting it to 3 would mean the next
    1096             :  feature read with GetNextFeature() would have been the 4th feature to have
    1097             :  been read if sequential reading took place from the beginning of the layer,
    1098             :  including accounting for spatial and attribute filters.
    1099             : 
    1100             :  Only in rare circumstances is SetNextByIndex() efficiently implemented.
    1101             :  In all other cases the default implementation which calls ResetReading()
    1102             :  and then calls GetNextFeature() nIndex times is used.  To determine if
    1103             :  fast seeking is available on the current layer use the TestCapability()
    1104             :  method with a value of OLCFastSetNextByIndex.
    1105             : 
    1106             :  Starting with GDAL 3.12, when implementations can detect that nIndex is
    1107             :  invalid (at the minimum all should detect negative indices), they should
    1108             :  return OGRERR_NON_EXISTING_FEATURE, and following calls to GetNextFeature()
    1109             :  should return nullptr, until ResetReading() or a valid call to
    1110             :  SetNextByIndex() is done.
    1111             : 
    1112             :  This method is the same as the C++ method OGRLayer::SetNextByIndex()
    1113             : 
    1114             :  @param hLayer handle to the layer
    1115             :  @param nIndex the index indicating how many steps into the result set
    1116             :  to seek.
    1117             : 
    1118             :  @return OGRERR_NONE on success or an error code.
    1119             : */
    1120             : 
    1121          41 : OGRErr OGR_L_SetNextByIndex(OGRLayerH hLayer, GIntBig nIndex)
    1122             : 
    1123             : {
    1124          41 :     VALIDATE_POINTER1(hLayer, "OGR_L_SetNextByIndex", OGRERR_INVALID_HANDLE);
    1125             : 
    1126             : #ifdef OGRAPISPY_ENABLED
    1127          41 :     if (bOGRAPISpyEnabled)
    1128           2 :         OGRAPISpy_L_SetNextByIndex(hLayer, nIndex);
    1129             : #endif
    1130             : 
    1131          41 :     return OGRLayer::FromHandle(hLayer)->SetNextByIndex(nIndex);
    1132             : }
    1133             : 
    1134             : /************************************************************************/
    1135             : /*                      OGRLayer::GetNextFeature()                      */
    1136             : /************************************************************************/
    1137             : 
    1138             : /**
    1139             :  \fn OGRFeature *OGRLayer::GetNextFeature();
    1140             : 
    1141             :  \brief Fetch the next available feature from this layer.
    1142             : 
    1143             :  The returned feature becomes the responsibility of the caller to
    1144             :  delete with OGRFeature::DestroyFeature(). It is critical that all
    1145             :  features associated with an OGRLayer (more specifically an
    1146             :  OGRFeatureDefn) be deleted before that layer/datasource is deleted.
    1147             : 
    1148             :  Only features matching the current spatial filter (set with
    1149             :  SetSpatialFilter()) will be returned.
    1150             : 
    1151             :  This method implements sequential access to the features of a layer.  The
    1152             :  ResetReading() method can be used to start at the beginning again.
    1153             : 
    1154             :  Starting with GDAL 3.6, it is possible to retrieve them by batches, with a
    1155             :  column-oriented memory layout, using the GetArrowStream() method.
    1156             : 
    1157             :  Features returned by GetNextFeature() may or may not be affected by
    1158             :  concurrent modifications depending on drivers. A guaranteed way of seeing
    1159             :  modifications in effect is to call ResetReading() on layers where
    1160             :  GetNextFeature() has been called, before reading again.  Structural changes
    1161             :  in layers (field addition, deletion, ...) when a read is in progress may or
    1162             :  may not be possible depending on drivers.  If a transaction is
    1163             :  committed/aborted, the current sequential reading may or may not be valid
    1164             :  after that operation and a call to ResetReading() might be needed.
    1165             : 
    1166             :  This method is the same as the C function OGR_L_GetNextFeature().
    1167             : 
    1168             :  @return a feature, or NULL if no more features are available.
    1169             : 
    1170             : */
    1171             : 
    1172             : /************************************************************************/
    1173             : /*                        OGR_L_GetNextFeature()                        */
    1174             : /************************************************************************/
    1175             : 
    1176             : /**
    1177             :  \brief Fetch the next available feature from this layer.
    1178             : 
    1179             :  The returned feature becomes the responsibility of the caller to
    1180             :  delete with OGR_F_Destroy().  It is critical that all features
    1181             :  associated with an OGRLayer (more specifically an OGRFeatureDefn) be
    1182             :  deleted before that layer/datasource is deleted.
    1183             : 
    1184             :  Only features matching the current spatial filter (set with
    1185             :  SetSpatialFilter()) will be returned.
    1186             : 
    1187             :  This function implements sequential access to the features of a layer.
    1188             :  The OGR_L_ResetReading() function can be used to start at the beginning
    1189             :  again.
    1190             : 
    1191             :  Starting with GDAL 3.6, it is possible to retrieve them by batches, with a
    1192             :  column-oriented memory layout, using the OGR_L_GetArrowStream() function.
    1193             : 
    1194             :  Features returned by OGR_GetNextFeature() may or may not be affected by
    1195             :  concurrent modifications depending on drivers. A guaranteed way of seeing
    1196             :  modifications in effect is to call OGR_L_ResetReading() on layers where
    1197             :  OGR_GetNextFeature() has been called, before reading again.  Structural
    1198             :  changes in layers (field addition, deletion, ...) when a read is in progress
    1199             :  may or may not be possible depending on drivers.  If a transaction is
    1200             :  committed/aborted, the current sequential reading may or may not be valid
    1201             :  after that operation and a call to OGR_L_ResetReading() might be needed.
    1202             : 
    1203             :  This function is the same as the C++ method OGRLayer::GetNextFeature().
    1204             : 
    1205             :  @param hLayer handle to the layer from which feature are read.
    1206             :  @return a handle to a feature, or NULL if no more features are available.
    1207             : 
    1208             : */
    1209             : 
    1210       95523 : OGRFeatureH OGR_L_GetNextFeature(OGRLayerH hLayer)
    1211             : 
    1212             : {
    1213       95523 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetNextFeature", nullptr);
    1214             : 
    1215             : #ifdef OGRAPISPY_ENABLED
    1216       95523 :     if (bOGRAPISpyEnabled)
    1217           8 :         OGRAPISpy_L_GetNextFeature(hLayer);
    1218             : #endif
    1219             : 
    1220       95523 :     return OGRFeature::ToHandle(OGRLayer::FromHandle(hLayer)->GetNextFeature());
    1221             : }
    1222             : 
    1223             : /************************************************************************/
    1224             : /*                      ConvertGeomsIfNecessary()                       */
    1225             : /************************************************************************/
    1226             : 
    1227     1020940 : void OGRLayer::ConvertGeomsIfNecessary(OGRFeature *poFeature)
    1228             : {
    1229     1020940 :     if (!m_poPrivate->m_bConvertGeomsIfNecessaryAlreadyCalled)
    1230             :     {
    1231             :         // One time initialization
    1232       10924 :         m_poPrivate->m_bConvertGeomsIfNecessaryAlreadyCalled = true;
    1233       10924 :         m_poPrivate->m_bSupportsCurve = TestCapability(OLCCurveGeometries);
    1234       10924 :         m_poPrivate->m_bSupportsM = TestCapability(OLCMeasuredGeometries);
    1235       10924 :         if (CPLTestBool(
    1236             :                 CPLGetConfigOption("OGR_APPLY_GEOM_SET_PRECISION", "FALSE")))
    1237             :         {
    1238           2 :             const auto poFeatureDefn = GetLayerDefn();
    1239           2 :             const int nGeomFieldCount = poFeatureDefn->GetGeomFieldCount();
    1240           2 :             for (int i = 0; i < nGeomFieldCount; i++)
    1241             :             {
    1242           2 :                 const double dfXYResolution = poFeatureDefn->GetGeomFieldDefn(i)
    1243           2 :                                                   ->GetCoordinatePrecision()
    1244           2 :                                                   .dfXYResolution;
    1245           4 :                 if (dfXYResolution != OGRGeomCoordinatePrecision::UNKNOWN &&
    1246           2 :                     OGRGeometryFactory::haveGEOS())
    1247             :                 {
    1248           2 :                     m_poPrivate->m_bApplyGeomSetPrecision = true;
    1249           2 :                     break;
    1250             :                 }
    1251             :             }
    1252             :         }
    1253             :     }
    1254             : 
    1255     1947250 :     if (!m_poPrivate->m_bSupportsCurve || !m_poPrivate->m_bSupportsM ||
    1256      926306 :         m_poPrivate->m_bApplyGeomSetPrecision)
    1257             :     {
    1258       94637 :         const auto poFeatureDefn = GetLayerDefn();
    1259       94637 :         const int nGeomFieldCount = poFeatureDefn->GetGeomFieldCount();
    1260      186946 :         for (int i = 0; i < nGeomFieldCount; i++)
    1261             :         {
    1262       92309 :             OGRGeometry *poGeom = poFeature->GetGeomFieldRef(i);
    1263       92309 :             if (poGeom)
    1264             :             {
    1265      108645 :                 if (!m_poPrivate->m_bSupportsM &&
    1266       19421 :                     OGR_GT_HasM(poGeom->getGeometryType()))
    1267             :                 {
    1268           5 :                     poGeom->setMeasured(FALSE);
    1269             :                 }
    1270             : 
    1271      178235 :                 if (!m_poPrivate->m_bSupportsCurve &&
    1272       89011 :                     OGR_GT_IsNonLinear(poGeom->getGeometryType()))
    1273             :                 {
    1274             :                     OGRwkbGeometryType eTargetType =
    1275          30 :                         OGR_GT_GetLinear(poGeom->getGeometryType());
    1276             :                     auto poGeomUniquePtr = OGRGeometryFactory::forceTo(
    1277          30 :                         std::unique_ptr<OGRGeometry>(
    1278             :                             poFeature->StealGeometry(i)),
    1279          30 :                         eTargetType);
    1280          30 :                     poFeature->SetGeomField(i, std::move(poGeomUniquePtr));
    1281          30 :                     poGeom = poFeature->GetGeomFieldRef(i);
    1282             :                 }
    1283             : 
    1284       89224 :                 if (poGeom && m_poPrivate->m_bApplyGeomSetPrecision)
    1285             :                 {
    1286             :                     const double dfXYResolution =
    1287           2 :                         poFeatureDefn->GetGeomFieldDefn(i)
    1288           2 :                             ->GetCoordinatePrecision()
    1289           2 :                             .dfXYResolution;
    1290           4 :                     if (dfXYResolution != OGRGeomCoordinatePrecision::UNKNOWN &&
    1291           2 :                         !poGeom->hasCurveGeometry())
    1292             :                     {
    1293           2 :                         auto poNewGeom = poGeom->SetPrecision(dfXYResolution,
    1294             :                                                               /* nFlags = */ 0);
    1295           2 :                         if (poNewGeom)
    1296             :                         {
    1297           2 :                             poFeature->SetGeomFieldDirectly(i, poNewGeom);
    1298             :                             // If there was potential further processing...
    1299             :                             // poGeom = poFeature->GetGeomFieldRef(i);
    1300             :                         }
    1301             :                     }
    1302             :                 }
    1303             :             }
    1304             :         }
    1305             :     }
    1306     1020940 : }
    1307             : 
    1308             : /************************************************************************/
    1309             : /*                             SetFeature()                             */
    1310             : /************************************************************************/
    1311             : 
    1312             : /**
    1313             :  \brief Rewrite/replace an existing feature.
    1314             : 
    1315             :  This method will write a feature to the layer, based on the feature id
    1316             :  within the OGRFeature.
    1317             : 
    1318             :  Use OGRLayer::TestCapability(OLCRandomWrite) to establish if this layer
    1319             :  supports random access writing via SetFeature().
    1320             : 
    1321             :  The way unset fields in the provided poFeature are processed is driver dependent:
    1322             :  <ul>
    1323             :  <li>
    1324             :  SQL based drivers which implement SetFeature() through SQL UPDATE will skip
    1325             :  unset fields, and thus the content of the existing feature will be preserved.
    1326             :  </li>
    1327             :  <li>
    1328             :  The shapefile driver will write a NULL value in the DBF file.
    1329             :  </li>
    1330             :  <li>
    1331             :  The GeoJSON driver will take into account unset fields to remove the corresponding
    1332             :  JSON member.
    1333             :  </li>
    1334             :  </ul>
    1335             : 
    1336             :  Drivers should specialize the ISetFeature() method.
    1337             : 
    1338             :  This method is the same as the C function OGR_L_SetFeature().
    1339             : 
    1340             :  To set a feature, but create it if it doesn't exist see OGRLayer::UpsertFeature().
    1341             : 
    1342             :  @param poFeature the feature to write.
    1343             : 
    1344             :  @return OGRERR_NONE if the operation works, otherwise an appropriate error
    1345             :  code (e.g OGRERR_NON_EXISTING_FEATURE if the feature does not exist).
    1346             : 
    1347             :  @see UpdateFeature(), CreateFeature(), UpsertFeature()
    1348             : */
    1349             : 
    1350        3200 : OGRErr OGRLayer::SetFeature(OGRFeature *poFeature)
    1351             : 
    1352             : {
    1353        3200 :     ConvertGeomsIfNecessary(poFeature);
    1354        3200 :     return ISetFeature(poFeature);
    1355             : }
    1356             : 
    1357             : /************************************************************************/
    1358             : /*                            ISetFeature()                             */
    1359             : /************************************************************************/
    1360             : 
    1361             : /**
    1362             :  \brief Rewrite/replace an existing feature.
    1363             : 
    1364             :  This method is implemented by drivers and not called directly. User code should
    1365             :  use SetFeature() instead.
    1366             : 
    1367             :  This method will write a feature to the layer, based on the feature id
    1368             :  within the OGRFeature.
    1369             : 
    1370             :  @param poFeature the feature to write.
    1371             : 
    1372             :  @return OGRERR_NONE if the operation works, otherwise an appropriate error
    1373             :  code (e.g OGRERR_NON_EXISTING_FEATURE if the feature does not exist).
    1374             : 
    1375             :  @see SetFeature()
    1376             : */
    1377             : 
    1378         228 : OGRErr OGRLayer::ISetFeature(OGRFeature *poFeature)
    1379             : 
    1380             : {
    1381             :     (void)poFeature;
    1382         228 :     return OGRERR_UNSUPPORTED_OPERATION;
    1383             : }
    1384             : 
    1385             : /************************************************************************/
    1386             : /*                          OGR_L_SetFeature()                          */
    1387             : /************************************************************************/
    1388             : 
    1389             : /**
    1390             :  \brief Rewrite/replace an existing feature.
    1391             : 
    1392             :  This function will write a feature to the layer, based on the feature id
    1393             :  within the OGRFeature.
    1394             : 
    1395             :  Use OGR_L_TestCapability(OLCRandomWrite) to establish if this layer
    1396             :  supports random access writing via OGR_L_SetFeature().
    1397             : 
    1398             :  The way unset fields in the provided poFeature are processed is driver dependent:
    1399             :  <ul>
    1400             :  <li>
    1401             :  SQL based drivers which implement SetFeature() through SQL UPDATE will skip
    1402             :  unset fields, and thus the content of the existing feature will be preserved.
    1403             :  </li>
    1404             :  <li>
    1405             :  The shapefile driver will write a NULL value in the DBF file.
    1406             :  </li>
    1407             :  <li>
    1408             :  The GeoJSON driver will take into account unset fields to remove the corresponding
    1409             :  JSON member.
    1410             :  </li>
    1411             :  </ul>
    1412             : 
    1413             :  This function is the same as the C++ method OGRLayer::SetFeature().
    1414             : 
    1415             :  To set a feature, but create it if it doesn't exist see OGR_L_UpsertFeature().
    1416             : 
    1417             :  @param hLayer handle to the layer to write the feature.
    1418             :  @param hFeat the feature to write.
    1419             : 
    1420             :  @return OGRERR_NONE if the operation works, otherwise an appropriate error
    1421             :  code (e.g OGRERR_NON_EXISTING_FEATURE if the feature does not exist).
    1422             : 
    1423             :  @see OGR_L_UpdateFeature(), OGR_L_CreateFeature(), OGR_L_UpsertFeature()
    1424             : */
    1425             : 
    1426        2480 : OGRErr OGR_L_SetFeature(OGRLayerH hLayer, OGRFeatureH hFeat)
    1427             : 
    1428             : {
    1429        2480 :     VALIDATE_POINTER1(hLayer, "OGR_L_SetFeature", OGRERR_INVALID_HANDLE);
    1430        2480 :     VALIDATE_POINTER1(hFeat, "OGR_L_SetFeature", OGRERR_INVALID_HANDLE);
    1431             : 
    1432             : #ifdef OGRAPISPY_ENABLED
    1433        2480 :     if (bOGRAPISpyEnabled)
    1434           2 :         OGRAPISpy_L_SetFeature(hLayer, hFeat);
    1435             : #endif
    1436             : 
    1437        2480 :     return OGRLayer::FromHandle(hLayer)->SetFeature(
    1438        2480 :         OGRFeature::FromHandle(hFeat));
    1439             : }
    1440             : 
    1441             : /************************************************************************/
    1442             : /*                             SetFeature()                             */
    1443             : /************************************************************************/
    1444             : 
    1445             : /**
    1446             :  \brief Rewrite/replace an existing feature, transferring ownership
    1447             :         of the feature to the layer
    1448             : 
    1449             :  This method will write a feature to the layer, based on the feature id
    1450             :  within the OGRFeature.
    1451             : 
    1452             :  Use OGRLayer::TestCapability(OLCRandomWrite) to establish if this layer
    1453             :  supports random access writing via SetFeature().
    1454             : 
    1455             :  The way unset fields in the provided poFeature are processed is driver dependent:
    1456             :  <ul>
    1457             :  <li>
    1458             :  SQL based drivers which implement SetFeature() through SQL UPDATE will skip
    1459             :  unset fields, and thus the content of the existing feature will be preserved.
    1460             :  </li>
    1461             :  <li>
    1462             :  The shapefile driver will write a NULL value in the DBF file.
    1463             :  </li>
    1464             :  <li>
    1465             :  The GeoJSON driver will take into account unset fields to remove the corresponding
    1466             :  JSON member.
    1467             :  </li>
    1468             :  </ul>
    1469             : 
    1470             :  Drivers should specialize the ISetFeatureUniqPtr() method.
    1471             : 
    1472             :  To set a feature, but create it if it doesn't exist see OGRLayer::UpsertFeature().
    1473             : 
    1474             :  @param poFeature the feature to write.
    1475             : 
    1476             :  @return OGRERR_NONE if the operation works, otherwise an appropriate error
    1477             :  code (e.g OGRERR_NON_EXISTING_FEATURE if the feature does not exist).
    1478             : 
    1479             :  @see UpdateFeature(), CreateFeature(), UpsertFeature()
    1480             :  @since 3.13
    1481             : */
    1482             : 
    1483         537 : OGRErr OGRLayer::SetFeature(std::unique_ptr<OGRFeature> poFeature)
    1484             : 
    1485             : {
    1486         537 :     ConvertGeomsIfNecessary(poFeature.get());
    1487         537 :     return ISetFeatureUniqPtr(std::move(poFeature));
    1488             : }
    1489             : 
    1490             : /************************************************************************/
    1491             : /*                         ISetFeatureUniqPtr()                         */
    1492             : /************************************************************************/
    1493             : 
    1494             : /**
    1495             :  \brief Rewrite/replace an existing feature, transferring ownership
    1496             :         of the feature to the layer
    1497             : 
    1498             :  WARNING: if drivers implement this method, they *MUST* also implement
    1499             :  ISetFeature()
    1500             : 
    1501             :  This method is implemented by drivers and not called directly. User code should
    1502             :  use SetFeature() instead.
    1503             : 
    1504             :  This method will write a feature to the layer, based on the feature id
    1505             :  within the OGRFeature.
    1506             : 
    1507             :  @param poFeature the feature to write.
    1508             : 
    1509             :  @return OGRERR_NONE if the operation works, otherwise an appropriate error
    1510             :  code (e.g OGRERR_NON_EXISTING_FEATURE if the feature does not exist).
    1511             : 
    1512             :  @see SetFeature()
    1513             :  @since 3.13
    1514             : */
    1515             : 
    1516           0 : OGRErr OGRLayer::ISetFeatureUniqPtr(std::unique_ptr<OGRFeature> poFeature)
    1517             : 
    1518             : {
    1519           0 :     return ISetFeature(poFeature.get());
    1520             : }
    1521             : 
    1522             : /************************************************************************/
    1523             : /*                           CreateFeature()                            */
    1524             : /************************************************************************/
    1525             : 
    1526             : /**
    1527             :  \brief Create and write a new feature within a layer.
    1528             : 
    1529             :  The passed feature is written to the layer as a new feature, rather than
    1530             :  overwriting an existing one.  If the feature has a feature id other than
    1531             :  OGRNullFID, then the native implementation may use that as the feature id
    1532             :  of the new feature, but not necessarily.  Upon successful return the
    1533             :  passed feature will have been updated with the new feature id.
    1534             : 
    1535             :  Drivers should specialize the ICreateFeature() method.
    1536             : 
    1537             :  This method is the same as the C function OGR_L_CreateFeature().
    1538             : 
    1539             :  To create a feature, but set it if it exists see OGRLayer::UpsertFeature().
    1540             : 
    1541             :  @param poFeature the feature to write to disk.
    1542             : 
    1543             :  @return OGRERR_NONE on success.
    1544             : 
    1545             :  @see SetFeature(), UpdateFeature(), UpsertFeature()
    1546             : */
    1547             : 
    1548      696397 : OGRErr OGRLayer::CreateFeature(OGRFeature *poFeature)
    1549             : 
    1550             : {
    1551      696397 :     ConvertGeomsIfNecessary(poFeature);
    1552      696397 :     return ICreateFeature(poFeature);
    1553             : }
    1554             : 
    1555             : /************************************************************************/
    1556             : /*                           ICreateFeature()                           */
    1557             : /************************************************************************/
    1558             : 
    1559             : /**
    1560             :  \brief Create and write a new feature within a layer.
    1561             : 
    1562             :  This method is implemented by drivers and not called directly. User code should
    1563             :  use CreateFeature() instead.
    1564             : 
    1565             :  The passed feature is written to the layer as a new feature, rather than
    1566             :  overwriting an existing one.  If the feature has a feature id other than
    1567             :  OGRNullFID, then the native implementation may use that as the feature id
    1568             :  of the new feature, but not necessarily.  Upon successful return the
    1569             :  passed feature will have been updated with the new feature id.
    1570             : 
    1571             :  @param poFeature the feature to write to disk.
    1572             : 
    1573             :  @return OGRERR_NONE on success.
    1574             : 
    1575             :  @see CreateFeature()
    1576             : */
    1577             : 
    1578           0 : OGRErr OGRLayer::ICreateFeature(OGRFeature *poFeature)
    1579             : 
    1580             : {
    1581             :     (void)poFeature;
    1582           0 :     return OGRERR_UNSUPPORTED_OPERATION;
    1583             : }
    1584             : 
    1585             : /************************************************************************/
    1586             : /*                        OGR_L_CreateFeature()                         */
    1587             : /************************************************************************/
    1588             : 
    1589             : /**
    1590             :  \brief Create and write a new feature within a layer.
    1591             : 
    1592             :  The passed feature is written to the layer as a new feature, rather than
    1593             :  overwriting an existing one.  If the feature has a feature id other than
    1594             :  OGRNullFID, then the native implementation may use that as the feature id
    1595             :  of the new feature, but not necessarily.  Upon successful return the
    1596             :  passed feature will have been updated with the new feature id.
    1597             : 
    1598             :  This function is the same as the C++ method OGRLayer::CreateFeature().
    1599             : 
    1600             :  To create a feature, but set it if it exists see OGR_L_UpsertFeature().
    1601             : 
    1602             :  @param hLayer handle to the layer to write the feature to.
    1603             :  @param hFeat the handle of the feature to write to disk.
    1604             : 
    1605             :  @return OGRERR_NONE on success.
    1606             : 
    1607             :  @see OGR_L_SetFeature(), OGR_L_UpdateFeature(), OGR_L_UpsertFeature()
    1608             : */
    1609             : 
    1610      300244 : OGRErr OGR_L_CreateFeature(OGRLayerH hLayer, OGRFeatureH hFeat)
    1611             : 
    1612             : {
    1613      300244 :     VALIDATE_POINTER1(hLayer, "OGR_L_CreateFeature", OGRERR_INVALID_HANDLE);
    1614      300244 :     VALIDATE_POINTER1(hFeat, "OGR_L_CreateFeature", OGRERR_INVALID_HANDLE);
    1615             : 
    1616             : #ifdef OGRAPISPY_ENABLED
    1617      300244 :     if (bOGRAPISpyEnabled)
    1618           5 :         OGRAPISpy_L_CreateFeature(hLayer, hFeat);
    1619             : #endif
    1620             : 
    1621      300244 :     return OGRLayer::FromHandle(hLayer)->CreateFeature(
    1622      300244 :         OGRFeature::FromHandle(hFeat));
    1623             : }
    1624             : 
    1625             : /************************************************************************/
    1626             : /*                           CreateFeature()                            */
    1627             : /************************************************************************/
    1628             : 
    1629             : /**
    1630             :  \brief Create and write a new feature within a layer, transferring ownership
    1631             :         of the feature to the layer
    1632             : 
    1633             :  The passed feature is written to the layer as a new feature, rather than
    1634             :  overwriting an existing one.  If the feature has a feature id other than
    1635             :  OGRNullFID, then the native implementation may use that as the feature id
    1636             :  of the new feature, but not necessarily.  Upon successful return the
    1637             :  passed feature will have been updated with the new feature id.
    1638             : 
    1639             :  Drivers should specialize the ICreateFeatureUniqPtr() method.
    1640             : 
    1641             :  To create a feature, but set it if it exists see OGRLayer::UpsertFeature().
    1642             : 
    1643             :  @param poFeature the feature to write to disk.
    1644             :  @param[out] pnFID Pointer to an integer that will receive the potentially
    1645             :              updated FID
    1646             : 
    1647             :  @return OGRERR_NONE on success.
    1648             : 
    1649             :  @see SetFeature(), UpdateFeature(), UpsertFeature()
    1650             :  @since 3.13
    1651             : */
    1652             : 
    1653      320698 : OGRErr OGRLayer::CreateFeature(std::unique_ptr<OGRFeature> poFeature,
    1654             :                                GIntBig *pnFID)
    1655             : 
    1656             : {
    1657      320698 :     ConvertGeomsIfNecessary(poFeature.get());
    1658      320698 :     return ICreateFeatureUniqPtr(std::move(poFeature), pnFID);
    1659             : }
    1660             : 
    1661             : /************************************************************************/
    1662             : /*                       ICreateFeatureUniqPtr()                        */
    1663             : /************************************************************************/
    1664             : 
    1665             : /**
    1666             :  \brief Create and write a new feature within a layer, transferring ownership
    1667             :         of the feature to the layer
    1668             : 
    1669             :  WARNING: if drivers implement this method, they *MUST* also implement
    1670             :  ICreateFeature()
    1671             : 
    1672             :  The passed feature is written to the layer as a new feature, rather than
    1673             :  overwriting an existing one.  If the feature has a feature id other than
    1674             :  OGRNullFID, then the native implementation may use that as the feature id
    1675             :  of the new feature, but not necessarily.  Upon successful return the
    1676             :  passed feature will have been updated with the new feature id.
    1677             : 
    1678             :  @param poFeature the feature to write to disk.
    1679             :  @param[out] pnFID Pointer to an integer that will receive the potentially
    1680             :              updated FID
    1681             : 
    1682             :  @return OGRERR_NONE on success.
    1683             : 
    1684             :  @see ICreateFeature()
    1685             :  @see CreateFeature(std::unique_ptr<OGRFeature> , GIntBig*)
    1686             :  @since 3.13
    1687             : */
    1688             : 
    1689          15 : OGRErr OGRLayer::ICreateFeatureUniqPtr(std::unique_ptr<OGRFeature> poFeature,
    1690             :                                        GIntBig *pnFID)
    1691             : 
    1692             : {
    1693          15 :     const OGRErr eErr = ICreateFeature(poFeature.get());
    1694          15 :     if (pnFID)
    1695           0 :         *pnFID = poFeature->GetFID();
    1696          15 :     return eErr;
    1697             : }
    1698             : 
    1699             : /************************************************************************/
    1700             : /*                           UpsertFeature()                            */
    1701             : /************************************************************************/
    1702             : 
    1703             : /**
    1704             :  \brief Rewrite/replace an existing feature or create a new feature within a layer.
    1705             : 
    1706             :  This function will write a feature to the layer, based on the feature id
    1707             :  within the OGRFeature.  If the feature id doesn't exist a new feature will be
    1708             :  written.  Otherwise, the existing feature will be rewritten.
    1709             : 
    1710             :  Use OGRLayer::TestCapability(OLCUpsertFeature) to establish if this layer
    1711             :  supports upsert writing.
    1712             : 
    1713             :  This method is the same as the C function OGR_L_UpsertFeature().
    1714             : 
    1715             :  @param poFeature the feature to write to disk.
    1716             : 
    1717             :  @return OGRERR_NONE on success.
    1718             :  @since GDAL 3.6.0
    1719             : 
    1720             :  @see SetFeature(), CreateFeature(), UpdateFeature()
    1721             : */
    1722             : 
    1723          34 : OGRErr OGRLayer::UpsertFeature(OGRFeature *poFeature)
    1724             : 
    1725             : {
    1726          34 :     ConvertGeomsIfNecessary(poFeature);
    1727          34 :     return IUpsertFeature(poFeature);
    1728             : }
    1729             : 
    1730             : /************************************************************************/
    1731             : /*                           IUpsertFeature()                           */
    1732             : /************************************************************************/
    1733             : 
    1734             : /**
    1735             :  \brief Rewrite/replace an existing feature or create a new feature within a layer.
    1736             : 
    1737             :  This method is implemented by drivers and not called directly. User code should
    1738             :  use UpsertFeature() instead.
    1739             : 
    1740             :  This function will write a feature to the layer, based on the feature id
    1741             :  within the OGRFeature.  If the feature id doesn't exist a new feature will be
    1742             :  written.  Otherwise, the existing feature will be rewritten.
    1743             : 
    1744             :  @param poFeature the feature to write to disk.
    1745             : 
    1746             :  @return OGRERR_NONE on success.
    1747             :  @since GDAL 3.6.0
    1748             : 
    1749             :  @see UpsertFeature()
    1750             : */
    1751             : 
    1752           0 : OGRErr OGRLayer::IUpsertFeature(OGRFeature *poFeature)
    1753             : {
    1754             :     (void)poFeature;
    1755           0 :     return OGRERR_UNSUPPORTED_OPERATION;
    1756             : }
    1757             : 
    1758             : /************************************************************************/
    1759             : /*                        OGR_L_UpsertFeature()                         */
    1760             : /************************************************************************/
    1761             : 
    1762             : /**
    1763             :  \brief Rewrite/replace an existing feature or create a new feature within a layer.
    1764             : 
    1765             :  This function will write a feature to the layer, based on the feature id
    1766             :  within the OGRFeature.  If the feature id doesn't exist a new feature will be
    1767             :  written.  Otherwise, the existing feature will be rewritten.
    1768             : 
    1769             :  Use OGR_L_TestCapability(OLCUpsertFeature) to establish if this layer
    1770             :  supports upsert writing.
    1771             : 
    1772             :  This function is the same as the C++ method OGRLayer::UpsertFeature().
    1773             : 
    1774             :  @param hLayer handle to the layer to write the feature to.
    1775             :  @param hFeat the handle of the feature to write to disk.
    1776             : 
    1777             :  @return OGRERR_NONE on success.
    1778             :  @since GDAL 3.6.0
    1779             : 
    1780             :  @see OGR_L_SetFeature(), OGR_L_CreateFeature(), OGR_L_UpdateFeature()
    1781             : */
    1782             : 
    1783          32 : OGRErr OGR_L_UpsertFeature(OGRLayerH hLayer, OGRFeatureH hFeat)
    1784             : 
    1785             : {
    1786          32 :     VALIDATE_POINTER1(hLayer, "OGR_L_UpsertFeature", OGRERR_INVALID_HANDLE);
    1787          32 :     VALIDATE_POINTER1(hFeat, "OGR_L_UpsertFeature", OGRERR_INVALID_HANDLE);
    1788             : 
    1789             : #ifdef OGRAPISPY_ENABLED
    1790          32 :     if (bOGRAPISpyEnabled)
    1791           0 :         OGRAPISpy_L_UpsertFeature(hLayer, hFeat);
    1792             : #endif
    1793             : 
    1794          32 :     return OGRLayer::FromHandle(hLayer)->UpsertFeature(
    1795          32 :         OGRFeature::FromHandle(hFeat));
    1796             : }
    1797             : 
    1798             : /************************************************************************/
    1799             : /*                           UpdateFeature()                            */
    1800             : /************************************************************************/
    1801             : 
    1802             : /**
    1803             :  \brief Update (part of) an existing feature.
    1804             : 
    1805             :  This method will update the specified attribute and geometry fields of a
    1806             :  feature to the layer, based on the feature id within the OGRFeature.
    1807             : 
    1808             :  Use OGRLayer::TestCapability(OLCRandomWrite) to establish if this layer
    1809             :  supports random access writing via UpdateFeature(). And to know if the
    1810             :  driver supports a dedicated/efficient UpdateFeature() method, test for the
    1811             :  OLCUpdateFeature capability.
    1812             : 
    1813             :  The way unset fields in the provided poFeature are processed is driver dependent:
    1814             :  <ul>
    1815             :  <li>
    1816             :  SQL based drivers which implement SetFeature() through SQL UPDATE will skip
    1817             :  unset fields, and thus the content of the existing feature will be preserved.
    1818             :  </li>
    1819             :  <li>
    1820             :  The shapefile driver will write a NULL value in the DBF file.
    1821             :  </li>
    1822             :  <li>
    1823             :  The GeoJSON driver will take into account unset fields to remove the corresponding
    1824             :  JSON member.
    1825             :  </li>
    1826             :  </ul>
    1827             : 
    1828             :  This method is the same as the C function OGR_L_UpdateFeature().
    1829             : 
    1830             :  To fully replace a feature, see OGRLayer::SetFeature().
    1831             : 
    1832             :  Note that after this call the content of hFeat might have changed, and will
    1833             :  *not* reflect the content you would get with GetFeature().
    1834             :  In particular for performance reasons, passed geometries might have been "stolen",
    1835             :  in particular for the default implementation of UpdateFeature() which relies
    1836             :  on GetFeature() + SetFeature().
    1837             : 
    1838             :  @param poFeature the feature to update.
    1839             : 
    1840             :  @param nUpdatedFieldsCount number of attribute fields to update. May be 0
    1841             : 
    1842             :  @param panUpdatedFieldsIdx array of nUpdatedFieldsCount values, each between
    1843             :                             0 and GetLayerDefn()->GetFieldCount() - 1, indicating
    1844             :                             which fields of poFeature must be updated in the
    1845             :                             layer.
    1846             : 
    1847             :  @param nUpdatedGeomFieldsCount number of geometry fields to update. May be 0
    1848             : 
    1849             :  @param panUpdatedGeomFieldsIdx array of nUpdatedGeomFieldsCount values, each between
    1850             :                                 0 and GetLayerDefn()->GetGeomFieldCount() - 1, indicating
    1851             :                                 which geometry fields of poFeature must be updated in the
    1852             :                                 layer.
    1853             : 
    1854             :  @param bUpdateStyleString whether the feature style string in the layer should
    1855             :                            be updated with the one of poFeature.
    1856             : 
    1857             :  @return OGRERR_NONE if the operation works, otherwise an appropriate error
    1858             :  code (e.g OGRERR_NON_EXISTING_FEATURE if the feature does not exist).
    1859             : 
    1860             :  @since GDAL 3.7
    1861             : 
    1862             :  @see UpdateFeature(), CreateFeature(), UpsertFeature()
    1863             : */
    1864             : 
    1865          75 : OGRErr OGRLayer::UpdateFeature(OGRFeature *poFeature, int nUpdatedFieldsCount,
    1866             :                                const int *panUpdatedFieldsIdx,
    1867             :                                int nUpdatedGeomFieldsCount,
    1868             :                                const int *panUpdatedGeomFieldsIdx,
    1869             :                                bool bUpdateStyleString)
    1870             : 
    1871             : {
    1872          75 :     ConvertGeomsIfNecessary(poFeature);
    1873          75 :     const int nFieldCount = GetLayerDefn()->GetFieldCount();
    1874         136 :     for (int i = 0; i < nUpdatedFieldsCount; ++i)
    1875             :     {
    1876          63 :         if (panUpdatedFieldsIdx[i] < 0 || panUpdatedFieldsIdx[i] >= nFieldCount)
    1877             :         {
    1878           2 :             CPLError(CE_Failure, CPLE_AppDefined,
    1879             :                      "Invalid panUpdatedFieldsIdx[%d] = %d", i,
    1880           2 :                      panUpdatedFieldsIdx[i]);
    1881           2 :             return OGRERR_FAILURE;
    1882             :         }
    1883             :     }
    1884          73 :     const int nGeomFieldCount = GetLayerDefn()->GetGeomFieldCount();
    1885          83 :     for (int i = 0; i < nUpdatedGeomFieldsCount; ++i)
    1886             :     {
    1887          12 :         if (panUpdatedGeomFieldsIdx[i] < 0 ||
    1888          11 :             panUpdatedGeomFieldsIdx[i] >= nGeomFieldCount)
    1889             :         {
    1890           2 :             CPLError(CE_Failure, CPLE_AppDefined,
    1891             :                      "Invalid panUpdatedGeomFieldsIdx[%d] = %d", i,
    1892           2 :                      panUpdatedGeomFieldsIdx[i]);
    1893           2 :             return OGRERR_FAILURE;
    1894             :         }
    1895             :     }
    1896          71 :     return IUpdateFeature(poFeature, nUpdatedFieldsCount, panUpdatedFieldsIdx,
    1897             :                           nUpdatedGeomFieldsCount, panUpdatedGeomFieldsIdx,
    1898          71 :                           bUpdateStyleString);
    1899             : }
    1900             : 
    1901             : /************************************************************************/
    1902             : /*                           IUpdateFeature()                           */
    1903             : /************************************************************************/
    1904             : 
    1905             : /**
    1906             :  \brief Update (part of) an existing feature.
    1907             : 
    1908             :  This method is implemented by drivers and not called directly. User code should
    1909             :  use UpdateFeature() instead.
    1910             : 
    1911             :  @param poFeature the feature to update.
    1912             : 
    1913             :  @param nUpdatedFieldsCount number of attribute fields to update. May be 0
    1914             : 
    1915             :  @param panUpdatedFieldsIdx array of nUpdatedFieldsCount values, each between
    1916             :                             0 and GetLayerDefn()->GetFieldCount() - 1, indicating
    1917             :                             which fields of poFeature must be updated in the
    1918             :                             layer.
    1919             : 
    1920             :  @param nUpdatedGeomFieldsCount number of geometry fields to update. May be 0
    1921             : 
    1922             :  @param panUpdatedGeomFieldsIdx array of nUpdatedGeomFieldsCount values, each between
    1923             :                                 0 and GetLayerDefn()->GetGeomFieldCount() - 1, indicating
    1924             :                                 which geometry fields of poFeature must be updated in the
    1925             :                                 layer.
    1926             : 
    1927             :  @param bUpdateStyleString whether the feature style string in the layer should
    1928             :                            be updated with the one of poFeature.
    1929             : 
    1930             :  @return OGRERR_NONE if the operation works, otherwise an appropriate error
    1931             :  code (e.g OGRERR_NON_EXISTING_FEATURE if the feature does not exist).
    1932             : 
    1933             :  @since GDAL 3.7
    1934             : 
    1935             :  @see UpdateFeature()
    1936             : */
    1937             : 
    1938          28 : OGRErr OGRLayer::IUpdateFeature(OGRFeature *poFeature, int nUpdatedFieldsCount,
    1939             :                                 const int *panUpdatedFieldsIdx,
    1940             :                                 int nUpdatedGeomFieldsCount,
    1941             :                                 const int *panUpdatedGeomFieldsIdx,
    1942             :                                 bool bUpdateStyleString)
    1943             : {
    1944          28 :     if (!TestCapability(OLCRandomWrite))
    1945           0 :         return OGRERR_UNSUPPORTED_OPERATION;
    1946             : 
    1947             :     auto poFeatureExisting =
    1948          56 :         std::unique_ptr<OGRFeature>(GetFeature(poFeature->GetFID()));
    1949          28 :     if (!poFeatureExisting)
    1950           1 :         return OGRERR_NON_EXISTING_FEATURE;
    1951             : 
    1952          52 :     for (int i = 0; i < nUpdatedFieldsCount; ++i)
    1953             :     {
    1954          25 :         poFeatureExisting->SetField(
    1955          25 :             panUpdatedFieldsIdx[i],
    1956          25 :             poFeature->GetRawFieldRef(panUpdatedFieldsIdx[i]));
    1957             :     }
    1958          29 :     for (int i = 0; i < nUpdatedGeomFieldsCount; ++i)
    1959             :     {
    1960           2 :         poFeatureExisting->SetGeomFieldDirectly(
    1961           2 :             panUpdatedGeomFieldsIdx[i],
    1962           2 :             poFeature->StealGeometry(panUpdatedGeomFieldsIdx[i]));
    1963             :     }
    1964          27 :     if (bUpdateStyleString)
    1965             :     {
    1966           0 :         poFeatureExisting->SetStyleString(poFeature->GetStyleString());
    1967             :     }
    1968          27 :     return ISetFeature(poFeatureExisting.get());
    1969             : }
    1970             : 
    1971             : /************************************************************************/
    1972             : /*                        OGR_L_UpdateFeature()                         */
    1973             : /************************************************************************/
    1974             : 
    1975             : /**
    1976             :  \brief Update (part of) an existing feature.
    1977             : 
    1978             :  This function will update the specified attribute and geometry fields of a
    1979             :  feature to the layer, based on the feature id within the OGRFeature.
    1980             : 
    1981             :  Use OGR_L_TestCapability(OLCRandomWrite) to establish if this layer
    1982             :  supports random access writing via UpdateFeature(). And to know if the
    1983             :  driver supports a dedicated/efficient UpdateFeature() method, test for the
    1984             :  OLCUpdateFeature capability.
    1985             : 
    1986             :  The way unset fields in the provided poFeature are processed is driver dependent:
    1987             :  <ul>
    1988             :  <li>
    1989             :  SQL based drivers which implement SetFeature() through SQL UPDATE will skip
    1990             :  unset fields, and thus the content of the existing feature will be preserved.
    1991             :  </li>
    1992             :  <li>
    1993             :  The shapefile driver will write a NULL value in the DBF file.
    1994             :  </li>
    1995             :  <li>
    1996             :  The GeoJSON driver will take into account unset fields to remove the corresponding
    1997             :  JSON member.
    1998             :  </li>
    1999             :  </ul>
    2000             : 
    2001             :  This method is the same as the C++ method OGRLayer::UpdateFeature().
    2002             : 
    2003             :  To fully replace a feature, see OGR_L_SetFeature()
    2004             : 
    2005             :  Note that after this call the content of hFeat might have changed, and will
    2006             :  *not* reflect the content you would get with OGR_L_GetFeature().
    2007             :  In particular for performance reasons, passed geometries might have been "stolen",
    2008             :  in particular for the default implementation of UpdateFeature() which relies
    2009             :  on GetFeature() + SetFeature().
    2010             : 
    2011             :  @param hLayer handle to the layer to write the feature.
    2012             : 
    2013             :  @param hFeat the feature to update.
    2014             : 
    2015             :  @param nUpdatedFieldsCount number of attribute fields to update. May be 0
    2016             : 
    2017             :  @param panUpdatedFieldsIdx array of nUpdatedFieldsCount values, each between
    2018             :                             0 and GetLayerDefn()->GetFieldCount() - 1, indicating
    2019             :                             which fields of hFeat must be updated in the
    2020             :                             layer.
    2021             : 
    2022             :  @param nUpdatedGeomFieldsCount number of geometry fields to update. May be 0
    2023             : 
    2024             :  @param panUpdatedGeomFieldsIdx array of nUpdatedGeomFieldsCount values, each between
    2025             :                                 0 and GetLayerDefn()->GetGeomFieldCount() - 1, indicating
    2026             :                                 which geometry fields of hFeat must be updated in the
    2027             :                                 layer.
    2028             : 
    2029             :  @param bUpdateStyleString whether the feature style string in the layer should
    2030             :                            be updated with the one of hFeat.
    2031             : 
    2032             :  @return OGRERR_NONE if the operation works, otherwise an appropriate error
    2033             :  code (e.g OGRERR_NON_EXISTING_FEATURE if the feature does not exist).
    2034             : 
    2035             :  @since GDAL 3.7
    2036             : 
    2037             :  @see OGR_L_UpdateFeature(), OGR_L_CreateFeature(), OGR_L_UpsertFeature()
    2038             : */
    2039             : 
    2040          31 : OGRErr OGR_L_UpdateFeature(OGRLayerH hLayer, OGRFeatureH hFeat,
    2041             :                            int nUpdatedFieldsCount,
    2042             :                            const int *panUpdatedFieldsIdx,
    2043             :                            int nUpdatedGeomFieldsCount,
    2044             :                            const int *panUpdatedGeomFieldsIdx,
    2045             :                            bool bUpdateStyleString)
    2046             : 
    2047             : {
    2048          31 :     VALIDATE_POINTER1(hLayer, "OGR_L_UpdateFeature", OGRERR_INVALID_HANDLE);
    2049          31 :     VALIDATE_POINTER1(hFeat, "OGR_L_UpdateFeature", OGRERR_INVALID_HANDLE);
    2050             : 
    2051          31 :     return OGRLayer::FromHandle(hLayer)->UpdateFeature(
    2052             :         OGRFeature::FromHandle(hFeat), nUpdatedFieldsCount, panUpdatedFieldsIdx,
    2053          31 :         nUpdatedGeomFieldsCount, panUpdatedGeomFieldsIdx, bUpdateStyleString);
    2054             : }
    2055             : 
    2056             : /************************************************************************/
    2057             : /*                            CreateField()                             */
    2058             : /************************************************************************/
    2059             : 
    2060             : /**
    2061             : \brief Create a new field on a layer.
    2062             : 
    2063             : You must use this to create new fields
    2064             : on a real layer. Internally the OGRFeatureDefn for the layer will be updated
    2065             : to reflect the new field.  Applications should never modify the OGRFeatureDefn
    2066             : used by a layer directly.
    2067             : 
    2068             : This method should not be called while there are feature objects in existence that
    2069             : were obtained or created with the previous layer definition.
    2070             : 
    2071             : Not all drivers support this method. You can query a layer to check if it supports it
    2072             : with the OLCCreateField capability. Some drivers may only support this method while
    2073             : there are still no features in the layer. When it is supported, the existing features of the
    2074             : backing file/database should be updated accordingly.
    2075             : 
    2076             : Drivers may or may not support not-null constraints. If they support creating
    2077             : fields with not-null constraints, this is generally before creating any feature to the layer.
    2078             : 
    2079             : This function is the same as the C function OGR_L_CreateField().
    2080             : 
    2081             : @param poField field definition to write to disk.
    2082             : @param bApproxOK If TRUE, the field may be created in a slightly different
    2083             : form depending on the limitations of the format driver.
    2084             : 
    2085             : @return OGRERR_NONE on success.
    2086             : */
    2087             : 
    2088          80 : OGRErr OGRLayer::CreateField(const OGRFieldDefn *poField, int bApproxOK)
    2089             : 
    2090             : {
    2091             :     (void)poField;
    2092             :     (void)bApproxOK;
    2093             : 
    2094          80 :     CPLError(CE_Failure, CPLE_NotSupported,
    2095             :              "CreateField() not supported by this layer.");
    2096             : 
    2097          80 :     return OGRERR_UNSUPPORTED_OPERATION;
    2098             : }
    2099             : 
    2100             : /************************************************************************/
    2101             : /*                         OGR_L_CreateField()                          */
    2102             : /************************************************************************/
    2103             : 
    2104             : /**
    2105             : \brief Create a new field on a layer.
    2106             : 
    2107             : You must use this to create new fields
    2108             : on a real layer. Internally the OGRFeatureDefn for the layer will be updated
    2109             : to reflect the new field.  Applications should never modify the OGRFeatureDefn
    2110             : used by a layer directly.
    2111             : 
    2112             : This function should not be called while there are feature objects in existence that
    2113             : were obtained or created with the previous layer definition.
    2114             : 
    2115             : Not all drivers support this function. You can query a layer to check if it supports it
    2116             : with the OLCCreateField capability. Some drivers may only support this method while
    2117             : there are still no features in the layer. When it is supported, the existing features of the
    2118             : backing file/database should be updated accordingly.
    2119             : 
    2120             : Drivers may or may not support not-null constraints. If they support creating
    2121             : fields with not-null constraints, this is generally before creating any feature to the layer.
    2122             : 
    2123             :  This function is the same as the C++ method OGRLayer::CreateField().
    2124             : 
    2125             :  @param hLayer handle to the layer to write the field definition.
    2126             :  @param hField handle of the field definition to write to disk.
    2127             :  @param bApproxOK If TRUE, the field may be created in a slightly different
    2128             : form depending on the limitations of the format driver.
    2129             : 
    2130             :  @return OGRERR_NONE on success.
    2131             : */
    2132             : 
    2133       78375 : OGRErr OGR_L_CreateField(OGRLayerH hLayer, OGRFieldDefnH hField, int bApproxOK)
    2134             : 
    2135             : {
    2136       78375 :     VALIDATE_POINTER1(hLayer, "OGR_L_CreateField", OGRERR_INVALID_HANDLE);
    2137       78375 :     VALIDATE_POINTER1(hField, "OGR_L_CreateField", OGRERR_INVALID_HANDLE);
    2138             : 
    2139             : #ifdef OGRAPISPY_ENABLED
    2140       78375 :     if (bOGRAPISpyEnabled)
    2141           6 :         OGRAPISpy_L_CreateField(hLayer, hField, bApproxOK);
    2142             : #endif
    2143             : 
    2144      156750 :     return OGRLayer::FromHandle(hLayer)->CreateField(
    2145       78375 :         OGRFieldDefn::FromHandle(hField), bApproxOK);
    2146             : }
    2147             : 
    2148             : /************************************************************************/
    2149             : /*                            DeleteField()                             */
    2150             : /************************************************************************/
    2151             : 
    2152             : /**
    2153             : \brief Delete an existing field on a layer.
    2154             : 
    2155             : You must use this to delete existing fields
    2156             : on a real layer. Internally the OGRFeatureDefn for the layer will be updated
    2157             : to reflect the deleted field.  Applications should never modify the OGRFeatureDefn
    2158             : used by a layer directly.
    2159             : 
    2160             : This method should not be called while there are feature objects in existence that
    2161             : were obtained or created with the previous layer definition.
    2162             : 
    2163             : If a OGRFieldDefn* object corresponding to the deleted field has been retrieved
    2164             : from the layer definition before the call to DeleteField(), it must no longer be
    2165             : used after the call to DeleteField(), which will have destroyed it.
    2166             : 
    2167             : Not all drivers support this method. You can query a layer to check if it supports it
    2168             : with the OLCDeleteField capability. Some drivers may only support this method while
    2169             : there are still no features in the layer. When it is supported, the existing features of the
    2170             : backing file/database should be updated accordingly.
    2171             : 
    2172             : This function is the same as the C function OGR_L_DeleteField().
    2173             : 
    2174             : @param iField index of the field to delete.
    2175             : 
    2176             : @return OGRERR_NONE on success.
    2177             : */
    2178             : 
    2179           0 : OGRErr OGRLayer::DeleteField(int iField)
    2180             : 
    2181             : {
    2182             :     (void)iField;
    2183             : 
    2184           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2185             :              "DeleteField() not supported by this layer.");
    2186             : 
    2187           0 :     return OGRERR_UNSUPPORTED_OPERATION;
    2188             : }
    2189             : 
    2190             : /************************************************************************/
    2191             : /*                         OGR_L_DeleteField()                          */
    2192             : /************************************************************************/
    2193             : 
    2194             : /**
    2195             : \brief Delete an existing field on a layer.
    2196             : 
    2197             : You must use this to delete existing fields
    2198             : on a real layer. Internally the OGRFeatureDefn for the layer will be updated
    2199             : to reflect the deleted field.  Applications should never modify the OGRFeatureDefn
    2200             : used by a layer directly.
    2201             : 
    2202             : This function should not be called while there are feature objects in existence that
    2203             : were obtained or created with the previous layer definition.
    2204             : 
    2205             : If a OGRFieldDefnH object corresponding to the deleted field has been retrieved
    2206             : from the layer definition before the call to DeleteField(), it must no longer be
    2207             : used after the call to DeleteField(), which will have destroyed it.
    2208             : 
    2209             : Not all drivers support this function. You can query a layer to check if it supports it
    2210             : with the OLCDeleteField capability. Some drivers may only support this method while
    2211             : there are still no features in the layer. When it is supported, the existing features of the
    2212             : backing file/database should be updated accordingly.
    2213             : 
    2214             : This function is the same as the C++ method OGRLayer::DeleteField().
    2215             : 
    2216             : @param hLayer handle to the layer.
    2217             : @param iField index of the field to delete.
    2218             : 
    2219             : @return OGRERR_NONE on success.
    2220             : */
    2221             : 
    2222         375 : OGRErr OGR_L_DeleteField(OGRLayerH hLayer, int iField)
    2223             : 
    2224             : {
    2225         375 :     VALIDATE_POINTER1(hLayer, "OGR_L_DeleteField", OGRERR_INVALID_HANDLE);
    2226             : 
    2227             : #ifdef OGRAPISPY_ENABLED
    2228         375 :     if (bOGRAPISpyEnabled)
    2229           2 :         OGRAPISpy_L_DeleteField(hLayer, iField);
    2230             : #endif
    2231             : 
    2232         375 :     return OGRLayer::FromHandle(hLayer)->DeleteField(iField);
    2233             : }
    2234             : 
    2235             : /************************************************************************/
    2236             : /*                           ReorderFields()                            */
    2237             : /************************************************************************/
    2238             : 
    2239             : /**
    2240             : \brief Reorder all the fields of a layer.
    2241             : 
    2242             : You must use this to reorder existing fields
    2243             : on a real layer. Internally the OGRFeatureDefn for the layer will be updated
    2244             : to reflect the reordering of the fields.  Applications should never modify the OGRFeatureDefn
    2245             : used by a layer directly.
    2246             : 
    2247             : This method should not be called while there are feature objects in existence that
    2248             : were obtained or created with the previous layer definition.
    2249             : 
    2250             : panMap is such that,for each field definition at position i after reordering,
    2251             : its position before reordering was panMap[i].
    2252             : 
    2253             : For example, let suppose the fields were "0","1","2","3","4" initially.
    2254             : ReorderFields([0,2,3,1,4]) will reorder them as "0","2","3","1","4".
    2255             : 
    2256             : Not all drivers support this method. You can query a layer to check if it supports it
    2257             : with the OLCReorderFields capability. Some drivers may only support this method while
    2258             : there are still no features in the layer. When it is supported, the existing features of the
    2259             : backing file/database should be updated accordingly.
    2260             : 
    2261             : This function is the same as the C function OGR_L_ReorderFields().
    2262             : 
    2263             : @param panMap an array of GetLayerDefn()->OGRFeatureDefn::GetFieldCount() elements which
    2264             : is a permutation of [0, GetLayerDefn()->OGRFeatureDefn::GetFieldCount()-1].
    2265             : 
    2266             : @return OGRERR_NONE on success.
    2267             : */
    2268             : 
    2269           0 : OGRErr OGRLayer::ReorderFields(int *panMap)
    2270             : 
    2271             : {
    2272             :     (void)panMap;
    2273             : 
    2274           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2275             :              "ReorderFields() not supported by this layer.");
    2276             : 
    2277           0 :     return OGRERR_UNSUPPORTED_OPERATION;
    2278             : }
    2279             : 
    2280             : /************************************************************************/
    2281             : /*                        OGR_L_ReorderFields()                         */
    2282             : /************************************************************************/
    2283             : 
    2284             : /**
    2285             : \brief Reorder all the fields of a layer.
    2286             : 
    2287             : You must use this to reorder existing fields
    2288             : on a real layer. Internally the OGRFeatureDefn for the layer will be updated
    2289             : to reflect the reordering of the fields.  Applications should never modify the OGRFeatureDefn
    2290             : used by a layer directly.
    2291             : 
    2292             : This function should not be called while there are feature objects in existence that
    2293             : were obtained or created with the previous layer definition.
    2294             : 
    2295             : panMap is such that,for each field definition at position i after reordering,
    2296             : its position before reordering was panMap[i].
    2297             : 
    2298             : For example, let suppose the fields were "0","1","2","3","4" initially.
    2299             : ReorderFields([0,2,3,1,4]) will reorder them as "0","2","3","1","4".
    2300             : 
    2301             : Not all drivers support this function. You can query a layer to check if it supports it
    2302             : with the OLCReorderFields capability. Some drivers may only support this method while
    2303             : there are still no features in the layer. When it is supported, the existing features of the
    2304             : backing file/database should be updated accordingly.
    2305             : 
    2306             : This function is the same as the C++ method OGRLayer::ReorderFields().
    2307             : 
    2308             : @param hLayer handle to the layer.
    2309             : @param panMap an array of GetLayerDefn()->OGRFeatureDefn::GetFieldCount() elements which
    2310             : is a permutation of [0, GetLayerDefn()->OGRFeatureDefn::GetFieldCount()-1].
    2311             : 
    2312             : @return OGRERR_NONE on success.
    2313             : */
    2314             : 
    2315          43 : OGRErr OGR_L_ReorderFields(OGRLayerH hLayer, int *panMap)
    2316             : 
    2317             : {
    2318          43 :     VALIDATE_POINTER1(hLayer, "OGR_L_ReorderFields", OGRERR_INVALID_HANDLE);
    2319             : 
    2320             : #ifdef OGRAPISPY_ENABLED
    2321          43 :     if (bOGRAPISpyEnabled)
    2322           2 :         OGRAPISpy_L_ReorderFields(hLayer, panMap);
    2323             : #endif
    2324             : 
    2325          43 :     return OGRLayer::FromHandle(hLayer)->ReorderFields(panMap);
    2326             : }
    2327             : 
    2328             : /************************************************************************/
    2329             : /*                            ReorderField()                            */
    2330             : /************************************************************************/
    2331             : 
    2332             : /**
    2333             : \brief Reorder an existing field on a layer.
    2334             : 
    2335             : This method is a convenience wrapper of ReorderFields() dedicated to move a single field.
    2336             : It is a non-virtual method, so drivers should implement ReorderFields() instead.
    2337             : 
    2338             : You must use this to reorder existing fields
    2339             : on a real layer. Internally the OGRFeatureDefn for the layer will be updated
    2340             : to reflect the reordering of the fields.  Applications should never modify the OGRFeatureDefn
    2341             : used by a layer directly.
    2342             : 
    2343             : This method should not be called while there are feature objects in existence that
    2344             : were obtained or created with the previous layer definition.
    2345             : 
    2346             : The field definition that was at initial position iOldFieldPos will be moved at
    2347             : position iNewFieldPos, and elements between will be shuffled accordingly.
    2348             : 
    2349             : For example, let suppose the fields were "0","1","2","3","4" initially.
    2350             : ReorderField(1, 3) will reorder them as "0","2","3","1","4".
    2351             : 
    2352             : Not all drivers support this method. You can query a layer to check if it supports it
    2353             : with the OLCReorderFields capability. Some drivers may only support this method while
    2354             : there are still no features in the layer. When it is supported, the existing features of the
    2355             : backing file/database should be updated accordingly.
    2356             : 
    2357             : This function is the same as the C function OGR_L_ReorderField().
    2358             : 
    2359             : @param iOldFieldPos previous position of the field to move. Must be in the range [0,GetFieldCount()-1].
    2360             : @param iNewFieldPos new position of the field to move. Must be in the range [0,GetFieldCount()-1].
    2361             : 
    2362             : @return OGRERR_NONE on success.
    2363             : */
    2364             : 
    2365          34 : OGRErr OGRLayer::ReorderField(int iOldFieldPos, int iNewFieldPos)
    2366             : 
    2367             : {
    2368             :     OGRErr eErr;
    2369             : 
    2370          34 :     int nFieldCount = GetLayerDefn()->GetFieldCount();
    2371             : 
    2372          34 :     if (iOldFieldPos < 0 || iOldFieldPos >= nFieldCount)
    2373             :     {
    2374           0 :         CPLError(CE_Failure, CPLE_NotSupported, "Invalid field index");
    2375           0 :         return OGRERR_FAILURE;
    2376             :     }
    2377          34 :     if (iNewFieldPos < 0 || iNewFieldPos >= nFieldCount)
    2378             :     {
    2379           0 :         CPLError(CE_Failure, CPLE_NotSupported, "Invalid field index");
    2380           0 :         return OGRERR_FAILURE;
    2381             :     }
    2382          34 :     if (iNewFieldPos == iOldFieldPos)
    2383           0 :         return OGRERR_NONE;
    2384             : 
    2385          34 :     int *panMap = static_cast<int *>(CPLMalloc(sizeof(int) * nFieldCount));
    2386          34 :     if (iOldFieldPos < iNewFieldPos)
    2387             :     {
    2388             :         /* "0","1","2","3","4" (1,3) -> "0","2","3","1","4" */
    2389          15 :         int i = 0;  // Used after for.
    2390          19 :         for (; i < iOldFieldPos; i++)
    2391           4 :             panMap[i] = i;
    2392          40 :         for (; i < iNewFieldPos; i++)
    2393          25 :             panMap[i] = i + 1;
    2394          15 :         panMap[iNewFieldPos] = iOldFieldPos;
    2395          27 :         for (i = iNewFieldPos + 1; i < nFieldCount; i++)
    2396          12 :             panMap[i] = i;
    2397             :     }
    2398             :     else
    2399             :     {
    2400             :         /* "0","1","2","3","4" (3,1) -> "0","3","1","2","4" */
    2401          23 :         for (int i = 0; i < iNewFieldPos; i++)
    2402           4 :             panMap[i] = i;
    2403          19 :         panMap[iNewFieldPos] = iOldFieldPos;
    2404          19 :         int i = iNewFieldPos + 1;  // Used after for.
    2405          67 :         for (; i <= iOldFieldPos; i++)
    2406          48 :             panMap[i] = i - 1;
    2407          31 :         for (; i < nFieldCount; i++)
    2408          12 :             panMap[i] = i;
    2409             :     }
    2410             : 
    2411          34 :     eErr = ReorderFields(panMap);
    2412             : 
    2413          34 :     CPLFree(panMap);
    2414             : 
    2415          34 :     return eErr;
    2416             : }
    2417             : 
    2418             : /************************************************************************/
    2419             : /*                         OGR_L_ReorderField()                         */
    2420             : /************************************************************************/
    2421             : 
    2422             : /**
    2423             : \brief Reorder an existing field on a layer.
    2424             : 
    2425             : This function is a convenience wrapper of OGR_L_ReorderFields() dedicated to move a single field.
    2426             : 
    2427             : You must use this to reorder existing fields
    2428             : on a real layer. Internally the OGRFeatureDefn for the layer will be updated
    2429             : to reflect the reordering of the fields.  Applications should never modify the OGRFeatureDefn
    2430             : used by a layer directly.
    2431             : 
    2432             : This function should not be called while there are feature objects in existence that
    2433             : were obtained or created with the previous layer definition.
    2434             : 
    2435             : The field definition that was at initial position iOldFieldPos will be moved at
    2436             : position iNewFieldPos, and elements between will be shuffled accordingly.
    2437             : 
    2438             : For example, let suppose the fields were "0","1","2","3","4" initially.
    2439             : ReorderField(1, 3) will reorder them as "0","2","3","1","4".
    2440             : 
    2441             : Not all drivers support this function. You can query a layer to check if it supports it
    2442             : with the OLCReorderFields capability. Some drivers may only support this method while
    2443             : there are still no features in the layer. When it is supported, the existing features of the
    2444             : backing file/database should be updated accordingly.
    2445             : 
    2446             : This function is the same as the C++ method OGRLayer::ReorderField().
    2447             : 
    2448             : @param hLayer handle to the layer.
    2449             : @param iOldFieldPos previous position of the field to move. Must be in the range [0,GetFieldCount()-1].
    2450             : @param iNewFieldPos new position of the field to move. Must be in the range [0,GetFieldCount()-1].
    2451             : 
    2452             : @return OGRERR_NONE on success.
    2453             : */
    2454             : 
    2455          34 : OGRErr OGR_L_ReorderField(OGRLayerH hLayer, int iOldFieldPos, int iNewFieldPos)
    2456             : 
    2457             : {
    2458          34 :     VALIDATE_POINTER1(hLayer, "OGR_L_ReorderField", OGRERR_INVALID_HANDLE);
    2459             : 
    2460             : #ifdef OGRAPISPY_ENABLED
    2461          34 :     if (bOGRAPISpyEnabled)
    2462           2 :         OGRAPISpy_L_ReorderField(hLayer, iOldFieldPos, iNewFieldPos);
    2463             : #endif
    2464             : 
    2465          34 :     return OGRLayer::FromHandle(hLayer)->ReorderField(iOldFieldPos,
    2466          34 :                                                       iNewFieldPos);
    2467             : }
    2468             : 
    2469             : /************************************************************************/
    2470             : /*                           AlterFieldDefn()                           */
    2471             : /************************************************************************/
    2472             : 
    2473             : /**
    2474             : \brief Alter the definition of an existing field on a layer.
    2475             : 
    2476             : You must use this to alter the definition of an existing field of a real layer.
    2477             : Internally the OGRFeatureDefn for the layer will be updated
    2478             : to reflect the altered field.  Applications should never modify the OGRFeatureDefn
    2479             : used by a layer directly.
    2480             : 
    2481             : This method should not be called while there are feature objects in existence that
    2482             : were obtained or created with the previous layer definition.
    2483             : 
    2484             : Not all drivers support this method. You can query a layer to check if it supports it
    2485             : with the OLCAlterFieldDefn capability. Some drivers may only support this method while
    2486             : there are still no features in the layer. When it is supported, the existing features of the
    2487             : backing file/database should be updated accordingly. Some drivers might also not support
    2488             : all update flags.
    2489             : 
    2490             : This function is the same as the C function OGR_L_AlterFieldDefn().
    2491             : 
    2492             : @param iField index of the field whose definition must be altered.
    2493             : @param poNewFieldDefn new field definition
    2494             : @param nFlagsIn combination of ALTER_NAME_FLAG, ALTER_TYPE_FLAG, ALTER_WIDTH_PRECISION_FLAG,
    2495             : ALTER_NULLABLE_FLAG and ALTER_DEFAULT_FLAG
    2496             : to indicate which of the name and/or type and/or width and precision fields and/or nullability from the new field
    2497             : definition must be taken into account.
    2498             : 
    2499             : @return OGRERR_NONE on success.
    2500             : */
    2501             : 
    2502           0 : OGRErr OGRLayer::AlterFieldDefn(int iField, OGRFieldDefn *poNewFieldDefn,
    2503             :                                 int nFlagsIn)
    2504             : 
    2505             : {
    2506             :     (void)iField;
    2507             :     (void)poNewFieldDefn;
    2508             :     (void)nFlagsIn;
    2509           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2510             :              "AlterFieldDefn() not supported by this layer.");
    2511             : 
    2512           0 :     return OGRERR_UNSUPPORTED_OPERATION;
    2513             : }
    2514             : 
    2515             : /************************************************************************/
    2516             : /*                        OGR_L_AlterFieldDefn()                        */
    2517             : /************************************************************************/
    2518             : 
    2519             : /**
    2520             : \brief Alter the definition of an existing field on a layer.
    2521             : 
    2522             : You must use this to alter the definition of an existing field of a real layer.
    2523             : Internally the OGRFeatureDefn for the layer will be updated
    2524             : to reflect the altered field.  Applications should never modify the OGRFeatureDefn
    2525             : used by a layer directly.
    2526             : 
    2527             : This function should not be called while there are feature objects in existence that
    2528             : were obtained or created with the previous layer definition.
    2529             : 
    2530             : Not all drivers support this function. You can query a layer to check if it supports it
    2531             : with the OLCAlterFieldDefn capability. Some drivers may only support this method while
    2532             : there are still no features in the layer. When it is supported, the existing features of the
    2533             : backing file/database should be updated accordingly. Some drivers might also not support
    2534             : all update flags.
    2535             : 
    2536             : This function is the same as the C++ method OGRLayer::AlterFieldDefn().
    2537             : 
    2538             : @param hLayer handle to the layer.
    2539             : @param iField index of the field whose definition must be altered.
    2540             : @param hNewFieldDefn new field definition
    2541             : @param nFlags combination of ALTER_NAME_FLAG, ALTER_TYPE_FLAG, ALTER_WIDTH_PRECISION_FLAG,
    2542             : ALTER_NULLABLE_FLAG and ALTER_DEFAULT_FLAG
    2543             : to indicate which of the name and/or type and/or width and precision fields and/or nullability from the new field
    2544             : definition must be taken into account.
    2545             : 
    2546             : @return OGRERR_NONE on success.
    2547             : */
    2548             : 
    2549         130 : OGRErr OGR_L_AlterFieldDefn(OGRLayerH hLayer, int iField,
    2550             :                             OGRFieldDefnH hNewFieldDefn, int nFlags)
    2551             : 
    2552             : {
    2553         130 :     VALIDATE_POINTER1(hLayer, "OGR_L_AlterFieldDefn", OGRERR_INVALID_HANDLE);
    2554         130 :     VALIDATE_POINTER1(hNewFieldDefn, "OGR_L_AlterFieldDefn",
    2555             :                       OGRERR_INVALID_HANDLE);
    2556             : 
    2557             : #ifdef OGRAPISPY_ENABLED
    2558         130 :     if (bOGRAPISpyEnabled)
    2559           2 :         OGRAPISpy_L_AlterFieldDefn(hLayer, iField, hNewFieldDefn, nFlags);
    2560             : #endif
    2561             : 
    2562         260 :     return OGRLayer::FromHandle(hLayer)->AlterFieldDefn(
    2563         130 :         iField, OGRFieldDefn::FromHandle(hNewFieldDefn), nFlags);
    2564             : }
    2565             : 
    2566             : /************************************************************************/
    2567             : /*                         AlterGeomFieldDefn()                         */
    2568             : /************************************************************************/
    2569             : 
    2570             : /**
    2571             : \brief Alter the definition of an existing geometry field on a layer.
    2572             : 
    2573             : You must use this to alter the definition of an existing geometry field of a real layer.
    2574             : Internally the OGRFeatureDefn for the layer will be updated
    2575             : to reflect the altered field.  Applications should never modify the OGRFeatureDefn
    2576             : used by a layer directly.
    2577             : 
    2578             : Note that altering the SRS does *not* cause coordinate reprojection to occur:
    2579             : this is simply a modification of the layer metadata (correcting a wrong SRS
    2580             : definition). No modification to existing geometries will ever be performed,
    2581             : so this method cannot be used to e.g. promote single part geometries to their
    2582             : multipart equivalents.
    2583             : 
    2584             : This method should not be called while there are feature objects in existence that
    2585             : were obtained or created with the previous layer definition.
    2586             : 
    2587             : Not all drivers support this method. You can query a layer to check if it supports it
    2588             : with the OLCAlterGeomFieldDefn capability. Some drivers might not support
    2589             : all update flags. The GDAL_DMD_ALTER_GEOM_FIELD_DEFN_FLAGS driver metadata item
    2590             : can be queried to examine which flags may be supported by a driver.
    2591             : 
    2592             : This function is the same as the C function OGR_L_AlterGeomFieldDefn().
    2593             : 
    2594             : @param iGeomField index of the field whose definition must be altered.
    2595             : @param poNewGeomFieldDefn new field definition
    2596             : @param nFlagsIn combination of ALTER_GEOM_FIELD_DEFN_NAME_FLAG, ALTER_GEOM_FIELD_DEFN_TYPE_FLAG, ALTER_GEOM_FIELD_DEFN_NULLABLE_FLAG, ALTER_GEOM_FIELD_DEFN_SRS_FLAG, ALTER_GEOM_FIELD_DEFN_SRS_COORD_EPOCH_FLAG
    2597             : to indicate which of the name and/or type and/or nullability and/or SRS and/or coordinate epoch from the new field
    2598             : definition must be taken into account. Or ALTER_GEOM_FIELD_DEFN_ALL_FLAG to update all members.
    2599             : 
    2600             : @return OGRERR_NONE on success.
    2601             : 
    2602             : @since OGR 3.6.0
    2603             : */
    2604             : 
    2605           0 : OGRErr OGRLayer::AlterGeomFieldDefn(int iGeomField,
    2606             :                                     const OGRGeomFieldDefn *poNewGeomFieldDefn,
    2607             :                                     int nFlagsIn)
    2608             : 
    2609             : {
    2610             :     (void)iGeomField;
    2611             :     (void)poNewGeomFieldDefn;
    2612             :     (void)nFlagsIn;
    2613             : 
    2614           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2615             :              "AlterGeomFieldDefn() not supported by this layer.");
    2616             : 
    2617           0 :     return OGRERR_UNSUPPORTED_OPERATION;
    2618             : }
    2619             : 
    2620             : /************************************************************************/
    2621             : /*                      OGR_L_AlterGeomFieldDefn()                      */
    2622             : /************************************************************************/
    2623             : 
    2624             : /**
    2625             : \brief Alter the definition of an existing geometry field on a layer.
    2626             : 
    2627             : You must use this to alter the definition of an existing geometry field of a real layer.
    2628             : Internally the OGRFeatureDefn for the layer will be updated
    2629             : to reflect the altered field.  Applications should never modify the OGRFeatureDefn
    2630             : used by a layer directly.
    2631             : 
    2632             : Note that altering the SRS does *not* cause coordinate reprojection to occur:
    2633             : this is simply a modification of the layer metadata (correcting a wrong SRS
    2634             : definition). No modification to existing geometries will ever be performed,
    2635             : so this method cannot be used to e.g. promote single part geometries to their
    2636             : multipart equivalents.
    2637             : 
    2638             : This function should not be called while there are feature objects in existence that
    2639             : were obtained or created with the previous layer definition.
    2640             : 
    2641             : Not all drivers support this function. You can query a layer to check if it supports it
    2642             : with the OLCAlterGeomFieldDefn capability. Some drivers might not support
    2643             : all update flags. The GDAL_DMD_ALTER_GEOM_FIELD_DEFN_FLAGS driver metadata item
    2644             : can be queried to examine which flags may be supported by a driver.
    2645             : 
    2646             : This function is the same as the C++ method OGRLayer::AlterFieldDefn().
    2647             : 
    2648             : @param hLayer handle to the layer.
    2649             : @param iGeomField index of the field whose definition must be altered.
    2650             : @param hNewGeomFieldDefn new field definition
    2651             : @param nFlags combination of ALTER_GEOM_FIELD_DEFN_NAME_FLAG, ALTER_GEOM_FIELD_DEFN_TYPE_FLAG, ALTER_GEOM_FIELD_DEFN_NULLABLE_FLAG, ALTER_GEOM_FIELD_DEFN_SRS_FLAG, ALTER_GEOM_FIELD_DEFN_SRS_COORD_EPOCH_FLAG
    2652             : to indicate which of the name and/or type and/or nullability and/or SRS and/or coordinate epoch from the new field
    2653             : definition must be taken into account. Or ALTER_GEOM_FIELD_DEFN_ALL_FLAG to update all members.
    2654             : 
    2655             : @return OGRERR_NONE on success.
    2656             : 
    2657             : @since OGR 3.6.0
    2658             : */
    2659             : 
    2660          33 : OGRErr OGR_L_AlterGeomFieldDefn(OGRLayerH hLayer, int iGeomField,
    2661             :                                 OGRGeomFieldDefnH hNewGeomFieldDefn, int nFlags)
    2662             : 
    2663             : {
    2664          33 :     VALIDATE_POINTER1(hLayer, "OGR_L_AlterGeomFieldDefn",
    2665             :                       OGRERR_INVALID_HANDLE);
    2666          33 :     VALIDATE_POINTER1(hNewGeomFieldDefn, "OGR_L_AlterGeomFieldDefn",
    2667             :                       OGRERR_INVALID_HANDLE);
    2668             : 
    2669          66 :     return OGRLayer::FromHandle(hLayer)->AlterGeomFieldDefn(
    2670             :         iGeomField,
    2671             :         const_cast<const OGRGeomFieldDefn *>(
    2672          33 :             OGRGeomFieldDefn::FromHandle(hNewGeomFieldDefn)),
    2673          33 :         nFlags);
    2674             : }
    2675             : 
    2676             : /************************************************************************/
    2677             : /*                          CreateGeomField()                           */
    2678             : /************************************************************************/
    2679             : 
    2680             : /**
    2681             : \brief Create a new geometry field on a layer.
    2682             : 
    2683             : You must use this to create new geometry fields
    2684             : on a real layer. Internally the OGRFeatureDefn for the layer will be updated
    2685             : to reflect the new field.  Applications should never modify the OGRFeatureDefn
    2686             : used by a layer directly.
    2687             : 
    2688             : This method should not be called while there are feature objects in existence that
    2689             : were obtained or created with the previous layer definition.
    2690             : 
    2691             : Not all drivers support this method. You can query a layer to check if it supports it
    2692             : with the OLCCreateGeomField capability. Some drivers may only support this method while
    2693             : there are still no features in the layer. When it is supported, the existing features of the
    2694             : backing file/database should be updated accordingly.
    2695             : 
    2696             : Drivers may or may not support not-null constraints. If they support creating
    2697             : fields with not-null constraints, this is generally before creating any feature to the layer.
    2698             : 
    2699             : This function is the same as the C function OGR_L_CreateGeomField().
    2700             : 
    2701             : @param poField geometry field definition to write to disk.
    2702             : @param bApproxOK If TRUE, the field may be created in a slightly different
    2703             : form depending on the limitations of the format driver.
    2704             : 
    2705             : @return OGRERR_NONE on success.
    2706             : */
    2707             : 
    2708           0 : OGRErr OGRLayer::CreateGeomField(const OGRGeomFieldDefn *poField, int bApproxOK)
    2709             : 
    2710             : {
    2711             :     (void)poField;
    2712             :     (void)bApproxOK;
    2713             : 
    2714           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2715             :              "CreateGeomField() not supported by this layer.");
    2716             : 
    2717           0 :     return OGRERR_UNSUPPORTED_OPERATION;
    2718             : }
    2719             : 
    2720             : /************************************************************************/
    2721             : /*                       OGR_L_CreateGeomField()                        */
    2722             : /************************************************************************/
    2723             : 
    2724             : /**
    2725             : \brief Create a new geometry field on a layer.
    2726             : 
    2727             : You must use this to create new geometry fields
    2728             : on a real layer. Internally the OGRFeatureDefn for the layer will be updated
    2729             : to reflect the new field.  Applications should never modify the OGRFeatureDefn
    2730             : used by a layer directly.
    2731             : 
    2732             : This function should not be called while there are feature objects in existence that
    2733             : were obtained or created with the previous layer definition.
    2734             : 
    2735             : Not all drivers support this function. You can query a layer to check if it supports it
    2736             : with the OLCCreateField capability. Some drivers may only support this method while
    2737             : there are still no features in the layer. When it is supported, the existing features of the
    2738             : backing file/database should be updated accordingly.
    2739             : 
    2740             : Drivers may or may not support not-null constraints. If they support creating
    2741             : fields with not-null constraints, this is generally before creating any feature to the layer.
    2742             : 
    2743             :  This function is the same as the C++ method OGRLayer::CreateField().
    2744             : 
    2745             :  @param hLayer handle to the layer to write the field definition.
    2746             :  @param hField handle of the geometry field definition to write to disk.
    2747             :  @param bApproxOK If TRUE, the field may be created in a slightly different
    2748             : form depending on the limitations of the format driver.
    2749             : 
    2750             :  @return OGRERR_NONE on success.
    2751             : */
    2752             : 
    2753         167 : OGRErr OGR_L_CreateGeomField(OGRLayerH hLayer, OGRGeomFieldDefnH hField,
    2754             :                              int bApproxOK)
    2755             : 
    2756             : {
    2757         167 :     VALIDATE_POINTER1(hLayer, "OGR_L_CreateGeomField", OGRERR_INVALID_HANDLE);
    2758         167 :     VALIDATE_POINTER1(hField, "OGR_L_CreateGeomField", OGRERR_INVALID_HANDLE);
    2759             : 
    2760             : #ifdef OGRAPISPY_ENABLED
    2761         167 :     if (bOGRAPISpyEnabled)
    2762           2 :         OGRAPISpy_L_CreateGeomField(hLayer, hField, bApproxOK);
    2763             : #endif
    2764             : 
    2765         334 :     return OGRLayer::FromHandle(hLayer)->CreateGeomField(
    2766         167 :         OGRGeomFieldDefn::FromHandle(hField), bApproxOK);
    2767             : }
    2768             : 
    2769             : /************************************************************************/
    2770             : /*                          StartTransaction()                          */
    2771             : /************************************************************************/
    2772             : 
    2773             : /**
    2774             :  \brief For datasources which support transactions, StartTransaction creates a transaction.
    2775             : 
    2776             :  If starting the transaction fails, will return
    2777             :  OGRERR_FAILURE. Datasources which do not support transactions will
    2778             :  always return OGRERR_NONE.
    2779             : 
    2780             :  Use of this API is discouraged when the dataset offers
    2781             :  dataset level transaction with GDALDataset::StartTransaction(). The reason is
    2782             :  that most drivers can only offer transactions at dataset level, and not layer level.
    2783             :  Very few drivers really support transactions at layer scope.
    2784             : 
    2785             :  This function is the same as the C function OGR_L_StartTransaction().
    2786             : 
    2787             :  @return OGRERR_NONE on success.
    2788             : */
    2789             : 
    2790         938 : OGRErr OGRLayer::StartTransaction()
    2791             : 
    2792             : {
    2793         938 :     return OGRERR_NONE;
    2794             : }
    2795             : 
    2796             : /************************************************************************/
    2797             : /*                       OGR_L_StartTransaction()                       */
    2798             : /************************************************************************/
    2799             : 
    2800             : /**
    2801             :  \brief For datasources which support transactions, StartTransaction creates a transaction.
    2802             : 
    2803             :  If starting the transaction fails, will return
    2804             :  OGRERR_FAILURE. Datasources which do not support transactions will
    2805             :  always return OGRERR_NONE.
    2806             : 
    2807             :  Use of this API is discouraged when the dataset offers
    2808             :  dataset level transaction with GDALDataset::StartTransaction(). The reason is
    2809             :  that most drivers can only offer transactions at dataset level, and not layer level.
    2810             :  Very few drivers really support transactions at layer scope.
    2811             : 
    2812             :  This function is the same as the C++ method OGRLayer::StartTransaction().
    2813             : 
    2814             :  @param hLayer handle to the layer
    2815             : 
    2816             :  @return OGRERR_NONE on success.
    2817             : 
    2818             : */
    2819             : 
    2820         161 : OGRErr OGR_L_StartTransaction(OGRLayerH hLayer)
    2821             : 
    2822             : {
    2823         161 :     VALIDATE_POINTER1(hLayer, "OGR_L_StartTransaction", OGRERR_INVALID_HANDLE);
    2824             : 
    2825             : #ifdef OGRAPISPY_ENABLED
    2826         161 :     if (bOGRAPISpyEnabled)
    2827           2 :         OGRAPISpy_L_StartTransaction(hLayer);
    2828             : #endif
    2829             : 
    2830         161 :     return OGRLayer::FromHandle(hLayer)->StartTransaction();
    2831             : }
    2832             : 
    2833             : /************************************************************************/
    2834             : /*                         CommitTransaction()                          */
    2835             : /************************************************************************/
    2836             : 
    2837             : /**
    2838             :  \brief For datasources which support transactions, CommitTransaction commits a transaction.
    2839             : 
    2840             :  If no transaction is active, or the commit fails, will return
    2841             :  OGRERR_FAILURE. Datasources which do not support transactions will
    2842             :  always return OGRERR_NONE.
    2843             : 
    2844             :  This function is the same as the C function OGR_L_CommitTransaction().
    2845             : 
    2846             :  @return OGRERR_NONE on success.
    2847             : */
    2848             : 
    2849         889 : OGRErr OGRLayer::CommitTransaction()
    2850             : 
    2851             : {
    2852         889 :     return OGRERR_NONE;
    2853             : }
    2854             : 
    2855             : /************************************************************************/
    2856             : /*                      OGR_L_CommitTransaction()                       */
    2857             : /************************************************************************/
    2858             : 
    2859             : /**
    2860             :  \brief For datasources which support transactions, CommitTransaction commits a transaction.
    2861             : 
    2862             :  If no transaction is active, or the commit fails, will return
    2863             :  OGRERR_FAILURE. Datasources which do not support transactions will
    2864             :  always return OGRERR_NONE.
    2865             : 
    2866             :  This function is the same as the C function OGR_L_CommitTransaction().
    2867             : 
    2868             :  @return OGRERR_NONE on success.
    2869             : */
    2870             : 
    2871         141 : OGRErr OGR_L_CommitTransaction(OGRLayerH hLayer)
    2872             : 
    2873             : {
    2874         141 :     VALIDATE_POINTER1(hLayer, "OGR_L_CommitTransaction", OGRERR_INVALID_HANDLE);
    2875             : 
    2876             : #ifdef OGRAPISPY_ENABLED
    2877         141 :     if (bOGRAPISpyEnabled)
    2878           2 :         OGRAPISpy_L_CommitTransaction(hLayer);
    2879             : #endif
    2880             : 
    2881         141 :     return OGRLayer::FromHandle(hLayer)->CommitTransaction();
    2882             : }
    2883             : 
    2884             : /************************************************************************/
    2885             : /*                        RollbackTransaction()                         */
    2886             : /************************************************************************/
    2887             : 
    2888             : /**
    2889             :  \brief For datasources which support transactions, RollbackTransaction will roll back a datasource to its state before the start of the current transaction.
    2890             :  If no transaction is active, or the rollback fails, will return
    2891             :  OGRERR_FAILURE. Datasources which do not support transactions will
    2892             :  always return OGRERR_NONE.
    2893             : 
    2894             :  This function is the same as the C function OGR_L_RollbackTransaction().
    2895             : 
    2896             : 
    2897             :  OGRFeature* instances acquired or created between the StartTransaction() and RollbackTransaction() should
    2898             :  be destroyed before RollbackTransaction() if the field structure has been modified during the transaction.
    2899             : 
    2900             :  In particular, the following is invalid:
    2901             : 
    2902             :  \code
    2903             :  lyr->StartTransaction();
    2904             :  lyr->DeleteField(...);
    2905             :  f = new OGRFeature(lyr->GetLayerDefn());
    2906             :  lyr->RollbackTransaction();
    2907             :  // f is in a inconsistent state at this point, given its array of fields doesn't match
    2908             :  // the updated layer definition, and thus it cannot even be safely deleted !
    2909             :  \endcode
    2910             : 
    2911             :  Instead, the feature should be destroyed before the rollback:
    2912             : 
    2913             :  \code
    2914             :  lyr->StartTransaction();
    2915             :  lyr->DeleteField(...);
    2916             :  f = new OGRFeature(lyr->GetLayerDefn());
    2917             :  ...
    2918             :  delete f;
    2919             :  \endcode
    2920             : 
    2921             :  @return OGRERR_NONE on success.
    2922             : */
    2923             : 
    2924          52 : OGRErr OGRLayer::RollbackTransaction()
    2925             : 
    2926             : {
    2927          52 :     return OGRERR_UNSUPPORTED_OPERATION;
    2928             : }
    2929             : 
    2930             : /************************************************************************/
    2931             : /*                     OGR_L_RollbackTransaction()                      */
    2932             : /************************************************************************/
    2933             : 
    2934             : /**
    2935             :  \brief For datasources which support transactions, RollbackTransaction will roll back a datasource to its state before the start of the current transaction.
    2936             :  If no transaction is active, or the rollback fails, will return
    2937             :  OGRERR_FAILURE. Datasources which do not support transactions will
    2938             :  always return OGRERR_NONE.
    2939             : 
    2940             :  This function is the same as the C++ method OGRLayer::RollbackTransaction().
    2941             : 
    2942             :  @param hLayer handle to the layer
    2943             : 
    2944             :  @return OGRERR_NONE on success.
    2945             : */
    2946             : 
    2947          26 : OGRErr OGR_L_RollbackTransaction(OGRLayerH hLayer)
    2948             : 
    2949             : {
    2950          26 :     VALIDATE_POINTER1(hLayer, "OGR_L_RollbackTransaction",
    2951             :                       OGRERR_INVALID_HANDLE);
    2952             : 
    2953             : #ifdef OGRAPISPY_ENABLED
    2954          26 :     if (bOGRAPISpyEnabled)
    2955           2 :         OGRAPISpy_L_RollbackTransaction(hLayer);
    2956             : #endif
    2957             : 
    2958          26 :     return OGRLayer::FromHandle(hLayer)->RollbackTransaction();
    2959             : }
    2960             : 
    2961             : /************************************************************************/
    2962             : /*                       OGRLayer::GetLayerDefn()                       */
    2963             : /************************************************************************/
    2964             : 
    2965             : /**
    2966             :  \fn OGRFeatureDefn *OGRLayer::GetLayerDefn();
    2967             : 
    2968             :  \brief Fetch the schema information for this layer.
    2969             : 
    2970             :  The returned OGRFeatureDefn is owned by the OGRLayer, and should not be
    2971             :  modified or freed by the application.  It encapsulates the attribute schema
    2972             :  of the features of the layer.
    2973             : 
    2974             :  This method is the same as the C function OGR_L_GetLayerDefn().
    2975             : 
    2976             :  @return feature definition.
    2977             : */
    2978             : 
    2979             : /**
    2980             :  \fn const OGRFeatureDefn *OGRLayer::GetLayerDefn() const;
    2981             : 
    2982             :  \brief Fetch the schema information for this layer.
    2983             : 
    2984             :  The returned OGRFeatureDefn is owned by the OGRLayer, and should not be
    2985             :  modified or freed by the application.  It encapsulates the attribute schema
    2986             :  of the features of the layer.
    2987             : 
    2988             :  Note that even if this method is const, there is no guarantee it can be
    2989             :  safely called by concurrent threads on the same GDALDataset object.
    2990             : 
    2991             :  This method is the same as the C function OGR_L_GetLayerDefn().
    2992             : 
    2993             :  @return feature definition.
    2994             : 
    2995             :  @since 3.12
    2996             : */
    2997             : 
    2998             : /************************************************************************/
    2999             : /*                         OGR_L_GetLayerDefn()                         */
    3000             : /************************************************************************/
    3001             : 
    3002             : /**
    3003             :  \brief Fetch the schema information for this layer.
    3004             : 
    3005             :  The returned handle to the OGRFeatureDefn is owned by the OGRLayer,
    3006             :  and should not be modified or freed by the application.  It encapsulates
    3007             :  the attribute schema of the features of the layer.
    3008             : 
    3009             :  This function is the same as the C++ method OGRLayer::GetLayerDefn().
    3010             : 
    3011             :  @param hLayer handle to the layer to get the schema information.
    3012             :  @return a handle to the feature definition.
    3013             : 
    3014             : */
    3015      135548 : OGRFeatureDefnH OGR_L_GetLayerDefn(OGRLayerH hLayer)
    3016             : 
    3017             : {
    3018      135548 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetLayerDefn", nullptr);
    3019             : 
    3020             : #ifdef OGRAPISPY_ENABLED
    3021      135548 :     if (bOGRAPISpyEnabled)
    3022          15 :         OGRAPISpy_L_GetLayerDefn(hLayer);
    3023             : #endif
    3024             : 
    3025      135548 :     return OGRFeatureDefn::ToHandle(
    3026      135548 :         OGRLayer::FromHandle(hLayer)->GetLayerDefn());
    3027             : }
    3028             : 
    3029             : /************************************************************************/
    3030             : /*                        OGR_L_FindFieldIndex()                        */
    3031             : /************************************************************************/
    3032             : 
    3033             : /**
    3034             :  \brief Find the index of field in a layer.
    3035             : 
    3036             :  The returned number is the index of the field in the layers, or -1 if the
    3037             :  field doesn't exist.
    3038             : 
    3039             :  If bExactMatch is set to FALSE and the field doesn't exist in the given form
    3040             :  the driver might apply some changes to make it match, like those it might do
    3041             :  if the layer was created (eg. like LAUNDER in the OCI driver).
    3042             : 
    3043             :  This method is the same as the C++ method OGRLayer::FindFieldIndex().
    3044             : 
    3045             :  @return field index, or -1 if the field doesn't exist
    3046             : */
    3047             : 
    3048           2 : int OGR_L_FindFieldIndex(OGRLayerH hLayer, const char *pszFieldName,
    3049             :                          int bExactMatch)
    3050             : 
    3051             : {
    3052           2 :     VALIDATE_POINTER1(hLayer, "OGR_L_FindFieldIndex", -1);
    3053             : 
    3054             : #ifdef OGRAPISPY_ENABLED
    3055           2 :     if (bOGRAPISpyEnabled)
    3056           2 :         OGRAPISpy_L_FindFieldIndex(hLayer, pszFieldName, bExactMatch);
    3057             : #endif
    3058             : 
    3059           4 :     return OGRLayer::FromHandle(hLayer)->FindFieldIndex(pszFieldName,
    3060           2 :                                                         bExactMatch);
    3061             : }
    3062             : 
    3063             : /************************************************************************/
    3064             : /*                           FindFieldIndex()                           */
    3065             : /************************************************************************/
    3066             : 
    3067             : /**
    3068             :  \brief Find the index of field in the layer.
    3069             : 
    3070             :  The returned number is the index of the field in the layers, or -1 if the
    3071             :  field doesn't exist.
    3072             : 
    3073             :  If bExactMatch is set to FALSE and the field doesn't exist in the given form
    3074             :  the driver might apply some changes to make it match, like those it might do
    3075             :  if the layer was created (eg. like LAUNDER in the OCI driver).
    3076             : 
    3077             :  This method is the same as the C function OGR_L_FindFieldIndex().
    3078             : 
    3079             :  @return field index, or -1 if the field doesn't exist
    3080             : */
    3081             : 
    3082          83 : int OGRLayer::FindFieldIndex(const char *pszFieldName,
    3083             :                              CPL_UNUSED int bExactMatch)
    3084             : {
    3085          83 :     return GetLayerDefn()->GetFieldIndex(pszFieldName);
    3086             : }
    3087             : 
    3088             : /************************************************************************/
    3089             : /*                           GetSpatialRef()                            */
    3090             : /************************************************************************/
    3091             : 
    3092             : /**
    3093             :  \brief Fetch the spatial reference system for this layer.
    3094             : 
    3095             :  The returned object is owned by the OGRLayer and should not be modified
    3096             :  or freed by the application.
    3097             : 
    3098             :  Note that even if this method is const (since GDAL 3.12), there is no guarantee
    3099             :  it can be safely called by concurrent threads on the same GDALDataset object.
    3100             : 
    3101             :  Several geometry fields can be associated to a
    3102             :  feature definition. Each geometry field can have its own spatial reference
    3103             :  system, which is returned by OGRGeomFieldDefn::GetSpatialRef().
    3104             :  OGRLayer::GetSpatialRef() is equivalent to
    3105             :  GetLayerDefn()->OGRFeatureDefn::GetGeomFieldDefn(0)->GetSpatialRef()
    3106             : 
    3107             :  This method is the same as the C function OGR_L_GetSpatialRef().
    3108             : 
    3109             :  @return spatial reference, or NULL if there isn't one.
    3110             : */
    3111             : 
    3112      443624 : const OGRSpatialReference *OGRLayer::GetSpatialRef() const
    3113             : {
    3114      443624 :     const auto poLayerDefn = GetLayerDefn();
    3115      443624 :     if (poLayerDefn->GetGeomFieldCount() > 0)
    3116      442964 :         return poLayerDefn->GetGeomFieldDefn(0)->GetSpatialRef();
    3117             :     else
    3118         660 :         return nullptr;
    3119             : }
    3120             : 
    3121             : /************************************************************************/
    3122             : /*                        OGR_L_GetSpatialRef()                         */
    3123             : /************************************************************************/
    3124             : 
    3125             : /**
    3126             :  \brief Fetch the spatial reference system for this layer.
    3127             : 
    3128             :  The returned object is owned by the OGRLayer and should not be modified
    3129             :  or freed by the application.
    3130             : 
    3131             :  This function is the same as the C++ method OGRLayer::GetSpatialRef().
    3132             : 
    3133             :  @param hLayer handle to the layer to get the spatial reference from.
    3134             :  @return spatial reference, or NULL if there isn't one.
    3135             : */
    3136             : 
    3137        1167 : OGRSpatialReferenceH OGR_L_GetSpatialRef(OGRLayerH hLayer)
    3138             : 
    3139             : {
    3140        1167 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetSpatialRef", nullptr);
    3141             : 
    3142             : #ifdef OGRAPISPY_ENABLED
    3143        1167 :     if (bOGRAPISpyEnabled)
    3144           2 :         OGRAPISpy_L_GetSpatialRef(hLayer);
    3145             : #endif
    3146             : 
    3147        1167 :     return OGRSpatialReference::ToHandle(const_cast<OGRSpatialReference *>(
    3148        1167 :         OGRLayer::FromHandle(hLayer)->GetSpatialRef()));
    3149             : }
    3150             : 
    3151             : /************************************************************************/
    3152             : /*                      OGRLayer::TestCapability()                      */
    3153             : /************************************************************************/
    3154             : 
    3155             : /**
    3156             :  \fn bool OGRLayer::TestCapability( const char * pszCap ) const;
    3157             : 
    3158             :  \brief Test if this layer supported the named capability.
    3159             : 
    3160             :  The capability codes that can be tested are represented as strings, but
    3161             :  \#defined constants exists to ensure correct spelling.  Specific layer
    3162             :  types may implement class specific capabilities, but this can't generally
    3163             :  be discovered by the caller. <p>
    3164             : 
    3165             : <ul>
    3166             : 
    3167             :  <li> <b>OLCRandomRead</b> / "RandomRead": TRUE if the GetFeature() method
    3168             : is implemented in an optimized way for this layer, as opposed to the default
    3169             : implementation using ResetReading() and GetNextFeature() to find the requested
    3170             : feature id.<p>
    3171             : 
    3172             :  <li> <b>OLCSequentialWrite</b> / "SequentialWrite": TRUE if the
    3173             : CreateFeature() method works for this layer.  Note this means that this
    3174             : particular layer is writable.  The same OGRLayer class may return FALSE
    3175             : for other layer instances that are effectively read-only.<p>
    3176             : 
    3177             :  <li> <b>OLCRandomWrite</b> / "RandomWrite": TRUE if the SetFeature() method
    3178             : is operational on this layer.  Note this means that this
    3179             : particular layer is writable.  The same OGRLayer class may return FALSE
    3180             : for other layer instances that are effectively read-only.<p>
    3181             : 
    3182             :  <li> <b>OLCUpsertFeature</b> / "UpsertFeature": TRUE if the UpsertFeature()
    3183             : method is operational on this layer.  Note this means that this
    3184             : particular layer is writable.  The same OGRLayer class may return FALSE
    3185             : for other layer instances that are effectively read-only.<p>
    3186             : 
    3187             :  <li> <b>OLCFastSpatialFilter</b> / "FastSpatialFilter": TRUE if this layer
    3188             : implements spatial filtering efficiently.  Layers that effectively read all
    3189             : features, and test them with the OGRFeature intersection methods should
    3190             : return FALSE.  This can be used as a clue by the application whether it
    3191             : should build and maintain its own spatial index for features in this layer.<p>
    3192             : 
    3193             :  <li> <b>OLCFastFeatureCount</b> / "FastFeatureCount":
    3194             : TRUE if this layer can return a feature
    3195             : count (via GetFeatureCount()) efficiently. i.e. without counting
    3196             : the features.  In some cases this will return TRUE until a spatial filter is
    3197             : installed after which it will return FALSE.<p>
    3198             : 
    3199             :  <li> <b>OLCFastGetExtent</b> / "FastGetExtent":
    3200             : TRUE if this layer can return its data extent (via GetExtent())
    3201             : efficiently, i.e. without scanning all the features.  In some cases this
    3202             : will return TRUE until a spatial filter is installed after which it will
    3203             : return FALSE.<p>
    3204             : 
    3205             :  <li> <b>OLCFastSetNextByIndex</b> / "FastSetNextByIndex":
    3206             : TRUE if this layer can perform the SetNextByIndex() call efficiently, otherwise
    3207             : FALSE.<p>
    3208             : 
    3209             :  <li> <b>OLCCreateField</b> / "CreateField": TRUE if this layer can create
    3210             : new fields on the current layer using CreateField(), otherwise FALSE.<p>
    3211             : 
    3212             :  <li> <b>OLCCreateGeomField</b> / "CreateGeomField": (GDAL >= 1.11) TRUE if this layer can create
    3213             : new geometry fields on the current layer using CreateGeomField(), otherwise FALSE.<p>
    3214             : 
    3215             :  <li> <b>OLCDeleteField</b> / "DeleteField": TRUE if this layer can delete
    3216             : existing fields on the current layer using DeleteField(), otherwise FALSE.<p>
    3217             : 
    3218             :  <li> <b>OLCReorderFields</b> / "ReorderFields": TRUE if this layer can reorder
    3219             : existing fields on the current layer using ReorderField() or ReorderFields(), otherwise FALSE.<p>
    3220             : 
    3221             :  <li> <b>OLCAlterFieldDefn</b> / "AlterFieldDefn": TRUE if this layer can alter
    3222             : the definition of an existing field on the current layer using AlterFieldDefn(), otherwise FALSE.<p>
    3223             : 
    3224             :  <li> <b>OLCAlterGeomFieldDefn</b> / "AlterGeomFieldDefn": TRUE if this layer can alter
    3225             : the definition of an existing geometry field on the current layer using AlterGeomFieldDefn(), otherwise FALSE.<p>
    3226             : 
    3227             :  <li> <b>OLCDeleteFeature</b> / "DeleteFeature": TRUE if the DeleteFeature()
    3228             : method is supported on this layer, otherwise FALSE.<p>
    3229             : 
    3230             :  <li> <b>OLCStringsAsUTF8</b> / "StringsAsUTF8": TRUE if values of OFTString
    3231             : fields are assured to be in UTF-8 format.  If FALSE the encoding of fields
    3232             : is uncertain, though it might still be UTF-8.<p>
    3233             : 
    3234             : <li> <b>OLCTransactions</b> / "Transactions": TRUE if the StartTransaction(),
    3235             : CommitTransaction() and RollbackTransaction() methods work in a meaningful way,
    3236             : otherwise FALSE.<p>
    3237             : 
    3238             : <li> <b>OLCIgnoreFields</b> / "IgnoreFields": TRUE if fields, geometry and style
    3239             : will be omitted when fetching features as set by SetIgnoredFields() method.
    3240             : 
    3241             : <li> <b>OLCCurveGeometries</b> / "CurveGeometries": TRUE if this layer supports
    3242             : writing curve geometries or may return such geometries.
    3243             : 
    3244             : <p>
    3245             : 
    3246             : </ul>
    3247             : 
    3248             :  This method is the same as the C function OGR_L_TestCapability().
    3249             : 
    3250             :  @param pszCap the name of the capability to test.
    3251             : 
    3252             :  @return TRUE if the layer has the requested capability, or FALSE otherwise.
    3253             : OGRLayers will return FALSE for any unrecognized capabilities.<p>
    3254             : 
    3255             : */
    3256             : 
    3257             : /************************************************************************/
    3258             : /*                        OGR_L_TestCapability()                        */
    3259             : /************************************************************************/
    3260             : 
    3261             : /**
    3262             :  \brief Test if this layer supported the named capability.
    3263             : 
    3264             :  The capability codes that can be tested are represented as strings, but
    3265             :  \#defined constants exists to ensure correct spelling.  Specific layer
    3266             :  types may implement class specific capabilities, but this can't generally
    3267             :  be discovered by the caller. <p>
    3268             : 
    3269             : <ul>
    3270             : 
    3271             :  <li> <b>OLCRandomRead</b> / "RandomRead": TRUE if the GetFeature() method
    3272             : is implemented in an optimized way for this layer, as opposed to the default
    3273             : implementation using ResetReading() and GetNextFeature() to find the requested
    3274             : feature id.<p>
    3275             : 
    3276             :  <li> <b>OLCSequentialWrite</b> / "SequentialWrite": TRUE if the
    3277             : CreateFeature() method works for this layer.  Note this means that this
    3278             : particular layer is writable.  The same OGRLayer class may return FALSE
    3279             : for other layer instances that are effectively read-only.<p>
    3280             : 
    3281             :  <li> <b>OLCRandomWrite</b> / "RandomWrite": TRUE if the SetFeature() method
    3282             : is operational on this layer.  Note this means that this
    3283             : particular layer is writable.  The same OGRLayer class may return FALSE
    3284             : for other layer instances that are effectively read-only.<p>
    3285             : 
    3286             :  <li> <b>OLCUpsertFeature</b> / "UpsertFeature": TRUE if the UpsertFeature()
    3287             : method is operational on this layer.  Note this means that this
    3288             : particular layer is writable.  The same OGRLayer class may return FALSE
    3289             : for other layer instances that are effectively read-only.<p>
    3290             : 
    3291             :  <li> <b>OLCFastSpatialFilter</b> / "FastSpatialFilter": TRUE if this layer
    3292             : implements spatial filtering efficiently.  Layers that effectively read all
    3293             : features, and test them with the OGRFeature intersection methods should
    3294             : return FALSE.  This can be used as a clue by the application whether it
    3295             : should build and maintain its own spatial index for features in this
    3296             : layer.<p>
    3297             : 
    3298             :  <li> <b>OLCFastFeatureCount</b> / "FastFeatureCount":
    3299             : TRUE if this layer can return a feature
    3300             : count (via OGR_L_GetFeatureCount()) efficiently, i.e. without counting
    3301             : the features.  In some cases this will return TRUE until a spatial filter is
    3302             : installed after which it will return FALSE.<p>
    3303             : 
    3304             :  <li> <b>OLCFastGetExtent</b> / "FastGetExtent":
    3305             : TRUE if this layer can return its data extent (via OGR_L_GetExtent())
    3306             : efficiently, i.e. without scanning all the features.  In some cases this
    3307             : will return TRUE until a spatial filter is installed after which it will
    3308             : return FALSE.<p>
    3309             : 
    3310             :  <li> <b>OLCFastSetNextByIndex</b> / "FastSetNextByIndex":
    3311             : TRUE if this layer can perform the SetNextByIndex() call efficiently, otherwise
    3312             : FALSE.<p>
    3313             : 
    3314             :  <li> <b>OLCCreateField</b> / "CreateField": TRUE if this layer can create
    3315             : new fields on the current layer using CreateField(), otherwise FALSE.<p>
    3316             : 
    3317             :  <li> <b>OLCCreateGeomField</b> / "CreateGeomField": (GDAL >= 1.11) TRUE if this layer can create
    3318             : new geometry fields on the current layer using CreateGeomField(), otherwise FALSE.<p>
    3319             : 
    3320             :  <li> <b>OLCDeleteField</b> / "DeleteField": TRUE if this layer can delete
    3321             : existing fields on the current layer using DeleteField(), otherwise FALSE.<p>
    3322             : 
    3323             :  <li> <b>OLCReorderFields</b> / "ReorderFields": TRUE if this layer can reorder
    3324             : existing fields on the current layer using ReorderField() or ReorderFields(), otherwise FALSE.<p>
    3325             : 
    3326             :  <li> <b>OLCAlterFieldDefn</b> / "AlterFieldDefn": TRUE if this layer can alter
    3327             : the definition of an existing field on the current layer using AlterFieldDefn(), otherwise FALSE.<p>
    3328             : 
    3329             :  <li> <b>OLCAlterGeomFieldDefn</b> / "AlterGeomFieldDefn": TRUE if this layer can alter
    3330             : the definition of an existing geometry field on the current layer using AlterGeomFieldDefn(), otherwise FALSE.<p>
    3331             : 
    3332             :  <li> <b>OLCDeleteFeature</b> / "DeleteFeature": TRUE if the DeleteFeature()
    3333             : method is supported on this layer, otherwise FALSE.<p>
    3334             : 
    3335             :  <li> <b>OLCStringsAsUTF8</b> / "StringsAsUTF8": TRUE if values of OFTString
    3336             : fields are assured to be in UTF-8 format.  If FALSE the encoding of fields
    3337             : is uncertain, though it might still be UTF-8.<p>
    3338             : 
    3339             : <li> <b>OLCTransactions</b> / "Transactions": TRUE if the StartTransaction(),
    3340             : CommitTransaction() and RollbackTransaction() methods work in a meaningful way,
    3341             : otherwise FALSE.<p>
    3342             : 
    3343             : <li> <b>OLCCurveGeometries</b> / "CurveGeometries": TRUE if this layer supports
    3344             : writing curve geometries or may return such geometries.
    3345             : 
    3346             : <p>
    3347             : 
    3348             : </ul>
    3349             : 
    3350             :  This function is the same as the C++ method OGRLayer::TestCapability().
    3351             : 
    3352             :  @param hLayer handle to the layer to get the capability from.
    3353             :  @param pszCap the name of the capability to test.
    3354             : 
    3355             :  @return TRUE if the layer has the requested capability, or FALSE otherwise.
    3356             : OGRLayers will return FALSE for any unrecognized capabilities.<p>
    3357             : 
    3358             : */
    3359             : 
    3360        1007 : int OGR_L_TestCapability(OGRLayerH hLayer, const char *pszCap)
    3361             : 
    3362             : {
    3363        1007 :     VALIDATE_POINTER1(hLayer, "OGR_L_TestCapability", 0);
    3364        1007 :     VALIDATE_POINTER1(pszCap, "OGR_L_TestCapability", 0);
    3365             : 
    3366             : #ifdef OGRAPISPY_ENABLED
    3367        1007 :     if (bOGRAPISpyEnabled)
    3368           2 :         OGRAPISpy_L_TestCapability(hLayer, pszCap);
    3369             : #endif
    3370             : 
    3371        1007 :     return OGRLayer::FromHandle(hLayer)->TestCapability(pszCap);
    3372             : }
    3373             : 
    3374             : /************************************************************************/
    3375             : /*                          GetSpatialFilter()                          */
    3376             : /************************************************************************/
    3377             : 
    3378             : /**
    3379             :  \brief This method returns the current spatial filter for this layer.
    3380             : 
    3381             :  The returned pointer is to an internally owned object, and should not
    3382             :  be altered or deleted by the caller.
    3383             : 
    3384             :  This method is the same as the C function OGR_L_GetSpatialFilter().
    3385             : 
    3386             :  @return spatial filter geometry.
    3387             :  */
    3388             : 
    3389         519 : OGRGeometry *OGRLayer::GetSpatialFilter()
    3390             : 
    3391             : {
    3392         519 :     return m_poFilterGeom;
    3393             : }
    3394             : 
    3395             : /************************************************************************/
    3396             : /*                       OGR_L_GetSpatialFilter()                       */
    3397             : /************************************************************************/
    3398             : 
    3399             : /**
    3400             :  \brief This function returns the current spatial filter for this layer.
    3401             : 
    3402             :  The returned pointer is to an internally owned object, and should not
    3403             :  be altered or deleted by the caller.
    3404             : 
    3405             :  This function is the same as the C++ method OGRLayer::GetSpatialFilter().
    3406             : 
    3407             :  @param hLayer handle to the layer to get the spatial filter from.
    3408             :  @return a handle to the spatial filter geometry.
    3409             :  */
    3410             : 
    3411           6 : OGRGeometryH OGR_L_GetSpatialFilter(OGRLayerH hLayer)
    3412             : 
    3413             : {
    3414           6 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetSpatialFilter", nullptr);
    3415             : 
    3416             : #ifdef OGRAPISPY_ENABLED
    3417           6 :     if (bOGRAPISpyEnabled)
    3418           2 :         OGRAPISpy_L_GetSpatialFilter(hLayer);
    3419             : #endif
    3420             : 
    3421           6 :     return OGRGeometry::ToHandle(
    3422          12 :         OGRLayer::FromHandle(hLayer)->GetSpatialFilter());
    3423             : }
    3424             : 
    3425             : /************************************************************************/
    3426             : /*           ValidateGeometryFieldIndexForSetSpatialFilter()            */
    3427             : /************************************************************************/
    3428             : 
    3429             : //! @cond Doxygen_Suppress
    3430       54265 : bool OGRLayer::ValidateGeometryFieldIndexForSetSpatialFilter(
    3431             :     int iGeomField, const OGRGeometry *poGeomIn, bool bIsSelectLayer)
    3432             : {
    3433       54265 :     if (iGeomField == 0 && poGeomIn == nullptr &&
    3434           0 :         GetLayerDefn()->GetGeomFieldCount() == 0)
    3435             :     {
    3436             :         // Setting a null spatial filter on geometry field idx 0
    3437             :         // when there are no geometry field can't harm, and is accepted silently
    3438             :         // for backward compatibility with existing practice.
    3439             :     }
    3440      108224 :     else if (iGeomField < 0 ||
    3441       53959 :              iGeomField >= GetLayerDefn()->GetGeomFieldCount())
    3442             :     {
    3443         713 :         if (iGeomField == 0)
    3444             :         {
    3445          99 :             CPLError(
    3446             :                 CE_Failure, CPLE_AppDefined,
    3447             :                 bIsSelectLayer
    3448             :                     ? "Cannot set spatial filter: no geometry field selected."
    3449             :                     : "Cannot set spatial filter: no geometry field present in "
    3450             :                       "layer.");
    3451             :         }
    3452             :         else
    3453             :         {
    3454         614 :             CPLError(CE_Failure, CPLE_AppDefined,
    3455             :                      "Cannot set spatial filter on non-existing geometry field "
    3456             :                      "of index %d.",
    3457             :                      iGeomField);
    3458             :         }
    3459         713 :         return false;
    3460             :     }
    3461       53552 :     return true;
    3462             : }
    3463             : 
    3464             : //! @endcond
    3465             : 
    3466             : /************************************************************************/
    3467             : /*                          SetSpatialFilter()                          */
    3468             : /************************************************************************/
    3469             : 
    3470             : /**
    3471             :  \brief Set a new spatial filter.
    3472             : 
    3473             :  This method set the geometry to be used as a spatial filter when
    3474             :  fetching features via the GetNextFeature() method.  Only features that
    3475             :  geometrically intersect the filter geometry will be returned.
    3476             : 
    3477             :  Currently this test is may be inaccurately implemented, but it is
    3478             :  guaranteed that all features whose envelope (as returned by
    3479             :  OGRGeometry::getEnvelope()) overlaps the envelope of the spatial filter
    3480             :  will be returned.  This can result in more shapes being returned that
    3481             :  should strictly be the case.
    3482             : 
    3483             :  Features with null or empty geometries will never
    3484             :  be considered as matching a spatial filter.
    3485             : 
    3486             :  This method makes an internal copy of the passed geometry.  The
    3487             :  passed geometry remains the responsibility of the caller, and may
    3488             :  be safely destroyed.
    3489             : 
    3490             :  For the time being the passed filter geometry should be in the same
    3491             :  SRS as the layer (as returned by OGRLayer::GetSpatialRef()).  In the
    3492             :  future this may be generalized.
    3493             : 
    3494             :  This method is the same as the C function OGR_L_SetSpatialFilter().
    3495             : 
    3496             :  @param poFilter the geometry to use as a filtering region.  NULL may
    3497             :  be passed indicating that the current spatial filter should be cleared,
    3498             :  but no new one instituted.
    3499             :  */
    3500             : 
    3501        7271 : OGRErr OGRLayer::SetSpatialFilter(const OGRGeometry *poFilter)
    3502             : 
    3503             : {
    3504        7271 :     return SetSpatialFilter(0, poFilter);
    3505             : }
    3506             : 
    3507             : /**
    3508             :  \brief Set a new spatial filter.
    3509             : 
    3510             :  This method set the geometry to be used as a spatial filter when
    3511             :  fetching features via the GetNextFeature() method.  Only features that
    3512             :  geometrically intersect the filter geometry will be returned.
    3513             : 
    3514             :  Currently this test is may be inaccurately implemented, but it is
    3515             :  guaranteed that all features who's envelope (as returned by
    3516             :  OGRGeometry::getEnvelope()) overlaps the envelope of the spatial filter
    3517             :  will be returned.  This can result in more shapes being returned that
    3518             :  should strictly be the case.
    3519             : 
    3520             :  This method makes an internal copy of the passed geometry.  The
    3521             :  passed geometry remains the responsibility of the caller, and may
    3522             :  be safely destroyed.
    3523             : 
    3524             :  For the time being the passed filter geometry should be in the same
    3525             :  SRS as the geometry field definition it corresponds to (as returned by
    3526             :  GetLayerDefn()->OGRFeatureDefn::GetGeomFieldDefn(iGeomField)->GetSpatialRef()).  In the
    3527             :  future this may be generalized.
    3528             : 
    3529             :  Note that only the last spatial filter set is applied, even if several
    3530             :  successive calls are done with different iGeomField values.
    3531             : 
    3532             :  This method is the same as the C function OGR_L_SetSpatialFilterEx().
    3533             : 
    3534             :  @param iGeomField index of the geometry field on which the spatial filter
    3535             :  operates.
    3536             :  @param poFilter the geometry to use as a filtering region.  NULL may
    3537             :  be passed indicating that the current spatial filter should be cleared,
    3538             :  but no new one instituted.
    3539             :  */
    3540             : 
    3541       67193 : OGRErr OGRLayer::SetSpatialFilter(int iGeomField, const OGRGeometry *poFilter)
    3542             : 
    3543             : {
    3544       67193 :     if (iGeomField == 0)
    3545             :     {
    3546      118764 :         if (poFilter &&
    3547       52917 :             !ValidateGeometryFieldIndexForSetSpatialFilter(0, poFilter))
    3548             :         {
    3549          99 :             return OGRERR_FAILURE;
    3550             :         }
    3551             :     }
    3552             :     else
    3553             :     {
    3554        1346 :         if (!ValidateGeometryFieldIndexForSetSpatialFilter(iGeomField,
    3555             :                                                            poFilter))
    3556             :         {
    3557         614 :             return OGRERR_FAILURE;
    3558             :         }
    3559             :     }
    3560             : 
    3561       66480 :     return ISetSpatialFilter(iGeomField, poFilter);
    3562             : }
    3563             : 
    3564             : /************************************************************************/
    3565             : /*                         ISetSpatialFilter()                          */
    3566             : /************************************************************************/
    3567             : 
    3568             : /**
    3569             :  \brief Set a new spatial filter.
    3570             : 
    3571             :  Virtual method implemented by drivers since 3.11. In previous versions,
    3572             :  SetSpatialFilter() / SetSpatialFilterRect() itself was the virtual method.
    3573             : 
    3574             :  Driver implementations, when wanting to call the base method, must take
    3575             :  care of calling OGRLayer::ISetSpatialFilter() (and note the public method without
    3576             :  the leading I).
    3577             : 
    3578             :  @param iGeomField index of the geometry field on which the spatial filter
    3579             :  operates.
    3580             :  @param poFilter the geometry to use as a filtering region.  NULL may
    3581             :  be passed indicating that the current spatial filter should be cleared,
    3582             :  but no new one instituted.
    3583             : 
    3584             :  @since GDAL 3.11
    3585             :  */
    3586             : 
    3587       38420 : OGRErr OGRLayer::ISetSpatialFilter(int iGeomField, const OGRGeometry *poFilter)
    3588             : 
    3589             : {
    3590       38420 :     m_iGeomFieldFilter = iGeomField;
    3591       38420 :     if (InstallFilter(poFilter))
    3592       29577 :         ResetReading();
    3593       38420 :     return OGRERR_NONE;
    3594             : }
    3595             : 
    3596             : /************************************************************************/
    3597             : /*                       OGR_L_SetSpatialFilter()                       */
    3598             : /************************************************************************/
    3599             : 
    3600             : /**
    3601             :  \brief Set a new spatial filter.
    3602             : 
    3603             :  This function set the geometry to be used as a spatial filter when
    3604             :  fetching features via the OGR_L_GetNextFeature() function.  Only
    3605             :  features that geometrically intersect the filter geometry will be
    3606             :  returned.
    3607             : 
    3608             :  Currently this test is may be inaccurately implemented, but it is
    3609             :  guaranteed that all features whose envelope (as returned by
    3610             :  OGR_G_GetEnvelope()) overlaps the envelope of the spatial filter
    3611             :  will be returned.  This can result in more shapes being returned that
    3612             :  should strictly be the case.
    3613             : 
    3614             :  Features with null or empty geometries will never
    3615             :  be considered as matching a spatial filter.
    3616             : 
    3617             :  This function makes an internal copy of the passed geometry.  The
    3618             :  passed geometry remains the responsibility of the caller, and may
    3619             :  be safely destroyed.
    3620             : 
    3621             :  For the time being the passed filter geometry should be in the same
    3622             :  SRS as the layer (as returned by OGR_L_GetSpatialRef()).  In the
    3623             :  future this may be generalized.
    3624             : 
    3625             :  This function is the same as the C++ method OGRLayer::SetSpatialFilter.
    3626             : 
    3627             :  @param hLayer handle to the layer on which to set the spatial filter.
    3628             :  @param hGeom handle to the geometry to use as a filtering region.  NULL may
    3629             :  be passed indicating that the current spatial filter should be cleared,
    3630             :  but no new one instituted.
    3631             : 
    3632             :  */
    3633             : 
    3634         789 : void OGR_L_SetSpatialFilter(OGRLayerH hLayer, OGRGeometryH hGeom)
    3635             : 
    3636             : {
    3637         789 :     VALIDATE_POINTER0(hLayer, "OGR_L_SetSpatialFilter");
    3638             : 
    3639             : #ifdef OGRAPISPY_ENABLED
    3640         789 :     if (bOGRAPISpyEnabled)
    3641           4 :         OGRAPISpy_L_SetSpatialFilter(hLayer, hGeom);
    3642             : #endif
    3643             : 
    3644        1578 :     OGRLayer::FromHandle(hLayer)->SetSpatialFilter(
    3645         789 :         OGRGeometry::FromHandle(hGeom));
    3646             : }
    3647             : 
    3648             : /************************************************************************/
    3649             : /*                      OGR_L_SetSpatialFilterEx()                      */
    3650             : /************************************************************************/
    3651             : 
    3652             : /**
    3653             :  \brief Set a new spatial filter.
    3654             : 
    3655             :  This function set the geometry to be used as a spatial filter when
    3656             :  fetching features via the OGR_L_GetNextFeature() function.  Only
    3657             :  features that geometrically intersect the filter geometry will be
    3658             :  returned.
    3659             : 
    3660             :  Currently this test is may be inaccurately implemented, but it is
    3661             :  guaranteed that all features who's envelope (as returned by
    3662             :  OGR_G_GetEnvelope()) overlaps the envelope of the spatial filter
    3663             :  will be returned.  This can result in more shapes being returned that
    3664             :  should strictly be the case.
    3665             : 
    3666             :  This function makes an internal copy of the passed geometry.  The
    3667             :  passed geometry remains the responsibility of the caller, and may
    3668             :  be safely destroyed.
    3669             : 
    3670             :  For the time being the passed filter geometry should be in the same
    3671             :  SRS as the geometry field definition it corresponds to (as returned by
    3672             :  GetLayerDefn()->OGRFeatureDefn::GetGeomFieldDefn(iGeomField)->GetSpatialRef()).  In the
    3673             :  future this may be generalized.
    3674             : 
    3675             :  Note that only the last spatial filter set is applied, even if several
    3676             :  successive calls are done with different iGeomField values.
    3677             : 
    3678             :  This function is the same as the C++ method OGRLayer::SetSpatialFilter.
    3679             : 
    3680             :  @param hLayer handle to the layer on which to set the spatial filter.
    3681             :  @param iGeomField index of the geometry field on which the spatial filter
    3682             :  operates.
    3683             :  @param hGeom handle to the geometry to use as a filtering region.  NULL may
    3684             :  be passed indicating that the current spatial filter should be cleared,
    3685             :  but no new one instituted.
    3686             : 
    3687             :  */
    3688             : 
    3689          12 : void OGR_L_SetSpatialFilterEx(OGRLayerH hLayer, int iGeomField,
    3690             :                               OGRGeometryH hGeom)
    3691             : 
    3692             : {
    3693          12 :     VALIDATE_POINTER0(hLayer, "OGR_L_SetSpatialFilterEx");
    3694             : 
    3695             : #ifdef OGRAPISPY_ENABLED
    3696          12 :     if (bOGRAPISpyEnabled)
    3697           2 :         OGRAPISpy_L_SetSpatialFilterEx(hLayer, iGeomField, hGeom);
    3698             : #endif
    3699             : 
    3700          24 :     OGRLayer::FromHandle(hLayer)->SetSpatialFilter(
    3701          12 :         iGeomField, OGRGeometry::FromHandle(hGeom));
    3702             : }
    3703             : 
    3704             : /************************************************************************/
    3705             : /*                        SetSpatialFilterRect()                        */
    3706             : /************************************************************************/
    3707             : 
    3708             : /**
    3709             :  \brief Set a new rectangular spatial filter.
    3710             : 
    3711             :  This method set rectangle to be used as a spatial filter when
    3712             :  fetching features via the GetNextFeature() method.  Only features that
    3713             :  geometrically intersect the given rectangle will be returned.
    3714             : 
    3715             :  The x/y values should be in the same coordinate system as the layer as
    3716             :  a whole (as returned by OGRLayer::GetSpatialRef()).   Internally this
    3717             :  method is normally implemented as creating a 5 vertex closed rectangular
    3718             :  polygon and passing it to OGRLayer::SetSpatialFilter().  It exists as
    3719             :  a convenience.
    3720             : 
    3721             :  The only way to clear a spatial filter set with this method is to
    3722             :  call OGRLayer::SetSpatialFilter(NULL).
    3723             : 
    3724             :  This method is the same as the C function OGR_L_SetSpatialFilterRect().
    3725             : 
    3726             :  @param dfMinX the minimum X coordinate for the rectangular region.
    3727             :  @param dfMinY the minimum Y coordinate for the rectangular region.
    3728             :  @param dfMaxX the maximum X coordinate for the rectangular region.
    3729             :  @param dfMaxY the maximum Y coordinate for the rectangular region.
    3730             : 
    3731             :  */
    3732             : 
    3733       48391 : OGRErr OGRLayer::SetSpatialFilterRect(double dfMinX, double dfMinY,
    3734             :                                       double dfMaxX, double dfMaxY)
    3735             : 
    3736             : {
    3737       48391 :     return SetSpatialFilterRect(0, dfMinX, dfMinY, dfMaxX, dfMaxY);
    3738             : }
    3739             : 
    3740             : /**
    3741             :  \brief Set a new rectangular spatial filter.
    3742             : 
    3743             :  This method set rectangle to be used as a spatial filter when
    3744             :  fetching features via the GetNextFeature() method.  Only features that
    3745             :  geometrically intersect the given rectangle will be returned.
    3746             : 
    3747             :  The x/y values should be in the same coordinate system as as the geometry
    3748             :  field definition it corresponds to (as returned by
    3749             :  GetLayerDefn()->OGRFeatureDefn::GetGeomFieldDefn(iGeomField)->GetSpatialRef()). Internally this
    3750             :  method is normally implemented as creating a 5 vertex closed rectangular
    3751             :  polygon and passing it to OGRLayer::SetSpatialFilter().  It exists as
    3752             :  a convenience.
    3753             : 
    3754             :  The only way to clear a spatial filter set with this method is to
    3755             :  call OGRLayer::SetSpatialFilter(NULL).
    3756             : 
    3757             :  This method is the same as the C function OGR_L_SetSpatialFilterRectEx().
    3758             : 
    3759             :  @param iGeomField index of the geometry field on which the spatial filter
    3760             :  operates.
    3761             :  @param dfMinX the minimum X coordinate for the rectangular region.
    3762             :  @param dfMinY the minimum Y coordinate for the rectangular region.
    3763             :  @param dfMaxX the maximum X coordinate for the rectangular region.
    3764             :  @param dfMaxY the maximum Y coordinate for the rectangular region.
    3765             :  */
    3766             : 
    3767       48431 : OGRErr OGRLayer::SetSpatialFilterRect(int iGeomField, double dfMinX,
    3768             :                                       double dfMinY, double dfMaxX,
    3769             :                                       double dfMaxY)
    3770             : 
    3771             : {
    3772       96862 :     auto poRing = std::make_unique<OGRLinearRing>();
    3773       96862 :     OGRPolygon oPoly;
    3774             : 
    3775       48431 :     poRing->addPoint(dfMinX, dfMinY);
    3776       48431 :     poRing->addPoint(dfMinX, dfMaxY);
    3777       48431 :     poRing->addPoint(dfMaxX, dfMaxY);
    3778       48431 :     poRing->addPoint(dfMaxX, dfMinY);
    3779       48431 :     poRing->addPoint(dfMinX, dfMinY);
    3780             : 
    3781       48431 :     oPoly.addRing(std::move(poRing));
    3782             : 
    3783       96862 :     return SetSpatialFilter(iGeomField, &oPoly);
    3784             : }
    3785             : 
    3786             : /************************************************************************/
    3787             : /*                     OGR_L_SetSpatialFilterRect()                     */
    3788             : /************************************************************************/
    3789             : 
    3790             : /**
    3791             :  \brief Set a new rectangular spatial filter.
    3792             : 
    3793             :  This method set rectangle to be used as a spatial filter when
    3794             :  fetching features via the OGR_L_GetNextFeature() method.  Only features that
    3795             :  geometrically intersect the given rectangle will be returned.
    3796             : 
    3797             :  The x/y values should be in the same coordinate system as the layer as
    3798             :  a whole (as returned by OGRLayer::GetSpatialRef()).   Internally this
    3799             :  method is normally implemented as creating a 5 vertex closed rectangular
    3800             :  polygon and passing it to OGRLayer::SetSpatialFilter().  It exists as
    3801             :  a convenience.
    3802             : 
    3803             :  The only way to clear a spatial filter set with this method is to
    3804             :  call OGRLayer::SetSpatialFilter(NULL).
    3805             : 
    3806             :  This method is the same as the C++ method OGRLayer::SetSpatialFilterRect().
    3807             : 
    3808             :  @param hLayer handle to the layer on which to set the spatial filter.
    3809             :  @param dfMinX the minimum X coordinate for the rectangular region.
    3810             :  @param dfMinY the minimum Y coordinate for the rectangular region.
    3811             :  @param dfMaxX the maximum X coordinate for the rectangular region.
    3812             :  @param dfMaxY the maximum Y coordinate for the rectangular region.
    3813             : 
    3814             :  */
    3815             : 
    3816       48021 : void OGR_L_SetSpatialFilterRect(OGRLayerH hLayer, double dfMinX, double dfMinY,
    3817             :                                 double dfMaxX, double dfMaxY)
    3818             : 
    3819             : {
    3820       48021 :     VALIDATE_POINTER0(hLayer, "OGR_L_SetSpatialFilterRect");
    3821             : 
    3822             : #ifdef OGRAPISPY_ENABLED
    3823       48021 :     if (bOGRAPISpyEnabled)
    3824           2 :         OGRAPISpy_L_SetSpatialFilterRect(hLayer, dfMinX, dfMinY, dfMaxX,
    3825             :                                          dfMaxY);
    3826             : #endif
    3827             : 
    3828       48021 :     OGRLayer::FromHandle(hLayer)->SetSpatialFilterRect(dfMinX, dfMinY, dfMaxX,
    3829             :                                                        dfMaxY);
    3830             : }
    3831             : 
    3832             : /************************************************************************/
    3833             : /*                    OGR_L_SetSpatialFilterRectEx()                    */
    3834             : /************************************************************************/
    3835             : 
    3836             : /**
    3837             :  \brief Set a new rectangular spatial filter.
    3838             : 
    3839             :  This method set rectangle to be used as a spatial filter when
    3840             :  fetching features via the OGR_L_GetNextFeature() method.  Only features that
    3841             :  geometrically intersect the given rectangle will be returned.
    3842             : 
    3843             :  The x/y values should be in the same coordinate system as as the geometry
    3844             :  field definition it corresponds to (as returned by
    3845             :  GetLayerDefn()->OGRFeatureDefn::GetGeomFieldDefn(iGeomField)->GetSpatialRef()). Internally this
    3846             :  method is normally implemented as creating a 5 vertex closed rectangular
    3847             :  polygon and passing it to OGRLayer::SetSpatialFilter().  It exists as
    3848             :  a convenience.
    3849             : 
    3850             :  The only way to clear a spatial filter set with this method is to
    3851             :  call OGRLayer::SetSpatialFilter(NULL).
    3852             : 
    3853             :  This method is the same as the C++ method OGRLayer::SetSpatialFilterRect().
    3854             : 
    3855             :  @param hLayer handle to the layer on which to set the spatial filter.
    3856             :  @param iGeomField index of the geometry field on which the spatial filter
    3857             :  operates.
    3858             :  @param dfMinX the minimum X coordinate for the rectangular region.
    3859             :  @param dfMinY the minimum Y coordinate for the rectangular region.
    3860             :  @param dfMaxX the maximum X coordinate for the rectangular region.
    3861             :  @param dfMaxY the maximum Y coordinate for the rectangular region.
    3862             : */
    3863             : 
    3864          15 : void OGR_L_SetSpatialFilterRectEx(OGRLayerH hLayer, int iGeomField,
    3865             :                                   double dfMinX, double dfMinY, double dfMaxX,
    3866             :                                   double dfMaxY)
    3867             : 
    3868             : {
    3869          15 :     VALIDATE_POINTER0(hLayer, "OGR_L_SetSpatialFilterRectEx");
    3870             : 
    3871             : #ifdef OGRAPISPY_ENABLED
    3872          15 :     if (bOGRAPISpyEnabled)
    3873           2 :         OGRAPISpy_L_SetSpatialFilterRectEx(hLayer, iGeomField, dfMinX, dfMinY,
    3874             :                                            dfMaxX, dfMaxY);
    3875             : #endif
    3876             : 
    3877          15 :     OGRLayer::FromHandle(hLayer)->SetSpatialFilterRect(iGeomField, dfMinX,
    3878             :                                                        dfMinY, dfMaxX, dfMaxY);
    3879             : }
    3880             : 
    3881             : /************************************************************************/
    3882             : /*                           InstallFilter()                            */
    3883             : /*                                                                      */
    3884             : /*      This method is only intended to be used from within             */
    3885             : /*      drivers, normally from the SetSpatialFilter() method.           */
    3886             : /*      It installs a filter, and also tests it to see if it is         */
    3887             : /*      rectangular.  If so, it this is kept track of alongside the     */
    3888             : /*      filter geometry itself so we can do cheaper comparisons in      */
    3889             : /*      the FilterGeometry() call.                                      */
    3890             : /*                                                                      */
    3891             : /*      Returns TRUE if the newly installed filter differs in some      */
    3892             : /*      way from the current one.                                       */
    3893             : /************************************************************************/
    3894             : 
    3895             : //! @cond Doxygen_Suppress
    3896       65436 : int OGRLayer::InstallFilter(const OGRGeometry *poFilter)
    3897             : 
    3898             : {
    3899       65436 :     if (m_poFilterGeom == poFilter)
    3900       10253 :         return FALSE;
    3901             : 
    3902             :     /* -------------------------------------------------------------------- */
    3903             :     /*      Replace the existing filter.                                    */
    3904             :     /* -------------------------------------------------------------------- */
    3905       55183 :     if (m_poFilterGeom != nullptr)
    3906             :     {
    3907       51761 :         delete m_poFilterGeom;
    3908       51761 :         m_poFilterGeom = nullptr;
    3909             :     }
    3910             : 
    3911       55183 :     if (m_pPreparedFilterGeom != nullptr)
    3912             :     {
    3913       51761 :         OGRDestroyPreparedGeometry(m_pPreparedFilterGeom);
    3914       51761 :         m_pPreparedFilterGeom = nullptr;
    3915             :     }
    3916             : 
    3917       55183 :     if (poFilter != nullptr)
    3918       52926 :         m_poFilterGeom = poFilter->clone();
    3919             : 
    3920       55183 :     m_bFilterIsEnvelope = FALSE;
    3921             : 
    3922       55183 :     if (m_poFilterGeom == nullptr)
    3923        2257 :         return TRUE;
    3924             : 
    3925       52926 :     m_poFilterGeom->getEnvelope(&m_sFilterEnvelope);
    3926             : 
    3927             :     /* Compile geometry filter as a prepared geometry */
    3928       52926 :     m_pPreparedFilterGeom =
    3929       52926 :         OGRCreatePreparedGeometry(OGRGeometry::ToHandle(m_poFilterGeom));
    3930             : 
    3931       52926 :     m_bFilterIsEnvelope = m_poFilterGeom->IsRectangle();
    3932             : 
    3933       52926 :     return TRUE;
    3934             : }
    3935             : 
    3936             : //! @endcond
    3937             : 
    3938             : /************************************************************************/
    3939             : /*                  DoesGeometryHavePointInEnvelope()                   */
    3940             : /************************************************************************/
    3941             : 
    3942        8223 : static bool DoesGeometryHavePointInEnvelope(const OGRGeometry *poGeometry,
    3943             :                                             const OGREnvelope &sEnvelope)
    3944             : {
    3945        8223 :     const OGRLineString *poLS = nullptr;
    3946             : 
    3947        8223 :     switch (wkbFlatten(poGeometry->getGeometryType()))
    3948             :     {
    3949          42 :         case wkbPoint:
    3950             :         {
    3951          42 :             const auto poPoint = poGeometry->toPoint();
    3952          42 :             const double x = poPoint->getX();
    3953          42 :             const double y = poPoint->getY();
    3954          35 :             return (x >= sEnvelope.MinX && y >= sEnvelope.MinY &&
    3955          77 :                     x <= sEnvelope.MaxX && y <= sEnvelope.MaxY);
    3956             :         }
    3957             : 
    3958         442 :         case wkbLineString:
    3959         442 :             poLS = poGeometry->toLineString();
    3960         442 :             break;
    3961             : 
    3962        4614 :         case wkbPolygon:
    3963             :         {
    3964        4614 :             const OGRPolygon *poPoly = poGeometry->toPolygon();
    3965        4614 :             poLS = poPoly->getExteriorRing();
    3966        4614 :             break;
    3967             :         }
    3968             : 
    3969        2884 :         case wkbMultiPoint:
    3970             :         case wkbMultiLineString:
    3971             :         case wkbMultiPolygon:
    3972             :         case wkbGeometryCollection:
    3973             :         {
    3974        3559 :             for (const auto &poSubGeom : *(poGeometry->toGeometryCollection()))
    3975             :             {
    3976        3034 :                 if (DoesGeometryHavePointInEnvelope(poSubGeom, sEnvelope))
    3977        2359 :                     return true;
    3978             :             }
    3979         525 :             return false;
    3980             :         }
    3981             : 
    3982         241 :         default:
    3983         241 :             return false;
    3984             :     }
    3985             : 
    3986        5056 :     if (poLS != nullptr)
    3987             :     {
    3988        5056 :         const int nNumPoints = poLS->getNumPoints();
    3989       59789 :         for (int i = 0; i < nNumPoints; i++)
    3990             :         {
    3991       58637 :             const double x = poLS->getX(i);
    3992       58637 :             const double y = poLS->getY(i);
    3993       58637 :             if (x >= sEnvelope.MinX && y >= sEnvelope.MinY &&
    3994       24311 :                 x <= sEnvelope.MaxX && y <= sEnvelope.MaxY)
    3995             :             {
    3996        3904 :                 return true;
    3997             :             }
    3998             :         }
    3999             :     }
    4000             : 
    4001        1152 :     return false;
    4002             : }
    4003             : 
    4004             : /************************************************************************/
    4005             : /*                           FilterGeometry()                           */
    4006             : /*                                                                      */
    4007             : /*      Compare the passed in geometry to the currently installed       */
    4008             : /*      filter.  Optimize for case where filter is just an              */
    4009             : /*      envelope.                                                       */
    4010             : /************************************************************************/
    4011             : 
    4012             : //! @cond Doxygen_Suppress
    4013      444819 : int OGRLayer::FilterGeometry(const OGRGeometry *poGeometry)
    4014             : 
    4015             : {
    4016             :     /* -------------------------------------------------------------------- */
    4017             :     /*      In trivial cases of new filter or target geometry, we accept    */
    4018             :     /*      an intersection.  No geometry is taken to mean "the whole       */
    4019             :     /*      world".                                                         */
    4020             :     /* -------------------------------------------------------------------- */
    4021      444819 :     if (m_poFilterGeom == nullptr)
    4022         376 :         return TRUE;
    4023             : 
    4024      444443 :     if (poGeometry == nullptr || poGeometry->IsEmpty())
    4025         304 :         return FALSE;
    4026             : 
    4027             :     /* -------------------------------------------------------------------- */
    4028             :     /*      Compute the target geometry envelope, and if there is no        */
    4029             :     /*      intersection between the envelopes we are sure not to have      */
    4030             :     /*      any intersection.                                               */
    4031             :     /* -------------------------------------------------------------------- */
    4032      444139 :     OGREnvelope sGeomEnv;
    4033             : 
    4034      444139 :     poGeometry->getEnvelope(&sGeomEnv);
    4035             : 
    4036      444139 :     if (sGeomEnv.MaxX < m_sFilterEnvelope.MinX ||
    4037      297486 :         sGeomEnv.MaxY < m_sFilterEnvelope.MinY ||
    4038      232160 :         m_sFilterEnvelope.MaxX < sGeomEnv.MinX ||
    4039      134886 :         m_sFilterEnvelope.MaxY < sGeomEnv.MinY)
    4040      325017 :         return FALSE;
    4041             : 
    4042             :     /* -------------------------------------------------------------------- */
    4043             :     /*      If the filter geometry is its own envelope and if the           */
    4044             :     /*      envelope of the geometry is inside the filter geometry,         */
    4045             :     /*      the geometry itself is inside the filter geometry               */
    4046             :     /* -------------------------------------------------------------------- */
    4047      119122 :     if (m_bFilterIsEnvelope && sGeomEnv.MinX >= m_sFilterEnvelope.MinX &&
    4048      113333 :         sGeomEnv.MinY >= m_sFilterEnvelope.MinY &&
    4049      111929 :         sGeomEnv.MaxX <= m_sFilterEnvelope.MaxX &&
    4050      111101 :         sGeomEnv.MaxY <= m_sFilterEnvelope.MaxY)
    4051             :     {
    4052      110720 :         return TRUE;
    4053             :     }
    4054             :     else
    4055             :     {
    4056             :         // If the filter geometry is its own envelope and if the geometry has
    4057             :         // at least one point inside the filter geometry, the geometry itself
    4058             :         // intersects the filter geometry.
    4059        8402 :         if (m_bFilterIsEnvelope)
    4060             :         {
    4061        5189 :             if (DoesGeometryHavePointInEnvelope(poGeometry, m_sFilterEnvelope))
    4062        3914 :                 return true;
    4063             :         }
    4064             : 
    4065             :         /* --------------------------------------------------------------------
    4066             :          */
    4067             :         /*      Fallback to full intersect test (using GEOS) if we still */
    4068             :         /*      don't know for sure. */
    4069             :         /* --------------------------------------------------------------------
    4070             :          */
    4071        4488 :         if (OGRGeometryFactory::haveGEOS())
    4072             :         {
    4073             :             // CPLDebug("OGRLayer", "GEOS intersection");
    4074        4488 :             if (m_pPreparedFilterGeom != nullptr)
    4075        4488 :                 return OGRPreparedGeometryIntersects(
    4076             :                     m_pPreparedFilterGeom,
    4077             :                     OGRGeometry::ToHandle(
    4078        4488 :                         const_cast<OGRGeometry *>(poGeometry)));
    4079             :             else
    4080           0 :                 return m_poFilterGeom->Intersects(poGeometry);
    4081             :         }
    4082             :         else
    4083           0 :             return TRUE;
    4084             :     }
    4085             : }
    4086             : 
    4087             : /************************************************************************/
    4088             : /*                         FilterWKBGeometry()                          */
    4089             : /************************************************************************/
    4090             : 
    4091         237 : bool OGRLayer::FilterWKBGeometry(const GByte *pabyWKB, size_t nWKBSize,
    4092             :                                  bool bEnvelopeAlreadySet,
    4093             :                                  OGREnvelope &sEnvelope) const
    4094             : {
    4095         237 :     OGRPreparedGeometry *pPreparedFilterGeom = m_pPreparedFilterGeom;
    4096             :     bool bRet =
    4097         474 :         FilterWKBGeometry(pabyWKB, nWKBSize, bEnvelopeAlreadySet, sEnvelope,
    4098         237 :                           m_poFilterGeom, CPL_TO_BOOL(m_bFilterIsEnvelope),
    4099         237 :                           m_sFilterEnvelope, pPreparedFilterGeom);
    4100         237 :     const_cast<OGRLayer *>(this)->m_pPreparedFilterGeom = pPreparedFilterGeom;
    4101         237 :     return bRet;
    4102             : }
    4103             : 
    4104             : /* static */
    4105         341 : bool OGRLayer::FilterWKBGeometry(const GByte *pabyWKB, size_t nWKBSize,
    4106             :                                  bool bEnvelopeAlreadySet,
    4107             :                                  OGREnvelope &sEnvelope,
    4108             :                                  const OGRGeometry *poFilterGeom,
    4109             :                                  bool bFilterIsEnvelope,
    4110             :                                  const OGREnvelope &sFilterEnvelope,
    4111             :                                  OGRPreparedGeometry *&pPreparedFilterGeom)
    4112             : {
    4113         341 :     if (!poFilterGeom)
    4114           0 :         return true;
    4115             : 
    4116         647 :     if ((bEnvelopeAlreadySet ||
    4117         682 :          OGRWKBGetBoundingBox(pabyWKB, nWKBSize, sEnvelope)) &&
    4118         341 :         sFilterEnvelope.Intersects(sEnvelope))
    4119             :     {
    4120         164 :         if (bFilterIsEnvelope && sFilterEnvelope.Contains(sEnvelope))
    4121             :         {
    4122         101 :             return true;
    4123             :         }
    4124             :         else
    4125             :         {
    4126         126 :             if (bFilterIsEnvelope &&
    4127          63 :                 OGRWKBIntersectsPessimistic(pabyWKB, nWKBSize, sFilterEnvelope))
    4128             :             {
    4129          51 :                 return true;
    4130             :             }
    4131          12 :             else if (OGRGeometryFactory::haveGEOS())
    4132             :             {
    4133          12 :                 OGRGeometry *poGeom = nullptr;
    4134          12 :                 int ret = FALSE;
    4135          12 :                 if (OGRGeometryFactory::createFromWkb(pabyWKB, nullptr, &poGeom,
    4136          12 :                                                       nWKBSize) == OGRERR_NONE)
    4137             :                 {
    4138          12 :                     if (!pPreparedFilterGeom)
    4139             :                     {
    4140           0 :                         pPreparedFilterGeom =
    4141           0 :                             OGRCreatePreparedGeometry(OGRGeometry::ToHandle(
    4142             :                                 const_cast<OGRGeometry *>(poFilterGeom)));
    4143             :                     }
    4144          12 :                     if (pPreparedFilterGeom)
    4145          12 :                         ret = OGRPreparedGeometryIntersects(
    4146             :                             pPreparedFilterGeom,
    4147             :                             OGRGeometry::ToHandle(
    4148             :                                 const_cast<OGRGeometry *>(poGeom)));
    4149             :                     else
    4150           0 :                         ret = poFilterGeom->Intersects(poGeom);
    4151             :                 }
    4152          12 :                 delete poGeom;
    4153          12 :                 return CPL_TO_BOOL(ret);
    4154             :             }
    4155             :             else
    4156             :             {
    4157             :                 // Assume intersection
    4158           0 :                 return true;
    4159             :             }
    4160             :         }
    4161             :     }
    4162             : 
    4163         177 :     return false;
    4164             : }
    4165             : 
    4166             : /************************************************************************/
    4167             : /*                      PrepareStartTransaction()                       */
    4168             : /************************************************************************/
    4169             : 
    4170        3203 : void OGRLayer::PrepareStartTransaction()
    4171             : {
    4172        3203 :     m_apoFieldDefnChanges.clear();
    4173        3203 :     m_apoGeomFieldDefnChanges.clear();
    4174        3203 : }
    4175             : 
    4176             : /************************************************************************/
    4177             : /*                     FinishRollbackTransaction()                      */
    4178             : /************************************************************************/
    4179             : 
    4180         175 : void OGRLayer::FinishRollbackTransaction(const std::string &osSavepointName)
    4181             : {
    4182             : 
    4183             :     // Deleted fields can be safely removed from the storage after being restored.
    4184         350 :     std::vector<int> toBeRemoved;
    4185             : 
    4186         175 :     bool bSavepointFound = false;
    4187             : 
    4188             :     // Loop through all changed fields and reset them to their previous state.
    4189         378 :     for (int i = static_cast<int>(m_apoFieldDefnChanges.size()) - 1; i >= 0;
    4190             :          i--)
    4191             :     {
    4192         203 :         auto &oFieldChange = m_apoFieldDefnChanges[i];
    4193             : 
    4194         203 :         if (!osSavepointName.empty())
    4195             :         {
    4196         172 :             if (oFieldChange.osSavepointName == osSavepointName)
    4197             :             {
    4198          60 :                 bSavepointFound = true;
    4199             :             }
    4200         112 :             else if (bSavepointFound)
    4201             :             {
    4202          56 :                 continue;
    4203             :             }
    4204             :         }
    4205             : 
    4206         147 :         CPLAssert(oFieldChange.poFieldDefn);
    4207         147 :         const char *pszName = oFieldChange.poFieldDefn->GetNameRef();
    4208         147 :         const int iField = oFieldChange.iField;
    4209         147 :         if (iField >= 0)
    4210             :         {
    4211         147 :             switch (oFieldChange.eChangeType)
    4212             :             {
    4213         128 :                 case FieldChangeType::DELETE_FIELD:
    4214             :                 {
    4215             :                     // Transfer ownership of the field to the layer
    4216         256 :                     whileUnsealing(GetLayerDefn())
    4217         128 :                         ->AddFieldDefn(std::move(oFieldChange.poFieldDefn));
    4218             : 
    4219             :                     // Now move the field to the right place
    4220             :                     // from the last position to its original position
    4221         128 :                     const int iFieldCount = GetLayerDefn()->GetFieldCount();
    4222         128 :                     CPLAssert(iFieldCount > 0);
    4223         128 :                     CPLAssert(iFieldCount > iField);
    4224         256 :                     std::vector<int> anOrder(iFieldCount);
    4225         204 :                     for (int j = 0; j < iField; j++)
    4226             :                     {
    4227          76 :                         anOrder[j] = j;
    4228             :                     }
    4229         248 :                     for (int j = iField + 1; j < iFieldCount; j++)
    4230             :                     {
    4231         120 :                         anOrder[j] = j - 1;
    4232             :                     }
    4233         128 :                     anOrder[iField] = iFieldCount - 1;
    4234         256 :                     if (OGRERR_NONE == whileUnsealing(GetLayerDefn())
    4235         128 :                                            ->ReorderFieldDefns(anOrder.data()))
    4236             :                     {
    4237         128 :                         toBeRemoved.push_back(i);
    4238             :                     }
    4239             :                     else
    4240             :                     {
    4241           0 :                         CPLError(CE_Failure, CPLE_AppDefined,
    4242             :                                  "Failed to restore deleted field %s", pszName);
    4243             :                     }
    4244         128 :                     break;
    4245             :                 }
    4246           8 :                 case FieldChangeType::ALTER_FIELD:
    4247             :                 {
    4248             :                     OGRFieldDefn *poFieldDefn =
    4249           8 :                         GetLayerDefn()->GetFieldDefn(iField);
    4250           8 :                     if (poFieldDefn)
    4251             :                     {
    4252           8 :                         *poFieldDefn = *oFieldChange.poFieldDefn;
    4253           8 :                         toBeRemoved.push_back(i);
    4254             :                     }
    4255             :                     else
    4256             :                     {
    4257           0 :                         CPLError(CE_Failure, CPLE_AppDefined,
    4258             :                                  "Failed to restore altered field %s", pszName);
    4259             :                     }
    4260           8 :                     break;
    4261             :                 }
    4262          11 :                 case FieldChangeType::ADD_FIELD:
    4263             :                 {
    4264             :                     std::unique_ptr<OGRFieldDefn> poFieldDef =
    4265          22 :                         GetLayerDefn()->StealFieldDefn(iField);
    4266          11 :                     if (poFieldDef)
    4267             :                     {
    4268          11 :                         oFieldChange.poFieldDefn = std::move(poFieldDef);
    4269             :                     }
    4270             :                     else
    4271             :                     {
    4272           0 :                         CPLError(CE_Failure, CPLE_AppDefined,
    4273             :                                  "Failed to delete added field %s", pszName);
    4274             :                     }
    4275          11 :                     break;
    4276             :                 }
    4277             :             }
    4278             :         }
    4279             :         else
    4280             :         {
    4281           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    4282             :                      "Failed to restore field %s (field not found at index %d)",
    4283             :                      pszName, iField);
    4284             :         }
    4285             :     }
    4286             : 
    4287             :     // Remove from the storage the deleted fields that have been restored
    4288         311 :     for (const auto &i : toBeRemoved)
    4289             :     {
    4290         136 :         m_apoFieldDefnChanges.erase(m_apoFieldDefnChanges.begin() + i);
    4291             :     }
    4292             : 
    4293             :     /**********************************************************************/
    4294             :     /* Reset geometry fields to their previous state.                    */
    4295             :     /**********************************************************************/
    4296             : 
    4297         175 :     bSavepointFound = false;
    4298             : 
    4299             :     // Loop through all changed geometry fields and reset them to their previous state.
    4300         175 :     for (int i = static_cast<int>(m_apoGeomFieldDefnChanges.size()) - 1; i >= 0;
    4301             :          i--)
    4302             :     {
    4303           0 :         auto &oGeomFieldChange = m_apoGeomFieldDefnChanges[i];
    4304             : 
    4305           0 :         if (!osSavepointName.empty())
    4306             :         {
    4307           0 :             if (oGeomFieldChange.osSavepointName == osSavepointName)
    4308             :             {
    4309           0 :                 bSavepointFound = true;
    4310             :             }
    4311           0 :             else if (bSavepointFound)
    4312             :             {
    4313           0 :                 continue;
    4314             :             }
    4315             :         }
    4316           0 :         const char *pszName = oGeomFieldChange.poFieldDefn->GetNameRef();
    4317           0 :         const int iGeomField = oGeomFieldChange.iField;
    4318           0 :         if (iGeomField >= 0)
    4319             :         {
    4320           0 :             switch (oGeomFieldChange.eChangeType)
    4321             :             {
    4322           0 :                 case FieldChangeType::DELETE_FIELD:
    4323             :                 case FieldChangeType::ALTER_FIELD:
    4324             :                 {
    4325             :                     // Currently not handled by OGR for geometry fields
    4326           0 :                     break;
    4327             :                 }
    4328           0 :                 case FieldChangeType::ADD_FIELD:
    4329             :                 {
    4330             :                     std::unique_ptr<OGRGeomFieldDefn> poGeomFieldDef =
    4331           0 :                         GetLayerDefn()->StealGeomFieldDefn(
    4332           0 :                             oGeomFieldChange.iField);
    4333           0 :                     if (poGeomFieldDef)
    4334             :                     {
    4335             :                         oGeomFieldChange.poFieldDefn =
    4336           0 :                             std::move(poGeomFieldDef);
    4337             :                     }
    4338             :                     else
    4339             :                     {
    4340           0 :                         CPLError(CE_Failure, CPLE_AppDefined,
    4341             :                                  "Failed to delete added geometry field %s",
    4342             :                                  pszName);
    4343             :                     }
    4344           0 :                     break;
    4345             :                 }
    4346             :             }
    4347             :         }
    4348             :         else
    4349             :         {
    4350           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    4351             :                      "Failed to restore geometry field %s (field not found at "
    4352             :                      "index %d)",
    4353             :                      pszName, oGeomFieldChange.iField);
    4354             :         }
    4355             :     }
    4356         175 : }
    4357             : 
    4358             : //! @endcond
    4359             : 
    4360             : /************************************************************************/
    4361             : /*                       OGRLayer::ResetReading()                       */
    4362             : /************************************************************************/
    4363             : 
    4364             : /**
    4365             :  \fn void OGRLayer::ResetReading();
    4366             : 
    4367             :  \brief Reset feature reading to start on the first feature.
    4368             : 
    4369             :  This affects GetNextFeature() and GetArrowStream().
    4370             : 
    4371             :  This method is the same as the C function OGR_L_ResetReading().
    4372             : */
    4373             : 
    4374             : /************************************************************************/
    4375             : /*                         OGR_L_ResetReading()                         */
    4376             : /************************************************************************/
    4377             : 
    4378             : /**
    4379             :  \brief Reset feature reading to start on the first feature.
    4380             : 
    4381             :  This affects GetNextFeature() and GetArrowStream().
    4382             : 
    4383             :  This function is the same as the C++ method OGRLayer::ResetReading().
    4384             : 
    4385             :  @param hLayer handle to the layer on which features are read.
    4386             : */
    4387             : 
    4388       18836 : void OGR_L_ResetReading(OGRLayerH hLayer)
    4389             : 
    4390             : {
    4391       18836 :     VALIDATE_POINTER0(hLayer, "OGR_L_ResetReading");
    4392             : 
    4393             : #ifdef OGRAPISPY_ENABLED
    4394       18836 :     if (bOGRAPISpyEnabled)
    4395           2 :         OGRAPISpy_L_ResetReading(hLayer);
    4396             : #endif
    4397             : 
    4398       18836 :     OGRLayer::FromHandle(hLayer)->ResetReading();
    4399             : }
    4400             : 
    4401             : /************************************************************************/
    4402             : /*                       InitializeIndexSupport()                       */
    4403             : /*                                                                      */
    4404             : /*      This is only intended to be called by driver layer              */
    4405             : /*      implementations but we don't make it protected so that the      */
    4406             : /*      datasources can do it too if that is more appropriate.          */
    4407             : /************************************************************************/
    4408             : 
    4409             : //! @cond Doxygen_Suppress
    4410             : OGRErr
    4411         845 : OGRLayer::InitializeIndexSupport([[maybe_unused]] const char *pszFilename)
    4412             : 
    4413             : {
    4414             : #ifdef HAVE_MITAB
    4415             :     OGRErr eErr;
    4416             : 
    4417         845 :     if (m_poAttrIndex != nullptr)
    4418         668 :         return OGRERR_NONE;
    4419             : 
    4420         177 :     m_poAttrIndex = OGRCreateDefaultLayerIndex();
    4421             : 
    4422         177 :     eErr = m_poAttrIndex->Initialize(pszFilename, this);
    4423         177 :     if (eErr != OGRERR_NONE)
    4424             :     {
    4425           0 :         delete m_poAttrIndex;
    4426           0 :         m_poAttrIndex = nullptr;
    4427             :     }
    4428             : 
    4429         177 :     return eErr;
    4430             : #else
    4431             :     return OGRERR_FAILURE;
    4432             : #endif
    4433             : }
    4434             : 
    4435             : //! @endcond
    4436             : 
    4437             : /************************************************************************/
    4438             : /*                             SyncToDisk()                             */
    4439             : /************************************************************************/
    4440             : 
    4441             : /**
    4442             : \brief Flush pending changes to disk.
    4443             : 
    4444             : This call is intended to force the layer to flush any pending writes to
    4445             : disk, and leave the disk file in a consistent state.  It would not normally
    4446             : have any effect on read-only datasources.
    4447             : 
    4448             : Some layers do not implement this method, and will still return
    4449             : OGRERR_NONE.  The default implementation just returns OGRERR_NONE.  An error
    4450             : is only returned if an error occurs while attempting to flush to disk.
    4451             : 
    4452             : In any event, you should always close any opened datasource with
    4453             : OGRDataSource::DestroyDataSource() that will ensure all data is correctly flushed.
    4454             : 
    4455             : This method is the same as the C function OGR_L_SyncToDisk().
    4456             : 
    4457             : @return OGRERR_NONE if no error occurs (even if nothing is done) or an
    4458             : error code.
    4459             : */
    4460             : 
    4461        6866 : OGRErr OGRLayer::SyncToDisk()
    4462             : 
    4463             : {
    4464        6866 :     return OGRERR_NONE;
    4465             : }
    4466             : 
    4467             : /************************************************************************/
    4468             : /*                          OGR_L_SyncToDisk()                          */
    4469             : /************************************************************************/
    4470             : 
    4471             : /**
    4472             : \brief Flush pending changes to disk.
    4473             : 
    4474             : This call is intended to force the layer to flush any pending writes to
    4475             : disk, and leave the disk file in a consistent state.  It would not normally
    4476             : have any effect on read-only datasources.
    4477             : 
    4478             : Some layers do not implement this method, and will still return
    4479             : OGRERR_NONE.  The default implementation just returns OGRERR_NONE.  An error
    4480             : is only returned if an error occurs while attempting to flush to disk.
    4481             : 
    4482             : In any event, you should always close any opened datasource with
    4483             : OGR_DS_Destroy() that will ensure all data is correctly flushed.
    4484             : 
    4485             : This method is the same as the C++ method OGRLayer::SyncToDisk()
    4486             : 
    4487             : @param hLayer handle to the layer
    4488             : 
    4489             : @return OGRERR_NONE if no error occurs (even if nothing is done) or an
    4490             : error code.
    4491             : */
    4492             : 
    4493         251 : OGRErr OGR_L_SyncToDisk(OGRLayerH hLayer)
    4494             : 
    4495             : {
    4496         251 :     VALIDATE_POINTER1(hLayer, "OGR_L_SyncToDisk", OGRERR_INVALID_HANDLE);
    4497             : 
    4498             : #ifdef OGRAPISPY_ENABLED
    4499         251 :     if (bOGRAPISpyEnabled)
    4500           2 :         OGRAPISpy_L_SyncToDisk(hLayer);
    4501             : #endif
    4502             : 
    4503         251 :     return OGRLayer::FromHandle(hLayer)->SyncToDisk();
    4504             : }
    4505             : 
    4506             : /************************************************************************/
    4507             : /*                           DeleteFeature()                            */
    4508             : /************************************************************************/
    4509             : 
    4510             : /**
    4511             :  \brief Delete feature from layer.
    4512             : 
    4513             :  The feature with the indicated feature id is deleted from the layer if
    4514             :  supported by the driver.  Most drivers do not support feature deletion,
    4515             :  and will return OGRERR_UNSUPPORTED_OPERATION.  The TestCapability()
    4516             :  layer method may be called with OLCDeleteFeature to check if the driver
    4517             :  supports feature deletion.
    4518             : 
    4519             :  This method is the same as the C function OGR_L_DeleteFeature().
    4520             : 
    4521             :  @param nFID the feature id to be deleted from the layer
    4522             : 
    4523             :  @return OGRERR_NONE if the operation works, otherwise an appropriate error
    4524             :  code (e.g OGRERR_NON_EXISTING_FEATURE if the feature does not exist).
    4525             : 
    4526             : */
    4527             : 
    4528         492 : OGRErr OGRLayer::DeleteFeature(CPL_UNUSED GIntBig nFID)
    4529             : {
    4530         492 :     return OGRERR_UNSUPPORTED_OPERATION;
    4531             : }
    4532             : 
    4533             : /************************************************************************/
    4534             : /*                        OGR_L_DeleteFeature()                         */
    4535             : /************************************************************************/
    4536             : 
    4537             : /**
    4538             :  \brief Delete feature from layer.
    4539             : 
    4540             :  The feature with the indicated feature id is deleted from the layer if
    4541             :  supported by the driver.  Most drivers do not support feature deletion,
    4542             :  and will return OGRERR_UNSUPPORTED_OPERATION.  The OGR_L_TestCapability()
    4543             :  function may be called with OLCDeleteFeature to check if the driver
    4544             :  supports feature deletion.
    4545             : 
    4546             :  This method is the same as the C++ method OGRLayer::DeleteFeature().
    4547             : 
    4548             :  @param hLayer handle to the layer
    4549             :  @param nFID the feature id to be deleted from the layer
    4550             : 
    4551             :  @return OGRERR_NONE if the operation works, otherwise an appropriate error
    4552             :  code (e.g OGRERR_NON_EXISTING_FEATURE if the feature does not exist).
    4553             : */
    4554             : 
    4555        3357 : OGRErr OGR_L_DeleteFeature(OGRLayerH hLayer, GIntBig nFID)
    4556             : 
    4557             : {
    4558        3357 :     VALIDATE_POINTER1(hLayer, "OGR_L_DeleteFeature", OGRERR_INVALID_HANDLE);
    4559             : 
    4560             : #ifdef OGRAPISPY_ENABLED
    4561        3357 :     if (bOGRAPISpyEnabled)
    4562           2 :         OGRAPISpy_L_DeleteFeature(hLayer, nFID);
    4563             : #endif
    4564             : 
    4565        3357 :     return OGRLayer::FromHandle(hLayer)->DeleteFeature(nFID);
    4566             : }
    4567             : 
    4568             : /************************************************************************/
    4569             : /*                          GetFeaturesRead()                           */
    4570             : /************************************************************************/
    4571             : 
    4572             : //! @cond Doxygen_Suppress
    4573           0 : GIntBig OGRLayer::GetFeaturesRead()
    4574             : 
    4575             : {
    4576           0 :     return m_nFeaturesRead;
    4577             : }
    4578             : 
    4579             : //! @endcond
    4580             : 
    4581             : /************************************************************************/
    4582             : /*                       OGR_L_GetFeaturesRead()                        */
    4583             : /************************************************************************/
    4584             : 
    4585           0 : GIntBig OGR_L_GetFeaturesRead(OGRLayerH hLayer)
    4586             : 
    4587             : {
    4588           0 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetFeaturesRead", 0);
    4589             : 
    4590           0 :     return OGRLayer::FromHandle(hLayer)->GetFeaturesRead();
    4591             : }
    4592             : 
    4593             : /************************************************************************/
    4594             : /*                             GetFIDColumn                             */
    4595             : /************************************************************************/
    4596             : 
    4597             : /**
    4598             :  \brief This method returns the name of the underlying database column being used as the FID column, or "" if not supported.
    4599             : 
    4600             :  This method is the same as the C function OGR_L_GetFIDColumn().
    4601             : 
    4602             :  @return fid column name.
    4603             : */
    4604             : 
    4605       10625 : const char *OGRLayer::GetFIDColumn() const
    4606             : 
    4607             : {
    4608       10625 :     return "";
    4609             : }
    4610             : 
    4611             : /************************************************************************/
    4612             : /*                         OGR_L_GetFIDColumn()                         */
    4613             : /************************************************************************/
    4614             : 
    4615             : /**
    4616             :  \brief This method returns the name of the underlying database column being used as the FID column, or "" if not supported.
    4617             : 
    4618             :  This method is the same as the C++ method OGRLayer::GetFIDColumn()
    4619             : 
    4620             :  @param hLayer handle to the layer
    4621             :  @return fid column name.
    4622             : */
    4623             : 
    4624         435 : const char *OGR_L_GetFIDColumn(OGRLayerH hLayer)
    4625             : 
    4626             : {
    4627         435 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetFIDColumn", nullptr);
    4628             : 
    4629             : #ifdef OGRAPISPY_ENABLED
    4630         435 :     if (bOGRAPISpyEnabled)
    4631           2 :         OGRAPISpy_L_GetFIDColumn(hLayer);
    4632             : #endif
    4633             : 
    4634         435 :     return OGRLayer::FromHandle(hLayer)->GetFIDColumn();
    4635             : }
    4636             : 
    4637             : /************************************************************************/
    4638             : /*                         GetGeometryColumn()                          */
    4639             : /************************************************************************/
    4640             : 
    4641             : /**
    4642             :  \brief This method returns the name of the underlying database column being used as the geometry column, or "" if not supported.
    4643             : 
    4644             :  For layers with multiple geometry fields, this method only returns the name
    4645             :  of the first geometry column. For other columns, use
    4646             :  GetLayerDefn()->OGRFeatureDefn::GetGeomFieldDefn(i)->GetNameRef().
    4647             : 
    4648             :  This method is the same as the C function OGR_L_GetGeometryColumn().
    4649             : 
    4650             :  @return geometry column name.
    4651             : */
    4652             : 
    4653        4013 : const char *OGRLayer::GetGeometryColumn() const
    4654             : 
    4655             : {
    4656        4013 :     const auto poLayerDefn = GetLayerDefn();
    4657        4013 :     if (poLayerDefn->GetGeomFieldCount() > 0)
    4658        3913 :         return poLayerDefn->GetGeomFieldDefn(0)->GetNameRef();
    4659             :     else
    4660         100 :         return "";
    4661             : }
    4662             : 
    4663             : /************************************************************************/
    4664             : /*                      OGR_L_GetGeometryColumn()                       */
    4665             : /************************************************************************/
    4666             : 
    4667             : /**
    4668             :  \brief This method returns the name of the underlying database column being used as the geometry column, or "" if not supported.
    4669             : 
    4670             :  For layers with multiple geometry fields, this method only returns the geometry
    4671             :  type of the first geometry column. For other columns, use
    4672             :  OGR_GFld_GetNameRef(OGR_FD_GetGeomFieldDefn(OGR_L_GetLayerDefn(hLayer), i)).
    4673             : 
    4674             :  This method is the same as the C++ method OGRLayer::GetGeometryColumn()
    4675             : 
    4676             :  @param hLayer handle to the layer
    4677             :  @return geometry column name.
    4678             : */
    4679             : 
    4680         715 : const char *OGR_L_GetGeometryColumn(OGRLayerH hLayer)
    4681             : 
    4682             : {
    4683         715 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetGeometryColumn", nullptr);
    4684             : 
    4685             : #ifdef OGRAPISPY_ENABLED
    4686         715 :     if (bOGRAPISpyEnabled)
    4687           2 :         OGRAPISpy_L_GetGeometryColumn(hLayer);
    4688             : #endif
    4689             : 
    4690         715 :     return OGRLayer::FromHandle(hLayer)->GetGeometryColumn();
    4691             : }
    4692             : 
    4693             : /************************************************************************/
    4694             : /*                           GetStyleTable()                            */
    4695             : /************************************************************************/
    4696             : 
    4697             : /**
    4698             :  \brief Returns layer style table.
    4699             : 
    4700             :  This method is the same as the C function OGR_L_GetStyleTable().
    4701             : 
    4702             :  @return pointer to a style table which should not be modified or freed by the
    4703             :  caller.
    4704             : */
    4705             : 
    4706        1287 : OGRStyleTable *OGRLayer::GetStyleTable()
    4707             : {
    4708        1287 :     return m_poStyleTable;
    4709             : }
    4710             : 
    4711             : /************************************************************************/
    4712             : /*                       SetStyleTableDirectly()                        */
    4713             : /************************************************************************/
    4714             : 
    4715             : /**
    4716             :  \brief Set layer style table.
    4717             : 
    4718             :  This method operate exactly as OGRLayer::SetStyleTable() except that it
    4719             :  assumes ownership of the passed table.
    4720             : 
    4721             :  This method is the same as the C function OGR_L_SetStyleTableDirectly().
    4722             : 
    4723             :  @param poStyleTable pointer to style table to set
    4724             : */
    4725             : 
    4726           0 : void OGRLayer::SetStyleTableDirectly(OGRStyleTable *poStyleTable)
    4727             : {
    4728           0 :     if (m_poStyleTable)
    4729           0 :         delete m_poStyleTable;
    4730           0 :     m_poStyleTable = poStyleTable;
    4731           0 : }
    4732             : 
    4733             : /************************************************************************/
    4734             : /*                           SetStyleTable()                            */
    4735             : /************************************************************************/
    4736             : 
    4737             : /**
    4738             :  \brief Set layer style table.
    4739             : 
    4740             :  This method operate exactly as OGRLayer::SetStyleTableDirectly() except
    4741             :  that it does not assume ownership of the passed table.
    4742             : 
    4743             :  This method is the same as the C function OGR_L_SetStyleTable().
    4744             : 
    4745             :  @param poStyleTable pointer to style table to set
    4746             : */
    4747             : 
    4748        1284 : void OGRLayer::SetStyleTable(OGRStyleTable *poStyleTable)
    4749             : {
    4750        1284 :     if (m_poStyleTable)
    4751           0 :         delete m_poStyleTable;
    4752        1284 :     if (poStyleTable)
    4753           2 :         m_poStyleTable = poStyleTable->Clone();
    4754        1284 : }
    4755             : 
    4756             : /************************************************************************/
    4757             : /*                        OGR_L_GetStyleTable()                         */
    4758             : /************************************************************************/
    4759             : 
    4760           4 : OGRStyleTableH OGR_L_GetStyleTable(OGRLayerH hLayer)
    4761             : 
    4762             : {
    4763           4 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetStyleTable", nullptr);
    4764             : 
    4765             :     return reinterpret_cast<OGRStyleTableH>(
    4766           4 :         OGRLayer::FromHandle(hLayer)->GetStyleTable());
    4767             : }
    4768             : 
    4769             : /************************************************************************/
    4770             : /*                    OGR_L_SetStyleTableDirectly()                     */
    4771             : /************************************************************************/
    4772             : 
    4773           0 : void OGR_L_SetStyleTableDirectly(OGRLayerH hLayer, OGRStyleTableH hStyleTable)
    4774             : 
    4775             : {
    4776           0 :     VALIDATE_POINTER0(hLayer, "OGR_L_SetStyleTableDirectly");
    4777             : 
    4778           0 :     OGRLayer::FromHandle(hLayer)->SetStyleTableDirectly(
    4779           0 :         reinterpret_cast<OGRStyleTable *>(hStyleTable));
    4780             : }
    4781             : 
    4782             : /************************************************************************/
    4783             : /*                        OGR_L_SetStyleTable()                         */
    4784             : /************************************************************************/
    4785             : 
    4786           2 : void OGR_L_SetStyleTable(OGRLayerH hLayer, OGRStyleTableH hStyleTable)
    4787             : 
    4788             : {
    4789           2 :     VALIDATE_POINTER0(hLayer, "OGR_L_SetStyleTable");
    4790           2 :     VALIDATE_POINTER0(hStyleTable, "OGR_L_SetStyleTable");
    4791             : 
    4792           2 :     OGRLayer::FromHandle(hLayer)->SetStyleTable(
    4793           2 :         reinterpret_cast<OGRStyleTable *>(hStyleTable));
    4794             : }
    4795             : 
    4796             : /************************************************************************/
    4797             : /*                              GetName()                               */
    4798             : /************************************************************************/
    4799             : 
    4800             : /**
    4801             :  \brief Return the layer name.
    4802             : 
    4803             :  This returns the same content as GetLayerDefn()->OGRFeatureDefn::GetName(), but for a
    4804             :  few drivers, calling GetName() directly can avoid lengthy layer
    4805             :  definition initialization.
    4806             : 
    4807             :  This method is the same as the C function OGR_L_GetName().
    4808             : 
    4809             :  If this method is derived in a driver, it must be done such that it
    4810             :  returns the same content as GetLayerDefn()->OGRFeatureDefn::GetName().
    4811             : 
    4812             :  @return the layer name (must not been freed)
    4813             : */
    4814             : 
    4815     1511600 : const char *OGRLayer::GetName() const
    4816             : 
    4817             : {
    4818     1511600 :     return GetLayerDefn()->GetName();
    4819             : }
    4820             : 
    4821             : /************************************************************************/
    4822             : /*                           OGR_L_GetName()                            */
    4823             : /************************************************************************/
    4824             : 
    4825             : /**
    4826             :  \brief Return the layer name.
    4827             : 
    4828             :  This returns the same content as OGR_FD_GetName(OGR_L_GetLayerDefn(hLayer)),
    4829             :  but for a few drivers, calling OGR_L_GetName() directly can avoid lengthy
    4830             :  layer definition initialization.
    4831             : 
    4832             :  This function is the same as the C++ method OGRLayer::GetName().
    4833             : 
    4834             :  @param hLayer handle to the layer.
    4835             :  @return the layer name (must not been freed)
    4836             : */
    4837             : 
    4838        1360 : const char *OGR_L_GetName(OGRLayerH hLayer)
    4839             : 
    4840             : {
    4841        1360 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetName", "");
    4842             : 
    4843             : #ifdef OGRAPISPY_ENABLED
    4844        1360 :     if (bOGRAPISpyEnabled)
    4845           2 :         OGRAPISpy_L_GetName(hLayer);
    4846             : #endif
    4847             : 
    4848        1360 :     return OGRLayer::FromHandle(hLayer)->GetName();
    4849             : }
    4850             : 
    4851             : /************************************************************************/
    4852             : /*                            GetGeomType()                             */
    4853             : /************************************************************************/
    4854             : 
    4855             : /**
    4856             :  \brief Return the layer geometry type.
    4857             : 
    4858             :  This returns the same result as GetLayerDefn()->OGRFeatureDefn::GetGeomType(), but for a
    4859             :  few drivers, calling GetGeomType() directly can avoid lengthy layer
    4860             :  definition initialization.
    4861             : 
    4862             :  Note that even if this method is const (since GDAL 3.12), there is no guarantee
    4863             :  it can be safely called by concurrent threads on the same GDALDataset object.
    4864             : 
    4865             :  For layers with multiple geometry fields, this method only returns the geometry
    4866             :  type of the first geometry column. For other columns, use
    4867             :  GetLayerDefn()->OGRFeatureDefn::GetGeomFieldDefn(i)->GetType().
    4868             :  For layers without any geometry field, this method returns wkbNone.
    4869             : 
    4870             :  This method is the same as the C function OGR_L_GetGeomType().
    4871             : 
    4872             :  If this method is derived in a driver, it must be done such that it
    4873             :  returns the same content as GetLayerDefn()->OGRFeatureDefn::GetGeomType().
    4874             : 
    4875             :  @return the geometry type
    4876             : */
    4877             : 
    4878      220597 : OGRwkbGeometryType OGRLayer::GetGeomType() const
    4879             : {
    4880      220597 :     const OGRFeatureDefn *poLayerDefn = GetLayerDefn();
    4881      220597 :     if (poLayerDefn == nullptr)
    4882             :     {
    4883           0 :         CPLDebug("OGR", "GetLayerType() returns NULL !");
    4884           0 :         return wkbUnknown;
    4885             :     }
    4886      220597 :     return poLayerDefn->GetGeomType();
    4887             : }
    4888             : 
    4889             : /************************************************************************/
    4890             : /*                         OGR_L_GetGeomType()                          */
    4891             : /************************************************************************/
    4892             : 
    4893             : /**
    4894             :  \brief Return the layer geometry type.
    4895             : 
    4896             :  This returns the same result as OGR_FD_GetGeomType(OGR_L_GetLayerDefn(hLayer)),
    4897             :  but for a few drivers, calling OGR_L_GetGeomType() directly can avoid lengthy
    4898             :  layer definition initialization.
    4899             : 
    4900             :  For layers with multiple geometry fields, this method only returns the geometry
    4901             :  type of the first geometry column. For other columns, use
    4902             :  OGR_GFld_GetType(OGR_FD_GetGeomFieldDefn(OGR_L_GetLayerDefn(hLayer), i)).
    4903             :  For layers without any geometry field, this method returns wkbNone.
    4904             : 
    4905             :  This function is the same as the C++ method OGRLayer::GetGeomType().
    4906             : 
    4907             :  @param hLayer handle to the layer.
    4908             :  @return the geometry type
    4909             : */
    4910             : 
    4911        1335 : OGRwkbGeometryType OGR_L_GetGeomType(OGRLayerH hLayer)
    4912             : 
    4913             : {
    4914        1335 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetGeomType", wkbUnknown);
    4915             : 
    4916             : #ifdef OGRAPISPY_ENABLED
    4917        1335 :     if (bOGRAPISpyEnabled)
    4918           2 :         OGRAPISpy_L_GetGeomType(hLayer);
    4919             : #endif
    4920             : 
    4921        1335 :     OGRwkbGeometryType eType = OGRLayer::FromHandle(hLayer)->GetGeomType();
    4922        1335 :     if (OGR_GT_IsNonLinear(eType) && !OGRGetNonLinearGeometriesEnabledFlag())
    4923             :     {
    4924           1 :         eType = OGR_GT_GetLinear(eType);
    4925             :     }
    4926        1335 :     return eType;
    4927             : }
    4928             : 
    4929             : /************************************************************************/
    4930             : /*                          SetIgnoredFields()                          */
    4931             : /************************************************************************/
    4932             : 
    4933             : /**
    4934             :  \brief Set which fields can be omitted when retrieving features from the layer.
    4935             : 
    4936             :  If the driver supports this functionality (testable using OLCIgnoreFields capability), it will not fetch the specified fields
    4937             :  in subsequent calls to GetFeature() / GetNextFeature() and thus save some processing time and/or bandwidth.
    4938             : 
    4939             :  Besides field names of the layers, the following special fields can be passed: "OGR_GEOMETRY" to ignore geometry and
    4940             :  "OGR_STYLE" to ignore layer style.
    4941             : 
    4942             :  By default, no fields are ignored.
    4943             : 
    4944             :  Note that fields that are used in an attribute filter should generally not be set as
    4945             :  ignored fields, as most drivers (such as those relying on the OGR SQL engine)
    4946             :  will be unable to correctly evaluate the attribute filter.
    4947             : 
    4948             :  This method is the same as the C function OGR_L_SetIgnoredFields()
    4949             : 
    4950             :  @param papszFields an array of field names terminated by NULL item. If NULL is passed, the ignored list is cleared.
    4951             :  @return OGRERR_NONE if all field names have been resolved (even if the driver does not support this method)
    4952             : */
    4953             : 
    4954        8604 : OGRErr OGRLayer::SetIgnoredFields(CSLConstList papszFields)
    4955             : {
    4956        8604 :     OGRFeatureDefn *poDefn = GetLayerDefn();
    4957             : 
    4958             :     // first set everything as *not* ignored
    4959       64066 :     for (int iField = 0; iField < poDefn->GetFieldCount(); iField++)
    4960             :     {
    4961       55462 :         poDefn->GetFieldDefn(iField)->SetIgnored(FALSE);
    4962             :     }
    4963       18055 :     for (int iField = 0; iField < poDefn->GetGeomFieldCount(); iField++)
    4964             :     {
    4965        9451 :         poDefn->GetGeomFieldDefn(iField)->SetIgnored(FALSE);
    4966             :     }
    4967        8604 :     poDefn->SetStyleIgnored(FALSE);
    4968             : 
    4969             :     // ignore some fields
    4970       14233 :     for (const char *pszFieldName : cpl::Iterate(papszFields))
    4971             :     {
    4972             :         // check special fields
    4973        5629 :         if (EQUAL(pszFieldName, "OGR_GEOMETRY"))
    4974         163 :             poDefn->SetGeometryIgnored(TRUE);
    4975        5466 :         else if (EQUAL(pszFieldName, "OGR_STYLE"))
    4976          13 :             poDefn->SetStyleIgnored(TRUE);
    4977             :         else
    4978             :         {
    4979             :             // check ordinary fields
    4980        5453 :             int iField = poDefn->GetFieldIndex(pszFieldName);
    4981        5453 :             if (iField == -1)
    4982             :             {
    4983             :                 // check geometry field
    4984        1045 :                 iField = poDefn->GetGeomFieldIndex(pszFieldName);
    4985        1045 :                 if (iField == -1)
    4986             :                 {
    4987           0 :                     return OGRERR_FAILURE;
    4988             :                 }
    4989             :                 else
    4990        1045 :                     poDefn->GetGeomFieldDefn(iField)->SetIgnored(TRUE);
    4991             :             }
    4992             :             else
    4993        4408 :                 poDefn->GetFieldDefn(iField)->SetIgnored(TRUE);
    4994             :         }
    4995             :     }
    4996             : 
    4997        8604 :     return OGRERR_NONE;
    4998             : }
    4999             : 
    5000             : /************************************************************************/
    5001             : /*                       OGR_L_SetIgnoredFields()                       */
    5002             : /************************************************************************/
    5003             : 
    5004             : /**
    5005             :  \brief Set which fields can be omitted when retrieving features from the layer.
    5006             : 
    5007             :  If the driver supports this functionality (testable using OLCIgnoreFields capability), it will not fetch the specified fields
    5008             :  in subsequent calls to GetFeature() / GetNextFeature() and thus save some processing time and/or bandwidth.
    5009             : 
    5010             :  Besides field names of the layers, the following special fields can be passed: "OGR_GEOMETRY" to ignore geometry and
    5011             :  "OGR_STYLE" to ignore layer style.
    5012             : 
    5013             :  By default, no fields are ignored.
    5014             : 
    5015             :  Note that fields that are used in an attribute filter should generally not be set as
    5016             :  ignored fields, as most drivers (such as those relying on the OGR SQL engine)
    5017             :  will be unable to correctly evaluate the attribute filter.
    5018             : 
    5019             :  This method is the same as the C++ method OGRLayer::SetIgnoredFields()
    5020             : 
    5021             :  @param hLayer handle to the layer
    5022             :  @param papszFields an array of field names terminated by NULL item. If NULL is passed, the ignored list is cleared.
    5023             :  @return OGRERR_NONE if all field names have been resolved (even if the driver does not support this method)
    5024             : */
    5025             : 
    5026         324 : OGRErr OGR_L_SetIgnoredFields(OGRLayerH hLayer, const char **papszFields)
    5027             : 
    5028             : {
    5029         324 :     VALIDATE_POINTER1(hLayer, "OGR_L_SetIgnoredFields", OGRERR_INVALID_HANDLE);
    5030             : 
    5031             : #ifdef OGRAPISPY_ENABLED
    5032         324 :     if (bOGRAPISpyEnabled)
    5033           2 :         OGRAPISpy_L_SetIgnoredFields(hLayer, papszFields);
    5034             : #endif
    5035             : 
    5036         324 :     return OGRLayer::FromHandle(hLayer)->SetIgnoredFields(papszFields);
    5037             : }
    5038             : 
    5039             : /************************************************************************/
    5040             : /*                               Rename()                               */
    5041             : /************************************************************************/
    5042             : 
    5043             : /** Rename layer.
    5044             :  *
    5045             :  * This operation is implemented only by layers that expose the OLCRename
    5046             :  * capability, and drivers that expose the GDAL_DCAP_RENAME_LAYERS capability
    5047             :  *
    5048             :  * This operation will fail if a layer with the new name already exists.
    5049             :  *
    5050             :  * On success, GetDescription() and GetLayerDefn()->GetName() will return
    5051             :  * pszNewName.
    5052             :  *
    5053             :  * Renaming the layer may interrupt current feature iteration.
    5054             :  *
    5055             :  * @param pszNewName New layer name. Must not be NULL.
    5056             :  * @return OGRERR_NONE in case of success
    5057             :  *
    5058             :  * @since GDAL 3.5
    5059             :  */
    5060           0 : OGRErr OGRLayer::Rename(CPL_UNUSED const char *pszNewName)
    5061             : {
    5062           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    5063             :              "Rename() not supported by this layer.");
    5064             : 
    5065           0 :     return OGRERR_UNSUPPORTED_OPERATION;
    5066             : }
    5067             : 
    5068             : /************************************************************************/
    5069             : /*                            OGR_L_Rename()                            */
    5070             : /************************************************************************/
    5071             : 
    5072             : /** Rename layer.
    5073             :  *
    5074             :  * This operation is implemented only by layers that expose the OLCRename
    5075             :  * capability, and drivers that expose the GDAL_DCAP_RENAME_LAYERS capability
    5076             :  *
    5077             :  * This operation will fail if a layer with the new name already exists.
    5078             :  *
    5079             :  * On success, GetDescription() and GetLayerDefn()->GetName() will return
    5080             :  * pszNewName.
    5081             :  *
    5082             :  * Renaming the layer may interrupt current feature iteration.
    5083             :  *
    5084             :  * @param hLayer     Layer to rename.
    5085             :  * @param pszNewName New layer name. Must not be NULL.
    5086             :  * @return OGRERR_NONE in case of success
    5087             :  *
    5088             :  * @since GDAL 3.5
    5089             :  */
    5090          30 : OGRErr OGR_L_Rename(OGRLayerH hLayer, const char *pszNewName)
    5091             : 
    5092             : {
    5093          30 :     VALIDATE_POINTER1(hLayer, "OGR_L_Rename", OGRERR_INVALID_HANDLE);
    5094          30 :     VALIDATE_POINTER1(pszNewName, "OGR_L_Rename", OGRERR_FAILURE);
    5095             : 
    5096          30 :     return OGRLayer::FromHandle(hLayer)->Rename(pszNewName);
    5097             : }
    5098             : 
    5099             : /************************************************************************/
    5100             : /*              helper functions for layer overlay methods              */
    5101             : /************************************************************************/
    5102             : 
    5103          85 : static OGRErr clone_spatial_filter(OGRLayer *pLayer, OGRGeometry **ppGeometry)
    5104             : {
    5105          85 :     OGRErr ret = OGRERR_NONE;
    5106          85 :     OGRGeometry *g = pLayer->GetSpatialFilter();
    5107          85 :     *ppGeometry = g ? g->clone() : nullptr;
    5108          85 :     return ret;
    5109             : }
    5110             : 
    5111         113 : static OGRErr create_field_map(OGRFeatureDefn *poDefn, int **map)
    5112             : {
    5113         113 :     OGRErr ret = OGRERR_NONE;
    5114         113 :     int n = poDefn->GetFieldCount();
    5115         113 :     if (n > 0)
    5116             :     {
    5117          85 :         *map = static_cast<int *>(VSI_MALLOC_VERBOSE(sizeof(int) * n));
    5118          85 :         if (!(*map))
    5119           0 :             return OGRERR_NOT_ENOUGH_MEMORY;
    5120         239 :         for (int i = 0; i < n; i++)
    5121         154 :             (*map)[i] = -1;
    5122             :     }
    5123         113 :     return ret;
    5124             : }
    5125             : 
    5126          62 : static OGRErr set_result_schema(OGRLayer *pLayerResult,
    5127             :                                 OGRFeatureDefn *poDefnInput,
    5128             :                                 OGRFeatureDefn *poDefnMethod, int *mapInput,
    5129             :                                 int *mapMethod, bool combined,
    5130             :                                 const char *const *papszOptions)
    5131             : {
    5132          62 :     if (!CPLTestBool(CSLFetchNameValueDef(papszOptions, "ADD_FIELDS", "YES")))
    5133           0 :         return OGRERR_NONE;
    5134             : 
    5135          62 :     OGRErr ret = OGRERR_NONE;
    5136          62 :     OGRFeatureDefn *poDefnResult = pLayerResult->GetLayerDefn();
    5137             :     const char *pszInputPrefix =
    5138          62 :         CSLFetchNameValue(papszOptions, "INPUT_PREFIX");
    5139             :     const char *pszMethodPrefix =
    5140          62 :         CSLFetchNameValue(papszOptions, "METHOD_PREFIX");
    5141             :     const bool bSkipFailures =
    5142          62 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "SKIP_FAILURES", "NO"));
    5143          62 :     if (poDefnResult->GetFieldCount() > 0)
    5144             :     {
    5145             :         // the user has defined the schema of the output layer
    5146          24 :         if (mapInput)
    5147             :         {
    5148          62 :             for (int iField = 0; iField < poDefnInput->GetFieldCount();
    5149             :                  iField++)
    5150             :             {
    5151             :                 CPLString osName(
    5152          38 :                     poDefnInput->GetFieldDefn(iField)->GetNameRef());
    5153          38 :                 if (pszInputPrefix != nullptr)
    5154          24 :                     osName = pszInputPrefix + osName;
    5155          38 :                 mapInput[iField] = poDefnResult->GetFieldIndex(osName);
    5156             :             }
    5157             :         }
    5158          24 :         if (!mapMethod)
    5159           4 :             return ret;
    5160             :         // cppcheck-suppress nullPointer
    5161          54 :         for (int iField = 0; iField < poDefnMethod->GetFieldCount(); iField++)
    5162             :         {
    5163             :             // cppcheck-suppress nullPointer
    5164          34 :             CPLString osName(poDefnMethod->GetFieldDefn(iField)->GetNameRef());
    5165          34 :             if (pszMethodPrefix != nullptr)
    5166          24 :                 osName = pszMethodPrefix + osName;
    5167          34 :             mapMethod[iField] = poDefnResult->GetFieldIndex(osName);
    5168             :         }
    5169             :     }
    5170             :     else
    5171             :     {
    5172             :         // use schema from the input layer or from input and method layers
    5173          38 :         const int nFieldsInput = poDefnInput->GetFieldCount();
    5174             : 
    5175             :         // If no prefix is specified and we have input+method layers, make
    5176             :         // sure we will generate unique field names
    5177          38 :         std::set<std::string> oSetInputFieldNames;
    5178          38 :         std::set<std::string> oSetMethodFieldNames;
    5179          38 :         if (poDefnMethod != nullptr && pszInputPrefix == nullptr &&
    5180             :             pszMethodPrefix == nullptr)
    5181             :         {
    5182          67 :             for (int iField = 0; iField < nFieldsInput; iField++)
    5183             :             {
    5184             :                 oSetInputFieldNames.insert(
    5185          36 :                     poDefnInput->GetFieldDefn(iField)->GetNameRef());
    5186             :             }
    5187          31 :             const int nFieldsMethod = poDefnMethod->GetFieldCount();
    5188          65 :             for (int iField = 0; iField < nFieldsMethod; iField++)
    5189             :             {
    5190             :                 oSetMethodFieldNames.insert(
    5191          34 :                     poDefnMethod->GetFieldDefn(iField)->GetNameRef());
    5192             :             }
    5193             :         }
    5194             : 
    5195          38 :         const bool bAddInputFields = CPLTestBool(
    5196             :             CSLFetchNameValueDef(papszOptions, "ADD_INPUT_FIELDS", "YES"));
    5197          38 :         if (bAddInputFields)
    5198             :         {
    5199          70 :             for (int iField = 0; iField < nFieldsInput; iField++)
    5200             :             {
    5201          36 :                 OGRFieldDefn oFieldDefn(poDefnInput->GetFieldDefn(iField));
    5202          36 :                 if (pszInputPrefix != nullptr)
    5203           0 :                     oFieldDefn.SetName(CPLSPrintf("%s%s", pszInputPrefix,
    5204             :                                                   oFieldDefn.GetNameRef()));
    5205          58 :                 else if (!oSetMethodFieldNames.empty() &&
    5206          58 :                          oSetMethodFieldNames.find(oFieldDefn.GetNameRef()) !=
    5207          58 :                              oSetMethodFieldNames.end())
    5208             :                 {
    5209             :                     // Field of same name present in method layer
    5210          13 :                     oFieldDefn.SetName(
    5211             :                         CPLSPrintf("input_%s", oFieldDefn.GetNameRef()));
    5212             :                 }
    5213          36 :                 ret = pLayerResult->CreateField(&oFieldDefn);
    5214          36 :                 if (ret != OGRERR_NONE)
    5215             :                 {
    5216           0 :                     if (!bSkipFailures)
    5217           0 :                         return ret;
    5218             :                     else
    5219             :                     {
    5220           0 :                         CPLErrorReset();
    5221           0 :                         ret = OGRERR_NONE;
    5222             :                     }
    5223             :                 }
    5224          36 :                 if (mapInput)
    5225          36 :                     mapInput[iField] =
    5226          36 :                         pLayerResult->GetLayerDefn()->GetFieldCount() - 1;
    5227             :             }
    5228             :         }
    5229             : 
    5230          38 :         if (!combined)
    5231          11 :             return ret;
    5232          27 :         if (!mapMethod)
    5233          12 :             return ret;
    5234          15 :         if (!poDefnMethod)
    5235           0 :             return ret;
    5236             : 
    5237          15 :         const bool bAddMethodFields = CPLTestBool(
    5238             :             CSLFetchNameValueDef(papszOptions, "ADD_METHOD_FIELDS", "YES"));
    5239          15 :         if (bAddMethodFields)
    5240             :         {
    5241          11 :             const int nFieldsMethod = poDefnMethod->GetFieldCount();
    5242          29 :             for (int iField = 0; iField < nFieldsMethod; iField++)
    5243             :             {
    5244          18 :                 OGRFieldDefn oFieldDefn(poDefnMethod->GetFieldDefn(iField));
    5245          18 :                 if (pszMethodPrefix != nullptr)
    5246           0 :                     oFieldDefn.SetName(CPLSPrintf("%s%s", pszMethodPrefix,
    5247             :                                                   oFieldDefn.GetNameRef()));
    5248          36 :                 else if (!oSetInputFieldNames.empty() &&
    5249          36 :                          oSetInputFieldNames.find(oFieldDefn.GetNameRef()) !=
    5250          36 :                              oSetInputFieldNames.end())
    5251             :                 {
    5252             :                     // Field of same name present in method layer
    5253          11 :                     oFieldDefn.SetName(
    5254             :                         CPLSPrintf("method_%s", oFieldDefn.GetNameRef()));
    5255             :                 }
    5256          18 :                 ret = pLayerResult->CreateField(&oFieldDefn);
    5257          18 :                 if (ret != OGRERR_NONE)
    5258             :                 {
    5259           0 :                     if (!bSkipFailures)
    5260           0 :                         return ret;
    5261             :                     else
    5262             :                     {
    5263           0 :                         CPLErrorReset();
    5264           0 :                         ret = OGRERR_NONE;
    5265             :                     }
    5266             :                 }
    5267          18 :                 mapMethod[iField] =
    5268          18 :                     pLayerResult->GetLayerDefn()->GetFieldCount() - 1;
    5269             :             }
    5270             :         }
    5271             :     }
    5272          35 :     return ret;
    5273             : }
    5274             : 
    5275         323 : static OGRGeometry *set_filter_from(OGRLayer *pLayer,
    5276             :                                     OGRGeometry *pGeometryExistingFilter,
    5277             :                                     OGRFeature *pFeature)
    5278             : {
    5279         323 :     OGRGeometry *geom = pFeature->GetGeometryRef();
    5280         323 :     if (!geom)
    5281           0 :         return nullptr;
    5282         323 :     if (pGeometryExistingFilter)
    5283             :     {
    5284           0 :         if (!geom->Intersects(pGeometryExistingFilter))
    5285           0 :             return nullptr;
    5286           0 :         OGRGeometry *intersection = geom->Intersection(pGeometryExistingFilter);
    5287           0 :         if (intersection)
    5288             :         {
    5289           0 :             pLayer->SetSpatialFilter(intersection);
    5290           0 :             delete intersection;
    5291             :         }
    5292             :         else
    5293           0 :             return nullptr;
    5294             :     }
    5295             :     else
    5296             :     {
    5297         323 :         pLayer->SetSpatialFilter(geom);
    5298             :     }
    5299         323 :     return geom;
    5300             : }
    5301             : 
    5302             : static std::unique_ptr<OGRGeometry>
    5303          24 : promote_to_multi(std::unique_ptr<OGRGeometry> poGeom)
    5304             : {
    5305          24 :     OGRwkbGeometryType eType = wkbFlatten(poGeom->getGeometryType());
    5306          24 :     if (eType == wkbPoint)
    5307             :         return std::unique_ptr<OGRGeometry>(
    5308           1 :             OGRGeometryFactory::forceToMultiPoint(poGeom.release()));
    5309          23 :     else if (eType == wkbPolygon)
    5310             :         return std::unique_ptr<OGRGeometry>(
    5311          23 :             OGRGeometryFactory::forceToMultiPolygon(poGeom.release()));
    5312           0 :     else if (eType == wkbLineString)
    5313             :         return std::unique_ptr<OGRGeometry>(
    5314           0 :             OGRGeometryFactory::forceToMultiLineString(poGeom.release()));
    5315             :     else
    5316           0 :         return poGeom;
    5317             : }
    5318             : 
    5319             : static std::unique_ptr<OGRGeometry>
    5320         231 : convert_geometry(std::unique_ptr<OGRGeometry> poGeom, bool bPromoteToMulti,
    5321             :                  OGRwkbGeometryType eOutputGeometryType)
    5322             : {
    5323         231 :     if (eOutputGeometryType != wkbUnknown)
    5324             :     {
    5325             :         poGeom =
    5326         105 :             OGRGeometryFactory::forceTo(std::move(poGeom), eOutputGeometryType);
    5327         105 :         if (poGeom && poGeom->getGeometryType() != eOutputGeometryType)
    5328           1 :             return nullptr;
    5329         104 :         return poGeom;
    5330             :     }
    5331         126 :     else if (bPromoteToMulti)
    5332          24 :         return promote_to_multi(std::move(poGeom));
    5333             :     else
    5334         102 :         return poGeom;
    5335             : }
    5336             : 
    5337             : /************************************************************************/
    5338             : /*                            Intersection()                            */
    5339             : /************************************************************************/
    5340             : /**
    5341             :  * \brief Intersection of two layers.
    5342             :  *
    5343             :  * The result layer contains features whose geometries represent areas
    5344             :  * that are common between features in the input layer and in the
    5345             :  * method layer. The features in the result layer have attributes from
    5346             :  * both input and method layers. The schema of the result layer can be
    5347             :  * set by the user or, if it is empty, is initialized to contain all
    5348             :  * fields in the input and method layers.
    5349             :  *
    5350             :  * \note If the schema of the result is set by user and contains
    5351             :  * fields that have the same name as a field in input and in method
    5352             :  * layer, then the attribute in the result feature will get the value
    5353             :  * from the feature of the method layer.
    5354             :  *
    5355             :  * \note For best performance use the minimum amount of features in
    5356             :  * the method layer and copy it into a memory layer.
    5357             :  *
    5358             :  * \note This method relies on GEOS support. Do not use unless the
    5359             :  * GEOS support is compiled in.
    5360             :  *
    5361             :  * The recognized list of options is:
    5362             :  * <ul>
    5363             :  * <li>SKIP_FAILURES=YES/NO. Set to YES to go on, even when a
    5364             :  *     feature could not be inserted or a GEOS call failed.
    5365             :  * </li>
    5366             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    5367             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    5368             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    5369             :  * </li>
    5370             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    5371             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    5372             :  *     be converted to it, the corresponding output feature is silently skipped.
    5373             :  *     Takes precedence over PROMOTE_TO_MULTI.
    5374             :  * </li>
    5375             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    5376             :  *     will be created from the fields of the input layer.
    5377             :  * </li>
    5378             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    5379             :  *     will be created from the fields of the method layer.
    5380             :  * </li>
    5381             :  * <li>USE_PREPARED_GEOMETRIES=YES/NO. Set to NO to not use prepared
    5382             :  *     geometries to pretest intersection of features of method layer
    5383             :  *     with features of this layer.
    5384             :  * </li>
    5385             :  * <li>PRETEST_CONTAINMENT=YES/NO. Set to YES to pretest the
    5386             :  *     containment of features of method layer within the features of
    5387             :  *     this layer. This will speed up the method significantly in some
    5388             :  *     cases. Requires that the prepared geometries are in effect.
    5389             :  * </li>
    5390             :  * <li>KEEP_LOWER_DIMENSION_GEOMETRIES=YES/NO. Set to NO to skip
    5391             :  *     result features with lower dimension geometry that would
    5392             :  *     otherwise be added to the result layer. The default is YES, to add
    5393             :  *     features with lower dimension geometry, but only if the result layer
    5394             :  *     has an unknown geometry type.
    5395             :  * </li>
    5396             :  * </ul>
    5397             :  *
    5398             :  * This method is the same as the C function OGR_L_Intersection().
    5399             :  *
    5400             :  * @param pLayerMethod the method layer. Should not be NULL.
    5401             :  *
    5402             :  * @param pLayerResult the layer where the features resulting from the
    5403             :  * operation are inserted. Should not be NULL. See above the note
    5404             :  * about the schema.
    5405             :  *
    5406             :  * @param papszOptions NULL terminated list of options (may be NULL).
    5407             :  *
    5408             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    5409             :  * reporting progress or NULL.
    5410             :  *
    5411             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    5412             :  *
    5413             :  * @return an error code if there was an error or the execution was
    5414             :  * interrupted, OGRERR_NONE otherwise.
    5415             :  *
    5416             :  * @note The first geometry field is always used.
    5417             :  *
    5418             :  * @since OGR 1.10
    5419             :  */
    5420             : 
    5421          15 : OGRErr OGRLayer::Intersection(OGRLayer *pLayerMethod, OGRLayer *pLayerResult,
    5422             :                               CSLConstList papszOptions,
    5423             :                               GDALProgressFunc pfnProgress, void *pProgressArg)
    5424             : {
    5425          15 :     OGRErr ret = OGRERR_NONE;
    5426          15 :     OGRFeatureDefn *poDefnInput = GetLayerDefn();
    5427          15 :     OGRFeatureDefn *poDefnMethod = pLayerMethod->GetLayerDefn();
    5428          15 :     OGRFeatureDefn *poDefnResult = nullptr;
    5429          15 :     OGRGeometry *pGeometryMethodFilter = nullptr;
    5430          15 :     int *mapInput = nullptr;
    5431          15 :     int *mapMethod = nullptr;
    5432          15 :     OGREnvelope sEnvelopeMethod;
    5433             :     GBool bEnvelopeSet;
    5434          15 :     double progress_max = static_cast<double>(GetFeatureCount(FALSE));
    5435          15 :     double progress_counter = 0;
    5436          15 :     double progress_ticker = 0;
    5437             :     const bool bSkipFailures =
    5438          15 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "SKIP_FAILURES", "NO"));
    5439          15 :     const bool bPromoteToMulti = CPLTestBool(
    5440             :         CSLFetchNameValueDef(papszOptions, "PROMOTE_TO_MULTI", "NO"));
    5441          15 :     const bool bUsePreparedGeometries = CPLTestBool(
    5442             :         CSLFetchNameValueDef(papszOptions, "USE_PREPARED_GEOMETRIES", "YES"));
    5443          15 :     const bool bPretestContainment = CPLTestBool(
    5444             :         CSLFetchNameValueDef(papszOptions, "PRETEST_CONTAINMENT", "NO"));
    5445          15 :     bool bKeepLowerDimGeom = CPLTestBool(CSLFetchNameValueDef(
    5446             :         papszOptions, "KEEP_LOWER_DIMENSION_GEOMETRIES", "YES"));
    5447             :     const char *pszOutputGeometryType =
    5448          15 :         CSLFetchNameValueDef(papszOptions, "OUTPUT_GEOMETRY_TYPE", "GEOMETRY");
    5449          15 :     const auto eOutputGeometryType = OGRFromOGCGeomType(pszOutputGeometryType);
    5450             : 
    5451             :     // check for GEOS
    5452          15 :     if (!OGRGeometryFactory::haveGEOS())
    5453             :     {
    5454           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5455             :                  "OGRLayer::Intersection() requires GEOS support");
    5456           0 :         return OGRERR_UNSUPPORTED_OPERATION;
    5457             :     }
    5458             : 
    5459             :     // get resources
    5460          15 :     ret = clone_spatial_filter(pLayerMethod, &pGeometryMethodFilter);
    5461          15 :     if (ret != OGRERR_NONE)
    5462           0 :         goto done;
    5463          15 :     ret = create_field_map(poDefnInput, &mapInput);
    5464          15 :     if (ret != OGRERR_NONE)
    5465           0 :         goto done;
    5466          15 :     ret = create_field_map(poDefnMethod, &mapMethod);
    5467          15 :     if (ret != OGRERR_NONE)
    5468           0 :         goto done;
    5469          15 :     ret = set_result_schema(pLayerResult, poDefnInput, poDefnMethod, mapInput,
    5470             :                             mapMethod, true, papszOptions);
    5471          15 :     if (ret != OGRERR_NONE)
    5472           0 :         goto done;
    5473          15 :     poDefnResult = pLayerResult->GetLayerDefn();
    5474          15 :     bEnvelopeSet = pLayerMethod->GetExtent(&sEnvelopeMethod, 1) == OGRERR_NONE;
    5475          15 :     if (bKeepLowerDimGeom)
    5476             :     {
    5477             :         // require that the result layer is of geom type unknown
    5478          13 :         if (pLayerResult->GetGeomType() != wkbUnknown)
    5479             :         {
    5480           1 :             CPLDebug("OGR", "Resetting KEEP_LOWER_DIMENSION_GEOMETRIES to NO "
    5481             :                             "since the result layer does not allow it.");
    5482           1 :             bKeepLowerDimGeom = false;
    5483             :         }
    5484             :     }
    5485             : 
    5486          44 :     for (auto &&x : this)
    5487             :     {
    5488             : 
    5489          29 :         if (pfnProgress)
    5490             :         {
    5491           2 :             double p = progress_counter / progress_max;
    5492           2 :             if (p > progress_ticker)
    5493             :             {
    5494           1 :                 if (!pfnProgress(p, "", pProgressArg))
    5495             :                 {
    5496           0 :                     CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    5497           0 :                     ret = OGRERR_FAILURE;
    5498           0 :                     goto done;
    5499             :                 }
    5500             :             }
    5501           2 :             progress_counter += 1.0;
    5502             :         }
    5503             : 
    5504             :         // is it worth to proceed?
    5505          29 :         if (bEnvelopeSet)
    5506             :         {
    5507          29 :             OGRGeometry *x_geom = x->GetGeometryRef();
    5508          29 :             if (x_geom)
    5509             :             {
    5510          29 :                 OGREnvelope x_env;
    5511          29 :                 x_geom->getEnvelope(&x_env);
    5512          29 :                 if (x_env.MaxX < sEnvelopeMethod.MinX ||
    5513          29 :                     x_env.MaxY < sEnvelopeMethod.MinY ||
    5514          29 :                     sEnvelopeMethod.MaxX < x_env.MinX ||
    5515          29 :                     sEnvelopeMethod.MaxY < x_env.MinY)
    5516             :                 {
    5517           0 :                     continue;
    5518             :                 }
    5519             :             }
    5520             :             else
    5521             :             {
    5522           0 :                 continue;
    5523             :             }
    5524             :         }
    5525             : 
    5526             :         // set up the filter for method layer
    5527          29 :         CPLErrorReset();
    5528             :         OGRGeometry *x_geom =
    5529          29 :             set_filter_from(pLayerMethod, pGeometryMethodFilter, x.get());
    5530          29 :         if (CPLGetLastErrorType() != CE_None)
    5531             :         {
    5532           0 :             if (!bSkipFailures)
    5533             :             {
    5534           0 :                 ret = OGRERR_FAILURE;
    5535           0 :                 goto done;
    5536             :             }
    5537             :             else
    5538             :             {
    5539           0 :                 CPLErrorReset();
    5540           0 :                 ret = OGRERR_NONE;
    5541             :             }
    5542             :         }
    5543          29 :         if (!x_geom)
    5544             :         {
    5545           0 :             continue;
    5546             :         }
    5547             : 
    5548           0 :         OGRPreparedGeometryUniquePtr x_prepared_geom;
    5549          29 :         if (bUsePreparedGeometries)
    5550             :         {
    5551          29 :             x_prepared_geom.reset(
    5552             :                 OGRCreatePreparedGeometry(OGRGeometry::ToHandle(x_geom)));
    5553          29 :             if (!x_prepared_geom)
    5554             :             {
    5555           0 :                 goto done;
    5556             :             }
    5557             :         }
    5558             : 
    5559          60 :         for (auto &&y : pLayerMethod)
    5560             :         {
    5561          31 :             OGRGeometry *y_geom = y->GetGeometryRef();
    5562          31 :             if (!y_geom)
    5563           5 :                 continue;
    5564           0 :             std::unique_ptr<OGRGeometry> z_geom;
    5565             : 
    5566          31 :             if (x_prepared_geom)
    5567             :             {
    5568          31 :                 CPLErrorReset();
    5569          31 :                 ret = OGRERR_NONE;
    5570          31 :                 if (bPretestContainment &&
    5571           0 :                     OGRPreparedGeometryContains(x_prepared_geom.get(),
    5572             :                                                 OGRGeometry::ToHandle(y_geom)))
    5573             :                 {
    5574           0 :                     if (CPLGetLastErrorType() == CE_None)
    5575           0 :                         z_geom.reset(y_geom->clone());
    5576             :                 }
    5577          31 :                 else if (!(OGRPreparedGeometryIntersects(
    5578             :                              x_prepared_geom.get(),
    5579             :                              OGRGeometry::ToHandle(y_geom))))
    5580             :                 {
    5581           0 :                     if (CPLGetLastErrorType() == CE_None)
    5582             :                     {
    5583           0 :                         continue;
    5584             :                     }
    5585             :                 }
    5586          31 :                 if (CPLGetLastErrorType() != CE_None)
    5587             :                 {
    5588           0 :                     if (!bSkipFailures)
    5589             :                     {
    5590           0 :                         ret = OGRERR_FAILURE;
    5591           0 :                         goto done;
    5592             :                     }
    5593             :                     else
    5594             :                     {
    5595           0 :                         CPLErrorReset();
    5596           0 :                         ret = OGRERR_NONE;
    5597           0 :                         continue;
    5598             :                     }
    5599             :                 }
    5600             :             }
    5601          31 :             if (!z_geom)
    5602             :             {
    5603          31 :                 CPLErrorReset();
    5604          31 :                 z_geom.reset(x_geom->Intersection(y_geom));
    5605          31 :                 if (CPLGetLastErrorType() != CE_None || z_geom == nullptr)
    5606             :                 {
    5607           0 :                     if (!bSkipFailures)
    5608             :                     {
    5609           0 :                         ret = OGRERR_FAILURE;
    5610           0 :                         goto done;
    5611             :                     }
    5612             :                     else
    5613             :                     {
    5614           0 :                         CPLErrorReset();
    5615           0 :                         ret = OGRERR_NONE;
    5616           0 :                         continue;
    5617             :                     }
    5618             :                 }
    5619          62 :                 if (z_geom->IsEmpty() ||
    5620          31 :                     (!bKeepLowerDimGeom &&
    5621           8 :                      (x_geom->getDimension() == y_geom->getDimension() &&
    5622           8 :                       z_geom->getDimension() < x_geom->getDimension())))
    5623             :                 {
    5624           4 :                     continue;
    5625             :                 }
    5626             :             }
    5627          27 :             OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    5628          27 :             z->SetFieldsFrom(x.get(), mapInput);
    5629          27 :             z->SetFieldsFrom(y.get(), mapMethod);
    5630          54 :             z_geom = convert_geometry(std::move(z_geom), bPromoteToMulti,
    5631          27 :                                       eOutputGeometryType);
    5632          27 :             if (!z_geom)
    5633           1 :                 continue;
    5634          26 :             z->SetGeometryDirectly(z_geom.release());
    5635          26 :             ret = pLayerResult->CreateFeature(z.get());
    5636             : 
    5637          26 :             if (ret != OGRERR_NONE)
    5638             :             {
    5639           0 :                 if (!bSkipFailures)
    5640             :                 {
    5641           0 :                     goto done;
    5642             :                 }
    5643             :                 else
    5644             :                 {
    5645           0 :                     CPLErrorReset();
    5646           0 :                     ret = OGRERR_NONE;
    5647             :                 }
    5648             :             }
    5649             :         }
    5650             :     }
    5651          15 :     if (pfnProgress && !pfnProgress(1.0, "", pProgressArg))
    5652             :     {
    5653           0 :         CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    5654           0 :         ret = OGRERR_FAILURE;
    5655           0 :         goto done;
    5656             :     }
    5657          15 : done:
    5658             :     // release resources
    5659          15 :     pLayerMethod->SetSpatialFilter(pGeometryMethodFilter);
    5660          15 :     if (pGeometryMethodFilter)
    5661           0 :         delete pGeometryMethodFilter;
    5662          15 :     if (mapInput)
    5663          11 :         VSIFree(mapInput);
    5664          15 :     if (mapMethod)
    5665          11 :         VSIFree(mapMethod);
    5666          15 :     return ret;
    5667             : }
    5668             : 
    5669             : /************************************************************************/
    5670             : /*                         OGR_L_Intersection()                         */
    5671             : /************************************************************************/
    5672             : /**
    5673             :  * \brief Intersection of two layers.
    5674             :  *
    5675             :  * The result layer contains features whose geometries represent areas
    5676             :  * that are common between features in the input layer and in the
    5677             :  * method layer. The features in the result layer have attributes from
    5678             :  * both input and method layers. The schema of the result layer can be
    5679             :  * set by the user or, if it is empty, is initialized to contain all
    5680             :  * fields in the input and method layers.
    5681             :  *
    5682             :  * \note If the schema of the result is set by user and contains
    5683             :  * fields that have the same name as a field in input and in method
    5684             :  * layer, then the attribute in the result feature will get the value
    5685             :  * from the feature of the method layer.
    5686             :  *
    5687             :  * \note For best performance use the minimum amount of features in
    5688             :  * the method layer and copy it into a memory layer.
    5689             :  *
    5690             :  * \note This method relies on GEOS support. Do not use unless the
    5691             :  * GEOS support is compiled in.
    5692             :  *
    5693             :  * The recognized list of options is :
    5694             :  * <ul>
    5695             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    5696             :  *     feature could not be inserted or a GEOS call failed.
    5697             :  * </li>
    5698             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    5699             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    5700             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    5701             :  * </li>
    5702             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    5703             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    5704             :  *     be converted to it, the corresponding output feature is silently skipped.
    5705             :  *     Takes precedence over PROMOTE_TO_MULTI.
    5706             :  * </li>
    5707             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    5708             :  *     will be created from the fields of the input layer.
    5709             :  * </li>
    5710             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    5711             :  *     will be created from the fields of the method layer.
    5712             :  * </li>
    5713             :  * <li>USE_PREPARED_GEOMETRIES=YES/NO. Set to NO to not use prepared
    5714             :  *     geometries to pretest intersection of features of method layer
    5715             :  *     with features of this layer.
    5716             :  * </li>
    5717             :  * <li>PRETEST_CONTAINMENT=YES/NO. Set to YES to pretest the
    5718             :  *     containment of features of method layer within the features of
    5719             :  *     this layer. This will speed up the method significantly in some
    5720             :  *     cases. Requires that the prepared geometries are in effect.
    5721             :  * </li>
    5722             :  * <li>KEEP_LOWER_DIMENSION_GEOMETRIES=YES/NO. Set to NO to skip
    5723             :  *     result features with lower dimension geometry that would
    5724             :  *     otherwise be added to the result layer. The default is YES, to add
    5725             :  *     features with lower dimension geometry, but only if the result layer
    5726             :  *     has an unknown geometry type.
    5727             :  * </li>
    5728             :  * </ul>
    5729             :  *
    5730             :  * This function is the same as the C++ method OGRLayer::Intersection().
    5731             :  *
    5732             :  * @param pLayerInput the input layer. Should not be NULL.
    5733             :  *
    5734             :  * @param pLayerMethod the method layer. Should not be NULL.
    5735             :  *
    5736             :  * @param pLayerResult the layer where the features resulting from the
    5737             :  * operation are inserted. Should not be NULL. See above the note
    5738             :  * about the schema.
    5739             :  *
    5740             :  * @param papszOptions NULL terminated list of options (may be NULL).
    5741             :  *
    5742             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    5743             :  * reporting progress or NULL.
    5744             :  *
    5745             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    5746             :  *
    5747             :  * @return an error code if there was an error or the execution was
    5748             :  * interrupted, OGRERR_NONE otherwise.
    5749             :  *
    5750             :  * @note The first geometry field is always used.
    5751             :  *
    5752             :  * @since OGR 1.10
    5753             :  */
    5754             : 
    5755           7 : OGRErr OGR_L_Intersection(OGRLayerH pLayerInput, OGRLayerH pLayerMethod,
    5756             :                           OGRLayerH pLayerResult, CSLConstList papszOptions,
    5757             :                           GDALProgressFunc pfnProgress, void *pProgressArg)
    5758             : 
    5759             : {
    5760           7 :     VALIDATE_POINTER1(pLayerInput, "OGR_L_Intersection", OGRERR_INVALID_HANDLE);
    5761           7 :     VALIDATE_POINTER1(pLayerMethod, "OGR_L_Intersection",
    5762             :                       OGRERR_INVALID_HANDLE);
    5763           7 :     VALIDATE_POINTER1(pLayerResult, "OGR_L_Intersection",
    5764             :                       OGRERR_INVALID_HANDLE);
    5765             : 
    5766             :     return OGRLayer::FromHandle(pLayerInput)
    5767           7 :         ->Intersection(OGRLayer::FromHandle(pLayerMethod),
    5768             :                        OGRLayer::FromHandle(pLayerResult), papszOptions,
    5769           7 :                        pfnProgress, pProgressArg);
    5770             : }
    5771             : 
    5772             : /************************************************************************/
    5773             : /*                               Union()                                */
    5774             : /************************************************************************/
    5775             : 
    5776             : /**
    5777             :  * \brief Union of two layers.
    5778             :  *
    5779             :  * The result layer contains features whose geometries represent areas
    5780             :  * that are either in the input layer, in the method layer, or in
    5781             :  * both. The features in the result layer have attributes from both
    5782             :  * input and method layers. For features which represent areas that
    5783             :  * are only in the input or in the method layer the respective
    5784             :  * attributes have undefined values. The schema of the result layer
    5785             :  * can be set by the user or, if it is empty, is initialized to
    5786             :  * contain all fields in the input and method layers.
    5787             :  *
    5788             :  * \note If the schema of the result is set by user and contains
    5789             :  * fields that have the same name as a field in input and in method
    5790             :  * layer, then the attribute in the result feature will get the value
    5791             :  * from the feature of the method layer (even if it is undefined).
    5792             :  *
    5793             :  * \note For best performance use the minimum amount of features in
    5794             :  * the method layer and copy it into a memory layer.
    5795             :  *
    5796             :  * \note This method relies on GEOS support. Do not use unless the
    5797             :  * GEOS support is compiled in.
    5798             :  *
    5799             :  * The recognized list of options is :
    5800             :  * <ul>
    5801             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    5802             :  *     feature could not be inserted or a GEOS call failed.
    5803             :  * </li>
    5804             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    5805             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    5806             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    5807             :  * </li>
    5808             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    5809             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    5810             :  *     be converted to it, the corresponding output feature is silently skipped.
    5811             :  *     Takes precedence over PROMOTE_TO_MULTI.
    5812             :  * </li>
    5813             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    5814             :  *     will be created from the fields of the input layer.
    5815             :  * </li>
    5816             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    5817             :  *     will be created from the fields of the method layer.
    5818             :  * </li>
    5819             :  * <li>USE_PREPARED_GEOMETRIES=YES/NO. Set to NO to not use prepared
    5820             :  *     geometries to pretest intersection of features of method layer
    5821             :  *     with features of this layer.
    5822             :  * </li>
    5823             :  * <li>KEEP_LOWER_DIMENSION_GEOMETRIES=YES/NO. Set to NO to skip
    5824             :  *     result features with lower dimension geometry that would
    5825             :  *     otherwise be added to the result layer. The default is YES, to add
    5826             :  *     features with lower dimension geometry, but only if the result layer
    5827             :  *     has an unknown geometry type.
    5828             :  * </li>
    5829             :  * </ul>
    5830             :  *
    5831             :  * This method is the same as the C function OGR_L_Union().
    5832             :  *
    5833             :  * @param pLayerMethod the method layer. Should not be NULL.
    5834             :  *
    5835             :  * @param pLayerResult the layer where the features resulting from the
    5836             :  * operation are inserted. Should not be NULL. See above the note
    5837             :  * about the schema.
    5838             :  *
    5839             :  * @param papszOptions NULL terminated list of options (may be NULL).
    5840             :  *
    5841             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    5842             :  * reporting progress or NULL.
    5843             :  *
    5844             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    5845             :  *
    5846             :  * @return an error code if there was an error or the execution was
    5847             :  * interrupted, OGRERR_NONE otherwise.
    5848             :  *
    5849             :  * @note The first geometry field is always used.
    5850             :  *
    5851             :  * @since OGR 1.10
    5852             :  */
    5853             : 
    5854          18 : OGRErr OGRLayer::Union(OGRLayer *pLayerMethod, OGRLayer *pLayerResult,
    5855             :                        CSLConstList papszOptions, GDALProgressFunc pfnProgress,
    5856             :                        void *pProgressArg)
    5857             : {
    5858          18 :     OGRErr ret = OGRERR_NONE;
    5859          18 :     OGRFeatureDefn *poDefnInput = GetLayerDefn();
    5860          18 :     OGRFeatureDefn *poDefnMethod = pLayerMethod->GetLayerDefn();
    5861          18 :     OGRFeatureDefn *poDefnResult = nullptr;
    5862          18 :     OGRGeometry *pGeometryMethodFilter = nullptr;
    5863          18 :     OGRGeometry *pGeometryInputFilter = nullptr;
    5864          18 :     int *mapInput = nullptr;
    5865          18 :     int *mapMethod = nullptr;
    5866             :     double progress_max =
    5867          18 :         static_cast<double>(GetFeatureCount(FALSE)) +
    5868          18 :         static_cast<double>(pLayerMethod->GetFeatureCount(FALSE));
    5869          18 :     double progress_counter = 0;
    5870          18 :     double progress_ticker = 0;
    5871             :     const bool bSkipFailures =
    5872          18 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "SKIP_FAILURES", "NO"));
    5873          18 :     const bool bPromoteToMulti = CPLTestBool(
    5874             :         CSLFetchNameValueDef(papszOptions, "PROMOTE_TO_MULTI", "NO"));
    5875          18 :     const bool bUsePreparedGeometries = CPLTestBool(
    5876             :         CSLFetchNameValueDef(papszOptions, "USE_PREPARED_GEOMETRIES", "YES"));
    5877          18 :     bool bKeepLowerDimGeom = CPLTestBool(CSLFetchNameValueDef(
    5878             :         papszOptions, "KEEP_LOWER_DIMENSION_GEOMETRIES", "YES"));
    5879             :     const char *pszOutputGeometryType =
    5880          18 :         CSLFetchNameValueDef(papszOptions, "OUTPUT_GEOMETRY_TYPE", "GEOMETRY");
    5881          18 :     const auto eOutputGeometryType = OGRFromOGCGeomType(pszOutputGeometryType);
    5882             : 
    5883             :     // check for GEOS
    5884          18 :     if (!OGRGeometryFactory::haveGEOS())
    5885             :     {
    5886           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    5887             :                  "OGRLayer::Union() requires GEOS support");
    5888           0 :         return OGRERR_UNSUPPORTED_OPERATION;
    5889             :     }
    5890             : 
    5891             :     // get resources
    5892          18 :     ret = clone_spatial_filter(this, &pGeometryInputFilter);
    5893          18 :     if (ret != OGRERR_NONE)
    5894           0 :         goto done;
    5895          18 :     ret = clone_spatial_filter(pLayerMethod, &pGeometryMethodFilter);
    5896          18 :     if (ret != OGRERR_NONE)
    5897           0 :         goto done;
    5898          18 :     ret = create_field_map(poDefnInput, &mapInput);
    5899          18 :     if (ret != OGRERR_NONE)
    5900           0 :         goto done;
    5901          18 :     ret = create_field_map(poDefnMethod, &mapMethod);
    5902          18 :     if (ret != OGRERR_NONE)
    5903           0 :         goto done;
    5904          18 :     ret = set_result_schema(pLayerResult, poDefnInput, poDefnMethod, mapInput,
    5905             :                             mapMethod, true, papszOptions);
    5906          18 :     if (ret != OGRERR_NONE)
    5907           0 :         goto done;
    5908          18 :     poDefnResult = pLayerResult->GetLayerDefn();
    5909          18 :     if (bKeepLowerDimGeom)
    5910             :     {
    5911             :         // require that the result layer is of geom type unknown
    5912          16 :         if (pLayerResult->GetGeomType() != wkbUnknown)
    5913             :         {
    5914          11 :             CPLDebug("OGR", "Resetting KEEP_LOWER_DIMENSION_GEOMETRIES to NO "
    5915             :                             "since the result layer does not allow it.");
    5916          11 :             bKeepLowerDimGeom = FALSE;
    5917             :         }
    5918             :     }
    5919             : 
    5920             :     // add features based on input layer
    5921         133 :     for (auto &&x : this)
    5922             :     {
    5923             : 
    5924         115 :         if (pfnProgress)
    5925             :         {
    5926           2 :             double p = progress_counter / progress_max;
    5927           2 :             if (p > progress_ticker)
    5928             :             {
    5929           1 :                 if (!pfnProgress(p, "", pProgressArg))
    5930             :                 {
    5931           0 :                     CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    5932           0 :                     ret = OGRERR_FAILURE;
    5933           0 :                     goto done;
    5934             :                 }
    5935             :             }
    5936           2 :             progress_counter += 1.0;
    5937             :         }
    5938             : 
    5939             :         // set up the filter on method layer
    5940         115 :         CPLErrorReset();
    5941             :         OGRGeometry *x_geom =
    5942         115 :             set_filter_from(pLayerMethod, pGeometryMethodFilter, x.get());
    5943         115 :         if (CPLGetLastErrorType() != CE_None)
    5944             :         {
    5945           0 :             if (!bSkipFailures)
    5946             :             {
    5947           0 :                 ret = OGRERR_FAILURE;
    5948           0 :                 goto done;
    5949             :             }
    5950             :             else
    5951             :             {
    5952           0 :                 CPLErrorReset();
    5953           0 :                 ret = OGRERR_NONE;
    5954             :             }
    5955             :         }
    5956         115 :         if (!x_geom)
    5957             :         {
    5958           0 :             continue;
    5959             :         }
    5960             : 
    5961           0 :         OGRPreparedGeometryUniquePtr x_prepared_geom;
    5962         115 :         if (bUsePreparedGeometries)
    5963             :         {
    5964         115 :             x_prepared_geom.reset(
    5965             :                 OGRCreatePreparedGeometry(OGRGeometry::ToHandle(x_geom)));
    5966         115 :             if (!x_prepared_geom)
    5967             :             {
    5968           0 :                 goto done;
    5969             :             }
    5970             :         }
    5971             : 
    5972             :         std::unique_ptr<OGRGeometry> x_geom_diff(
    5973             :             x_geom
    5974         115 :                 ->clone());  // this will be the geometry of the result feature
    5975         631 :         for (auto &&y : pLayerMethod)
    5976             :         {
    5977         516 :             OGRGeometry *y_geom = y->GetGeometryRef();
    5978         516 :             if (!y_geom)
    5979             :             {
    5980           0 :                 continue;
    5981             :             }
    5982             : 
    5983         516 :             CPLErrorReset();
    5984        1032 :             if (x_prepared_geom &&
    5985         516 :                 !(OGRPreparedGeometryIntersects(x_prepared_geom.get(),
    5986         516 :                                                 OGRGeometry::ToHandle(y_geom))))
    5987             :             {
    5988           0 :                 if (CPLGetLastErrorType() == CE_None)
    5989             :                 {
    5990           0 :                     continue;
    5991             :                 }
    5992             :             }
    5993         516 :             if (CPLGetLastErrorType() != CE_None)
    5994             :             {
    5995           0 :                 if (!bSkipFailures)
    5996             :                 {
    5997           0 :                     ret = OGRERR_FAILURE;
    5998           0 :                     goto done;
    5999             :                 }
    6000             :                 else
    6001             :                 {
    6002           0 :                     CPLErrorReset();
    6003           0 :                     ret = OGRERR_NONE;
    6004             :                 }
    6005             :             }
    6006             : 
    6007         516 :             CPLErrorReset();
    6008             :             std::unique_ptr<OGRGeometry> poIntersection(
    6009         516 :                 x_geom->Intersection(y_geom));
    6010         516 :             if (CPLGetLastErrorType() != CE_None || poIntersection == nullptr)
    6011             :             {
    6012           0 :                 if (!bSkipFailures)
    6013             :                 {
    6014           0 :                     ret = OGRERR_FAILURE;
    6015           0 :                     goto done;
    6016             :                 }
    6017             :                 else
    6018             :                 {
    6019           0 :                     CPLErrorReset();
    6020           0 :                     ret = OGRERR_NONE;
    6021           0 :                     continue;
    6022             :                 }
    6023             :             }
    6024        1032 :             if (poIntersection->IsEmpty() ||
    6025         516 :                 (!bKeepLowerDimGeom &&
    6026         507 :                  (x_geom->getDimension() == y_geom->getDimension() &&
    6027         507 :                   poIntersection->getDimension() < x_geom->getDimension())))
    6028             :             {
    6029             :                 // ok
    6030             :             }
    6031             :             else
    6032             :             {
    6033         112 :                 OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    6034         112 :                 z->SetFieldsFrom(x.get(), mapInput);
    6035         112 :                 z->SetFieldsFrom(y.get(), mapMethod);
    6036             :                 poIntersection =
    6037         224 :                     convert_geometry(std::move(poIntersection), bPromoteToMulti,
    6038         112 :                                      eOutputGeometryType);
    6039         112 :                 z->SetGeometryDirectly(poIntersection.release());
    6040             : 
    6041         112 :                 if (x_geom_diff)
    6042             :                 {
    6043         112 :                     CPLErrorReset();
    6044             :                     std::unique_ptr<OGRGeometry> x_geom_diff_new(
    6045         112 :                         x_geom_diff->Difference(y_geom));
    6046         224 :                     if (CPLGetLastErrorType() != CE_None ||
    6047         112 :                         x_geom_diff_new == nullptr)
    6048             :                     {
    6049           0 :                         if (!bSkipFailures)
    6050             :                         {
    6051           0 :                             ret = OGRERR_FAILURE;
    6052           0 :                             goto done;
    6053             :                         }
    6054             :                         else
    6055             :                         {
    6056           0 :                             CPLErrorReset();
    6057             :                         }
    6058             :                     }
    6059             :                     else
    6060             :                     {
    6061         112 :                         x_geom_diff.swap(x_geom_diff_new);
    6062             :                     }
    6063             :                 }
    6064             : 
    6065         112 :                 ret = pLayerResult->CreateFeature(z.get());
    6066         112 :                 if (ret != OGRERR_NONE)
    6067             :                 {
    6068           0 :                     if (!bSkipFailures)
    6069             :                     {
    6070           0 :                         goto done;
    6071             :                     }
    6072             :                     else
    6073             :                     {
    6074           0 :                         CPLErrorReset();
    6075           0 :                         ret = OGRERR_NONE;
    6076             :                     }
    6077             :                 }
    6078             :             }
    6079             :         }
    6080         115 :         x_prepared_geom.reset();
    6081             : 
    6082         115 :         if (x_geom_diff == nullptr || x_geom_diff->IsEmpty())
    6083             :         {
    6084             :             // ok
    6085             :         }
    6086             :         else
    6087             :         {
    6088          12 :             OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    6089          12 :             z->SetFieldsFrom(x.get(), mapInput);
    6090          24 :             x_geom_diff = convert_geometry(
    6091          24 :                 std::move(x_geom_diff), bPromoteToMulti, eOutputGeometryType);
    6092          12 :             if (!x_geom_diff)
    6093           0 :                 continue;
    6094          12 :             z->SetGeometryDirectly(x_geom_diff.release());
    6095          12 :             ret = pLayerResult->CreateFeature(z.get());
    6096          12 :             if (ret != OGRERR_NONE)
    6097             :             {
    6098           0 :                 if (!bSkipFailures)
    6099             :                 {
    6100           0 :                     goto done;
    6101             :                 }
    6102             :                 else
    6103             :                 {
    6104           0 :                     CPLErrorReset();
    6105           0 :                     ret = OGRERR_NONE;
    6106             :                 }
    6107             :             }
    6108             :         }
    6109             :     }
    6110             : 
    6111             :     // restore filter on method layer and add features based on it
    6112          18 :     pLayerMethod->SetSpatialFilter(pGeometryMethodFilter);
    6113         130 :     for (auto &&x : pLayerMethod)
    6114             :     {
    6115             : 
    6116         112 :         if (pfnProgress)
    6117             :         {
    6118           1 :             double p = progress_counter / progress_max;
    6119           1 :             if (p > progress_ticker)
    6120             :             {
    6121           1 :                 if (!pfnProgress(p, "", pProgressArg))
    6122             :                 {
    6123           0 :                     CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    6124           0 :                     ret = OGRERR_FAILURE;
    6125           0 :                     goto done;
    6126             :                 }
    6127             :             }
    6128           1 :             progress_counter += 1.0;
    6129             :         }
    6130             : 
    6131             :         // set up the filter on input layer
    6132         112 :         CPLErrorReset();
    6133             :         OGRGeometry *x_geom =
    6134         112 :             set_filter_from(this, pGeometryInputFilter, x.get());
    6135         112 :         if (CPLGetLastErrorType() != CE_None)
    6136             :         {
    6137           0 :             if (!bSkipFailures)
    6138             :             {
    6139           0 :                 ret = OGRERR_FAILURE;
    6140           0 :                 goto done;
    6141             :             }
    6142             :             else
    6143             :             {
    6144           0 :                 CPLErrorReset();
    6145           0 :                 ret = OGRERR_NONE;
    6146             :             }
    6147             :         }
    6148         112 :         if (!x_geom)
    6149             :         {
    6150           0 :             continue;
    6151             :         }
    6152             : 
    6153             :         std::unique_ptr<OGRGeometry> x_geom_diff(
    6154             :             x_geom
    6155         112 :                 ->clone());  // this will be the geometry of the result feature
    6156         628 :         for (auto &&y : this)
    6157             :         {
    6158         516 :             OGRGeometry *y_geom = y->GetGeometryRef();
    6159         516 :             if (!y_geom)
    6160             :             {
    6161           0 :                 continue;
    6162             :             }
    6163             : 
    6164         516 :             if (x_geom_diff)
    6165             :             {
    6166         516 :                 CPLErrorReset();
    6167             :                 std::unique_ptr<OGRGeometry> x_geom_diff_new(
    6168         516 :                     x_geom_diff->Difference(y_geom));
    6169        1032 :                 if (CPLGetLastErrorType() != CE_None ||
    6170         516 :                     x_geom_diff_new == nullptr)
    6171             :                 {
    6172           0 :                     if (!bSkipFailures)
    6173             :                     {
    6174           0 :                         ret = OGRERR_FAILURE;
    6175           0 :                         goto done;
    6176             :                     }
    6177             :                     else
    6178             :                     {
    6179           0 :                         CPLErrorReset();
    6180           0 :                         ret = OGRERR_NONE;
    6181             :                     }
    6182             :                 }
    6183             :                 else
    6184             :                 {
    6185         516 :                     x_geom_diff.swap(x_geom_diff_new);
    6186             :                 }
    6187             :             }
    6188             :         }
    6189             : 
    6190         112 :         if (x_geom_diff == nullptr || x_geom_diff->IsEmpty())
    6191             :         {
    6192             :             // ok
    6193             :         }
    6194             :         else
    6195             :         {
    6196           8 :             OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    6197           8 :             z->SetFieldsFrom(x.get(), mapMethod);
    6198          16 :             x_geom_diff = convert_geometry(
    6199          16 :                 std::move(x_geom_diff), bPromoteToMulti, eOutputGeometryType);
    6200           8 :             if (!x_geom_diff)
    6201           0 :                 continue;
    6202           8 :             z->SetGeometryDirectly(x_geom_diff.release());
    6203           8 :             ret = pLayerResult->CreateFeature(z.get());
    6204           8 :             if (ret != OGRERR_NONE)
    6205             :             {
    6206           0 :                 if (!bSkipFailures)
    6207             :                 {
    6208           0 :                     goto done;
    6209             :                 }
    6210             :                 else
    6211             :                 {
    6212           0 :                     CPLErrorReset();
    6213           0 :                     ret = OGRERR_NONE;
    6214             :                 }
    6215             :             }
    6216             :         }
    6217             :     }
    6218          18 :     if (pfnProgress && !pfnProgress(1.0, "", pProgressArg))
    6219             :     {
    6220           0 :         CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    6221           0 :         ret = OGRERR_FAILURE;
    6222           0 :         goto done;
    6223             :     }
    6224          18 : done:
    6225             :     // release resources
    6226          18 :     SetSpatialFilter(pGeometryInputFilter);
    6227          18 :     pLayerMethod->SetSpatialFilter(pGeometryMethodFilter);
    6228          18 :     if (pGeometryMethodFilter)
    6229           0 :         delete pGeometryMethodFilter;
    6230          18 :     if (pGeometryInputFilter)
    6231           0 :         delete pGeometryInputFilter;
    6232          18 :     if (mapInput)
    6233          15 :         VSIFree(mapInput);
    6234          18 :     if (mapMethod)
    6235          14 :         VSIFree(mapMethod);
    6236          18 :     return ret;
    6237             : }
    6238             : 
    6239             : /************************************************************************/
    6240             : /*                            OGR_L_Union()                             */
    6241             : /************************************************************************/
    6242             : 
    6243             : /**
    6244             :  * \brief Union of two layers.
    6245             :  *
    6246             :  * The result layer contains features whose geometries represent areas
    6247             :  * that are in either in the input layer, in the method layer, or in
    6248             :  * both. The features in the result layer have attributes from both
    6249             :  * input and method layers. For features which represent areas that
    6250             :  * are only in the input or in the method layer the respective
    6251             :  * attributes have undefined values. The schema of the result layer
    6252             :  * can be set by the user or, if it is empty, is initialized to
    6253             :  * contain all fields in the input and method layers.
    6254             :  *
    6255             :  * \note If the schema of the result is set by user and contains
    6256             :  * fields that have the same name as a field in input and in method
    6257             :  * layer, then the attribute in the result feature will get the value
    6258             :  * from the feature of the method layer (even if it is undefined).
    6259             :  *
    6260             :  * \note For best performance use the minimum amount of features in
    6261             :  * the method layer and copy it into a memory layer.
    6262             :  *
    6263             :  * \note This method relies on GEOS support. Do not use unless the
    6264             :  * GEOS support is compiled in.
    6265             :  *
    6266             :  * The recognized list of options is :
    6267             :  * <ul>
    6268             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    6269             :  *     feature could not be inserted or a GEOS call failed.
    6270             :  * </li>
    6271             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    6272             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    6273             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    6274             :  * </li>
    6275             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    6276             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    6277             :  *     be converted to it, the corresponding output feature is silently skipped.
    6278             :  *     Takes precedence over PROMOTE_TO_MULTI.
    6279             :  * </li>
    6280             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    6281             :  *     will be created from the fields of the input layer.
    6282             :  * </li>
    6283             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    6284             :  *     will be created from the fields of the method layer.
    6285             :  * </li>
    6286             :  * <li>USE_PREPARED_GEOMETRIES=YES/NO. Set to NO to not use prepared
    6287             :  *     geometries to pretest intersection of features of method layer
    6288             :  *     with features of this layer.
    6289             :  * </li>
    6290             :  * <li>KEEP_LOWER_DIMENSION_GEOMETRIES=YES/NO. Set to NO to skip
    6291             :  *     result features with lower dimension geometry that would
    6292             :  *     otherwise be added to the result layer. The default is YES, to add
    6293             :  *     features with lower dimension geometry, but only if the result layer
    6294             :  *     has an unknown geometry type.
    6295             :  * </li>
    6296             :  * </ul>
    6297             :  *
    6298             :  * This function is the same as the C++ method OGRLayer::Union().
    6299             :  *
    6300             :  * @param pLayerInput the input layer. Should not be NULL.
    6301             :  *
    6302             :  * @param pLayerMethod the method layer. Should not be NULL.
    6303             :  *
    6304             :  * @param pLayerResult the layer where the features resulting from the
    6305             :  * operation are inserted. Should not be NULL. See above the note
    6306             :  * about the schema.
    6307             :  *
    6308             :  * @param papszOptions NULL terminated list of options (may be NULL).
    6309             :  *
    6310             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    6311             :  * reporting progress or NULL.
    6312             :  *
    6313             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    6314             :  *
    6315             :  * @return an error code if there was an error or the execution was
    6316             :  * interrupted, OGRERR_NONE otherwise.
    6317             :  *
    6318             :  * @note The first geometry field is always used.
    6319             :  *
    6320             :  * @since OGR 1.10
    6321             :  */
    6322             : 
    6323           7 : OGRErr OGR_L_Union(OGRLayerH pLayerInput, OGRLayerH pLayerMethod,
    6324             :                    OGRLayerH pLayerResult, CSLConstList papszOptions,
    6325             :                    GDALProgressFunc pfnProgress, void *pProgressArg)
    6326             : 
    6327             : {
    6328           7 :     VALIDATE_POINTER1(pLayerInput, "OGR_L_Union", OGRERR_INVALID_HANDLE);
    6329           7 :     VALIDATE_POINTER1(pLayerMethod, "OGR_L_Union", OGRERR_INVALID_HANDLE);
    6330           7 :     VALIDATE_POINTER1(pLayerResult, "OGR_L_Union", OGRERR_INVALID_HANDLE);
    6331             : 
    6332             :     return OGRLayer::FromHandle(pLayerInput)
    6333           7 :         ->Union(OGRLayer::FromHandle(pLayerMethod),
    6334             :                 OGRLayer::FromHandle(pLayerResult), papszOptions, pfnProgress,
    6335           7 :                 pProgressArg);
    6336             : }
    6337             : 
    6338             : /************************************************************************/
    6339             : /*                           SymDifference()                            */
    6340             : /************************************************************************/
    6341             : 
    6342             : /**
    6343             :  * \brief Symmetrical difference of two layers.
    6344             :  *
    6345             :  * The result layer contains features whose geometries represent areas
    6346             :  * that are in either in the input layer or in the method layer but
    6347             :  * not in both. The features in the result layer have attributes from
    6348             :  * both input and method layers. For features which represent areas
    6349             :  * that are only in the input or in the method layer the respective
    6350             :  * attributes have undefined values. The schema of the result layer
    6351             :  * can be set by the user or, if it is empty, is initialized to
    6352             :  * contain all fields in the input and method layers.
    6353             :  *
    6354             :  * \note If the schema of the result is set by user and contains
    6355             :  * fields that have the same name as a field in input and in method
    6356             :  * layer, then the attribute in the result feature will get the value
    6357             :  * from the feature of the method layer (even if it is undefined).
    6358             :  *
    6359             :  * \note For best performance use the minimum amount of features in
    6360             :  * the method layer and copy it into a memory layer.
    6361             :  *
    6362             :  * \note This method relies on GEOS support. Do not use unless the
    6363             :  * GEOS support is compiled in.
    6364             :  *
    6365             :  * The recognized list of options is :
    6366             :  * <ul>
    6367             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    6368             :  *     feature could not be inserted or a GEOS call failed.
    6369             :  * </li>
    6370             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set it to YES to convert Polygons
    6371             :  *     into MultiPolygons, or LineStrings to MultiLineStrings.
    6372             :  * </li>
    6373             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    6374             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    6375             :  *     be converted to it, the corresponding output feature is silently skipped.
    6376             :  *     Takes precedence over PROMOTE_TO_MULTI.
    6377             :  * </li>
    6378             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    6379             :  *     will be created from the fields of the input layer.
    6380             :  * </li>
    6381             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    6382             :  *     will be created from the fields of the method layer.
    6383             :  * </li>
    6384             :  * </ul>
    6385             :  *
    6386             :  * This method is the same as the C function OGR_L_SymDifference().
    6387             :  *
    6388             :  * @param pLayerMethod the method layer. Should not be NULL.
    6389             :  *
    6390             :  * @param pLayerResult the layer where the features resulting from the
    6391             :  * operation are inserted. Should not be NULL. See above the note
    6392             :  * about the schema.
    6393             :  *
    6394             :  * @param papszOptions NULL terminated list of options (may be NULL).
    6395             :  *
    6396             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    6397             :  * reporting progress or NULL.
    6398             :  *
    6399             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    6400             :  *
    6401             :  * @return an error code if there was an error or the execution was
    6402             :  * interrupted, OGRERR_NONE otherwise.
    6403             :  *
    6404             :  * @note The first geometry field is always used.
    6405             :  *
    6406             :  * @since OGR 1.10
    6407             :  */
    6408             : 
    6409           5 : OGRErr OGRLayer::SymDifference(OGRLayer *pLayerMethod, OGRLayer *pLayerResult,
    6410             :                                CSLConstList papszOptions,
    6411             :                                GDALProgressFunc pfnProgress, void *pProgressArg)
    6412             : {
    6413           5 :     OGRErr ret = OGRERR_NONE;
    6414           5 :     OGRFeatureDefn *poDefnInput = GetLayerDefn();
    6415           5 :     OGRFeatureDefn *poDefnMethod = pLayerMethod->GetLayerDefn();
    6416           5 :     OGRFeatureDefn *poDefnResult = nullptr;
    6417           5 :     OGRGeometry *pGeometryMethodFilter = nullptr;
    6418           5 :     OGRGeometry *pGeometryInputFilter = nullptr;
    6419           5 :     int *mapInput = nullptr;
    6420           5 :     int *mapMethod = nullptr;
    6421             :     double progress_max =
    6422           5 :         static_cast<double>(GetFeatureCount(FALSE)) +
    6423           5 :         static_cast<double>(pLayerMethod->GetFeatureCount(FALSE));
    6424           5 :     double progress_counter = 0;
    6425           5 :     double progress_ticker = 0;
    6426             :     const bool bSkipFailures =
    6427           5 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "SKIP_FAILURES", "NO"));
    6428           5 :     const bool bPromoteToMulti = CPLTestBool(
    6429             :         CSLFetchNameValueDef(papszOptions, "PROMOTE_TO_MULTI", "NO"));
    6430             :     const char *pszOutputGeometryType =
    6431           5 :         CSLFetchNameValueDef(papszOptions, "OUTPUT_GEOMETRY_TYPE", "GEOMETRY");
    6432           5 :     const auto eOutputGeometryType = OGRFromOGCGeomType(pszOutputGeometryType);
    6433             : 
    6434             :     // check for GEOS
    6435           5 :     if (!OGRGeometryFactory::haveGEOS())
    6436             :     {
    6437           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6438             :                  "OGRLayer::SymDifference() requires GEOS support");
    6439           0 :         return OGRERR_UNSUPPORTED_OPERATION;
    6440             :     }
    6441             : 
    6442             :     // get resources
    6443           5 :     ret = clone_spatial_filter(this, &pGeometryInputFilter);
    6444           5 :     if (ret != OGRERR_NONE)
    6445           0 :         goto done;
    6446           5 :     ret = clone_spatial_filter(pLayerMethod, &pGeometryMethodFilter);
    6447           5 :     if (ret != OGRERR_NONE)
    6448           0 :         goto done;
    6449           5 :     ret = create_field_map(poDefnInput, &mapInput);
    6450           5 :     if (ret != OGRERR_NONE)
    6451           0 :         goto done;
    6452           5 :     ret = create_field_map(poDefnMethod, &mapMethod);
    6453           5 :     if (ret != OGRERR_NONE)
    6454           0 :         goto done;
    6455           5 :     ret = set_result_schema(pLayerResult, poDefnInput, poDefnMethod, mapInput,
    6456             :                             mapMethod, true, papszOptions);
    6457           5 :     if (ret != OGRERR_NONE)
    6458           0 :         goto done;
    6459           5 :     poDefnResult = pLayerResult->GetLayerDefn();
    6460             : 
    6461             :     // add features based on input layer
    6462          15 :     for (auto &&x : this)
    6463             :     {
    6464             : 
    6465          10 :         if (pfnProgress)
    6466             :         {
    6467           2 :             double p = progress_counter / progress_max;
    6468           2 :             if (p > progress_ticker)
    6469             :             {
    6470           1 :                 if (!pfnProgress(p, "", pProgressArg))
    6471             :                 {
    6472           0 :                     CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    6473           0 :                     ret = OGRERR_FAILURE;
    6474           0 :                     goto done;
    6475             :                 }
    6476             :             }
    6477           2 :             progress_counter += 1.0;
    6478             :         }
    6479             : 
    6480             :         // set up the filter on method layer
    6481          10 :         CPLErrorReset();
    6482             :         OGRGeometry *x_geom =
    6483          10 :             set_filter_from(pLayerMethod, pGeometryMethodFilter, x.get());
    6484          10 :         if (CPLGetLastErrorType() != CE_None)
    6485             :         {
    6486           0 :             if (!bSkipFailures)
    6487             :             {
    6488           0 :                 ret = OGRERR_FAILURE;
    6489           0 :                 goto done;
    6490             :             }
    6491             :             else
    6492             :             {
    6493           0 :                 CPLErrorReset();
    6494           0 :                 ret = OGRERR_NONE;
    6495             :             }
    6496             :         }
    6497          10 :         if (!x_geom)
    6498             :         {
    6499           0 :             continue;
    6500             :         }
    6501             : 
    6502             :         std::unique_ptr<OGRGeometry> geom(
    6503             :             x_geom
    6504          10 :                 ->clone());  // this will be the geometry of the result feature
    6505          18 :         for (auto &&y : pLayerMethod)
    6506             :         {
    6507          11 :             OGRGeometry *y_geom = y->GetGeometryRef();
    6508          11 :             if (!y_geom)
    6509             :             {
    6510           0 :                 continue;
    6511             :             }
    6512          11 :             if (geom)
    6513             :             {
    6514          11 :                 CPLErrorReset();
    6515          11 :                 std::unique_ptr<OGRGeometry> geom_new(geom->Difference(y_geom));
    6516          11 :                 if (CPLGetLastErrorType() != CE_None || geom_new == nullptr)
    6517             :                 {
    6518           0 :                     if (!bSkipFailures)
    6519             :                     {
    6520           0 :                         ret = OGRERR_FAILURE;
    6521           0 :                         goto done;
    6522             :                     }
    6523             :                     else
    6524             :                     {
    6525           0 :                         CPLErrorReset();
    6526           0 :                         ret = OGRERR_NONE;
    6527             :                     }
    6528             :                 }
    6529             :                 else
    6530             :                 {
    6531          11 :                     geom.swap(geom_new);
    6532             :                 }
    6533             :             }
    6534          11 :             if (geom && geom->IsEmpty())
    6535           3 :                 break;
    6536             :         }
    6537             : 
    6538          10 :         if (geom && !geom->IsEmpty())
    6539             :         {
    6540           7 :             OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    6541           7 :             z->SetFieldsFrom(x.get(), mapInput);
    6542          14 :             geom = convert_geometry(std::move(geom), bPromoteToMulti,
    6543           7 :                                     eOutputGeometryType);
    6544           7 :             if (!geom)
    6545           0 :                 continue;
    6546           7 :             z->SetGeometryDirectly(geom.release());
    6547           7 :             ret = pLayerResult->CreateFeature(z.get());
    6548           7 :             if (ret != OGRERR_NONE)
    6549             :             {
    6550           0 :                 if (!bSkipFailures)
    6551             :                 {
    6552           0 :                     goto done;
    6553             :                 }
    6554             :                 else
    6555             :                 {
    6556           0 :                     CPLErrorReset();
    6557           0 :                     ret = OGRERR_NONE;
    6558             :                 }
    6559             :             }
    6560             :         }
    6561             :     }
    6562             : 
    6563             :     // restore filter on method layer and add features based on it
    6564           5 :     pLayerMethod->SetSpatialFilter(pGeometryMethodFilter);
    6565          14 :     for (auto &&x : pLayerMethod)
    6566             :     {
    6567             : 
    6568           9 :         if (pfnProgress)
    6569             :         {
    6570           2 :             double p = progress_counter / progress_max;
    6571           2 :             if (p > progress_ticker)
    6572             :             {
    6573           2 :                 if (!pfnProgress(p, "", pProgressArg))
    6574             :                 {
    6575           0 :                     CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    6576           0 :                     ret = OGRERR_FAILURE;
    6577           0 :                     goto done;
    6578             :                 }
    6579             :             }
    6580           2 :             progress_counter += 1.0;
    6581             :         }
    6582             : 
    6583             :         // set up the filter on input layer
    6584           9 :         CPLErrorReset();
    6585             :         OGRGeometry *x_geom =
    6586           9 :             set_filter_from(this, pGeometryInputFilter, x.get());
    6587           9 :         if (CPLGetLastErrorType() != CE_None)
    6588             :         {
    6589           0 :             if (!bSkipFailures)
    6590             :             {
    6591           0 :                 ret = OGRERR_FAILURE;
    6592           0 :                 goto done;
    6593             :             }
    6594             :             else
    6595             :             {
    6596           0 :                 CPLErrorReset();
    6597           0 :                 ret = OGRERR_NONE;
    6598             :             }
    6599             :         }
    6600           9 :         if (!x_geom)
    6601             :         {
    6602           0 :             continue;
    6603             :         }
    6604             : 
    6605             :         std::unique_ptr<OGRGeometry> geom(
    6606             :             x_geom
    6607           9 :                 ->clone());  // this will be the geometry of the result feature
    6608          17 :         for (auto &&y : this)
    6609             :         {
    6610          11 :             OGRGeometry *y_geom = y->GetGeometryRef();
    6611          11 :             if (!y_geom)
    6612           0 :                 continue;
    6613          11 :             if (geom)
    6614             :             {
    6615          11 :                 CPLErrorReset();
    6616          11 :                 std::unique_ptr<OGRGeometry> geom_new(geom->Difference(y_geom));
    6617          11 :                 if (CPLGetLastErrorType() != CE_None || geom_new == nullptr)
    6618             :                 {
    6619           0 :                     if (!bSkipFailures)
    6620             :                     {
    6621           0 :                         ret = OGRERR_FAILURE;
    6622           0 :                         goto done;
    6623             :                     }
    6624             :                     else
    6625             :                     {
    6626           0 :                         CPLErrorReset();
    6627           0 :                         ret = OGRERR_NONE;
    6628             :                     }
    6629             :                 }
    6630             :                 else
    6631             :                 {
    6632          11 :                     geom.swap(geom_new);
    6633             :                 }
    6634             :             }
    6635          11 :             if (geom == nullptr || geom->IsEmpty())
    6636           3 :                 break;
    6637             :         }
    6638             : 
    6639           9 :         if (geom && !geom->IsEmpty())
    6640             :         {
    6641           6 :             OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    6642           6 :             z->SetFieldsFrom(x.get(), mapMethod);
    6643          12 :             geom = convert_geometry(std::move(geom), bPromoteToMulti,
    6644           6 :                                     eOutputGeometryType);
    6645           6 :             if (!geom)
    6646           0 :                 continue;
    6647           6 :             z->SetGeometryDirectly(geom.release());
    6648           6 :             ret = pLayerResult->CreateFeature(z.get());
    6649           6 :             if (ret != OGRERR_NONE)
    6650             :             {
    6651           0 :                 if (!bSkipFailures)
    6652             :                 {
    6653           0 :                     goto done;
    6654             :                 }
    6655             :                 else
    6656             :                 {
    6657           0 :                     CPLErrorReset();
    6658           0 :                     ret = OGRERR_NONE;
    6659             :                 }
    6660             :             }
    6661             :         }
    6662             :     }
    6663           5 :     if (pfnProgress && !pfnProgress(1.0, "", pProgressArg))
    6664             :     {
    6665           0 :         CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    6666           0 :         ret = OGRERR_FAILURE;
    6667           0 :         goto done;
    6668             :     }
    6669           5 : done:
    6670             :     // release resources
    6671           5 :     SetSpatialFilter(pGeometryInputFilter);
    6672           5 :     pLayerMethod->SetSpatialFilter(pGeometryMethodFilter);
    6673           5 :     if (pGeometryMethodFilter)
    6674           0 :         delete pGeometryMethodFilter;
    6675           5 :     if (pGeometryInputFilter)
    6676           0 :         delete pGeometryInputFilter;
    6677           5 :     if (mapInput)
    6678           4 :         VSIFree(mapInput);
    6679           5 :     if (mapMethod)
    6680           4 :         VSIFree(mapMethod);
    6681           5 :     return ret;
    6682             : }
    6683             : 
    6684             : /************************************************************************/
    6685             : /*                        OGR_L_SymDifference()                         */
    6686             : /************************************************************************/
    6687             : 
    6688             : /**
    6689             :  * \brief Symmetrical difference of two layers.
    6690             :  *
    6691             :  * The result layer contains features whose geometries represent areas
    6692             :  * that are in either in the input layer or in the method layer but
    6693             :  * not in both. The features in the result layer have attributes from
    6694             :  * both input and method layers. For features which represent areas
    6695             :  * that are only in the input or in the method layer the respective
    6696             :  * attributes have undefined values. The schema of the result layer
    6697             :  * can be set by the user or, if it is empty, is initialized to
    6698             :  * contain all fields in the input and method layers.
    6699             :  *
    6700             :  * \note If the schema of the result is set by user and contains
    6701             :  * fields that have the same name as a field in input and in method
    6702             :  * layer, then the attribute in the result feature will get the value
    6703             :  * from the feature of the method layer (even if it is undefined).
    6704             :  *
    6705             :  * \note For best performance use the minimum amount of features in
    6706             :  * the method layer and copy it into a memory layer.
    6707             :  *
    6708             :  * \note This method relies on GEOS support. Do not use unless the
    6709             :  * GEOS support is compiled in.
    6710             :  *
    6711             :  * The recognized list of options is :
    6712             :  * <ul>
    6713             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    6714             :  *     feature could not be inserted or a GEOS call failed.
    6715             :  * </li>
    6716             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    6717             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    6718             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    6719             :  * </li>
    6720             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    6721             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    6722             :  *     be converted to it, the corresponding output feature is silently skipped.
    6723             :  *     Takes precedence over PROMOTE_TO_MULTI.
    6724             :  * </li>
    6725             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    6726             :  *     will be created from the fields of the input layer.
    6727             :  * </li>
    6728             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    6729             :  *     will be created from the fields of the method layer.
    6730             :  * </li>
    6731             :  * </ul>
    6732             :  *
    6733             :  * This function is the same as the C++ method OGRLayer::SymDifference().
    6734             :  *
    6735             :  * @param pLayerInput the input layer. Should not be NULL.
    6736             :  *
    6737             :  * @param pLayerMethod the method layer. Should not be NULL.
    6738             :  *
    6739             :  * @param pLayerResult the layer where the features resulting from the
    6740             :  * operation are inserted. Should not be NULL. See above the note
    6741             :  * about the schema.
    6742             :  *
    6743             :  * @param papszOptions NULL terminated list of options (may be NULL).
    6744             :  *
    6745             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    6746             :  * reporting progress or NULL.
    6747             :  *
    6748             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    6749             :  *
    6750             :  * @return an error code if there was an error or the execution was
    6751             :  * interrupted, OGRERR_NONE otherwise.
    6752             :  *
    6753             :  * @note The first geometry field is always used.
    6754             :  *
    6755             :  * @since OGR 1.10
    6756             :  */
    6757             : 
    6758           4 : OGRErr OGR_L_SymDifference(OGRLayerH pLayerInput, OGRLayerH pLayerMethod,
    6759             :                            OGRLayerH pLayerResult, CSLConstList papszOptions,
    6760             :                            GDALProgressFunc pfnProgress, void *pProgressArg)
    6761             : 
    6762             : {
    6763           4 :     VALIDATE_POINTER1(pLayerInput, "OGR_L_SymDifference",
    6764             :                       OGRERR_INVALID_HANDLE);
    6765           4 :     VALIDATE_POINTER1(pLayerMethod, "OGR_L_SymDifference",
    6766             :                       OGRERR_INVALID_HANDLE);
    6767           4 :     VALIDATE_POINTER1(pLayerResult, "OGR_L_SymDifference",
    6768             :                       OGRERR_INVALID_HANDLE);
    6769             : 
    6770             :     return OGRLayer::FromHandle(pLayerInput)
    6771           4 :         ->SymDifference(OGRLayer::FromHandle(pLayerMethod),
    6772             :                         OGRLayer::FromHandle(pLayerResult), papszOptions,
    6773           4 :                         pfnProgress, pProgressArg);
    6774             : }
    6775             : 
    6776             : /************************************************************************/
    6777             : /*                              Identity()                              */
    6778             : /************************************************************************/
    6779             : 
    6780             : /**
    6781             :  * \brief Identify the features of this layer with the ones from the
    6782             :  * identity layer.
    6783             :  *
    6784             :  * The result layer contains features whose geometries represent areas
    6785             :  * that are in the input layer. The features in the result layer have
    6786             :  * attributes from both input and method layers. The schema of the
    6787             :  * result layer can be set by the user or, if it is empty, is
    6788             :  * initialized to contain all fields in input and method layers.
    6789             :  *
    6790             :  * \note If the schema of the result is set by user and contains
    6791             :  * fields that have the same name as a field in input and in method
    6792             :  * layer, then the attribute in the result feature will get the value
    6793             :  * from the feature of the method layer (even if it is undefined).
    6794             :  *
    6795             :  * \note For best performance use the minimum amount of features in
    6796             :  * the method layer and copy it into a memory layer.
    6797             :  *
    6798             :  * \note This method relies on GEOS support. Do not use unless the
    6799             :  * GEOS support is compiled in.
    6800             :  *
    6801             :  * The recognized list of options is :
    6802             :  * <ul>
    6803             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    6804             :  *     feature could not be inserted or a GEOS call failed.
    6805             :  * </li>
    6806             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    6807             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    6808             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    6809             :  * </li>
    6810             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    6811             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    6812             :  *     be converted to it, the corresponding output feature is silently skipped.
    6813             :  *     Takes precedence over PROMOTE_TO_MULTI.
    6814             :  * </li>
    6815             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    6816             :  *     will be created from the fields of the input layer.
    6817             :  * </li>
    6818             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    6819             :  *     will be created from the fields of the method layer.
    6820             :  * </li>
    6821             :  * <li>USE_PREPARED_GEOMETRIES=YES/NO. Set to NO to not use prepared
    6822             :  *     geometries to pretest intersection of features of method layer
    6823             :  *     with features of this layer.
    6824             :  * </li>
    6825             :  * <li>KEEP_LOWER_DIMENSION_GEOMETRIES=YES/NO. Set to NO to skip
    6826             :  *     result features with lower dimension geometry that would
    6827             :  *     otherwise be added to the result layer. The default is YES, to add
    6828             :  *     features with lower dimension geometry, but only if the result layer
    6829             :  *     has an unknown geometry type.
    6830             :  * </li>
    6831             :  * </ul>
    6832             :  *
    6833             :  * This method is the same as the C function OGR_L_Identity().
    6834             :  *
    6835             :  * @param pLayerMethod the method layer. Should not be NULL.
    6836             :  *
    6837             :  * @param pLayerResult the layer where the features resulting from the
    6838             :  * operation are inserted. Should not be NULL. See above the note
    6839             :  * about the schema.
    6840             :  *
    6841             :  * @param papszOptions NULL terminated list of options (may be NULL).
    6842             :  *
    6843             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    6844             :  * reporting progress or NULL.
    6845             :  *
    6846             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    6847             :  *
    6848             :  * @return an error code if there was an error or the execution was
    6849             :  * interrupted, OGRERR_NONE otherwise.
    6850             :  *
    6851             :  * @note The first geometry field is always used.
    6852             :  *
    6853             :  * @since OGR 1.10
    6854             :  */
    6855             : 
    6856           7 : OGRErr OGRLayer::Identity(OGRLayer *pLayerMethod, OGRLayer *pLayerResult,
    6857             :                           CSLConstList papszOptions,
    6858             :                           GDALProgressFunc pfnProgress, void *pProgressArg)
    6859             : {
    6860           7 :     OGRErr ret = OGRERR_NONE;
    6861           7 :     OGRFeatureDefn *poDefnInput = GetLayerDefn();
    6862           7 :     OGRFeatureDefn *poDefnMethod = pLayerMethod->GetLayerDefn();
    6863           7 :     OGRFeatureDefn *poDefnResult = nullptr;
    6864           7 :     OGRGeometry *pGeometryMethodFilter = nullptr;
    6865           7 :     int *mapInput = nullptr;
    6866           7 :     int *mapMethod = nullptr;
    6867           7 :     double progress_max = static_cast<double>(GetFeatureCount(FALSE));
    6868           7 :     double progress_counter = 0;
    6869           7 :     double progress_ticker = 0;
    6870             :     const bool bSkipFailures =
    6871           7 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "SKIP_FAILURES", "NO"));
    6872           7 :     const bool bPromoteToMulti = CPLTestBool(
    6873             :         CSLFetchNameValueDef(papszOptions, "PROMOTE_TO_MULTI", "NO"));
    6874           7 :     const bool bUsePreparedGeometries = CPLTestBool(
    6875             :         CSLFetchNameValueDef(papszOptions, "USE_PREPARED_GEOMETRIES", "YES"));
    6876           7 :     bool bKeepLowerDimGeom = CPLTestBool(CSLFetchNameValueDef(
    6877             :         papszOptions, "KEEP_LOWER_DIMENSION_GEOMETRIES", "YES"));
    6878             :     const char *pszOutputGeometryType =
    6879           7 :         CSLFetchNameValueDef(papszOptions, "OUTPUT_GEOMETRY_TYPE", "GEOMETRY");
    6880           7 :     const auto eOutputGeometryType = OGRFromOGCGeomType(pszOutputGeometryType);
    6881             : 
    6882             :     // check for GEOS
    6883           7 :     if (!OGRGeometryFactory::haveGEOS())
    6884             :     {
    6885           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    6886             :                  "OGRLayer::Identity() requires GEOS support");
    6887           0 :         return OGRERR_UNSUPPORTED_OPERATION;
    6888             :     }
    6889           7 :     if (bKeepLowerDimGeom)
    6890             :     {
    6891             :         // require that the result layer is of geom type unknown
    6892           5 :         if (pLayerResult->GetGeomType() != wkbUnknown)
    6893             :         {
    6894           0 :             CPLDebug("OGR", "Resetting KEEP_LOWER_DIMENSION_GEOMETRIES to NO "
    6895             :                             "since the result layer does not allow it.");
    6896           0 :             bKeepLowerDimGeom = FALSE;
    6897             :         }
    6898             :     }
    6899             : 
    6900             :     // get resources
    6901           7 :     ret = clone_spatial_filter(pLayerMethod, &pGeometryMethodFilter);
    6902           7 :     if (ret != OGRERR_NONE)
    6903           0 :         goto done;
    6904           7 :     ret = create_field_map(poDefnInput, &mapInput);
    6905           7 :     if (ret != OGRERR_NONE)
    6906           0 :         goto done;
    6907           7 :     ret = create_field_map(poDefnMethod, &mapMethod);
    6908           7 :     if (ret != OGRERR_NONE)
    6909           0 :         goto done;
    6910           7 :     ret = set_result_schema(pLayerResult, poDefnInput, poDefnMethod, mapInput,
    6911             :                             mapMethod, true, papszOptions);
    6912           7 :     if (ret != OGRERR_NONE)
    6913           0 :         goto done;
    6914           7 :     poDefnResult = pLayerResult->GetLayerDefn();
    6915             : 
    6916             :     // split the features in input layer to the result layer
    6917          21 :     for (auto &&x : this)
    6918             :     {
    6919             : 
    6920          14 :         if (pfnProgress)
    6921             :         {
    6922           2 :             double p = progress_counter / progress_max;
    6923           2 :             if (p > progress_ticker)
    6924             :             {
    6925           1 :                 if (!pfnProgress(p, "", pProgressArg))
    6926             :                 {
    6927           0 :                     CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    6928           0 :                     ret = OGRERR_FAILURE;
    6929           0 :                     goto done;
    6930             :                 }
    6931             :             }
    6932           2 :             progress_counter += 1.0;
    6933             :         }
    6934             : 
    6935             :         // set up the filter on method layer
    6936          14 :         CPLErrorReset();
    6937             :         OGRGeometry *x_geom =
    6938          14 :             set_filter_from(pLayerMethod, pGeometryMethodFilter, x.get());
    6939          14 :         if (CPLGetLastErrorType() != CE_None)
    6940             :         {
    6941           0 :             if (!bSkipFailures)
    6942             :             {
    6943           0 :                 ret = OGRERR_FAILURE;
    6944           0 :                 goto done;
    6945             :             }
    6946             :             else
    6947             :             {
    6948           0 :                 CPLErrorReset();
    6949           0 :                 ret = OGRERR_NONE;
    6950             :             }
    6951             :         }
    6952          14 :         if (!x_geom)
    6953             :         {
    6954           0 :             continue;
    6955             :         }
    6956             : 
    6957           0 :         OGRPreparedGeometryUniquePtr x_prepared_geom;
    6958          14 :         if (bUsePreparedGeometries)
    6959             :         {
    6960          14 :             x_prepared_geom.reset(
    6961             :                 OGRCreatePreparedGeometry(OGRGeometry::ToHandle(x_geom)));
    6962          14 :             if (!x_prepared_geom)
    6963             :             {
    6964           0 :                 goto done;
    6965             :             }
    6966             :         }
    6967             : 
    6968             :         std::unique_ptr<OGRGeometry> x_geom_diff(
    6969             :             x_geom
    6970          14 :                 ->clone());  // this will be the geometry of the result feature
    6971          30 :         for (auto &&y : pLayerMethod)
    6972             :         {
    6973          16 :             OGRGeometry *y_geom = y->GetGeometryRef();
    6974          16 :             if (!y_geom)
    6975           0 :                 continue;
    6976             : 
    6977          16 :             CPLErrorReset();
    6978          32 :             if (x_prepared_geom &&
    6979          16 :                 !(OGRPreparedGeometryIntersects(x_prepared_geom.get(),
    6980          16 :                                                 OGRGeometry::ToHandle(y_geom))))
    6981             :             {
    6982           0 :                 if (CPLGetLastErrorType() == CE_None)
    6983             :                 {
    6984           0 :                     continue;
    6985             :                 }
    6986             :             }
    6987          16 :             if (CPLGetLastErrorType() != CE_None)
    6988             :             {
    6989           0 :                 if (!bSkipFailures)
    6990             :                 {
    6991           0 :                     ret = OGRERR_FAILURE;
    6992           0 :                     goto done;
    6993             :                 }
    6994             :                 else
    6995             :                 {
    6996           0 :                     CPLErrorReset();
    6997           0 :                     ret = OGRERR_NONE;
    6998             :                 }
    6999             :             }
    7000             : 
    7001          16 :             CPLErrorReset();
    7002             :             std::unique_ptr<OGRGeometry> poIntersection(
    7003          16 :                 x_geom->Intersection(y_geom));
    7004          16 :             if (CPLGetLastErrorType() != CE_None || poIntersection == nullptr)
    7005             :             {
    7006           0 :                 if (!bSkipFailures)
    7007             :                 {
    7008           0 :                     ret = OGRERR_FAILURE;
    7009           0 :                     goto done;
    7010             :                 }
    7011             :                 else
    7012             :                 {
    7013           0 :                     CPLErrorReset();
    7014           0 :                     ret = OGRERR_NONE;
    7015             :                 }
    7016             :             }
    7017          32 :             else if (poIntersection->IsEmpty() ||
    7018          16 :                      (!bKeepLowerDimGeom &&
    7019           6 :                       (x_geom->getDimension() == y_geom->getDimension() &&
    7020           6 :                        poIntersection->getDimension() <
    7021           6 :                            x_geom->getDimension())))
    7022             :             {
    7023             :                 /* ok*/
    7024             :             }
    7025             :             else
    7026             :             {
    7027          12 :                 OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    7028          12 :                 z->SetFieldsFrom(x.get(), mapInput);
    7029          12 :                 z->SetFieldsFrom(y.get(), mapMethod);
    7030             :                 poIntersection =
    7031          24 :                     convert_geometry(std::move(poIntersection), bPromoteToMulti,
    7032          12 :                                      eOutputGeometryType);
    7033          12 :                 if (!poIntersection)
    7034           0 :                     continue;
    7035          12 :                 z->SetGeometryDirectly(poIntersection.release());
    7036          12 :                 if (x_geom_diff)
    7037             :                 {
    7038          12 :                     CPLErrorReset();
    7039             :                     std::unique_ptr<OGRGeometry> x_geom_diff_new(
    7040          12 :                         x_geom_diff->Difference(y_geom));
    7041          24 :                     if (CPLGetLastErrorType() != CE_None ||
    7042          12 :                         x_geom_diff_new == nullptr)
    7043             :                     {
    7044           0 :                         if (!bSkipFailures)
    7045             :                         {
    7046           0 :                             ret = OGRERR_FAILURE;
    7047           0 :                             goto done;
    7048             :                         }
    7049             :                         else
    7050             :                         {
    7051           0 :                             CPLErrorReset();
    7052             :                         }
    7053             :                     }
    7054             :                     else
    7055             :                     {
    7056          12 :                         x_geom_diff.swap(x_geom_diff_new);
    7057             :                     }
    7058             :                 }
    7059          12 :                 ret = pLayerResult->CreateFeature(z.get());
    7060          12 :                 if (ret != OGRERR_NONE)
    7061             :                 {
    7062           0 :                     if (!bSkipFailures)
    7063             :                     {
    7064           0 :                         goto done;
    7065             :                     }
    7066             :                     else
    7067             :                     {
    7068           0 :                         CPLErrorReset();
    7069           0 :                         ret = OGRERR_NONE;
    7070             :                     }
    7071             :                 }
    7072             :             }
    7073             :         }
    7074             : 
    7075          14 :         x_prepared_geom.reset();
    7076             : 
    7077          14 :         if (x_geom_diff == nullptr || x_geom_diff->IsEmpty())
    7078             :         {
    7079             :             /* ok */
    7080             :         }
    7081             :         else
    7082             :         {
    7083          11 :             OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    7084          11 :             z->SetFieldsFrom(x.get(), mapInput);
    7085          22 :             x_geom_diff = convert_geometry(
    7086          22 :                 std::move(x_geom_diff), bPromoteToMulti, eOutputGeometryType);
    7087          11 :             if (!x_geom_diff)
    7088           0 :                 continue;
    7089          11 :             z->SetGeometryDirectly(x_geom_diff.release());
    7090          11 :             ret = pLayerResult->CreateFeature(z.get());
    7091          11 :             if (ret != OGRERR_NONE)
    7092             :             {
    7093           0 :                 if (!bSkipFailures)
    7094             :                 {
    7095           0 :                     goto done;
    7096             :                 }
    7097             :                 else
    7098             :                 {
    7099           0 :                     CPLErrorReset();
    7100           0 :                     ret = OGRERR_NONE;
    7101             :                 }
    7102             :             }
    7103             :         }
    7104             :     }
    7105           7 :     if (pfnProgress && !pfnProgress(1.0, "", pProgressArg))
    7106             :     {
    7107           0 :         CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    7108           0 :         ret = OGRERR_FAILURE;
    7109           0 :         goto done;
    7110             :     }
    7111           7 : done:
    7112             :     // release resources
    7113           7 :     pLayerMethod->SetSpatialFilter(pGeometryMethodFilter);
    7114           7 :     if (pGeometryMethodFilter)
    7115           0 :         delete pGeometryMethodFilter;
    7116           7 :     if (mapInput)
    7117           4 :         VSIFree(mapInput);
    7118           7 :     if (mapMethod)
    7119           4 :         VSIFree(mapMethod);
    7120           7 :     return ret;
    7121             : }
    7122             : 
    7123             : /************************************************************************/
    7124             : /*                           OGR_L_Identity()                           */
    7125             : /************************************************************************/
    7126             : 
    7127             : /**
    7128             :  * \brief Identify the features of this layer with the ones from the
    7129             :  * identity layer.
    7130             :  *
    7131             :  * The result layer contains features whose geometries represent areas
    7132             :  * that are in the input layer. The features in the result layer have
    7133             :  * attributes from both input and method layers. The schema of the
    7134             :  * result layer can be set by the user or, if it is empty, is
    7135             :  * initialized to contain all fields in input and method layers.
    7136             :  *
    7137             :  * \note If the schema of the result is set by user and contains
    7138             :  * fields that have the same name as a field in input and in method
    7139             :  * layer, then the attribute in the result feature will get the value
    7140             :  * from the feature of the method layer (even if it is undefined).
    7141             :  *
    7142             :  * \note For best performance use the minimum amount of features in
    7143             :  * the method layer and copy it into a memory layer.
    7144             :  *
    7145             :  * \note This method relies on GEOS support. Do not use unless the
    7146             :  * GEOS support is compiled in.
    7147             :  *
    7148             :  * The recognized list of options is :
    7149             :  * <ul>
    7150             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    7151             :  *     feature could not be inserted or a GEOS call failed.
    7152             :  * </li>
    7153             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    7154             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    7155             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    7156             :  * </li>
    7157             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    7158             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    7159             :  *     be converted to it, the corresponding output feature is silently skipped.
    7160             :  *     Takes precedence over PROMOTE_TO_MULTI.
    7161             :  * </li>
    7162             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    7163             :  *     will be created from the fields of the input layer.
    7164             :  * </li>
    7165             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    7166             :  *     will be created from the fields of the method layer.
    7167             :  * </li>
    7168             :  * <li>USE_PREPARED_GEOMETRIES=YES/NO. Set to NO to not use prepared
    7169             :  *     geometries to pretest intersection of features of method layer
    7170             :  *     with features of this layer.
    7171             :  * </li>
    7172             :  * <li>KEEP_LOWER_DIMENSION_GEOMETRIES=YES/NO. Set to NO to skip
    7173             :  *     result features with lower dimension geometry that would
    7174             :  *     otherwise be added to the result layer. The default is YES, to add
    7175             :  *     features with lower dimension geometry, but only if the result layer
    7176             :  *     has an unknown geometry type.
    7177             :  * </li>
    7178             :  * </ul>
    7179             :  *
    7180             :  * This function is the same as the C++ method OGRLayer::Identity().
    7181             :  *
    7182             :  * @param pLayerInput the input layer. Should not be NULL.
    7183             :  *
    7184             :  * @param pLayerMethod the method layer. Should not be NULL.
    7185             :  *
    7186             :  * @param pLayerResult the layer where the features resulting from the
    7187             :  * operation are inserted. Should not be NULL. See above the note
    7188             :  * about the schema.
    7189             :  *
    7190             :  * @param papszOptions NULL terminated list of options (may be NULL).
    7191             :  *
    7192             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    7193             :  * reporting progress or NULL.
    7194             :  *
    7195             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    7196             :  *
    7197             :  * @return an error code if there was an error or the execution was
    7198             :  * interrupted, OGRERR_NONE otherwise.
    7199             :  *
    7200             :  * @note The first geometry field is always used.
    7201             :  *
    7202             :  * @since OGR 1.10
    7203             :  */
    7204             : 
    7205           6 : OGRErr OGR_L_Identity(OGRLayerH pLayerInput, OGRLayerH pLayerMethod,
    7206             :                       OGRLayerH pLayerResult, CSLConstList papszOptions,
    7207             :                       GDALProgressFunc pfnProgress, void *pProgressArg)
    7208             : 
    7209             : {
    7210           6 :     VALIDATE_POINTER1(pLayerInput, "OGR_L_Identity", OGRERR_INVALID_HANDLE);
    7211           6 :     VALIDATE_POINTER1(pLayerMethod, "OGR_L_Identity", OGRERR_INVALID_HANDLE);
    7212           6 :     VALIDATE_POINTER1(pLayerResult, "OGR_L_Identity", OGRERR_INVALID_HANDLE);
    7213             : 
    7214             :     return OGRLayer::FromHandle(pLayerInput)
    7215           6 :         ->Identity(OGRLayer::FromHandle(pLayerMethod),
    7216             :                    OGRLayer::FromHandle(pLayerResult), papszOptions,
    7217           6 :                    pfnProgress, pProgressArg);
    7218             : }
    7219             : 
    7220             : /************************************************************************/
    7221             : /*                               Update()                               */
    7222             : /************************************************************************/
    7223             : 
    7224             : /**
    7225             :  * \brief Update this layer with features from the update layer.
    7226             :  *
    7227             :  * The result layer contains features whose geometries represent areas
    7228             :  * that are either in the input layer or in the method layer. The
    7229             :  * features in the result layer have areas of the features of the
    7230             :  * method layer or those ares of the features of the input layer that
    7231             :  * are not covered by the method layer. The features of the result
    7232             :  * layer get their attributes from the input layer. The schema of the
    7233             :  * result layer can be set by the user or, if it is empty, is
    7234             :  * initialized to contain all fields in the input layer.
    7235             :  *
    7236             :  * \note If the schema of the result is set by user and contains
    7237             :  * fields that have the same name as a field in the method layer, then
    7238             :  * the attribute in the result feature the originates from the method
    7239             :  * layer will get the value from the feature of the method layer.
    7240             :  *
    7241             :  * \note For best performance use the minimum amount of features in
    7242             :  * the method layer and copy it into a memory layer.
    7243             :  *
    7244             :  * \note This method relies on GEOS support. Do not use unless the
    7245             :  * GEOS support is compiled in.
    7246             :  *
    7247             :  * The recognized list of options is :
    7248             :  * <ul>
    7249             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    7250             :  *     feature could not be inserted or a GEOS call failed.
    7251             :  * </li>
    7252             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    7253             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    7254             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    7255             :  * </li>
    7256             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    7257             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    7258             :  *     be converted to it, the corresponding output feature is silently skipped.
    7259             :  *     Takes precedence over PROMOTE_TO_MULTI.
    7260             :  * </li>
    7261             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    7262             :  *     will be created from the fields of the input layer.
    7263             :  * </li>
    7264             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    7265             :  *     will be created from the fields of the method layer.
    7266             :  * </li>
    7267             :  * </ul>
    7268             :  *
    7269             :  * This method is the same as the C function OGR_L_Update().
    7270             :  *
    7271             :  * @param pLayerMethod the method layer. Should not be NULL.
    7272             :  *
    7273             :  * @param pLayerResult the layer where the features resulting from the
    7274             :  * operation are inserted. Should not be NULL. See above the note
    7275             :  * about the schema.
    7276             :  *
    7277             :  * @param papszOptions NULL terminated list of options (may be NULL).
    7278             :  *
    7279             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    7280             :  * reporting progress or NULL.
    7281             :  *
    7282             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    7283             :  *
    7284             :  * @return an error code if there was an error or the execution was
    7285             :  * interrupted, OGRERR_NONE otherwise.
    7286             :  *
    7287             :  * @note The first geometry field is always used.
    7288             :  *
    7289             :  * @since OGR 1.10
    7290             :  */
    7291             : 
    7292           6 : OGRErr OGRLayer::Update(OGRLayer *pLayerMethod, OGRLayer *pLayerResult,
    7293             :                         CSLConstList papszOptions, GDALProgressFunc pfnProgress,
    7294             :                         void *pProgressArg)
    7295             : {
    7296           6 :     OGRErr ret = OGRERR_NONE;
    7297           6 :     OGRFeatureDefn *poDefnInput = GetLayerDefn();
    7298           6 :     OGRFeatureDefn *poDefnMethod = pLayerMethod->GetLayerDefn();
    7299           6 :     OGRFeatureDefn *poDefnResult = nullptr;
    7300           6 :     OGRGeometry *pGeometryMethodFilter = nullptr;
    7301           6 :     int *mapInput = nullptr;
    7302           6 :     int *mapMethod = nullptr;
    7303             :     double progress_max =
    7304           6 :         static_cast<double>(GetFeatureCount(FALSE)) +
    7305           6 :         static_cast<double>(pLayerMethod->GetFeatureCount(FALSE));
    7306           6 :     double progress_counter = 0;
    7307           6 :     double progress_ticker = 0;
    7308             :     const bool bSkipFailures =
    7309           6 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "SKIP_FAILURES", "NO"));
    7310           6 :     const bool bPromoteToMulti = CPLTestBool(
    7311             :         CSLFetchNameValueDef(papszOptions, "PROMOTE_TO_MULTI", "NO"));
    7312             :     const char *pszOutputGeometryType =
    7313           6 :         CSLFetchNameValueDef(papszOptions, "OUTPUT_GEOMETRY_TYPE", "GEOMETRY");
    7314           6 :     const auto eOutputGeometryType = OGRFromOGCGeomType(pszOutputGeometryType);
    7315             : 
    7316             :     // check for GEOS
    7317           6 :     if (!OGRGeometryFactory::haveGEOS())
    7318             :     {
    7319           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    7320             :                  "OGRLayer::Update() requires GEOS support");
    7321           0 :         return OGRERR_UNSUPPORTED_OPERATION;
    7322             :     }
    7323             : 
    7324             :     // get resources
    7325           6 :     ret = clone_spatial_filter(pLayerMethod, &pGeometryMethodFilter);
    7326           6 :     if (ret != OGRERR_NONE)
    7327           0 :         goto done;
    7328           6 :     ret = create_field_map(poDefnInput, &mapInput);
    7329           6 :     if (ret != OGRERR_NONE)
    7330           0 :         goto done;
    7331           6 :     ret = create_field_map(poDefnMethod, &mapMethod);
    7332           6 :     if (ret != OGRERR_NONE)
    7333           0 :         goto done;
    7334           6 :     ret = set_result_schema(pLayerResult, poDefnInput, poDefnMethod, mapInput,
    7335             :                             mapMethod, false, papszOptions);
    7336           6 :     if (ret != OGRERR_NONE)
    7337           0 :         goto done;
    7338           6 :     poDefnResult = pLayerResult->GetLayerDefn();
    7339             : 
    7340             :     // add clipped features from the input layer
    7341          18 :     for (auto &&x : this)
    7342             :     {
    7343             : 
    7344          12 :         if (pfnProgress)
    7345             :         {
    7346           2 :             double p = progress_counter / progress_max;
    7347           2 :             if (p > progress_ticker)
    7348             :             {
    7349           1 :                 if (!pfnProgress(p, "", pProgressArg))
    7350             :                 {
    7351           0 :                     CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    7352           0 :                     ret = OGRERR_FAILURE;
    7353           0 :                     goto done;
    7354             :                 }
    7355             :             }
    7356           2 :             progress_counter += 1.0;
    7357             :         }
    7358             : 
    7359             :         // set up the filter on method layer
    7360          12 :         CPLErrorReset();
    7361             :         OGRGeometry *x_geom =
    7362          12 :             set_filter_from(pLayerMethod, pGeometryMethodFilter, x.get());
    7363          12 :         if (CPLGetLastErrorType() != CE_None)
    7364             :         {
    7365           0 :             if (!bSkipFailures)
    7366             :             {
    7367           0 :                 ret = OGRERR_FAILURE;
    7368           0 :                 goto done;
    7369             :             }
    7370             :             else
    7371             :             {
    7372           0 :                 CPLErrorReset();
    7373           0 :                 ret = OGRERR_NONE;
    7374             :             }
    7375             :         }
    7376          12 :         if (!x_geom)
    7377             :         {
    7378           0 :             continue;
    7379             :         }
    7380             : 
    7381             :         std::unique_ptr<OGRGeometry> x_geom_diff(
    7382          12 :             x_geom->clone());  // this will be the geometry of a result feature
    7383          28 :         for (auto &&y : pLayerMethod)
    7384             :         {
    7385          16 :             OGRGeometry *y_geom = y->GetGeometryRef();
    7386          16 :             if (!y_geom)
    7387           0 :                 continue;
    7388          16 :             if (x_geom_diff)
    7389             :             {
    7390          16 :                 CPLErrorReset();
    7391             :                 std::unique_ptr<OGRGeometry> x_geom_diff_new(
    7392          16 :                     x_geom_diff->Difference(y_geom));
    7393          32 :                 if (CPLGetLastErrorType() != CE_None ||
    7394          16 :                     x_geom_diff_new == nullptr)
    7395             :                 {
    7396           0 :                     if (!bSkipFailures)
    7397             :                     {
    7398           0 :                         ret = OGRERR_FAILURE;
    7399           0 :                         goto done;
    7400             :                     }
    7401             :                     else
    7402             :                     {
    7403           0 :                         CPLErrorReset();
    7404           0 :                         ret = OGRERR_NONE;
    7405             :                     }
    7406             :                 }
    7407             :                 else
    7408             :                 {
    7409          16 :                     x_geom_diff.swap(x_geom_diff_new);
    7410             :                 }
    7411             :             }
    7412             :         }
    7413             : 
    7414          12 :         if (x_geom_diff == nullptr || x_geom_diff->IsEmpty())
    7415             :         {
    7416             :             /* ok */
    7417             :         }
    7418             :         else
    7419             :         {
    7420           7 :             OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    7421           7 :             z->SetFieldsFrom(x.get(), mapInput);
    7422          14 :             x_geom_diff = convert_geometry(
    7423          14 :                 std::move(x_geom_diff), bPromoteToMulti, eOutputGeometryType);
    7424           7 :             if (!x_geom_diff)
    7425           0 :                 continue;
    7426           7 :             z->SetGeometryDirectly(x_geom_diff.release());
    7427           7 :             ret = pLayerResult->CreateFeature(z.get());
    7428           7 :             if (ret != OGRERR_NONE)
    7429             :             {
    7430           0 :                 if (!bSkipFailures)
    7431             :                 {
    7432           0 :                     goto done;
    7433             :                 }
    7434             :                 else
    7435             :                 {
    7436           0 :                     CPLErrorReset();
    7437           0 :                     ret = OGRERR_NONE;
    7438             :                 }
    7439             :             }
    7440             :         }
    7441             :     }
    7442             : 
    7443             :     // restore the original filter and add features from the update layer
    7444           6 :     pLayerMethod->SetSpatialFilter(pGeometryMethodFilter);
    7445          16 :     for (auto &&y : pLayerMethod)
    7446             :     {
    7447             : 
    7448          10 :         if (pfnProgress)
    7449             :         {
    7450           1 :             double p = progress_counter / progress_max;
    7451           1 :             if (p > progress_ticker)
    7452             :             {
    7453           1 :                 if (!pfnProgress(p, "", pProgressArg))
    7454             :                 {
    7455           0 :                     CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    7456           0 :                     ret = OGRERR_FAILURE;
    7457           0 :                     goto done;
    7458             :                 }
    7459             :             }
    7460           1 :             progress_counter += 1.0;
    7461             :         }
    7462             : 
    7463          10 :         std::unique_ptr<OGRGeometry> y_geom(y->StealGeometry());
    7464          10 :         if (!y_geom)
    7465           0 :             continue;
    7466          20 :         y_geom = convert_geometry(std::move(y_geom), bPromoteToMulti,
    7467          10 :                                   eOutputGeometryType);
    7468          10 :         if (!y_geom)
    7469           0 :             continue;
    7470          10 :         OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    7471          10 :         if (mapMethod)
    7472           6 :             z->SetFieldsFrom(y.get(), mapMethod);
    7473          10 :         z->SetGeometryDirectly(y_geom.release());
    7474          10 :         ret = pLayerResult->CreateFeature(z.get());
    7475          10 :         if (ret != OGRERR_NONE)
    7476             :         {
    7477           0 :             if (!bSkipFailures)
    7478             :             {
    7479           0 :                 goto done;
    7480             :             }
    7481             :             else
    7482             :             {
    7483           0 :                 CPLErrorReset();
    7484           0 :                 ret = OGRERR_NONE;
    7485             :             }
    7486             :         }
    7487             :     }
    7488           6 :     if (pfnProgress && !pfnProgress(1.0, "", pProgressArg))
    7489             :     {
    7490           0 :         CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    7491           0 :         ret = OGRERR_FAILURE;
    7492           0 :         goto done;
    7493             :     }
    7494           6 : done:
    7495             :     // release resources
    7496           6 :     pLayerMethod->SetSpatialFilter(pGeometryMethodFilter);
    7497           6 :     if (pGeometryMethodFilter)
    7498           0 :         delete pGeometryMethodFilter;
    7499           6 :     if (mapInput)
    7500           4 :         VSIFree(mapInput);
    7501           6 :     if (mapMethod)
    7502           4 :         VSIFree(mapMethod);
    7503           6 :     return ret;
    7504             : }
    7505             : 
    7506             : /************************************************************************/
    7507             : /*                            OGR_L_Update()                            */
    7508             : /************************************************************************/
    7509             : 
    7510             : /**
    7511             :  * \brief Update this layer with features from the update layer.
    7512             :  *
    7513             :  * The result layer contains features whose geometries represent areas
    7514             :  * that are either in the input layer or in the method layer. The
    7515             :  * features in the result layer have areas of the features of the
    7516             :  * method layer or those ares of the features of the input layer that
    7517             :  * are not covered by the method layer. The features of the result
    7518             :  * layer get their attributes from the input layer. The schema of the
    7519             :  * result layer can be set by the user or, if it is empty, is
    7520             :  * initialized to contain all fields in the input layer.
    7521             :  *
    7522             :  * \note If the schema of the result is set by user and contains
    7523             :  * fields that have the same name as a field in the method layer, then
    7524             :  * the attribute in the result feature the originates from the method
    7525             :  * layer will get the value from the feature of the method layer.
    7526             :  *
    7527             :  * \note For best performance use the minimum amount of features in
    7528             :  * the method layer and copy it into a memory layer.
    7529             :  *
    7530             :  * \note This method relies on GEOS support. Do not use unless the
    7531             :  * GEOS support is compiled in.
    7532             :  *
    7533             :  * The recognized list of options is :
    7534             :  * <ul>
    7535             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    7536             :  *     feature could not be inserted or a GEOS call failed.
    7537             :  * </li>
    7538             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    7539             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    7540             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    7541             :  * </li>
    7542             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    7543             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    7544             :  *     be converted to it, the corresponding output feature is silently skipped.
    7545             :  *     Takes precedence over PROMOTE_TO_MULTI.
    7546             :  * </li>
    7547             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    7548             :  *     will be created from the fields of the input layer.
    7549             :  * </li>
    7550             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    7551             :  *     will be created from the fields of the method layer.
    7552             :  * </li>
    7553             :  * </ul>
    7554             :  *
    7555             :  * This function is the same as the C++ method OGRLayer::Update().
    7556             :  *
    7557             :  * @param pLayerInput the input layer. Should not be NULL.
    7558             :  *
    7559             :  * @param pLayerMethod the method layer. Should not be NULL.
    7560             :  *
    7561             :  * @param pLayerResult the layer where the features resulting from the
    7562             :  * operation are inserted. Should not be NULL. See above the note
    7563             :  * about the schema.
    7564             :  *
    7565             :  * @param papszOptions NULL terminated list of options (may be NULL).
    7566             :  *
    7567             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    7568             :  * reporting progress or NULL.
    7569             :  *
    7570             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    7571             :  *
    7572             :  * @return an error code if there was an error or the execution was
    7573             :  * interrupted, OGRERR_NONE otherwise.
    7574             :  *
    7575             :  * @note The first geometry field is always used.
    7576             :  *
    7577             :  * @since OGR 1.10
    7578             :  */
    7579             : 
    7580           5 : OGRErr OGR_L_Update(OGRLayerH pLayerInput, OGRLayerH pLayerMethod,
    7581             :                     OGRLayerH pLayerResult, CSLConstList papszOptions,
    7582             :                     GDALProgressFunc pfnProgress, void *pProgressArg)
    7583             : 
    7584             : {
    7585           5 :     VALIDATE_POINTER1(pLayerInput, "OGR_L_Update", OGRERR_INVALID_HANDLE);
    7586           5 :     VALIDATE_POINTER1(pLayerMethod, "OGR_L_Update", OGRERR_INVALID_HANDLE);
    7587           5 :     VALIDATE_POINTER1(pLayerResult, "OGR_L_Update", OGRERR_INVALID_HANDLE);
    7588             : 
    7589             :     return OGRLayer::FromHandle(pLayerInput)
    7590           5 :         ->Update(OGRLayer::FromHandle(pLayerMethod),
    7591             :                  OGRLayer::FromHandle(pLayerResult), papszOptions, pfnProgress,
    7592           5 :                  pProgressArg);
    7593             : }
    7594             : 
    7595             : /************************************************************************/
    7596             : /*                                Clip()                                */
    7597             : /************************************************************************/
    7598             : 
    7599             : /**
    7600             :  * \brief Clip off areas that are not covered by the method layer.
    7601             :  *
    7602             :  * The result layer contains features whose geometries represent areas
    7603             :  * that are in the input layer and in the method layer. The features
    7604             :  * in the result layer have the (possibly clipped) areas of features
    7605             :  * in the input layer and the attributes from the same features. The
    7606             :  * schema of the result layer can be set by the user or, if it is
    7607             :  * empty, is initialized to contain all fields in the input layer.
    7608             :  *
    7609             :  * \note For best performance use the minimum amount of features in
    7610             :  * the method layer and copy it into a memory layer.
    7611             :  *
    7612             :  * \note This method relies on GEOS support. Do not use unless the
    7613             :  * GEOS support is compiled in.
    7614             :  *
    7615             :  * The recognized list of options is :
    7616             :  * <ul>
    7617             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    7618             :  *     feature could not be inserted or a GEOS call failed.
    7619             :  * </li>
    7620             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    7621             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    7622             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    7623             :  * </li>
    7624             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    7625             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    7626             :  *     be converted to it, the corresponding output feature is silently skipped.
    7627             :  *     Takes precedence over PROMOTE_TO_MULTI.
    7628             :  * </li>
    7629             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    7630             :  *     will be created from the fields of the input layer.
    7631             :  * </li>
    7632             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    7633             :  *     will be created from the fields of the method layer.
    7634             :  * </li>
    7635             :  * </ul>
    7636             :  *
    7637             :  * This method is the same as the C function OGR_L_Clip().
    7638             :  *
    7639             :  * @param pLayerMethod the method layer. Should not be NULL.
    7640             :  *
    7641             :  * @param pLayerResult the layer where the features resulting from the
    7642             :  * operation are inserted. Should not be NULL. See above the note
    7643             :  * about the schema.
    7644             :  *
    7645             :  * @param papszOptions NULL terminated list of options (may be NULL).
    7646             :  *
    7647             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    7648             :  * reporting progress or NULL.
    7649             :  *
    7650             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    7651             :  *
    7652             :  * @return an error code if there was an error or the execution was
    7653             :  * interrupted, OGRERR_NONE otherwise.
    7654             :  *
    7655             :  * @note The first geometry field is always used.
    7656             :  *
    7657             :  * @since OGR 1.10
    7658             :  */
    7659             : 
    7660           4 : OGRErr OGRLayer::Clip(OGRLayer *pLayerMethod, OGRLayer *pLayerResult,
    7661             :                       CSLConstList papszOptions, GDALProgressFunc pfnProgress,
    7662             :                       void *pProgressArg)
    7663             : {
    7664           4 :     OGRErr ret = OGRERR_NONE;
    7665           4 :     OGRFeatureDefn *poDefnInput = GetLayerDefn();
    7666           4 :     OGRFeatureDefn *poDefnResult = nullptr;
    7667           4 :     OGRGeometry *pGeometryMethodFilter = nullptr;
    7668           4 :     int *mapInput = nullptr;
    7669           4 :     double progress_max = static_cast<double>(GetFeatureCount(FALSE));
    7670           4 :     double progress_counter = 0;
    7671           4 :     double progress_ticker = 0;
    7672             :     const bool bSkipFailures =
    7673           4 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "SKIP_FAILURES", "NO"));
    7674           4 :     const bool bPromoteToMulti = CPLTestBool(
    7675             :         CSLFetchNameValueDef(papszOptions, "PROMOTE_TO_MULTI", "NO"));
    7676             :     const char *pszOutputGeometryType =
    7677           4 :         CSLFetchNameValueDef(papszOptions, "OUTPUT_GEOMETRY_TYPE", "GEOMETRY");
    7678           4 :     const auto eOutputGeometryType = OGRFromOGCGeomType(pszOutputGeometryType);
    7679             : 
    7680             :     // check for GEOS
    7681           4 :     if (!OGRGeometryFactory::haveGEOS())
    7682             :     {
    7683           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    7684             :                  "OGRLayer::Clip() requires GEOS support");
    7685           0 :         return OGRERR_UNSUPPORTED_OPERATION;
    7686             :     }
    7687             : 
    7688           4 :     ret = clone_spatial_filter(pLayerMethod, &pGeometryMethodFilter);
    7689           4 :     if (ret != OGRERR_NONE)
    7690           0 :         goto done;
    7691           4 :     ret = create_field_map(poDefnInput, &mapInput);
    7692           4 :     if (ret != OGRERR_NONE)
    7693           0 :         goto done;
    7694           4 :     ret = set_result_schema(pLayerResult, poDefnInput, nullptr, mapInput,
    7695             :                             nullptr, false, papszOptions);
    7696           4 :     if (ret != OGRERR_NONE)
    7697           0 :         goto done;
    7698             : 
    7699           4 :     poDefnResult = pLayerResult->GetLayerDefn();
    7700          12 :     for (auto &&x : this)
    7701             :     {
    7702             : 
    7703           8 :         if (pfnProgress)
    7704             :         {
    7705           2 :             double p = progress_counter / progress_max;
    7706           2 :             if (p > progress_ticker)
    7707             :             {
    7708           1 :                 if (!pfnProgress(p, "", pProgressArg))
    7709             :                 {
    7710           0 :                     CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    7711           0 :                     ret = OGRERR_FAILURE;
    7712           0 :                     goto done;
    7713             :                 }
    7714             :             }
    7715           2 :             progress_counter += 1.0;
    7716             :         }
    7717             : 
    7718             :         // set up the filter on method layer
    7719           8 :         CPLErrorReset();
    7720             :         OGRGeometry *x_geom =
    7721           8 :             set_filter_from(pLayerMethod, pGeometryMethodFilter, x.get());
    7722           8 :         if (CPLGetLastErrorType() != CE_None)
    7723             :         {
    7724           0 :             if (!bSkipFailures)
    7725             :             {
    7726           0 :                 ret = OGRERR_FAILURE;
    7727           0 :                 goto done;
    7728             :             }
    7729             :             else
    7730             :             {
    7731           0 :                 CPLErrorReset();
    7732           0 :                 ret = OGRERR_NONE;
    7733             :             }
    7734             :         }
    7735           8 :         if (!x_geom)
    7736             :         {
    7737           0 :             continue;
    7738             :         }
    7739             : 
    7740             :         std::unique_ptr<OGRGeometry>
    7741           0 :             geom;  // this will be the geometry of the result feature
    7742             :         // incrementally add area from y to geom
    7743          16 :         for (auto &&y : pLayerMethod)
    7744             :         {
    7745           8 :             OGRGeometry *y_geom = y->GetGeometryRef();
    7746           8 :             if (!y_geom)
    7747           0 :                 continue;
    7748           8 :             if (!geom)
    7749             :             {
    7750           8 :                 geom.reset(y_geom->clone());
    7751             :             }
    7752             :             else
    7753             :             {
    7754           0 :                 CPLErrorReset();
    7755           0 :                 std::unique_ptr<OGRGeometry> geom_new(geom->Union(y_geom));
    7756           0 :                 if (CPLGetLastErrorType() != CE_None || geom_new == nullptr)
    7757             :                 {
    7758           0 :                     if (!bSkipFailures)
    7759             :                     {
    7760           0 :                         ret = OGRERR_FAILURE;
    7761           0 :                         goto done;
    7762             :                     }
    7763             :                     else
    7764             :                     {
    7765           0 :                         CPLErrorReset();
    7766           0 :                         ret = OGRERR_NONE;
    7767             :                     }
    7768             :                 }
    7769             :                 else
    7770             :                 {
    7771           0 :                     geom.swap(geom_new);
    7772             :                 }
    7773             :             }
    7774             :         }
    7775             : 
    7776             :         // possibly add a new feature with area x intersection sum of y
    7777           8 :         if (geom)
    7778             :         {
    7779           8 :             CPLErrorReset();
    7780             :             std::unique_ptr<OGRGeometry> poIntersection(
    7781           8 :                 x_geom->Intersection(geom.get()));
    7782           8 :             if (CPLGetLastErrorType() != CE_None || poIntersection == nullptr)
    7783             :             {
    7784           0 :                 if (!bSkipFailures)
    7785             :                 {
    7786           0 :                     ret = OGRERR_FAILURE;
    7787           0 :                     goto done;
    7788             :                 }
    7789             :                 else
    7790             :                 {
    7791           0 :                     CPLErrorReset();
    7792           0 :                     ret = OGRERR_NONE;
    7793             :                 }
    7794             :             }
    7795           8 :             else if (!poIntersection->IsEmpty())
    7796             :             {
    7797           8 :                 OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    7798           8 :                 z->SetFieldsFrom(x.get(), mapInput);
    7799             :                 poIntersection =
    7800          16 :                     convert_geometry(std::move(poIntersection), bPromoteToMulti,
    7801           8 :                                      eOutputGeometryType);
    7802           8 :                 if (!poIntersection)
    7803           0 :                     continue;
    7804           8 :                 z->SetGeometryDirectly(poIntersection.release());
    7805           8 :                 ret = pLayerResult->CreateFeature(z.get());
    7806           8 :                 if (ret != OGRERR_NONE)
    7807             :                 {
    7808           0 :                     if (!bSkipFailures)
    7809             :                     {
    7810           0 :                         goto done;
    7811             :                     }
    7812             :                     else
    7813             :                     {
    7814           0 :                         CPLErrorReset();
    7815           0 :                         ret = OGRERR_NONE;
    7816             :                     }
    7817             :                 }
    7818             :             }
    7819             :         }
    7820             :     }
    7821           4 :     if (pfnProgress && !pfnProgress(1.0, "", pProgressArg))
    7822             :     {
    7823           0 :         CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    7824           0 :         ret = OGRERR_FAILURE;
    7825           0 :         goto done;
    7826             :     }
    7827           4 : done:
    7828             :     // release resources
    7829           4 :     pLayerMethod->SetSpatialFilter(pGeometryMethodFilter);
    7830           4 :     if (pGeometryMethodFilter)
    7831           0 :         delete pGeometryMethodFilter;
    7832           4 :     if (mapInput)
    7833           4 :         VSIFree(mapInput);
    7834           4 :     return ret;
    7835             : }
    7836             : 
    7837             : /************************************************************************/
    7838             : /*                             OGR_L_Clip()                             */
    7839             : /************************************************************************/
    7840             : 
    7841             : /**
    7842             :  * \brief Clip off areas that are not covered by the method layer.
    7843             :  *
    7844             :  * The result layer contains features whose geometries represent areas
    7845             :  * that are in the input layer and in the method layer. The features
    7846             :  * in the result layer have the (possibly clipped) areas of features
    7847             :  * in the input layer and the attributes from the same features. The
    7848             :  * schema of the result layer can be set by the user or, if it is
    7849             :  * empty, is initialized to contain all fields in the input layer.
    7850             :  *
    7851             :  * \note For best performance use the minimum amount of features in
    7852             :  * the method layer and copy it into a memory layer.
    7853             :  *
    7854             :  * \note This method relies on GEOS support. Do not use unless the
    7855             :  * GEOS support is compiled in.
    7856             :  *
    7857             :  * The recognized list of options is :
    7858             :  * <ul>
    7859             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    7860             :  *     feature could not be inserted or a GEOS call failed.
    7861             :  * </li>
    7862             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    7863             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    7864             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    7865             :  * </li>
    7866             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    7867             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    7868             :  *     be converted to it, the corresponding output feature is silently skipped.
    7869             :  *     Takes precedence over PROMOTE_TO_MULTI.
    7870             :  * </li>
    7871             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    7872             :  *     will be created from the fields of the input layer.
    7873             :  * </li>
    7874             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    7875             :  *     will be created from the fields of the method layer.
    7876             :  * </li>
    7877             :  * </ul>
    7878             :  *
    7879             :  * This function is the same as the C++ method OGRLayer::Clip().
    7880             :  *
    7881             :  * @param pLayerInput the input layer. Should not be NULL.
    7882             :  *
    7883             :  * @param pLayerMethod the method layer. Should not be NULL.
    7884             :  *
    7885             :  * @param pLayerResult the layer where the features resulting from the
    7886             :  * operation are inserted. Should not be NULL. See above the note
    7887             :  * about the schema.
    7888             :  *
    7889             :  * @param papszOptions NULL terminated list of options (may be NULL).
    7890             :  *
    7891             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    7892             :  * reporting progress or NULL.
    7893             :  *
    7894             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    7895             :  *
    7896             :  * @return an error code if there was an error or the execution was
    7897             :  * interrupted, OGRERR_NONE otherwise.
    7898             :  *
    7899             :  * @note The first geometry field is always used.
    7900             :  *
    7901             :  * @since OGR 1.10
    7902             :  */
    7903             : 
    7904           3 : OGRErr OGR_L_Clip(OGRLayerH pLayerInput, OGRLayerH pLayerMethod,
    7905             :                   OGRLayerH pLayerResult, CSLConstList papszOptions,
    7906             :                   GDALProgressFunc pfnProgress, void *pProgressArg)
    7907             : 
    7908             : {
    7909           3 :     VALIDATE_POINTER1(pLayerInput, "OGR_L_Clip", OGRERR_INVALID_HANDLE);
    7910           3 :     VALIDATE_POINTER1(pLayerMethod, "OGR_L_Clip", OGRERR_INVALID_HANDLE);
    7911           3 :     VALIDATE_POINTER1(pLayerResult, "OGR_L_Clip", OGRERR_INVALID_HANDLE);
    7912             : 
    7913             :     return OGRLayer::FromHandle(pLayerInput)
    7914           3 :         ->Clip(OGRLayer::FromHandle(pLayerMethod),
    7915             :                OGRLayer::FromHandle(pLayerResult), papszOptions, pfnProgress,
    7916           3 :                pProgressArg);
    7917             : }
    7918             : 
    7919             : /************************************************************************/
    7920             : /*                               Erase()                                */
    7921             : /************************************************************************/
    7922             : 
    7923             : /**
    7924             :  * \brief Remove areas that are covered by the method layer.
    7925             :  *
    7926             :  * The result layer contains features whose geometries represent areas
    7927             :  * that are in the input layer but not in the method layer. The
    7928             :  * features in the result layer have attributes from the input
    7929             :  * layer. The schema of the result layer can be set by the user or, if
    7930             :  * it is empty, is initialized to contain all fields in the input
    7931             :  * layer.
    7932             :  *
    7933             :  * \note For best performance use the minimum amount of features in
    7934             :  * the method layer and copy it into a memory layer.
    7935             :  *
    7936             :  * \note This method relies on GEOS support. Do not use unless the
    7937             :  * GEOS support is compiled in.
    7938             :  *
    7939             :  * The recognized list of options is :
    7940             :  * <ul>
    7941             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    7942             :  *     feature could not be inserted or a GEOS call failed.
    7943             :  * </li>
    7944             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    7945             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    7946             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    7947             :  * </li>
    7948             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    7949             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    7950             :  *     be converted to it, the corresponding output feature is silently skipped.
    7951             :  *     Takes precedence over PROMOTE_TO_MULTI.
    7952             :  * </li>
    7953             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    7954             :  *     will be created from the fields of the input layer.
    7955             :  * </li>
    7956             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    7957             :  *     will be created from the fields of the method layer.
    7958             :  * </li>
    7959             :  * </ul>
    7960             :  *
    7961             :  * This method is the same as the C function OGR_L_Erase().
    7962             :  *
    7963             :  * @param pLayerMethod the method layer. Should not be NULL.
    7964             :  *
    7965             :  * @param pLayerResult the layer where the features resulting from the
    7966             :  * operation are inserted. Should not be NULL. See above the note
    7967             :  * about the schema.
    7968             :  *
    7969             :  * @param papszOptions NULL terminated list of options (may be NULL).
    7970             :  *
    7971             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    7972             :  * reporting progress or NULL.
    7973             :  *
    7974             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    7975             :  *
    7976             :  * @return an error code if there was an error or the execution was
    7977             :  * interrupted, OGRERR_NONE otherwise.
    7978             :  *
    7979             :  * @note The first geometry field is always used.
    7980             :  *
    7981             :  * @since OGR 1.10
    7982             :  */
    7983             : 
    7984           7 : OGRErr OGRLayer::Erase(OGRLayer *pLayerMethod, OGRLayer *pLayerResult,
    7985             :                        CSLConstList papszOptions, GDALProgressFunc pfnProgress,
    7986             :                        void *pProgressArg)
    7987             : {
    7988           7 :     OGRErr ret = OGRERR_NONE;
    7989           7 :     OGRFeatureDefn *poDefnInput = GetLayerDefn();
    7990           7 :     OGRFeatureDefn *poDefnResult = nullptr;
    7991           7 :     OGRGeometry *pGeometryMethodFilter = nullptr;
    7992           7 :     int *mapInput = nullptr;
    7993           7 :     double progress_max = static_cast<double>(GetFeatureCount(FALSE));
    7994           7 :     double progress_counter = 0;
    7995           7 :     double progress_ticker = 0;
    7996             :     const bool bSkipFailures =
    7997           7 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "SKIP_FAILURES", "NO"));
    7998           7 :     const bool bPromoteToMulti = CPLTestBool(
    7999             :         CSLFetchNameValueDef(papszOptions, "PROMOTE_TO_MULTI", "NO"));
    8000             :     const char *pszOutputGeometryType =
    8001           7 :         CSLFetchNameValueDef(papszOptions, "OUTPUT_GEOMETRY_TYPE", "GEOMETRY");
    8002           7 :     const auto eOutputGeometryType = OGRFromOGCGeomType(pszOutputGeometryType);
    8003             : 
    8004             :     // check for GEOS
    8005           7 :     if (!OGRGeometryFactory::haveGEOS())
    8006             :     {
    8007           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    8008             :                  "OGRLayer::Erase() requires GEOS support");
    8009           0 :         return OGRERR_UNSUPPORTED_OPERATION;
    8010             :     }
    8011             : 
    8012             :     // get resources
    8013           7 :     ret = clone_spatial_filter(pLayerMethod, &pGeometryMethodFilter);
    8014           7 :     if (ret != OGRERR_NONE)
    8015           0 :         goto done;
    8016           7 :     ret = create_field_map(poDefnInput, &mapInput);
    8017           7 :     if (ret != OGRERR_NONE)
    8018           0 :         goto done;
    8019           7 :     ret = set_result_schema(pLayerResult, poDefnInput, nullptr, mapInput,
    8020             :                             nullptr, false, papszOptions);
    8021           7 :     if (ret != OGRERR_NONE)
    8022           0 :         goto done;
    8023           7 :     poDefnResult = pLayerResult->GetLayerDefn();
    8024             : 
    8025          21 :     for (auto &&x : this)
    8026             :     {
    8027             : 
    8028          14 :         if (pfnProgress)
    8029             :         {
    8030           2 :             double p = progress_counter / progress_max;
    8031           2 :             if (p > progress_ticker)
    8032             :             {
    8033           1 :                 if (!pfnProgress(p, "", pProgressArg))
    8034             :                 {
    8035           0 :                     CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    8036           0 :                     ret = OGRERR_FAILURE;
    8037           0 :                     goto done;
    8038             :                 }
    8039             :             }
    8040           2 :             progress_counter += 1.0;
    8041             :         }
    8042             : 
    8043             :         // set up the filter on the method layer
    8044          14 :         CPLErrorReset();
    8045             :         OGRGeometry *x_geom =
    8046          14 :             set_filter_from(pLayerMethod, pGeometryMethodFilter, x.get());
    8047          14 :         if (CPLGetLastErrorType() != CE_None)
    8048             :         {
    8049           0 :             if (!bSkipFailures)
    8050             :             {
    8051           0 :                 ret = OGRERR_FAILURE;
    8052           0 :                 goto done;
    8053             :             }
    8054             :             else
    8055             :             {
    8056           0 :                 CPLErrorReset();
    8057           0 :                 ret = OGRERR_NONE;
    8058             :             }
    8059             :         }
    8060          14 :         if (!x_geom)
    8061             :         {
    8062           0 :             continue;
    8063             :         }
    8064             : 
    8065             :         std::unique_ptr<OGRGeometry> geom(
    8066             :             x_geom
    8067          14 :                 ->clone());  // this will be the geometry of the result feature
    8068             :         // incrementally erase y from geom
    8069          22 :         for (auto &&y : pLayerMethod)
    8070             :         {
    8071          11 :             OGRGeometry *y_geom = y->GetGeometryRef();
    8072          11 :             if (!y_geom)
    8073           0 :                 continue;
    8074          11 :             CPLErrorReset();
    8075          11 :             std::unique_ptr<OGRGeometry> geom_new(geom->Difference(y_geom));
    8076          11 :             if (CPLGetLastErrorType() != CE_None || geom_new == nullptr)
    8077             :             {
    8078           0 :                 if (!bSkipFailures)
    8079             :                 {
    8080           0 :                     ret = OGRERR_FAILURE;
    8081           0 :                     goto done;
    8082             :                 }
    8083             :                 else
    8084             :                 {
    8085           0 :                     CPLErrorReset();
    8086           0 :                     ret = OGRERR_NONE;
    8087             :                 }
    8088             :             }
    8089             :             else
    8090             :             {
    8091          11 :                 geom.swap(geom_new);
    8092          11 :                 if (geom->IsEmpty())
    8093             :                 {
    8094           3 :                     break;
    8095             :                 }
    8096             :             }
    8097             :         }
    8098             : 
    8099             :         // add a new feature if there is remaining area
    8100          14 :         if (!geom->IsEmpty())
    8101             :         {
    8102          11 :             OGRFeatureUniquePtr z(new OGRFeature(poDefnResult));
    8103          11 :             z->SetFieldsFrom(x.get(), mapInput);
    8104          22 :             geom = convert_geometry(std::move(geom), bPromoteToMulti,
    8105          11 :                                     eOutputGeometryType);
    8106          11 :             if (!geom)
    8107           0 :                 continue;
    8108          11 :             z->SetGeometryDirectly(geom.release());
    8109          11 :             ret = pLayerResult->CreateFeature(z.get());
    8110          11 :             if (ret != OGRERR_NONE)
    8111             :             {
    8112           0 :                 if (!bSkipFailures)
    8113             :                 {
    8114           0 :                     goto done;
    8115             :                 }
    8116             :                 else
    8117             :                 {
    8118           0 :                     CPLErrorReset();
    8119           0 :                     ret = OGRERR_NONE;
    8120             :                 }
    8121             :             }
    8122             :         }
    8123             :     }
    8124           7 :     if (pfnProgress && !pfnProgress(1.0, "", pProgressArg))
    8125             :     {
    8126           0 :         CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
    8127           0 :         ret = OGRERR_FAILURE;
    8128           0 :         goto done;
    8129             :     }
    8130           7 : done:
    8131             :     // release resources
    8132           7 :     pLayerMethod->SetSpatialFilter(pGeometryMethodFilter);
    8133           7 :     if (pGeometryMethodFilter)
    8134           0 :         delete pGeometryMethodFilter;
    8135           7 :     if (mapInput)
    8136           6 :         VSIFree(mapInput);
    8137           7 :     return ret;
    8138             : }
    8139             : 
    8140             : /************************************************************************/
    8141             : /*                            OGR_L_Erase()                             */
    8142             : /************************************************************************/
    8143             : 
    8144             : /**
    8145             :  * \brief Remove areas that are covered by the method layer.
    8146             :  *
    8147             :  * The result layer contains features whose geometries represent areas
    8148             :  * that are in the input layer but not in the method layer. The
    8149             :  * features in the result layer have attributes from the input
    8150             :  * layer. The schema of the result layer can be set by the user or, if
    8151             :  * it is empty, is initialized to contain all fields in the input
    8152             :  * layer.
    8153             :  *
    8154             :  * \note For best performance use the minimum amount of features in
    8155             :  * the method layer and copy it into a memory layer.
    8156             :  *
    8157             :  * \note This method relies on GEOS support. Do not use unless the
    8158             :  * GEOS support is compiled in.
    8159             :  *
    8160             :  * The recognized list of options is :
    8161             :  * <ul>
    8162             :  * <li>SKIP_FAILURES=YES/NO. Set it to YES to go on, even when a
    8163             :  *     feature could not be inserted or a GEOS call failed.
    8164             :  * </li>
    8165             :  * <li>PROMOTE_TO_MULTI=YES/NO. Set to YES to convert Polygons
    8166             :  *     into MultiPolygons, LineStrings to MultiLineStrings or
    8167             :  *     Points to MultiPoints (only since GDAL 3.9.2 for the later)
    8168             :  * </li>
    8169             :  * <li>OUTPUT_GEOMETRY_TYPE=[MULTI]POINT/[MULTI]LINESTRING/[MULTI]POLYGON/GEOMETRYCOLLECTION/GEOMETRY
    8170             :  *     Output geometry type (since GDAL 3.14.0). If the output geometry cannot
    8171             :  *     be converted to it, the corresponding output feature is silently skipped.
    8172             :  *     Takes precedence over PROMOTE_TO_MULTI.
    8173             :  * </li>
    8174             :  * <li>INPUT_PREFIX=string. Set a prefix for the field names that
    8175             :  *     will be created from the fields of the input layer.
    8176             :  * </li>
    8177             :  * <li>METHOD_PREFIX=string. Set a prefix for the field names that
    8178             :  *     will be created from the fields of the method layer.
    8179             :  * </li>
    8180             :  * </ul>
    8181             :  *
    8182             :  * This function is the same as the C++ method OGRLayer::Erase().
    8183             :  *
    8184             :  * @param pLayerInput the input layer. Should not be NULL.
    8185             :  *
    8186             :  * @param pLayerMethod the method layer. Should not be NULL.
    8187             :  *
    8188             :  * @param pLayerResult the layer where the features resulting from the
    8189             :  * operation are inserted. Should not be NULL. See above the note
    8190             :  * about the schema.
    8191             :  *
    8192             :  * @param papszOptions NULL terminated list of options (may be NULL).
    8193             :  *
    8194             :  * @param pfnProgress a GDALProgressFunc() compatible callback function for
    8195             :  * reporting progress or NULL.
    8196             :  *
    8197             :  * @param pProgressArg argument to be passed to pfnProgress. May be NULL.
    8198             :  *
    8199             :  * @return an error code if there was an error or the execution was
    8200             :  * interrupted, OGRERR_NONE otherwise.
    8201             :  *
    8202             :  * @note The first geometry field is always used.
    8203             :  *
    8204             :  * @since OGR 1.10
    8205             :  */
    8206             : 
    8207           6 : OGRErr OGR_L_Erase(OGRLayerH pLayerInput, OGRLayerH pLayerMethod,
    8208             :                    OGRLayerH pLayerResult, CSLConstList papszOptions,
    8209             :                    GDALProgressFunc pfnProgress, void *pProgressArg)
    8210             : 
    8211             : {
    8212           6 :     VALIDATE_POINTER1(pLayerInput, "OGR_L_Erase", OGRERR_INVALID_HANDLE);
    8213           6 :     VALIDATE_POINTER1(pLayerMethod, "OGR_L_Erase", OGRERR_INVALID_HANDLE);
    8214           6 :     VALIDATE_POINTER1(pLayerResult, "OGR_L_Erase", OGRERR_INVALID_HANDLE);
    8215             : 
    8216             :     return OGRLayer::FromHandle(pLayerInput)
    8217           6 :         ->Erase(OGRLayer::FromHandle(pLayerMethod),
    8218             :                 OGRLayer::FromHandle(pLayerResult), papszOptions, pfnProgress,
    8219           6 :                 pProgressArg);
    8220             : }
    8221             : 
    8222             : /************************************************************************/
    8223             : /*                  OGRLayer::FeatureIterator::Private                  */
    8224             : /************************************************************************/
    8225             : 
    8226             : struct OGRLayer::FeatureIterator::Private
    8227             : {
    8228             :     CPL_DISALLOW_COPY_ASSIGN(Private)
    8229       41108 :     Private() = default;
    8230             : 
    8231             :     OGRFeatureUniquePtr m_poFeature{};
    8232             :     OGRLayer *m_poLayer = nullptr;
    8233             :     bool m_bError = false;
    8234             :     bool m_bEOF = true;
    8235             : };
    8236             : 
    8237             : /************************************************************************/
    8238             : /*             OGRLayer::FeatureIterator::FeatureIterator()             */
    8239             : /************************************************************************/
    8240             : 
    8241       41108 : OGRLayer::FeatureIterator::FeatureIterator(OGRLayer *poLayer, bool bStart)
    8242       41108 :     : m_poPrivate(new OGRLayer::FeatureIterator::Private())
    8243             : {
    8244       41108 :     m_poPrivate->m_poLayer = poLayer;
    8245       41108 :     if (bStart)
    8246             :     {
    8247       20554 :         if (m_poPrivate->m_poLayer->m_poPrivate->m_bInFeatureIterator)
    8248             :         {
    8249           1 :             CPLError(CE_Failure, CPLE_NotSupported,
    8250             :                      "Only one feature iterator can be "
    8251             :                      "active at a time");
    8252           1 :             m_poPrivate->m_bError = true;
    8253             :         }
    8254             :         else
    8255             :         {
    8256       20553 :             m_poPrivate->m_poLayer->ResetReading();
    8257       41106 :             m_poPrivate->m_poFeature.reset(
    8258       20553 :                 m_poPrivate->m_poLayer->GetNextFeature());
    8259       20553 :             m_poPrivate->m_bEOF = m_poPrivate->m_poFeature == nullptr;
    8260       20553 :             m_poPrivate->m_poLayer->m_poPrivate->m_bInFeatureIterator = true;
    8261             :         }
    8262             :     }
    8263       41108 : }
    8264             : 
    8265             : /************************************************************************/
    8266             : /*            ~OGRLayer::FeatureIterator::FeatureIterator()             */
    8267             : /************************************************************************/
    8268             : 
    8269       41108 : OGRLayer::FeatureIterator::~FeatureIterator()
    8270             : {
    8271       41108 :     if (!m_poPrivate->m_bError && m_poPrivate->m_poLayer)
    8272       41107 :         m_poPrivate->m_poLayer->m_poPrivate->m_bInFeatureIterator = false;
    8273       41108 : }
    8274             : 
    8275             : /************************************************************************/
    8276             : /*                             operator*()                              */
    8277             : /************************************************************************/
    8278             : 
    8279      170988 : OGRFeatureUniquePtr &OGRLayer::FeatureIterator::operator*()
    8280             : {
    8281      170988 :     return m_poPrivate->m_poFeature;
    8282             : }
    8283             : 
    8284             : /************************************************************************/
    8285             : /*                             operator++()                             */
    8286             : /************************************************************************/
    8287             : 
    8288      170220 : OGRLayer::FeatureIterator &OGRLayer::FeatureIterator::operator++()
    8289             : {
    8290      170220 :     m_poPrivate->m_poFeature.reset(m_poPrivate->m_poLayer->GetNextFeature());
    8291      170220 :     m_poPrivate->m_bEOF = m_poPrivate->m_poFeature == nullptr;
    8292      170220 :     return *this;
    8293             : }
    8294             : 
    8295             : /************************************************************************/
    8296             : /*                             operator!=()                             */
    8297             : /************************************************************************/
    8298             : 
    8299      190774 : bool OGRLayer::FeatureIterator::operator!=(
    8300             :     const OGRLayer::FeatureIterator &it) const
    8301             : {
    8302      190774 :     return m_poPrivate->m_bEOF != it.m_poPrivate->m_bEOF;
    8303             : }
    8304             : 
    8305             : /************************************************************************/
    8306             : /*                               begin()                                */
    8307             : /************************************************************************/
    8308             : 
    8309       20554 : OGRLayer::FeatureIterator OGRLayer::begin()
    8310             : {
    8311       20554 :     return {this, true};
    8312             : }
    8313             : 
    8314             : /************************************************************************/
    8315             : /*                                end()                                 */
    8316             : /************************************************************************/
    8317             : 
    8318       20554 : OGRLayer::FeatureIterator OGRLayer::end()
    8319             : {
    8320       20554 :     return {this, false};
    8321             : }
    8322             : 
    8323             : /************************************************************************/
    8324             : /*                     OGRLayer::GetGeometryTypes()                     */
    8325             : /************************************************************************/
    8326             : 
    8327             : /** \brief Get actual geometry types found in features.
    8328             :  *
    8329             :  * This method iterates over features to retrieve their geometry types. This
    8330             :  * is mostly useful for layers that report a wkbUnknown geometry type with
    8331             :  * GetGeomType() or GetGeomFieldDefn(iGeomField)->GetType().
    8332             :  *
    8333             :  * By default this method returns an array of nEntryCount entries with each
    8334             :  * geometry type (in OGRGeometryTypeCounter::eGeomType) and the corresponding
    8335             :  * number of features (in OGRGeometryTypeCounter::nCount).
    8336             :  * Features without geometries are reported as eGeomType == wkbNone.
    8337             :  *
    8338             :  * The nFlagsGGT parameter can be a combination (with binary or operator) of the
    8339             :  * following hints:
    8340             :  * <ul>
    8341             :  * <li>OGR_GGT_COUNT_NOT_NEEDED: to indicate that only the set of geometry types
    8342             :  * matter, not the number of features per geometry type. Consequently the value
    8343             :  * of OGRGeometryTypeCounter::nCount should be ignored.</li>
    8344             :  * <li>OGR_GGT_STOP_IF_MIXED: to indicate that the implementation may stop
    8345             :  * iterating over features as soon as 2 different geometry types (not counting
    8346             :  * null geometries) are found. The value of OGRGeometryTypeCounter::nCount
    8347             :  * should be ignored (zero might be systematically reported by some
    8348             :  * implementations).</li> <li>OGR_GGT_GEOMCOLLECTIONZ_TINZ: to indicate that if
    8349             :  * a geometry is of type wkbGeometryCollection25D and its first sub-geometry is
    8350             :  * of type wkbTINZ, wkbTINZ should be reported as geometry type. This is mostly
    8351             :  * useful for the ESRI Shapefile and (Open)FileGDB drivers regarding MultiPatch
    8352             :  * geometries.</li>
    8353             :  * </ul>
    8354             :  *
    8355             :  * If the layer has no features, a non-NULL returned array with nEntryCount == 0
    8356             :  * will be returned.
    8357             :  *
    8358             :  * Spatial and/or attribute filters will be taken into account.
    8359             :  *
    8360             :  * This method will error out on a layer without geometry fields
    8361             :  * (GetGeomType() == wkbNone).
    8362             :  *
    8363             :  * A cancellation callback may be provided. The progress percentage it is called
    8364             :  * with is not relevant. The callback should return TRUE if processing should go
    8365             :  * on, or FALSE if it should be interrupted.
    8366             :  *
    8367             :  * @param iGeomField Geometry field index.
    8368             :  * @param nFlagsGGT Hint flags. 0, or combination of OGR_GGT_COUNT_NOT_NEEDED,
    8369             :  *                  OGR_GGT_STOP_IF_MIXED, OGR_GGT_GEOMCOLLECTIONZ_TINZ
    8370             :  * @param[out] nEntryCountOut Number of entries in the returned array.
    8371             :  * @param pfnProgress Cancellation callback. May be NULL.
    8372             :  * @param pProgressData User data for the cancellation callback. May be NULL.
    8373             :  * @return an array of nEntryCount that must be freed with CPLFree(),
    8374             :  *         or NULL in case of error
    8375             :  * @since GDAL 3.6
    8376             :  */
    8377             : OGRGeometryTypeCounter *
    8378          12 : OGRLayer::GetGeometryTypes(int iGeomField, int nFlagsGGT, int &nEntryCountOut,
    8379             :                            GDALProgressFunc pfnProgress, void *pProgressData)
    8380             : {
    8381          12 :     OGRFeatureDefn *poDefn = GetLayerDefn();
    8382          12 :     const int nGeomFieldCount = poDefn->GetGeomFieldCount();
    8383          12 :     if (iGeomField < 0 || iGeomField >= nGeomFieldCount)
    8384             :     {
    8385           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid value for iGeomField");
    8386           1 :         nEntryCountOut = 0;
    8387           1 :         return nullptr;
    8388             :     }
    8389             : 
    8390             :     // Ignore all fields but the geometry one of interest
    8391          22 :     CPLStringList aosIgnoredFieldsRestore;
    8392          22 :     CPLStringList aosIgnoredFields;
    8393          11 :     const int nFieldCount = poDefn->GetFieldCount();
    8394          33 :     for (int iField = 0; iField < nFieldCount; iField++)
    8395             :     {
    8396          22 :         const auto poFieldDefn = poDefn->GetFieldDefn(iField);
    8397          22 :         const char *pszName = poFieldDefn->GetNameRef();
    8398          22 :         if (poFieldDefn->IsIgnored())
    8399          10 :             aosIgnoredFieldsRestore.AddString(pszName);
    8400          22 :         if (iField != iGeomField)
    8401          11 :             aosIgnoredFields.AddString(pszName);
    8402             :     }
    8403          33 :     for (int iField = 0; iField < nGeomFieldCount; iField++)
    8404             :     {
    8405          22 :         const auto poFieldDefn = poDefn->GetGeomFieldDefn(iField);
    8406          22 :         const char *pszName = poFieldDefn->GetNameRef();
    8407          22 :         if (poFieldDefn->IsIgnored())
    8408          10 :             aosIgnoredFieldsRestore.AddString(pszName);
    8409          22 :         if (iField != iGeomField)
    8410          11 :             aosIgnoredFields.AddString(pszName);
    8411             :     }
    8412          11 :     if (poDefn->IsStyleIgnored())
    8413           0 :         aosIgnoredFieldsRestore.AddString("OGR_STYLE");
    8414          11 :     aosIgnoredFields.AddString("OGR_STYLE");
    8415          11 :     SetIgnoredFields(aosIgnoredFields.List());
    8416             : 
    8417             :     // Iterate over features
    8418          22 :     std::map<OGRwkbGeometryType, int64_t> oMapCount;
    8419          22 :     std::set<OGRwkbGeometryType> oSetNotNull;
    8420          11 :     const bool bGeomCollectionZTInZ =
    8421          11 :         (nFlagsGGT & OGR_GGT_GEOMCOLLECTIONZ_TINZ) != 0;
    8422          11 :     const bool bStopIfMixed = (nFlagsGGT & OGR_GGT_STOP_IF_MIXED) != 0;
    8423          11 :     if (pfnProgress == GDALDummyProgress)
    8424           0 :         pfnProgress = nullptr;
    8425          11 :     bool bInterrupted = false;
    8426          47 :     for (auto &&poFeature : *this)
    8427             :     {
    8428          36 :         const auto poGeom = poFeature->GetGeomFieldRef(iGeomField);
    8429          36 :         if (poGeom == nullptr)
    8430             :         {
    8431          18 :             ++oMapCount[wkbNone];
    8432             :         }
    8433             :         else
    8434             :         {
    8435          18 :             auto eGeomType = poGeom->getGeometryType();
    8436          18 :             if (bGeomCollectionZTInZ && eGeomType == wkbGeometryCollection25D)
    8437             :             {
    8438           1 :                 const auto poGC = poGeom->toGeometryCollection();
    8439           1 :                 if (poGC->getNumGeometries() > 0)
    8440             :                 {
    8441             :                     auto eSubGeomType =
    8442           1 :                         poGC->getGeometryRef(0)->getGeometryType();
    8443           1 :                     if (eSubGeomType == wkbTINZ)
    8444           1 :                         eGeomType = wkbTINZ;
    8445             :                 }
    8446             :             }
    8447          18 :             ++oMapCount[eGeomType];
    8448          18 :             if (bStopIfMixed)
    8449             :             {
    8450           4 :                 oSetNotNull.insert(eGeomType);
    8451           4 :                 if (oSetNotNull.size() == 2)
    8452           2 :                     break;
    8453             :             }
    8454             :         }
    8455          34 :         if (pfnProgress && !pfnProgress(0.0, "", pProgressData))
    8456             :         {
    8457           1 :             bInterrupted = true;
    8458           1 :             break;
    8459             :         }
    8460             :     }
    8461             : 
    8462             :     // Restore ignore fields state
    8463          11 :     SetIgnoredFields(aosIgnoredFieldsRestore.List());
    8464             : 
    8465          11 :     if (bInterrupted)
    8466             :     {
    8467           1 :         nEntryCountOut = 0;
    8468           1 :         return nullptr;
    8469             :     }
    8470             : 
    8471             :     // Format result
    8472          10 :     nEntryCountOut = static_cast<int>(oMapCount.size());
    8473             :     OGRGeometryTypeCounter *pasRet = static_cast<OGRGeometryTypeCounter *>(
    8474          10 :         CPLCalloc(1 + nEntryCountOut, sizeof(OGRGeometryTypeCounter)));
    8475          10 :     int i = 0;
    8476          37 :     for (const auto &oIter : oMapCount)
    8477             :     {
    8478          27 :         pasRet[i].eGeomType = oIter.first;
    8479          27 :         pasRet[i].nCount = oIter.second;
    8480          27 :         ++i;
    8481             :     }
    8482          10 :     return pasRet;
    8483             : }
    8484             : 
    8485             : /************************************************************************/
    8486             : /*                       OGR_L_GetGeometryTypes()                       */
    8487             : /************************************************************************/
    8488             : 
    8489             : /** \brief Get actual geometry types found in features.
    8490             :  *
    8491             :  * See OGRLayer::GetGeometryTypes() for details.
    8492             :  *
    8493             :  * @param hLayer Layer.
    8494             :  * @param iGeomField Geometry field index.
    8495             :  * @param nFlags Hint flags. 0, or combination of OGR_GGT_COUNT_NOT_NEEDED,
    8496             :  *               OGR_GGT_STOP_IF_MIXED, OGR_GGT_GEOMCOLLECTIONZ_TINZ
    8497             :  * @param[out] pnEntryCount Pointer to the number of entries in the returned
    8498             :  *                          array. Must not be NULL.
    8499             :  * @param pfnProgress Cancellation callback. May be NULL.
    8500             :  * @param pProgressData User data for the cancellation callback. May be NULL.
    8501             :  * @return an array of *pnEntryCount that must be freed with CPLFree(),
    8502             :  *         or NULL in case of error
    8503             :  * @since GDAL 3.6
    8504             :  */
    8505          54 : OGRGeometryTypeCounter *OGR_L_GetGeometryTypes(OGRLayerH hLayer, int iGeomField,
    8506             :                                                int nFlags, int *pnEntryCount,
    8507             :                                                GDALProgressFunc pfnProgress,
    8508             :                                                void *pProgressData)
    8509             : {
    8510          54 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetGeometryTypes", nullptr);
    8511          54 :     VALIDATE_POINTER1(pnEntryCount, "OGR_L_GetGeometryTypes", nullptr);
    8512             : 
    8513         108 :     return OGRLayer::FromHandle(hLayer)->GetGeometryTypes(
    8514          54 :         iGeomField, nFlags, *pnEntryCount, pfnProgress, pProgressData);
    8515             : }
    8516             : 
    8517             : /************************************************************************/
    8518             : /*                   OGRLayer::GetSupportedSRSList()                    */
    8519             : /************************************************************************/
    8520             : 
    8521             : /** \brief Get the list of SRS supported.
    8522             :  *
    8523             :  * The base implementation of this method will return an empty list. Some
    8524             :  * drivers (OAPIF, WFS) may return a non-empty list.
    8525             :  *
    8526             :  * One of the SRS returned may be passed to SetActiveSRS() to change the
    8527             :  * active SRS.
    8528             :  *
    8529             :  * @param iGeomField Geometry field index.
    8530             :  * @return list of supported SRS.
    8531             :  * @since GDAL 3.7
    8532             :  */
    8533             : const OGRLayer::GetSupportedSRSListRetType &
    8534         212 : OGRLayer::GetSupportedSRSList(CPL_UNUSED int iGeomField)
    8535             : {
    8536         212 :     static OGRLayer::GetSupportedSRSListRetType empty;
    8537         212 :     return empty;
    8538             : }
    8539             : 
    8540             : /************************************************************************/
    8541             : /*                     OGR_L_GetSupportedSRSList()                      */
    8542             : /************************************************************************/
    8543             : 
    8544             : /** \brief Get the list of SRS supported.
    8545             :  *
    8546             :  * The base implementation of this method will return an empty list. Some
    8547             :  * drivers (OAPIF, WFS) may return a non-empty list.
    8548             :  *
    8549             :  * One of the SRS returned may be passed to SetActiveSRS() to change the
    8550             :  * active SRS.
    8551             :  *
    8552             :  * @param hLayer Layer.
    8553             :  * @param iGeomField Geometry field index.
    8554             :  * @param[out] pnCount Number of values in returned array. Must not be null.
    8555             :  * @return list of supported SRS, to be freed with OSRFreeSRSArray(), or
    8556             :  * nullptr
    8557             :  * @since GDAL 3.7
    8558             :  */
    8559           4 : OGRSpatialReferenceH *OGR_L_GetSupportedSRSList(OGRLayerH hLayer,
    8560             :                                                 int iGeomField, int *pnCount)
    8561             : {
    8562           4 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetSupportedSRSList", nullptr);
    8563           4 :     VALIDATE_POINTER1(pnCount, "OGR_L_GetSupportedSRSList", nullptr);
    8564             : 
    8565             :     const auto &srsList =
    8566           4 :         OGRLayer::FromHandle(hLayer)->GetSupportedSRSList(iGeomField);
    8567           4 :     *pnCount = static_cast<int>(srsList.size());
    8568           4 :     if (srsList.empty())
    8569             :     {
    8570           2 :         return nullptr;
    8571             :     }
    8572             :     OGRSpatialReferenceH *pahRet = static_cast<OGRSpatialReferenceH *>(
    8573           2 :         CPLMalloc((1 + srsList.size()) * sizeof(OGRSpatialReferenceH)));
    8574           2 :     size_t i = 0;
    8575           7 :     for (const auto &poSRS : srsList)
    8576             :     {
    8577           5 :         poSRS->Reference();
    8578           5 :         pahRet[i] = OGRSpatialReference::ToHandle(poSRS.get());
    8579           5 :         ++i;
    8580             :     }
    8581           2 :     pahRet[i] = nullptr;
    8582           2 :     return pahRet;
    8583             : }
    8584             : 
    8585             : /************************************************************************/
    8586             : /*                       OGRLayer::SetActiveSRS()                       */
    8587             : /************************************************************************/
    8588             : 
    8589             : /** \brief Change the active SRS.
    8590             :  *
    8591             :  * The passed SRS must be in the list returned by GetSupportedSRSList()
    8592             :  * (the actual pointer may be different, but should be tested as identical
    8593             :  * with OGRSpatialReference::IsSame()).
    8594             :  *
    8595             :  * Changing the active SRS affects:
    8596             :  * <ul>
    8597             :  * <li>the SRS in which geometries of returned features are expressed,</li>
    8598             :  * <li>the SRS in which geometries of passed features (CreateFeature(),
    8599             :  * SetFeature()) are expressed,</li>
    8600             :  * <li>the SRS returned by GetSpatialRef() and
    8601             :  * GetGeomFieldDefn()->GetSpatialRef(),</li>
    8602             :  * <li>the SRS used to interpret SetSpatialFilter() values.</li>
    8603             :  * </ul>
    8604             :  * This also resets feature reading and the spatial filter.
    8605             :  * Note however that this does not modify the storage SRS of the features of
    8606             :  * geometries. Said otherwise, this setting is volatile and has no persistent
    8607             :  * effects after dataset reopening.
    8608             :  *
    8609             :  * @param iGeomField Geometry field index.
    8610             :  * @param poSRS SRS to use
    8611             :  * @return OGRERR_NONE in case of success, or OGRERR_FAILURE if
    8612             :  *         the passed SRS is not in GetSupportedSRSList()
    8613             :  * @since GDAL 3.7
    8614             :  */
    8615           1 : OGRErr OGRLayer::SetActiveSRS(CPL_UNUSED int iGeomField,
    8616             :                               CPL_UNUSED const OGRSpatialReference *poSRS)
    8617             : {
    8618           1 :     return OGRERR_FAILURE;
    8619             : }
    8620             : 
    8621             : /************************************************************************/
    8622             : /*                         OGR_L_SetActiveSRS()                         */
    8623             : /************************************************************************/
    8624             : 
    8625             : /** \brief Change the active SRS.
    8626             :  *
    8627             :  * The passed SRS must be in the list returned by GetSupportedSRSList()
    8628             :  * (the actual pointer may be different, but should be tested as identical
    8629             :  * with OGRSpatialReference::IsSame()).
    8630             :  *
    8631             :  * Changing the active SRS affects:
    8632             :  * <ul>
    8633             :  * <li>the SRS in which geometries of returned features are expressed,</li>
    8634             :  * <li>the SRS in which geometries of passed features (CreateFeature(),
    8635             :  * SetFeature()) are expressed,</li>
    8636             :  * <li>the SRS returned by GetSpatialRef() and
    8637             :  * GetGeomFieldDefn()->GetSpatialRef(),</li>
    8638             :  * <li>the SRS used to interpret SetSpatialFilter() values.</li>
    8639             :  * </ul>
    8640             :  * This also resets feature reading and the spatial filter.
    8641             :  * Note however that this does not modify the storage SRS of the features of
    8642             :  * geometries. Said otherwise, this setting is volatile and has no persistent
    8643             :  * effects after dataset reopening.
    8644             :  *
    8645             :  * @param hLayer Layer.
    8646             :  * @param iGeomField Geometry field index.
    8647             :  * @param hSRS SRS to use
    8648             :  * @return OGRERR_NONE in case of success, OGRERR_FAILURE if
    8649             :  *         the passed SRS is not in GetSupportedSRSList().
    8650             :  * @since GDAL 3.7
    8651             :  */
    8652           9 : OGRErr OGR_L_SetActiveSRS(OGRLayerH hLayer, int iGeomField,
    8653             :                           OGRSpatialReferenceH hSRS)
    8654             : {
    8655           9 :     VALIDATE_POINTER1(hLayer, "OGR_L_SetActiveSRS", OGRERR_FAILURE);
    8656          18 :     return OGRLayer::FromHandle(hLayer)->SetActiveSRS(
    8657           9 :         iGeomField, OGRSpatialReference::FromHandle(hSRS));
    8658             : }
    8659             : 
    8660             : /************************************************************************/
    8661             : /*                             GetDataset()                             */
    8662             : /************************************************************************/
    8663             : 
    8664             : /** Return the dataset associated with this layer.
    8665             :  *
    8666             :  * As of GDAL 3.9, GetDataset() is implemented on all in-tree drivers that
    8667             :  * have CreateLayer() capability. It may not be implemented in read-only
    8668             :  * drivers or out-of-tree drivers.
    8669             :  *
    8670             :  * It is currently only used by the GetRecordBatchSchema()
    8671             :  * method to retrieve the field domain associated with a field, to fill the
    8672             :  * dictionary field of a struct ArrowSchema.
    8673             :  * It is also used by CreateFieldFromArrowSchema() to determine which field
    8674             :  * types and subtypes are supported by the layer, by inspecting the driver
    8675             :  * metadata, and potentially use fallback types when needed.
    8676             :  *
    8677             :  * This method is the same as the C function OGR_L_GetDataset().
    8678             :  *
    8679             :  * @return dataset, or nullptr when unknown.
    8680             :  * @since GDAL 3.6
    8681             :  */
    8682          25 : GDALDataset *OGRLayer::GetDataset()
    8683             : {
    8684          25 :     return nullptr;
    8685             : }
    8686             : 
    8687             : /************************************************************************/
    8688             : /*                          OGR_L_GetDataset()                          */
    8689             : /************************************************************************/
    8690             : 
    8691             : /** Return the dataset associated with this layer.
    8692             :  *
    8693             :  * As of GDAL 3.9, GetDataset() is implemented on all in-tree drivers that
    8694             :  * have CreateLayer() capability. It may not be implemented in read-only
    8695             :  * drivers or out-of-tree drivers.
    8696             :  *
    8697             :  * It is currently only used by the GetRecordBatchSchema()
    8698             :  * method to retrieve the field domain associated with a field, to fill the
    8699             :  * dictionary field of a struct ArrowSchema.
    8700             :  * It is also used by CreateFieldFromArrowSchema() to determine which field
    8701             :  * types and subtypes are supported by the layer, by inspecting the driver
    8702             :  * metadata, and potentially use fallback types when needed.
    8703             :  *
    8704             :  * This function is the same as the C++ method OGRLayer::GetDataset().
    8705             :  *
    8706             :  * @return dataset, or nullptr when unknown.
    8707             :  * @since GDAL 3.9
    8708             :  */
    8709         264 : GDALDatasetH OGR_L_GetDataset(OGRLayerH hLayer)
    8710             : {
    8711         264 :     VALIDATE_POINTER1(hLayer, "OGR_L_GetDataset", nullptr);
    8712         264 :     return GDALDataset::ToHandle(OGRLayer::FromHandle(hLayer)->GetDataset());
    8713             : }

Generated by: LCOV version 1.14