# GDALDataset C++ API

## Include files

- gdal_dataset.h

- gdal_openinfo.h

- gdal_geotransform.h

- gdal_relationship.h

## GDALDataset class

class GDALDataset : public GDALMajorObject

  A set of associated raster bands, usually from one file.

  A dataset encapsulating one or more raster bands.

  Details are further discussed in the GDAL Raster Data Model.

  Use GDALOpen() or GDALOpenShared() to create a GDALDataset for a named file, or GDALDriver::Create() or GDALDriver::CreateCopy() to create a new dataset.

  Subclassed by GDALApplyVSGDataset, GDALColorReliefDataset, GDALComputedDataset, GDALGeneric3x3Dataset< T >, GDALOverviewDataset, GDALPamDataset, GDALVectorTranslateWrappedDataset, GNMNetwork, OGRDataSource, PythonPluginDataset

  Public Functions

  ~GDALDataset() override

    Destroy an open GDALDataset.

    This is the accepted method of closing a GDAL dataset and deallocating all resources associated with it.

    Equivalent of the C callable GDALClose(). Except that GDALClose() first decrements the reference count, and then closes only if it has dropped to zero.

    For Windows users, it is not recommended to use the delete operator on the dataset object because of known issues when allocating and freeing memory across module boundaries. Calling GDALClose() is then a better option.

  virtual CPLErr Close()

    Do final cleanup before a dataset is destroyed.

    This method is typically called by GDALClose() or the destructor of a GDALDataset subclass. It might also be called by C++ users before destroying a dataset. It should not be called on a shared dataset whose reference count is greater than one.

    It gives a last chance to the closing process to return an error code if something goes wrong, in particular in creation / update scenarios where file write or network communication might occur when finalizing the dataset.

    Implementations should be robust to this method to be called several times (on subsequent calls, it should do nothing and return CE_None). Once it has been called, no other method than Close() or the dataset destructor should be called. RasterBand or OGRLayer owned by the dataset should be assumed as no longer being valid.

    If a driver implements this method, it must also call it from its dataset destructor.

    This is the equivalent of C function GDALDatasetRunCloseWithoutDestroying().

    A typical implementation might look as the following

        MyDataset::~MyDataset()
        {
           try
           {
               MyDataset::Close();
           }
           catch (const std::exception &exc)
           {
               // If Close() can throw exception
               CPLError(CE_Failure, CPLE_AppDefined,
                        "Exception thrown in MyDataset::Close(): %s",
                        exc.what());
           }
           catch (...)
           {
               // If Close() can throw exception
               CPLError(CE_Failure, CPLE_AppDefined,
                        "Exception thrown in MyDataset::Close()");
           }
        }

        CPLErr MyDataset::Close()
        {
            CPLErr eErr = CE_None;
            if( nOpenFlags != OPEN_FLAGS_CLOSED )
            {
                eErr = MyDataset::FlushCache(true);

                // Do something driver specific
                if (m_fpImage)
                {
                    if( VSIFCloseL(m_fpImage) != 0 )
                    {
                        CPLError(CE_Failure, CPLE_FileIO, "VSIFCloseL() failed");
                        eErr = CE_Failure;
                    }
                }

                // Call parent Close() implementation.
                eErr = GDAL::Combine(eErr, MyParentDatasetClass::Close());
            }
            return eErr;
        }

    Since

      GDAL 3.7

  int GetRasterXSize() const

    Fetch raster width in pixels.

    Equivalent of the C function GDALGetRasterXSize().

    Returns:

      the width in pixels of raster bands in this GDALDataset.

  int GetRasterYSize() const

    Fetch raster height in pixels.

    Equivalent of the C function GDALGetRasterYSize().

    Returns:

      the height in pixels of raster bands in this GDALDataset.

  int GetRasterCount() const

    Fetch the number of raster bands on this dataset.

    Same as the C function GDALGetRasterCount().

    Returns:

      the number of raster bands.

  GDALRasterBand *GetRasterBand(int)

    Fetch a band object for a dataset.

    See GetBands() for a C++ iterator version of this method.

    Equivalent of the C function GDALGetRasterBand().

    Parameters:

      nBandId -- the index number of the band to fetch, from 1 to GetRasterCount().

    Returns:

      the nBandId th band object

  const GDALRasterBand *GetRasterBand(int) const

    Fetch a band object for a dataset.

    See GetBands() for a C++ iterator version of this method.

    Equivalent of the C function GDALGetRasterBand().

    Parameters:

      nBandId -- the index number of the band to fetch, from 1 to GetRasterCount().

    Returns:

      the nBandId th band object

  virtual bool SetQueryLoggerFunc(GDALQueryLoggerFunc pfnQueryLoggerFuncIn, void *poQueryLoggerArgIn)

    SetQueryLoggerFunc.

    Parameters:

      - pfnQueryLoggerFuncIn -- query logger function callback

      - poQueryLoggerArgIn -- arguments passed to the query logger function

    Returns:

      true on success

  Bands GetBands()

    Function that returns an iterable object over GDALRasterBand in the dataset.

    This is a C++ iterator friendly version of GetRasterBand().

    Typical use is:

        for( auto&& poBand: poDS->GetBands() )
        {
              std::cout << "Band  << poBand->GetDescription() << std::endl;
        }

    See also

    GetRasterBand()

  ConstBands GetBands() const

    Function that returns an iterable object over GDALRasterBand in the dataset.

    This is a C++ iterator friendly version of GetRasterBand().

    Typical use is:

        for( const auto* poBand: poDS->GetConstBands() )
        {
              std::cout << "Band  << poBand->GetDescription() << std::endl;
        }

    See also

    GetRasterBand()

    Since

      GDAL 3.12

  virtual CPLErr FlushCache(bool bAtClosing = false)

    Flush all write cached data to disk.

    Any raster (or other GDAL) data written via GDAL calls, but buffered internally will be written to disk.

    The default implementation of this method just calls the FlushCache() method on each of the raster bands and the SyncToDisk() method on each of the layers. Conceptually, calling FlushCache() on a dataset should include any work that might be accomplished by calling SyncToDisk() on layers in that dataset.

    Using this method does not prevent use from calling GDALClose() to properly close a dataset and ensure that important data not addressed by FlushCache() is written in the file.

    This method is the same as the C function GDALFlushCache().

    Parameters:

      bAtClosing -- Whether this is called from a GDALDataset destructor

    Returns:

      CE_None in case of success (note: return value added in GDAL 3.7)

  virtual CPLErr DropCache()

    Drop all write cached data.

    This method is the same as the C function GDALDropCache().

    Since

      3.9

    Returns:

      CE_None in case of success

  virtual GIntBig GetEstimatedRAMUsage()

    Return the intrinsic RAM usage of this dataset.

    The returned value should take into account caches in the underlying driver and decoding library, but not the usage related to the GDAL block cache.

    At time of writing, this method is only implemented in the JP2OpenJPEG driver. For single-tiled JPEG2000 images, the decoding of the image, even partially, involves allocating at least width * height * number_of_bands * sizeof(uint32_t) bytes inside the libopenjp2 library.

    This method is used by the GDALDatasetPool class, itself used by the GDAL VRT driver, to determine how long a dataset in the pool must be kept open, given the RAM usage of the dataset with respect to the usable total RAM.

    Since

      GDAL 3.7

    Returns:

      RAM usage in bytes, or -1 if unknown (the default implementation returns -1)

  virtual const OGRSpatialReference *GetSpatialRef() const

    Fetch the spatial reference for this dataset.

    Same as the C function GDALGetSpatialRef().

    When a projection definition is not available, null is returned. If used on a dataset where there are GCPs and not a geotransform, this method returns null. Use GetGCPSpatialRef() instead.

    Since GDAL 3.12, the default implementation of this method will iterate over vector layers and return their SRS if all geometry columns of all layers use the same SRS, or nullptr otherwise.

    See also

    https://gdal.org/tutorials/osr_api_tut.html

    Since

      GDAL 3.0

    Returns:

      a pointer to an internal object. It should not be altered or freed. Its lifetime will be the one of the dataset object.

  virtual CPLErr SetSpatialRef(const OGRSpatialReference *poSRS)

    Set the spatial reference system for this dataset.

    An error may occur because the dataset is not writable, or because the dataset does not support the indicated projection. Many formats do not support writing projections.

    This method is the same as the C GDALSetSpatialRef() function.

    Since

      GDAL 3.0

    Parameters:

      poSRS -- spatial reference system object. nullptr can potentially be passed for drivers that support unsetting the SRS.

    Returns:

      CE_Failure if an error occurs, otherwise CE_None.

  virtual const OGRSpatialReference *GetSpatialRefRasterOnly() const

    Fetch the spatial reference for this dataset (ignoring vector layers)

    Since

      GDAL 3.12

    Returns:

      a pointer to an internal object. It should not be altered or freed. Its lifetime will be the one of the dataset object.

  virtual const OGRSpatialReference *GetSpatialRefVectorOnly() const

    Fetch the spatial reference for this dataset (only for vector layers)

    The default implementation of this method will iterate over vector layers and return their SRS if all geometry columns of all layers use the same SRS, or nullptr otherwise.

    Since

      GDAL 3.12

    Returns:

      a pointer to an internal object. It should not be altered or freed. Its lifetime will be the one of the dataset object.

  const char *GetProjectionRef(void) const

    Fetch the projection definition string for this dataset.

    Same as the C function GDALGetProjectionRef().

    The returned string defines the projection coordinate system of the image in OpenGIS WKT format. It should be suitable for use with the OGRSpatialReference class.

    When a projection definition is not available an empty (but not NULL) string is returned.

    See also

    https://gdal.org/tutorials/osr_api_tut.html

    Note

    Starting with GDAL 3.0, this is a compatibility layer around GetSpatialRef()

    Returns:

      a pointer to an internal projection reference string. It should not be altered, freed or expected to last for long.

  CPLErr SetProjection(const char *pszProjection)

    Set the projection reference string for this dataset.

    The string should be in OGC WKT or PROJ.4 format. An error may occur because of incorrectly specified projection strings, because the dataset is not writable, or because the dataset does not support the indicated projection. Many formats do not support writing projections.

    This method is the same as the C GDALSetProjection() function.

    Note

    Startig with GDAL 3.0, this is a compatibility layer around SetSpatialRef()

    Parameters:

      pszProjection -- projection reference string.

    Returns:

      CE_Failure if an error occurs, otherwise CE_None.

  virtual CPLErr GetGeoTransform(GDALGeoTransform &gt) const

    Fetch the affine transformation coefficients.

    Fetches the coefficients for transforming between pixel/line (P,L) raster space, and projection coordinates (Xp,Yp) space.

        Xp = gt[0] + P*gt[1] + L*gt[2];
        Yp = gt[3] + P*padfTransform[4] + L*gt[5];

    In a north up image, gt[1] is the pixel width, and gt[5] is the pixel height. The upper left corner of the upper left pixel is at position (gt[0],gt[3]).

    The default transform is (0,1,0,0,0,1) and should be returned even when a CE_Failure error is returned, such as for formats that don't support transformation to projection coordinates.

    This method does the same thing as the C GDALGetGeoTransform() function.

    Since

      3.12

    Parameters:

      gt -- an existing six double buffer into which the transformation will be placed.

    Returns:

      CE_None on success, or CE_Failure if no transform can be fetched.

  virtual CPLErr SetGeoTransform(const GDALGeoTransform &gt)

    Set the affine transformation coefficients.

    See GetGeoTransform() for details on the meaning of the padfTransform coefficients.

    This method does the same thing as the C GDALSetGeoTransform() function.

    Since

      3.12

    Parameters:

      gt -- the transformation coefficients to be written with the dataset.

    Returns:

      CE_None on success, or CE_Failure if this transform cannot be written.

  CPLErr GetGeoTransform(double *padfGeoTransform) const

    Fetch the affine transformation coefficients.

    Fetches the coefficients for transforming between pixel/line (P,L) raster space, and projection coordinates (Xp,Yp) space.

        Xp = padfTransform[0] + P*padfTransform[1] + L*padfTransform[2];
        Yp = padfTransform[3] + P*padfTransform[4] + L*padfTransform[5];

    In a north up image, padfTransform[1] is the pixel width, and padfTransform[5] is the pixel height. The upper left corner of the upper left pixel is at position (padfTransform[0],padfTransform[3]).

    The default transform is (0,1,0,0,0,1) and should be returned even when a CE_Failure error is returned, such as for formats that don't support transformation to projection coordinates.

    This method does the same thing as the C GDALGetGeoTransform() function.

    Deprecated:

      since 3.12. Use GetGeoTransform(GDALGeoTransform&) instead

    Parameters:

      padfTransform -- an existing six double buffer into which the transformation will be placed.

    Returns:

      CE_None on success, or CE_Failure if no transform can be fetched.

  CPLErr SetGeoTransform(const double *padfGeoTransform)

    Set the affine transformation coefficients.

    See GetGeoTransform() for details on the meaning of the padfTransform coefficients.

    This method does the same thing as the C GDALSetGeoTransform() function.

    Deprecated:

      since 3.12. Use SetGeoTransform(const GDALGeoTransform&) instead

    Parameters:

      padfTransform -- a six double buffer containing the transformation coefficients to be written with the dataset.

    Returns:

      CE_None on success, or CE_Failure if this transform cannot be written.

  virtual CPLErr GetExtent(OGREnvelope *psExtent, const OGRSpatialReference *poCRS = nullptr) const

    Return extent of dataset in specified CRS.

    OGREnvelope.MinX/MaxX represents longitudes, and MinY/MaxY latitudes.

    For rasters, the base implementation of this method only succeeds if GetGeoTransform() and GetSpatialRef() succeed. For vectors, the base implementation of this method iterates over layers and call their OGRLayer::GetExtent() method.

    TestCapability(GDsCFastGetExtent) can be used to test if the execution time of this method is fast.

    This is the same as C function GDALGetExtent()

    Since

      GDAL 3.12

    Parameters:

      - psExtent -- [out] Pointer to output extent. Must NOT be null.

      - poCRS -- CRS in which to express the extent. If not specified, this will be the raster CRS or the CRS of the first layer for a vector dataset.

    Returns:

      CE_None in case of success, CE_Failure otherwise

  virtual CPLErr GetExtentWGS84LongLat(OGREnvelope *psExtent) const

    Return extent of dataset in WGS84 longitude/latitude.

    OGREnvelope.MinX/MaxX represents longitudes, and MinY/MaxY latitudes.

    TestCapability(GDsCFastGetExtentWGS84LongLat) can be used to test if the execution time of this method is fast.

    This is the same as C function GDALGetExtentWGS84LongLat()

    Since

      GDAL 3.12

    Returns:

      extent (valid only if IsInit() method returns true)

  CPLErr GeolocationToPixelLine(double dfGeolocX, double dfGeolocY, const OGRSpatialReference *poSRS, double *pdfPixel, double *pdfLine, CSLConstList papszTransformerOptions = nullptr) const

    Transform georeferenced coordinates to pixel/line coordinates.

    When poSRS is null, those georeferenced coordinates (dfGeolocX, dfGeolocY) must be in the "natural" SRS of the dataset, that is the one returned by GetSpatialRef() if there is a geotransform, GetGCPSpatialRef() if there are GCPs, WGS 84 if there are RPC coefficients, or the SRS of the geolocation array (generally WGS 84) if there is a geolocation array. If that natural SRS is a geographic one, dfGeolocX must be a longitude, and dfGeolocY a latitude. If that natural SRS is a projected one, dfGeolocX must be a easting, and dfGeolocY a northing.

    When poSRS is set to a non-null value, (dfGeolocX, dfGeolocY) must be expressed in that CRS, and that tuple must be conformant with the data-axis-to-crs-axis setting of poSRS, that is the one returned by the OGRSpatialReference::GetDataAxisToSRSAxisMapping(). If you want to be sure of the axis order, then make sure to call poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER) before calling this method, and in that case, dfGeolocX must be a longitude or an easting value, and dfGeolocX a latitude or a northing value.

    This method uses GDALCreateGenImgProjTransformer2() underneath.

    Since

      GDAL 3.11

    Parameters:

      - dfGeolocX -- X coordinate of the position (longitude or easting if poSRS is null, otherwise consistent with poSRS data-axis-to-crs-axis mapping), where interpolation should be done.

      - dfGeolocY -- Y coordinate of the position (latitude or northing if poSRS is null, otherwise consistent with poSRS data-axis-to-crs-axis mapping), where interpolation should be done.

      - poSRS -- If set, override the natural CRS in which dfGeolocX, dfGeolocY are expressed

      - pdfPixel -- [out] Pointer to the variable where to the store the pixel/column coordinate.

      - pdfLine -- [out] Pointer to the variable where to the store the line coordinate.

      - papszTransformerOptions -- Options accepted by GDALCreateGenImgProjTransformer2(), or nullptr.

    Returns:

      CE_None on success, or an error code on failure.

  virtual CPLErr AddBand(GDALDataType eType, char **papszOptions = nullptr)

    Add a band to a dataset.

    This method will add a new band to the dataset if the underlying format supports this action. Most formats do not.

    Note that the new GDALRasterBand is not returned. It may be fetched after successful completion of the method by calling GDALDataset::GetRasterBand(GDALDataset::GetRasterCount()) as the newest band will always be the last band.

    Parameters:

      - eType -- the data type of the pixels in the new band.

      - papszOptions -- a list of NAME=VALUE option strings. The supported options are format specific. NULL may be passed by default.

    Returns:

      CE_None on success or CE_Failure on failure.

  virtual void *GetInternalHandle(const char *pszHandleName)

    Fetch a format specific internally meaningful handle.

    This method is the same as the C GDALGetInternalHandle() method.

    Parameters:

      pszHandleName -- the handle name desired. The meaningful names will be specific to the file format.

    Returns:

      the desired handle value, or NULL if not recognized/supported.

  virtual GDALDriver *GetDriver(void)

    Fetch the driver to which this dataset relates.

    This method is the same as the C GDALGetDatasetDriver() function.

    Returns:

      the driver on which the dataset was created with GDALOpen() or GDALCreate().

  virtual char **GetFileList(void)

    Fetch files forming dataset.

    Returns a list of files believed to be part of this dataset. If it returns an empty list of files it means there is believed to be no local file system files associated with the dataset (for instance a virtual dataset). The returned file list is owned by the caller and should be deallocated with CSLDestroy().

    The returned filenames will normally be relative or absolute paths depending on the path used to originally open the dataset. The strings will be UTF-8 encoded.

    This method is the same as the C GDALGetFileList() function.

    Returns:

      NULL or a NULL terminated array of file names.

  const char *GetDriverName() const

    Return driver name.

    Returns:

      driver name.

  virtual const OGRSpatialReference *GetGCPSpatialRef() const

    Get output spatial reference system for GCPs.

    Same as the C function GDALGetGCPSpatialRef().

    When a SRS is not available, null is returned. If used on a dataset where there is a geotransform, and not GCPs, this method returns null. Use GetSpatialRef() instead.

    Since

      GDAL 3.0

    Returns:

      a pointer to an internal object. It should not be altered or freed. Its lifetime will be the one of the dataset object, or until the next call to this method.

  virtual int GetGCPCount()

    Get number of GCPs.

    This method is the same as the C function GDALGetGCPCount().

    Returns:

      number of GCPs for this dataset. Zero if there are none.

  virtual const GDAL_GCP *GetGCPs()

    Fetch GCPs.

    This method is the same as the C function GDALGetGCPs().

    Returns:

      pointer to internal GCP structure list. It should not be modified, and may change on the next GDAL call.

  virtual CPLErr SetGCPs(int nGCPCount, const GDAL_GCP *pasGCPList, const OGRSpatialReference *poGCP_SRS)

    Assign GCPs.

    This method is the same as the C function GDALSetGCPs().

    This method assigns the passed set of GCPs to this dataset, as well as setting their coordinate system. Internally copies are made of the coordinate system and list of points, so the caller remains responsible for deallocating these arguments if appropriate.

    Most formats do not support setting of GCPs, even formats that can handle GCPs. These formats will return CE_Failure.

    Since

      GDAL 3.0

    Parameters:

      - nGCPCount -- number of GCPs being assigned.

      - pasGCPList -- array of GCP structures being assign (nGCPCount in array).

      - poGCP_SRS -- the new coordinate reference system to assign for the GCP output coordinates. This parameter should be null if no output coordinate system is known.

    Returns:

      CE_None on success, CE_Failure on failure (including if action is not supported for this format).

  const char *GetGCPProjection() const

    Get output projection for GCPs.

    This method is the same as the C function GDALGetGCPProjection().

    The projection string follows the normal rules from GetProjectionRef().

    Note

    Starting with GDAL 3.0, this is a compatibility layer around GetGCPSpatialRef()

    Returns:

      internal projection string or "" if there are no GCPs. It should not be altered, freed or expected to last for long.

  CPLErr SetGCPs(int nGCPCount, const GDAL_GCP *pasGCPList, const char *pszGCPProjection)

    Assign GCPs.

    This method is the same as the C function GDALSetGCPs().

    This method assigns the passed set of GCPs to this dataset, as well as setting their coordinate system. Internally copies are made of the coordinate system and list of points, so the caller remains responsible for deallocating these arguments if appropriate.

    Most formats do not support setting of GCPs, even formats that can handle GCPs. These formats will return CE_Failure.

    Note

    Startig with GDAL 3.0, this is a compatibility layer around SetGCPs(int, const GDAL_GCP*, const char*)

    Parameters:

      - nGCPCount -- number of GCPs being assigned.

      - pasGCPList -- array of GCP structures being assign (nGCPCount in array).

      - pszGCPProjection -- the new OGC WKT coordinate system to assign for the GCP output coordinates. This parameter should be "" if no output coordinate system is known.

    Returns:

      CE_None on success, CE_Failure on failure (including if action is not supported for this format).

  virtual CPLErr AdviseRead(int nXOff, int nYOff, int nXSize, int nYSize, int nBufXSize, int nBufYSize, GDALDataType eDT, int nBandCount, int *panBandList, char **papszOptions)

    Advise driver of upcoming read requests.

    Some GDAL drivers operate more efficiently if they know in advance what set of upcoming read requests will be made. The AdviseRead() method allows an application to notify the driver of the region and bands of interest, and at what resolution the region will be read.

    Many drivers just ignore the AdviseRead() call, but it can dramatically accelerate access via some drivers.

    Depending on call paths, drivers might receive several calls to AdviseRead() with the same parameters.

    Parameters:

      - nXOff -- The pixel offset to the top left corner of the region of the band to be accessed. This would be zero to start from the left side.

      - nYOff -- The line offset to the top left corner of the region of the band to be accessed. This would be zero to start from the top.

      - nXSize -- The width of the region of the band to be accessed in pixels.

      - nYSize -- The height of the region of the band to be accessed in lines.

      - nBufXSize -- the width of the buffer image into which the desired region is to be read, or from which it is to be written.

      - nBufYSize -- the height of the buffer image into which the desired region is to be read, or from which it is to be written.

      - eBufType -- the type of the pixel values in the pData data buffer. The pixel values will automatically be translated to/from the GDALRasterBand data type as needed.

      - nBandCount -- the number of bands being read or written.

      - panBandMap -- the list of nBandCount band numbers being read/written. Note band numbers are 1 based. This may be NULL to select the first nBandCount bands.

      - papszOptions -- a list of name=value strings with special control options. Normally this is NULL.

    Returns:

      CE_Failure if the request is invalid and CE_None if it works or is ignored.

  virtual CPLErr CreateMaskBand(int nFlagsIn)

    Adds a mask band to the dataset.

    The default implementation of the CreateMaskBand() method is implemented based on similar rules to the .ovr handling implemented using the GDALDefaultOverviews object. A TIFF file with the extension .msk will be created with the same basename as the original file, and it will have one band. The mask images will be deflate compressed tiled images with the same block size as the original image if possible. It will have INTERNAL_MASK_FLAGS_xx metadata items set at the dataset level, where xx matches the band number of a band of the main dataset. The value of those items will be the one of the nFlagsIn parameter.

    Note that if you got a mask band with a previous call to GetMaskBand(), it might be invalidated by CreateMaskBand(). So you have to call GetMaskBand() again.

    See also

    https://gdal.org/development/rfc/rfc15_nodatabitmask.html

    See also

    GDALRasterBand::CreateMaskBand()

    Parameters:

      nFlagsIn -- 0 or combination of GMF_PER_DATASET / GMF_ALPHA. GMF_PER_DATASET will be always set, even if not explicitly specified.

    Returns:

      CE_None on success or CE_Failure on an error.

  virtual GDALAsyncReader *BeginAsyncReader(int nXOff, int nYOff, int nXSize, int nYSize, void *pBuf, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, int *panBandMap, int nPixelSpace, int nLineSpace, int nBandSpace, char **papszOptions)

    Sets up an asynchronous data request.

    This method establish an asynchronous raster read request for the indicated window on the dataset into the indicated buffer. The parameters for windowing, buffer size, buffer type and buffer organization are similar to those for GDALDataset::RasterIO(); however, this call only launches the request and filling the buffer is accomplished via calls to GetNextUpdatedRegion() on the return GDALAsyncReader session object.

    Once all processing for the created session is complete, or if no further refinement of the request is required, the GDALAsyncReader object should be destroyed with the GDALDataset::EndAsyncReader() method.

    Note that the data buffer (pData) will potentially continue to be updated as long as the session lives, but it is not deallocated when the session (GDALAsyncReader) is destroyed with EndAsyncReader(). It should be deallocated by the application at that point.

    Additional information on asynchronous IO in GDAL may be found at: https://gdal.org/development/rfc/rfc24_progressive_data_support.html

    This method is the same as the C GDALBeginAsyncReader() function.

    Parameters:

      - nXOff -- The pixel offset to the top left corner of the region of the band to be accessed. This would be zero to start from the left side.

      - nYOff -- The line offset to the top left corner of the region of the band to be accessed. This would be zero to start from the top.

      - nXSize -- The width of the region of the band to be accessed in pixels.

      - nYSize -- The height of the region of the band to be accessed in lines.

      - pBuf -- The buffer into which the data should be read. This buffer must contain at least nBufXSize * nBufYSize * nBandCount words of type eBufType. It is organized in left to right,top to bottom pixel order. Spacing is controlled by the nPixelSpace, and nLineSpace parameters.

      - nBufXSize -- the width of the buffer image into which the desired region is to be read, or from which it is to be written.

      - nBufYSize -- the height of the buffer image into which the desired region is to be read, or from which it is to be written.

      - eBufType -- the type of the pixel values in the pData data buffer. The pixel values will automatically be translated to/from the GDALRasterBand data type as needed.

      - nBandCount -- the number of bands being read or written.

      - panBandMap -- the list of nBandCount band numbers being read/written. Note band numbers are 1 based. This may be NULL to select the first nBandCount bands.

      - nPixelSpace -- The byte offset from the start of one pixel value in pData to the start of the next pixel value within a scanline. If defaulted (0) the size of the datatype eBufType is used.

      - nLineSpace -- The byte offset from the start of one scanline in pData to the start of the next. If defaulted the size of the datatype eBufType * nBufXSize is used.

      - nBandSpace -- the byte offset from the start of one bands data to the start of the next. If defaulted (zero) the value will be nLineSpace * nBufYSize implying band sequential organization of the data buffer.

      - papszOptions -- Driver specific control options in a string list or NULL. Consult driver documentation for options supported.

    Returns:

      The GDALAsyncReader object representing the request.

  virtual void EndAsyncReader(GDALAsyncReader *poARIO)

    End asynchronous request.

    This method destroys an asynchronous io request and recovers all resources associated with it.

    This method is the same as the C function GDALEndAsyncReader().

    Parameters:

      poARIO -- pointer to a GDALAsyncReader

  CPLErr RasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize, void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType, int nBandCount, const int *panBandMap, GSpacing nPixelSpace, GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg)

    Read/write a region of image data from multiple bands.

    This method allows reading a region of one or more GDALRasterBands from this dataset into a buffer, or writing data from a buffer into a region of the GDALRasterBands. It automatically takes care of data type translation if the data type (eBufType) of the buffer is different than that of the GDALRasterBand. The method also takes care of image decimation / replication if the buffer size (nBufXSize x nBufYSize) is different than the size of the region being accessed (nXSize x nYSize).

    The window of interest expressed by (nXOff, nYOff, nXSize, nYSize) should be fully within the raster space, that is nXOff >= 0, nYOff >= 0, nXOff + nXSize <= GetRasterXSize() and nYOff + nYSize <= GetRasterYSize(). If reads larger than the raster space are wished, GDALTranslate() might be used. Or use nLineSpace and a possibly shifted pData value.

    The nPixelSpace, nLineSpace and nBandSpace parameters allow reading into or writing from various organization of buffers.

    Some formats may efficiently implement decimation into a buffer by reading from lower resolution overview images. The logic of the default implementation in the base class GDALRasterBand is the following one. It computes a target_downscaling_factor from the window of interest and buffer size which is min(nXSize/nBufXSize, nYSize/nBufYSize). It then walks through overviews and will select the first one whose downscaling factor is greater than target_downscaling_factor / 1.2.

    Let's assume we have overviews at downscaling factors 2, 4 and 8. The relationship between target_downscaling_factor and the select overview level is the following one:

    target_downscaling_factor | selected_overview
    --- | ---
    ]0, 2 / 1.2] | full resolution band
    ]2 / 1.2, 4 / 1.2] | 2x downsampled band
    ]4 / 1.2, 8 / 1.2] | 4x downsampled band
    ]8 / 1.2, infinity[ | 8x downsampled band

    Note that starting with GDAL 3.9, this 1.2 oversampling factor can be modified by setting the GDAL_OVERVIEW_OVERSAMPLING_THRESHOLD configuration option. Also note that starting with GDAL 3.9, when the resampling algorithm specified in psExtraArg->eResampleAlg is different from GRIORA_NearestNeighbour, this oversampling threshold defaults to 1. Consequently if there are overviews of downscaling factor 2, 4 and 8, and the desired downscaling factor is 7.99, the overview of factor 4 will be selected for a non nearest resampling.

    For highest performance full resolution data access, read and write on "block boundaries" as returned by GetBlockSize(), or use the ReadBlock() and WriteBlock() methods.

    This method is the same as the C GDALDatasetRasterIO() or GDALDatasetRasterIOEx() functions.

    Parameters:

      - eRWFlag -- Either GF_Read to read a region of data, or GF_Write to write a region of data.

      - nXOff -- The pixel offset to the top left corner of the region of the band to be accessed. This would be zero to start from the left side.

      - nYOff -- The line offset to the top left corner of the region of the band to be accessed. This would be zero to start from the top.

      - nXSize -- The width of the region of the band to be accessed in pixels.

      - nYSize -- The height of the region of the band to be accessed in lines.

      - pData -- The buffer into which the data should be read, or from which it should be written. This buffer must contain at least nBufXSize * nBufYSize * nBandCount words of type eBufType. It is organized in left to right,top to bottom pixel order. Spacing is controlled by the nPixelSpace, and nLineSpace parameters. Note that even with eRWFlag==GF_Write, the content of the buffer might be temporarily modified during the execution of this method (and eventually restored back to its original content), so it is not safe to use a buffer stored in a read-only section of the calling program.

      - nBufXSize -- the width of the buffer image into which the desired region is to be read, or from which it is to be written.

      - nBufYSize -- the height of the buffer image into which the desired region is to be read, or from which it is to be written.

      - eBufType -- the type of the pixel values in the pData data buffer. The pixel values will automatically be translated to/from the GDALRasterBand data type as needed. Most driver implementations will use GDALCopyWords64() to perform data type translation.

      - nBandCount -- the number of bands being read or written.

      - panBandMap -- the list of nBandCount band numbers being read/written. Note band numbers are 1 based. This may be NULL to select the first nBandCount bands. (Note: before GDAL 3.10, argument type was "int*", and not "const int*")

      - nPixelSpace -- The byte offset from the start of one pixel value in pData to the start of the next pixel value within a scanline. If defaulted (0) the size of the datatype eBufType is used.

      - nLineSpace -- The byte offset from the start of one scanline in pData to the start of the next. If defaulted (0) the size of the datatype eBufType * nBufXSize is used.

      - nBandSpace -- the byte offset from the start of one bands data to the start of the next. If defaulted (0) the value will be nLineSpace * nBufYSize implying band sequential organization of the data buffer.

      - psExtraArg -- pointer to a GDALRasterIOExtraArg structure with additional arguments to specify resampling and progress callback, or NULL for default behavior. The GDAL_RASTERIO_RESAMPLING configuration option can also be defined to override the default resampling to one of BILINEAR, CUBIC, CUBICSPLINE, LANCZOS, AVERAGE or MODE.

    Returns:

      CE_Failure if the access fails, otherwise CE_None.

  virtual CPLStringList GetCompressionFormats(int nXOff, int nYOff, int nXSize, int nYSize, int nBandCount, const int *panBandList)

    Return the compression formats that can be natively obtained for the window of interest and requested bands.

    For example, a tiled dataset may be able to return data in a compressed format if the window of interest matches exactly a tile. For some formats, drivers may also be able to merge several tiles together (not currently implemented though).

    Each format string is a pseudo MIME type, whose first part can be passed as the pszFormat argument of ReadCompressedData(), with additional parameters specified as key=value with a semi-colon separator.

    The amount and types of optional parameters passed after the MIME type is format dependent, and driver dependent (some drivers might not be able to return those extra information without doing a rather costly processing).

    For example, a driver might return "JPEG;frame_type=SOF0_baseline;" "bit_depth=8;num_components=3;subsampling=4:2:0;colorspace=YCbCr", and consequently "JPEG" can be passed as the pszFormat argument of ReadCompressedData(). For JPEG, implementations can use the GDALGetCompressionFormatForJPEG() helper method to generate a string like above from a JPEG codestream.

    Several values might be returned. For example, the JPEGXL driver will return "JXL", but also potentially "JPEG" if the JPEGXL codestream includes a JPEG reconstruction box.

    In the general case this method will return an empty list.

    This is the same as C function GDALDatasetGetCompressionFormats().

    For example, to check if native compression format(s) are available on the whole image:

        const CPLStringList aosFormats =
           poDataset->GetCompressionFormats(0, 0,
                                            poDataset->GetRasterXSize(),
                                            poDataset->GetRasterYSize(),
                                            poDataset->GetRasterCount(),
                                            nullptr);
        for( const char* pszFormat: aosFormats )
        {
           // Remove optional parameters and just print out the MIME type.
           const CPLStringList aosTokens(CSLTokenizeString2(pszFormat, ";", 0));
           printf("Found format %s\n, aosTokens[0]);
        }

    Since

      GDAL 3.7

    Parameters:

      - nXOff -- The pixel offset to the top left corner of the region of the band to be accessed. This would be zero to start from the left side.

      - nYOff -- The line offset to the top left corner of the region of the band to be accessed. This would be zero to start from the top.

      - nXSize -- The width of the region of the band to be accessed in pixels.

      - nYSize -- The height of the region of the band to be accessed in lines.

      - nBandCount -- the number of bands being requested.

      - panBandList -- the list of nBandCount band numbers. Note band numbers are 1 based. This may be NULL to select the first nBandCount bands.

    Returns:

      a list of compatible formats (which may be empty)

  virtual CPLErr ReadCompressedData(const char *pszFormat, int nXOff, int nYOff, int nXSize, int nYSize, int nBands, const int *panBandList, void **ppBuffer, size_t *pnBufferSize, char **ppszDetailedFormat)

    Return the compressed content that can be natively obtained for the window of interest and requested bands.

    For example, a tiled dataset may be able to return data in compressed format if the window of interest matches exactly a tile. For some formats, drivers may also be example to merge several tiles together (not currently implemented though).

    The implementation should make sure that the content returned forms a valid standalone file. For example, for the GeoTIFF implementation of this method, when extracting a JPEG tile, the method will automatically add the content of the JPEG Huffman and/or quantization tables that might be stored in the TIFF JpegTables tag, and not in tile data itself.

    In the general case this method will return CE_Failure.

    This is the same as C function GDALDatasetReadCompressedData().

    For example, to request JPEG content on the whole image and let GDAL deal with the buffer allocation.

        void* pBuffer = nullptr;
        size_t nBufferSize = 0;
        CPLErr eErr =
           poDataset->ReadCompressedData("JPEG",
                                         0, 0,
                                         poDataset->GetRasterXSize(),
                                         poDataset->GetRasterYSize(),
                                         poDataset->GetRasterCount(),
                                         nullptr, // panBandList
                                         &pBuffer,
                                         &nBufferSize,
                                         nullptr // ppszDetailedFormat
                                        );
        if (eErr == CE_None)
        {
            CPLAssert(pBuffer != nullptr);
            CPLAssert(nBufferSize > 0);
            VSILFILE* fp = VSIFOpenL("my.jpeg", "wb");
            if (fp)
            {
                VSIFWriteL(pBuffer, nBufferSize, 1, fp);
                VSIFCloseL(fp);
            }
            VSIFree(pBuffer);
        }

    Or to manage the buffer allocation on your side:

        size_t nUpperBoundBufferSize = 0;
        CPLErr eErr =
           poDataset->ReadCompressedData("JPEG",
                                         0, 0,
                                         poDataset->GetRasterXSize(),
                                         poDataset->GetRasterYSize(),
                                         poDataset->GetRasterCount(),
                                         nullptr, // panBandList
                                         nullptr, // ppBuffer,
                                         &nUpperBoundBufferSize,
                                         nullptr // ppszDetailedFormat
                                        );
        if (eErr == CE_None)
        {
            std::vector<uint8_t> myBuffer;
            myBuffer.resize(nUpperBoundBufferSize);
            void* pBuffer = myBuffer.data();
            size_t nActualSize = nUpperBoundBufferSize;
            char* pszDetailedFormat = nullptr;
            // We also request detailed format, but we could have passed it to
            // nullptr as well.
            eErr =
              poDataset->ReadCompressedData("JPEG",
                                            0, 0,
                                            poDataset->GetRasterXSize(),
                                            poDataset->GetRasterYSize(),
                                            poDataset->GetRasterCount(),
                                            nullptr, // panBandList
                                            &pBuffer,
                                            &nActualSize,
                                            &pszDetailedFormat);
            if (eErr == CE_None)
            {
               CPLAssert(pBuffer == myBuffer.data()); // pointed value not modified
               CPLAssert(nActualSize <= nUpperBoundBufferSize);
               myBuffer.resize(nActualSize);
               // do something useful
               VSIFree(pszDetailedFormat);
            }
        }

    Since

      GDAL 3.7

    Parameters:

      - pszFormat -- Requested compression format (e.g. "JPEG", "WEBP", "JXL"). This is the MIME type of one of the values returned by GetCompressionFormats(). The format string is designed to potentially include at a later point key=value optional parameters separated by a semi-colon character. At time of writing, none are implemented. ReadCompressedData() implementations should verify optional parameters and return CE_Failure if they cannot support one of them.

      - nXOff -- The pixel offset to the top left corner of the region of the band to be accessed. This would be zero to start from the left side.

      - nYOff -- The line offset to the top left corner of the region of the band to be accessed. This would be zero to start from the top.

      - nXSize -- The width of the region of the band to be accessed in pixels.

      - nYSize -- The height of the region of the band to be accessed in lines.

      - nBandCount -- the number of bands being requested.

      - panBandList -- the list of nBandCount band numbers. Note band numbers are 1 based. This may be NULL to select the first nBandCount bands.

      - ppBuffer -- Pointer to a buffer to store the compressed data or nullptr. If ppBuffer is not nullptr, then pnBufferSize should also not be nullptr. If ppBuffer is not nullptr, and *ppBuffer is not nullptr, then the provided buffer will be filled with the compressed data, provided that pnBufferSize and *pnBufferSize are not nullptr, and *pnBufferSize, indicating the size of *ppBuffer, is sufficiently large to hold the data. If ppBuffer is not nullptr, but *ppBuffer is nullptr, then the method will allocate *ppBuffer using VSIMalloc(), and thus the caller is responsible to free it with VSIFree(). If ppBuffer is nullptr, then the compressed data itself will not be returned, but *pnBufferSize will be updated with an upper bound of the size that would be necessary to hold it (if pnBufferSize != nullptr).

      - pnBufferSize -- Output buffer size, or nullptr. If ppBuffer != nullptr && *ppBuffer != nullptr, then pnBufferSize should be != nullptr and *pnBufferSize contain the size of *ppBuffer. If the method is successful, *pnBufferSize will be updated with the actual size used.

      - ppszDetailedFormat -- Pointer to an output string, or nullptr. If ppszDetailedFormat is not nullptr, then, on success, the method will allocate a new string in *ppszDetailedFormat (to be freed with VSIFree()) *ppszDetailedFormat might contain strings like "JPEG;frame_type=SOF0_baseline;bit_depth=8;num_components=3;" "subsampling=4:2:0;colorspace=YCbCr" or simply the MIME type. The string will contain at least as much information as what GetCompressionFormats() returns, and potentially more when ppBuffer != nullptr.

    Returns:

      CE_None in case of success, CE_Failure otherwise.

  int Reference()

    Add one to dataset reference count.

    The reference is one after instantiation.

    This method is the same as the C GDALReferenceDataset() function.

    Returns:

      the post-increment reference count.

  int Dereference()

    Subtract one from dataset reference count.

    The reference is one after instantiation. Generally when the reference count has dropped to zero the dataset may be safely deleted (closed).

    This method is the same as the C GDALDereferenceDataset() function.

    Returns:

      the post-decrement reference count.

  int ReleaseRef()

    Drop a reference to this object, and destroy if no longer referenced.

    Returns:

      TRUE if the object has been destroyed.

  inline GDALAccess GetAccess() const

    Return access mode.

    Returns:

      access mode.

  int GetShared() const

    Returns shared flag.

    Returns:

      TRUE if the GDALDataset is available for sharing, or FALSE if not.

  void MarkAsShared()

    Mark this dataset as available for sharing.

  void MarkSuppressOnClose()

    Set that the dataset must be deleted on close.

    This is the same as C function GDALDatasetMarkSuppressOnClose()

  void UnMarkSuppressOnClose()

    Remove the flag requesting the dataset to be deleted on close.

  inline bool IsMarkedSuppressOnClose() const

    Return MarkSuppressOnClose flag.

    Returns:

      MarkSuppressOnClose flag.

  inline char **GetOpenOptions()

    Return open options.

    Returns:

      open options.

  bool IsThreadSafe(int nScopeFlags) const

    Return whether this dataset, and its related objects (typically raster bands), can be called for the intended scope.

    Note that in the current implementation, nScopeFlags should be set to GDAL_OF_RASTER, as thread-safety is limited to read-only operations and excludes operations on vector layers (OGRLayer) or multidimensional API (GDALGroup, GDALMDArray, etc.)

    This is the same as the C function GDALDatasetIsThreadSafe().

    Since

      3.10

  CPLErr BuildOverviews(const char *pszResampling, int nOverviews, const int *panOverviewList, int nListBands, const int *panBandList, GDALProgressFunc pfnProgress, void *pProgressData, CSLConstList papszOptions)

    Build raster overview(s)

    If the operation is not supported for the indicated dataset, then CE_Failure is returned, and CPLGetLastErrorNo() will return CPLE_NotSupported.

    Depending on the actual file format, all overviews level can be also deleted by specifying nOverviews == 0. This works at least for external overviews (.ovr), TIFF internal overviews, etc.

    Starting with GDAL 3.2, the GDAL_NUM_THREADS configuration option can be set to "ALL_CPUS" or a integer value to specify the number of threads to use for overview computation.

    This method is the same as the C function GDALBuildOverviewsEx().

    For example, to build overview level 2, 4 and 8 on all bands the following call could be made:

        int       anOverviewList[3] = { 2, 4, 8 };

        poDataset->BuildOverviews( "NEAREST", 3, anOverviewList, 0, nullptr,
                                   GDALDummyProgress, nullptr );

    See also

    GDALRegenerateOverviewsEx()

    Parameters:

      - pszResampling -- one of "AVERAGE", "AVERAGE_MAGPHASE", "RMS", "BILINEAR", "CUBIC", "CUBICSPLINE", "GAUSS", "LANCZOS", "MODE", "NEAREST", or "NONE" controlling the downsampling method applied.

      - nOverviews -- number of overviews to build, or 0 to clean overviews.

      - panOverviewList -- the list of overview decimation factors (positive integers, normally larger or equal to 2) to build, or NULL if nOverviews == 0.

      - nListBands -- number of bands to build overviews for in panBandList. Build for all bands if this is 0.

      - panBandList -- list of band numbers.

      - pfnProgress -- a function to call to report progress, or NULL.

      - pProgressData -- application data to pass to the progress function.

      - papszOptions -- (GDAL >= 3.6) NULL terminated list of options as key=value pairs, or NULL. Possible keys are the ones returned by GetDriver()->GetMetadataItem(GDAL_DMD_OVERVIEW_CREATIONOPTIONLIST)

    Returns:

      CE_None on success or CE_Failure if the operation doesn't work.

  virtual CPLErr AddOverviews(const std::vector<GDALDataset*> &apoSrcOvrDS, GDALProgressFunc pfnProgress, void *pProgressData, CSLConstList papszOptions)

    Add overview from existing dataset(s)

    This function creates new overview levels or refresh existing one from the list of provided overview datasets. Source overviews may come from any GDAL supported format, provided they have the same number of bands and geospatial extent than the target dataset.

    If the operation is not supported for the indicated dataset, then CE_Failure is returned, and CPLGetLastErrorNo() will return CPLE_NotSupported.

    At time of writing, this method is only implemented for internal overviews of GeoTIFF datasets and external overviews in GeoTIFF format.

    Since

      3.12

    Parameters:

      - apoSrcOvrDS -- Vector of source overviews.

      - pfnProgress -- a function to call to report progress, or NULL.

      - pProgressData -- application data to pass to the progress function.

      - papszOptions -- NULL terminated list of options as key=value pairs, or NULL. Possible keys are the ones returned by GetDriver()->GetMetadataItem(GDAL_DMD_OVERVIEW_CREATIONOPTIONLIST)

    Returns:

      CE_None on success or CE_Failure if the operation doesn't work.

  virtual char **GetMetadata(const char *pszDomain = "") override

    Fetch metadata.

    The returned string list is owned by the object, and may change at any time. It is formatted as a "Name=value" list with the last pointer value being NULL. Use the CPL StringList functions such as CSLFetchNameValue() to manipulate it.

    Note that relatively few formats return any metadata at this time.

    This method does the same thing as the C function GDALGetMetadata().

    Parameters:

      pszDomain -- the domain of interest. Use "" or NULL for the default domain.

    Returns:

      NULL or a string list.

  virtual CPLErr SetMetadata(char **papszMetadata, const char *pszDomain) override

    Set metadata.

    CAUTION: depending on the format, older values of the updated information might still be found in the file in a "ghost" state, even if no longer accessible through the GDAL API. This is for example the case of the GTiff format (this is not a exhaustive list)

    The C function GDALSetMetadata() does the same thing as this method.

    Parameters:

      - papszMetadata -- the metadata in name=value string list format to apply.

      - pszDomain -- the domain of interest. Use "" or NULL for the default domain.

    Returns:

      CE_None on success, CE_Failure on failure and CE_Warning if the metadata has been accepted, but is likely not maintained persistently by the underlying object between sessions.

  virtual CPLErr SetMetadataItem(const char *pszName, const char *pszValue, const char *pszDomain) override

    Set single metadata item.

    CAUTION: depending on the format, older values of the updated information might still be found in the file in a "ghost" state, even if no longer accessible through the GDAL API. This is for example the case of the GTiff format (this is not a exhaustive list)

    The C function GDALSetMetadataItem() does the same thing as this method.

    Parameters:

      - pszName -- the key for the metadata item to fetch.

      - pszValue -- the value to assign to the key.

      - pszDomain -- the domain to set within, use NULL for the default domain.

    Returns:

      CE_None on success, or an error code on failure.

  virtual char **GetMetadataDomainList() override

    Fetch list of metadata domains.

    The returned string list is the list of (non-empty) metadata domains.

    This method does the same thing as the C function GDALGetMetadataDomainList().

    Returns:

      NULL or a string list. Must be freed with CSLDestroy()

  virtual void ClearStatistics()

    Clear statistics.

    Only implemented for now in PAM supported datasets

    This is the same as the C function GDALDatasetClearStatistics().

    Since

      GDAL 3.2

  std::shared_ptr<GDALMDArray> AsMDArray(CSLConstList papszOptions = nullptr)

    Return a view of this dataset as a 3D multidimensional GDALMDArray.

    If this dataset is not already marked as shared, it will be, so that the returned array holds a reference to it.

    If the dataset has a geotransform attached, the X and Y dimensions of the returned array will have an associated indexing variable.

    The currently supported list of options is:

    - DIM_ORDER=<order> where order can be "AUTO", "Band,Y,X" or "Y,X,Band". "Band,Y,X" means that the first (slowest changing) dimension is Band and the last (fastest changing direction) is X "Y,X,Band" means that the first (slowest changing) dimension is Y and the last (fastest changing direction) is Band. "AUTO" (the default) selects "Band,Y,X" for single band datasets, or takes into account the INTERLEAVE metadata item in the IMAGE_STRUCTURE domain. If it equals BAND, then "Band,Y,X" is used. Otherwise (if it equals PIXEL), "Y,X,Band" is use.

    - BAND_INDEXING_VAR_ITEM={Description}|{None}|{Index}|{ColorInterpretation}|<BandMetadataItem>: item from which to build the band indexing variable.

      - "{Description}", the default, means to use the band description (or "Band index" if empty).

      - "{None}" means that no band indexing variable must be created.

      - "{Index}" means that the band index (starting at one) is used.

      - "{ColorInterpretation}" means that the band color interpretation is used (i.e. "Red", "Green", "Blue").

      - <BandMetadataItem> is the name of a band metadata item to use.

    - BAND_INDEXING_VAR_TYPE=String|Real|Integer: the data type of the band indexing variable, when BAND_INDEXING_VAR_ITEM corresponds to a band metadata item. Defaults to String.

    - BAND_DIM_NAME=<string>: Name of the band dimension. Defaults to "Band".

    - X_DIM_NAME=<string>: Name of the X dimension. Defaults to "X".

    - Y_DIM_NAME=<string>: Name of the Y dimension. Defaults to "Y".

    This is the same as the C function GDALDatasetAsMDArray().

    The "reverse" method is GDALMDArray::AsClassicDataset().

    Since

      GDAL 3.12

    Parameters:

      papszOptions -- Null-terminated list of strings, or nullptr.

    Returns:

      a new array, or nullptr.

  virtual int GetLayerCount() const

    Get the number of layers in this dataset.

    This method is the same as the C function GDALDatasetGetLayerCount(), and the deprecated OGR_DS_GetLayerCount().

    Note that even if this method is const, there is no guarantee it can be safely called by concurrent threads on the same GDALDataset object.

    Returns:

      layer count.

  virtual const OGRLayer *GetLayer(int iLayer) const

    Fetch a layer by index.

    The returned layer remains owned by the GDALDataset and should not be deleted by the application.

    Note that even if this method is const, there is no guarantee it can be safely called by concurrent threads on the same GDALDataset object.

    See GetLayers() for a C++ iterator version of this method.

    This method is the same as the C function GDALDatasetGetLayer() and the deprecated OGR_DS_GetLayer().

    See also

    GetLayers()

    Since

      GDAL 3.12

    Parameters:

      iLayer -- a layer number between 0 and GetLayerCount()-1.

    Returns:

      the layer, or NULL if iLayer is out of range or an error occurs.

  inline OGRLayer *GetLayer(int iLayer)

    Fetch a layer by index.

    The returned layer remains owned by the GDALDataset and should not be deleted by the application.

    See GetLayers() for a C++ iterator version of this method.

    This method is the same as the C function GDALDatasetGetLayer() and the deprecated OGR_DS_GetLayer().

    See also

    GetLayers()

    Parameters:

      iLayer -- a layer number between 0 and GetLayerCount()-1.

    Returns:

      the layer, or NULL if iLayer is out of range or an error occurs.

  virtual bool IsLayerPrivate(int iLayer) const

    Returns true if the layer at the specified index is deemed a private or system table, or an internal detail only.

    This method is the same as the C function GDALDatasetIsLayerPrivate().

    Since

      GDAL 3.4

    Parameters:

      iLayer -- a layer number between 0 and GetLayerCount()-1.

    Returns:

      true if the layer is a private or system table.

  Layers GetLayers()

    Function that returns an iterable object over layers in the dataset.

    This is a C++ iterator friendly version of GetLayer().

    Typical use is:

        for( auto&& poLayer: poDS->GetLayers() )
        {
              std::cout << "Layer  << poLayer->GetName() << std::endl;
        }

    See also

    GetLayer()

  ConstLayers GetLayers() const

    Function that returns an iterable object over layers in the dataset.

    This is a C++ iterator friendly version of GetLayer().

    Typical use is:

        for( auto&& poLayer: poDS->GetLayers() )
        {
              std::cout << "Layer  << poLayer->GetName() << std::endl;
        }

    See also

    GetLayer()

    Since

      GDAL 3.12

  virtual OGRLayer *GetLayerByName(const char*)

    Fetch a layer by name.

    The returned layer remains owned by the GDALDataset and should not be deleted by the application.

    This method is the same as the C function GDALDatasetGetLayerByName() and the deprecated OGR_DS_GetLayerByName().

    Parameters:

      pszName -- the layer name of the layer to fetch.

    Returns:

      the layer, or NULL if Layer is not found or an error occurs.

  int GetLayerIndex(const char *pszName) const

    Returns the index of the layer specified by name.

    Since

      GDAL 3.12

    Parameters:

      pszName -- layer name (not NULL)

    Returns:

      an index >= 0, or -1 if not found.

  virtual OGRErr DeleteLayer(int iLayer)

    Delete the indicated layer from the datasource.

    If this method is supported the ODsCDeleteLayer capability will test TRUE on the GDALDataset.

    This method is the same as the C function GDALDatasetDeleteLayer() and the deprecated OGR_DS_DeleteLayer().

    Parameters:

      iLayer -- the index of the layer to delete.

    Returns:

      OGRERR_NONE on success, or OGRERR_UNSUPPORTED_OPERATION if deleting layers is not supported for this datasource.

  virtual void ResetReading()

    Reset feature reading to start on the first feature.

    This affects GetNextFeature().

    Depending on drivers, this may also have the side effect of calling OGRLayer::ResetReading() on the layers of this dataset.

    This method is the same as the C function GDALDatasetResetReading().

  virtual OGRFeature *GetNextFeature(OGRLayer **ppoBelongingLayer, double *pdfProgressPct, GDALProgressFunc pfnProgress, void *pProgressData)

    Fetch the next available feature from this dataset.

    This method is intended for the few drivers where OGRLayer::GetNextFeature() is not efficient, but in general OGRLayer::GetNextFeature() is a more natural API.

    See GetFeatures() for a C++ iterator version of this method.

    The returned feature becomes the responsibility of the caller to delete with OGRFeature::DestroyFeature().

    Depending on the driver, this method may return features from layers in a non sequential way. This is what may happen when the ODsCRandomLayerRead capability is declared (for example for the OSM and GMLAS drivers). When datasets declare this capability, it is strongly advised to use GDALDataset::GetNextFeature() instead of OGRLayer::GetNextFeature(), as the later might have a slow, incomplete or stub implementation.

    The default implementation, used by most drivers, will however iterate over each layer, and then over each feature within this layer.

    This method takes into account spatial and attribute filters set on layers that will be iterated upon.

    The ResetReading() method can be used to start at the beginning again.

    Depending on drivers, this may also have the side effect of calling OGRLayer::GetNextFeature() on the layers of this dataset.

    This method is the same as the C function GDALDatasetGetNextFeature().

    See also

    GetFeatures()

    Parameters:

      - ppoBelongingLayer -- a pointer to a OGRLayer* variable to receive the layer to which the object belongs to, or NULL. It is possible that the output of *ppoBelongingLayer to be NULL despite the feature not being NULL.

      - pdfProgressPct -- a pointer to a double variable to receive the percentage progress (in [0,1] range), or NULL. On return, the pointed value might be negative if determining the progress is not possible.

      - pfnProgress -- a progress callback to report progress (for GetNextFeature() calls that might have a long duration) and offer cancellation possibility, or NULL.

      - pProgressData -- user data provided to pfnProgress, or NULL

    Returns:

      a feature, or NULL if no more features are available.

  Features GetFeatures()

    Function that return an iterable object over features in the dataset layer.

    This is a C++ iterator friendly version of GetNextFeature().

    Using this iterator for standard range-based loops is safe, but due to implementation limitations, you shouldn't try to access (dereference) more than one iterator step at a time, since the FeatureLayerPair reference which is returned is reused.

    Typical use is:

        for( auto&& oFeatureLayerPair: poDS->GetFeatures() )
        {
              std::cout << "Feature of layer " <<
                      oFeatureLayerPair.layer->GetName() << std::endl;
              oFeatureLayerPair.feature->DumpReadable();
        }

    See also

    GetNextFeature()

  virtual int TestCapability(const char*) const

    Test if capability is available.

    One of the following dataset capability names can be passed into this method, and a TRUE or FALSE value will be returned indicating whether or not the capability is available for this object.

    - ODsCCreateLayer: True if this datasource can create new layers.

    - ODsCDeleteLayer: True if this datasource can delete existing layers.

    - ODsCCreateGeomFieldAfterCreateLayer: True if the layers of this datasource support CreateGeomField() just after layer creation.

    - ODsCCurveGeometries: True if this datasource supports curve geometries.

    - ODsCTransactions: True if this datasource supports (efficient) transactions.

    - ODsCEmulatedTransactions: True if this datasource supports transactions through emulation.

    - ODsCRandomLayerRead: True if this datasource has a dedicated GetNextFeature() implementation, potentially returning features from layers in a non sequential way.

    - ODsCRandomLayerWrite: True if this datasource supports calling CreateFeature() on layers in a non sequential way.

    - GDsCAddRelationship: True if AddRelationship() is supported

    - GDsCDeleteRelationship: True if DeleteRelationship() is supported

    - GDsCUpdateRelationship: True if UpdateRelationship() is supported

    - GDsCFastGetExtent: True if GetExtent() is fast

    - GDsCFastGetExtentWGS84LongLat: True if GetExtentWGS84LongLat() is fast

    The #define macro forms of the capability names should be used in preference to the strings themselves to avoid misspelling.

    This method is the same as the C function GDALDatasetTestCapability() and the deprecated OGR_DS_TestCapability().

    Parameters:

      pszCap -- the capability to test.

    Returns:

      TRUE if capability available otherwise FALSE.

  virtual std::vector<std::string> GetFieldDomainNames(CSLConstList papszOptions = nullptr) const

    Returns a list of the names of all field domains stored in the dataset.

    Since

      GDAL 3.5

    Note

    The default implementation assumes that drivers fully populate m_oMapFieldDomains when opening a dataset. If this assumption is incorrect then a specialized implementation of GetFieldDomainNames() must be implemented.

    Parameters:

      papszOptions -- Driver specific options determining how attributes should be retrieved. Pass nullptr for default behavior.

    Returns:

      list of field domain names

  virtual const OGRFieldDomain *GetFieldDomain(const std::string &name) const

    Get a field domain from its name.

    Since

      GDAL 3.3

    Returns:

      the field domain, or nullptr if not found.

  virtual bool AddFieldDomain(std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)

    Add a field domain to the dataset.

    Only a few drivers will support this operation, and some of them might only support it only for some types of field domains. At the time of writing (GDAL 3.3), only the Memory and GeoPackage drivers support this operation. A dataset having at least some support for this operation should report the ODsCAddFieldDomain dataset capability.

    Anticipated failures will not be emitted through the CPLError() infrastructure, but will be reported in the failureReason output parameter.

    Since

      GDAL 3.3

    Note

    Drivers should make sure to update m_oMapFieldDomains in order for the default implementation of GetFieldDomainNames() to work correctly, or alternatively a specialized implementation of GetFieldDomainNames() should be implemented.

    Parameters:

      - domain -- The domain definition.

      - failureReason -- Output parameter. Will contain an error message if an error occurs.

    Returns:

      true in case of success.

  virtual bool DeleteFieldDomain(const std::string &name, std::string &failureReason)

    Removes a field domain from the dataset.

    Only a few drivers will support this operation.

    At the time of writing (GDAL 3.5), only the Memory and GeoPackage drivers support this operation. A dataset having at least some support for this operation should report the ODsCDeleteFieldDomain dataset capability.

    Anticipated failures will not be emitted through the CPLError() infrastructure, but will be reported in the failureReason output parameter.

    Since

      GDAL 3.5

    Note

    Drivers should make sure to update m_oMapFieldDomains in order for the default implementation of GetFieldDomainNames() to work correctly, or alternatively a specialized implementation of GetFieldDomainNames() should be implemented.

    Parameters:

      - name -- The domain name.

      - failureReason -- Output parameter. Will contain an error message if an error occurs.

    Returns:

      true in case of success.

  virtual bool UpdateFieldDomain(std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)

    Updates an existing field domain by replacing its definition.

    The existing field domain with matching name will be replaced.

    Only a few drivers will support this operation, and some of them might only support it only for some types of field domains. At the time of writing (GDAL 3.5), only the Memory driver supports this operation. A dataset having at least some support for this operation should report the ODsCUpdateFieldDomain dataset capability.

    Anticipated failures will not be emitted through the CPLError() infrastructure, but will be reported in the failureReason output parameter.

    Since

      GDAL 3.5

    Parameters:

      - domain -- The domain definition.

      - failureReason -- Output parameter. Will contain an error message if an error occurs.

    Returns:

      true in case of success.

  virtual std::vector<std::string> GetRelationshipNames(CSLConstList papszOptions = nullptr) const

    Returns a list of the names of all relationships stored in the dataset.

    Since

      GDAL 3.6

    Parameters:

      papszOptions -- Driver specific options determining how relationships should be retrieved. Pass nullptr for default behavior.

    Returns:

      list of relationship names

  virtual const GDALRelationship *GetRelationship(const std::string &name) const

    Get a relationship from its name.

    Since

      GDAL 3.6

    Returns:

      the relationship, or nullptr if not found.

  virtual bool AddRelationship(std::unique_ptr<GDALRelationship> &&relationship, std::string &failureReason)

    Add a relationship to the dataset.

    Only a few drivers will support this operation, and some of them might only support it only for some types of relationships.

    A dataset having at least some support for this operation should report the GDsCAddRelationship dataset capability.

    Anticipated failures will not be emitted through the CPLError() infrastructure, but will be reported in the failureReason output parameter.

    When adding a many-to-many relationship (GDALRelationshipCardinality::GRC_MANY_TO_MANY), it is possible to omit the mapping table name (see GDALRelationship::GetMappingTableName) to instruct the driver to create an appropriately named and structured mapping table. Some dataset formats require particular naming conventions and field structures for the mapping table, and delegating the construction of the mapping table to the driver will avoid these pitfalls.

    Since

      GDAL 3.6

    Parameters:

      - relationship -- The relationship definition.

      - failureReason -- Output parameter. Will contain an error message if an error occurs.

    Returns:

      true in case of success.

  virtual bool DeleteRelationship(const std::string &name, std::string &failureReason)

    Removes a relationship from the dataset.

    Only a few drivers will support this operation.

    A dataset having at least some support for this operation should report the GDsCDeleteRelationship dataset capability.

    Anticipated failures will not be emitted through the CPLError() infrastructure, but will be reported in the failureReason output parameter.

    Since

      GDAL 3.6

    Parameters:

      - name -- The relationship name.

      - failureReason -- Output parameter. Will contain an error message if an error occurs.

    Returns:

      true in case of success.

  virtual bool UpdateRelationship(std::unique_ptr<GDALRelationship> &&relationship, std::string &failureReason)

    Updates an existing relationship by replacing its definition.

    The existing relationship with matching name will be replaced.

    Only a few drivers will support this operation, and some of them might only support it only for some types of relationships. A dataset having at least some support for this operation should report the GDsCUpdateRelationship dataset capability.

    Anticipated failures will not be emitted through the CPLError() infrastructure, but will be reported in the failureReason output parameter.

    Since

      GDAL 3.6

    Parameters:

      - relationship -- The relationship definition.

      - failureReason -- Output parameter. Will contain an error message if an error occurs.

    Returns:

      true in case of success.

  OGRLayer *CreateLayer(const char *pszName, const OGRSpatialReference *poSpatialRef, OGRwkbGeometryType eGType = wkbUnknown, CSLConstList papszOptions = nullptr)

    This method attempts to create a new layer on the dataset with the indicated name, coordinate system, geometry type.

    The papszOptions argument can be used to control driver specific creation options. These options are normally documented in the format specific documentation. That function will try to validate the creation option list passed to the driver with the GDALValidateCreationOptions() method. This check can be disabled by defining the configuration option GDAL_VALIDATE_CREATION_OPTIONS set to NO.

    Drivers should extend the ICreateLayer() method and not CreateLayer(). CreateLayer() adds validation of layer creation options, before delegating the actual work to ICreateLayer().

    This method is the same as the C function GDALDatasetCreateLayer() and the deprecated OGR_DS_CreateLayer().

    Example:

        #include "gdal.h"
        #include "cpl_string.h"

        ...

                OGRLayer *poLayer;
                char     **papszOptions;

                if( !poDS->TestCapability( ODsCCreateLayer ) )
                {
                ...
                }

                papszOptions = CSLSetNameValue( papszOptions, "DIM", "2" );
                poLayer = poDS->CreateLayer( "NewLayer", nullptr, wkbUnknown,
                                             papszOptions );
                CSLDestroy( papszOptions );

                if( poLayer == NULL )
                {
                    ...
                }

    Parameters:

      - pszName -- the name for the new layer. This should ideally not match any existing layer on the datasource.

      - poSpatialRef -- the coordinate system to use for the new layer, or NULL if no coordinate system is available.

      - eGType -- the geometry type for the layer. Use wkbUnknown if there are no constraints on the types geometry to be written.

      - papszOptions -- a StringList of name=value options. Options are driver specific.

    Returns:

      NULL is returned on failure, or a new OGRLayer handle on success.

  OGRLayer *CreateLayer(const char *pszName, const OGRGeomFieldDefn *poGeomFieldDefn, CSLConstList papszOptions = nullptr)

    This method attempts to create a new layer on the dataset with the indicated name and geometry field definition.

    When poGeomFieldDefn is not null, most drivers should honor poGeomFieldDefn->GetType() and poGeomFieldDefn->GetSpatialRef(). Drivers that honor poGeomFieldDefn->GetCoordinatePrecision() will declare the GDAL_DCAP_HONOR_GEOM_COORDINATE_PRECISION capability. Drivers may honor poGeomFieldDefn->GetNameRef() and poGeomFieldDefn->IsNullable(), but there are very few currently.

    Note that even if a geometry coordinate precision is set and a driver honors the GDAL_DCAP_HONOR_GEOM_COORDINATE_PRECISION capability, geometries passed to OGRLayer::CreateFeature() and OGRLayer::SetFeature() are assumed to be compatible with the coordinate precision. That is they are assumed to be valid once their coordinates are rounded to it. If it might not be the case, the user may set the OGR_APPLY_GEOM_SET_PRECISION configuration option before calling CreateFeature() or SetFeature() to force the OGRGeometry::SetPrecision() method to be called on the passed geometries.

    The papszOptions argument can be used to control driver specific creation options. These options are normally documented in the format specific documentation. This function will try to validate the creation option list passed to the driver with the GDALValidateCreationOptions() method. This check can be disabled by defining the configuration option GDAL_VALIDATE_CREATION_OPTIONS set to NO.

    Drivers should extend the ICreateLayer() method and not CreateLayer(). CreateLayer() adds validation of layer creation options, before delegating the actual work to ICreateLayer().

    This method is the same as the C function GDALDatasetCreateLayerFromGeomFieldDefn().

    Since

      3.9

    Parameters:

      - pszName -- the name for the new layer. This should ideally not match any existing layer on the datasource.

      - poGeomFieldDefn -- the geometry field definition to use for the new layer, or NULL if there is no geometry field.

      - papszOptions -- a StringList of name=value options. Options are driver specific.

    Returns:

      NULL is returned on failure, or a new OGRLayer handle on success.

  virtual OGRLayer *CopyLayer(OGRLayer *poSrcLayer, const char *pszNewName, char **papszOptions = nullptr)

    Duplicate an existing layer.

    This method creates a new layer, duplicate the field definitions of the source layer and then duplicate each features of the source layer. The papszOptions argument can be used to control driver specific creation options. These options are normally documented in the format specific documentation. The source layer may come from another dataset.

    This method is the same as the C function GDALDatasetCopyLayer() and the deprecated OGR_DS_CopyLayer().

    Parameters:

      - poSrcLayer -- source layer.

      - pszNewName -- the name of the layer to create.

      - papszOptions -- a StringList of name=value options. Options are driver specific. There is a common option to set output layer spatial reference: DST_SRSWKT. The option should be in WKT format. Starting with GDAL 3.7, the common option COPY_MD can be set to NO to prevent the default copying of the metadata from the source layer to the target layer.

    Returns:

      a handle to the layer, or NULL if an error occurs.

  virtual OGRStyleTable *GetStyleTable()

    Returns dataset style table.

    This method is the same as the C function GDALDatasetGetStyleTable() and the deprecated OGR_DS_GetStyleTable().

    Returns:

      pointer to a style table which should not be modified or freed by the caller.

  virtual void SetStyleTableDirectly(OGRStyleTable *poStyleTable)

    Set dataset style table.

    This method operate exactly as SetStyleTable() except that it assumes ownership of the passed table.

    This method is the same as the C function GDALDatasetSetStyleTableDirectly() and the deprecated OGR_DS_SetStyleTableDirectly().

    Parameters:

      poStyleTable -- pointer to style table to set

  virtual void SetStyleTable(OGRStyleTable *poStyleTable)

    Set dataset style table.

    This method operate exactly as SetStyleTableDirectly() except that it does not assume ownership of the passed table.

    This method is the same as the C function GDALDatasetSetStyleTable() and the deprecated OGR_DS_SetStyleTable().

    Parameters:

      poStyleTable -- pointer to style table to set

  virtual OGRLayer *ExecuteSQL(const char *pszStatement, OGRGeometry *poSpatialFilter, const char *pszDialect)

    Execute an SQL statement against the data store.

    The result of an SQL query is either NULL for statements that are in error, or that have no results set, or an OGRLayer pointer representing a results set from the query. Note that this OGRLayer is in addition to the layers in the data store and must be destroyed with ReleaseResultSet() before the dataset is closed (destroyed).

    This method is the same as the C function GDALDatasetExecuteSQL() and the deprecated OGR_DS_ExecuteSQL().

    For more information on the SQL dialect supported internally by OGR review the OGR SQL document. Some drivers (i.e. Oracle and PostGIS) pass the SQL directly through to the underlying RDBMS.

    Starting with OGR 1.10, the SQLITE dialect can also be used.

    Parameters:

      - pszStatement -- the SQL statement to execute.

      - poSpatialFilter -- geometry which represents a spatial filter. Can be NULL.

      - pszDialect -- allows control of the statement dialect. If set to NULL, the OGR SQL engine will be used, except for RDBMS drivers that will use their dedicated SQL engine, unless OGRSQL is explicitly passed as the dialect. Starting with OGR 1.10, the SQLITE dialect can also be used.

    Returns:

      an OGRLayer containing the results of the query. Deallocate with ReleaseResultSet().

  virtual void ReleaseResultSet(OGRLayer *poResultsSet)

    Release results of ExecuteSQL().

    This method should only be used to deallocate OGRLayers resulting from an ExecuteSQL() call on the same GDALDataset. Failure to deallocate a results set before destroying the GDALDataset may cause errors.

    This method is the same as the C function GDALDatasetReleaseResultSet() and the deprecated OGR_DS_ReleaseResultSet().

    Parameters:

      poResultsSet -- the result of a previous ExecuteSQL() call.

  virtual OGRErr AbortSQL()

    Abort any SQL statement running in the data store.

    This function can be safely called from any thread (pending that the dataset object is still alive). Driver implementations will make sure that it can be called in a thread-safe way.

    This might not be implemented by all drivers. At time of writing, only SQLite, GPKG and PG drivers implement it

    This method is the same as the C method GDALDatasetAbortSQL()

    Since

      GDAL 3.2.0

  int GetRefCount() const

    Fetch reference count.

    This method is the same as the C function OGR_DS_GetRefCount().

    Returns:

      the current reference count for the datasource object itself.

  int GetSummaryRefCount() const

    Fetch reference count of datasource and all owned layers.

    This method is the same as the C function OGR_DS_GetSummaryRefCount().

    Deprecated:
    Returns:

      the current summary reference count for the datasource and its layers.

  OGRErr Release()

    Drop a reference to this dataset, and if the reference count drops to one close (destroy) the dataset.

    This method is the same as the C function OGRReleaseDataSource().

    Deprecated:

      . Use GDALClose() instead

    Returns:

      OGRERR_NONE on success or an error code.

  virtual OGRErr StartTransaction(int bForce = FALSE)

    For datasources which support transactions, StartTransaction creates a `transaction.

    If starting the transaction fails, will return OGRERR_FAILURE. Datasources which do not support transactions will always return OGRERR_UNSUPPORTED_OPERATION.

    Nested transactions are not supported.

    All changes done after the start of the transaction are definitely applied in the datasource if CommitTransaction() is called. They may be canceled by calling RollbackTransaction() instead.

    At the time of writing, transactions only apply on vector layers.

    Datasets that support transactions will advertise the ODsCTransactions capability. Use of transactions at dataset level is generally preferred to transactions at layer level, whose scope is rarely limited to the layer from which it was started.

    In case StartTransaction() fails, neither CommitTransaction() or RollbackTransaction() should be called.

    If an error occurs after a successful StartTransaction(), the whole transaction may or may not be implicitly canceled, depending on drivers. (e.g. the PG driver will cancel it, SQLite/GPKG not). In any case, in the event of an error, an explicit call to RollbackTransaction() should be done to keep things balanced.

    By default, when bForce is set to FALSE, only "efficient" transactions will be attempted. Some drivers may offer an emulation of transactions, but sometimes with significant overhead, in which case the user must explicitly allow for such an emulation by setting bForce to TRUE. Drivers that offer emulated transactions should advertise the ODsCEmulatedTransactions capability (and not ODsCTransactions).

    This function is the same as the C function GDALDatasetStartTransaction().

    Parameters:

      bForce -- can be set to TRUE if an emulation, possibly slow, of a transaction mechanism is acceptable.

    Returns:

      OGRERR_NONE on success.

  virtual OGRErr CommitTransaction()

    For datasources which support transactions, CommitTransaction commits a transaction.

    If no transaction is active, or the commit fails, will return OGRERR_FAILURE. Datasources which do not support transactions will always return OGRERR_UNSUPPORTED_OPERATION.

    Depending on drivers, this may or may not abort layer sequential readings that are active.

    This function is the same as the C function GDALDatasetCommitTransaction().

    Returns:

      OGRERR_NONE on success.

  virtual OGRErr RollbackTransaction()

    For datasources which support transactions, RollbackTransaction will roll back a datasource to its state before the start of the current transaction.

    If no transaction is active, or the rollback fails, will return OGRERR_FAILURE. Datasources which do not support transactions will always return OGRERR_UNSUPPORTED_OPERATION.

    This function is the same as the C function GDALDatasetRollbackTransaction().

    Returns:

      OGRERR_NONE on success.

  virtual std::shared_ptr<GDALGroup> GetRootGroup() const

    Return the root GDALGroup of this dataset.

    Only valid for multidimensional datasets.

    This is the same as the C function GDALDatasetGetRootGroup().

    Since

      GDAL 3.1

  Public Static Functions

  static GDALDataset **GetOpenDatasets(int *pnDatasetCount)

    Fetch all open GDAL dataset handles.

    This method is the same as the C function GDALGetOpenDatasets().

    NOTE: This method is not thread safe. The returned list may change at any time and it should not be freed.

    Parameters:

      pnCount -- integer into which to place the count of dataset pointers being returned.

    Returns:

      a pointer to an array of dataset handles.

  static inline GDALDatasetH ToHandle(GDALDataset *poDS)

    Convert a GDALDataset* to a GDALDatasetH.

  static inline GDALDataset *FromHandle(GDALDatasetH hDS)

    Convert a GDALDatasetH to a GDALDataset*.

  static inline GDALDataset *Open(const char *pszFilename, unsigned int nOpenFlags = 0, const char *const *papszAllowedDrivers = nullptr, const char *const *papszOpenOptions = nullptr, const char *const *papszSiblingFiles = nullptr)

    See also

    GDALOpenEx().

  static std::string BuildFilename(const char *pszFilename, const char *pszReferencePath, bool bRelativeToReferencePath)

    Generates a filename, potentially relative to another one.

    Given the path to a reference directory, and a path to a file referenced from it, build a path to the file that the current application can use. If the file path is already absolute, rather than relative, or if bRelativeToReferencePath is false, then the filename of interest will be returned unaltered.

    This is enhanced version of CPLProjectRelativeFilenameSafe() that takes into account the subdataset syntax.

    Examples:

        BuildFilename("tmp/abc.gif", "abc/def", true) == "abc/def/tmp/abc.gif"
        BuildFilename("../abc.gif", "/abc/def") == "/abc/abc.gif"
        BuildFilename("abc.gif", "C:\WIN", true) == "C:\WIN\abc.gif"
        BuildFilename("abc.gif", "C:\WIN", false) == "abc.gif"
        BuildFilename("/home/even/foo.tif", "/home/even/workdir", true) == "/home/even/foo.tif"

    Since

      3.11

    Parameters:

      - pszFilename -- Filename of interest.

      - pszReferencePath -- Path to a reference directory.

      - bRelativeToReferencePath -- Whether pszFilename, if a relative path, is relative to pszReferencePath

  class Bands

    Class returned by GetBands() that act as a container for raster bands.

    Public Functions

    const Iterator begin() const

      Return beginning of band iterator.

    const Iterator end() const

      Return end of band iterator.

    size_t size() const

      Get the number of raster bands in this dataset.

      Returns:

        raster band count.

    GDALRasterBand *operator[](int iBand)

      Fetch a raster band by index.

      The returned band remains owned by the GDALDataset and should not be deleted by the application.

      Warning

      Contrary to GDALDataset::GetRasterBand(), the indexing here is consistent with the conventions of C/C++, i.e. starting at 0.

      Parameters:

        iBand -- a band index between 0 and size()-1.

      Returns:

        the band, or nullptr if iBand is out of range or an error occurs.

    GDALRasterBand *operator[](size_t iBand)

      Fetch a raster band by index.

      The returned band remains owned by the GDALDataset and should not be deleted by the application.

      Warning

      Contrary to GDALDataset::GetRasterBand(), the indexing here is consistent with the conventions of C/C++, i.e. starting at 0.

      Parameters:

        iBand -- a band index between 0 and size()-1.

      Returns:

        the band, or nullptr if iBand is out of range or an error occurs.

  class ConstBands

    Class returned by GetBands() that act as a container for raster bands.

    Public Functions

    const Iterator begin() const

      Return beginning of band iterator.

      Since

        GDAL 3.12

    const Iterator end() const

      Return end of band iterator.

      Since

        GDAL 3.12

    size_t size() const

      Get the number of raster bands in this dataset.

      Since

        GDAL 3.12

      Returns:

        raster band count.

    const GDALRasterBand *operator[](int iBand) const

      Fetch a raster band by index.

      The returned band remains owned by the GDALDataset and should not be deleted by the application.

      Since

        GDAL 3.12

      Warning

      Contrary to GDALDataset::GetRasterBand(), the indexing here is consistent with the conventions of C/C++, i.e. starting at 0.

      Parameters:

        iBand -- a band index between 0 and size()-1.

      Returns:

        the band, or nullptr if iBand is out of range or an error occurs.

    const GDALRasterBand *operator[](size_t iBand) const

      Fetch a raster band by index.

      The returned band remains owned by the GDALDataset and should not be deleted by the application.

      Since

        GDAL 3.12

      Warning

      Contrary to GDALDataset::GetRasterBand(), the indexing here is consistent with the conventions of C/C++, i.e. starting at 0.

      Parameters:

        iBand -- a band index between 0 and size()-1.

      Returns:

        the band, or nullptr if iBand is out of range or an error occurs.

  class ConstLayers

    Class returned by GetLayers() that acts as a range of layers.

    Since

      GDAL 3.12

    Public Functions

    Iterator begin() const

      Return beginning of layer iterator.

      Since

        GDAL 3.12

    Iterator end() const

      Return end of layer iterator.

      Since

        GDAL 3.12

    size_t size() const

      Get the number of layers in this dataset.

      Since

        GDAL 3.12

      Returns:

        layer count.

    const OGRLayer *operator[](int iLayer)

      Fetch a layer by index.

      The returned layer remains owned by the GDALDataset and should not be deleted by the application.

      Since

        GDAL 3.12

      Parameters:

        iLayer -- a layer number between 0 and size()-1.

      Returns:

        the layer, or nullptr if iLayer is out of range or an error occurs.

    const OGRLayer *operator[](size_t iLayer)

      Fetch a layer by index.

      The returned layer remains owned by the GDALDataset and should not be deleted by the application.

      Since

        GDAL 3.12

      Parameters:

        iLayer -- a layer number between 0 and size()-1.

      Returns:

        the layer, or nullptr if iLayer is out of range or an error occurs.

    const OGRLayer *operator[](const char *pszLayername)

      Fetch a layer by name.

      The returned layer remains owned by the GDALDataset and should not be deleted by the application.

      Since

        GDAL 3.12

      Parameters:

        pszLayerName -- layer name

      Returns:

        the layer, or nullptr if pszLayerName does not match with a layer

    class Iterator

      Layer iterator.

      Since

        GDAL 3.12

      Public Types

      using value_type = const OGRLayer*

        value_type

      using reference = const OGRLayer*

        reference

      using difference_type = void

        difference_type

      using pointer = void

        pointer

      using iterator_category = std::input_iterator_tag

        iterator_category

      Public Functions

      Iterator()

        Default constructor.

      Iterator(const GDALDataset *poDS, bool bStart)

        Constructor.

      Iterator(const Iterator &oOther)

        Copy constructor.

      Iterator(Iterator &&oOther) noexcept

        Move constructor.

      ~Iterator()

        Destructor.

      Iterator &operator=(const Iterator &oOther)

        Assignment operator.

      Iterator &operator=(Iterator &&oOther) noexcept

        Move assignment operator.

      value_type operator*() const

        Dereference operator.

      Iterator &operator++()

        Pre-increment operator.

      Iterator operator++(int)

        Post-increment operator.

      bool operator!=(const Iterator &it) const

        Difference comparison operator.

      struct Private
  struct FeatureLayerPair

    Object returned by GetFeatures() iterators.

    Public Members

    OGRFeatureUniquePtr feature = {}

      Unique pointer to a OGRFeature.

    OGRLayer *layer = nullptr

      Layer to which the feature belongs to.

  class Features

    Class returned by GetFeatures() that act as a container for vector features.

    Public Functions

    const Iterator begin() const

      Return beginning of feature iterator.

    const Iterator end() const

      Return end of feature iterator.

  class Layers

    Class returned by GetLayers() that acts as a range of layers.

    Public Functions

    Iterator begin() const

      Return beginning of layer iterator.

    Iterator end() const

      Return end of layer iterator.

    size_t size() const

      Get the number of layers in this dataset.

      Returns:

        layer count.

    OGRLayer *operator[](int iLayer)

      Fetch a layer by index.

      The returned layer remains owned by the GDALDataset and should not be deleted by the application.

      Parameters:

        iLayer -- a layer number between 0 and size()-1.

      Returns:

        the layer, or nullptr if iLayer is out of range or an error occurs.

    OGRLayer *operator[](size_t iLayer)

      Fetch a layer by index.

      The returned layer remains owned by the GDALDataset and should not be deleted by the application.

      Parameters:

        iLayer -- a layer number between 0 and size()-1.

      Returns:

        the layer, or nullptr if iLayer is out of range or an error occurs.

    OGRLayer *operator[](const char *pszLayername)

      Fetch a layer by name.

      The returned layer remains owned by the GDALDataset and should not be deleted by the application.

      Parameters:

        pszLayerName -- layer name

      Returns:

        the layer, or nullptr if pszLayerName does not match with a layer

    class Iterator

      Layer iterator.

      Public Types

      using value_type = OGRLayer*

        value_type

      using reference = OGRLayer*

        reference

      using difference_type = void

        difference_type

      using pointer = void

        pointer

      using iterator_category = std::input_iterator_tag

        iterator_category

      Public Functions

      Iterator()

        Default constructor.

      Iterator(GDALDataset *poDS, bool bStart)

        Constructor.

      Iterator(const Iterator &oOther)

        Copy constructor.

      Iterator(Iterator &&oOther) noexcept

        Move constructor.

      ~Iterator()

        Destructor.

      Iterator &operator=(const Iterator &oOther)

        Assignment operator.

      Iterator &operator=(Iterator &&oOther) noexcept

        Move assignment operator.

      value_type operator*() const

        Dereference operator.

      Iterator &operator++()

        Pre-increment operator.

      Iterator operator++(int)

        Post-increment operator.

      bool operator!=(const Iterator &it) const

        Difference comparison operator.

      struct Private
  class Private

## GDALOpenInfo class

class GDALOpenInfo

  Class for dataset open functions.

  Public Functions

  GDALOpenInfo(const char *pszFile, int nOpenFlagsIn, const char *const *papszSiblingFiles = nullptr)

    Constructor/.

    Parameters:

      - pszFilenameIn -- filename

      - nOpenFlagsIn -- open flags

      - papszSiblingsIn -- list of sibling files, or NULL.

  int TryToIngest(int nBytes)

    Ingest bytes from the file.

    Parameters:

      nBytes -- number of bytes to ingest.

    Returns:

      TRUE if successful

  char **GetSiblingFiles()

    Return sibling files.

    If the list of sibling files has not already been established, it will be, unless the GDAL_DISABLE_READDIR_ON_OPEN configuration option has been set to YES or EMPTY_DIR when this instance was constructed.

    Returns:

      sibling files. Ownership belongs to "this".

  char **StealSiblingFiles()

    Return sibling files and steal reference.

    Returns:

      sibling files. Ownership below to the caller (must be freed with CSLDestroy)

  bool AreSiblingFilesLoaded() const

    Return whether sibling files have been loaded.

    Returns:

      true or false.

  bool IsSingleAllowedDriver(const char *pszDriverName) const

    Returns true if the driver name is the single in the list of allowed drivers.

    Since

      GDAL 3.10

    Parameters:

      pszDriverName -- Driver name to test.

    Returns:

      true if the driver name is the single in the list of allowed drivers.

  inline bool IsExtensionEqualToCI(const char *pszExt) const

    Return whether the extension of the file is equal to pszExt, using case-insensitive comparison.

    Since

      3.11

  Public Members

  char *pszFilename = nullptr

    Filename.

  std::string osExtension = {}

    Result of CPLGetExtension(pszFilename);.

  char **papszOpenOptions = nullptr

    Open options.

  GDALAccess eAccess = GA_ReadOnly

    Access flag.

  int nOpenFlags = 0

    Open flags.

  bool bStatOK = false

    Whether stat()'ing the file was successful.

  bool bIsDirectory = false

    Whether the file is a directory.

  VSILFILE *fpL = nullptr

    Pointer to the file.

  int nHeaderBytes = 0

    Number of bytes in pabyHeader.

  GByte *pabyHeader = nullptr

    Buffer with first bytes of the file.

  const char *const *papszAllowedDrivers = nullptr

    Allowed drivers (NULL for all)

## GDALGeoTransform class

class GDALGeoTransform

  Class that encapsulates a geotransform matrix.

  It contains 6 coefficients expressing an affine transformation from (column, line) raster space to (X, Y) georeferenced space, such that

      X = xorig + column * xscale + line * xrot;
      Y = yorig + column * yrot   + line * yscale;

  The default value is the identity transformation.

  Since

    3.12

  Public Functions

  inline GDALGeoTransform() = default

    Default constructor for an identity geotransformation matrix.

  inline explicit GDALGeoTransform(const double coeffs[6])

    Constructor from a array of 6 double.

  inline GDALGeoTransform(double xorigIn, double xscaleIn, double xrotIn, double yorigIn, double yrotIn, double yscaleIn)

    Constructor from 6 double values.

  template<typename T>
  inline double operator[](T idx) const

    Element accessor.

    idx must be in [0,5] range

  template<typename T>
  inline double &operator[](T idx)

    Element accessor.

    idx must be in [0,5] range

  inline bool operator==(const GDALGeoTransform &other) const

    Equality test operator.

  inline bool operator!=(const GDALGeoTransform &other) const

    Inequality test operator.

  inline const double *data() const

    Cast to const double*.

  inline double *data()

    Cast to double*.

  inline void Apply(double dfPixel, double dfLine, double *pdfGeoX, double *pdfGeoY) const

    Apply GeoTransform to x/y coordinate.

    Applies the following computation, converting a (pixel, line) coordinate into a georeferenced (geo_x, geo_y) location.

        *pdfGeoX = padfGeoTransform[0] + dfPixel * padfGeoTransform[1]
                                       + dfLine  * padfGeoTransform[2];
        *pdfGeoY = padfGeoTransform[3] + dfPixel * padfGeoTransform[4]
                                       + dfLine  * padfGeoTransform[5];

    Parameters:

      - dfPixel -- Input pixel position.

      - dfLine -- Input line position.

      - pdfGeoX -- output location where geo_x (easting/longitude) location is placed.

      - pdfGeoY -- output location where geo_y (northing/latitude) location is placed.

  bool Apply(const OGREnvelope &env, GDALRasterWindow &window) const

    Apply a geotransform to an OGREnvelope in geographic coordinates.

    Parameters:

      - env -- An envelope in geographic coordinates

      - window -- A window in pixel/line coordinates

    Returns:

      true if the geotransform was successfully applied

  bool Apply(const GDALRasterWindow &window, OGREnvelope &env) const

    Apply a geotransform to a GDALRasterWindow in pixel/line coordinates.

    Parameters:

      - window -- A window in pixel/line coordinates

      - env -- An envelope in geographic coordinates

    Returns:

      true if the geotransform was successfully applied

  inline std::pair<double, double> Apply(double dfPixel, double dfLine) const

    Apply GeoTransform to x/y coordinate.

    Applies the following computation, converting a (pixel, line) coordinate into a georeferenced (geo_x, geo_y) location.

        out.first = padfGeoTransform[0] + dfPixel * padfGeoTransform[1]
                                         + dfLine  * padfGeoTransform[2];
        out.second = padfGeoTransform[3] + dfPixel * padfGeoTransform[4]
                                         + dfLine  * padfGeoTransform[5];

    Parameters:

      - dfPixel -- Input pixel position.

      - dfLine -- Input line position.

    Returns:

      output location as a (geo_x, geo_y) pair

  inline bool GetInverse(GDALGeoTransform &inverse) const

    Invert Geotransform.

    This function will invert a standard 3x2 set of GeoTransform coefficients. This converts the equation from being pixel to geo to being geo to pixel.

    Parameters:

      inverse -- [out] Output geotransform

    Returns:

      true on success or false if the equation is uninvertable.

  inline void Rescale(double dfXRatio, double dfYRatio)

    Rescale a geotransform by multiplying its scale and rotation terms by the provided ratios.

    This is typically used to compute the geotransform matrix of an overview dataset from the full resolution dataset, where the ratios are the size of the full resolution dataset divided by the size of the overview.

  inline bool IsAxisAligned() const

    Check whether the geotransform has a rotation component.

  Public Members

  double xorig = 0

    X value of the origin of the raster.

  double xscale = 1

    X scale factor.

  double xrot = 0

    X rotation factor.

  double yorig = 0

    Y value of the origin of the raster.

  double yrot = 0

    Y rotation factor.

  double yscale = 1

    Y scale factor.

## GDALRelationship class

class GDALRelationship

  Definition of a table relationship.

  GDALRelationship describes the relationship between two tables, including properties such as the cardinality of the relationship and the participating tables.

  Not all relationship properties are supported by all data formats.

  Since

    GDAL 3.6

  Public Functions

  inline GDALRelationship(const std::string &osName, const std::string &osLeftTableName, const std::string &osRightTableName, GDALRelationshipCardinality eCardinality = GDALRelationshipCardinality::GRC_ONE_TO_MANY)

    Constructor for a relationship between two tables.

    Parameters:

      - osName -- relationship name

      - osLeftTableName -- left table name

      - osRightTableName -- right table name

      - eCardinality -- cardinality of relationship

  inline const std::string &GetName() const

    Get the name of the relationship.

  inline GDALRelationshipCardinality GetCardinality() const

    Get the cardinality of the relationship.

  inline const std::string &GetLeftTableName() const

    Get the name of the left (or base/origin) table in the relationship.

    See also

    GetRightTableName()

  inline const std::string &GetRightTableName() const

    Get the name of the right (or related/destination) table in the relationship.

  inline const std::string &GetMappingTableName() const

    Get the name of the mapping table for many-to-many relationships.

    See also

    SetMappingTableName()

  inline void SetMappingTableName(const std::string &osName)

    Sets the name of the mapping table for many-to-many relationships.

    See also

    GetMappingTableName()

  inline const std::vector<std::string> &GetLeftTableFields() const

    Get the names of the participating fields from the left table in the relationship.

    See also

    GetRightTableFields()

    See also

    SetLeftTableFields()

  inline const std::vector<std::string> &GetRightTableFields() const

    Get the names of the participating fields from the right table in the relationship.

    See also

    GetLeftTableFields()

    See also

    SetRightTableFields()

  inline void SetLeftTableFields(const std::vector<std::string> &osListFields)

    Sets the names of the participating fields from the left table in the relationship.

    See also

    GetLeftTableFields()

    See also

    SetRightTableFields()

  inline void SetRightTableFields(const std::vector<std::string> &osListFields)

    Sets the names of the participating fields from the right table in the relationship.

    See also

    GetRightTableFields()

    See also

    SetLeftTableFields()

  inline const std::vector<std::string> &GetLeftMappingTableFields() const

    Get the names of the mapping table fields which correspond to the participating fields from the left table in the relationship.

    See also

    GetRightMappingTableFields()

    See also

    SetLeftMappingTableFields()

  inline const std::vector<std::string> &GetRightMappingTableFields() const

    Get the names of the mapping table fields which correspond to the participating fields from the right table in the relationship.

    See also

    GetLeftMappingTableFields()

    See also

    SetRightMappingTableFields()

  inline void SetLeftMappingTableFields(const std::vector<std::string> &osListFields)

    Sets the names of the mapping table fields which correspond to the participating fields from the left table in the relationship.

    See also

    GetLeftMappingTableFields()

    See also

    SetRightMappingTableFields()

  inline void SetRightMappingTableFields(const std::vector<std::string> &osListFields)

    Sets the names of the mapping table fields which correspond to the participating fields from the right table in the relationship.

    See also

    GetRightMappingTableFields()

    See also

    SetLeftMappingTableFields()

  inline GDALRelationshipType GetType() const

    Get the type of the relationship.

    See also

    SetType()

  inline void SetType(GDALRelationshipType eType)

    Sets the type of the relationship.

    See also

    GetType()

  inline const std::string &GetForwardPathLabel() const

    Get the label of the forward path for the relationship.

    The forward and backward path labels are free-form, user-friendly strings which can be used to generate descriptions of the relationship between features from the right and left tables.

    E.g. when the left table contains buildings and the right table contains furniture, the forward path label could be "contains" and the backward path label could be "is located within". A client could then generate a user friendly description string such as "fire hose 1234 is located

    within building 15a".

    See also

    SetForwardPathLabel()

    See also

    GetBackwardPathLabel()

  inline void SetForwardPathLabel(const std::string &osLabel)

    Sets the label of the forward path for the relationship.

    The forward and backward path labels are free-form, user-friendly strings which can be used to generate descriptions of the relationship between features from the right and left tables.

    E.g. when the left table contains buildings and the right table contains furniture, the forward path label could be "contains" and the backward path label could be "is located within". A client could then generate a user friendly description string such as "fire hose 1234 is located

    within building 15a".

    See also

    GetForwardPathLabel()

    See also

    SetBackwardPathLabel()

  inline const std::string &GetBackwardPathLabel() const

    Get the label of the backward path for the relationship.

    The forward and backward path labels are free-form, user-friendly strings which can be used to generate descriptions of the relationship between features from the right and left tables.

    E.g. when the left table contains buildings and the right table contains furniture, the forward path label could be "contains" and the backward path label could be "is located within". A client could then generate a user friendly description string such as "fire hose 1234 is located

    within building 15a".

    See also

    SetBackwardPathLabel()

    See also

    GetForwardPathLabel()

  inline void SetBackwardPathLabel(const std::string &osLabel)

    Sets the label of the backward path for the relationship.

    The forward and backward path labels are free-form, user-friendly strings which can be used to generate descriptions of the relationship between features from the right and left tables.

    E.g. when the left table contains buildings and the right table contains furniture, the forward path label could be "contains" and the backward path label could be "is located within". A client could then generate a user friendly description string such as "fire hose 1234 is located

    within building 15a".

    See also

    GetBackwardPathLabel()

    See also

    SetForwardPathLabel()

  inline const std::string &GetRelatedTableType() const

    Get the type string of the related table.

    This a free-form string representing the type of related features, where the exact interpretation is format dependent. For instance, table types from GeoPackage relationships will directly reflect the categories from the GeoPackage related tables extension (i.e. "media", "simple

    attributes", "features", "attributes" and "tiles").

    See also

    SetRelatedTableType()

  inline void SetRelatedTableType(const std::string &osType)

    Sets the type string of the related table.

    This a free-form string representing the type of related features, where the exact interpretation is format dependent. For instance, table types from GeoPackage relationships will directly reflect the categories from the GeoPackage related tables extension (i.e. "media", "simple

    attributes", "features", "attributes" and "tiles").

    See also

    GetRelatedTableType()

  Public Static Functions

  static inline GDALRelationshipH ToHandle(GDALRelationship *poRelationship)

    Convert a GDALRelationship* to a GDALRelationshipH.

  static inline GDALRelationship *FromHandle(GDALRelationshipH hRelationship)

    Convert a GDALRelationshipH to a GDALRelationship*.