LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/gpkg - ogrgeopackagedatasource.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 4122 4597 89.7 %
Date: 2025-12-22 19:17:04 Functions: 141 141 100.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GeoPackage Translator
       4             :  * Purpose:  Implements GDALGeoPackageDataset class
       5             :  * Author:   Paul Ramsey <pramsey@boundlessgeo.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2013, Paul Ramsey <pramsey@boundlessgeo.com>
       9             :  * Copyright (c) 2014, Even Rouault <even dot rouault at spatialys.com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "ogr_geopackage.h"
      15             : #include "ogr_p.h"
      16             : #include "ogr_swq.h"
      17             : #include "gdal_alg.h"
      18             : #include "gdalwarper.h"
      19             : #include "gdal_utils.h"
      20             : #include "ogrgeopackageutility.h"
      21             : #include "ogrsqliteutility.h"
      22             : #include "ogr_wkb.h"
      23             : #include "vrt/vrtdataset.h"
      24             : 
      25             : #include "tilematrixset.hpp"
      26             : 
      27             : #include <cstdlib>
      28             : 
      29             : #include <algorithm>
      30             : #include <limits>
      31             : #include <sstream>
      32             : 
      33             : #define COMPILATION_ALLOWED
      34             : #define DEFINE_OGRSQLiteSQLFunctionsSetCaseSensitiveLike
      35             : #include "ogrsqlitesqlfunctionscommon.cpp"
      36             : 
      37             : // Keep in sync prototype of those 2 functions between gdalopeninfo.cpp,
      38             : // ogrsqlitedatasource.cpp and ogrgeopackagedatasource.cpp
      39             : void GDALOpenInfoDeclareFileNotToOpen(const char *pszFilename,
      40             :                                       const GByte *pabyHeader,
      41             :                                       int nHeaderBytes);
      42             : void GDALOpenInfoUnDeclareFileNotToOpen(const char *pszFilename);
      43             : 
      44             : /************************************************************************/
      45             : /*                             Tiling schemes                           */
      46             : /************************************************************************/
      47             : 
      48             : typedef struct
      49             : {
      50             :     const char *pszName;
      51             :     int nEPSGCode;
      52             :     double dfMinX;
      53             :     double dfMaxY;
      54             :     int nTileXCountZoomLevel0;
      55             :     int nTileYCountZoomLevel0;
      56             :     int nTileWidth;
      57             :     int nTileHeight;
      58             :     double dfPixelXSizeZoomLevel0;
      59             :     double dfPixelYSizeZoomLevel0;
      60             : } TilingSchemeDefinition;
      61             : 
      62             : static const TilingSchemeDefinition asTilingSchemes[] = {
      63             :     /* See http://portal.opengeospatial.org/files/?artifact_id=35326 (WMTS 1.0),
      64             :        Annex E.3 */
      65             :     {"GoogleCRS84Quad", 4326, -180.0, 180.0, 1, 1, 256, 256, 360.0 / 256,
      66             :      360.0 / 256},
      67             : 
      68             :     /* See global-mercator at
      69             :        http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification */
      70             :     {"PseudoTMS_GlobalMercator", 3857, -20037508.34, 20037508.34, 2, 2, 256,
      71             :      256, 78271.516, 78271.516},
      72             : };
      73             : 
      74             : // Setting it above 30 would lead to integer overflow ((1 << 31) > INT_MAX)
      75             : constexpr int MAX_ZOOM_LEVEL = 30;
      76             : 
      77             : /************************************************************************/
      78             : /*                     GetTilingScheme()                                */
      79             : /************************************************************************/
      80             : 
      81             : static std::unique_ptr<TilingSchemeDefinition>
      82         570 : GetTilingScheme(const char *pszName)
      83             : {
      84         570 :     if (EQUAL(pszName, "CUSTOM"))
      85         442 :         return nullptr;
      86             : 
      87         256 :     for (const auto &tilingScheme : asTilingSchemes)
      88             :     {
      89         195 :         if (EQUAL(pszName, tilingScheme.pszName))
      90             :         {
      91          67 :             return std::make_unique<TilingSchemeDefinition>(tilingScheme);
      92             :         }
      93             :     }
      94             : 
      95          61 :     if (EQUAL(pszName, "PseudoTMS_GlobalGeodetic"))
      96           6 :         pszName = "InspireCRS84Quad";
      97             : 
      98         122 :     auto poTM = gdal::TileMatrixSet::parse(pszName);
      99          61 :     if (poTM == nullptr)
     100           1 :         return nullptr;
     101          60 :     if (!poTM->haveAllLevelsSameTopLeft())
     102             :     {
     103           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     104             :                  "Unsupported tiling scheme: not all zoom levels have same top "
     105             :                  "left corner");
     106           0 :         return nullptr;
     107             :     }
     108          60 :     if (!poTM->haveAllLevelsSameTileSize())
     109             :     {
     110           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     111             :                  "Unsupported tiling scheme: not all zoom levels have same "
     112             :                  "tile size");
     113           0 :         return nullptr;
     114             :     }
     115          60 :     if (!poTM->hasOnlyPowerOfTwoVaryingScales())
     116             :     {
     117           1 :         CPLError(CE_Failure, CPLE_NotSupported,
     118             :                  "Unsupported tiling scheme: resolution of consecutive zoom "
     119             :                  "levels is not always 2");
     120           1 :         return nullptr;
     121             :     }
     122          59 :     if (poTM->hasVariableMatrixWidth())
     123             :     {
     124           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     125             :                  "Unsupported tiling scheme: some levels have variable matrix "
     126             :                  "width");
     127           0 :         return nullptr;
     128             :     }
     129         118 :     auto poTilingScheme = std::make_unique<TilingSchemeDefinition>();
     130          59 :     poTilingScheme->pszName = pszName;
     131             : 
     132         118 :     OGRSpatialReference oSRS;
     133          59 :     if (oSRS.SetFromUserInput(poTM->crs().c_str()) != OGRERR_NONE)
     134             :     {
     135           0 :         return nullptr;
     136             :     }
     137          59 :     if (poTM->crs() == "http://www.opengis.net/def/crs/OGC/1.3/CRS84")
     138             :     {
     139           6 :         poTilingScheme->nEPSGCode = 4326;
     140             :     }
     141             :     else
     142             :     {
     143          53 :         const char *pszAuthName = oSRS.GetAuthorityName(nullptr);
     144          53 :         const char *pszAuthCode = oSRS.GetAuthorityCode(nullptr);
     145          53 :         if (pszAuthName == nullptr || !EQUAL(pszAuthName, "EPSG") ||
     146             :             pszAuthCode == nullptr)
     147             :         {
     148           0 :             CPLError(CE_Failure, CPLE_NotSupported,
     149             :                      "Unsupported tiling scheme: only EPSG CRS supported");
     150           0 :             return nullptr;
     151             :         }
     152          53 :         poTilingScheme->nEPSGCode = atoi(pszAuthCode);
     153             :     }
     154          59 :     const auto &zoomLevel0 = poTM->tileMatrixList()[0];
     155          59 :     poTilingScheme->dfMinX = zoomLevel0.mTopLeftX;
     156          59 :     poTilingScheme->dfMaxY = zoomLevel0.mTopLeftY;
     157          59 :     poTilingScheme->nTileXCountZoomLevel0 = zoomLevel0.mMatrixWidth;
     158          59 :     poTilingScheme->nTileYCountZoomLevel0 = zoomLevel0.mMatrixHeight;
     159          59 :     poTilingScheme->nTileWidth = zoomLevel0.mTileWidth;
     160          59 :     poTilingScheme->nTileHeight = zoomLevel0.mTileHeight;
     161          59 :     poTilingScheme->dfPixelXSizeZoomLevel0 = zoomLevel0.mResX;
     162          59 :     poTilingScheme->dfPixelYSizeZoomLevel0 = zoomLevel0.mResY;
     163             : 
     164         118 :     const bool bInvertAxis = oSRS.EPSGTreatsAsLatLong() != FALSE ||
     165          59 :                              oSRS.EPSGTreatsAsNorthingEasting() != FALSE;
     166          59 :     if (bInvertAxis)
     167             :     {
     168           6 :         std::swap(poTilingScheme->dfMinX, poTilingScheme->dfMaxY);
     169           6 :         std::swap(poTilingScheme->dfPixelXSizeZoomLevel0,
     170           6 :                   poTilingScheme->dfPixelYSizeZoomLevel0);
     171             :     }
     172          59 :     return poTilingScheme;
     173             : }
     174             : 
     175             : static const char *pszCREATE_GPKG_GEOMETRY_COLUMNS =
     176             :     "CREATE TABLE gpkg_geometry_columns ("
     177             :     "table_name TEXT NOT NULL,"
     178             :     "column_name TEXT NOT NULL,"
     179             :     "geometry_type_name TEXT NOT NULL,"
     180             :     "srs_id INTEGER NOT NULL,"
     181             :     "z TINYINT NOT NULL,"
     182             :     "m TINYINT NOT NULL,"
     183             :     "CONSTRAINT pk_geom_cols PRIMARY KEY (table_name, column_name),"
     184             :     "CONSTRAINT uk_gc_table_name UNIQUE (table_name),"
     185             :     "CONSTRAINT fk_gc_tn FOREIGN KEY (table_name) REFERENCES "
     186             :     "gpkg_contents(table_name),"
     187             :     "CONSTRAINT fk_gc_srs FOREIGN KEY (srs_id) REFERENCES gpkg_spatial_ref_sys "
     188             :     "(srs_id)"
     189             :     ")";
     190             : 
     191         976 : OGRErr GDALGeoPackageDataset::SetApplicationAndUserVersionId()
     192             : {
     193         976 :     CPLAssert(hDB != nullptr);
     194             : 
     195         976 :     const CPLString osPragma(CPLString().Printf("PRAGMA application_id = %u;"
     196             :                                                 "PRAGMA user_version = %u",
     197             :                                                 m_nApplicationId,
     198        1952 :                                                 m_nUserVersion));
     199        1952 :     return SQLCommand(hDB, osPragma.c_str());
     200             : }
     201             : 
     202        2639 : bool GDALGeoPackageDataset::CloseDB()
     203             : {
     204        2639 :     OGRSQLiteUnregisterSQLFunctions(m_pSQLFunctionData);
     205        2639 :     m_pSQLFunctionData = nullptr;
     206        2639 :     return OGRSQLiteBaseDataSource::CloseDB();
     207             : }
     208             : 
     209          11 : bool GDALGeoPackageDataset::ReOpenDB()
     210             : {
     211          11 :     CPLAssert(hDB != nullptr);
     212          11 :     CPLAssert(m_pszFilename != nullptr);
     213             : 
     214          11 :     FinishSpatialite();
     215             : 
     216          11 :     CloseDB();
     217             : 
     218             :     /* And re-open the file */
     219          11 :     return OpenOrCreateDB(SQLITE_OPEN_READWRITE);
     220             : }
     221             : 
     222         831 : static OGRErr GDALGPKGImportFromEPSG(OGRSpatialReference *poSpatialRef,
     223             :                                      int nEPSGCode)
     224             : {
     225         831 :     CPLPushErrorHandler(CPLQuietErrorHandler);
     226         831 :     const OGRErr eErr = poSpatialRef->importFromEPSG(nEPSGCode);
     227         831 :     CPLPopErrorHandler();
     228         831 :     CPLErrorReset();
     229         831 :     return eErr;
     230             : }
     231             : 
     232             : std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
     233        1274 : GDALGeoPackageDataset::GetSpatialRef(int iSrsId, bool bFallbackToEPSG,
     234             :                                      bool bEmitErrorIfNotFound)
     235             : {
     236        1274 :     const auto oIter = m_oMapSrsIdToSrs.find(iSrsId);
     237        1274 :     if (oIter != m_oMapSrsIdToSrs.end())
     238             :     {
     239          91 :         if (oIter->second == nullptr)
     240          33 :             return nullptr;
     241          58 :         oIter->second->Reference();
     242             :         return std::unique_ptr<OGRSpatialReference,
     243          58 :                                OGRSpatialReferenceReleaser>(oIter->second);
     244             :     }
     245             : 
     246        1183 :     if (iSrsId == 0 || iSrsId == -1)
     247             :     {
     248         119 :         OGRSpatialReference *poSpatialRef = new OGRSpatialReference();
     249         119 :         poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     250             : 
     251             :         // See corresponding tests in GDALGeoPackageDataset::GetSrsId
     252         119 :         if (iSrsId == 0)
     253             :         {
     254          29 :             poSpatialRef->SetGeogCS("Undefined geographic SRS", "unknown",
     255             :                                     "unknown", SRS_WGS84_SEMIMAJOR,
     256             :                                     SRS_WGS84_INVFLATTENING);
     257             :         }
     258          90 :         else if (iSrsId == -1)
     259             :         {
     260          90 :             poSpatialRef->SetLocalCS("Undefined Cartesian SRS");
     261          90 :             poSpatialRef->SetLinearUnits(SRS_UL_METER, 1.0);
     262             :         }
     263             : 
     264         119 :         m_oMapSrsIdToSrs[iSrsId] = poSpatialRef;
     265         119 :         poSpatialRef->Reference();
     266             :         return std::unique_ptr<OGRSpatialReference,
     267         119 :                                OGRSpatialReferenceReleaser>(poSpatialRef);
     268             :     }
     269             : 
     270        2128 :     CPLString oSQL;
     271        1064 :     oSQL.Printf("SELECT srs_name, definition, organization, "
     272             :                 "organization_coordsys_id%s%s "
     273             :                 "FROM gpkg_spatial_ref_sys WHERE "
     274             :                 "srs_id = %d LIMIT 2",
     275        1064 :                 m_bHasDefinition12_063 ? ", definition_12_063" : "",
     276        1064 :                 m_bHasEpochColumn ? ", epoch" : "", iSrsId);
     277             : 
     278        2128 :     auto oResult = SQLQuery(hDB, oSQL.c_str());
     279             : 
     280        1064 :     if (!oResult || oResult->RowCount() != 1)
     281             :     {
     282          12 :         if (bFallbackToEPSG)
     283             :         {
     284           7 :             CPLDebug("GPKG",
     285             :                      "unable to read srs_id '%d' from gpkg_spatial_ref_sys",
     286             :                      iSrsId);
     287           7 :             OGRSpatialReference *poSRS = new OGRSpatialReference();
     288           7 :             if (poSRS->importFromEPSG(iSrsId) == OGRERR_NONE)
     289             :             {
     290           5 :                 poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     291             :                 return std::unique_ptr<OGRSpatialReference,
     292           5 :                                        OGRSpatialReferenceReleaser>(poSRS);
     293             :             }
     294           2 :             poSRS->Release();
     295             :         }
     296           5 :         else if (bEmitErrorIfNotFound)
     297             :         {
     298           2 :             CPLError(CE_Warning, CPLE_AppDefined,
     299             :                      "unable to read srs_id '%d' from gpkg_spatial_ref_sys",
     300             :                      iSrsId);
     301           2 :             m_oMapSrsIdToSrs[iSrsId] = nullptr;
     302             :         }
     303           7 :         return nullptr;
     304             :     }
     305             : 
     306        1052 :     const char *pszName = oResult->GetValue(0, 0);
     307        1052 :     if (pszName && EQUAL(pszName, "Undefined SRS"))
     308             :     {
     309         457 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     310         457 :         return nullptr;
     311             :     }
     312         595 :     const char *pszWkt = oResult->GetValue(1, 0);
     313         595 :     if (pszWkt == nullptr)
     314           0 :         return nullptr;
     315         595 :     const char *pszOrganization = oResult->GetValue(2, 0);
     316         595 :     const char *pszOrganizationCoordsysID = oResult->GetValue(3, 0);
     317             :     const char *pszWkt2 =
     318         595 :         m_bHasDefinition12_063 ? oResult->GetValue(4, 0) : nullptr;
     319         595 :     if (pszWkt2 && !EQUAL(pszWkt2, "undefined"))
     320          76 :         pszWkt = pszWkt2;
     321             :     const char *pszCoordinateEpoch =
     322         595 :         m_bHasEpochColumn ? oResult->GetValue(5, 0) : nullptr;
     323             :     const double dfCoordinateEpoch =
     324         595 :         pszCoordinateEpoch ? CPLAtof(pszCoordinateEpoch) : 0.0;
     325             : 
     326         595 :     OGRSpatialReference *poSpatialRef = new OGRSpatialReference();
     327         595 :     poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     328             :     // Try to import first from EPSG code, and then from WKT
     329         595 :     if (!(pszOrganization && pszOrganizationCoordsysID &&
     330         595 :           EQUAL(pszOrganization, "EPSG") &&
     331         575 :           (atoi(pszOrganizationCoordsysID) == iSrsId ||
     332           4 :            (dfCoordinateEpoch > 0 && strstr(pszWkt, "DYNAMIC[") == nullptr)) &&
     333         575 :           GDALGPKGImportFromEPSG(
     334        1190 :               poSpatialRef, atoi(pszOrganizationCoordsysID)) == OGRERR_NONE) &&
     335          20 :         poSpatialRef->importFromWkt(pszWkt) != OGRERR_NONE)
     336             :     {
     337           0 :         CPLError(CE_Warning, CPLE_AppDefined,
     338             :                  "Unable to parse srs_id '%d' well-known text '%s'", iSrsId,
     339             :                  pszWkt);
     340           0 :         delete poSpatialRef;
     341           0 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     342           0 :         return nullptr;
     343             :     }
     344             : 
     345         595 :     poSpatialRef->StripTOWGS84IfKnownDatumAndAllowed();
     346         595 :     poSpatialRef->SetCoordinateEpoch(dfCoordinateEpoch);
     347         595 :     m_oMapSrsIdToSrs[iSrsId] = poSpatialRef;
     348         595 :     poSpatialRef->Reference();
     349             :     return std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>(
     350         595 :         poSpatialRef);
     351             : }
     352             : 
     353         285 : const char *GDALGeoPackageDataset::GetSrsName(const OGRSpatialReference &oSRS)
     354             : {
     355         285 :     const char *pszName = oSRS.GetName();
     356         285 :     if (pszName)
     357         285 :         return pszName;
     358             : 
     359             :     // Something odd.  Return empty.
     360           0 :     return "Unnamed SRS";
     361             : }
     362             : 
     363             : /* Add the definition_12_063 column to an existing gpkg_spatial_ref_sys table */
     364           7 : bool GDALGeoPackageDataset::ConvertGpkgSpatialRefSysToExtensionWkt2(
     365             :     bool bForceEpoch)
     366             : {
     367           7 :     const bool bAddEpoch = (m_nUserVersion >= GPKG_1_4_VERSION || bForceEpoch);
     368             :     auto oResultTable = SQLQuery(
     369             :         hDB, "SELECT srs_name, srs_id, organization, organization_coordsys_id, "
     370          14 :              "definition, description FROM gpkg_spatial_ref_sys LIMIT 100000");
     371           7 :     if (!oResultTable)
     372           0 :         return false;
     373             : 
     374             :     // Temporary remove foreign key checks
     375             :     const GPKGTemporaryForeignKeyCheckDisabler
     376           7 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
     377             : 
     378           7 :     bool bRet = SoftStartTransaction() == OGRERR_NONE;
     379             : 
     380           7 :     if (bRet)
     381             :     {
     382             :         std::string osSQL("CREATE TABLE gpkg_spatial_ref_sys_temp ("
     383             :                           "srs_name TEXT NOT NULL,"
     384             :                           "srs_id INTEGER NOT NULL PRIMARY KEY,"
     385             :                           "organization TEXT NOT NULL,"
     386             :                           "organization_coordsys_id INTEGER NOT NULL,"
     387             :                           "definition TEXT NOT NULL,"
     388             :                           "description TEXT, "
     389           7 :                           "definition_12_063 TEXT NOT NULL");
     390           7 :         if (bAddEpoch)
     391           6 :             osSQL += ", epoch DOUBLE";
     392           7 :         osSQL += ")";
     393           7 :         bRet = SQLCommand(hDB, osSQL.c_str()) == OGRERR_NONE;
     394             :     }
     395             : 
     396           7 :     if (bRet)
     397             :     {
     398          32 :         for (int i = 0; bRet && i < oResultTable->RowCount(); i++)
     399             :         {
     400          25 :             const char *pszSrsName = oResultTable->GetValue(0, i);
     401          25 :             const char *pszSrsId = oResultTable->GetValue(1, i);
     402          25 :             const char *pszOrganization = oResultTable->GetValue(2, i);
     403             :             const char *pszOrganizationCoordsysID =
     404          25 :                 oResultTable->GetValue(3, i);
     405          25 :             const char *pszDefinition = oResultTable->GetValue(4, i);
     406             :             if (pszSrsName == nullptr || pszSrsId == nullptr ||
     407             :                 pszOrganization == nullptr ||
     408             :                 pszOrganizationCoordsysID == nullptr)
     409             :             {
     410             :                 // should not happen as there are NOT NULL constraints
     411             :                 // But a database could lack such NOT NULL constraints or have
     412             :                 // large values that would cause a memory allocation failure.
     413             :             }
     414          25 :             const char *pszDescription = oResultTable->GetValue(5, i);
     415             :             char *pszSQL;
     416             : 
     417          50 :             OGRSpatialReference oSRS;
     418          25 :             if (pszOrganization && pszOrganizationCoordsysID &&
     419          25 :                 EQUAL(pszOrganization, "EPSG"))
     420             :             {
     421           9 :                 oSRS.importFromEPSG(atoi(pszOrganizationCoordsysID));
     422             :             }
     423          34 :             if (!oSRS.IsEmpty() && pszDefinition &&
     424           9 :                 !EQUAL(pszDefinition, "undefined"))
     425             :             {
     426           9 :                 oSRS.SetFromUserInput(pszDefinition);
     427             :             }
     428          25 :             char *pszWKT2 = nullptr;
     429          25 :             if (!oSRS.IsEmpty())
     430             :             {
     431           9 :                 const char *const apszOptionsWkt2[] = {"FORMAT=WKT2_2015",
     432             :                                                        nullptr};
     433           9 :                 oSRS.exportToWkt(&pszWKT2, apszOptionsWkt2);
     434           9 :                 if (pszWKT2 && pszWKT2[0] == '\0')
     435             :                 {
     436           0 :                     CPLFree(pszWKT2);
     437           0 :                     pszWKT2 = nullptr;
     438             :                 }
     439             :             }
     440          25 :             if (pszWKT2 == nullptr)
     441             :             {
     442          16 :                 pszWKT2 = CPLStrdup("undefined");
     443             :             }
     444             : 
     445          25 :             if (pszDescription)
     446             :             {
     447          22 :                 pszSQL = sqlite3_mprintf(
     448             :                     "INSERT INTO gpkg_spatial_ref_sys_temp(srs_name, srs_id, "
     449             :                     "organization, organization_coordsys_id, definition, "
     450             :                     "description, definition_12_063) VALUES ('%q', '%q', '%q', "
     451             :                     "'%q', '%q', '%q', '%q')",
     452             :                     pszSrsName, pszSrsId, pszOrganization,
     453             :                     pszOrganizationCoordsysID, pszDefinition, pszDescription,
     454             :                     pszWKT2);
     455             :             }
     456             :             else
     457             :             {
     458           3 :                 pszSQL = sqlite3_mprintf(
     459             :                     "INSERT INTO gpkg_spatial_ref_sys_temp(srs_name, srs_id, "
     460             :                     "organization, organization_coordsys_id, definition, "
     461             :                     "description, definition_12_063) VALUES ('%q', '%q', '%q', "
     462             :                     "'%q', '%q', NULL, '%q')",
     463             :                     pszSrsName, pszSrsId, pszOrganization,
     464             :                     pszOrganizationCoordsysID, pszDefinition, pszWKT2);
     465             :             }
     466             : 
     467          25 :             CPLFree(pszWKT2);
     468          25 :             bRet &= SQLCommand(hDB, pszSQL) == OGRERR_NONE;
     469          25 :             sqlite3_free(pszSQL);
     470             :         }
     471             :     }
     472             : 
     473           7 :     if (bRet)
     474             :     {
     475           7 :         bRet =
     476           7 :             SQLCommand(hDB, "DROP TABLE gpkg_spatial_ref_sys") == OGRERR_NONE;
     477             :     }
     478           7 :     if (bRet)
     479             :     {
     480           7 :         bRet = SQLCommand(hDB, "ALTER TABLE gpkg_spatial_ref_sys_temp RENAME "
     481             :                                "TO gpkg_spatial_ref_sys") == OGRERR_NONE;
     482             :     }
     483           7 :     if (bRet)
     484             :     {
     485          14 :         bRet = OGRERR_NONE == CreateExtensionsTableIfNecessary() &&
     486           7 :                OGRERR_NONE == SQLCommand(hDB,
     487             :                                          "INSERT INTO gpkg_extensions "
     488             :                                          "(table_name, column_name, "
     489             :                                          "extension_name, definition, scope) "
     490             :                                          "VALUES "
     491             :                                          "('gpkg_spatial_ref_sys', "
     492             :                                          "'definition_12_063', 'gpkg_crs_wkt', "
     493             :                                          "'http://www.geopackage.org/spec120/"
     494             :                                          "#extension_crs_wkt', 'read-write')");
     495             :     }
     496           7 :     if (bRet && bAddEpoch)
     497             :     {
     498           6 :         bRet =
     499             :             OGRERR_NONE ==
     500           6 :                 SQLCommand(hDB, "UPDATE gpkg_extensions SET extension_name = "
     501             :                                 "'gpkg_crs_wkt_1_1' "
     502          12 :                                 "WHERE extension_name = 'gpkg_crs_wkt'") &&
     503             :             OGRERR_NONE ==
     504           6 :                 SQLCommand(
     505             :                     hDB,
     506             :                     "INSERT INTO gpkg_extensions "
     507             :                     "(table_name, column_name, extension_name, definition, "
     508             :                     "scope) "
     509             :                     "VALUES "
     510             :                     "('gpkg_spatial_ref_sys', 'epoch', 'gpkg_crs_wkt_1_1', "
     511             :                     "'http://www.geopackage.org/spec/#extension_crs_wkt', "
     512             :                     "'read-write')");
     513             :     }
     514           7 :     if (bRet)
     515             :     {
     516           7 :         SoftCommitTransaction();
     517           7 :         m_bHasDefinition12_063 = true;
     518           7 :         if (bAddEpoch)
     519           6 :             m_bHasEpochColumn = true;
     520             :     }
     521             :     else
     522             :     {
     523           0 :         SoftRollbackTransaction();
     524             :     }
     525             : 
     526           7 :     return bRet;
     527             : }
     528             : 
     529         939 : int GDALGeoPackageDataset::GetSrsId(const OGRSpatialReference *poSRSIn)
     530             : {
     531         939 :     const char *pszName = poSRSIn ? poSRSIn->GetName() : nullptr;
     532        1350 :     if (!poSRSIn || poSRSIn->IsEmpty() ||
     533         411 :         (pszName && EQUAL(pszName, "Undefined SRS")))
     534             :     {
     535         530 :         OGRErr err = OGRERR_NONE;
     536         530 :         const int nSRSId = SQLGetInteger(
     537             :             hDB,
     538             :             "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE srs_name = "
     539             :             "'Undefined SRS' AND organization = 'GDAL'",
     540             :             &err);
     541         530 :         if (err == OGRERR_NONE)
     542          57 :             return nSRSId;
     543             : 
     544             :         // The below WKT definitions are somehow questionable (using a unknown
     545             :         // unit). For GDAL >= 3.9, they won't be used. They will only be used
     546             :         // for earlier versions.
     547             :         const char *pszSQL;
     548             : #define UNDEFINED_CRS_SRS_ID 99999
     549             :         static_assert(UNDEFINED_CRS_SRS_ID == FIRST_CUSTOM_SRSID - 1);
     550             : #define STRINGIFY(x) #x
     551             : #define XSTRINGIFY(x) STRINGIFY(x)
     552         473 :         if (m_bHasDefinition12_063)
     553             :         {
     554             :             /* clang-format off */
     555           1 :             pszSQL =
     556             :                 "INSERT INTO gpkg_spatial_ref_sys "
     557             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     558             :                 "definition, definition_12_063, description) VALUES "
     559             :                 "('Undefined SRS'," XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ",'GDAL',"
     560             :                 XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ","
     561             :                 "'LOCAL_CS[\"Undefined SRS\",LOCAL_DATUM[\"unknown\",32767],"
     562             :                 "UNIT[\"unknown\",0],AXIS[\"Easting\",EAST],"
     563             :                 "AXIS[\"Northing\",NORTH]]',"
     564             :                 "'ENGCRS[\"Undefined SRS\",EDATUM[\"unknown\"],CS[Cartesian,2],"
     565             :                 "AXIS[\"easting\",east,ORDER[1],LENGTHUNIT[\"unknown\",0]],"
     566             :                 "AXIS[\"northing\",north,ORDER[2],LENGTHUNIT[\"unknown\",0]]]',"
     567             :                 "'Custom undefined coordinate reference system')";
     568             :             /* clang-format on */
     569             :         }
     570             :         else
     571             :         {
     572             :             /* clang-format off */
     573         472 :             pszSQL =
     574             :                 "INSERT INTO gpkg_spatial_ref_sys "
     575             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     576             :                 "definition, description) VALUES "
     577             :                 "('Undefined SRS'," XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ",'GDAL',"
     578             :                 XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ","
     579             :                 "'LOCAL_CS[\"Undefined SRS\",LOCAL_DATUM[\"unknown\",32767],"
     580             :                 "UNIT[\"unknown\",0],AXIS[\"Easting\",EAST],"
     581             :                 "AXIS[\"Northing\",NORTH]]',"
     582             :                 "'Custom undefined coordinate reference system')";
     583             :             /* clang-format on */
     584             :         }
     585         473 :         if (SQLCommand(hDB, pszSQL) == OGRERR_NONE)
     586         473 :             return UNDEFINED_CRS_SRS_ID;
     587             : #undef UNDEFINED_CRS_SRS_ID
     588             : #undef XSTRINGIFY
     589             : #undef STRINGIFY
     590           0 :         return -1;
     591             :     }
     592             : 
     593         818 :     std::unique_ptr<OGRSpatialReference> poSRS(poSRSIn->Clone());
     594             : 
     595         409 :     if (poSRS->IsGeographic() || poSRS->IsLocal())
     596             :     {
     597             :         // See corresponding tests in GDALGeoPackageDataset::GetSpatialRef
     598         140 :         if (pszName != nullptr && strlen(pszName) > 0)
     599             :         {
     600         140 :             if (EQUAL(pszName, "Undefined geographic SRS"))
     601           2 :                 return 0;
     602             : 
     603         138 :             if (EQUAL(pszName, "Undefined Cartesian SRS"))
     604           1 :                 return -1;
     605             :         }
     606             :     }
     607             : 
     608         406 :     const char *pszAuthorityName = poSRS->GetAuthorityName(nullptr);
     609             : 
     610         406 :     if (pszAuthorityName == nullptr || strlen(pszAuthorityName) == 0)
     611             :     {
     612             :         // Try to force identify an EPSG code.
     613          26 :         poSRS->AutoIdentifyEPSG();
     614             : 
     615          26 :         pszAuthorityName = poSRS->GetAuthorityName(nullptr);
     616          26 :         if (pszAuthorityName != nullptr && EQUAL(pszAuthorityName, "EPSG"))
     617             :         {
     618           0 :             const char *pszAuthorityCode = poSRS->GetAuthorityCode(nullptr);
     619           0 :             if (pszAuthorityCode != nullptr && strlen(pszAuthorityCode) > 0)
     620             :             {
     621             :                 /* Import 'clean' SRS */
     622           0 :                 poSRS->importFromEPSG(atoi(pszAuthorityCode));
     623             : 
     624           0 :                 pszAuthorityName = poSRS->GetAuthorityName(nullptr);
     625             :             }
     626             :         }
     627             : 
     628          26 :         poSRS->SetCoordinateEpoch(poSRSIn->GetCoordinateEpoch());
     629             :     }
     630             : 
     631             :     // Check whether the EPSG authority code is already mapped to a
     632             :     // SRS ID.
     633         406 :     char *pszSQL = nullptr;
     634         406 :     int nSRSId = DEFAULT_SRID;
     635         406 :     int nAuthorityCode = 0;
     636         406 :     OGRErr err = OGRERR_NONE;
     637         406 :     bool bCanUseAuthorityCode = false;
     638         406 :     const char *const apszIsSameOptions[] = {
     639             :         "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES",
     640             :         "IGNORE_COORDINATE_EPOCH=YES", nullptr};
     641         406 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0)
     642             :     {
     643         380 :         const char *pszAuthorityCode = poSRS->GetAuthorityCode(nullptr);
     644         380 :         if (pszAuthorityCode)
     645             :         {
     646         380 :             if (CPLGetValueType(pszAuthorityCode) == CPL_VALUE_INTEGER)
     647             :             {
     648         380 :                 nAuthorityCode = atoi(pszAuthorityCode);
     649             :             }
     650             :             else
     651             :             {
     652           0 :                 CPLDebug("GPKG",
     653             :                          "SRS has %s:%s identification, but the code not "
     654             :                          "being an integer value cannot be stored as such "
     655             :                          "in the database.",
     656             :                          pszAuthorityName, pszAuthorityCode);
     657           0 :                 pszAuthorityName = nullptr;
     658             :             }
     659             :         }
     660             :     }
     661             : 
     662         786 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     663         380 :         poSRSIn->GetCoordinateEpoch() == 0)
     664             :     {
     665             :         pszSQL =
     666         375 :             sqlite3_mprintf("SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     667             :                             "upper(organization) = upper('%q') AND "
     668             :                             "organization_coordsys_id = %d",
     669             :                             pszAuthorityName, nAuthorityCode);
     670             : 
     671         375 :         nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     672         375 :         sqlite3_free(pszSQL);
     673             : 
     674             :         // Got a match? Return it!
     675         375 :         if (OGRERR_NONE == err)
     676             :         {
     677         117 :             auto poRefSRS = GetSpatialRef(nSRSId);
     678             :             bool bOK =
     679         117 :                 (poRefSRS == nullptr ||
     680         118 :                  poSRS->IsSame(poRefSRS.get(), apszIsSameOptions) ||
     681           1 :                  !CPLTestBool(CPLGetConfigOption("OGR_GPKG_CHECK_SRS", "YES")));
     682         117 :             if (bOK)
     683             :             {
     684         116 :                 return nSRSId;
     685             :             }
     686             :             else
     687             :             {
     688           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
     689             :                          "Passed SRS uses %s:%d identification, but its "
     690             :                          "definition is not compatible with the "
     691             :                          "definition of that object already in the database. "
     692             :                          "Registering it as a new entry into the database.",
     693             :                          pszAuthorityName, nAuthorityCode);
     694           1 :                 pszAuthorityName = nullptr;
     695           1 :                 nAuthorityCode = 0;
     696             :             }
     697             :         }
     698             :     }
     699             : 
     700             :     // Translate SRS to WKT.
     701         290 :     CPLCharUniquePtr pszWKT1;
     702         290 :     CPLCharUniquePtr pszWKT2_2015;
     703         290 :     CPLCharUniquePtr pszWKT2_2019;
     704         290 :     const char *const apszOptionsWkt1[] = {"FORMAT=WKT1_GDAL", nullptr};
     705         290 :     const char *const apszOptionsWkt2_2015[] = {"FORMAT=WKT2_2015", nullptr};
     706         290 :     const char *const apszOptionsWkt2_2019[] = {"FORMAT=WKT2_2019", nullptr};
     707             : 
     708         580 :     std::string osEpochTest;
     709         290 :     if (poSRSIn->GetCoordinateEpoch() > 0 && m_bHasEpochColumn)
     710             :     {
     711             :         osEpochTest =
     712           3 :             CPLSPrintf(" AND epoch = %.17g", poSRSIn->GetCoordinateEpoch());
     713             :     }
     714             : 
     715         571 :     if (!(poSRS->IsGeographic() && poSRS->GetAxesCount() == 3) &&
     716         281 :         !poSRS->IsDerivedGeographic())
     717             :     {
     718         562 :         CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
     719         281 :         char *pszTmp = nullptr;
     720         281 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt1);
     721         281 :         pszWKT1.reset(pszTmp);
     722         281 :         if (pszWKT1 && pszWKT1.get()[0] == '\0')
     723             :         {
     724           0 :             pszWKT1.reset();
     725             :         }
     726             :     }
     727             :     {
     728         580 :         CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
     729         290 :         char *pszTmp = nullptr;
     730         290 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2015);
     731         290 :         pszWKT2_2015.reset(pszTmp);
     732         290 :         if (pszWKT2_2015 && pszWKT2_2015.get()[0] == '\0')
     733             :         {
     734           0 :             pszWKT2_2015.reset();
     735             :         }
     736             :     }
     737             :     {
     738         290 :         char *pszTmp = nullptr;
     739         290 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2019);
     740         290 :         pszWKT2_2019.reset(pszTmp);
     741         290 :         if (pszWKT2_2019 && pszWKT2_2019.get()[0] == '\0')
     742             :         {
     743           0 :             pszWKT2_2019.reset();
     744             :         }
     745             :     }
     746             : 
     747         290 :     if (!pszWKT1 && !pszWKT2_2015 && !pszWKT2_2019)
     748             :     {
     749           0 :         return DEFAULT_SRID;
     750             :     }
     751             : 
     752         290 :     if (poSRSIn->GetCoordinateEpoch() == 0 || m_bHasEpochColumn)
     753             :     {
     754             :         // Search if there is already an existing entry with this WKT
     755         287 :         if (m_bHasDefinition12_063 && (pszWKT2_2015 || pszWKT2_2019))
     756             :         {
     757          42 :             if (pszWKT1)
     758             :             {
     759         144 :                 pszSQL = sqlite3_mprintf(
     760             :                     "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     761             :                     "(definition = '%q' OR definition_12_063 IN ('%q','%q'))%s",
     762             :                     pszWKT1.get(),
     763          72 :                     pszWKT2_2015 ? pszWKT2_2015.get() : "invalid",
     764          72 :                     pszWKT2_2019 ? pszWKT2_2019.get() : "invalid",
     765             :                     osEpochTest.c_str());
     766             :             }
     767             :             else
     768             :             {
     769          24 :                 pszSQL = sqlite3_mprintf(
     770             :                     "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     771             :                     "definition_12_063 IN ('%q', '%q')%s",
     772          12 :                     pszWKT2_2015 ? pszWKT2_2015.get() : "invalid",
     773          12 :                     pszWKT2_2019 ? pszWKT2_2019.get() : "invalid",
     774             :                     osEpochTest.c_str());
     775             :             }
     776             :         }
     777         245 :         else if (pszWKT1)
     778             :         {
     779             :             pszSQL =
     780         242 :                 sqlite3_mprintf("SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     781             :                                 "definition = '%q'%s",
     782             :                                 pszWKT1.get(), osEpochTest.c_str());
     783             :         }
     784             :         else
     785             :         {
     786           3 :             pszSQL = nullptr;
     787             :         }
     788         287 :         if (pszSQL)
     789             :         {
     790         284 :             nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     791         284 :             sqlite3_free(pszSQL);
     792         284 :             if (OGRERR_NONE == err)
     793             :             {
     794           5 :                 return nSRSId;
     795             :             }
     796             :         }
     797             :     }
     798             : 
     799         546 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     800         261 :         poSRSIn->GetCoordinateEpoch() == 0)
     801             :     {
     802         257 :         bool bTryToReuseSRSId = true;
     803         257 :         if (EQUAL(pszAuthorityName, "EPSG"))
     804             :         {
     805         512 :             OGRSpatialReference oSRS_EPSG;
     806         256 :             if (GDALGPKGImportFromEPSG(&oSRS_EPSG, nAuthorityCode) ==
     807             :                 OGRERR_NONE)
     808             :             {
     809         257 :                 if (!poSRS->IsSame(&oSRS_EPSG, apszIsSameOptions) &&
     810           1 :                     CPLTestBool(
     811             :                         CPLGetConfigOption("OGR_GPKG_CHECK_SRS", "YES")))
     812             :                 {
     813           1 :                     bTryToReuseSRSId = false;
     814           1 :                     CPLError(
     815             :                         CE_Warning, CPLE_AppDefined,
     816             :                         "Passed SRS uses %s:%d identification, but its "
     817             :                         "definition is not compatible with the "
     818             :                         "official definition of the object. "
     819             :                         "Registering it as a non-%s entry into the database.",
     820             :                         pszAuthorityName, nAuthorityCode, pszAuthorityName);
     821           1 :                     pszAuthorityName = nullptr;
     822           1 :                     nAuthorityCode = 0;
     823             :                 }
     824             :             }
     825             :         }
     826         257 :         if (bTryToReuseSRSId)
     827             :         {
     828             :             // No match, but maybe we can use the nAuthorityCode as the nSRSId?
     829         256 :             pszSQL = sqlite3_mprintf(
     830             :                 "SELECT Count(*) FROM gpkg_spatial_ref_sys WHERE "
     831             :                 "srs_id = %d",
     832             :                 nAuthorityCode);
     833             : 
     834             :             // Yep, we can!
     835         256 :             if (SQLGetInteger(hDB, pszSQL, nullptr) == 0)
     836         255 :                 bCanUseAuthorityCode = true;
     837         256 :             sqlite3_free(pszSQL);
     838             :         }
     839             :     }
     840             : 
     841         285 :     bool bConvertGpkgSpatialRefSysToExtensionWkt2 = false;
     842         285 :     bool bForceEpoch = false;
     843         288 :     if (!m_bHasDefinition12_063 && pszWKT1 == nullptr &&
     844           3 :         (pszWKT2_2015 != nullptr || pszWKT2_2019 != nullptr))
     845             :     {
     846           3 :         bConvertGpkgSpatialRefSysToExtensionWkt2 = true;
     847             :     }
     848             : 
     849             :     // Add epoch column if needed
     850         285 :     if (poSRSIn->GetCoordinateEpoch() > 0 && !m_bHasEpochColumn)
     851             :     {
     852           3 :         if (m_bHasDefinition12_063)
     853             :         {
     854           0 :             if (SoftStartTransaction() != OGRERR_NONE)
     855           0 :                 return DEFAULT_SRID;
     856           0 :             if (SQLCommand(hDB, "ALTER TABLE gpkg_spatial_ref_sys "
     857           0 :                                 "ADD COLUMN epoch DOUBLE") != OGRERR_NONE ||
     858           0 :                 SQLCommand(hDB, "UPDATE gpkg_extensions SET extension_name = "
     859             :                                 "'gpkg_crs_wkt_1_1' "
     860             :                                 "WHERE extension_name = 'gpkg_crs_wkt'") !=
     861           0 :                     OGRERR_NONE ||
     862           0 :                 SQLCommand(
     863             :                     hDB,
     864             :                     "INSERT INTO gpkg_extensions "
     865             :                     "(table_name, column_name, extension_name, definition, "
     866             :                     "scope) "
     867             :                     "VALUES "
     868             :                     "('gpkg_spatial_ref_sys', 'epoch', 'gpkg_crs_wkt_1_1', "
     869             :                     "'http://www.geopackage.org/spec/#extension_crs_wkt', "
     870             :                     "'read-write')") != OGRERR_NONE)
     871             :             {
     872           0 :                 SoftRollbackTransaction();
     873           0 :                 return DEFAULT_SRID;
     874             :             }
     875             : 
     876           0 :             if (SoftCommitTransaction() != OGRERR_NONE)
     877           0 :                 return DEFAULT_SRID;
     878             : 
     879           0 :             m_bHasEpochColumn = true;
     880             :         }
     881             :         else
     882             :         {
     883           3 :             bConvertGpkgSpatialRefSysToExtensionWkt2 = true;
     884           3 :             bForceEpoch = true;
     885             :         }
     886             :     }
     887             : 
     888         291 :     if (bConvertGpkgSpatialRefSysToExtensionWkt2 &&
     889           6 :         !ConvertGpkgSpatialRefSysToExtensionWkt2(bForceEpoch))
     890             :     {
     891           0 :         return DEFAULT_SRID;
     892             :     }
     893             : 
     894             :     // Reuse the authority code number as SRS_ID if we can
     895         285 :     if (bCanUseAuthorityCode)
     896             :     {
     897         255 :         nSRSId = nAuthorityCode;
     898             :     }
     899             :     // Otherwise, generate a new SRS_ID number (max + 1)
     900             :     else
     901             :     {
     902             :         // Get the current maximum srid in the srs table.
     903          30 :         const int nMaxSRSId = SQLGetInteger(
     904             :             hDB, "SELECT MAX(srs_id) FROM gpkg_spatial_ref_sys", nullptr);
     905          30 :         nSRSId = std::max(FIRST_CUSTOM_SRSID, nMaxSRSId + 1);
     906             :     }
     907             : 
     908         570 :     std::string osEpochColumn;
     909         285 :     std::string osEpochVal;
     910         285 :     if (poSRSIn->GetCoordinateEpoch() > 0)
     911             :     {
     912           5 :         osEpochColumn = ", epoch";
     913           5 :         osEpochVal = CPLSPrintf(", %.17g", poSRSIn->GetCoordinateEpoch());
     914             :     }
     915             : 
     916             :     // Add new SRS row to gpkg_spatial_ref_sys.
     917         285 :     if (m_bHasDefinition12_063)
     918             :     {
     919             :         // Force WKT2_2019 when we have a dynamic CRS and coordinate epoch
     920          45 :         const char *pszWKT2 = poSRSIn->IsDynamic() &&
     921          10 :                                       poSRSIn->GetCoordinateEpoch() > 0 &&
     922           1 :                                       pszWKT2_2019
     923           1 :                                   ? pszWKT2_2019.get()
     924          44 :                               : pszWKT2_2015 ? pszWKT2_2015.get()
     925          97 :                                              : pszWKT2_2019.get();
     926             : 
     927          45 :         if (pszAuthorityName != nullptr && nAuthorityCode > 0)
     928             :         {
     929          99 :             pszSQL = sqlite3_mprintf(
     930             :                 "INSERT INTO gpkg_spatial_ref_sys "
     931             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     932             :                 "definition, definition_12_063%s) VALUES "
     933             :                 "('%q', %d, upper('%q'), %d, '%q', '%q'%s)",
     934          33 :                 osEpochColumn.c_str(), GetSrsName(*poSRS), nSRSId,
     935             :                 pszAuthorityName, nAuthorityCode,
     936          62 :                 pszWKT1 ? pszWKT1.get() : "undefined",
     937             :                 pszWKT2 ? pszWKT2 : "undefined", osEpochVal.c_str());
     938             :         }
     939             :         else
     940             :         {
     941          36 :             pszSQL = sqlite3_mprintf(
     942             :                 "INSERT INTO gpkg_spatial_ref_sys "
     943             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     944             :                 "definition, definition_12_063%s) VALUES "
     945             :                 "('%q', %d, upper('%q'), %d, '%q', '%q'%s)",
     946          12 :                 osEpochColumn.c_str(), GetSrsName(*poSRS), nSRSId, "NONE",
     947          21 :                 nSRSId, pszWKT1 ? pszWKT1.get() : "undefined",
     948             :                 pszWKT2 ? pszWKT2 : "undefined", osEpochVal.c_str());
     949             :         }
     950             :     }
     951             :     else
     952             :     {
     953         240 :         if (pszAuthorityName != nullptr && nAuthorityCode > 0)
     954             :         {
     955         454 :             pszSQL = sqlite3_mprintf(
     956             :                 "INSERT INTO gpkg_spatial_ref_sys "
     957             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     958             :                 "definition) VALUES ('%q', %d, upper('%q'), %d, '%q')",
     959         227 :                 GetSrsName(*poSRS), nSRSId, pszAuthorityName, nAuthorityCode,
     960         454 :                 pszWKT1 ? pszWKT1.get() : "undefined");
     961             :         }
     962             :         else
     963             :         {
     964          26 :             pszSQL = sqlite3_mprintf(
     965             :                 "INSERT INTO gpkg_spatial_ref_sys "
     966             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     967             :                 "definition) VALUES ('%q', %d, upper('%q'), %d, '%q')",
     968          13 :                 GetSrsName(*poSRS), nSRSId, "NONE", nSRSId,
     969          26 :                 pszWKT1 ? pszWKT1.get() : "undefined");
     970             :         }
     971             :     }
     972             : 
     973             :     // Add new row to gpkg_spatial_ref_sys.
     974         285 :     CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
     975             : 
     976             :     // Free everything that was allocated.
     977         285 :     sqlite3_free(pszSQL);
     978             : 
     979         285 :     return nSRSId;
     980             : }
     981             : 
     982             : /************************************************************************/
     983             : /*                       ~GDALGeoPackageDataset()                       */
     984             : /************************************************************************/
     985             : 
     986        5256 : GDALGeoPackageDataset::~GDALGeoPackageDataset()
     987             : {
     988        2628 :     GDALGeoPackageDataset::Close();
     989        5256 : }
     990             : 
     991             : /************************************************************************/
     992             : /*                              Close()                                 */
     993             : /************************************************************************/
     994             : 
     995        4416 : CPLErr GDALGeoPackageDataset::Close(GDALProgressFunc, void *)
     996             : {
     997        4416 :     CPLErr eErr = CE_None;
     998        4416 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     999             :     {
    1000        1545 :         if (eAccess == GA_Update && m_poParentDS == nullptr &&
    1001        4173 :             !m_osRasterTable.empty() && !m_bGeoTransformValid)
    1002             :         {
    1003           3 :             CPLError(CE_Failure, CPLE_AppDefined,
    1004             :                      "Raster table %s not correctly initialized due to missing "
    1005             :                      "call to SetGeoTransform()",
    1006             :                      m_osRasterTable.c_str());
    1007             :         }
    1008             : 
    1009        5247 :         if (!IsMarkedSuppressOnClose() &&
    1010        2619 :             GDALGeoPackageDataset::FlushCache(true) != CE_None)
    1011             :         {
    1012           7 :             eErr = CE_Failure;
    1013             :         }
    1014             : 
    1015             :         // Destroy bands now since we don't want
    1016             :         // GDALGPKGMBTilesLikeRasterBand::FlushCache() to run after dataset
    1017             :         // destruction
    1018        4445 :         for (int i = 0; i < nBands; i++)
    1019        1817 :             delete papoBands[i];
    1020        2628 :         nBands = 0;
    1021        2628 :         CPLFree(papoBands);
    1022        2628 :         papoBands = nullptr;
    1023             : 
    1024             :         // Destroy overviews before cleaning m_hTempDB as they could still
    1025             :         // need it
    1026        2628 :         m_apoOverviewDS.clear();
    1027             : 
    1028        2628 :         if (m_poParentDS)
    1029             :         {
    1030         325 :             hDB = nullptr;
    1031             :         }
    1032             : 
    1033        2628 :         m_apoLayers.clear();
    1034             : 
    1035             :         std::map<int, OGRSpatialReference *>::iterator oIter =
    1036        2628 :             m_oMapSrsIdToSrs.begin();
    1037        3801 :         for (; oIter != m_oMapSrsIdToSrs.end(); ++oIter)
    1038             :         {
    1039        1173 :             OGRSpatialReference *poSRS = oIter->second;
    1040        1173 :             if (poSRS)
    1041         714 :                 poSRS->Release();
    1042             :         }
    1043             : 
    1044        2628 :         if (!CloseDB())
    1045           0 :             eErr = CE_Failure;
    1046             : 
    1047        2628 :         if (OGRSQLiteBaseDataSource::Close() != CE_None)
    1048           0 :             eErr = CE_Failure;
    1049             :     }
    1050        4416 :     return eErr;
    1051             : }
    1052             : 
    1053             : /************************************************************************/
    1054             : /*                         ICanIWriteBlock()                            */
    1055             : /************************************************************************/
    1056             : 
    1057        5696 : bool GDALGeoPackageDataset::ICanIWriteBlock()
    1058             : {
    1059        5696 :     if (!GetUpdate())
    1060             :     {
    1061           0 :         CPLError(
    1062             :             CE_Failure, CPLE_NotSupported,
    1063             :             "IWriteBlock() not supported on dataset opened in read-only mode");
    1064           0 :         return false;
    1065             :     }
    1066             : 
    1067        5696 :     if (m_pabyCachedTiles == nullptr)
    1068             :     {
    1069           0 :         return false;
    1070             :     }
    1071             : 
    1072        5696 :     if (!m_bGeoTransformValid || m_nSRID == UNKNOWN_SRID)
    1073             :     {
    1074           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    1075             :                  "IWriteBlock() not supported if georeferencing not set");
    1076           0 :         return false;
    1077             :     }
    1078        5696 :     return true;
    1079             : }
    1080             : 
    1081             : /************************************************************************/
    1082             : /*                            IRasterIO()                               */
    1083             : /************************************************************************/
    1084             : 
    1085         132 : CPLErr GDALGeoPackageDataset::IRasterIO(
    1086             :     GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
    1087             :     void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
    1088             :     int nBandCount, BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
    1089             :     GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg)
    1090             : 
    1091             : {
    1092         132 :     CPLErr eErr = OGRSQLiteBaseDataSource::IRasterIO(
    1093             :         eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    1094             :         eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
    1095             :         psExtraArg);
    1096             : 
    1097             :     // If writing all bands, in non-shifted mode, flush all entirely written
    1098             :     // tiles This can avoid "stressing" the block cache with too many dirty
    1099             :     // blocks. Note: this logic would be useless with a per-dataset block cache.
    1100         132 :     if (eErr == CE_None && eRWFlag == GF_Write && nXSize == nBufXSize &&
    1101         123 :         nYSize == nBufYSize && nBandCount == nBands &&
    1102         120 :         m_nShiftXPixelsMod == 0 && m_nShiftYPixelsMod == 0)
    1103             :     {
    1104             :         auto poBand =
    1105         116 :             cpl::down_cast<GDALGPKGMBTilesLikeRasterBand *>(GetRasterBand(1));
    1106             :         int nBlockXSize, nBlockYSize;
    1107         116 :         poBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
    1108         116 :         const int nBlockXStart = DIV_ROUND_UP(nXOff, nBlockXSize);
    1109         116 :         const int nBlockYStart = DIV_ROUND_UP(nYOff, nBlockYSize);
    1110         116 :         const int nBlockXEnd = (nXOff + nXSize) / nBlockXSize;
    1111         116 :         const int nBlockYEnd = (nYOff + nYSize) / nBlockYSize;
    1112         270 :         for (int nBlockY = nBlockXStart; nBlockY < nBlockYEnd; nBlockY++)
    1113             :         {
    1114        4371 :             for (int nBlockX = nBlockYStart; nBlockX < nBlockXEnd; nBlockX++)
    1115             :             {
    1116             :                 GDALRasterBlock *poBlock =
    1117        4217 :                     poBand->AccessibleTryGetLockedBlockRef(nBlockX, nBlockY);
    1118        4217 :                 if (poBlock)
    1119             :                 {
    1120             :                     // GetDirty() should be true in most situation (otherwise
    1121             :                     // it means the block cache is under extreme pressure!)
    1122        4215 :                     if (poBlock->GetDirty())
    1123             :                     {
    1124             :                         // IWriteBlock() on one band will check the dirty state
    1125             :                         // of the corresponding blocks in other bands, to decide
    1126             :                         // if it can call WriteTile(), so we have only to do
    1127             :                         // that on one of the bands
    1128        4215 :                         if (poBlock->Write() != CE_None)
    1129         250 :                             eErr = CE_Failure;
    1130             :                     }
    1131        4215 :                     poBlock->DropLock();
    1132             :                 }
    1133             :             }
    1134             :         }
    1135             :     }
    1136             : 
    1137         132 :     return eErr;
    1138             : }
    1139             : 
    1140             : /************************************************************************/
    1141             : /*                          GetOGRTableLimit()                          */
    1142             : /************************************************************************/
    1143             : 
    1144        4261 : static int GetOGRTableLimit()
    1145             : {
    1146        4261 :     return atoi(CPLGetConfigOption("OGR_TABLE_LIMIT", "10000"));
    1147             : }
    1148             : 
    1149             : /************************************************************************/
    1150             : /*                      GetNameTypeMapFromSQliteMaster()                */
    1151             : /************************************************************************/
    1152             : 
    1153             : const std::map<CPLString, CPLString> &
    1154        1319 : GDALGeoPackageDataset::GetNameTypeMapFromSQliteMaster()
    1155             : {
    1156        1319 :     if (!m_oMapNameToType.empty())
    1157         348 :         return m_oMapNameToType;
    1158             : 
    1159             :     CPLString osSQL(
    1160             :         "SELECT name, type FROM sqlite_master WHERE "
    1161             :         "type IN ('view', 'table') OR "
    1162        1942 :         "(name LIKE 'trigger_%_feature_count_%' AND type = 'trigger')");
    1163         971 :     const int nTableLimit = GetOGRTableLimit();
    1164         971 :     if (nTableLimit > 0)
    1165             :     {
    1166         971 :         osSQL += " LIMIT ";
    1167         971 :         osSQL += CPLSPrintf("%d", 1 + 3 * nTableLimit);
    1168             :     }
    1169             : 
    1170         971 :     auto oResult = SQLQuery(hDB, osSQL);
    1171         971 :     if (oResult)
    1172             :     {
    1173       16112 :         for (int i = 0; i < oResult->RowCount(); i++)
    1174             :         {
    1175       15141 :             const char *pszName = oResult->GetValue(0, i);
    1176       15141 :             const char *pszType = oResult->GetValue(1, i);
    1177       15141 :             m_oMapNameToType[CPLString(pszName).toupper()] = pszType;
    1178             :         }
    1179             :     }
    1180             : 
    1181         971 :     return m_oMapNameToType;
    1182             : }
    1183             : 
    1184             : /************************************************************************/
    1185             : /*                    RemoveTableFromSQLiteMasterCache()                */
    1186             : /************************************************************************/
    1187             : 
    1188          57 : void GDALGeoPackageDataset::RemoveTableFromSQLiteMasterCache(
    1189             :     const char *pszTableName)
    1190             : {
    1191          57 :     m_oMapNameToType.erase(CPLString(pszTableName).toupper());
    1192          57 : }
    1193             : 
    1194             : /************************************************************************/
    1195             : /*                  GetUnknownExtensionsTableSpecific()                 */
    1196             : /************************************************************************/
    1197             : 
    1198             : const std::map<CPLString, std::vector<GPKGExtensionDesc>> &
    1199         923 : GDALGeoPackageDataset::GetUnknownExtensionsTableSpecific()
    1200             : {
    1201         923 :     if (m_bMapTableToExtensionsBuilt)
    1202          92 :         return m_oMapTableToExtensions;
    1203         831 :     m_bMapTableToExtensionsBuilt = true;
    1204             : 
    1205         831 :     if (!HasExtensionsTable())
    1206          52 :         return m_oMapTableToExtensions;
    1207             : 
    1208             :     CPLString osSQL(
    1209             :         "SELECT table_name, extension_name, definition, scope "
    1210             :         "FROM gpkg_extensions WHERE "
    1211             :         "table_name IS NOT NULL "
    1212             :         "AND extension_name IS NOT NULL "
    1213             :         "AND definition IS NOT NULL "
    1214             :         "AND scope IS NOT NULL "
    1215             :         "AND extension_name NOT IN ('gpkg_geom_CIRCULARSTRING', "
    1216             :         "'gpkg_geom_COMPOUNDCURVE', 'gpkg_geom_CURVEPOLYGON', "
    1217             :         "'gpkg_geom_MULTICURVE', "
    1218             :         "'gpkg_geom_MULTISURFACE', 'gpkg_geom_CURVE', 'gpkg_geom_SURFACE', "
    1219             :         "'gpkg_geom_POLYHEDRALSURFACE', 'gpkg_geom_TIN', 'gpkg_geom_TRIANGLE', "
    1220             :         "'gpkg_rtree_index', 'gpkg_geometry_type_trigger', "
    1221             :         "'gpkg_srs_id_trigger', "
    1222             :         "'gpkg_crs_wkt', 'gpkg_crs_wkt_1_1', 'gpkg_schema', "
    1223             :         "'gpkg_related_tables', 'related_tables'"
    1224             : #ifdef HAVE_SPATIALITE
    1225             :         ", 'gdal_spatialite_computed_geom_column'"
    1226             : #endif
    1227        1558 :         ")");
    1228         779 :     const int nTableLimit = GetOGRTableLimit();
    1229         779 :     if (nTableLimit > 0)
    1230             :     {
    1231         779 :         osSQL += " LIMIT ";
    1232         779 :         osSQL += CPLSPrintf("%d", 1 + 10 * nTableLimit);
    1233             :     }
    1234             : 
    1235         779 :     auto oResult = SQLQuery(hDB, osSQL);
    1236         779 :     if (oResult)
    1237             :     {
    1238        1444 :         for (int i = 0; i < oResult->RowCount(); i++)
    1239             :         {
    1240         665 :             const char *pszTableName = oResult->GetValue(0, i);
    1241         665 :             const char *pszExtensionName = oResult->GetValue(1, i);
    1242         665 :             const char *pszDefinition = oResult->GetValue(2, i);
    1243         665 :             const char *pszScope = oResult->GetValue(3, i);
    1244         665 :             if (pszTableName && pszExtensionName && pszDefinition && pszScope)
    1245             :             {
    1246         665 :                 GPKGExtensionDesc oDesc;
    1247         665 :                 oDesc.osExtensionName = pszExtensionName;
    1248         665 :                 oDesc.osDefinition = pszDefinition;
    1249         665 :                 oDesc.osScope = pszScope;
    1250        1330 :                 m_oMapTableToExtensions[CPLString(pszTableName).toupper()]
    1251         665 :                     .push_back(std::move(oDesc));
    1252             :             }
    1253             :         }
    1254             :     }
    1255             : 
    1256         779 :     return m_oMapTableToExtensions;
    1257             : }
    1258             : 
    1259             : /************************************************************************/
    1260             : /*                           GetContents()                              */
    1261             : /************************************************************************/
    1262             : 
    1263             : const std::map<CPLString, GPKGContentsDesc> &
    1264         905 : GDALGeoPackageDataset::GetContents()
    1265             : {
    1266         905 :     if (m_bMapTableToContentsBuilt)
    1267          76 :         return m_oMapTableToContents;
    1268         829 :     m_bMapTableToContentsBuilt = true;
    1269             : 
    1270             :     CPLString osSQL("SELECT table_name, data_type, identifier, "
    1271             :                     "description, min_x, min_y, max_x, max_y "
    1272        1658 :                     "FROM gpkg_contents");
    1273         829 :     const int nTableLimit = GetOGRTableLimit();
    1274         829 :     if (nTableLimit > 0)
    1275             :     {
    1276         829 :         osSQL += " LIMIT ";
    1277         829 :         osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1278             :     }
    1279             : 
    1280         829 :     auto oResult = SQLQuery(hDB, osSQL);
    1281         829 :     if (oResult)
    1282             :     {
    1283        1779 :         for (int i = 0; i < oResult->RowCount(); i++)
    1284             :         {
    1285         950 :             const char *pszTableName = oResult->GetValue(0, i);
    1286         950 :             if (pszTableName == nullptr)
    1287           0 :                 continue;
    1288         950 :             const char *pszDataType = oResult->GetValue(1, i);
    1289         950 :             const char *pszIdentifier = oResult->GetValue(2, i);
    1290         950 :             const char *pszDescription = oResult->GetValue(3, i);
    1291         950 :             const char *pszMinX = oResult->GetValue(4, i);
    1292         950 :             const char *pszMinY = oResult->GetValue(5, i);
    1293         950 :             const char *pszMaxX = oResult->GetValue(6, i);
    1294         950 :             const char *pszMaxY = oResult->GetValue(7, i);
    1295         950 :             GPKGContentsDesc oDesc;
    1296         950 :             if (pszDataType)
    1297         950 :                 oDesc.osDataType = pszDataType;
    1298         950 :             if (pszIdentifier)
    1299         950 :                 oDesc.osIdentifier = pszIdentifier;
    1300         950 :             if (pszDescription)
    1301         949 :                 oDesc.osDescription = pszDescription;
    1302         950 :             if (pszMinX)
    1303         637 :                 oDesc.osMinX = pszMinX;
    1304         950 :             if (pszMinY)
    1305         637 :                 oDesc.osMinY = pszMinY;
    1306         950 :             if (pszMaxX)
    1307         637 :                 oDesc.osMaxX = pszMaxX;
    1308         950 :             if (pszMaxY)
    1309         637 :                 oDesc.osMaxY = pszMaxY;
    1310        1900 :             m_oMapTableToContents[CPLString(pszTableName).toupper()] =
    1311        1900 :                 std::move(oDesc);
    1312             :         }
    1313             :     }
    1314             : 
    1315         829 :     return m_oMapTableToContents;
    1316             : }
    1317             : 
    1318             : /************************************************************************/
    1319             : /*                                Open()                                */
    1320             : /************************************************************************/
    1321             : 
    1322        1300 : int GDALGeoPackageDataset::Open(GDALOpenInfo *poOpenInfo,
    1323             :                                 const std::string &osFilenameInZip)
    1324             : {
    1325        1300 :     m_osFilenameInZip = osFilenameInZip;
    1326        1300 :     CPLAssert(m_apoLayers.empty());
    1327        1300 :     CPLAssert(hDB == nullptr);
    1328             : 
    1329        1300 :     SetDescription(poOpenInfo->pszFilename);
    1330        2600 :     CPLString osFilename(poOpenInfo->pszFilename);
    1331        2600 :     CPLString osSubdatasetTableName;
    1332             :     GByte abyHeaderLetMeHerePlease[100];
    1333        1300 :     const GByte *pabyHeader = poOpenInfo->pabyHeader;
    1334        1300 :     if (STARTS_WITH_CI(poOpenInfo->pszFilename, "GPKG:"))
    1335             :     {
    1336         248 :         char **papszTokens = CSLTokenizeString2(poOpenInfo->pszFilename, ":",
    1337             :                                                 CSLT_HONOURSTRINGS);
    1338         248 :         int nCount = CSLCount(papszTokens);
    1339         248 :         if (nCount < 2)
    1340             :         {
    1341           0 :             CSLDestroy(papszTokens);
    1342           0 :             return FALSE;
    1343             :         }
    1344             : 
    1345         248 :         if (nCount <= 3)
    1346             :         {
    1347         246 :             osFilename = papszTokens[1];
    1348             :         }
    1349             :         /* GPKG:C:\BLA.GPKG:foo */
    1350           2 :         else if (nCount == 4 && strlen(papszTokens[1]) == 1 &&
    1351           2 :                  (papszTokens[2][0] == '/' || papszTokens[2][0] == '\\'))
    1352             :         {
    1353           2 :             osFilename = CPLString(papszTokens[1]) + ":" + papszTokens[2];
    1354             :         }
    1355             :         // GPKG:/vsicurl/http[s]://[user:passwd@]example.com[:8080]/foo.gpkg:bar
    1356           0 :         else if (/*nCount >= 4 && */
    1357           0 :                  (EQUAL(papszTokens[1], "/vsicurl/http") ||
    1358           0 :                   EQUAL(papszTokens[1], "/vsicurl/https")))
    1359             :         {
    1360           0 :             osFilename = CPLString(papszTokens[1]);
    1361           0 :             for (int i = 2; i < nCount - 1; i++)
    1362             :             {
    1363           0 :                 osFilename += ':';
    1364           0 :                 osFilename += papszTokens[i];
    1365             :             }
    1366             :         }
    1367         248 :         if (nCount >= 3)
    1368          14 :             osSubdatasetTableName = papszTokens[nCount - 1];
    1369             : 
    1370         248 :         CSLDestroy(papszTokens);
    1371         248 :         VSILFILE *fp = VSIFOpenL(osFilename, "rb");
    1372         248 :         if (fp != nullptr)
    1373             :         {
    1374         248 :             VSIFReadL(abyHeaderLetMeHerePlease, 1, 100, fp);
    1375         248 :             VSIFCloseL(fp);
    1376             :         }
    1377         248 :         pabyHeader = abyHeaderLetMeHerePlease;
    1378             :     }
    1379        1052 :     else if (poOpenInfo->pabyHeader &&
    1380        1052 :              STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1381             :                          "SQLite format 3"))
    1382             :     {
    1383        1045 :         m_bCallUndeclareFileNotToOpen = true;
    1384        1045 :         GDALOpenInfoDeclareFileNotToOpen(osFilename, poOpenInfo->pabyHeader,
    1385             :                                          poOpenInfo->nHeaderBytes);
    1386             :     }
    1387             : 
    1388        1300 :     eAccess = poOpenInfo->eAccess;
    1389        1300 :     if (!m_osFilenameInZip.empty())
    1390             :     {
    1391           2 :         m_pszFilename = CPLStrdup(CPLSPrintf(
    1392             :             "/vsizip/{%s}/%s", osFilename.c_str(), m_osFilenameInZip.c_str()));
    1393             :     }
    1394             :     else
    1395             :     {
    1396        1298 :         m_pszFilename = CPLStrdup(osFilename);
    1397             :     }
    1398             : 
    1399        1300 :     if (poOpenInfo->papszOpenOptions)
    1400             :     {
    1401         100 :         CSLDestroy(papszOpenOptions);
    1402         100 :         papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
    1403             :     }
    1404             : 
    1405             : #ifdef ENABLE_SQL_GPKG_FORMAT
    1406        1300 :     if (poOpenInfo->pabyHeader &&
    1407        1052 :         STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1408           5 :                     "-- SQL GPKG") &&
    1409           5 :         poOpenInfo->fpL != nullptr)
    1410             :     {
    1411           5 :         if (sqlite3_open_v2(":memory:", &hDB, SQLITE_OPEN_READWRITE, nullptr) !=
    1412             :             SQLITE_OK)
    1413             :         {
    1414           0 :             return FALSE;
    1415             :         }
    1416             : 
    1417           5 :         InstallSQLFunctions();
    1418             : 
    1419             :         // Ingest the lines of the dump
    1420           5 :         VSIFSeekL(poOpenInfo->fpL, 0, SEEK_SET);
    1421             :         const char *pszLine;
    1422          76 :         while ((pszLine = CPLReadLineL(poOpenInfo->fpL)) != nullptr)
    1423             :         {
    1424          71 :             if (STARTS_WITH(pszLine, "--"))
    1425           5 :                 continue;
    1426             : 
    1427          66 :             if (!SQLCheckLineIsSafe(pszLine))
    1428           0 :                 return false;
    1429             : 
    1430          66 :             char *pszErrMsg = nullptr;
    1431          66 :             if (sqlite3_exec(hDB, pszLine, nullptr, nullptr, &pszErrMsg) !=
    1432             :                 SQLITE_OK)
    1433             :             {
    1434           0 :                 if (pszErrMsg)
    1435           0 :                     CPLDebug("SQLITE", "Error %s", pszErrMsg);
    1436             :             }
    1437          66 :             sqlite3_free(pszErrMsg);
    1438           5 :         }
    1439             :     }
    1440             : 
    1441        1295 :     else if (pabyHeader != nullptr)
    1442             : #endif
    1443             :     {
    1444        1295 :         if (poOpenInfo->fpL)
    1445             :         {
    1446             :             // See above comment about -wal locking for the importance of
    1447             :             // closing that file, prior to calling sqlite3_open()
    1448         947 :             VSIFCloseL(poOpenInfo->fpL);
    1449         947 :             poOpenInfo->fpL = nullptr;
    1450             :         }
    1451             : 
    1452             :         /* See if we can open the SQLite database */
    1453        1295 :         if (!OpenOrCreateDB(GetUpdate() ? SQLITE_OPEN_READWRITE
    1454             :                                         : SQLITE_OPEN_READONLY))
    1455           2 :             return FALSE;
    1456             : 
    1457        1293 :         memcpy(&m_nApplicationId, pabyHeader + knApplicationIdPos, 4);
    1458        1293 :         m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    1459        1293 :         memcpy(&m_nUserVersion, pabyHeader + knUserVersionPos, 4);
    1460        1293 :         m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    1461        1293 :         if (m_nApplicationId == GP10_APPLICATION_ID)
    1462             :         {
    1463           7 :             CPLDebug("GPKG", "GeoPackage v1.0");
    1464             :         }
    1465        1286 :         else if (m_nApplicationId == GP11_APPLICATION_ID)
    1466             :         {
    1467           2 :             CPLDebug("GPKG", "GeoPackage v1.1");
    1468             :         }
    1469        1284 :         else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    1470        1280 :                  m_nUserVersion >= GPKG_1_2_VERSION)
    1471             :         {
    1472        1278 :             CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    1473        1278 :                      (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    1474             :         }
    1475             :     }
    1476             : 
    1477             :     /* Requirement 6: The SQLite PRAGMA integrity_check SQL command SHALL return
    1478             :      * “ok” */
    1479             :     /* http://opengis.github.io/geopackage/#_file_integrity */
    1480             :     /* Disable integrity check by default, since it is expensive on big files */
    1481        1298 :     if (CPLTestBool(CPLGetConfigOption("OGR_GPKG_INTEGRITY_CHECK", "NO")) &&
    1482           0 :         OGRERR_NONE != PragmaCheck("integrity_check", "ok", 1))
    1483             :     {
    1484           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1485             :                  "pragma integrity_check on '%s' failed", m_pszFilename);
    1486           0 :         return FALSE;
    1487             :     }
    1488             : 
    1489             :     /* Requirement 7: The SQLite PRAGMA foreign_key_check() SQL with no */
    1490             :     /* parameter value SHALL return an empty result set */
    1491             :     /* http://opengis.github.io/geopackage/#_file_integrity */
    1492             :     /* Disable the check by default, since it is to corrupt databases, and */
    1493             :     /* that causes issues to downstream software that can't open them. */
    1494        1298 :     if (CPLTestBool(CPLGetConfigOption("OGR_GPKG_FOREIGN_KEY_CHECK", "NO")) &&
    1495           0 :         OGRERR_NONE != PragmaCheck("foreign_key_check", "", 0))
    1496             :     {
    1497           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1498             :                  "pragma foreign_key_check on '%s' failed.", m_pszFilename);
    1499           0 :         return FALSE;
    1500             :     }
    1501             : 
    1502             :     /* Check for requirement metadata tables */
    1503             :     /* Requirement 10: gpkg_spatial_ref_sys must exist */
    1504             :     /* Requirement 13: gpkg_contents must exist */
    1505        1298 :     if (SQLGetInteger(hDB,
    1506             :                       "SELECT COUNT(*) FROM sqlite_master WHERE "
    1507             :                       "name IN ('gpkg_spatial_ref_sys', 'gpkg_contents') AND "
    1508             :                       "type IN ('table', 'view')",
    1509        1298 :                       nullptr) != 2)
    1510             :     {
    1511           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1512             :                  "At least one of the required GeoPackage tables, "
    1513             :                  "gpkg_spatial_ref_sys or gpkg_contents, is missing");
    1514           0 :         return FALSE;
    1515             :     }
    1516             : 
    1517        1298 :     DetectSpatialRefSysColumns();
    1518             : 
    1519             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    1520        1298 :     if (SQLGetInteger(hDB,
    1521             :                       "SELECT 1 FROM sqlite_master WHERE "
    1522             :                       "name = 'gpkg_ogr_contents' AND type = 'table'",
    1523        1298 :                       nullptr) == 1)
    1524             :     {
    1525        1290 :         m_bHasGPKGOGRContents = true;
    1526             :     }
    1527             : #endif
    1528             : 
    1529        1298 :     CheckUnknownExtensions();
    1530             : 
    1531        1298 :     int bRet = FALSE;
    1532        1298 :     bool bHasGPKGExtRelations = false;
    1533        1298 :     if (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR)
    1534             :     {
    1535        1111 :         m_bHasGPKGGeometryColumns =
    1536        1111 :             SQLGetInteger(hDB,
    1537             :                           "SELECT 1 FROM sqlite_master WHERE "
    1538             :                           "name = 'gpkg_geometry_columns' AND "
    1539             :                           "type IN ('table', 'view')",
    1540        1111 :                           nullptr) == 1;
    1541        1111 :         bHasGPKGExtRelations = HasGpkgextRelationsTable();
    1542             :     }
    1543        1298 :     if (m_bHasGPKGGeometryColumns)
    1544             :     {
    1545             :         /* Load layer definitions for all tables in gpkg_contents &
    1546             :          * gpkg_geometry_columns */
    1547             :         /* and non-spatial tables as well */
    1548             :         std::string osSQL =
    1549             :             "SELECT c.table_name, c.identifier, 1 as is_spatial, "
    1550             :             "g.column_name, g.geometry_type_name, g.z, g.m, c.min_x, c.min_y, "
    1551             :             "c.max_x, c.max_y, 1 AS is_in_gpkg_contents, "
    1552             :             "(SELECT type FROM sqlite_master WHERE lower(name) = "
    1553             :             "lower(c.table_name) AND type IN ('table', 'view')) AS object_type "
    1554             :             "  FROM gpkg_geometry_columns g "
    1555             :             "  JOIN gpkg_contents c ON (g.table_name = c.table_name)"
    1556             :             "  WHERE "
    1557             :             "  c.table_name <> 'ogr_empty_table' AND"
    1558             :             "  c.data_type = 'features' "
    1559             :             // aspatial: Was the only method available in OGR 2.0 and 2.1
    1560             :             // attributes: GPKG 1.2 or later
    1561             :             "UNION ALL "
    1562             :             "SELECT table_name, identifier, 0 as is_spatial, NULL, NULL, 0, 0, "
    1563             :             "0 AS xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 1 AS "
    1564             :             "is_in_gpkg_contents, "
    1565             :             "(SELECT type FROM sqlite_master WHERE lower(name) = "
    1566             :             "lower(table_name) AND type IN ('table', 'view')) AS object_type "
    1567             :             "  FROM gpkg_contents"
    1568        1110 :             "  WHERE data_type IN ('aspatial', 'attributes') ";
    1569             : 
    1570        2220 :         const char *pszListAllTables = CSLFetchNameValueDef(
    1571        1110 :             poOpenInfo->papszOpenOptions, "LIST_ALL_TABLES", "AUTO");
    1572        1110 :         bool bHasASpatialOrAttributes = HasGDALAspatialExtension();
    1573        1110 :         if (!bHasASpatialOrAttributes)
    1574             :         {
    1575             :             auto oResultTable =
    1576             :                 SQLQuery(hDB, "SELECT * FROM gpkg_contents WHERE "
    1577        1109 :                               "data_type = 'attributes' LIMIT 1");
    1578        1109 :             bHasASpatialOrAttributes =
    1579        1109 :                 (oResultTable && oResultTable->RowCount() == 1);
    1580             :         }
    1581        1110 :         if (bHasGPKGExtRelations)
    1582             :         {
    1583             :             osSQL += "UNION ALL "
    1584             :                      "SELECT mapping_table_name, mapping_table_name, 0 as "
    1585             :                      "is_spatial, NULL, NULL, 0, 0, 0 AS "
    1586             :                      "xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 0 AS "
    1587             :                      "is_in_gpkg_contents, 'table' AS object_type "
    1588             :                      "FROM gpkgext_relations WHERE "
    1589             :                      "lower(mapping_table_name) NOT IN (SELECT "
    1590             :                      "lower(table_name) FROM gpkg_contents) AND "
    1591             :                      "EXISTS (SELECT 1 FROM sqlite_master WHERE "
    1592             :                      "type IN ('table', 'view') AND "
    1593          18 :                      "lower(name) = lower(mapping_table_name))";
    1594             :         }
    1595        1110 :         if (EQUAL(pszListAllTables, "YES") ||
    1596        1109 :             (!bHasASpatialOrAttributes && EQUAL(pszListAllTables, "AUTO")))
    1597             :         {
    1598             :             // vgpkg_ is Spatialite virtual table
    1599             :             osSQL +=
    1600             :                 "UNION ALL "
    1601             :                 "SELECT name, name, 0 as is_spatial, NULL, NULL, 0, 0, 0 AS "
    1602             :                 "xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 0 AS "
    1603             :                 "is_in_gpkg_contents, type AS object_type "
    1604             :                 "FROM sqlite_master WHERE type IN ('table', 'view') "
    1605             :                 "AND name NOT LIKE 'gpkg_%' "
    1606             :                 "AND name NOT LIKE 'vgpkg_%' "
    1607             :                 "AND name NOT LIKE 'rtree_%' AND name NOT LIKE 'sqlite_%' "
    1608             :                 // Avoid reading those views from simple_sewer_features.gpkg
    1609             :                 "AND name NOT IN ('st_spatial_ref_sys', 'spatial_ref_sys', "
    1610             :                 "'st_geometry_columns', 'geometry_columns') "
    1611             :                 "AND lower(name) NOT IN (SELECT lower(table_name) FROM "
    1612        1040 :                 "gpkg_contents)";
    1613        1040 :             if (bHasGPKGExtRelations)
    1614             :             {
    1615             :                 osSQL += " AND lower(name) NOT IN (SELECT "
    1616             :                          "lower(mapping_table_name) FROM "
    1617          13 :                          "gpkgext_relations)";
    1618             :             }
    1619             :         }
    1620        1110 :         const int nTableLimit = GetOGRTableLimit();
    1621        1110 :         if (nTableLimit > 0)
    1622             :         {
    1623        1110 :             osSQL += " LIMIT ";
    1624        1110 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1625             :         }
    1626             : 
    1627        1110 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1628        1110 :         if (!oResult)
    1629             :         {
    1630           0 :             return FALSE;
    1631             :         }
    1632             : 
    1633        1110 :         if (nTableLimit > 0 && oResult->RowCount() > nTableLimit)
    1634             :         {
    1635           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    1636             :                      "File has more than %d vector tables. "
    1637             :                      "Limiting to first %d (can be overridden with "
    1638             :                      "OGR_TABLE_LIMIT config option)",
    1639             :                      nTableLimit, nTableLimit);
    1640           1 :             oResult->LimitRowCount(nTableLimit);
    1641             :         }
    1642             : 
    1643        1110 :         if (oResult->RowCount() > 0)
    1644             :         {
    1645         993 :             bRet = TRUE;
    1646             : 
    1647         993 :             m_apoLayers.reserve(oResult->RowCount());
    1648             : 
    1649        1986 :             std::map<std::string, int> oMapTableRefCount;
    1650        4185 :             for (int i = 0; i < oResult->RowCount(); i++)
    1651             :             {
    1652        3192 :                 const char *pszTableName = oResult->GetValue(0, i);
    1653        3192 :                 if (pszTableName == nullptr)
    1654           0 :                     continue;
    1655        3192 :                 if (++oMapTableRefCount[pszTableName] == 2)
    1656             :                 {
    1657             :                     // This should normally not happen if all constraints are
    1658             :                     // properly set
    1659           2 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1660             :                              "Table %s appearing several times in "
    1661             :                              "gpkg_contents and/or gpkg_geometry_columns",
    1662             :                              pszTableName);
    1663             :                 }
    1664             :             }
    1665             : 
    1666        1986 :             std::set<std::string> oExistingLayers;
    1667        4185 :             for (int i = 0; i < oResult->RowCount(); i++)
    1668             :             {
    1669        3192 :                 const char *pszTableName = oResult->GetValue(0, i);
    1670        3192 :                 if (pszTableName == nullptr)
    1671           2 :                     continue;
    1672             :                 const bool bTableHasSeveralGeomColumns =
    1673        3192 :                     oMapTableRefCount[pszTableName] > 1;
    1674        3192 :                 bool bIsSpatial = CPL_TO_BOOL(oResult->GetValueAsInteger(2, i));
    1675        3192 :                 const char *pszGeomColName = oResult->GetValue(3, i);
    1676        3192 :                 const char *pszGeomType = oResult->GetValue(4, i);
    1677        3192 :                 const char *pszZ = oResult->GetValue(5, i);
    1678        3192 :                 const char *pszM = oResult->GetValue(6, i);
    1679             :                 bool bIsInGpkgContents =
    1680        3192 :                     CPL_TO_BOOL(oResult->GetValueAsInteger(11, i));
    1681        3192 :                 if (!bIsInGpkgContents)
    1682          44 :                     m_bNonSpatialTablesNonRegisteredInGpkgContentsFound = true;
    1683        3192 :                 const char *pszObjectType = oResult->GetValue(12, i);
    1684        3192 :                 if (pszObjectType == nullptr ||
    1685        3191 :                     !(EQUAL(pszObjectType, "table") ||
    1686          21 :                       EQUAL(pszObjectType, "view")))
    1687             :                 {
    1688           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1689             :                              "Table/view %s is referenced in gpkg_contents, "
    1690             :                              "but does not exist",
    1691             :                              pszTableName);
    1692           1 :                     continue;
    1693             :                 }
    1694             :                 // Non-standard and undocumented behavior:
    1695             :                 // if the same table appears to have several geometry columns,
    1696             :                 // handle it for now as multiple layers named
    1697             :                 // "table_name (geom_col_name)"
    1698             :                 // The way we handle that might change in the future (e.g
    1699             :                 // could be a single layer with multiple geometry columns)
    1700             :                 std::string osLayerNameWithGeomColName =
    1701        6410 :                     pszGeomColName ? std::string(pszTableName) + " (" +
    1702             :                                          pszGeomColName + ')'
    1703        6382 :                                    : std::string(pszTableName);
    1704        3191 :                 if (cpl::contains(oExistingLayers, osLayerNameWithGeomColName))
    1705           1 :                     continue;
    1706        3190 :                 oExistingLayers.insert(osLayerNameWithGeomColName);
    1707             :                 const std::string osLayerName =
    1708             :                     bTableHasSeveralGeomColumns
    1709           3 :                         ? std::move(osLayerNameWithGeomColName)
    1710        6383 :                         : std::string(pszTableName);
    1711             :                 auto poLayer = std::make_unique<OGRGeoPackageTableLayer>(
    1712        6380 :                     this, osLayerName.c_str());
    1713        3190 :                 bool bHasZ = pszZ && atoi(pszZ) > 0;
    1714        3190 :                 bool bHasM = pszM && atoi(pszM) > 0;
    1715        3190 :                 if (pszGeomType && EQUAL(pszGeomType, "GEOMETRY"))
    1716             :                 {
    1717         644 :                     if (pszZ && atoi(pszZ) == 2)
    1718          14 :                         bHasZ = false;
    1719         644 :                     if (pszM && atoi(pszM) == 2)
    1720           6 :                         bHasM = false;
    1721             :                 }
    1722        3190 :                 poLayer->SetOpeningParameters(
    1723             :                     pszTableName, pszObjectType, bIsInGpkgContents, bIsSpatial,
    1724             :                     pszGeomColName, pszGeomType, bHasZ, bHasM);
    1725        3190 :                 m_apoLayers.push_back(std::move(poLayer));
    1726             :             }
    1727             :         }
    1728             :     }
    1729             : 
    1730        1298 :     bool bHasTileMatrixSet = false;
    1731        1298 :     if (poOpenInfo->nOpenFlags & GDAL_OF_RASTER)
    1732             :     {
    1733         574 :         bHasTileMatrixSet = SQLGetInteger(hDB,
    1734             :                                           "SELECT 1 FROM sqlite_master WHERE "
    1735             :                                           "name = 'gpkg_tile_matrix_set' AND "
    1736             :                                           "type IN ('table', 'view')",
    1737             :                                           nullptr) == 1;
    1738             :     }
    1739        1298 :     if (bHasTileMatrixSet)
    1740             :     {
    1741             :         std::string osSQL =
    1742             :             "SELECT c.table_name, c.identifier, c.description, c.srs_id, "
    1743             :             "c.min_x, c.min_y, c.max_x, c.max_y, "
    1744             :             "tms.min_x, tms.min_y, tms.max_x, tms.max_y, c.data_type "
    1745             :             "FROM gpkg_contents c JOIN gpkg_tile_matrix_set tms ON "
    1746             :             "c.table_name = tms.table_name WHERE "
    1747         572 :             "data_type IN ('tiles', '2d-gridded-coverage')";
    1748         572 :         if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE"))
    1749             :             osSubdatasetTableName =
    1750           2 :                 CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE");
    1751         572 :         if (!osSubdatasetTableName.empty())
    1752             :         {
    1753          16 :             char *pszTmp = sqlite3_mprintf(" AND c.table_name='%q'",
    1754             :                                            osSubdatasetTableName.c_str());
    1755          16 :             osSQL += pszTmp;
    1756          16 :             sqlite3_free(pszTmp);
    1757          16 :             SetPhysicalFilename(osFilename.c_str());
    1758             :         }
    1759         572 :         const int nTableLimit = GetOGRTableLimit();
    1760         572 :         if (nTableLimit > 0)
    1761             :         {
    1762         572 :             osSQL += " LIMIT ";
    1763         572 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1764             :         }
    1765             : 
    1766         572 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1767         572 :         if (!oResult)
    1768             :         {
    1769           0 :             return FALSE;
    1770             :         }
    1771             : 
    1772         572 :         if (oResult->RowCount() == 0 && !osSubdatasetTableName.empty())
    1773             :         {
    1774           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1775             :                      "Cannot find table '%s' in GeoPackage dataset",
    1776             :                      osSubdatasetTableName.c_str());
    1777             :         }
    1778         571 :         else if (oResult->RowCount() == 1)
    1779             :         {
    1780         274 :             const char *pszTableName = oResult->GetValue(0, 0);
    1781         274 :             const char *pszIdentifier = oResult->GetValue(1, 0);
    1782         274 :             const char *pszDescription = oResult->GetValue(2, 0);
    1783         274 :             const char *pszSRSId = oResult->GetValue(3, 0);
    1784         274 :             const char *pszMinX = oResult->GetValue(4, 0);
    1785         274 :             const char *pszMinY = oResult->GetValue(5, 0);
    1786         274 :             const char *pszMaxX = oResult->GetValue(6, 0);
    1787         274 :             const char *pszMaxY = oResult->GetValue(7, 0);
    1788         274 :             const char *pszTMSMinX = oResult->GetValue(8, 0);
    1789         274 :             const char *pszTMSMinY = oResult->GetValue(9, 0);
    1790         274 :             const char *pszTMSMaxX = oResult->GetValue(10, 0);
    1791         274 :             const char *pszTMSMaxY = oResult->GetValue(11, 0);
    1792         274 :             const char *pszDataType = oResult->GetValue(12, 0);
    1793         274 :             if (pszTableName && pszTMSMinX && pszTMSMinY && pszTMSMaxX &&
    1794             :                 pszTMSMaxY)
    1795             :             {
    1796         548 :                 bRet = OpenRaster(
    1797             :                     pszTableName, pszIdentifier, pszDescription,
    1798         274 :                     pszSRSId ? atoi(pszSRSId) : 0, CPLAtof(pszTMSMinX),
    1799             :                     CPLAtof(pszTMSMinY), CPLAtof(pszTMSMaxX),
    1800             :                     CPLAtof(pszTMSMaxY), pszMinX, pszMinY, pszMaxX, pszMaxY,
    1801         274 :                     EQUAL(pszDataType, "tiles"), poOpenInfo->papszOpenOptions);
    1802             :             }
    1803             :         }
    1804         297 :         else if (oResult->RowCount() >= 1)
    1805             :         {
    1806           5 :             bRet = TRUE;
    1807             : 
    1808           5 :             if (nTableLimit > 0 && oResult->RowCount() > nTableLimit)
    1809             :             {
    1810           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1811             :                          "File has more than %d raster tables. "
    1812             :                          "Limiting to first %d (can be overridden with "
    1813             :                          "OGR_TABLE_LIMIT config option)",
    1814             :                          nTableLimit, nTableLimit);
    1815           1 :                 oResult->LimitRowCount(nTableLimit);
    1816             :             }
    1817             : 
    1818           5 :             int nSDSCount = 0;
    1819        2013 :             for (int i = 0; i < oResult->RowCount(); i++)
    1820             :             {
    1821        2008 :                 const char *pszTableName = oResult->GetValue(0, i);
    1822        2008 :                 const char *pszIdentifier = oResult->GetValue(1, i);
    1823        2008 :                 if (pszTableName == nullptr)
    1824           0 :                     continue;
    1825             :                 m_aosSubDatasets.AddNameValue(
    1826             :                     CPLSPrintf("SUBDATASET_%d_NAME", nSDSCount + 1),
    1827        2008 :                     CPLSPrintf("GPKG:%s:%s", m_pszFilename, pszTableName));
    1828             :                 m_aosSubDatasets.AddNameValue(
    1829             :                     CPLSPrintf("SUBDATASET_%d_DESC", nSDSCount + 1),
    1830             :                     pszIdentifier
    1831        2008 :                         ? CPLSPrintf("%s - %s", pszTableName, pszIdentifier)
    1832        4016 :                         : pszTableName);
    1833        2008 :                 nSDSCount++;
    1834             :             }
    1835             :         }
    1836             :     }
    1837             : 
    1838        1298 :     if (!bRet && (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR))
    1839             :     {
    1840          33 :         if ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE))
    1841             :         {
    1842          22 :             bRet = TRUE;
    1843             :         }
    1844             :         else
    1845             :         {
    1846          11 :             CPLDebug("GPKG",
    1847             :                      "This GeoPackage has no vector content and is opened "
    1848             :                      "in read-only mode. If you open it in update mode, "
    1849             :                      "opening will be successful.");
    1850             :         }
    1851             :     }
    1852             : 
    1853        1298 :     if (eAccess == GA_Update)
    1854             :     {
    1855         259 :         FixupWrongRTreeTrigger();
    1856         259 :         FixupWrongMedataReferenceColumnNameUpdate();
    1857             :     }
    1858             : 
    1859        1298 :     SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    1860             : 
    1861        1298 :     return bRet;
    1862             : }
    1863             : 
    1864             : /************************************************************************/
    1865             : /*                    DetectSpatialRefSysColumns()                      */
    1866             : /************************************************************************/
    1867             : 
    1868        1308 : void GDALGeoPackageDataset::DetectSpatialRefSysColumns()
    1869             : {
    1870             :     // Detect definition_12_063 column
    1871             :     {
    1872        1308 :         sqlite3_stmt *hSQLStmt = nullptr;
    1873        1308 :         int rc = sqlite3_prepare_v2(
    1874             :             hDB, "SELECT definition_12_063 FROM gpkg_spatial_ref_sys ", -1,
    1875             :             &hSQLStmt, nullptr);
    1876        1308 :         if (rc == SQLITE_OK)
    1877             :         {
    1878          85 :             m_bHasDefinition12_063 = true;
    1879          85 :             sqlite3_finalize(hSQLStmt);
    1880             :         }
    1881             :     }
    1882             : 
    1883             :     // Detect epoch column
    1884        1308 :     if (m_bHasDefinition12_063)
    1885             :     {
    1886          85 :         sqlite3_stmt *hSQLStmt = nullptr;
    1887             :         int rc =
    1888          85 :             sqlite3_prepare_v2(hDB, "SELECT epoch FROM gpkg_spatial_ref_sys ",
    1889             :                                -1, &hSQLStmt, nullptr);
    1890          85 :         if (rc == SQLITE_OK)
    1891             :         {
    1892          76 :             m_bHasEpochColumn = true;
    1893          76 :             sqlite3_finalize(hSQLStmt);
    1894             :         }
    1895             :     }
    1896        1308 : }
    1897             : 
    1898             : /************************************************************************/
    1899             : /*                    FixupWrongRTreeTrigger()                          */
    1900             : /************************************************************************/
    1901             : 
    1902         259 : void GDALGeoPackageDataset::FixupWrongRTreeTrigger()
    1903             : {
    1904             :     auto oResult = SQLQuery(
    1905             :         hDB,
    1906             :         "SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND "
    1907         259 :         "NAME LIKE 'rtree_%_update3' AND sql LIKE '% AFTER UPDATE OF % ON %'");
    1908         259 :     if (oResult == nullptr)
    1909           0 :         return;
    1910         259 :     if (oResult->RowCount() > 0)
    1911             :     {
    1912           1 :         CPLDebug("GPKG", "Fixing incorrect trigger(s) related to RTree");
    1913             :     }
    1914         261 :     for (int i = 0; i < oResult->RowCount(); i++)
    1915             :     {
    1916           2 :         const char *pszName = oResult->GetValue(0, i);
    1917           2 :         const char *pszSQL = oResult->GetValue(1, i);
    1918           2 :         const char *pszPtr1 = strstr(pszSQL, " AFTER UPDATE OF ");
    1919           2 :         if (pszPtr1)
    1920             :         {
    1921           2 :             const char *pszPtr = pszPtr1 + strlen(" AFTER UPDATE OF ");
    1922             :             // Skipping over geometry column name
    1923           4 :             while (*pszPtr == ' ')
    1924           2 :                 pszPtr++;
    1925           2 :             if (pszPtr[0] == '"' || pszPtr[0] == '\'')
    1926             :             {
    1927           1 :                 char chStringDelim = pszPtr[0];
    1928           1 :                 pszPtr++;
    1929           9 :                 while (*pszPtr != '\0' && *pszPtr != chStringDelim)
    1930             :                 {
    1931           8 :                     if (*pszPtr == '\\' && pszPtr[1] == chStringDelim)
    1932           0 :                         pszPtr += 2;
    1933             :                     else
    1934           8 :                         pszPtr += 1;
    1935             :                 }
    1936           1 :                 if (*pszPtr == chStringDelim)
    1937           1 :                     pszPtr++;
    1938             :             }
    1939             :             else
    1940             :             {
    1941           1 :                 pszPtr++;
    1942           8 :                 while (*pszPtr != ' ')
    1943           7 :                     pszPtr++;
    1944             :             }
    1945           2 :             if (*pszPtr == ' ')
    1946             :             {
    1947           2 :                 SQLCommand(hDB,
    1948           4 :                            ("DROP TRIGGER \"" + SQLEscapeName(pszName) + "\"")
    1949             :                                .c_str());
    1950           4 :                 CPLString newSQL;
    1951           2 :                 newSQL.assign(pszSQL, pszPtr1 - pszSQL);
    1952           2 :                 newSQL += " AFTER UPDATE";
    1953           2 :                 newSQL += pszPtr;
    1954           2 :                 SQLCommand(hDB, newSQL);
    1955             :             }
    1956             :         }
    1957             :     }
    1958             : }
    1959             : 
    1960             : /************************************************************************/
    1961             : /*             FixupWrongMedataReferenceColumnNameUpdate()              */
    1962             : /************************************************************************/
    1963             : 
    1964         259 : void GDALGeoPackageDataset::FixupWrongMedataReferenceColumnNameUpdate()
    1965             : {
    1966             :     // Fix wrong trigger that was generated by GDAL < 2.4.0
    1967             :     // See https://github.com/qgis/QGIS/issues/42768
    1968             :     auto oResult = SQLQuery(
    1969             :         hDB, "SELECT sql FROM sqlite_master WHERE type = 'trigger' AND "
    1970             :              "NAME ='gpkg_metadata_reference_column_name_update' AND "
    1971         259 :              "sql LIKE '%column_nameIS%'");
    1972         259 :     if (oResult == nullptr)
    1973           0 :         return;
    1974         259 :     if (oResult->RowCount() == 1)
    1975             :     {
    1976           1 :         CPLDebug("GPKG", "Fixing incorrect trigger "
    1977             :                          "gpkg_metadata_reference_column_name_update");
    1978           1 :         const char *pszSQL = oResult->GetValue(0, 0);
    1979             :         std::string osNewSQL(
    1980           3 :             CPLString(pszSQL).replaceAll("column_nameIS", "column_name IS"));
    1981             : 
    1982           1 :         SQLCommand(hDB,
    1983             :                    "DROP TRIGGER gpkg_metadata_reference_column_name_update");
    1984           1 :         SQLCommand(hDB, osNewSQL.c_str());
    1985             :     }
    1986             : }
    1987             : 
    1988             : /************************************************************************/
    1989             : /*                  ClearCachedRelationships()                          */
    1990             : /************************************************************************/
    1991             : 
    1992          36 : void GDALGeoPackageDataset::ClearCachedRelationships()
    1993             : {
    1994          36 :     m_bHasPopulatedRelationships = false;
    1995          36 :     m_osMapRelationships.clear();
    1996          36 : }
    1997             : 
    1998             : /************************************************************************/
    1999             : /*                           LoadRelationships()                        */
    2000             : /************************************************************************/
    2001             : 
    2002          85 : void GDALGeoPackageDataset::LoadRelationships() const
    2003             : {
    2004          85 :     m_osMapRelationships.clear();
    2005             : 
    2006          85 :     std::vector<std::string> oExcludedTables;
    2007          85 :     if (HasGpkgextRelationsTable())
    2008             :     {
    2009          37 :         LoadRelationshipsUsingRelatedTablesExtension();
    2010             : 
    2011          89 :         for (const auto &oRelationship : m_osMapRelationships)
    2012             :         {
    2013             :             oExcludedTables.emplace_back(
    2014          52 :                 oRelationship.second->GetMappingTableName());
    2015             :         }
    2016             :     }
    2017             : 
    2018             :     // Also load relationships defined using foreign keys (i.e. one-to-many
    2019             :     // relationships). Here we must exclude any relationships defined from the
    2020             :     // related tables extension, we don't want them included twice.
    2021          85 :     LoadRelationshipsFromForeignKeys(oExcludedTables);
    2022          85 :     m_bHasPopulatedRelationships = true;
    2023          85 : }
    2024             : 
    2025             : /************************************************************************/
    2026             : /*         LoadRelationshipsUsingRelatedTablesExtension()               */
    2027             : /************************************************************************/
    2028             : 
    2029          37 : void GDALGeoPackageDataset::LoadRelationshipsUsingRelatedTablesExtension() const
    2030             : {
    2031          37 :     m_osMapRelationships.clear();
    2032             : 
    2033             :     auto oResultTable = SQLQuery(
    2034          37 :         hDB, "SELECT base_table_name, base_primary_column, "
    2035             :              "related_table_name, related_primary_column, relation_name, "
    2036          74 :              "mapping_table_name FROM gpkgext_relations");
    2037          37 :     if (oResultTable && oResultTable->RowCount() > 0)
    2038             :     {
    2039          86 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    2040             :         {
    2041          53 :             const char *pszBaseTableName = oResultTable->GetValue(0, i);
    2042          53 :             if (!pszBaseTableName)
    2043             :             {
    2044           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2045             :                          "Could not retrieve base_table_name from "
    2046             :                          "gpkgext_relations");
    2047           1 :                 continue;
    2048             :             }
    2049          53 :             const char *pszBasePrimaryColumn = oResultTable->GetValue(1, i);
    2050          53 :             if (!pszBasePrimaryColumn)
    2051             :             {
    2052           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2053             :                          "Could not retrieve base_primary_column from "
    2054             :                          "gpkgext_relations");
    2055           0 :                 continue;
    2056             :             }
    2057          53 :             const char *pszRelatedTableName = oResultTable->GetValue(2, i);
    2058          53 :             if (!pszRelatedTableName)
    2059             :             {
    2060           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2061             :                          "Could not retrieve related_table_name from "
    2062             :                          "gpkgext_relations");
    2063           0 :                 continue;
    2064             :             }
    2065          53 :             const char *pszRelatedPrimaryColumn = oResultTable->GetValue(3, i);
    2066          53 :             if (!pszRelatedPrimaryColumn)
    2067             :             {
    2068           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2069             :                          "Could not retrieve related_primary_column from "
    2070             :                          "gpkgext_relations");
    2071           0 :                 continue;
    2072             :             }
    2073          53 :             const char *pszRelationName = oResultTable->GetValue(4, i);
    2074          53 :             if (!pszRelationName)
    2075             :             {
    2076           0 :                 CPLError(
    2077             :                     CE_Warning, CPLE_AppDefined,
    2078             :                     "Could not retrieve relation_name from gpkgext_relations");
    2079           0 :                 continue;
    2080             :             }
    2081          53 :             const char *pszMappingTableName = oResultTable->GetValue(5, i);
    2082          53 :             if (!pszMappingTableName)
    2083             :             {
    2084           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2085             :                          "Could not retrieve mapping_table_name from "
    2086             :                          "gpkgext_relations");
    2087           0 :                 continue;
    2088             :             }
    2089             : 
    2090             :             // confirm that mapping table exists
    2091             :             char *pszSQL =
    2092          53 :                 sqlite3_mprintf("SELECT 1 FROM sqlite_master WHERE "
    2093             :                                 "name='%q' AND type IN ('table', 'view')",
    2094             :                                 pszMappingTableName);
    2095          53 :             const int nMappingTableCount = SQLGetInteger(hDB, pszSQL, nullptr);
    2096          53 :             sqlite3_free(pszSQL);
    2097             : 
    2098          55 :             if (nMappingTableCount < 1 &&
    2099           2 :                 !const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    2100           2 :                     pszMappingTableName))
    2101             :             {
    2102           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2103             :                          "Relationship mapping table %s does not exist",
    2104             :                          pszMappingTableName);
    2105           1 :                 continue;
    2106             :             }
    2107             : 
    2108             :             const std::string osRelationName = GenerateNameForRelationship(
    2109         104 :                 pszBaseTableName, pszRelatedTableName, pszRelationName);
    2110             : 
    2111         104 :             std::string osType{};
    2112             :             // defined requirement classes -- for these types the relation name
    2113             :             // will be specific string value from the related tables extension.
    2114             :             // In this case we need to construct a unique relationship name
    2115             :             // based on the related tables
    2116          52 :             if (EQUAL(pszRelationName, "media") ||
    2117          40 :                 EQUAL(pszRelationName, "simple_attributes") ||
    2118          40 :                 EQUAL(pszRelationName, "features") ||
    2119          18 :                 EQUAL(pszRelationName, "attributes") ||
    2120           2 :                 EQUAL(pszRelationName, "tiles"))
    2121             :             {
    2122          50 :                 osType = pszRelationName;
    2123             :             }
    2124             :             else
    2125             :             {
    2126             :                 // user defined types default to features
    2127           2 :                 osType = "features";
    2128             :             }
    2129             : 
    2130             :             auto poRelationship = std::make_unique<GDALRelationship>(
    2131             :                 osRelationName, pszBaseTableName, pszRelatedTableName,
    2132         104 :                 GRC_MANY_TO_MANY);
    2133             : 
    2134         104 :             poRelationship->SetLeftTableFields({pszBasePrimaryColumn});
    2135         104 :             poRelationship->SetRightTableFields({pszRelatedPrimaryColumn});
    2136         104 :             poRelationship->SetLeftMappingTableFields({"base_id"});
    2137         104 :             poRelationship->SetRightMappingTableFields({"related_id"});
    2138          52 :             poRelationship->SetMappingTableName(pszMappingTableName);
    2139          52 :             poRelationship->SetRelatedTableType(osType);
    2140             : 
    2141          52 :             m_osMapRelationships[osRelationName] = std::move(poRelationship);
    2142             :         }
    2143             :     }
    2144          37 : }
    2145             : 
    2146             : /************************************************************************/
    2147             : /*                GenerateNameForRelationship()                         */
    2148             : /************************************************************************/
    2149             : 
    2150          76 : std::string GDALGeoPackageDataset::GenerateNameForRelationship(
    2151             :     const char *pszBaseTableName, const char *pszRelatedTableName,
    2152             :     const char *pszType)
    2153             : {
    2154             :     // defined requirement classes -- for these types the relation name will be
    2155             :     // specific string value from the related tables extension. In this case we
    2156             :     // need to construct a unique relationship name based on the related tables
    2157          76 :     if (EQUAL(pszType, "media") || EQUAL(pszType, "simple_attributes") ||
    2158          53 :         EQUAL(pszType, "features") || EQUAL(pszType, "attributes") ||
    2159           8 :         EQUAL(pszType, "tiles"))
    2160             :     {
    2161         136 :         std::ostringstream stream;
    2162             :         stream << pszBaseTableName << '_' << pszRelatedTableName << '_'
    2163          68 :                << pszType;
    2164          68 :         return stream.str();
    2165             :     }
    2166             :     else
    2167             :     {
    2168             :         // user defined types default to features
    2169           8 :         return pszType;
    2170             :     }
    2171             : }
    2172             : 
    2173             : /************************************************************************/
    2174             : /*                       ValidateRelationship()                         */
    2175             : /************************************************************************/
    2176             : 
    2177          28 : bool GDALGeoPackageDataset::ValidateRelationship(
    2178             :     const GDALRelationship *poRelationship, std::string &failureReason)
    2179             : {
    2180             : 
    2181          28 :     if (poRelationship->GetCardinality() !=
    2182             :         GDALRelationshipCardinality::GRC_MANY_TO_MANY)
    2183             :     {
    2184           3 :         failureReason = "Only many to many relationships are supported";
    2185           3 :         return false;
    2186             :     }
    2187             : 
    2188          50 :     std::string osRelatedTableType = poRelationship->GetRelatedTableType();
    2189          65 :     if (!osRelatedTableType.empty() && osRelatedTableType != "features" &&
    2190          30 :         osRelatedTableType != "media" &&
    2191          20 :         osRelatedTableType != "simple_attributes" &&
    2192          55 :         osRelatedTableType != "attributes" && osRelatedTableType != "tiles")
    2193             :     {
    2194             :         failureReason =
    2195           4 :             ("Related table type " + osRelatedTableType +
    2196             :              " is not a valid value for the GeoPackage specification. "
    2197             :              "Valid values are: features, media, simple_attributes, "
    2198             :              "attributes, tiles.")
    2199           2 :                 .c_str();
    2200           2 :         return false;
    2201             :     }
    2202             : 
    2203          23 :     const std::string &osLeftTableName = poRelationship->GetLeftTableName();
    2204          23 :     OGRGeoPackageLayer *poLeftTable = cpl::down_cast<OGRGeoPackageLayer *>(
    2205          23 :         GetLayerByName(osLeftTableName.c_str()));
    2206          23 :     if (!poLeftTable)
    2207             :     {
    2208           4 :         failureReason = ("Left table " + osLeftTableName +
    2209             :                          " is not an existing layer in the dataset")
    2210           2 :                             .c_str();
    2211           2 :         return false;
    2212             :     }
    2213          21 :     const std::string &osRightTableName = poRelationship->GetRightTableName();
    2214          21 :     OGRGeoPackageLayer *poRightTable = cpl::down_cast<OGRGeoPackageLayer *>(
    2215          21 :         GetLayerByName(osRightTableName.c_str()));
    2216          21 :     if (!poRightTable)
    2217             :     {
    2218           4 :         failureReason = ("Right table " + osRightTableName +
    2219             :                          " is not an existing layer in the dataset")
    2220           2 :                             .c_str();
    2221           2 :         return false;
    2222             :     }
    2223             : 
    2224          19 :     const auto &aosLeftTableFields = poRelationship->GetLeftTableFields();
    2225          19 :     if (aosLeftTableFields.empty())
    2226             :     {
    2227           1 :         failureReason = "No left table fields were specified";
    2228           1 :         return false;
    2229             :     }
    2230          18 :     else if (aosLeftTableFields.size() > 1)
    2231             :     {
    2232             :         failureReason = "Only a single left table field is permitted for the "
    2233           1 :                         "GeoPackage specification";
    2234           1 :         return false;
    2235             :     }
    2236             :     else
    2237             :     {
    2238             :         // validate left field exists
    2239          34 :         if (poLeftTable->GetLayerDefn()->GetFieldIndex(
    2240          37 :                 aosLeftTableFields[0].c_str()) < 0 &&
    2241           3 :             !EQUAL(poLeftTable->GetFIDColumn(), aosLeftTableFields[0].c_str()))
    2242             :         {
    2243           2 :             failureReason = ("Left table field " + aosLeftTableFields[0] +
    2244           2 :                              " does not exist in " + osLeftTableName)
    2245           1 :                                 .c_str();
    2246           1 :             return false;
    2247             :         }
    2248             :     }
    2249             : 
    2250          16 :     const auto &aosRightTableFields = poRelationship->GetRightTableFields();
    2251          16 :     if (aosRightTableFields.empty())
    2252             :     {
    2253           1 :         failureReason = "No right table fields were specified";
    2254           1 :         return false;
    2255             :     }
    2256          15 :     else if (aosRightTableFields.size() > 1)
    2257             :     {
    2258             :         failureReason = "Only a single right table field is permitted for the "
    2259           1 :                         "GeoPackage specification";
    2260           1 :         return false;
    2261             :     }
    2262             :     else
    2263             :     {
    2264             :         // validate right field exists
    2265          28 :         if (poRightTable->GetLayerDefn()->GetFieldIndex(
    2266          32 :                 aosRightTableFields[0].c_str()) < 0 &&
    2267           4 :             !EQUAL(poRightTable->GetFIDColumn(),
    2268             :                    aosRightTableFields[0].c_str()))
    2269             :         {
    2270           4 :             failureReason = ("Right table field " + aosRightTableFields[0] +
    2271           4 :                              " does not exist in " + osRightTableName)
    2272           2 :                                 .c_str();
    2273           2 :             return false;
    2274             :         }
    2275             :     }
    2276             : 
    2277          12 :     return true;
    2278             : }
    2279             : 
    2280             : /************************************************************************/
    2281             : /*                         InitRaster()                                 */
    2282             : /************************************************************************/
    2283             : 
    2284         358 : bool GDALGeoPackageDataset::InitRaster(
    2285             :     GDALGeoPackageDataset *poParentDS, const char *pszTableName, double dfMinX,
    2286             :     double dfMinY, double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2287             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2288             :     const char *pszContentsMaxY, char **papszOpenOptionsIn,
    2289             :     const SQLResult &oResult, int nIdxInResult)
    2290             : {
    2291         358 :     m_osRasterTable = pszTableName;
    2292         358 :     m_dfTMSMinX = dfMinX;
    2293         358 :     m_dfTMSMaxY = dfMaxY;
    2294             : 
    2295             :     // Despite prior checking, the type might be Binary and
    2296             :     // SQLResultGetValue() not working properly on it
    2297         358 :     int nZoomLevel = atoi(oResult.GetValue(0, nIdxInResult));
    2298         358 :     if (nZoomLevel < 0 || nZoomLevel > 65536)
    2299             :     {
    2300           0 :         return false;
    2301             :     }
    2302         358 :     double dfPixelXSize = CPLAtof(oResult.GetValue(1, nIdxInResult));
    2303         358 :     double dfPixelYSize = CPLAtof(oResult.GetValue(2, nIdxInResult));
    2304         358 :     if (dfPixelXSize <= 0 || dfPixelYSize <= 0)
    2305             :     {
    2306           0 :         return false;
    2307             :     }
    2308         358 :     int nTileWidth = atoi(oResult.GetValue(3, nIdxInResult));
    2309         358 :     int nTileHeight = atoi(oResult.GetValue(4, nIdxInResult));
    2310         358 :     if (nTileWidth <= 0 || nTileWidth > 65536 || nTileHeight <= 0 ||
    2311             :         nTileHeight > 65536)
    2312             :     {
    2313           0 :         return false;
    2314             :     }
    2315             :     int nTileMatrixWidth = static_cast<int>(
    2316         716 :         std::min(static_cast<GIntBig>(INT_MAX),
    2317         358 :                  CPLAtoGIntBig(oResult.GetValue(5, nIdxInResult))));
    2318             :     int nTileMatrixHeight = static_cast<int>(
    2319         716 :         std::min(static_cast<GIntBig>(INT_MAX),
    2320         358 :                  CPLAtoGIntBig(oResult.GetValue(6, nIdxInResult))));
    2321         358 :     if (nTileMatrixWidth <= 0 || nTileMatrixHeight <= 0)
    2322             :     {
    2323           0 :         return false;
    2324             :     }
    2325             : 
    2326             :     /* Use content bounds in priority over tile_matrix_set bounds */
    2327         358 :     double dfGDALMinX = dfMinX;
    2328         358 :     double dfGDALMinY = dfMinY;
    2329         358 :     double dfGDALMaxX = dfMaxX;
    2330         358 :     double dfGDALMaxY = dfMaxY;
    2331             :     pszContentsMinX =
    2332         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINX", pszContentsMinX);
    2333             :     pszContentsMinY =
    2334         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINY", pszContentsMinY);
    2335             :     pszContentsMaxX =
    2336         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXX", pszContentsMaxX);
    2337             :     pszContentsMaxY =
    2338         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXY", pszContentsMaxY);
    2339         358 :     if (pszContentsMinX != nullptr && pszContentsMinY != nullptr &&
    2340         358 :         pszContentsMaxX != nullptr && pszContentsMaxY != nullptr)
    2341             :     {
    2342         715 :         if (CPLAtof(pszContentsMinX) < CPLAtof(pszContentsMaxX) &&
    2343         357 :             CPLAtof(pszContentsMinY) < CPLAtof(pszContentsMaxY))
    2344             :         {
    2345         357 :             dfGDALMinX = CPLAtof(pszContentsMinX);
    2346         357 :             dfGDALMinY = CPLAtof(pszContentsMinY);
    2347         357 :             dfGDALMaxX = CPLAtof(pszContentsMaxX);
    2348         357 :             dfGDALMaxY = CPLAtof(pszContentsMaxY);
    2349             :         }
    2350             :         else
    2351             :         {
    2352           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    2353             :                      "Illegal min_x/min_y/max_x/max_y values for %s in open "
    2354             :                      "options and/or gpkg_contents. Using bounds of "
    2355             :                      "gpkg_tile_matrix_set instead",
    2356             :                      pszTableName);
    2357             :         }
    2358             :     }
    2359         358 :     if (dfGDALMinX >= dfGDALMaxX || dfGDALMinY >= dfGDALMaxY)
    2360             :     {
    2361           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2362             :                  "Illegal min_x/min_y/max_x/max_y values for %s", pszTableName);
    2363           0 :         return false;
    2364             :     }
    2365             : 
    2366         358 :     int nBandCount = 0;
    2367             :     const char *pszBAND_COUNT =
    2368         358 :         CSLFetchNameValue(papszOpenOptionsIn, "BAND_COUNT");
    2369         358 :     if (poParentDS)
    2370             :     {
    2371          86 :         nBandCount = poParentDS->GetRasterCount();
    2372             :     }
    2373         272 :     else if (m_eDT != GDT_UInt8)
    2374             :     {
    2375          65 :         if (pszBAND_COUNT != nullptr && !EQUAL(pszBAND_COUNT, "AUTO") &&
    2376           0 :             !EQUAL(pszBAND_COUNT, "1"))
    2377             :         {
    2378           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2379             :                      "BAND_COUNT ignored for non-Byte data");
    2380             :         }
    2381          65 :         nBandCount = 1;
    2382             :     }
    2383             :     else
    2384             :     {
    2385         207 :         if (pszBAND_COUNT != nullptr && !EQUAL(pszBAND_COUNT, "AUTO"))
    2386             :         {
    2387          69 :             nBandCount = atoi(pszBAND_COUNT);
    2388          69 :             if (nBandCount == 1)
    2389           5 :                 GetMetadata("IMAGE_STRUCTURE");
    2390             :         }
    2391             :         else
    2392             :         {
    2393         138 :             GetMetadata("IMAGE_STRUCTURE");
    2394         138 :             nBandCount = m_nBandCountFromMetadata;
    2395         138 :             if (nBandCount == 1)
    2396          39 :                 m_eTF = GPKG_TF_PNG;
    2397             :         }
    2398         207 :         if (nBandCount == 1 && !m_osTFFromMetadata.empty())
    2399             :         {
    2400           2 :             m_eTF = GDALGPKGMBTilesGetTileFormat(m_osTFFromMetadata.c_str());
    2401             :         }
    2402         207 :         if (nBandCount <= 0 || nBandCount > 4)
    2403          85 :             nBandCount = 4;
    2404             :     }
    2405             : 
    2406         358 :     return InitRaster(poParentDS, pszTableName, nZoomLevel, nBandCount, dfMinX,
    2407             :                       dfMaxY, dfPixelXSize, dfPixelYSize, nTileWidth,
    2408             :                       nTileHeight, nTileMatrixWidth, nTileMatrixHeight,
    2409         358 :                       dfGDALMinX, dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    2410             : }
    2411             : 
    2412             : /************************************************************************/
    2413             : /*                      ComputeTileAndPixelShifts()                     */
    2414             : /************************************************************************/
    2415             : 
    2416         784 : bool GDALGeoPackageDataset::ComputeTileAndPixelShifts()
    2417             : {
    2418             :     int nTileWidth, nTileHeight;
    2419         784 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2420             : 
    2421             :     // Compute shift between GDAL origin and TileMatrixSet origin
    2422         784 :     const double dfShiftXPixels = (m_gt[0] - m_dfTMSMinX) / m_gt[1];
    2423         784 :     if (!(dfShiftXPixels / nTileWidth >= INT_MIN &&
    2424         781 :           dfShiftXPixels / nTileWidth < INT_MAX))
    2425             :     {
    2426           3 :         return false;
    2427             :     }
    2428         781 :     const int64_t nShiftXPixels =
    2429         781 :         static_cast<int64_t>(floor(0.5 + dfShiftXPixels));
    2430         781 :     m_nShiftXTiles = static_cast<int>(nShiftXPixels / nTileWidth);
    2431         781 :     if (nShiftXPixels < 0 && (nShiftXPixels % nTileWidth) != 0)
    2432          11 :         m_nShiftXTiles--;
    2433         781 :     m_nShiftXPixelsMod =
    2434         781 :         (static_cast<int>(nShiftXPixels % nTileWidth) + nTileWidth) %
    2435             :         nTileWidth;
    2436             : 
    2437         781 :     const double dfShiftYPixels = (m_gt[3] - m_dfTMSMaxY) / m_gt[5];
    2438         781 :     if (!(dfShiftYPixels / nTileHeight >= INT_MIN &&
    2439         781 :           dfShiftYPixels / nTileHeight < INT_MAX))
    2440             :     {
    2441           1 :         return false;
    2442             :     }
    2443         780 :     const int64_t nShiftYPixels =
    2444         780 :         static_cast<int64_t>(floor(0.5 + dfShiftYPixels));
    2445         780 :     m_nShiftYTiles = static_cast<int>(nShiftYPixels / nTileHeight);
    2446         780 :     if (nShiftYPixels < 0 && (nShiftYPixels % nTileHeight) != 0)
    2447          11 :         m_nShiftYTiles--;
    2448         780 :     m_nShiftYPixelsMod =
    2449         780 :         (static_cast<int>(nShiftYPixels % nTileHeight) + nTileHeight) %
    2450             :         nTileHeight;
    2451         780 :     return true;
    2452             : }
    2453             : 
    2454             : /************************************************************************/
    2455             : /*                            AllocCachedTiles()                        */
    2456             : /************************************************************************/
    2457             : 
    2458         780 : bool GDALGeoPackageDataset::AllocCachedTiles()
    2459             : {
    2460             :     int nTileWidth, nTileHeight;
    2461         780 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2462             : 
    2463             :     // We currently need 4 caches because of
    2464             :     // GDALGPKGMBTilesLikePseudoDataset::ReadTile(int nRow, int nCol)
    2465         780 :     const int nCacheCount = 4;
    2466             :     /*
    2467             :             (m_nShiftXPixelsMod != 0 || m_nShiftYPixelsMod != 0) ? 4 :
    2468             :             (GetUpdate() && m_eDT == GDT_UInt8) ? 2 : 1;
    2469             :     */
    2470         780 :     m_pabyCachedTiles = static_cast<GByte *>(VSI_MALLOC3_VERBOSE(
    2471             :         cpl::fits_on<int>(nCacheCount * (m_eDT == GDT_UInt8 ? 4 : 1) *
    2472             :                           m_nDTSize),
    2473             :         nTileWidth, nTileHeight));
    2474         780 :     if (m_pabyCachedTiles == nullptr)
    2475             :     {
    2476           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Too big tiles: %d x %d",
    2477             :                  nTileWidth, nTileHeight);
    2478           0 :         return false;
    2479             :     }
    2480             : 
    2481         780 :     return true;
    2482             : }
    2483             : 
    2484             : /************************************************************************/
    2485             : /*                         InitRaster()                                 */
    2486             : /************************************************************************/
    2487             : 
    2488         597 : bool GDALGeoPackageDataset::InitRaster(
    2489             :     GDALGeoPackageDataset *poParentDS, const char *pszTableName, int nZoomLevel,
    2490             :     int nBandCount, double dfTMSMinX, double dfTMSMaxY, double dfPixelXSize,
    2491             :     double dfPixelYSize, int nTileWidth, int nTileHeight, int nTileMatrixWidth,
    2492             :     int nTileMatrixHeight, double dfGDALMinX, double dfGDALMinY,
    2493             :     double dfGDALMaxX, double dfGDALMaxY)
    2494             : {
    2495         597 :     m_osRasterTable = pszTableName;
    2496         597 :     m_dfTMSMinX = dfTMSMinX;
    2497         597 :     m_dfTMSMaxY = dfTMSMaxY;
    2498         597 :     m_nZoomLevel = nZoomLevel;
    2499         597 :     m_nTileMatrixWidth = nTileMatrixWidth;
    2500         597 :     m_nTileMatrixHeight = nTileMatrixHeight;
    2501             : 
    2502         597 :     m_bGeoTransformValid = true;
    2503         597 :     m_gt[0] = dfGDALMinX;
    2504         597 :     m_gt[1] = dfPixelXSize;
    2505         597 :     m_gt[3] = dfGDALMaxY;
    2506         597 :     m_gt[5] = -dfPixelYSize;
    2507         597 :     double dfRasterXSize = 0.5 + (dfGDALMaxX - dfGDALMinX) / dfPixelXSize;
    2508         597 :     double dfRasterYSize = 0.5 + (dfGDALMaxY - dfGDALMinY) / dfPixelYSize;
    2509         597 :     if (dfRasterXSize > INT_MAX || dfRasterYSize > INT_MAX)
    2510             :     {
    2511           0 :         CPLError(CE_Failure, CPLE_NotSupported, "Too big raster: %f x %f",
    2512             :                  dfRasterXSize, dfRasterYSize);
    2513           0 :         return false;
    2514             :     }
    2515         597 :     nRasterXSize = std::max(1, static_cast<int>(dfRasterXSize));
    2516         597 :     nRasterYSize = std::max(1, static_cast<int>(dfRasterYSize));
    2517             : 
    2518         597 :     if (poParentDS)
    2519             :     {
    2520         325 :         m_poParentDS = poParentDS;
    2521         325 :         eAccess = poParentDS->eAccess;
    2522         325 :         hDB = poParentDS->hDB;
    2523         325 :         m_eTF = poParentDS->m_eTF;
    2524         325 :         m_eDT = poParentDS->m_eDT;
    2525         325 :         m_nDTSize = poParentDS->m_nDTSize;
    2526         325 :         m_dfScale = poParentDS->m_dfScale;
    2527         325 :         m_dfOffset = poParentDS->m_dfOffset;
    2528         325 :         m_dfPrecision = poParentDS->m_dfPrecision;
    2529         325 :         m_usGPKGNull = poParentDS->m_usGPKGNull;
    2530         325 :         m_nQuality = poParentDS->m_nQuality;
    2531         325 :         m_nZLevel = poParentDS->m_nZLevel;
    2532         325 :         m_bDither = poParentDS->m_bDither;
    2533             :         /*m_nSRID = poParentDS->m_nSRID;*/
    2534         325 :         m_osWHERE = poParentDS->m_osWHERE;
    2535         325 :         SetDescription(CPLSPrintf("%s - zoom_level=%d",
    2536         325 :                                   poParentDS->GetDescription(), m_nZoomLevel));
    2537             :     }
    2538             : 
    2539        2091 :     for (int i = 1; i <= nBandCount; i++)
    2540             :     {
    2541             :         auto poNewBand = std::make_unique<GDALGeoPackageRasterBand>(
    2542        1494 :             this, nTileWidth, nTileHeight);
    2543        1494 :         if (poParentDS)
    2544             :         {
    2545         761 :             int bHasNoData = FALSE;
    2546             :             double dfNoDataValue =
    2547         761 :                 poParentDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    2548         761 :             if (bHasNoData)
    2549          24 :                 poNewBand->SetNoDataValueInternal(dfNoDataValue);
    2550             :         }
    2551             : 
    2552        1494 :         if (nBandCount == 1 && m_poCTFromMetadata)
    2553             :         {
    2554           3 :             poNewBand->AssignColorTable(m_poCTFromMetadata.get());
    2555             :         }
    2556        1494 :         if (!m_osNodataValueFromMetadata.empty())
    2557             :         {
    2558           8 :             poNewBand->SetNoDataValueInternal(
    2559             :                 CPLAtof(m_osNodataValueFromMetadata.c_str()));
    2560             :         }
    2561             : 
    2562        1494 :         SetBand(i, std::move(poNewBand));
    2563             :     }
    2564             : 
    2565         597 :     if (!ComputeTileAndPixelShifts())
    2566             :     {
    2567           3 :         CPLError(CE_Failure, CPLE_AppDefined,
    2568             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    2569           3 :         return false;
    2570             :     }
    2571             : 
    2572         594 :     GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    2573         594 :     GDALPamDataset::SetMetadataItem("ZOOM_LEVEL",
    2574             :                                     CPLSPrintf("%d", m_nZoomLevel));
    2575             : 
    2576         594 :     return AllocCachedTiles();
    2577             : }
    2578             : 
    2579             : /************************************************************************/
    2580             : /*                 GDALGPKGMBTilesGetTileFormat()                       */
    2581             : /************************************************************************/
    2582             : 
    2583          80 : GPKGTileFormat GDALGPKGMBTilesGetTileFormat(const char *pszTF)
    2584             : {
    2585          80 :     GPKGTileFormat eTF = GPKG_TF_PNG_JPEG;
    2586          80 :     if (pszTF)
    2587             :     {
    2588          80 :         if (EQUAL(pszTF, "PNG_JPEG") || EQUAL(pszTF, "AUTO"))
    2589           1 :             eTF = GPKG_TF_PNG_JPEG;
    2590          79 :         else if (EQUAL(pszTF, "PNG"))
    2591          46 :             eTF = GPKG_TF_PNG;
    2592          33 :         else if (EQUAL(pszTF, "PNG8"))
    2593           6 :             eTF = GPKG_TF_PNG8;
    2594          27 :         else if (EQUAL(pszTF, "JPEG"))
    2595          14 :             eTF = GPKG_TF_JPEG;
    2596          13 :         else if (EQUAL(pszTF, "WEBP"))
    2597          13 :             eTF = GPKG_TF_WEBP;
    2598             :         else
    2599             :         {
    2600           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2601             :                      "Unsuppoted value for TILE_FORMAT: %s", pszTF);
    2602             :         }
    2603             :     }
    2604          80 :     return eTF;
    2605             : }
    2606             : 
    2607          28 : const char *GDALMBTilesGetTileFormatName(GPKGTileFormat eTF)
    2608             : {
    2609          28 :     switch (eTF)
    2610             :     {
    2611          26 :         case GPKG_TF_PNG:
    2612             :         case GPKG_TF_PNG8:
    2613          26 :             return "png";
    2614           1 :         case GPKG_TF_JPEG:
    2615           1 :             return "jpg";
    2616           1 :         case GPKG_TF_WEBP:
    2617           1 :             return "webp";
    2618           0 :         default:
    2619           0 :             break;
    2620             :     }
    2621           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2622             :              "Unsuppoted value for TILE_FORMAT: %d", static_cast<int>(eTF));
    2623           0 :     return nullptr;
    2624             : }
    2625             : 
    2626             : /************************************************************************/
    2627             : /*                         OpenRaster()                                 */
    2628             : /************************************************************************/
    2629             : 
    2630         274 : bool GDALGeoPackageDataset::OpenRaster(
    2631             :     const char *pszTableName, const char *pszIdentifier,
    2632             :     const char *pszDescription, int nSRSId, double dfMinX, double dfMinY,
    2633             :     double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2634             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2635             :     const char *pszContentsMaxY, bool bIsTiles, char **papszOpenOptionsIn)
    2636             : {
    2637         274 :     if (dfMinX >= dfMaxX || dfMinY >= dfMaxY)
    2638           0 :         return false;
    2639             : 
    2640             :     // Config option just for debug, and for example force set to NaN
    2641             :     // which is not supported
    2642         548 :     CPLString osDataNull = CPLGetConfigOption("GPKG_NODATA", "");
    2643         548 :     CPLString osUom;
    2644         548 :     CPLString osFieldName;
    2645         548 :     CPLString osGridCellEncoding;
    2646         274 :     if (!bIsTiles)
    2647             :     {
    2648          65 :         char *pszSQL = sqlite3_mprintf(
    2649             :             "SELECT datatype, scale, offset, data_null, precision FROM "
    2650             :             "gpkg_2d_gridded_coverage_ancillary "
    2651             :             "WHERE tile_matrix_set_name = '%q' "
    2652             :             "AND datatype IN ('integer', 'float')"
    2653             :             "AND (scale > 0 OR scale IS NULL)",
    2654             :             pszTableName);
    2655          65 :         auto oResult = SQLQuery(hDB, pszSQL);
    2656          65 :         sqlite3_free(pszSQL);
    2657          65 :         if (!oResult || oResult->RowCount() == 0)
    2658             :         {
    2659           0 :             return false;
    2660             :         }
    2661          65 :         const char *pszDataType = oResult->GetValue(0, 0);
    2662          65 :         const char *pszScale = oResult->GetValue(1, 0);
    2663          65 :         const char *pszOffset = oResult->GetValue(2, 0);
    2664          65 :         const char *pszDataNull = oResult->GetValue(3, 0);
    2665          65 :         const char *pszPrecision = oResult->GetValue(4, 0);
    2666          65 :         if (pszDataNull)
    2667          23 :             osDataNull = pszDataNull;
    2668          65 :         if (EQUAL(pszDataType, "float"))
    2669             :         {
    2670           6 :             SetDataType(GDT_Float32);
    2671           6 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    2672             :         }
    2673             :         else
    2674             :         {
    2675          59 :             SetDataType(GDT_Float32);
    2676          59 :             m_eTF = GPKG_TF_PNG_16BIT;
    2677          59 :             const double dfScale = pszScale ? CPLAtof(pszScale) : 1.0;
    2678          59 :             const double dfOffset = pszOffset ? CPLAtof(pszOffset) : 0.0;
    2679          59 :             if (dfScale == 1.0)
    2680             :             {
    2681          59 :                 if (dfOffset == 0.0)
    2682             :                 {
    2683          24 :                     SetDataType(GDT_UInt16);
    2684             :                 }
    2685          35 :                 else if (dfOffset == -32768.0)
    2686             :                 {
    2687          35 :                     SetDataType(GDT_Int16);
    2688             :                 }
    2689             :                 // coverity[tainted_data]
    2690           0 :                 else if (dfOffset == -32767.0 && !osDataNull.empty() &&
    2691           0 :                          CPLAtof(osDataNull) == 65535.0)
    2692             :                 // Given that we will map the nodata value to -32768
    2693             :                 {
    2694           0 :                     SetDataType(GDT_Int16);
    2695             :                 }
    2696             :             }
    2697             : 
    2698             :             // Check that the tile offset and scales are compatible of a
    2699             :             // final integer result.
    2700          59 :             if (m_eDT != GDT_Float32)
    2701             :             {
    2702             :                 // coverity[tainted_data]
    2703          59 :                 if (dfScale == 1.0 && dfOffset == -32768.0 &&
    2704         118 :                     !osDataNull.empty() && CPLAtof(osDataNull) == 65535.0)
    2705             :                 {
    2706             :                     // Given that we will map the nodata value to -32768
    2707           9 :                     pszSQL = sqlite3_mprintf(
    2708             :                         "SELECT 1 FROM "
    2709             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2710             :                         "tpudt_name = '%q' "
    2711             :                         "AND NOT ((offset = 0.0 or offset = 1.0) "
    2712             :                         "AND scale = 1.0) "
    2713             :                         "LIMIT 1",
    2714             :                         pszTableName);
    2715             :                 }
    2716             :                 else
    2717             :                 {
    2718          50 :                     pszSQL = sqlite3_mprintf(
    2719             :                         "SELECT 1 FROM "
    2720             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2721             :                         "tpudt_name = '%q' "
    2722             :                         "AND NOT (offset = 0.0 AND scale = 1.0) LIMIT 1",
    2723             :                         pszTableName);
    2724             :                 }
    2725          59 :                 sqlite3_stmt *hSQLStmt = nullptr;
    2726             :                 int rc =
    2727          59 :                     SQLPrepareWithError(hDB, pszSQL, -1, &hSQLStmt, nullptr);
    2728             : 
    2729          59 :                 if (rc == SQLITE_OK)
    2730             :                 {
    2731          59 :                     if (sqlite3_step(hSQLStmt) == SQLITE_ROW)
    2732             :                     {
    2733           8 :                         SetDataType(GDT_Float32);
    2734             :                     }
    2735          59 :                     sqlite3_finalize(hSQLStmt);
    2736             :                 }
    2737          59 :                 sqlite3_free(pszSQL);
    2738             :             }
    2739             : 
    2740          59 :             SetGlobalOffsetScale(dfOffset, dfScale);
    2741             :         }
    2742          65 :         if (pszPrecision)
    2743          65 :             m_dfPrecision = CPLAtof(pszPrecision);
    2744             : 
    2745             :         // Request those columns in a separate query, so as to keep
    2746             :         // compatibility with pre OGC 17-066r1 databases
    2747             :         pszSQL =
    2748          65 :             sqlite3_mprintf("SELECT uom, field_name, grid_cell_encoding FROM "
    2749             :                             "gpkg_2d_gridded_coverage_ancillary "
    2750             :                             "WHERE tile_matrix_set_name = '%q'",
    2751             :                             pszTableName);
    2752          65 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    2753          65 :         oResult = SQLQuery(hDB, pszSQL);
    2754          65 :         CPLPopErrorHandler();
    2755          65 :         sqlite3_free(pszSQL);
    2756          65 :         if (oResult && oResult->RowCount() == 1)
    2757             :         {
    2758          64 :             const char *pszUom = oResult->GetValue(0, 0);
    2759          64 :             if (pszUom)
    2760           2 :                 osUom = pszUom;
    2761          64 :             const char *pszFieldName = oResult->GetValue(1, 0);
    2762          64 :             if (pszFieldName)
    2763          64 :                 osFieldName = pszFieldName;
    2764          64 :             const char *pszGridCellEncoding = oResult->GetValue(2, 0);
    2765          64 :             if (pszGridCellEncoding)
    2766          64 :                 osGridCellEncoding = pszGridCellEncoding;
    2767             :         }
    2768             :     }
    2769             : 
    2770         274 :     m_bRecordInsertedInGPKGContent = true;
    2771         274 :     m_nSRID = nSRSId;
    2772             : 
    2773         547 :     if (auto poSRS = GetSpatialRef(nSRSId))
    2774             :     {
    2775         273 :         m_oSRS = *(poSRS.get());
    2776             :     }
    2777             : 
    2778             :     /* Various sanity checks added in the SELECT */
    2779         274 :     char *pszQuotedTableName = sqlite3_mprintf("'%q'", pszTableName);
    2780         548 :     CPLString osQuotedTableName(pszQuotedTableName);
    2781         274 :     sqlite3_free(pszQuotedTableName);
    2782         274 :     char *pszSQL = sqlite3_mprintf(
    2783             :         "SELECT zoom_level, pixel_x_size, pixel_y_size, tile_width, "
    2784             :         "tile_height, matrix_width, matrix_height "
    2785             :         "FROM gpkg_tile_matrix tm "
    2786             :         "WHERE table_name = %s "
    2787             :         // INT_MAX would be the theoretical maximum value to avoid
    2788             :         // overflows, but that's already a insane value.
    2789             :         "AND zoom_level >= 0 AND zoom_level <= 65536 "
    2790             :         "AND pixel_x_size > 0 AND pixel_y_size > 0 "
    2791             :         "AND tile_width >= 1 AND tile_width <= 65536 "
    2792             :         "AND tile_height >= 1 AND tile_height <= 65536 "
    2793             :         "AND matrix_width >= 1 AND matrix_height >= 1",
    2794             :         osQuotedTableName.c_str());
    2795         548 :     CPLString osSQL(pszSQL);
    2796             :     const char *pszZoomLevel =
    2797         274 :         CSLFetchNameValue(papszOpenOptionsIn, "ZOOM_LEVEL");
    2798         274 :     if (pszZoomLevel)
    2799             :     {
    2800           5 :         if (GetUpdate())
    2801           1 :             osSQL += CPLSPrintf(" AND zoom_level <= %d", atoi(pszZoomLevel));
    2802             :         else
    2803             :         {
    2804             :             osSQL += CPLSPrintf(
    2805             :                 " AND (zoom_level = %d OR (zoom_level < %d AND EXISTS(SELECT 1 "
    2806             :                 "FROM %s WHERE zoom_level = tm.zoom_level LIMIT 1)))",
    2807             :                 atoi(pszZoomLevel), atoi(pszZoomLevel),
    2808           4 :                 osQuotedTableName.c_str());
    2809             :         }
    2810             :     }
    2811             :     // In read-only mode, only lists non empty zoom levels
    2812         269 :     else if (!GetUpdate())
    2813             :     {
    2814             :         osSQL += CPLSPrintf(" AND EXISTS(SELECT 1 FROM %s WHERE zoom_level = "
    2815             :                             "tm.zoom_level LIMIT 1)",
    2816         215 :                             osQuotedTableName.c_str());
    2817             :     }
    2818             :     else  // if( pszZoomLevel == nullptr )
    2819             :     {
    2820             :         osSQL +=
    2821             :             CPLSPrintf(" AND zoom_level <= (SELECT MAX(zoom_level) FROM %s)",
    2822          54 :                        osQuotedTableName.c_str());
    2823             :     }
    2824         274 :     osSQL += " ORDER BY zoom_level DESC";
    2825             :     // To avoid denial of service.
    2826         274 :     osSQL += " LIMIT 100";
    2827             : 
    2828         548 :     auto oResult = SQLQuery(hDB, osSQL.c_str());
    2829         274 :     if (!oResult || oResult->RowCount() == 0)
    2830             :     {
    2831         114 :         if (oResult && oResult->RowCount() == 0 && pszContentsMinX != nullptr &&
    2832         114 :             pszContentsMinY != nullptr && pszContentsMaxX != nullptr &&
    2833             :             pszContentsMaxY != nullptr)
    2834             :         {
    2835          56 :             osSQL = pszSQL;
    2836          56 :             osSQL += " ORDER BY zoom_level DESC";
    2837          56 :             if (!GetUpdate())
    2838          30 :                 osSQL += " LIMIT 1";
    2839          56 :             oResult = SQLQuery(hDB, osSQL.c_str());
    2840             :         }
    2841          57 :         if (!oResult || oResult->RowCount() == 0)
    2842             :         {
    2843           1 :             if (oResult && pszZoomLevel != nullptr)
    2844             :             {
    2845           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2846             :                          "ZOOM_LEVEL is probably not valid w.r.t tile "
    2847             :                          "table content");
    2848             :             }
    2849           1 :             sqlite3_free(pszSQL);
    2850           1 :             return false;
    2851             :         }
    2852             :     }
    2853         273 :     sqlite3_free(pszSQL);
    2854             : 
    2855             :     // If USE_TILE_EXTENT=YES, then query the tile table to find which tiles
    2856             :     // actually exist.
    2857             : 
    2858             :     // CAUTION: Do not move those variables inside inner scope !
    2859         546 :     CPLString osContentsMinX, osContentsMinY, osContentsMaxX, osContentsMaxY;
    2860             : 
    2861         273 :     if (CPLTestBool(
    2862             :             CSLFetchNameValueDef(papszOpenOptionsIn, "USE_TILE_EXTENT", "NO")))
    2863             :     {
    2864          13 :         pszSQL = sqlite3_mprintf(
    2865             :             "SELECT MIN(tile_column), MIN(tile_row), MAX(tile_column), "
    2866             :             "MAX(tile_row) FROM \"%w\" WHERE zoom_level = %d",
    2867             :             pszTableName, atoi(oResult->GetValue(0, 0)));
    2868          13 :         auto oResult2 = SQLQuery(hDB, pszSQL);
    2869          13 :         sqlite3_free(pszSQL);
    2870          26 :         if (!oResult2 || oResult2->RowCount() == 0 ||
    2871             :             // Can happen if table is empty
    2872          38 :             oResult2->GetValue(0, 0) == nullptr ||
    2873             :             // Can happen if table has no NOT NULL constraint on tile_row
    2874             :             // and that all tile_row are NULL
    2875          12 :             oResult2->GetValue(1, 0) == nullptr)
    2876             :         {
    2877           1 :             return false;
    2878             :         }
    2879          12 :         const double dfPixelXSize = CPLAtof(oResult->GetValue(1, 0));
    2880          12 :         const double dfPixelYSize = CPLAtof(oResult->GetValue(2, 0));
    2881          12 :         const int nTileWidth = atoi(oResult->GetValue(3, 0));
    2882          12 :         const int nTileHeight = atoi(oResult->GetValue(4, 0));
    2883             :         osContentsMinX =
    2884          24 :             CPLSPrintf("%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2885          12 :                                              atoi(oResult2->GetValue(0, 0)));
    2886             :         osContentsMaxY =
    2887          24 :             CPLSPrintf("%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2888          12 :                                              atoi(oResult2->GetValue(1, 0)));
    2889             :         osContentsMaxX = CPLSPrintf(
    2890          24 :             "%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2891          12 :                                   (1 + atoi(oResult2->GetValue(2, 0))));
    2892             :         osContentsMinY = CPLSPrintf(
    2893          24 :             "%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2894          12 :                                   (1 + atoi(oResult2->GetValue(3, 0))));
    2895          12 :         pszContentsMinX = osContentsMinX.c_str();
    2896          12 :         pszContentsMinY = osContentsMinY.c_str();
    2897          12 :         pszContentsMaxX = osContentsMaxX.c_str();
    2898          12 :         pszContentsMaxY = osContentsMaxY.c_str();
    2899             :     }
    2900             : 
    2901         272 :     if (!InitRaster(nullptr, pszTableName, dfMinX, dfMinY, dfMaxX, dfMaxY,
    2902             :                     pszContentsMinX, pszContentsMinY, pszContentsMaxX,
    2903         272 :                     pszContentsMaxY, papszOpenOptionsIn, *oResult, 0))
    2904             :     {
    2905           3 :         return false;
    2906             :     }
    2907             : 
    2908         269 :     auto poBand = cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(1));
    2909         269 :     if (!osDataNull.empty())
    2910             :     {
    2911          23 :         double dfGPKGNoDataValue = CPLAtof(osDataNull);
    2912          23 :         if (m_eTF == GPKG_TF_PNG_16BIT)
    2913             :         {
    2914          21 :             if (dfGPKGNoDataValue < 0 || dfGPKGNoDataValue > 65535 ||
    2915          21 :                 static_cast<int>(dfGPKGNoDataValue) != dfGPKGNoDataValue)
    2916             :             {
    2917           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2918             :                          "data_null = %.17g is invalid for integer data_type",
    2919             :                          dfGPKGNoDataValue);
    2920             :             }
    2921             :             else
    2922             :             {
    2923          21 :                 m_usGPKGNull = static_cast<GUInt16>(dfGPKGNoDataValue);
    2924          21 :                 if (m_eDT == GDT_Int16 && m_usGPKGNull > 32767)
    2925           9 :                     dfGPKGNoDataValue = -32768.0;
    2926          12 :                 else if (m_eDT == GDT_Float32)
    2927             :                 {
    2928             :                     // Pick a value that is unlikely to be hit with offset &
    2929             :                     // scale
    2930           4 :                     dfGPKGNoDataValue = -std::numeric_limits<float>::max();
    2931             :                 }
    2932          21 :                 poBand->SetNoDataValueInternal(dfGPKGNoDataValue);
    2933             :             }
    2934             :         }
    2935             :         else
    2936             :         {
    2937           2 :             poBand->SetNoDataValueInternal(
    2938           2 :                 static_cast<float>(dfGPKGNoDataValue));
    2939             :         }
    2940             :     }
    2941         269 :     if (!osUom.empty())
    2942             :     {
    2943           2 :         poBand->SetUnitTypeInternal(osUom);
    2944             :     }
    2945         269 :     if (!osFieldName.empty())
    2946             :     {
    2947          64 :         GetRasterBand(1)->GDALRasterBand::SetDescription(osFieldName);
    2948             :     }
    2949         269 :     if (!osGridCellEncoding.empty())
    2950             :     {
    2951          64 :         if (osGridCellEncoding == "grid-value-is-center")
    2952             :         {
    2953          15 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2954             :                                             GDALMD_AOP_POINT);
    2955             :         }
    2956          49 :         else if (osGridCellEncoding == "grid-value-is-area")
    2957             :         {
    2958          45 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2959             :                                             GDALMD_AOP_AREA);
    2960             :         }
    2961             :         else
    2962             :         {
    2963           4 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2964             :                                             GDALMD_AOP_POINT);
    2965           4 :             GetRasterBand(1)->GDALRasterBand::SetMetadataItem(
    2966             :                 "GRID_CELL_ENCODING", osGridCellEncoding);
    2967             :         }
    2968             :     }
    2969             : 
    2970         269 :     CheckUnknownExtensions(true);
    2971             : 
    2972             :     // Do this after CheckUnknownExtensions() so that m_eTF is set to
    2973             :     // GPKG_TF_WEBP if the table already registers the gpkg_webp extension
    2974         269 :     const char *pszTF = CSLFetchNameValue(papszOpenOptionsIn, "TILE_FORMAT");
    2975         269 :     if (pszTF)
    2976             :     {
    2977           4 :         if (!GetUpdate())
    2978             :         {
    2979           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2980             :                      "TILE_FORMAT open option ignored in read-only mode");
    2981             :         }
    2982           4 :         else if (m_eTF == GPKG_TF_PNG_16BIT ||
    2983           4 :                  m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    2984             :         {
    2985           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2986             :                      "TILE_FORMAT open option ignored on gridded coverages");
    2987             :         }
    2988             :         else
    2989             :         {
    2990           4 :             GPKGTileFormat eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    2991           4 :             if (eTF == GPKG_TF_WEBP && m_eTF != eTF)
    2992             :             {
    2993           1 :                 if (!RegisterWebPExtension())
    2994           0 :                     return false;
    2995             :             }
    2996           4 :             m_eTF = eTF;
    2997             :         }
    2998             :     }
    2999             : 
    3000         269 :     ParseCompressionOptions(papszOpenOptionsIn);
    3001             : 
    3002         269 :     m_osWHERE = CSLFetchNameValueDef(papszOpenOptionsIn, "WHERE", "");
    3003             : 
    3004             :     // Set metadata
    3005         269 :     if (pszIdentifier && pszIdentifier[0])
    3006         269 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", pszIdentifier);
    3007         269 :     if (pszDescription && pszDescription[0])
    3008          21 :         GDALPamDataset::SetMetadataItem("DESCRIPTION", pszDescription);
    3009             : 
    3010             :     // Add overviews
    3011         354 :     for (int i = 1; i < oResult->RowCount(); i++)
    3012             :     {
    3013          86 :         auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3014          86 :         poOvrDS->ShareLockWithParentDataset(this);
    3015         172 :         if (!poOvrDS->InitRaster(this, pszTableName, dfMinX, dfMinY, dfMaxX,
    3016             :                                  dfMaxY, pszContentsMinX, pszContentsMinY,
    3017             :                                  pszContentsMaxX, pszContentsMaxY,
    3018          86 :                                  papszOpenOptionsIn, *oResult, i))
    3019             :         {
    3020           0 :             break;
    3021             :         }
    3022             : 
    3023             :         int nTileWidth, nTileHeight;
    3024          86 :         poOvrDS->GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3025             :         const bool bStop =
    3026          87 :             (eAccess == GA_ReadOnly && poOvrDS->GetRasterXSize() < nTileWidth &&
    3027           1 :              poOvrDS->GetRasterYSize() < nTileHeight);
    3028             : 
    3029          86 :         m_apoOverviewDS.push_back(std::move(poOvrDS));
    3030             : 
    3031          86 :         if (bStop)
    3032             :         {
    3033           1 :             break;
    3034             :         }
    3035             :     }
    3036             : 
    3037         269 :     return true;
    3038             : }
    3039             : 
    3040             : /************************************************************************/
    3041             : /*                           GetSpatialRef()                            */
    3042             : /************************************************************************/
    3043             : 
    3044          17 : const OGRSpatialReference *GDALGeoPackageDataset::GetSpatialRef() const
    3045             : {
    3046          17 :     if (GetLayerCount())
    3047           1 :         return GDALDataset::GetSpatialRef();
    3048          16 :     return GetSpatialRefRasterOnly();
    3049             : }
    3050             : 
    3051             : /************************************************************************/
    3052             : /*                      GetSpatialRefRasterOnly()                       */
    3053             : /************************************************************************/
    3054             : 
    3055             : const OGRSpatialReference *
    3056          17 : GDALGeoPackageDataset::GetSpatialRefRasterOnly() const
    3057             : 
    3058             : {
    3059          17 :     return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
    3060             : }
    3061             : 
    3062             : /************************************************************************/
    3063             : /*                           SetSpatialRef()                            */
    3064             : /************************************************************************/
    3065             : 
    3066         152 : CPLErr GDALGeoPackageDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    3067             : {
    3068         152 :     if (nBands == 0)
    3069             :     {
    3070           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3071             :                  "SetProjection() not supported on a dataset with 0 band");
    3072           1 :         return CE_Failure;
    3073             :     }
    3074         151 :     if (eAccess != GA_Update)
    3075             :     {
    3076           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3077             :                  "SetProjection() not supported on read-only dataset");
    3078           1 :         return CE_Failure;
    3079             :     }
    3080             : 
    3081         150 :     const int nSRID = GetSrsId(poSRS);
    3082         300 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3083         150 :     if (poTS && nSRID != poTS->nEPSGCode)
    3084             :     {
    3085           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3086             :                  "Projection should be EPSG:%d for %s tiling scheme",
    3087           1 :                  poTS->nEPSGCode, m_osTilingScheme.c_str());
    3088           1 :         return CE_Failure;
    3089             :     }
    3090             : 
    3091         149 :     m_nSRID = nSRID;
    3092         149 :     m_oSRS.Clear();
    3093         149 :     if (poSRS)
    3094         148 :         m_oSRS = *poSRS;
    3095             : 
    3096         149 :     if (m_bRecordInsertedInGPKGContent)
    3097             :     {
    3098         121 :         char *pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET srs_id = %d "
    3099             :                                        "WHERE lower(table_name) = lower('%q')",
    3100             :                                        m_nSRID, m_osRasterTable.c_str());
    3101         121 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3102         121 :         sqlite3_free(pszSQL);
    3103         121 :         if (eErr != OGRERR_NONE)
    3104           0 :             return CE_Failure;
    3105             : 
    3106         121 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_tile_matrix_set SET srs_id = %d "
    3107             :                                  "WHERE lower(table_name) = lower('%q')",
    3108             :                                  m_nSRID, m_osRasterTable.c_str());
    3109         121 :         eErr = SQLCommand(hDB, pszSQL);
    3110         121 :         sqlite3_free(pszSQL);
    3111         121 :         if (eErr != OGRERR_NONE)
    3112           0 :             return CE_Failure;
    3113             :     }
    3114             : 
    3115         149 :     return CE_None;
    3116             : }
    3117             : 
    3118             : /************************************************************************/
    3119             : /*                          GetGeoTransform()                           */
    3120             : /************************************************************************/
    3121             : 
    3122          33 : CPLErr GDALGeoPackageDataset::GetGeoTransform(GDALGeoTransform &gt) const
    3123             : {
    3124          33 :     gt = m_gt;
    3125          33 :     if (!m_bGeoTransformValid)
    3126           2 :         return CE_Failure;
    3127             :     else
    3128          31 :         return CE_None;
    3129             : }
    3130             : 
    3131             : /************************************************************************/
    3132             : /*                          SetGeoTransform()                           */
    3133             : /************************************************************************/
    3134             : 
    3135         192 : CPLErr GDALGeoPackageDataset::SetGeoTransform(const GDALGeoTransform &gt)
    3136             : {
    3137         192 :     if (nBands == 0)
    3138             :     {
    3139           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3140             :                  "SetGeoTransform() not supported on a dataset with 0 band");
    3141           2 :         return CE_Failure;
    3142             :     }
    3143         190 :     if (eAccess != GA_Update)
    3144             :     {
    3145           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3146             :                  "SetGeoTransform() not supported on read-only dataset");
    3147           1 :         return CE_Failure;
    3148             :     }
    3149         189 :     if (m_bGeoTransformValid)
    3150             :     {
    3151           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3152             :                  "Cannot modify geotransform once set");
    3153           1 :         return CE_Failure;
    3154             :     }
    3155         188 :     if (gt[2] != 0.0 || gt[4] != 0 || gt[5] > 0.0)
    3156             :     {
    3157           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3158             :                  "Only north-up non rotated geotransform supported");
    3159           0 :         return CE_Failure;
    3160             :     }
    3161             : 
    3162         188 :     if (m_nZoomLevel < 0)
    3163             :     {
    3164         187 :         const auto poTS = GetTilingScheme(m_osTilingScheme);
    3165         187 :         if (poTS)
    3166             :         {
    3167          20 :             double dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3168          20 :             double dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3169         199 :             for (m_nZoomLevel = 0; m_nZoomLevel < MAX_ZOOM_LEVEL;
    3170         179 :                  m_nZoomLevel++)
    3171             :             {
    3172         198 :                 double dfExpectedPixelXSize =
    3173         198 :                     dfPixelXSizeZoomLevel0 / (1 << m_nZoomLevel);
    3174         198 :                 double dfExpectedPixelYSize =
    3175         198 :                     dfPixelYSizeZoomLevel0 / (1 << m_nZoomLevel);
    3176         198 :                 if (fabs(gt[1] - dfExpectedPixelXSize) <
    3177         217 :                         1e-8 * dfExpectedPixelXSize &&
    3178          19 :                     fabs(fabs(gt[5]) - dfExpectedPixelYSize) <
    3179          19 :                         1e-8 * dfExpectedPixelYSize)
    3180             :                 {
    3181          19 :                     break;
    3182             :                 }
    3183             :             }
    3184          20 :             if (m_nZoomLevel == MAX_ZOOM_LEVEL)
    3185             :             {
    3186           1 :                 m_nZoomLevel = -1;
    3187           1 :                 CPLError(
    3188             :                     CE_Failure, CPLE_NotSupported,
    3189             :                     "Could not find an appropriate zoom level of %s tiling "
    3190             :                     "scheme that matches raster pixel size",
    3191             :                     m_osTilingScheme.c_str());
    3192           1 :                 return CE_Failure;
    3193             :             }
    3194             :         }
    3195             :     }
    3196             : 
    3197         187 :     m_gt = gt;
    3198         187 :     m_bGeoTransformValid = true;
    3199             : 
    3200         187 :     return FinalizeRasterRegistration();
    3201             : }
    3202             : 
    3203             : /************************************************************************/
    3204             : /*                      FinalizeRasterRegistration()                    */
    3205             : /************************************************************************/
    3206             : 
    3207         187 : CPLErr GDALGeoPackageDataset::FinalizeRasterRegistration()
    3208             : {
    3209             :     OGRErr eErr;
    3210             : 
    3211         187 :     m_dfTMSMinX = m_gt[0];
    3212         187 :     m_dfTMSMaxY = m_gt[3];
    3213             : 
    3214             :     int nTileWidth, nTileHeight;
    3215         187 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3216             : 
    3217         187 :     if (m_nZoomLevel < 0)
    3218             :     {
    3219         167 :         m_nZoomLevel = 0;
    3220         241 :         while ((nRasterXSize >> m_nZoomLevel) > nTileWidth ||
    3221         167 :                (nRasterYSize >> m_nZoomLevel) > nTileHeight)
    3222          74 :             m_nZoomLevel++;
    3223             :     }
    3224             : 
    3225         187 :     double dfPixelXSizeZoomLevel0 = m_gt[1] * (1 << m_nZoomLevel);
    3226         187 :     double dfPixelYSizeZoomLevel0 = fabs(m_gt[5]) * (1 << m_nZoomLevel);
    3227             :     int nTileXCountZoomLevel0 =
    3228         187 :         std::max(1, DIV_ROUND_UP((nRasterXSize >> m_nZoomLevel), nTileWidth));
    3229             :     int nTileYCountZoomLevel0 =
    3230         187 :         std::max(1, DIV_ROUND_UP((nRasterYSize >> m_nZoomLevel), nTileHeight));
    3231             : 
    3232         374 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3233         187 :     if (poTS)
    3234             :     {
    3235          20 :         CPLAssert(m_nZoomLevel >= 0);
    3236          20 :         m_dfTMSMinX = poTS->dfMinX;
    3237          20 :         m_dfTMSMaxY = poTS->dfMaxY;
    3238          20 :         dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3239          20 :         dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3240          20 :         nTileXCountZoomLevel0 = poTS->nTileXCountZoomLevel0;
    3241          20 :         nTileYCountZoomLevel0 = poTS->nTileYCountZoomLevel0;
    3242             :     }
    3243         187 :     m_nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << m_nZoomLevel);
    3244         187 :     m_nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << m_nZoomLevel);
    3245             : 
    3246         187 :     if (!ComputeTileAndPixelShifts())
    3247             :     {
    3248           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    3249             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    3250           1 :         return CE_Failure;
    3251             :     }
    3252             : 
    3253         186 :     if (!AllocCachedTiles())
    3254             :     {
    3255           0 :         return CE_Failure;
    3256             :     }
    3257             : 
    3258         186 :     double dfGDALMinX = m_gt[0];
    3259         186 :     double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3260         186 :     double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3261         186 :     double dfGDALMaxY = m_gt[3];
    3262             : 
    3263         186 :     if (SoftStartTransaction() != OGRERR_NONE)
    3264           0 :         return CE_Failure;
    3265             : 
    3266             :     const char *pszCurrentDate =
    3267         186 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3268             :     CPLString osInsertGpkgContentsFormatting(
    3269             :         "INSERT INTO gpkg_contents "
    3270             :         "(table_name,data_type,identifier,description,min_x,min_y,max_x,max_y,"
    3271             :         "last_change,srs_id) VALUES "
    3272         372 :         "('%q','%q','%q','%q',%.17g,%.17g,%.17g,%.17g,");
    3273         186 :     osInsertGpkgContentsFormatting += (pszCurrentDate) ? "'%q'" : "%s";
    3274         186 :     osInsertGpkgContentsFormatting += ",%d)";
    3275         372 :     char *pszSQL = sqlite3_mprintf(
    3276             :         osInsertGpkgContentsFormatting.c_str(), m_osRasterTable.c_str(),
    3277         186 :         (m_eDT == GDT_UInt8) ? "tiles" : "2d-gridded-coverage",
    3278             :         m_osIdentifier.c_str(), m_osDescription.c_str(), dfGDALMinX, dfGDALMinY,
    3279             :         dfGDALMaxX, dfGDALMaxY,
    3280             :         pszCurrentDate ? pszCurrentDate
    3281             :                        : "strftime('%Y-%m-%dT%H:%M:%fZ','now')",
    3282             :         m_nSRID);
    3283             : 
    3284         186 :     eErr = SQLCommand(hDB, pszSQL);
    3285         186 :     sqlite3_free(pszSQL);
    3286         186 :     if (eErr != OGRERR_NONE)
    3287             :     {
    3288           8 :         SoftRollbackTransaction();
    3289           8 :         return CE_Failure;
    3290             :     }
    3291             : 
    3292         178 :     double dfTMSMaxX = m_dfTMSMinX + nTileXCountZoomLevel0 * nTileWidth *
    3293             :                                          dfPixelXSizeZoomLevel0;
    3294         178 :     double dfTMSMinY = m_dfTMSMaxY - nTileYCountZoomLevel0 * nTileHeight *
    3295             :                                          dfPixelYSizeZoomLevel0;
    3296             : 
    3297             :     pszSQL =
    3298         178 :         sqlite3_mprintf("INSERT INTO gpkg_tile_matrix_set "
    3299             :                         "(table_name,srs_id,min_x,min_y,max_x,max_y) VALUES "
    3300             :                         "('%q',%d,%.17g,%.17g,%.17g,%.17g)",
    3301             :                         m_osRasterTable.c_str(), m_nSRID, m_dfTMSMinX,
    3302             :                         dfTMSMinY, dfTMSMaxX, m_dfTMSMaxY);
    3303         178 :     eErr = SQLCommand(hDB, pszSQL);
    3304         178 :     sqlite3_free(pszSQL);
    3305         178 :     if (eErr != OGRERR_NONE)
    3306             :     {
    3307           0 :         SoftRollbackTransaction();
    3308           0 :         return CE_Failure;
    3309             :     }
    3310             : 
    3311         178 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3312             : 
    3313         591 :     for (int i = 0; i <= m_nZoomLevel; i++)
    3314             :     {
    3315         413 :         double dfPixelXSizeZoomLevel = 0.0;
    3316         413 :         double dfPixelYSizeZoomLevel = 0.0;
    3317         413 :         int nTileMatrixWidth = 0;
    3318         413 :         int nTileMatrixHeight = 0;
    3319         413 :         if (EQUAL(m_osTilingScheme, "CUSTOM"))
    3320             :         {
    3321         232 :             dfPixelXSizeZoomLevel = m_gt[1] * (1 << (m_nZoomLevel - i));
    3322         232 :             dfPixelYSizeZoomLevel = fabs(m_gt[5]) * (1 << (m_nZoomLevel - i));
    3323             :         }
    3324             :         else
    3325             :         {
    3326         181 :             dfPixelXSizeZoomLevel = dfPixelXSizeZoomLevel0 / (1 << i);
    3327         181 :             dfPixelYSizeZoomLevel = dfPixelYSizeZoomLevel0 / (1 << i);
    3328             :         }
    3329         413 :         nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << i);
    3330         413 :         nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << i);
    3331             : 
    3332         413 :         pszSQL = sqlite3_mprintf(
    3333             :             "INSERT INTO gpkg_tile_matrix "
    3334             :             "(table_name,zoom_level,matrix_width,matrix_height,tile_width,tile_"
    3335             :             "height,pixel_x_size,pixel_y_size) VALUES "
    3336             :             "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3337             :             m_osRasterTable.c_str(), i, nTileMatrixWidth, nTileMatrixHeight,
    3338             :             nTileWidth, nTileHeight, dfPixelXSizeZoomLevel,
    3339             :             dfPixelYSizeZoomLevel);
    3340         413 :         eErr = SQLCommand(hDB, pszSQL);
    3341         413 :         sqlite3_free(pszSQL);
    3342         413 :         if (eErr != OGRERR_NONE)
    3343             :         {
    3344           0 :             SoftRollbackTransaction();
    3345           0 :             return CE_Failure;
    3346             :         }
    3347             : 
    3348         413 :         if (i < m_nZoomLevel)
    3349             :         {
    3350         470 :             auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3351         235 :             poOvrDS->ShareLockWithParentDataset(this);
    3352         235 :             poOvrDS->InitRaster(this, m_osRasterTable, i, nBands, m_dfTMSMinX,
    3353             :                                 m_dfTMSMaxY, dfPixelXSizeZoomLevel,
    3354             :                                 dfPixelYSizeZoomLevel, nTileWidth, nTileHeight,
    3355             :                                 nTileMatrixWidth, nTileMatrixHeight, dfGDALMinX,
    3356             :                                 dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    3357             : 
    3358         235 :             m_apoOverviewDS[m_nZoomLevel - 1 - i] = std::move(poOvrDS);
    3359             :         }
    3360             :     }
    3361             : 
    3362         178 :     if (!m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.empty())
    3363             :     {
    3364          40 :         eErr = SQLCommand(
    3365             :             hDB, m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.c_str());
    3366          40 :         m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.clear();
    3367          40 :         if (eErr != OGRERR_NONE)
    3368             :         {
    3369           0 :             SoftRollbackTransaction();
    3370           0 :             return CE_Failure;
    3371             :         }
    3372             :     }
    3373             : 
    3374         178 :     SoftCommitTransaction();
    3375             : 
    3376         178 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3377         178 :     m_bRecordInsertedInGPKGContent = true;
    3378             : 
    3379         178 :     return CE_None;
    3380             : }
    3381             : 
    3382             : /************************************************************************/
    3383             : /*                             FlushCache()                             */
    3384             : /************************************************************************/
    3385             : 
    3386        2828 : CPLErr GDALGeoPackageDataset::FlushCache(bool bAtClosing)
    3387             : {
    3388        2828 :     if (m_bInFlushCache)
    3389           0 :         return CE_None;
    3390             : 
    3391        2828 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3392             :     {
    3393        2825 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3394             :     }
    3395             : 
    3396        2828 :     if (m_bRemoveOGREmptyTable)
    3397             :     {
    3398         765 :         m_bRemoveOGREmptyTable = false;
    3399         765 :         RemoveOGREmptyTable();
    3400             :     }
    3401             : 
    3402        2828 :     CPLErr eErr = IFlushCacheWithErrCode(bAtClosing);
    3403             : 
    3404        2828 :     FlushMetadata();
    3405             : 
    3406        2828 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3407             :     {
    3408             :         // Needed again as above IFlushCacheWithErrCode()
    3409             :         // may have call GDALGeoPackageRasterBand::InvalidateStatistics()
    3410             :         // which modifies metadata
    3411        2828 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3412             :     }
    3413             : 
    3414        2828 :     return eErr;
    3415             : }
    3416             : 
    3417        5063 : CPLErr GDALGeoPackageDataset::IFlushCacheWithErrCode(bool bAtClosing)
    3418             : 
    3419             : {
    3420        5063 :     if (m_bInFlushCache)
    3421        2168 :         return CE_None;
    3422        2895 :     m_bInFlushCache = true;
    3423        2895 :     if (hDB && eAccess == GA_ReadOnly && bAtClosing)
    3424             :     {
    3425             :         // Clean-up metadata that will go to PAM by removing items that
    3426             :         // are reconstructed.
    3427        2104 :         CPLStringList aosMD;
    3428        1675 :         for (CSLConstList papszIter = GetMetadata(); papszIter && *papszIter;
    3429             :              ++papszIter)
    3430             :         {
    3431         623 :             char *pszKey = nullptr;
    3432         623 :             CPLParseNameValue(*papszIter, &pszKey);
    3433        1246 :             if (pszKey &&
    3434         623 :                 (EQUAL(pszKey, "AREA_OR_POINT") ||
    3435         477 :                  EQUAL(pszKey, "IDENTIFIER") || EQUAL(pszKey, "DESCRIPTION") ||
    3436         256 :                  EQUAL(pszKey, "ZOOM_LEVEL") ||
    3437         653 :                  STARTS_WITH(pszKey, "GPKG_METADATA_ITEM_")))
    3438             :             {
    3439             :                 // remove it
    3440             :             }
    3441             :             else
    3442             :             {
    3443          30 :                 aosMD.AddString(*papszIter);
    3444             :             }
    3445         623 :             CPLFree(pszKey);
    3446             :         }
    3447        1052 :         oMDMD.SetMetadata(aosMD.List());
    3448        1052 :         oMDMD.SetMetadata(nullptr, "IMAGE_STRUCTURE");
    3449             : 
    3450        2104 :         GDALPamDataset::FlushCache(bAtClosing);
    3451             :     }
    3452             :     else
    3453             :     {
    3454             :         // Short circuit GDALPamDataset to avoid serialization to .aux.xml
    3455        1843 :         GDALDataset::FlushCache(bAtClosing);
    3456             :     }
    3457             : 
    3458        7054 :     for (auto &poLayer : m_apoLayers)
    3459             :     {
    3460        4159 :         poLayer->RunDeferredCreationIfNecessary();
    3461        4159 :         poLayer->CreateSpatialIndexIfNecessary();
    3462             :     }
    3463             : 
    3464             :     // Update raster table last_change column in gpkg_contents if needed
    3465        2895 :     if (m_bHasModifiedTiles)
    3466             :     {
    3467         540 :         for (int i = 1; i <= nBands; ++i)
    3468             :         {
    3469             :             auto poBand =
    3470         359 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    3471         359 :             if (!poBand->HaveStatsMetadataBeenSetInThisSession())
    3472             :             {
    3473         346 :                 poBand->InvalidateStatistics();
    3474         346 :                 if (psPam && psPam->pszPamFilename)
    3475         346 :                     VSIUnlink(psPam->pszPamFilename);
    3476             :             }
    3477             :         }
    3478             : 
    3479         181 :         UpdateGpkgContentsLastChange(m_osRasterTable);
    3480             : 
    3481         181 :         m_bHasModifiedTiles = false;
    3482             :     }
    3483             : 
    3484        2895 :     CPLErr eErr = FlushTiles();
    3485             : 
    3486        2895 :     m_bInFlushCache = false;
    3487        2895 :     return eErr;
    3488             : }
    3489             : 
    3490             : /************************************************************************/
    3491             : /*                       GetCurrentDateEscapedSQL()                      */
    3492             : /************************************************************************/
    3493             : 
    3494        2138 : std::string GDALGeoPackageDataset::GetCurrentDateEscapedSQL()
    3495             : {
    3496             :     const char *pszCurrentDate =
    3497        2138 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3498        2138 :     if (pszCurrentDate)
    3499          10 :         return '\'' + SQLEscapeLiteral(pszCurrentDate) + '\'';
    3500        2133 :     return "strftime('%Y-%m-%dT%H:%M:%fZ','now')";
    3501             : }
    3502             : 
    3503             : /************************************************************************/
    3504             : /*                    UpdateGpkgContentsLastChange()                    */
    3505             : /************************************************************************/
    3506             : 
    3507             : OGRErr
    3508         936 : GDALGeoPackageDataset::UpdateGpkgContentsLastChange(const char *pszTableName)
    3509             : {
    3510             :     char *pszSQL =
    3511         936 :         sqlite3_mprintf("UPDATE gpkg_contents SET "
    3512             :                         "last_change = %s "
    3513             :                         "WHERE lower(table_name) = lower('%q')",
    3514        1872 :                         GetCurrentDateEscapedSQL().c_str(), pszTableName);
    3515         936 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    3516         936 :     sqlite3_free(pszSQL);
    3517         936 :     return eErr;
    3518             : }
    3519             : 
    3520             : /************************************************************************/
    3521             : /*                          IBuildOverviews()                           */
    3522             : /************************************************************************/
    3523             : 
    3524          20 : CPLErr GDALGeoPackageDataset::IBuildOverviews(
    3525             :     const char *pszResampling, int nOverviews, const int *panOverviewList,
    3526             :     int nBandsIn, const int * /*panBandList*/, GDALProgressFunc pfnProgress,
    3527             :     void *pProgressData, CSLConstList papszOptions)
    3528             : {
    3529          20 :     if (GetAccess() != GA_Update)
    3530             :     {
    3531           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3532             :                  "Overview building not supported on a database opened in "
    3533             :                  "read-only mode");
    3534           1 :         return CE_Failure;
    3535             :     }
    3536          19 :     if (m_poParentDS != nullptr)
    3537             :     {
    3538           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3539             :                  "Overview building not supported on overview dataset");
    3540           1 :         return CE_Failure;
    3541             :     }
    3542             : 
    3543          18 :     if (nOverviews == 0)
    3544             :     {
    3545           5 :         for (auto &poOvrDS : m_apoOverviewDS)
    3546           3 :             poOvrDS->FlushCache(false);
    3547             : 
    3548           2 :         SoftStartTransaction();
    3549             : 
    3550           2 :         if (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    3551             :         {
    3552           1 :             char *pszSQL = sqlite3_mprintf(
    3553             :                 "DELETE FROM gpkg_2d_gridded_tile_ancillary WHERE id IN "
    3554             :                 "(SELECT y.id FROM \"%w\" x "
    3555             :                 "JOIN gpkg_2d_gridded_tile_ancillary y "
    3556             :                 "ON x.id = y.tpudt_id AND y.tpudt_name = '%q' AND "
    3557             :                 "x.zoom_level < %d)",
    3558             :                 m_osRasterTable.c_str(), m_osRasterTable.c_str(), m_nZoomLevel);
    3559           1 :             OGRErr eErr = SQLCommand(hDB, pszSQL);
    3560           1 :             sqlite3_free(pszSQL);
    3561           1 :             if (eErr != OGRERR_NONE)
    3562             :             {
    3563           0 :                 SoftRollbackTransaction();
    3564           0 :                 return CE_Failure;
    3565             :             }
    3566             :         }
    3567             : 
    3568             :         char *pszSQL =
    3569           2 :             sqlite3_mprintf("DELETE FROM \"%w\" WHERE zoom_level < %d",
    3570             :                             m_osRasterTable.c_str(), m_nZoomLevel);
    3571           2 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3572           2 :         sqlite3_free(pszSQL);
    3573           2 :         if (eErr != OGRERR_NONE)
    3574             :         {
    3575           0 :             SoftRollbackTransaction();
    3576           0 :             return CE_Failure;
    3577             :         }
    3578             : 
    3579           2 :         SoftCommitTransaction();
    3580             : 
    3581           2 :         return CE_None;
    3582             :     }
    3583             : 
    3584          16 :     if (nBandsIn != nBands)
    3585             :     {
    3586           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3587             :                  "Generation of overviews in GPKG only"
    3588             :                  "supported when operating on all bands.");
    3589           0 :         return CE_Failure;
    3590             :     }
    3591             : 
    3592          16 :     if (m_apoOverviewDS.empty())
    3593             :     {
    3594           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3595             :                  "Image too small to support overviews");
    3596           0 :         return CE_Failure;
    3597             :     }
    3598             : 
    3599          16 :     FlushCache(false);
    3600          60 :     for (int i = 0; i < nOverviews; i++)
    3601             :     {
    3602          47 :         if (panOverviewList[i] < 2)
    3603             :         {
    3604           1 :             CPLError(CE_Failure, CPLE_IllegalArg,
    3605             :                      "Overview factor must be >= 2");
    3606           1 :             return CE_Failure;
    3607             :         }
    3608             : 
    3609          46 :         bool bFound = false;
    3610          46 :         int jCandidate = -1;
    3611          46 :         int nMaxOvFactor = 0;
    3612         196 :         for (int j = 0; j < static_cast<int>(m_apoOverviewDS.size()); j++)
    3613             :         {
    3614         190 :             const auto poODS = m_apoOverviewDS[j].get();
    3615             :             const int nOvFactor =
    3616         190 :                 static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3617             : 
    3618         190 :             nMaxOvFactor = nOvFactor;
    3619             : 
    3620         190 :             if (nOvFactor == panOverviewList[i])
    3621             :             {
    3622          40 :                 bFound = true;
    3623          40 :                 break;
    3624             :             }
    3625             : 
    3626         150 :             if (jCandidate < 0 && nOvFactor > panOverviewList[i])
    3627           1 :                 jCandidate = j;
    3628             :         }
    3629             : 
    3630          46 :         if (!bFound)
    3631             :         {
    3632             :             /* Mostly for debug */
    3633           6 :             if (!CPLTestBool(CPLGetConfigOption(
    3634             :                     "ALLOW_GPKG_ZOOM_OTHER_EXTENSION", "YES")))
    3635             :             {
    3636           2 :                 CPLString osOvrList;
    3637           4 :                 for (const auto &poODS : m_apoOverviewDS)
    3638             :                 {
    3639             :                     const int nOvFactor =
    3640           2 :                         static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3641             : 
    3642           2 :                     if (!osOvrList.empty())
    3643           0 :                         osOvrList += ' ';
    3644           2 :                     osOvrList += CPLSPrintf("%d", nOvFactor);
    3645             :                 }
    3646           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    3647             :                          "Only overviews %s can be computed",
    3648             :                          osOvrList.c_str());
    3649           2 :                 return CE_Failure;
    3650             :             }
    3651             :             else
    3652             :             {
    3653           4 :                 int nOvFactor = panOverviewList[i];
    3654           4 :                 if (jCandidate < 0)
    3655           3 :                     jCandidate = static_cast<int>(m_apoOverviewDS.size());
    3656             : 
    3657           4 :                 int nOvXSize = std::max(1, GetRasterXSize() / nOvFactor);
    3658           4 :                 int nOvYSize = std::max(1, GetRasterYSize() / nOvFactor);
    3659           4 :                 if (!(jCandidate == static_cast<int>(m_apoOverviewDS.size()) &&
    3660           5 :                       nOvFactor == 2 * nMaxOvFactor) &&
    3661           1 :                     !m_bZoomOther)
    3662             :                 {
    3663           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    3664             :                              "Use of overview factor %d causes gpkg_zoom_other "
    3665             :                              "extension to be needed",
    3666             :                              nOvFactor);
    3667           1 :                     RegisterZoomOtherExtension();
    3668           1 :                     m_bZoomOther = true;
    3669             :                 }
    3670             : 
    3671           4 :                 SoftStartTransaction();
    3672             : 
    3673           4 :                 CPLAssert(jCandidate > 0);
    3674             :                 const int nNewZoomLevel =
    3675           4 :                     m_apoOverviewDS[jCandidate - 1]->m_nZoomLevel;
    3676             : 
    3677             :                 char *pszSQL;
    3678             :                 OGRErr eErr;
    3679          24 :                 for (int k = 0; k <= jCandidate; k++)
    3680             :                 {
    3681          60 :                     pszSQL = sqlite3_mprintf(
    3682             :                         "UPDATE gpkg_tile_matrix SET zoom_level = %d "
    3683             :                         "WHERE lower(table_name) = lower('%q') AND zoom_level "
    3684             :                         "= %d",
    3685          20 :                         m_nZoomLevel - k + 1, m_osRasterTable.c_str(),
    3686          20 :                         m_nZoomLevel - k);
    3687          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3688          20 :                     sqlite3_free(pszSQL);
    3689          20 :                     if (eErr != OGRERR_NONE)
    3690             :                     {
    3691           0 :                         SoftRollbackTransaction();
    3692           0 :                         return CE_Failure;
    3693             :                     }
    3694             : 
    3695             :                     pszSQL =
    3696          20 :                         sqlite3_mprintf("UPDATE \"%w\" SET zoom_level = %d "
    3697             :                                         "WHERE zoom_level = %d",
    3698             :                                         m_osRasterTable.c_str(),
    3699          20 :                                         m_nZoomLevel - k + 1, m_nZoomLevel - k);
    3700          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3701          20 :                     sqlite3_free(pszSQL);
    3702          20 :                     if (eErr != OGRERR_NONE)
    3703             :                     {
    3704           0 :                         SoftRollbackTransaction();
    3705           0 :                         return CE_Failure;
    3706             :                     }
    3707             :                 }
    3708             : 
    3709           4 :                 double dfGDALMinX = m_gt[0];
    3710           4 :                 double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3711           4 :                 double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3712           4 :                 double dfGDALMaxY = m_gt[3];
    3713           4 :                 double dfPixelXSizeZoomLevel = m_gt[1] * nOvFactor;
    3714           4 :                 double dfPixelYSizeZoomLevel = fabs(m_gt[5]) * nOvFactor;
    3715             :                 int nTileWidth, nTileHeight;
    3716           4 :                 GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3717           4 :                 int nTileMatrixWidth = DIV_ROUND_UP(nOvXSize, nTileWidth);
    3718           4 :                 int nTileMatrixHeight = DIV_ROUND_UP(nOvYSize, nTileHeight);
    3719           4 :                 pszSQL = sqlite3_mprintf(
    3720             :                     "INSERT INTO gpkg_tile_matrix "
    3721             :                     "(table_name,zoom_level,matrix_width,matrix_height,tile_"
    3722             :                     "width,tile_height,pixel_x_size,pixel_y_size) VALUES "
    3723             :                     "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3724             :                     m_osRasterTable.c_str(), nNewZoomLevel, nTileMatrixWidth,
    3725             :                     nTileMatrixHeight, nTileWidth, nTileHeight,
    3726             :                     dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel);
    3727           4 :                 eErr = SQLCommand(hDB, pszSQL);
    3728           4 :                 sqlite3_free(pszSQL);
    3729           4 :                 if (eErr != OGRERR_NONE)
    3730             :                 {
    3731           0 :                     SoftRollbackTransaction();
    3732           0 :                     return CE_Failure;
    3733             :                 }
    3734             : 
    3735           4 :                 SoftCommitTransaction();
    3736             : 
    3737           4 :                 m_nZoomLevel++; /* this change our zoom level as well as
    3738             :                                    previous overviews */
    3739          20 :                 for (int k = 0; k < jCandidate; k++)
    3740          16 :                     m_apoOverviewDS[k]->m_nZoomLevel++;
    3741             : 
    3742           4 :                 auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3743           4 :                 poOvrDS->ShareLockWithParentDataset(this);
    3744           4 :                 poOvrDS->InitRaster(
    3745             :                     this, m_osRasterTable, nNewZoomLevel, nBands, m_dfTMSMinX,
    3746             :                     m_dfTMSMaxY, dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel,
    3747             :                     nTileWidth, nTileHeight, nTileMatrixWidth,
    3748             :                     nTileMatrixHeight, dfGDALMinX, dfGDALMinY, dfGDALMaxX,
    3749             :                     dfGDALMaxY);
    3750           4 :                 m_apoOverviewDS.insert(m_apoOverviewDS.begin() + jCandidate,
    3751           8 :                                        std::move(poOvrDS));
    3752             :             }
    3753             :         }
    3754             :     }
    3755             : 
    3756             :     GDALRasterBand ***papapoOverviewBands = static_cast<GDALRasterBand ***>(
    3757          13 :         CPLCalloc(sizeof(GDALRasterBand **), nBands));
    3758          13 :     CPLErr eErr = CE_None;
    3759          49 :     for (int iBand = 0; eErr == CE_None && iBand < nBands; iBand++)
    3760             :     {
    3761          72 :         papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
    3762          36 :             CPLCalloc(sizeof(GDALRasterBand *), nOverviews));
    3763          36 :         int iCurOverview = 0;
    3764         185 :         for (int i = 0; i < nOverviews; i++)
    3765             :         {
    3766         149 :             bool bFound = false;
    3767         724 :             for (const auto &poODS : m_apoOverviewDS)
    3768             :             {
    3769             :                 const int nOvFactor =
    3770         724 :                     static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3771             : 
    3772         724 :                 if (nOvFactor == panOverviewList[i])
    3773             :                 {
    3774         298 :                     papapoOverviewBands[iBand][iCurOverview] =
    3775         149 :                         poODS->GetRasterBand(iBand + 1);
    3776         149 :                     iCurOverview++;
    3777         149 :                     bFound = true;
    3778         149 :                     break;
    3779             :                 }
    3780             :             }
    3781         149 :             if (!bFound)
    3782             :             {
    3783           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3784             :                          "Could not find dataset corresponding to ov factor %d",
    3785           0 :                          panOverviewList[i]);
    3786           0 :                 eErr = CE_Failure;
    3787             :             }
    3788             :         }
    3789          36 :         if (eErr == CE_None)
    3790             :         {
    3791          36 :             CPLAssert(iCurOverview == nOverviews);
    3792             :         }
    3793             :     }
    3794             : 
    3795          13 :     if (eErr == CE_None)
    3796          13 :         eErr = GDALRegenerateOverviewsMultiBand(
    3797          13 :             nBands, papoBands, nOverviews, papapoOverviewBands, pszResampling,
    3798             :             pfnProgress, pProgressData, papszOptions);
    3799             : 
    3800          49 :     for (int iBand = 0; iBand < nBands; iBand++)
    3801             :     {
    3802          36 :         CPLFree(papapoOverviewBands[iBand]);
    3803             :     }
    3804          13 :     CPLFree(papapoOverviewBands);
    3805             : 
    3806          13 :     return eErr;
    3807             : }
    3808             : 
    3809             : /************************************************************************/
    3810             : /*                            GetFileList()                             */
    3811             : /************************************************************************/
    3812             : 
    3813          38 : char **GDALGeoPackageDataset::GetFileList()
    3814             : {
    3815          38 :     TryLoadXML();
    3816          38 :     return GDALPamDataset::GetFileList();
    3817             : }
    3818             : 
    3819             : /************************************************************************/
    3820             : /*                      GetMetadataDomainList()                         */
    3821             : /************************************************************************/
    3822             : 
    3823          47 : char **GDALGeoPackageDataset::GetMetadataDomainList()
    3824             : {
    3825          47 :     GetMetadata();
    3826          47 :     if (!m_osRasterTable.empty())
    3827           5 :         GetMetadata("GEOPACKAGE");
    3828          47 :     return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
    3829          47 :                                    TRUE, "SUBDATASETS", nullptr);
    3830             : }
    3831             : 
    3832             : /************************************************************************/
    3833             : /*                        CheckMetadataDomain()                         */
    3834             : /************************************************************************/
    3835             : 
    3836        6002 : const char *GDALGeoPackageDataset::CheckMetadataDomain(const char *pszDomain)
    3837             : {
    3838        6187 :     if (pszDomain != nullptr && EQUAL(pszDomain, "GEOPACKAGE") &&
    3839         185 :         m_osRasterTable.empty())
    3840             :     {
    3841           4 :         CPLError(
    3842             :             CE_Warning, CPLE_IllegalArg,
    3843             :             "Using GEOPACKAGE for a non-raster geopackage is not supported. "
    3844             :             "Using default domain instead");
    3845           4 :         return nullptr;
    3846             :     }
    3847        5998 :     return pszDomain;
    3848             : }
    3849             : 
    3850             : /************************************************************************/
    3851             : /*                           HasMetadataTables()                        */
    3852             : /************************************************************************/
    3853             : 
    3854        5700 : bool GDALGeoPackageDataset::HasMetadataTables() const
    3855             : {
    3856        5700 :     if (m_nHasMetadataTables < 0)
    3857             :     {
    3858             :         const int nCount =
    3859        2177 :             SQLGetInteger(hDB,
    3860             :                           "SELECT COUNT(*) FROM sqlite_master WHERE name IN "
    3861             :                           "('gpkg_metadata', 'gpkg_metadata_reference') "
    3862             :                           "AND type IN ('table', 'view')",
    3863             :                           nullptr);
    3864        2177 :         m_nHasMetadataTables = nCount == 2;
    3865             :     }
    3866        5700 :     return CPL_TO_BOOL(m_nHasMetadataTables);
    3867             : }
    3868             : 
    3869             : /************************************************************************/
    3870             : /*                         HasDataColumnsTable()                        */
    3871             : /************************************************************************/
    3872             : 
    3873        1276 : bool GDALGeoPackageDataset::HasDataColumnsTable() const
    3874             : {
    3875        2552 :     const int nCount = SQLGetInteger(
    3876        1276 :         hDB,
    3877             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_data_columns'"
    3878             :         "AND type IN ('table', 'view')",
    3879             :         nullptr);
    3880        1276 :     return nCount == 1;
    3881             : }
    3882             : 
    3883             : /************************************************************************/
    3884             : /*                    HasDataColumnConstraintsTable()                   */
    3885             : /************************************************************************/
    3886             : 
    3887         157 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTable() const
    3888             : {
    3889         157 :     const int nCount = SQLGetInteger(hDB,
    3890             :                                      "SELECT 1 FROM sqlite_master WHERE name = "
    3891             :                                      "'gpkg_data_column_constraints'"
    3892             :                                      "AND type IN ('table', 'view')",
    3893             :                                      nullptr);
    3894         157 :     return nCount == 1;
    3895             : }
    3896             : 
    3897             : /************************************************************************/
    3898             : /*                  HasDataColumnConstraintsTableGPKG_1_0()             */
    3899             : /************************************************************************/
    3900             : 
    3901         109 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTableGPKG_1_0() const
    3902             : {
    3903         109 :     if (m_nApplicationId != GP10_APPLICATION_ID)
    3904         107 :         return false;
    3905             :     // In GPKG 1.0, the columns were named minIsInclusive, maxIsInclusive
    3906             :     // They were changed in 1.1 to min_is_inclusive, max_is_inclusive
    3907           2 :     bool bRet = false;
    3908           2 :     sqlite3_stmt *hSQLStmt = nullptr;
    3909           2 :     int rc = sqlite3_prepare_v2(hDB,
    3910             :                                 "SELECT minIsInclusive, maxIsInclusive FROM "
    3911             :                                 "gpkg_data_column_constraints",
    3912             :                                 -1, &hSQLStmt, nullptr);
    3913           2 :     if (rc == SQLITE_OK)
    3914             :     {
    3915           2 :         bRet = true;
    3916           2 :         sqlite3_finalize(hSQLStmt);
    3917             :     }
    3918           2 :     return bRet;
    3919             : }
    3920             : 
    3921             : /************************************************************************/
    3922             : /*      CreateColumnsTableAndColumnConstraintsTablesIfNecessary()       */
    3923             : /************************************************************************/
    3924             : 
    3925          50 : bool GDALGeoPackageDataset::
    3926             :     CreateColumnsTableAndColumnConstraintsTablesIfNecessary()
    3927             : {
    3928          50 :     if (!HasDataColumnsTable())
    3929             :     {
    3930             :         // Geopackage < 1.3 had
    3931             :         // CONSTRAINT fk_gdc_tn FOREIGN KEY (table_name) REFERENCES
    3932             :         // gpkg_contents(table_name) instead of the unique constraint.
    3933          10 :         if (OGRERR_NONE !=
    3934          10 :             SQLCommand(
    3935             :                 GetDB(),
    3936             :                 "CREATE TABLE gpkg_data_columns ("
    3937             :                 "table_name TEXT NOT NULL,"
    3938             :                 "column_name TEXT NOT NULL,"
    3939             :                 "name TEXT,"
    3940             :                 "title TEXT,"
    3941             :                 "description TEXT,"
    3942             :                 "mime_type TEXT,"
    3943             :                 "constraint_name TEXT,"
    3944             :                 "CONSTRAINT pk_gdc PRIMARY KEY (table_name, column_name),"
    3945             :                 "CONSTRAINT gdc_tn UNIQUE (table_name, name));"))
    3946             :         {
    3947           0 :             return false;
    3948             :         }
    3949             :     }
    3950          50 :     if (!HasDataColumnConstraintsTable())
    3951             :     {
    3952          22 :         const char *min_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3953          11 :                                            ? "min_is_inclusive"
    3954             :                                            : "minIsInclusive";
    3955          22 :         const char *max_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3956          11 :                                            ? "max_is_inclusive"
    3957             :                                            : "maxIsInclusive";
    3958             : 
    3959             :         const std::string osSQL(
    3960             :             CPLSPrintf("CREATE TABLE gpkg_data_column_constraints ("
    3961             :                        "constraint_name TEXT NOT NULL,"
    3962             :                        "constraint_type TEXT NOT NULL,"
    3963             :                        "value TEXT,"
    3964             :                        "min NUMERIC,"
    3965             :                        "%s BOOLEAN,"
    3966             :                        "max NUMERIC,"
    3967             :                        "%s BOOLEAN,"
    3968             :                        "description TEXT,"
    3969             :                        "CONSTRAINT gdcc_ntv UNIQUE (constraint_name, "
    3970             :                        "constraint_type, value));",
    3971          11 :                        min_is_inclusive, max_is_inclusive));
    3972          11 :         if (OGRERR_NONE != SQLCommand(GetDB(), osSQL.c_str()))
    3973             :         {
    3974           0 :             return false;
    3975             :         }
    3976             :     }
    3977          50 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    3978             :     {
    3979           0 :         return false;
    3980             :     }
    3981          50 :     if (SQLGetInteger(GetDB(),
    3982             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3983             :                       "table_name = 'gpkg_data_columns'",
    3984          50 :                       nullptr) != 1)
    3985             :     {
    3986          11 :         if (OGRERR_NONE !=
    3987          11 :             SQLCommand(
    3988             :                 GetDB(),
    3989             :                 "INSERT INTO gpkg_extensions "
    3990             :                 "(table_name,column_name,extension_name,definition,scope) "
    3991             :                 "VALUES ('gpkg_data_columns', NULL, 'gpkg_schema', "
    3992             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    3993             :                 "'read-write')"))
    3994             :         {
    3995           0 :             return false;
    3996             :         }
    3997             :     }
    3998          50 :     if (SQLGetInteger(GetDB(),
    3999             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    4000             :                       "table_name = 'gpkg_data_column_constraints'",
    4001          50 :                       nullptr) != 1)
    4002             :     {
    4003          11 :         if (OGRERR_NONE !=
    4004          11 :             SQLCommand(
    4005             :                 GetDB(),
    4006             :                 "INSERT INTO gpkg_extensions "
    4007             :                 "(table_name,column_name,extension_name,definition,scope) "
    4008             :                 "VALUES ('gpkg_data_column_constraints', NULL, 'gpkg_schema', "
    4009             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    4010             :                 "'read-write')"))
    4011             :         {
    4012           0 :             return false;
    4013             :         }
    4014             :     }
    4015             : 
    4016          50 :     return true;
    4017             : }
    4018             : 
    4019             : /************************************************************************/
    4020             : /*                        HasGpkgextRelationsTable()                    */
    4021             : /************************************************************************/
    4022             : 
    4023        1270 : bool GDALGeoPackageDataset::HasGpkgextRelationsTable() const
    4024             : {
    4025        2540 :     const int nCount = SQLGetInteger(
    4026        1270 :         hDB,
    4027             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkgext_relations'"
    4028             :         "AND type IN ('table', 'view')",
    4029             :         nullptr);
    4030        1270 :     return nCount == 1;
    4031             : }
    4032             : 
    4033             : /************************************************************************/
    4034             : /*                    CreateRelationsTableIfNecessary()                 */
    4035             : /************************************************************************/
    4036             : 
    4037           9 : bool GDALGeoPackageDataset::CreateRelationsTableIfNecessary()
    4038             : {
    4039           9 :     if (HasGpkgextRelationsTable())
    4040             :     {
    4041           5 :         return true;
    4042             :     }
    4043             : 
    4044           4 :     if (OGRERR_NONE !=
    4045           4 :         SQLCommand(GetDB(), "CREATE TABLE gpkgext_relations ("
    4046             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    4047             :                             "base_table_name TEXT NOT NULL,"
    4048             :                             "base_primary_column TEXT NOT NULL DEFAULT 'id',"
    4049             :                             "related_table_name TEXT NOT NULL,"
    4050             :                             "related_primary_column TEXT NOT NULL DEFAULT 'id',"
    4051             :                             "relation_name TEXT NOT NULL,"
    4052             :                             "mapping_table_name TEXT NOT NULL UNIQUE);"))
    4053             :     {
    4054           0 :         return false;
    4055             :     }
    4056             : 
    4057           4 :     return true;
    4058             : }
    4059             : 
    4060             : /************************************************************************/
    4061             : /*                        HasQGISLayerStyles()                          */
    4062             : /************************************************************************/
    4063             : 
    4064          11 : bool GDALGeoPackageDataset::HasQGISLayerStyles() const
    4065             : {
    4066             :     // QGIS layer_styles extension:
    4067             :     // https://github.com/pka/qgpkg/blob/master/qgis_geopackage_extension.md
    4068          11 :     bool bRet = false;
    4069             :     const int nCount =
    4070          11 :         SQLGetInteger(hDB,
    4071             :                       "SELECT 1 FROM sqlite_master WHERE name = 'layer_styles'"
    4072             :                       "AND type = 'table'",
    4073             :                       nullptr);
    4074          11 :     if (nCount == 1)
    4075             :     {
    4076           1 :         sqlite3_stmt *hSQLStmt = nullptr;
    4077           2 :         int rc = sqlite3_prepare_v2(
    4078           1 :             hDB, "SELECT f_table_name, f_geometry_column FROM layer_styles", -1,
    4079             :             &hSQLStmt, nullptr);
    4080           1 :         if (rc == SQLITE_OK)
    4081             :         {
    4082           1 :             bRet = true;
    4083           1 :             sqlite3_finalize(hSQLStmt);
    4084             :         }
    4085             :     }
    4086          11 :     return bRet;
    4087             : }
    4088             : 
    4089             : /************************************************************************/
    4090             : /*                            GetMetadata()                             */
    4091             : /************************************************************************/
    4092             : 
    4093        3940 : char **GDALGeoPackageDataset::GetMetadata(const char *pszDomain)
    4094             : 
    4095             : {
    4096        3940 :     pszDomain = CheckMetadataDomain(pszDomain);
    4097        3940 :     if (pszDomain != nullptr && EQUAL(pszDomain, "SUBDATASETS"))
    4098          66 :         return m_aosSubDatasets.List();
    4099             : 
    4100        3874 :     if (m_bHasReadMetadataFromStorage)
    4101        1764 :         return GDALPamDataset::GetMetadata(pszDomain);
    4102             : 
    4103        2110 :     m_bHasReadMetadataFromStorage = true;
    4104             : 
    4105        2110 :     TryLoadXML();
    4106             : 
    4107        2110 :     if (!HasMetadataTables())
    4108        1598 :         return GDALPamDataset::GetMetadata(pszDomain);
    4109             : 
    4110         512 :     char *pszSQL = nullptr;
    4111         512 :     if (!m_osRasterTable.empty())
    4112             :     {
    4113         170 :         pszSQL = sqlite3_mprintf(
    4114             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4115             :             "mdr.reference_scope FROM gpkg_metadata md "
    4116             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4117             :             "WHERE "
    4118             :             "(mdr.reference_scope = 'geopackage' OR "
    4119             :             "(mdr.reference_scope = 'table' AND lower(mdr.table_name) = "
    4120             :             "lower('%q'))) ORDER BY md.id "
    4121             :             "LIMIT 1000",  // to avoid denial of service
    4122             :             m_osRasterTable.c_str());
    4123             :     }
    4124             :     else
    4125             :     {
    4126         342 :         pszSQL = sqlite3_mprintf(
    4127             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4128             :             "mdr.reference_scope FROM gpkg_metadata md "
    4129             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4130             :             "WHERE "
    4131             :             "mdr.reference_scope = 'geopackage' ORDER BY md.id "
    4132             :             "LIMIT 1000"  // to avoid denial of service
    4133             :         );
    4134             :     }
    4135             : 
    4136        1024 :     auto oResult = SQLQuery(hDB, pszSQL);
    4137         512 :     sqlite3_free(pszSQL);
    4138         512 :     if (!oResult)
    4139             :     {
    4140           0 :         return GDALPamDataset::GetMetadata(pszDomain);
    4141             :     }
    4142             : 
    4143         512 :     char **papszMetadata = CSLDuplicate(GDALPamDataset::GetMetadata());
    4144             : 
    4145             :     /* GDAL metadata */
    4146         702 :     for (int i = 0; i < oResult->RowCount(); i++)
    4147             :     {
    4148         190 :         const char *pszMetadata = oResult->GetValue(0, i);
    4149         190 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4150         190 :         const char *pszMimeType = oResult->GetValue(2, i);
    4151         190 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4152         190 :         if (pszMetadata && pszMDStandardURI && pszMimeType &&
    4153         190 :             pszReferenceScope && EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4154         174 :             EQUAL(pszMimeType, "text/xml"))
    4155             :         {
    4156         174 :             CPLXMLNode *psXMLNode = CPLParseXMLString(pszMetadata);
    4157         174 :             if (psXMLNode)
    4158             :             {
    4159         348 :                 GDALMultiDomainMetadata oLocalMDMD;
    4160         174 :                 oLocalMDMD.XMLInit(psXMLNode, FALSE);
    4161         333 :                 if (!m_osRasterTable.empty() &&
    4162         159 :                     EQUAL(pszReferenceScope, "geopackage"))
    4163             :                 {
    4164           6 :                     oMDMD.SetMetadata(oLocalMDMD.GetMetadata(), "GEOPACKAGE");
    4165             :                 }
    4166             :                 else
    4167             :                 {
    4168             :                     papszMetadata =
    4169         168 :                         CSLMerge(papszMetadata, oLocalMDMD.GetMetadata());
    4170         168 :                     CSLConstList papszDomainList = oLocalMDMD.GetDomainList();
    4171         168 :                     CSLConstList papszIter = papszDomainList;
    4172         447 :                     while (papszIter && *papszIter)
    4173             :                     {
    4174         279 :                         if (EQUAL(*papszIter, "IMAGE_STRUCTURE"))
    4175             :                         {
    4176             :                             CSLConstList papszMD =
    4177         126 :                                 oLocalMDMD.GetMetadata(*papszIter);
    4178             :                             const char *pszBAND_COUNT =
    4179         126 :                                 CSLFetchNameValue(papszMD, "BAND_COUNT");
    4180         126 :                             if (pszBAND_COUNT)
    4181         124 :                                 m_nBandCountFromMetadata = atoi(pszBAND_COUNT);
    4182             : 
    4183             :                             const char *pszCOLOR_TABLE =
    4184         126 :                                 CSLFetchNameValue(papszMD, "COLOR_TABLE");
    4185         126 :                             if (pszCOLOR_TABLE)
    4186             :                             {
    4187             :                                 const CPLStringList aosTokens(
    4188             :                                     CSLTokenizeString2(pszCOLOR_TABLE, "{,",
    4189          26 :                                                        0));
    4190          13 :                                 if ((aosTokens.size() % 4) == 0)
    4191             :                                 {
    4192          13 :                                     const int nColors = aosTokens.size() / 4;
    4193             :                                     m_poCTFromMetadata =
    4194          13 :                                         std::make_unique<GDALColorTable>();
    4195        3341 :                                     for (int iColor = 0; iColor < nColors;
    4196             :                                          ++iColor)
    4197             :                                     {
    4198             :                                         GDALColorEntry sEntry;
    4199        3328 :                                         sEntry.c1 = static_cast<short>(
    4200        3328 :                                             atoi(aosTokens[4 * iColor + 0]));
    4201        3328 :                                         sEntry.c2 = static_cast<short>(
    4202        3328 :                                             atoi(aosTokens[4 * iColor + 1]));
    4203        3328 :                                         sEntry.c3 = static_cast<short>(
    4204        3328 :                                             atoi(aosTokens[4 * iColor + 2]));
    4205        3328 :                                         sEntry.c4 = static_cast<short>(
    4206        3328 :                                             atoi(aosTokens[4 * iColor + 3]));
    4207        3328 :                                         m_poCTFromMetadata->SetColorEntry(
    4208             :                                             iColor, &sEntry);
    4209             :                                     }
    4210             :                                 }
    4211             :                             }
    4212             : 
    4213             :                             const char *pszTILE_FORMAT =
    4214         126 :                                 CSLFetchNameValue(papszMD, "TILE_FORMAT");
    4215         126 :                             if (pszTILE_FORMAT)
    4216             :                             {
    4217           8 :                                 m_osTFFromMetadata = pszTILE_FORMAT;
    4218           8 :                                 oMDMD.SetMetadataItem("TILE_FORMAT",
    4219             :                                                       pszTILE_FORMAT,
    4220             :                                                       "IMAGE_STRUCTURE");
    4221             :                             }
    4222             : 
    4223             :                             const char *pszNodataValue =
    4224         126 :                                 CSLFetchNameValue(papszMD, "NODATA_VALUE");
    4225         126 :                             if (pszNodataValue)
    4226             :                             {
    4227           2 :                                 m_osNodataValueFromMetadata = pszNodataValue;
    4228             :                             }
    4229             :                         }
    4230             : 
    4231         153 :                         else if (!EQUAL(*papszIter, "") &&
    4232          16 :                                  !STARTS_WITH(*papszIter, "BAND_"))
    4233             :                         {
    4234          12 :                             oMDMD.SetMetadata(
    4235           6 :                                 oLocalMDMD.GetMetadata(*papszIter), *papszIter);
    4236             :                         }
    4237         279 :                         papszIter++;
    4238             :                     }
    4239             :                 }
    4240         174 :                 CPLDestroyXMLNode(psXMLNode);
    4241             :             }
    4242             :         }
    4243             :     }
    4244             : 
    4245         512 :     GDALPamDataset::SetMetadata(papszMetadata);
    4246         512 :     CSLDestroy(papszMetadata);
    4247         512 :     papszMetadata = nullptr;
    4248             : 
    4249             :     /* Add non-GDAL metadata now */
    4250         512 :     int nNonGDALMDILocal = 1;
    4251         512 :     int nNonGDALMDIGeopackage = 1;
    4252         702 :     for (int i = 0; i < oResult->RowCount(); i++)
    4253             :     {
    4254         190 :         const char *pszMetadata = oResult->GetValue(0, i);
    4255         190 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4256         190 :         const char *pszMimeType = oResult->GetValue(2, i);
    4257         190 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4258         190 :         if (pszMetadata == nullptr || pszMDStandardURI == nullptr ||
    4259         190 :             pszMimeType == nullptr || pszReferenceScope == nullptr)
    4260             :         {
    4261             :             // should not happen as there are NOT NULL constraints
    4262             :             // But a database could lack such NOT NULL constraints or have
    4263             :             // large values that would cause a memory allocation failure.
    4264           0 :             continue;
    4265             :         }
    4266         190 :         int bIsGPKGScope = EQUAL(pszReferenceScope, "geopackage");
    4267         190 :         if (EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4268         174 :             EQUAL(pszMimeType, "text/xml"))
    4269         174 :             continue;
    4270             : 
    4271          16 :         if (!m_osRasterTable.empty() && bIsGPKGScope)
    4272             :         {
    4273           8 :             oMDMD.SetMetadataItem(
    4274             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDIGeopackage),
    4275             :                 pszMetadata, "GEOPACKAGE");
    4276           8 :             nNonGDALMDIGeopackage++;
    4277             :         }
    4278             :         /*else if( strcmp( pszMDStandardURI, "http://www.isotc211.org/2005/gmd"
    4279             :         ) == 0 && strcmp( pszMimeType, "text/xml" ) == 0 )
    4280             :         {
    4281             :             char* apszMD[2];
    4282             :             apszMD[0] = (char*)pszMetadata;
    4283             :             apszMD[1] = NULL;
    4284             :             oMDMD.SetMetadata(apszMD, "xml:MD_Metadata");
    4285             :         }*/
    4286             :         else
    4287             :         {
    4288           8 :             oMDMD.SetMetadataItem(
    4289             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDILocal),
    4290             :                 pszMetadata);
    4291           8 :             nNonGDALMDILocal++;
    4292             :         }
    4293             :     }
    4294             : 
    4295         512 :     return GDALPamDataset::GetMetadata(pszDomain);
    4296             : }
    4297             : 
    4298             : /************************************************************************/
    4299             : /*                            WriteMetadata()                           */
    4300             : /************************************************************************/
    4301             : 
    4302         732 : void GDALGeoPackageDataset::WriteMetadata(
    4303             :     CPLXMLNode *psXMLNode, /* will be destroyed by the method */
    4304             :     const char *pszTableName)
    4305             : {
    4306         732 :     const bool bIsEmpty = (psXMLNode == nullptr);
    4307         732 :     if (!HasMetadataTables())
    4308             :     {
    4309         532 :         if (bIsEmpty || !CreateMetadataTables())
    4310             :         {
    4311         243 :             CPLDestroyXMLNode(psXMLNode);
    4312         243 :             return;
    4313             :         }
    4314             :     }
    4315             : 
    4316         489 :     char *pszXML = nullptr;
    4317         489 :     if (!bIsEmpty)
    4318             :     {
    4319             :         CPLXMLNode *psMasterXMLNode =
    4320         336 :             CPLCreateXMLNode(nullptr, CXT_Element, "GDALMultiDomainMetadata");
    4321         336 :         psMasterXMLNode->psChild = psXMLNode;
    4322         336 :         pszXML = CPLSerializeXMLTree(psMasterXMLNode);
    4323         336 :         CPLDestroyXMLNode(psMasterXMLNode);
    4324             :     }
    4325             :     // cppcheck-suppress uselessAssignmentPtrArg
    4326         489 :     psXMLNode = nullptr;
    4327             : 
    4328         489 :     char *pszSQL = nullptr;
    4329         489 :     if (pszTableName && pszTableName[0] != '\0')
    4330             :     {
    4331         344 :         pszSQL = sqlite3_mprintf(
    4332             :             "SELECT md.id FROM gpkg_metadata md "
    4333             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4334             :             "WHERE md.md_scope = 'dataset' AND "
    4335             :             "md.md_standard_uri='http://gdal.org' "
    4336             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = 'table' AND "
    4337             :             "lower(mdr.table_name) = lower('%q')",
    4338             :             pszTableName);
    4339             :     }
    4340             :     else
    4341             :     {
    4342         145 :         pszSQL = sqlite3_mprintf(
    4343             :             "SELECT md.id FROM gpkg_metadata md "
    4344             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4345             :             "WHERE md.md_scope = 'dataset' AND "
    4346             :             "md.md_standard_uri='http://gdal.org' "
    4347             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = "
    4348             :             "'geopackage'");
    4349             :     }
    4350             :     OGRErr err;
    4351         489 :     int mdId = SQLGetInteger(hDB, pszSQL, &err);
    4352         489 :     if (err != OGRERR_NONE)
    4353         457 :         mdId = -1;
    4354         489 :     sqlite3_free(pszSQL);
    4355             : 
    4356         489 :     if (bIsEmpty)
    4357             :     {
    4358         153 :         if (mdId >= 0)
    4359             :         {
    4360           6 :             SQLCommand(
    4361             :                 hDB,
    4362             :                 CPLSPrintf(
    4363             :                     "DELETE FROM gpkg_metadata_reference WHERE md_file_id = %d",
    4364             :                     mdId));
    4365           6 :             SQLCommand(
    4366             :                 hDB,
    4367             :                 CPLSPrintf("DELETE FROM gpkg_metadata WHERE id = %d", mdId));
    4368             :         }
    4369             :     }
    4370             :     else
    4371             :     {
    4372         336 :         if (mdId >= 0)
    4373             :         {
    4374          26 :             pszSQL = sqlite3_mprintf(
    4375             :                 "UPDATE gpkg_metadata SET metadata = '%q' WHERE id = %d",
    4376             :                 pszXML, mdId);
    4377             :         }
    4378             :         else
    4379             :         {
    4380             :             pszSQL =
    4381         310 :                 sqlite3_mprintf("INSERT INTO gpkg_metadata (md_scope, "
    4382             :                                 "md_standard_uri, mime_type, metadata) VALUES "
    4383             :                                 "('dataset','http://gdal.org','text/xml','%q')",
    4384             :                                 pszXML);
    4385             :         }
    4386         336 :         SQLCommand(hDB, pszSQL);
    4387         336 :         sqlite3_free(pszSQL);
    4388             : 
    4389         336 :         CPLFree(pszXML);
    4390             : 
    4391         336 :         if (mdId < 0)
    4392             :         {
    4393         310 :             const sqlite_int64 nFID = sqlite3_last_insert_rowid(hDB);
    4394         310 :             if (pszTableName != nullptr && pszTableName[0] != '\0')
    4395             :             {
    4396         298 :                 pszSQL = sqlite3_mprintf(
    4397             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4398             :                     "table_name, timestamp, md_file_id) VALUES "
    4399             :                     "('table', '%q', %s, %d)",
    4400         596 :                     pszTableName, GetCurrentDateEscapedSQL().c_str(),
    4401             :                     static_cast<int>(nFID));
    4402             :             }
    4403             :             else
    4404             :             {
    4405          12 :                 pszSQL = sqlite3_mprintf(
    4406             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4407             :                     "timestamp, md_file_id) VALUES "
    4408             :                     "('geopackage', %s, %d)",
    4409          24 :                     GetCurrentDateEscapedSQL().c_str(), static_cast<int>(nFID));
    4410             :             }
    4411             :         }
    4412             :         else
    4413             :         {
    4414          26 :             pszSQL = sqlite3_mprintf("UPDATE gpkg_metadata_reference SET "
    4415             :                                      "timestamp = %s WHERE md_file_id = %d",
    4416          52 :                                      GetCurrentDateEscapedSQL().c_str(), mdId);
    4417             :         }
    4418         336 :         SQLCommand(hDB, pszSQL);
    4419         336 :         sqlite3_free(pszSQL);
    4420             :     }
    4421             : }
    4422             : 
    4423             : /************************************************************************/
    4424             : /*                        CreateMetadataTables()                        */
    4425             : /************************************************************************/
    4426             : 
    4427         308 : bool GDALGeoPackageDataset::CreateMetadataTables()
    4428             : {
    4429             :     const bool bCreateTriggers =
    4430         308 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "NO"));
    4431             : 
    4432             :     /* From C.10. gpkg_metadata Table 35. gpkg_metadata Table Definition SQL  */
    4433             :     CPLString osSQL = "CREATE TABLE gpkg_metadata ("
    4434             :                       "id INTEGER CONSTRAINT m_pk PRIMARY KEY ASC NOT NULL,"
    4435             :                       "md_scope TEXT NOT NULL DEFAULT 'dataset',"
    4436             :                       "md_standard_uri TEXT NOT NULL,"
    4437             :                       "mime_type TEXT NOT NULL DEFAULT 'text/xml',"
    4438             :                       "metadata TEXT NOT NULL DEFAULT ''"
    4439         616 :                       ")";
    4440             : 
    4441             :     /* From D.2. metadata Table 40. metadata Trigger Definition SQL  */
    4442         308 :     const char *pszMetadataTriggers =
    4443             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_insert' "
    4444             :         "BEFORE INSERT ON 'gpkg_metadata' "
    4445             :         "FOR EACH ROW BEGIN "
    4446             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata violates "
    4447             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4448             :         "collectionSession | series | dataset | featureType | feature | "
    4449             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4450             :         "taxonomy software | service | collectionHardware | "
    4451             :         "nonGeographicDataset | dimensionGroup') "
    4452             :         "WHERE NOT(NEW.md_scope IN "
    4453             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4454             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4455             :         "'catalogue','schema','taxonomy','software','service', "
    4456             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4457             :         "END; "
    4458             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_update' "
    4459             :         "BEFORE UPDATE OF 'md_scope' ON 'gpkg_metadata' "
    4460             :         "FOR EACH ROW BEGIN "
    4461             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata violates "
    4462             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4463             :         "collectionSession | series | dataset | featureType | feature | "
    4464             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4465             :         "taxonomy software | service | collectionHardware | "
    4466             :         "nonGeographicDataset | dimensionGroup') "
    4467             :         "WHERE NOT(NEW.md_scope IN "
    4468             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4469             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4470             :         "'catalogue','schema','taxonomy','software','service', "
    4471             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4472             :         "END";
    4473         308 :     if (bCreateTriggers)
    4474             :     {
    4475           0 :         osSQL += ";";
    4476           0 :         osSQL += pszMetadataTriggers;
    4477             :     }
    4478             : 
    4479             :     /* From C.11. gpkg_metadata_reference Table 36. gpkg_metadata_reference
    4480             :      * Table Definition SQL */
    4481             :     osSQL += ";"
    4482             :              "CREATE TABLE gpkg_metadata_reference ("
    4483             :              "reference_scope TEXT NOT NULL,"
    4484             :              "table_name TEXT,"
    4485             :              "column_name TEXT,"
    4486             :              "row_id_value INTEGER,"
    4487             :              "timestamp DATETIME NOT NULL DEFAULT "
    4488             :              "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    4489             :              "md_file_id INTEGER NOT NULL,"
    4490             :              "md_parent_id INTEGER,"
    4491             :              "CONSTRAINT crmr_mfi_fk FOREIGN KEY (md_file_id) REFERENCES "
    4492             :              "gpkg_metadata(id),"
    4493             :              "CONSTRAINT crmr_mpi_fk FOREIGN KEY (md_parent_id) REFERENCES "
    4494             :              "gpkg_metadata(id)"
    4495         308 :              ")";
    4496             : 
    4497             :     /* From D.3. metadata_reference Table 41. gpkg_metadata_reference Trigger
    4498             :      * Definition SQL   */
    4499         308 :     const char *pszMetadataReferenceTriggers =
    4500             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_insert' "
    4501             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4502             :         "FOR EACH ROW BEGIN "
    4503             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4504             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4505             :         "table\", \"column\", \"row\", \"row/col\"') "
    4506             :         "WHERE NOT NEW.reference_scope IN "
    4507             :         "('geopackage','table','column','row','row/col'); "
    4508             :         "END; "
    4509             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_update' "
    4510             :         "BEFORE UPDATE OF 'reference_scope' ON 'gpkg_metadata_reference' "
    4511             :         "FOR EACH ROW BEGIN "
    4512             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4513             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4514             :         "\"table\", \"column\", \"row\", \"row/col\"') "
    4515             :         "WHERE NOT NEW.reference_scope IN "
    4516             :         "('geopackage','table','column','row','row/col'); "
    4517             :         "END; "
    4518             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_insert' "
    4519             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4520             :         "FOR EACH ROW BEGIN "
    4521             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4522             :         "violates constraint: column name must be NULL when reference_scope "
    4523             :         "is \"geopackage\", \"table\" or \"row\"') "
    4524             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4525             :         "AND NEW.column_name IS NOT NULL); "
    4526             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4527             :         "violates constraint: column name must be defined for the specified "
    4528             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4529             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4530             :         "AND NOT NEW.table_name IN ( "
    4531             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4532             :         "AND name = NEW.table_name "
    4533             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4534             :         "END; "
    4535             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_update' "
    4536             :         "BEFORE UPDATE OF column_name ON 'gpkg_metadata_reference' "
    4537             :         "FOR EACH ROW BEGIN "
    4538             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4539             :         "violates constraint: column name must be NULL when reference_scope "
    4540             :         "is \"geopackage\", \"table\" or \"row\"') "
    4541             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4542             :         "AND NEW.column_name IS NOT NULL); "
    4543             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4544             :         "violates constraint: column name must be defined for the specified "
    4545             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4546             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4547             :         "AND NOT NEW.table_name IN ( "
    4548             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4549             :         "AND name = NEW.table_name "
    4550             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4551             :         "END; "
    4552             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_insert' "
    4553             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4554             :         "FOR EACH ROW BEGIN "
    4555             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4556             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4557             :         "is \"geopackage\", \"table\" or \"column\"') "
    4558             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4559             :         "AND NEW.row_id_value IS NOT NULL; "
    4560             :         "END; "
    4561             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_update' "
    4562             :         "BEFORE UPDATE OF 'row_id_value' ON 'gpkg_metadata_reference' "
    4563             :         "FOR EACH ROW BEGIN "
    4564             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4565             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4566             :         "is \"geopackage\", \"table\" or \"column\"') "
    4567             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4568             :         "AND NEW.row_id_value IS NOT NULL; "
    4569             :         "END; "
    4570             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_insert' "
    4571             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4572             :         "FOR EACH ROW BEGIN "
    4573             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4574             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4575             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4576             :         "WHERE NOT (NEW.timestamp GLOB "
    4577             :         "'[1-2][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-"
    4578             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4579             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4580             :         "END; "
    4581             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_update' "
    4582             :         "BEFORE UPDATE OF 'timestamp' ON 'gpkg_metadata_reference' "
    4583             :         "FOR EACH ROW BEGIN "
    4584             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4585             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4586             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4587             :         "WHERE NOT (NEW.timestamp GLOB "
    4588             :         "'[1-2][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-"
    4589             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4590             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4591             :         "END";
    4592         308 :     if (bCreateTriggers)
    4593             :     {
    4594           0 :         osSQL += ";";
    4595           0 :         osSQL += pszMetadataReferenceTriggers;
    4596             :     }
    4597             : 
    4598         308 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    4599           2 :         return false;
    4600             : 
    4601         306 :     osSQL += ";";
    4602             :     osSQL += "INSERT INTO gpkg_extensions "
    4603             :              "(table_name, column_name, extension_name, definition, scope) "
    4604             :              "VALUES "
    4605             :              "('gpkg_metadata', NULL, 'gpkg_metadata', "
    4606             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4607         306 :              "'read-write')";
    4608             : 
    4609         306 :     osSQL += ";";
    4610             :     osSQL += "INSERT INTO gpkg_extensions "
    4611             :              "(table_name, column_name, extension_name, definition, scope) "
    4612             :              "VALUES "
    4613             :              "('gpkg_metadata_reference', NULL, 'gpkg_metadata', "
    4614             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4615         306 :              "'read-write')";
    4616             : 
    4617         306 :     const bool bOK = SQLCommand(hDB, osSQL) == OGRERR_NONE;
    4618         306 :     m_nHasMetadataTables = bOK;
    4619         306 :     return bOK;
    4620             : }
    4621             : 
    4622             : /************************************************************************/
    4623             : /*                            FlushMetadata()                           */
    4624             : /************************************************************************/
    4625             : 
    4626        8892 : void GDALGeoPackageDataset::FlushMetadata()
    4627             : {
    4628        8892 :     if (!m_bMetadataDirty || m_poParentDS != nullptr ||
    4629         367 :         m_nCreateMetadataTables == FALSE)
    4630        8531 :         return;
    4631         361 :     m_bMetadataDirty = false;
    4632             : 
    4633         361 :     if (eAccess == GA_ReadOnly)
    4634             :     {
    4635           3 :         return;
    4636             :     }
    4637             : 
    4638         358 :     bool bCanWriteAreaOrPoint =
    4639         714 :         !m_bGridCellEncodingAsCO &&
    4640         356 :         (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT);
    4641         358 :     if (!m_osRasterTable.empty())
    4642             :     {
    4643             :         const char *pszIdentifier =
    4644         144 :             GDALGeoPackageDataset::GetMetadataItem("IDENTIFIER");
    4645             :         const char *pszDescription =
    4646         144 :             GDALGeoPackageDataset::GetMetadataItem("DESCRIPTION");
    4647         173 :         if (!m_bIdentifierAsCO && pszIdentifier != nullptr &&
    4648          29 :             pszIdentifier != m_osIdentifier)
    4649             :         {
    4650          14 :             m_osIdentifier = pszIdentifier;
    4651             :             char *pszSQL =
    4652          14 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4653             :                                 "WHERE lower(table_name) = lower('%q')",
    4654             :                                 pszIdentifier, m_osRasterTable.c_str());
    4655          14 :             SQLCommand(hDB, pszSQL);
    4656          14 :             sqlite3_free(pszSQL);
    4657             :         }
    4658         151 :         if (!m_bDescriptionAsCO && pszDescription != nullptr &&
    4659           7 :             pszDescription != m_osDescription)
    4660             :         {
    4661           7 :             m_osDescription = pszDescription;
    4662             :             char *pszSQL =
    4663           7 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4664             :                                 "WHERE lower(table_name) = lower('%q')",
    4665             :                                 pszDescription, m_osRasterTable.c_str());
    4666           7 :             SQLCommand(hDB, pszSQL);
    4667           7 :             sqlite3_free(pszSQL);
    4668             :         }
    4669         144 :         if (bCanWriteAreaOrPoint)
    4670             :         {
    4671             :             const char *pszAreaOrPoint =
    4672          28 :                 GDALGeoPackageDataset::GetMetadataItem(GDALMD_AREA_OR_POINT);
    4673          28 :             if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_AREA))
    4674             :             {
    4675          23 :                 bCanWriteAreaOrPoint = false;
    4676          23 :                 char *pszSQL = sqlite3_mprintf(
    4677             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4678             :                     "grid_cell_encoding = 'grid-value-is-area' WHERE "
    4679             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4680             :                     m_osRasterTable.c_str());
    4681          23 :                 SQLCommand(hDB, pszSQL);
    4682          23 :                 sqlite3_free(pszSQL);
    4683             :             }
    4684           5 :             else if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_POINT))
    4685             :             {
    4686           1 :                 bCanWriteAreaOrPoint = false;
    4687           1 :                 char *pszSQL = sqlite3_mprintf(
    4688             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4689             :                     "grid_cell_encoding = 'grid-value-is-center' WHERE "
    4690             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4691             :                     m_osRasterTable.c_str());
    4692           1 :                 SQLCommand(hDB, pszSQL);
    4693           1 :                 sqlite3_free(pszSQL);
    4694             :             }
    4695             :         }
    4696             :     }
    4697             : 
    4698         358 :     char **papszMDDup = nullptr;
    4699         563 :     for (char **papszIter = GDALGeoPackageDataset::GetMetadata();
    4700         563 :          papszIter && *papszIter; ++papszIter)
    4701             :     {
    4702         205 :         if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4703          29 :             continue;
    4704         176 :         if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4705           8 :             continue;
    4706         168 :         if (STARTS_WITH_CI(*papszIter, "ZOOM_LEVEL="))
    4707          14 :             continue;
    4708         154 :         if (STARTS_WITH_CI(*papszIter, "GPKG_METADATA_ITEM_"))
    4709           4 :             continue;
    4710         150 :         if ((m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT) &&
    4711          29 :             !bCanWriteAreaOrPoint &&
    4712          26 :             STARTS_WITH_CI(*papszIter, GDALMD_AREA_OR_POINT))
    4713             :         {
    4714          26 :             continue;
    4715             :         }
    4716         124 :         papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4717             :     }
    4718             : 
    4719         358 :     CPLXMLNode *psXMLNode = nullptr;
    4720             :     {
    4721         358 :         GDALMultiDomainMetadata oLocalMDMD;
    4722         358 :         CSLConstList papszDomainList = oMDMD.GetDomainList();
    4723         358 :         CSLConstList papszIter = papszDomainList;
    4724         358 :         oLocalMDMD.SetMetadata(papszMDDup);
    4725         687 :         while (papszIter && *papszIter)
    4726             :         {
    4727         329 :             if (!EQUAL(*papszIter, "") &&
    4728         159 :                 !EQUAL(*papszIter, "IMAGE_STRUCTURE") &&
    4729          15 :                 !EQUAL(*papszIter, "GEOPACKAGE"))
    4730             :             {
    4731           8 :                 oLocalMDMD.SetMetadata(oMDMD.GetMetadata(*papszIter),
    4732             :                                        *papszIter);
    4733             :             }
    4734         329 :             papszIter++;
    4735             :         }
    4736         358 :         if (m_nBandCountFromMetadata > 0)
    4737             :         {
    4738          74 :             oLocalMDMD.SetMetadataItem(
    4739             :                 "BAND_COUNT", CPLSPrintf("%d", m_nBandCountFromMetadata),
    4740             :                 "IMAGE_STRUCTURE");
    4741          74 :             if (nBands == 1)
    4742             :             {
    4743          50 :                 const auto poCT = GetRasterBand(1)->GetColorTable();
    4744          50 :                 if (poCT)
    4745             :                 {
    4746          16 :                     std::string osVal("{");
    4747           8 :                     const int nColorCount = poCT->GetColorEntryCount();
    4748        2056 :                     for (int i = 0; i < nColorCount; ++i)
    4749             :                     {
    4750        2048 :                         if (i > 0)
    4751        2040 :                             osVal += ',';
    4752        2048 :                         const GDALColorEntry *psEntry = poCT->GetColorEntry(i);
    4753             :                         osVal +=
    4754        2048 :                             CPLSPrintf("{%d,%d,%d,%d}", psEntry->c1,
    4755        2048 :                                        psEntry->c2, psEntry->c3, psEntry->c4);
    4756             :                     }
    4757           8 :                     osVal += '}';
    4758           8 :                     oLocalMDMD.SetMetadataItem("COLOR_TABLE", osVal.c_str(),
    4759             :                                                "IMAGE_STRUCTURE");
    4760             :                 }
    4761             :             }
    4762          74 :             if (nBands == 1)
    4763             :             {
    4764          50 :                 const char *pszTILE_FORMAT = nullptr;
    4765          50 :                 switch (m_eTF)
    4766             :                 {
    4767           0 :                     case GPKG_TF_PNG_JPEG:
    4768           0 :                         pszTILE_FORMAT = "JPEG_PNG";
    4769           0 :                         break;
    4770          44 :                     case GPKG_TF_PNG:
    4771          44 :                         break;
    4772           0 :                     case GPKG_TF_PNG8:
    4773           0 :                         pszTILE_FORMAT = "PNG8";
    4774           0 :                         break;
    4775           3 :                     case GPKG_TF_JPEG:
    4776           3 :                         pszTILE_FORMAT = "JPEG";
    4777           3 :                         break;
    4778           3 :                     case GPKG_TF_WEBP:
    4779           3 :                         pszTILE_FORMAT = "WEBP";
    4780           3 :                         break;
    4781           0 :                     case GPKG_TF_PNG_16BIT:
    4782           0 :                         break;
    4783           0 :                     case GPKG_TF_TIFF_32BIT_FLOAT:
    4784           0 :                         break;
    4785             :                 }
    4786          50 :                 if (pszTILE_FORMAT)
    4787           6 :                     oLocalMDMD.SetMetadataItem("TILE_FORMAT", pszTILE_FORMAT,
    4788             :                                                "IMAGE_STRUCTURE");
    4789             :             }
    4790             :         }
    4791         502 :         if (GetRasterCount() > 0 &&
    4792         144 :             GetRasterBand(1)->GetRasterDataType() == GDT_UInt8)
    4793             :         {
    4794         114 :             int bHasNoData = FALSE;
    4795             :             const double dfNoDataValue =
    4796         114 :                 GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    4797         114 :             if (bHasNoData)
    4798             :             {
    4799           3 :                 oLocalMDMD.SetMetadataItem("NODATA_VALUE",
    4800             :                                            CPLSPrintf("%.17g", dfNoDataValue),
    4801             :                                            "IMAGE_STRUCTURE");
    4802             :             }
    4803             :         }
    4804         607 :         for (int i = 1; i <= GetRasterCount(); ++i)
    4805             :         {
    4806             :             auto poBand =
    4807         249 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    4808         249 :             poBand->AddImplicitStatistics(false);
    4809         249 :             char **papszMD = GetRasterBand(i)->GetMetadata();
    4810         249 :             poBand->AddImplicitStatistics(true);
    4811         249 :             if (papszMD)
    4812             :             {
    4813          14 :                 oLocalMDMD.SetMetadata(papszMD, CPLSPrintf("BAND_%d", i));
    4814             :             }
    4815             :         }
    4816         358 :         psXMLNode = oLocalMDMD.Serialize();
    4817             :     }
    4818             : 
    4819         358 :     CSLDestroy(papszMDDup);
    4820         358 :     papszMDDup = nullptr;
    4821             : 
    4822         358 :     WriteMetadata(psXMLNode, m_osRasterTable.c_str());
    4823             : 
    4824         358 :     if (!m_osRasterTable.empty())
    4825             :     {
    4826             :         char **papszGeopackageMD =
    4827         144 :             GDALGeoPackageDataset::GetMetadata("GEOPACKAGE");
    4828             : 
    4829         144 :         papszMDDup = nullptr;
    4830         153 :         for (char **papszIter = papszGeopackageMD; papszIter && *papszIter;
    4831             :              ++papszIter)
    4832             :         {
    4833           9 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4834             :         }
    4835             : 
    4836         288 :         GDALMultiDomainMetadata oLocalMDMD;
    4837         144 :         oLocalMDMD.SetMetadata(papszMDDup);
    4838         144 :         CSLDestroy(papszMDDup);
    4839         144 :         papszMDDup = nullptr;
    4840         144 :         psXMLNode = oLocalMDMD.Serialize();
    4841             : 
    4842         144 :         WriteMetadata(psXMLNode, nullptr);
    4843             :     }
    4844             : 
    4845         588 :     for (auto &poLayer : m_apoLayers)
    4846             :     {
    4847         230 :         const char *pszIdentifier = poLayer->GetMetadataItem("IDENTIFIER");
    4848         230 :         const char *pszDescription = poLayer->GetMetadataItem("DESCRIPTION");
    4849         230 :         if (pszIdentifier != nullptr)
    4850             :         {
    4851             :             char *pszSQL =
    4852           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4853             :                                 "WHERE lower(table_name) = lower('%q')",
    4854             :                                 pszIdentifier, poLayer->GetName());
    4855           3 :             SQLCommand(hDB, pszSQL);
    4856           3 :             sqlite3_free(pszSQL);
    4857             :         }
    4858         230 :         if (pszDescription != nullptr)
    4859             :         {
    4860             :             char *pszSQL =
    4861           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4862             :                                 "WHERE lower(table_name) = lower('%q')",
    4863             :                                 pszDescription, poLayer->GetName());
    4864           3 :             SQLCommand(hDB, pszSQL);
    4865           3 :             sqlite3_free(pszSQL);
    4866             :         }
    4867             : 
    4868         230 :         papszMDDup = nullptr;
    4869         624 :         for (char **papszIter = poLayer->GetMetadata(); papszIter && *papszIter;
    4870             :              ++papszIter)
    4871             :         {
    4872         394 :             if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4873           3 :                 continue;
    4874         391 :             if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4875           3 :                 continue;
    4876         388 :             if (STARTS_WITH_CI(*papszIter, "OLMD_FID64="))
    4877           0 :                 continue;
    4878         388 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4879             :         }
    4880             : 
    4881             :         {
    4882         230 :             GDALMultiDomainMetadata oLocalMDMD;
    4883         230 :             char **papszDomainList = poLayer->GetMetadataDomainList();
    4884         230 :             char **papszIter = papszDomainList;
    4885         230 :             oLocalMDMD.SetMetadata(papszMDDup);
    4886         513 :             while (papszIter && *papszIter)
    4887             :             {
    4888         283 :                 if (!EQUAL(*papszIter, ""))
    4889          66 :                     oLocalMDMD.SetMetadata(poLayer->GetMetadata(*papszIter),
    4890             :                                            *papszIter);
    4891         283 :                 papszIter++;
    4892             :             }
    4893         230 :             CSLDestroy(papszDomainList);
    4894         230 :             psXMLNode = oLocalMDMD.Serialize();
    4895             :         }
    4896             : 
    4897         230 :         CSLDestroy(papszMDDup);
    4898         230 :         papszMDDup = nullptr;
    4899             : 
    4900         230 :         WriteMetadata(psXMLNode, poLayer->GetName());
    4901             :     }
    4902             : }
    4903             : 
    4904             : /************************************************************************/
    4905             : /*                          GetMetadataItem()                           */
    4906             : /************************************************************************/
    4907             : 
    4908        1908 : const char *GDALGeoPackageDataset::GetMetadataItem(const char *pszName,
    4909             :                                                    const char *pszDomain)
    4910             : {
    4911        1908 :     pszDomain = CheckMetadataDomain(pszDomain);
    4912        1908 :     return CSLFetchNameValue(GetMetadata(pszDomain), pszName);
    4913             : }
    4914             : 
    4915             : /************************************************************************/
    4916             : /*                            SetMetadata()                             */
    4917             : /************************************************************************/
    4918             : 
    4919         133 : CPLErr GDALGeoPackageDataset::SetMetadata(char **papszMetadata,
    4920             :                                           const char *pszDomain)
    4921             : {
    4922         133 :     pszDomain = CheckMetadataDomain(pszDomain);
    4923         133 :     m_bMetadataDirty = true;
    4924         133 :     GetMetadata(); /* force loading from storage if needed */
    4925         133 :     return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
    4926             : }
    4927             : 
    4928             : /************************************************************************/
    4929             : /*                          SetMetadataItem()                           */
    4930             : /************************************************************************/
    4931             : 
    4932          21 : CPLErr GDALGeoPackageDataset::SetMetadataItem(const char *pszName,
    4933             :                                               const char *pszValue,
    4934             :                                               const char *pszDomain)
    4935             : {
    4936          21 :     pszDomain = CheckMetadataDomain(pszDomain);
    4937          21 :     m_bMetadataDirty = true;
    4938          21 :     GetMetadata(); /* force loading from storage if needed */
    4939          21 :     return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    4940             : }
    4941             : 
    4942             : /************************************************************************/
    4943             : /*                                Create()                              */
    4944             : /************************************************************************/
    4945             : 
    4946        1003 : int GDALGeoPackageDataset::Create(const char *pszFilename, int nXSize,
    4947             :                                   int nYSize, int nBandsIn, GDALDataType eDT,
    4948             :                                   char **papszOptions)
    4949             : {
    4950        2006 :     CPLString osCommand;
    4951             : 
    4952             :     /* First, ensure there isn't any such file yet. */
    4953             :     VSIStatBufL sStatBuf;
    4954             : 
    4955        1003 :     if (nBandsIn != 0)
    4956             :     {
    4957         226 :         if (eDT == GDT_UInt8)
    4958             :         {
    4959         156 :             if (nBandsIn != 1 && nBandsIn != 2 && nBandsIn != 3 &&
    4960             :                 nBandsIn != 4)
    4961             :             {
    4962           1 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4963             :                          "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), "
    4964             :                          "3 (RGB) or 4 (RGBA) band dataset supported for "
    4965             :                          "Byte datatype");
    4966           1 :                 return FALSE;
    4967             :             }
    4968             :         }
    4969          70 :         else if (eDT == GDT_Int16 || eDT == GDT_UInt16 || eDT == GDT_Float32)
    4970             :         {
    4971          43 :             if (nBandsIn != 1)
    4972             :             {
    4973           3 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4974             :                          "Only single band dataset supported for non Byte "
    4975             :                          "datatype");
    4976           3 :                 return FALSE;
    4977             :             }
    4978             :         }
    4979             :         else
    4980             :         {
    4981          27 :             CPLError(CE_Failure, CPLE_NotSupported,
    4982             :                      "Only Byte, Int16, UInt16 or Float32 supported");
    4983          27 :             return FALSE;
    4984             :         }
    4985             :     }
    4986             : 
    4987         972 :     const size_t nFilenameLen = strlen(pszFilename);
    4988         972 :     const bool bGpkgZip =
    4989         967 :         (nFilenameLen > strlen(".gpkg.zip") &&
    4990        1939 :          !STARTS_WITH(pszFilename, "/vsizip/") &&
    4991         967 :          EQUAL(pszFilename + nFilenameLen - strlen(".gpkg.zip"), ".gpkg.zip"));
    4992             : 
    4993             :     const bool bUseTempFile =
    4994         973 :         bGpkgZip || (CPLTestBool(CPLGetConfigOption(
    4995           1 :                          "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", "NO")) &&
    4996           1 :                      (VSIHasOptimizedReadMultiRange(pszFilename) != FALSE ||
    4997           1 :                       EQUAL(CPLGetConfigOption(
    4998             :                                 "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", ""),
    4999         972 :                             "FORCED")));
    5000             : 
    5001         972 :     bool bFileExists = false;
    5002         972 :     if (VSIStatL(pszFilename, &sStatBuf) == 0)
    5003             :     {
    5004          10 :         bFileExists = true;
    5005          20 :         if (nBandsIn == 0 || bUseTempFile ||
    5006          10 :             !CPLTestBool(
    5007             :                 CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")))
    5008             :         {
    5009           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5010             :                      "A file system object called '%s' already exists.",
    5011             :                      pszFilename);
    5012             : 
    5013           0 :             return FALSE;
    5014             :         }
    5015             :     }
    5016             : 
    5017         972 :     if (bUseTempFile)
    5018             :     {
    5019           3 :         if (bGpkgZip)
    5020             :         {
    5021           2 :             std::string osFilenameInZip(CPLGetFilename(pszFilename));
    5022           2 :             osFilenameInZip.resize(osFilenameInZip.size() - strlen(".zip"));
    5023             :             m_osFinalFilename =
    5024           2 :                 std::string("/vsizip/{") + pszFilename + "}/" + osFilenameInZip;
    5025             :         }
    5026             :         else
    5027             :         {
    5028           1 :             m_osFinalFilename = pszFilename;
    5029             :         }
    5030           3 :         m_pszFilename = CPLStrdup(
    5031           6 :             CPLGenerateTempFilenameSafe(CPLGetFilename(pszFilename)).c_str());
    5032           3 :         CPLDebug("GPKG", "Creating temporary file %s", m_pszFilename);
    5033             :     }
    5034             :     else
    5035             :     {
    5036         969 :         m_pszFilename = CPLStrdup(pszFilename);
    5037             :     }
    5038         972 :     m_bNew = true;
    5039         972 :     eAccess = GA_Update;
    5040         972 :     m_bDateTimeWithTZ =
    5041         972 :         EQUAL(CSLFetchNameValueDef(papszOptions, "DATETIME_FORMAT", "WITH_TZ"),
    5042             :               "WITH_TZ");
    5043             : 
    5044             :     // for test/debug purposes only. true is the nominal value
    5045         972 :     m_bPNGSupports2Bands =
    5046         972 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_2BANDS", "TRUE"));
    5047         972 :     m_bPNGSupportsCT =
    5048         972 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_CT", "TRUE"));
    5049             : 
    5050         972 :     if (!OpenOrCreateDB(bFileExists
    5051             :                             ? SQLITE_OPEN_READWRITE
    5052             :                             : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE))
    5053           7 :         return FALSE;
    5054             : 
    5055             :     /* Default to synchronous=off for performance for new file */
    5056        1920 :     if (!bFileExists &&
    5057         955 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5058             :     {
    5059         441 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5060             :     }
    5061             : 
    5062             :     /* OGR UTF-8 support. If we set the UTF-8 Pragma early on, it */
    5063             :     /* will be written into the main file and supported henceforth */
    5064         965 :     SQLCommand(hDB, "PRAGMA encoding = \"UTF-8\"");
    5065             : 
    5066         965 :     if (bFileExists)
    5067             :     {
    5068          10 :         VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
    5069          10 :         if (fp)
    5070             :         {
    5071             :             GByte abyHeader[100];
    5072          10 :             VSIFReadL(abyHeader, 1, sizeof(abyHeader), fp);
    5073          10 :             VSIFCloseL(fp);
    5074             : 
    5075          10 :             memcpy(&m_nApplicationId, abyHeader + knApplicationIdPos, 4);
    5076          10 :             m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    5077          10 :             memcpy(&m_nUserVersion, abyHeader + knUserVersionPos, 4);
    5078          10 :             m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    5079             : 
    5080          10 :             if (m_nApplicationId == GP10_APPLICATION_ID)
    5081             :             {
    5082           0 :                 CPLDebug("GPKG", "GeoPackage v1.0");
    5083             :             }
    5084          10 :             else if (m_nApplicationId == GP11_APPLICATION_ID)
    5085             :             {
    5086           0 :                 CPLDebug("GPKG", "GeoPackage v1.1");
    5087             :             }
    5088          10 :             else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    5089          10 :                      m_nUserVersion >= GPKG_1_2_VERSION)
    5090             :             {
    5091          10 :                 CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    5092          10 :                          (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    5093             :             }
    5094             :         }
    5095             : 
    5096          10 :         DetectSpatialRefSysColumns();
    5097             :     }
    5098             : 
    5099         965 :     const char *pszVersion = CSLFetchNameValue(papszOptions, "VERSION");
    5100         965 :     if (pszVersion && !EQUAL(pszVersion, "AUTO"))
    5101             :     {
    5102          40 :         if (EQUAL(pszVersion, "1.0"))
    5103             :         {
    5104           2 :             m_nApplicationId = GP10_APPLICATION_ID;
    5105           2 :             m_nUserVersion = 0;
    5106             :         }
    5107          38 :         else if (EQUAL(pszVersion, "1.1"))
    5108             :         {
    5109           1 :             m_nApplicationId = GP11_APPLICATION_ID;
    5110           1 :             m_nUserVersion = 0;
    5111             :         }
    5112          37 :         else if (EQUAL(pszVersion, "1.2"))
    5113             :         {
    5114          15 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5115          15 :             m_nUserVersion = GPKG_1_2_VERSION;
    5116             :         }
    5117          22 :         else if (EQUAL(pszVersion, "1.3"))
    5118             :         {
    5119           3 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5120           3 :             m_nUserVersion = GPKG_1_3_VERSION;
    5121             :         }
    5122          19 :         else if (EQUAL(pszVersion, "1.4"))
    5123             :         {
    5124          19 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5125          19 :             m_nUserVersion = GPKG_1_4_VERSION;
    5126             :         }
    5127             :     }
    5128             : 
    5129         965 :     SoftStartTransaction();
    5130             : 
    5131        1930 :     CPLString osSQL;
    5132         965 :     if (!bFileExists)
    5133             :     {
    5134             :         /* Requirement 10: A GeoPackage SHALL include a gpkg_spatial_ref_sys
    5135             :          * table */
    5136             :         /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5137             :         osSQL = "CREATE TABLE gpkg_spatial_ref_sys ("
    5138             :                 "srs_name TEXT NOT NULL,"
    5139             :                 "srs_id INTEGER NOT NULL PRIMARY KEY,"
    5140             :                 "organization TEXT NOT NULL,"
    5141             :                 "organization_coordsys_id INTEGER NOT NULL,"
    5142             :                 "definition  TEXT NOT NULL,"
    5143         955 :                 "description TEXT";
    5144         955 :         if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "CRS_WKT_EXTENSION",
    5145        1136 :                                              "NO")) ||
    5146         181 :             (nBandsIn != 0 && eDT != GDT_UInt8))
    5147             :         {
    5148          42 :             m_bHasDefinition12_063 = true;
    5149          42 :             osSQL += ", definition_12_063 TEXT NOT NULL";
    5150          42 :             if (m_nUserVersion >= GPKG_1_4_VERSION)
    5151             :             {
    5152          40 :                 osSQL += ", epoch DOUBLE";
    5153          40 :                 m_bHasEpochColumn = true;
    5154             :             }
    5155             :         }
    5156             :         osSQL += ")"
    5157             :                  ";"
    5158             :                  /* Requirement 11: The gpkg_spatial_ref_sys table in a
    5159             :                     GeoPackage SHALL */
    5160             :                  /* contain a record for EPSG:4326, the geodetic WGS84 SRS */
    5161             :                  /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5162             : 
    5163             :                  "INSERT INTO gpkg_spatial_ref_sys ("
    5164             :                  "srs_name, srs_id, organization, organization_coordsys_id, "
    5165         955 :                  "definition, description";
    5166         955 :         if (m_bHasDefinition12_063)
    5167          42 :             osSQL += ", definition_12_063";
    5168             :         osSQL +=
    5169             :             ") VALUES ("
    5170             :             "'WGS 84 geodetic', 4326, 'EPSG', 4326, '"
    5171             :             "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS "
    5172             :             "84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],"
    5173             :             "AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY["
    5174             :             "\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY["
    5175             :             "\"EPSG\",\"9122\"]],AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\","
    5176             :             "EAST],AUTHORITY[\"EPSG\",\"4326\"]]"
    5177             :             "', 'longitude/latitude coordinates in decimal degrees on the WGS "
    5178         955 :             "84 spheroid'";
    5179         955 :         if (m_bHasDefinition12_063)
    5180             :             osSQL +=
    5181             :                 ", 'GEODCRS[\"WGS 84\", DATUM[\"World Geodetic System 1984\", "
    5182             :                 "ELLIPSOID[\"WGS 84\",6378137, 298.257223563, "
    5183             :                 "LENGTHUNIT[\"metre\", 1.0]]], PRIMEM[\"Greenwich\", 0.0, "
    5184             :                 "ANGLEUNIT[\"degree\",0.0174532925199433]], CS[ellipsoidal, "
    5185             :                 "2], AXIS[\"latitude\", north, ORDER[1]], AXIS[\"longitude\", "
    5186             :                 "east, ORDER[2]], ANGLEUNIT[\"degree\", 0.0174532925199433], "
    5187          42 :                 "ID[\"EPSG\", 4326]]'";
    5188             :         osSQL +=
    5189             :             ")"
    5190             :             ";"
    5191             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5192             :                SHALL */
    5193             :             /* contain a record with an srs_id of -1, an organization of “NONE”,
    5194             :              */
    5195             :             /* an organization_coordsys_id of -1, and definition “undefined” */
    5196             :             /* for undefined Cartesian coordinate reference systems */
    5197             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5198             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5199             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5200         955 :             "definition, description";
    5201         955 :         if (m_bHasDefinition12_063)
    5202          42 :             osSQL += ", definition_12_063";
    5203             :         osSQL += ") VALUES ("
    5204             :                  "'Undefined Cartesian SRS', -1, 'NONE', -1, 'undefined', "
    5205         955 :                  "'undefined Cartesian coordinate reference system'";
    5206         955 :         if (m_bHasDefinition12_063)
    5207          42 :             osSQL += ", 'undefined'";
    5208             :         osSQL +=
    5209             :             ")"
    5210             :             ";"
    5211             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5212             :                SHALL */
    5213             :             /* contain a record with an srs_id of 0, an organization of “NONE”,
    5214             :              */
    5215             :             /* an organization_coordsys_id of 0, and definition “undefined” */
    5216             :             /* for undefined geographic coordinate reference systems */
    5217             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5218             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5219             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5220         955 :             "definition, description";
    5221         955 :         if (m_bHasDefinition12_063)
    5222          42 :             osSQL += ", definition_12_063";
    5223             :         osSQL += ") VALUES ("
    5224             :                  "'Undefined geographic SRS', 0, 'NONE', 0, 'undefined', "
    5225         955 :                  "'undefined geographic coordinate reference system'";
    5226         955 :         if (m_bHasDefinition12_063)
    5227          42 :             osSQL += ", 'undefined'";
    5228             :         osSQL += ")"
    5229             :                  ";"
    5230             :                  /* Requirement 13: A GeoPackage file SHALL include a
    5231             :                     gpkg_contents table */
    5232             :                  /* http://opengis.github.io/geopackage/#_contents */
    5233             :                  "CREATE TABLE gpkg_contents ("
    5234             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5235             :                  "data_type TEXT NOT NULL,"
    5236             :                  "identifier TEXT UNIQUE,"
    5237             :                  "description TEXT DEFAULT '',"
    5238             :                  "last_change DATETIME NOT NULL DEFAULT "
    5239             :                  "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    5240             :                  "min_x DOUBLE, min_y DOUBLE,"
    5241             :                  "max_x DOUBLE, max_y DOUBLE,"
    5242             :                  "srs_id INTEGER,"
    5243             :                  "CONSTRAINT fk_gc_r_srs_id FOREIGN KEY (srs_id) REFERENCES "
    5244             :                  "gpkg_spatial_ref_sys(srs_id)"
    5245         955 :                  ")";
    5246             : 
    5247             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5248         955 :         if (CPLFetchBool(papszOptions, "ADD_GPKG_OGR_CONTENTS", true))
    5249             :         {
    5250         950 :             m_bHasGPKGOGRContents = true;
    5251             :             osSQL += ";"
    5252             :                      "CREATE TABLE gpkg_ogr_contents("
    5253             :                      "table_name TEXT NOT NULL PRIMARY KEY,"
    5254             :                      "feature_count INTEGER DEFAULT NULL"
    5255         950 :                      ")";
    5256             :         }
    5257             : #endif
    5258             : 
    5259             :         /* Requirement 21: A GeoPackage with a gpkg_contents table row with a
    5260             :          * “features” */
    5261             :         /* data_type SHALL contain a gpkg_geometry_columns table or updateable
    5262             :          * view */
    5263             :         /* http://opengis.github.io/geopackage/#_geometry_columns */
    5264             :         const bool bCreateGeometryColumns =
    5265         955 :             CPLTestBool(CPLGetConfigOption("CREATE_GEOMETRY_COLUMNS", "YES"));
    5266         955 :         if (bCreateGeometryColumns)
    5267             :         {
    5268         954 :             m_bHasGPKGGeometryColumns = true;
    5269         954 :             osSQL += ";";
    5270         954 :             osSQL += pszCREATE_GPKG_GEOMETRY_COLUMNS;
    5271             :         }
    5272             :     }
    5273             : 
    5274             :     const bool bCreateTriggers =
    5275         965 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "YES"));
    5276          10 :     if ((bFileExists && nBandsIn != 0 &&
    5277          10 :          SQLGetInteger(
    5278             :              hDB,
    5279             :              "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_tile_matrix_set' "
    5280             :              "AND type in ('table', 'view')",
    5281        1930 :              nullptr) == 0) ||
    5282         964 :         (!bFileExists &&
    5283         955 :          CPLTestBool(CPLGetConfigOption("CREATE_RASTER_TABLES", "YES"))))
    5284             :     {
    5285         955 :         if (!osSQL.empty())
    5286         954 :             osSQL += ";";
    5287             : 
    5288             :         /* From C.5. gpkg_tile_matrix_set Table 28. gpkg_tile_matrix_set Table
    5289             :          * Creation SQL  */
    5290             :         osSQL += "CREATE TABLE gpkg_tile_matrix_set ("
    5291             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5292             :                  "srs_id INTEGER NOT NULL,"
    5293             :                  "min_x DOUBLE NOT NULL,"
    5294             :                  "min_y DOUBLE NOT NULL,"
    5295             :                  "max_x DOUBLE NOT NULL,"
    5296             :                  "max_y DOUBLE NOT NULL,"
    5297             :                  "CONSTRAINT fk_gtms_table_name FOREIGN KEY (table_name) "
    5298             :                  "REFERENCES gpkg_contents(table_name),"
    5299             :                  "CONSTRAINT fk_gtms_srs FOREIGN KEY (srs_id) REFERENCES "
    5300             :                  "gpkg_spatial_ref_sys (srs_id)"
    5301             :                  ")"
    5302             :                  ";"
    5303             : 
    5304             :                  /* From C.6. gpkg_tile_matrix Table 29. gpkg_tile_matrix Table
    5305             :                     Creation SQL */
    5306             :                  "CREATE TABLE gpkg_tile_matrix ("
    5307             :                  "table_name TEXT NOT NULL,"
    5308             :                  "zoom_level INTEGER NOT NULL,"
    5309             :                  "matrix_width INTEGER NOT NULL,"
    5310             :                  "matrix_height INTEGER NOT NULL,"
    5311             :                  "tile_width INTEGER NOT NULL,"
    5312             :                  "tile_height INTEGER NOT NULL,"
    5313             :                  "pixel_x_size DOUBLE NOT NULL,"
    5314             :                  "pixel_y_size DOUBLE NOT NULL,"
    5315             :                  "CONSTRAINT pk_ttm PRIMARY KEY (table_name, zoom_level),"
    5316             :                  "CONSTRAINT fk_tmm_table_name FOREIGN KEY (table_name) "
    5317             :                  "REFERENCES gpkg_contents(table_name)"
    5318         955 :                  ")";
    5319             : 
    5320         955 :         if (bCreateTriggers)
    5321             :         {
    5322             :             /* From D.1. gpkg_tile_matrix Table 39. gpkg_tile_matrix Trigger
    5323             :              * Definition SQL */
    5324         955 :             const char *pszTileMatrixTrigger =
    5325             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_insert' "
    5326             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5327             :                 "FOR EACH ROW BEGIN "
    5328             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5329             :                 "violates constraint: zoom_level cannot be less than 0') "
    5330             :                 "WHERE (NEW.zoom_level < 0); "
    5331             :                 "END; "
    5332             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_update' "
    5333             :                 "BEFORE UPDATE of zoom_level ON 'gpkg_tile_matrix' "
    5334             :                 "FOR EACH ROW BEGIN "
    5335             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5336             :                 "violates constraint: zoom_level cannot be less than 0') "
    5337             :                 "WHERE (NEW.zoom_level < 0); "
    5338             :                 "END; "
    5339             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_insert' "
    5340             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5341             :                 "FOR EACH ROW BEGIN "
    5342             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5343             :                 "violates constraint: matrix_width cannot be less than 1') "
    5344             :                 "WHERE (NEW.matrix_width < 1); "
    5345             :                 "END; "
    5346             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_update' "
    5347             :                 "BEFORE UPDATE OF matrix_width ON 'gpkg_tile_matrix' "
    5348             :                 "FOR EACH ROW BEGIN "
    5349             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5350             :                 "violates constraint: matrix_width cannot be less than 1') "
    5351             :                 "WHERE (NEW.matrix_width < 1); "
    5352             :                 "END; "
    5353             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_insert' "
    5354             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5355             :                 "FOR EACH ROW BEGIN "
    5356             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5357             :                 "violates constraint: matrix_height cannot be less than 1') "
    5358             :                 "WHERE (NEW.matrix_height < 1); "
    5359             :                 "END; "
    5360             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_update' "
    5361             :                 "BEFORE UPDATE OF matrix_height ON 'gpkg_tile_matrix' "
    5362             :                 "FOR EACH ROW BEGIN "
    5363             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5364             :                 "violates constraint: matrix_height cannot be less than 1') "
    5365             :                 "WHERE (NEW.matrix_height < 1); "
    5366             :                 "END; "
    5367             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_insert' "
    5368             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5369             :                 "FOR EACH ROW BEGIN "
    5370             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5371             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5372             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5373             :                 "END; "
    5374             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_update' "
    5375             :                 "BEFORE UPDATE OF pixel_x_size ON 'gpkg_tile_matrix' "
    5376             :                 "FOR EACH ROW BEGIN "
    5377             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5378             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5379             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5380             :                 "END; "
    5381             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_insert' "
    5382             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5383             :                 "FOR EACH ROW BEGIN "
    5384             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5385             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5386             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5387             :                 "END; "
    5388             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_update' "
    5389             :                 "BEFORE UPDATE OF pixel_y_size ON 'gpkg_tile_matrix' "
    5390             :                 "FOR EACH ROW BEGIN "
    5391             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5392             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5393             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5394             :                 "END;";
    5395         955 :             osSQL += ";";
    5396         955 :             osSQL += pszTileMatrixTrigger;
    5397             :         }
    5398             :     }
    5399             : 
    5400         965 :     if (!osSQL.empty() && OGRERR_NONE != SQLCommand(hDB, osSQL))
    5401           1 :         return FALSE;
    5402             : 
    5403         964 :     if (!bFileExists)
    5404             :     {
    5405             :         const char *pszMetadataTables =
    5406         954 :             CSLFetchNameValue(papszOptions, "METADATA_TABLES");
    5407         954 :         if (pszMetadataTables)
    5408          10 :             m_nCreateMetadataTables = int(CPLTestBool(pszMetadataTables));
    5409             : 
    5410         954 :         if (m_nCreateMetadataTables == TRUE && !CreateMetadataTables())
    5411           0 :             return FALSE;
    5412             : 
    5413         954 :         if (m_bHasDefinition12_063)
    5414             :         {
    5415          84 :             if (OGRERR_NONE != CreateExtensionsTableIfNecessary() ||
    5416             :                 OGRERR_NONE !=
    5417          42 :                     SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5418             :                                     "(table_name, column_name, extension_name, "
    5419             :                                     "definition, scope) "
    5420             :                                     "VALUES "
    5421             :                                     "('gpkg_spatial_ref_sys', "
    5422             :                                     "'definition_12_063', 'gpkg_crs_wkt', "
    5423             :                                     "'http://www.geopackage.org/spec120/"
    5424             :                                     "#extension_crs_wkt', 'read-write')"))
    5425             :             {
    5426           0 :                 return FALSE;
    5427             :             }
    5428          42 :             if (m_bHasEpochColumn)
    5429             :             {
    5430          40 :                 if (OGRERR_NONE !=
    5431          40 :                         SQLCommand(
    5432             :                             hDB, "UPDATE gpkg_extensions SET extension_name = "
    5433             :                                  "'gpkg_crs_wkt_1_1' "
    5434          80 :                                  "WHERE extension_name = 'gpkg_crs_wkt'") ||
    5435             :                     OGRERR_NONE !=
    5436          40 :                         SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5437             :                                         "(table_name, column_name, "
    5438             :                                         "extension_name, definition, scope) "
    5439             :                                         "VALUES "
    5440             :                                         "('gpkg_spatial_ref_sys', 'epoch', "
    5441             :                                         "'gpkg_crs_wkt_1_1', "
    5442             :                                         "'http://www.geopackage.org/spec/"
    5443             :                                         "#extension_crs_wkt', "
    5444             :                                         "'read-write')"))
    5445             :                 {
    5446           0 :                     return FALSE;
    5447             :                 }
    5448             :             }
    5449             :         }
    5450             :     }
    5451             : 
    5452         964 :     if (nBandsIn != 0)
    5453             :     {
    5454         190 :         const std::string osTableName = CPLGetBasenameSafe(m_pszFilename);
    5455             :         m_osRasterTable = CSLFetchNameValueDef(papszOptions, "RASTER_TABLE",
    5456         190 :                                                osTableName.c_str());
    5457         190 :         if (m_osRasterTable.empty())
    5458             :         {
    5459           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5460             :                      "RASTER_TABLE must be set to a non empty value");
    5461           0 :             return FALSE;
    5462             :         }
    5463         190 :         m_bIdentifierAsCO =
    5464         190 :             CSLFetchNameValue(papszOptions, "RASTER_IDENTIFIER") != nullptr;
    5465             :         m_osIdentifier = CSLFetchNameValueDef(papszOptions, "RASTER_IDENTIFIER",
    5466         190 :                                               m_osRasterTable);
    5467         190 :         m_bDescriptionAsCO =
    5468         190 :             CSLFetchNameValue(papszOptions, "RASTER_DESCRIPTION") != nullptr;
    5469             :         m_osDescription =
    5470         190 :             CSLFetchNameValueDef(papszOptions, "RASTER_DESCRIPTION", "");
    5471         190 :         SetDataType(eDT);
    5472         190 :         if (eDT == GDT_Int16)
    5473          16 :             SetGlobalOffsetScale(-32768.0, 1.0);
    5474             : 
    5475             :         /* From C.7. sample_tile_pyramid (Informative) Table 31. EXAMPLE: tiles
    5476             :          * table Create Table SQL (Informative) */
    5477             :         char *pszSQL =
    5478         190 :             sqlite3_mprintf("CREATE TABLE \"%w\" ("
    5479             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    5480             :                             "zoom_level INTEGER NOT NULL,"
    5481             :                             "tile_column INTEGER NOT NULL,"
    5482             :                             "tile_row INTEGER NOT NULL,"
    5483             :                             "tile_data BLOB NOT NULL,"
    5484             :                             "UNIQUE (zoom_level, tile_column, tile_row)"
    5485             :                             ")",
    5486             :                             m_osRasterTable.c_str());
    5487         190 :         osSQL = pszSQL;
    5488         190 :         sqlite3_free(pszSQL);
    5489             : 
    5490         190 :         if (bCreateTriggers)
    5491             :         {
    5492         190 :             osSQL += ";";
    5493         190 :             osSQL += CreateRasterTriggersSQL(m_osRasterTable);
    5494             :         }
    5495             : 
    5496         190 :         OGRErr eErr = SQLCommand(hDB, osSQL);
    5497         190 :         if (OGRERR_NONE != eErr)
    5498           0 :             return FALSE;
    5499             : 
    5500         190 :         const char *pszTF = CSLFetchNameValue(papszOptions, "TILE_FORMAT");
    5501         190 :         if (eDT == GDT_Int16 || eDT == GDT_UInt16)
    5502             :         {
    5503          27 :             m_eTF = GPKG_TF_PNG_16BIT;
    5504          27 :             if (pszTF)
    5505             :             {
    5506           1 :                 if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "PNG"))
    5507             :                 {
    5508           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5509             :                              "Only AUTO or PNG supported "
    5510             :                              "as tile format for Int16 / UInt16");
    5511             :                 }
    5512             :             }
    5513             :         }
    5514         163 :         else if (eDT == GDT_Float32)
    5515             :         {
    5516          13 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    5517          13 :             if (pszTF)
    5518             :             {
    5519           5 :                 if (EQUAL(pszTF, "PNG"))
    5520           5 :                     m_eTF = GPKG_TF_PNG_16BIT;
    5521           0 :                 else if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "TIFF"))
    5522             :                 {
    5523           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5524             :                              "Only AUTO, PNG or TIFF supported "
    5525             :                              "as tile format for Float32");
    5526             :                 }
    5527             :             }
    5528             :         }
    5529             :         else
    5530             :         {
    5531         150 :             if (pszTF)
    5532             :             {
    5533          71 :                 m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    5534          71 :                 if (nBandsIn == 1 && m_eTF != GPKG_TF_PNG)
    5535           7 :                     m_bMetadataDirty = true;
    5536             :             }
    5537          79 :             else if (nBandsIn == 1)
    5538          68 :                 m_eTF = GPKG_TF_PNG;
    5539             :         }
    5540             : 
    5541         190 :         if (eDT != GDT_UInt8)
    5542             :         {
    5543          40 :             if (!CreateTileGriddedTable(papszOptions))
    5544           0 :                 return FALSE;
    5545             :         }
    5546             : 
    5547         190 :         nRasterXSize = nXSize;
    5548         190 :         nRasterYSize = nYSize;
    5549             : 
    5550             :         const char *pszTileSize =
    5551         190 :             CSLFetchNameValueDef(papszOptions, "BLOCKSIZE", "256");
    5552             :         const char *pszTileWidth =
    5553         190 :             CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", pszTileSize);
    5554             :         const char *pszTileHeight =
    5555         190 :             CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", pszTileSize);
    5556         190 :         int nTileWidth = atoi(pszTileWidth);
    5557         190 :         int nTileHeight = atoi(pszTileHeight);
    5558         190 :         if ((nTileWidth < 8 || nTileWidth > 4096 || nTileHeight < 8 ||
    5559         380 :              nTileHeight > 4096) &&
    5560           1 :             !CPLTestBool(CPLGetConfigOption("GPKG_ALLOW_CRAZY_SETTINGS", "NO")))
    5561             :         {
    5562           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5563             :                      "Invalid block dimensions: %dx%d", nTileWidth,
    5564             :                      nTileHeight);
    5565           0 :             return FALSE;
    5566             :         }
    5567             : 
    5568         513 :         for (int i = 1; i <= nBandsIn; i++)
    5569             :         {
    5570         323 :             SetBand(i, std::make_unique<GDALGeoPackageRasterBand>(
    5571             :                            this, nTileWidth, nTileHeight));
    5572             :         }
    5573             : 
    5574         190 :         GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL",
    5575             :                                         "IMAGE_STRUCTURE");
    5576         190 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", m_osIdentifier);
    5577         190 :         if (!m_osDescription.empty())
    5578           1 :             GDALPamDataset::SetMetadataItem("DESCRIPTION", m_osDescription);
    5579             : 
    5580         190 :         ParseCompressionOptions(papszOptions);
    5581             : 
    5582         190 :         if (m_eTF == GPKG_TF_WEBP)
    5583             :         {
    5584          10 :             if (!RegisterWebPExtension())
    5585           0 :                 return FALSE;
    5586             :         }
    5587             : 
    5588             :         m_osTilingScheme =
    5589         190 :             CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5590         190 :         if (!EQUAL(m_osTilingScheme, "CUSTOM"))
    5591             :         {
    5592          22 :             const auto poTS = GetTilingScheme(m_osTilingScheme);
    5593          22 :             if (!poTS)
    5594           0 :                 return FALSE;
    5595             : 
    5596          43 :             if (nTileWidth != poTS->nTileWidth ||
    5597          21 :                 nTileHeight != poTS->nTileHeight)
    5598             :             {
    5599           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    5600             :                          "Tile dimension should be %dx%d for %s tiling scheme",
    5601           1 :                          poTS->nTileWidth, poTS->nTileHeight,
    5602             :                          m_osTilingScheme.c_str());
    5603           1 :                 return FALSE;
    5604             :             }
    5605             : 
    5606             :             const char *pszZoomLevel =
    5607          21 :                 CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    5608          21 :             if (pszZoomLevel)
    5609             :             {
    5610           1 :                 m_nZoomLevel = atoi(pszZoomLevel);
    5611           1 :                 int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    5612           1 :                 while ((1 << nMaxZoomLevelForThisTM) >
    5613           2 :                            INT_MAX / poTS->nTileXCountZoomLevel0 ||
    5614           1 :                        (1 << nMaxZoomLevelForThisTM) >
    5615           1 :                            INT_MAX / poTS->nTileYCountZoomLevel0)
    5616             :                 {
    5617           0 :                     --nMaxZoomLevelForThisTM;
    5618             :                 }
    5619             : 
    5620           1 :                 if (m_nZoomLevel < 0 || m_nZoomLevel > nMaxZoomLevelForThisTM)
    5621             :                 {
    5622           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    5623             :                              "ZOOM_LEVEL = %s is invalid. It should be in "
    5624             :                              "[0,%d] range",
    5625             :                              pszZoomLevel, nMaxZoomLevelForThisTM);
    5626           0 :                     return FALSE;
    5627             :                 }
    5628             :             }
    5629             : 
    5630             :             // Implicitly sets SRS.
    5631          21 :             OGRSpatialReference oSRS;
    5632          21 :             if (oSRS.importFromEPSG(poTS->nEPSGCode) != OGRERR_NONE)
    5633           0 :                 return FALSE;
    5634          21 :             char *pszWKT = nullptr;
    5635          21 :             oSRS.exportToWkt(&pszWKT);
    5636          21 :             SetProjection(pszWKT);
    5637          21 :             CPLFree(pszWKT);
    5638             :         }
    5639             :         else
    5640             :         {
    5641         168 :             if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5642             :             {
    5643           0 :                 CPLError(
    5644             :                     CE_Failure, CPLE_NotSupported,
    5645             :                     "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5646           0 :                 return false;
    5647             :             }
    5648             :         }
    5649             :     }
    5650             : 
    5651         963 :     if (bFileExists && nBandsIn > 0 && eDT == GDT_UInt8)
    5652             :     {
    5653             :         // If there was an ogr_empty_table table, we can remove it
    5654           9 :         RemoveOGREmptyTable();
    5655             :     }
    5656             : 
    5657         963 :     SoftCommitTransaction();
    5658             : 
    5659             :     /* Requirement 2 */
    5660             :     /* We have to do this after there's some content so the database file */
    5661             :     /* is not zero length */
    5662         963 :     SetApplicationAndUserVersionId();
    5663             : 
    5664             :     /* Default to synchronous=off for performance for new file */
    5665        1916 :     if (!bFileExists &&
    5666         953 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5667             :     {
    5668         441 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5669             :     }
    5670             : 
    5671         963 :     return TRUE;
    5672             : }
    5673             : 
    5674             : /************************************************************************/
    5675             : /*                        RemoveOGREmptyTable()                         */
    5676             : /************************************************************************/
    5677             : 
    5678         774 : void GDALGeoPackageDataset::RemoveOGREmptyTable()
    5679             : {
    5680             :     // Run with sqlite3_exec since we don't want errors to be emitted
    5681         774 :     sqlite3_exec(hDB, "DROP TABLE IF EXISTS ogr_empty_table", nullptr, nullptr,
    5682             :                  nullptr);
    5683         774 :     sqlite3_exec(
    5684             :         hDB, "DELETE FROM gpkg_contents WHERE table_name = 'ogr_empty_table'",
    5685             :         nullptr, nullptr, nullptr);
    5686             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5687         774 :     if (m_bHasGPKGOGRContents)
    5688             :     {
    5689         760 :         sqlite3_exec(hDB,
    5690             :                      "DELETE FROM gpkg_ogr_contents WHERE "
    5691             :                      "table_name = 'ogr_empty_table'",
    5692             :                      nullptr, nullptr, nullptr);
    5693             :     }
    5694             : #endif
    5695         774 :     sqlite3_exec(hDB,
    5696             :                  "DELETE FROM gpkg_geometry_columns WHERE "
    5697             :                  "table_name = 'ogr_empty_table'",
    5698             :                  nullptr, nullptr, nullptr);
    5699         774 : }
    5700             : 
    5701             : /************************************************************************/
    5702             : /*                        CreateTileGriddedTable()                      */
    5703             : /************************************************************************/
    5704             : 
    5705          40 : bool GDALGeoPackageDataset::CreateTileGriddedTable(char **papszOptions)
    5706             : {
    5707          80 :     CPLString osSQL;
    5708          40 :     if (!HasGriddedCoverageAncillaryTable())
    5709             :     {
    5710             :         // It doesn't exist. So create gpkg_extensions table if necessary, and
    5711             :         // gpkg_2d_gridded_coverage_ancillary & gpkg_2d_gridded_tile_ancillary,
    5712             :         // and register them as extensions.
    5713          40 :         if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    5714           0 :             return false;
    5715             : 
    5716             :         // Req 1 /table-defs/coverage-ancillary
    5717             :         osSQL = "CREATE TABLE gpkg_2d_gridded_coverage_ancillary ("
    5718             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5719             :                 "tile_matrix_set_name TEXT NOT NULL UNIQUE,"
    5720             :                 "datatype TEXT NOT NULL DEFAULT 'integer',"
    5721             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5722             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5723             :                 "precision REAL DEFAULT 1.0,"
    5724             :                 "data_null REAL,"
    5725             :                 "grid_cell_encoding TEXT DEFAULT 'grid-value-is-center',"
    5726             :                 "uom TEXT,"
    5727             :                 "field_name TEXT DEFAULT 'Height',"
    5728             :                 "quantity_definition TEXT DEFAULT 'Height',"
    5729             :                 "CONSTRAINT fk_g2dgtct_name FOREIGN KEY(tile_matrix_set_name) "
    5730             :                 "REFERENCES gpkg_tile_matrix_set ( table_name ) "
    5731             :                 "CHECK (datatype in ('integer','float')))"
    5732             :                 ";"
    5733             :                 // Requirement 2 /table-defs/tile-ancillary
    5734             :                 "CREATE TABLE gpkg_2d_gridded_tile_ancillary ("
    5735             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5736             :                 "tpudt_name TEXT NOT NULL,"
    5737             :                 "tpudt_id INTEGER NOT NULL,"
    5738             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5739             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5740             :                 "min REAL DEFAULT NULL,"
    5741             :                 "max REAL DEFAULT NULL,"
    5742             :                 "mean REAL DEFAULT NULL,"
    5743             :                 "std_dev REAL DEFAULT NULL,"
    5744             :                 "CONSTRAINT fk_g2dgtat_name FOREIGN KEY (tpudt_name) "
    5745             :                 "REFERENCES gpkg_contents(table_name),"
    5746             :                 "UNIQUE (tpudt_name, tpudt_id))"
    5747             :                 ";"
    5748             :                 // Requirement 6 /gpkg-extensions
    5749             :                 "INSERT INTO gpkg_extensions "
    5750             :                 "(table_name, column_name, extension_name, definition, scope) "
    5751             :                 "VALUES ('gpkg_2d_gridded_coverage_ancillary', NULL, "
    5752             :                 "'gpkg_2d_gridded_coverage', "
    5753             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5754             :                 "'read-write')"
    5755             :                 ";"
    5756             :                 // Requirement 6 /gpkg-extensions
    5757             :                 "INSERT INTO gpkg_extensions "
    5758             :                 "(table_name, column_name, extension_name, definition, scope) "
    5759             :                 "VALUES ('gpkg_2d_gridded_tile_ancillary', NULL, "
    5760             :                 "'gpkg_2d_gridded_coverage', "
    5761             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5762             :                 "'read-write')"
    5763          40 :                 ";";
    5764             :     }
    5765             : 
    5766             :     // Requirement 6 /gpkg-extensions
    5767          40 :     char *pszSQL = sqlite3_mprintf(
    5768             :         "INSERT INTO gpkg_extensions "
    5769             :         "(table_name, column_name, extension_name, definition, scope) "
    5770             :         "VALUES ('%q', 'tile_data', "
    5771             :         "'gpkg_2d_gridded_coverage', "
    5772             :         "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5773             :         "'read-write')",
    5774             :         m_osRasterTable.c_str());
    5775          40 :     osSQL += pszSQL;
    5776          40 :     osSQL += ";";
    5777          40 :     sqlite3_free(pszSQL);
    5778             : 
    5779             :     // Requirement 7 /gpkg-2d-gridded-coverage-ancillary
    5780             :     // Requirement 8 /gpkg-2d-gridded-coverage-ancillary-set-name
    5781             :     // Requirement 9 /gpkg-2d-gridded-coverage-ancillary-datatype
    5782          40 :     m_dfPrecision =
    5783          40 :         CPLAtof(CSLFetchNameValueDef(papszOptions, "PRECISION", "1"));
    5784             :     CPLString osGridCellEncoding(CSLFetchNameValueDef(
    5785          80 :         papszOptions, "GRID_CELL_ENCODING", "grid-value-is-center"));
    5786          40 :     m_bGridCellEncodingAsCO =
    5787          40 :         CSLFetchNameValue(papszOptions, "GRID_CELL_ENCODING") != nullptr;
    5788          80 :     CPLString osUom(CSLFetchNameValueDef(papszOptions, "UOM", ""));
    5789             :     CPLString osFieldName(
    5790          80 :         CSLFetchNameValueDef(papszOptions, "FIELD_NAME", "Height"));
    5791             :     CPLString osQuantityDefinition(
    5792          80 :         CSLFetchNameValueDef(papszOptions, "QUANTITY_DEFINITION", "Height"));
    5793             : 
    5794         121 :     pszSQL = sqlite3_mprintf(
    5795             :         "INSERT INTO gpkg_2d_gridded_coverage_ancillary "
    5796             :         "(tile_matrix_set_name, datatype, scale, offset, precision, "
    5797             :         "grid_cell_encoding, uom, field_name, quantity_definition) "
    5798             :         "VALUES (%Q, '%s', %.17g, %.17g, %.17g, %Q, %Q, %Q, %Q)",
    5799             :         m_osRasterTable.c_str(),
    5800          40 :         (m_eTF == GPKG_TF_PNG_16BIT) ? "integer" : "float", m_dfScale,
    5801             :         m_dfOffset, m_dfPrecision, osGridCellEncoding.c_str(),
    5802          41 :         osUom.empty() ? nullptr : osUom.c_str(), osFieldName.c_str(),
    5803             :         osQuantityDefinition.c_str());
    5804          40 :     m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary = pszSQL;
    5805          40 :     sqlite3_free(pszSQL);
    5806             : 
    5807             :     // Requirement 3 /gpkg-spatial-ref-sys-row
    5808             :     auto oResultTable = SQLQuery(
    5809          80 :         hDB, "SELECT * FROM gpkg_spatial_ref_sys WHERE srs_id = 4979 LIMIT 2");
    5810          40 :     bool bHasEPSG4979 = (oResultTable && oResultTable->RowCount() == 1);
    5811          40 :     if (!bHasEPSG4979)
    5812             :     {
    5813          41 :         if (!m_bHasDefinition12_063 &&
    5814           1 :             !ConvertGpkgSpatialRefSysToExtensionWkt2(/*bForceEpoch=*/false))
    5815             :         {
    5816           0 :             return false;
    5817             :         }
    5818             : 
    5819             :         // This is WKT 2...
    5820          40 :         const char *pszWKT =
    5821             :             "GEODCRS[\"WGS 84\","
    5822             :             "DATUM[\"World Geodetic System 1984\","
    5823             :             "  ELLIPSOID[\"WGS 84\",6378137,298.257223563,"
    5824             :             "LENGTHUNIT[\"metre\",1.0]]],"
    5825             :             "CS[ellipsoidal,3],"
    5826             :             "  AXIS[\"latitude\",north,ORDER[1],ANGLEUNIT[\"degree\","
    5827             :             "0.0174532925199433]],"
    5828             :             "  AXIS[\"longitude\",east,ORDER[2],ANGLEUNIT[\"degree\","
    5829             :             "0.0174532925199433]],"
    5830             :             "  AXIS[\"ellipsoidal height\",up,ORDER[3],"
    5831             :             "LENGTHUNIT[\"metre\",1.0]],"
    5832             :             "ID[\"EPSG\",4979]]";
    5833             : 
    5834          40 :         pszSQL = sqlite3_mprintf(
    5835             :             "INSERT INTO gpkg_spatial_ref_sys "
    5836             :             "(srs_name,srs_id,organization,organization_coordsys_id,"
    5837             :             "definition,definition_12_063) VALUES "
    5838             :             "('WGS 84 3D', 4979, 'EPSG', 4979, 'undefined', '%q')",
    5839             :             pszWKT);
    5840          40 :         osSQL += ";";
    5841          40 :         osSQL += pszSQL;
    5842          40 :         sqlite3_free(pszSQL);
    5843             :     }
    5844             : 
    5845          40 :     return SQLCommand(hDB, osSQL) == OGRERR_NONE;
    5846             : }
    5847             : 
    5848             : /************************************************************************/
    5849             : /*                    HasGriddedCoverageAncillaryTable()                */
    5850             : /************************************************************************/
    5851             : 
    5852          44 : bool GDALGeoPackageDataset::HasGriddedCoverageAncillaryTable()
    5853             : {
    5854             :     auto oResultTable = SQLQuery(
    5855             :         hDB, "SELECT * FROM sqlite_master WHERE type IN ('table', 'view') AND "
    5856          44 :              "name = 'gpkg_2d_gridded_coverage_ancillary'");
    5857          44 :     bool bHasTable = (oResultTable && oResultTable->RowCount() == 1);
    5858          88 :     return bHasTable;
    5859             : }
    5860             : 
    5861             : /************************************************************************/
    5862             : /*                      GetUnderlyingDataset()                          */
    5863             : /************************************************************************/
    5864             : 
    5865           3 : static GDALDataset *GetUnderlyingDataset(GDALDataset *poSrcDS)
    5866             : {
    5867           3 :     if (auto poVRTDS = dynamic_cast<VRTDataset *>(poSrcDS))
    5868             :     {
    5869           0 :         auto poTmpDS = poVRTDS->GetSingleSimpleSource();
    5870           0 :         if (poTmpDS)
    5871           0 :             return poTmpDS;
    5872             :     }
    5873             : 
    5874           3 :     return poSrcDS;
    5875             : }
    5876             : 
    5877             : /************************************************************************/
    5878             : /*                            CreateCopy()                              */
    5879             : /************************************************************************/
    5880             : 
    5881             : typedef struct
    5882             : {
    5883             :     const char *pszName;
    5884             :     GDALResampleAlg eResampleAlg;
    5885             : } WarpResamplingAlg;
    5886             : 
    5887             : static const WarpResamplingAlg asResamplingAlg[] = {
    5888             :     {"NEAREST", GRA_NearestNeighbour},
    5889             :     {"BILINEAR", GRA_Bilinear},
    5890             :     {"CUBIC", GRA_Cubic},
    5891             :     {"CUBICSPLINE", GRA_CubicSpline},
    5892             :     {"LANCZOS", GRA_Lanczos},
    5893             :     {"MODE", GRA_Mode},
    5894             :     {"AVERAGE", GRA_Average},
    5895             :     {"RMS", GRA_RMS},
    5896             : };
    5897             : 
    5898         162 : GDALDataset *GDALGeoPackageDataset::CreateCopy(const char *pszFilename,
    5899             :                                                GDALDataset *poSrcDS,
    5900             :                                                int bStrict, char **papszOptions,
    5901             :                                                GDALProgressFunc pfnProgress,
    5902             :                                                void *pProgressData)
    5903             : {
    5904         162 :     const int nBands = poSrcDS->GetRasterCount();
    5905         162 :     if (nBands == 0)
    5906             :     {
    5907           2 :         GDALDataset *poDS = nullptr;
    5908             :         GDALDriver *poThisDriver =
    5909           2 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5910           2 :         if (poThisDriver != nullptr)
    5911             :         {
    5912           2 :             poDS = poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS,
    5913             :                                                    bStrict, papszOptions,
    5914             :                                                    pfnProgress, pProgressData);
    5915             :         }
    5916           2 :         return poDS;
    5917             :     }
    5918             : 
    5919             :     const char *pszTilingScheme =
    5920         160 :         CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5921             : 
    5922         320 :     CPLStringList apszUpdatedOptions(CSLDuplicate(papszOptions));
    5923         160 :     if (CPLTestBool(
    5924         166 :             CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")) &&
    5925           6 :         CSLFetchNameValue(papszOptions, "RASTER_TABLE") == nullptr)
    5926             :     {
    5927             :         const std::string osBasename(CPLGetBasenameSafe(
    5928           6 :             GetUnderlyingDataset(poSrcDS)->GetDescription()));
    5929           3 :         apszUpdatedOptions.SetNameValue("RASTER_TABLE", osBasename.c_str());
    5930             :     }
    5931             : 
    5932         160 :     if (nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4)
    5933             :     {
    5934           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    5935             :                  "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or "
    5936             :                  "4 (RGBA) band dataset supported");
    5937           1 :         return nullptr;
    5938             :     }
    5939             : 
    5940         159 :     const char *pszUnitType = poSrcDS->GetRasterBand(1)->GetUnitType();
    5941         318 :     if (CSLFetchNameValue(papszOptions, "UOM") == nullptr && pszUnitType &&
    5942         159 :         !EQUAL(pszUnitType, ""))
    5943             :     {
    5944           1 :         apszUpdatedOptions.SetNameValue("UOM", pszUnitType);
    5945             :     }
    5946             : 
    5947         159 :     if (EQUAL(pszTilingScheme, "CUSTOM"))
    5948             :     {
    5949         135 :         if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5950             :         {
    5951           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    5952             :                      "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5953           0 :             return nullptr;
    5954             :         }
    5955             : 
    5956         135 :         GDALGeoPackageDataset *poDS = nullptr;
    5957             :         GDALDriver *poThisDriver =
    5958         135 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5959         135 :         if (poThisDriver != nullptr)
    5960             :         {
    5961         135 :             apszUpdatedOptions.SetNameValue("SKIP_HOLES", "YES");
    5962         135 :             poDS = cpl::down_cast<GDALGeoPackageDataset *>(
    5963             :                 poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS, bStrict,
    5964             :                                                 apszUpdatedOptions, pfnProgress,
    5965         135 :                                                 pProgressData));
    5966             : 
    5967         250 :             if (poDS != nullptr &&
    5968         135 :                 poSrcDS->GetRasterBand(1)->GetRasterDataType() == GDT_UInt8 &&
    5969             :                 nBands <= 3)
    5970             :             {
    5971          75 :                 poDS->m_nBandCountFromMetadata = nBands;
    5972          75 :                 poDS->m_bMetadataDirty = true;
    5973             :             }
    5974             :         }
    5975         135 :         if (poDS)
    5976         115 :             poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    5977         135 :         return poDS;
    5978             :     }
    5979             : 
    5980          48 :     const auto poTS = GetTilingScheme(pszTilingScheme);
    5981          24 :     if (!poTS)
    5982             :     {
    5983           2 :         return nullptr;
    5984             :     }
    5985          22 :     const int nEPSGCode = poTS->nEPSGCode;
    5986             : 
    5987          44 :     OGRSpatialReference oSRS;
    5988          22 :     if (oSRS.importFromEPSG(nEPSGCode) != OGRERR_NONE)
    5989             :     {
    5990           0 :         return nullptr;
    5991             :     }
    5992          22 :     char *pszWKT = nullptr;
    5993          22 :     oSRS.exportToWkt(&pszWKT);
    5994          22 :     char **papszTO = CSLSetNameValue(nullptr, "DST_SRS", pszWKT);
    5995             : 
    5996          22 :     void *hTransformArg = nullptr;
    5997             : 
    5998             :     // Hack to compensate for GDALSuggestedWarpOutput2() failure (or not
    5999             :     // ideal suggestion with PROJ 8) when reprojecting latitude = +/- 90 to
    6000             :     // EPSG:3857.
    6001          22 :     GDALGeoTransform srcGT;
    6002          22 :     std::unique_ptr<GDALDataset> poTmpDS;
    6003          22 :     bool bEPSG3857Adjust = false;
    6004           8 :     if (nEPSGCode == 3857 && poSrcDS->GetGeoTransform(srcGT) == CE_None &&
    6005          30 :         srcGT[2] == 0 && srcGT[4] == 0 && srcGT[5] < 0)
    6006             :     {
    6007           8 :         const auto poSrcSRS = poSrcDS->GetSpatialRef();
    6008           8 :         if (poSrcSRS && poSrcSRS->IsGeographic())
    6009             :         {
    6010           2 :             double maxLat = srcGT[3];
    6011           2 :             double minLat = srcGT[3] + poSrcDS->GetRasterYSize() * srcGT[5];
    6012             :             // Corresponds to the latitude of below MAX_GM
    6013           2 :             constexpr double MAX_LAT = 85.0511287798066;
    6014           2 :             bool bModified = false;
    6015           2 :             if (maxLat > MAX_LAT)
    6016             :             {
    6017           2 :                 maxLat = MAX_LAT;
    6018           2 :                 bModified = true;
    6019             :             }
    6020           2 :             if (minLat < -MAX_LAT)
    6021             :             {
    6022           2 :                 minLat = -MAX_LAT;
    6023           2 :                 bModified = true;
    6024             :             }
    6025           2 :             if (bModified)
    6026             :             {
    6027           4 :                 CPLStringList aosOptions;
    6028           2 :                 aosOptions.AddString("-of");
    6029           2 :                 aosOptions.AddString("VRT");
    6030           2 :                 aosOptions.AddString("-projwin");
    6031           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", srcGT[0]));
    6032           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", maxLat));
    6033             :                 aosOptions.AddString(CPLSPrintf(
    6034           2 :                     "%.17g", srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1]));
    6035           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", minLat));
    6036             :                 auto psOptions =
    6037           2 :                     GDALTranslateOptionsNew(aosOptions.List(), nullptr);
    6038           2 :                 poTmpDS.reset(GDALDataset::FromHandle(GDALTranslate(
    6039             :                     "", GDALDataset::ToHandle(poSrcDS), psOptions, nullptr)));
    6040           2 :                 GDALTranslateOptionsFree(psOptions);
    6041           2 :                 if (poTmpDS)
    6042             :                 {
    6043           2 :                     bEPSG3857Adjust = true;
    6044           2 :                     hTransformArg = GDALCreateGenImgProjTransformer2(
    6045           2 :                         GDALDataset::FromHandle(poTmpDS.get()), nullptr,
    6046             :                         papszTO);
    6047             :                 }
    6048             :             }
    6049             :         }
    6050             :     }
    6051          22 :     if (hTransformArg == nullptr)
    6052             :     {
    6053             :         hTransformArg =
    6054          20 :             GDALCreateGenImgProjTransformer2(poSrcDS, nullptr, papszTO);
    6055             :     }
    6056             : 
    6057          22 :     if (hTransformArg == nullptr)
    6058             :     {
    6059           1 :         CPLFree(pszWKT);
    6060           1 :         CSLDestroy(papszTO);
    6061           1 :         return nullptr;
    6062             :     }
    6063             : 
    6064          21 :     GDALTransformerInfo *psInfo =
    6065             :         static_cast<GDALTransformerInfo *>(hTransformArg);
    6066          21 :     GDALGeoTransform gt;
    6067             :     double adfExtent[4];
    6068             :     int nXSize, nYSize;
    6069             : 
    6070          21 :     if (GDALSuggestedWarpOutput2(poSrcDS, psInfo->pfnTransform, hTransformArg,
    6071             :                                  gt.data(), &nXSize, &nYSize, adfExtent,
    6072          21 :                                  0) != CE_None)
    6073             :     {
    6074           0 :         CPLFree(pszWKT);
    6075           0 :         CSLDestroy(papszTO);
    6076           0 :         GDALDestroyGenImgProjTransformer(hTransformArg);
    6077           0 :         return nullptr;
    6078             :     }
    6079             : 
    6080          21 :     GDALDestroyGenImgProjTransformer(hTransformArg);
    6081          21 :     hTransformArg = nullptr;
    6082          21 :     poTmpDS.reset();
    6083             : 
    6084          21 :     if (bEPSG3857Adjust)
    6085             :     {
    6086           2 :         constexpr double SPHERICAL_RADIUS = 6378137.0;
    6087           2 :         constexpr double MAX_GM =
    6088             :             SPHERICAL_RADIUS * M_PI;  // 20037508.342789244
    6089           2 :         double maxNorthing = gt[3];
    6090           2 :         double minNorthing = gt[3] + gt[5] * nYSize;
    6091           2 :         bool bChanged = false;
    6092           2 :         if (maxNorthing > MAX_GM)
    6093             :         {
    6094           2 :             bChanged = true;
    6095           2 :             maxNorthing = MAX_GM;
    6096             :         }
    6097           2 :         if (minNorthing < -MAX_GM)
    6098             :         {
    6099           2 :             bChanged = true;
    6100           2 :             minNorthing = -MAX_GM;
    6101             :         }
    6102           2 :         if (bChanged)
    6103             :         {
    6104           2 :             gt[3] = maxNorthing;
    6105           2 :             nYSize = int((maxNorthing - minNorthing) / (-gt[5]) + 0.5);
    6106           2 :             adfExtent[1] = maxNorthing + nYSize * gt[5];
    6107           2 :             adfExtent[3] = maxNorthing;
    6108             :         }
    6109             :     }
    6110             : 
    6111          21 :     double dfComputedRes = gt[1];
    6112          21 :     double dfPrevRes = 0.0;
    6113          21 :     double dfRes = 0.0;
    6114          21 :     int nZoomLevel = 0;  // Used after for.
    6115          21 :     const char *pszZoomLevel = CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    6116          21 :     if (pszZoomLevel)
    6117             :     {
    6118           2 :         nZoomLevel = atoi(pszZoomLevel);
    6119             : 
    6120           2 :         int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    6121           2 :         while ((1 << nMaxZoomLevelForThisTM) >
    6122           4 :                    INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6123           2 :                (1 << nMaxZoomLevelForThisTM) >
    6124           2 :                    INT_MAX / poTS->nTileYCountZoomLevel0)
    6125             :         {
    6126           0 :             --nMaxZoomLevelForThisTM;
    6127             :         }
    6128             : 
    6129           2 :         if (nZoomLevel < 0 || nZoomLevel > nMaxZoomLevelForThisTM)
    6130             :         {
    6131           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6132             :                      "ZOOM_LEVEL = %s is invalid. It should be in [0,%d] range",
    6133             :                      pszZoomLevel, nMaxZoomLevelForThisTM);
    6134           1 :             CPLFree(pszWKT);
    6135           1 :             CSLDestroy(papszTO);
    6136           1 :             return nullptr;
    6137             :         }
    6138             :     }
    6139             :     else
    6140             :     {
    6141         171 :         for (; nZoomLevel < MAX_ZOOM_LEVEL; nZoomLevel++)
    6142             :         {
    6143         171 :             dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6144         171 :             if (dfComputedRes > dfRes ||
    6145         152 :                 fabs(dfComputedRes - dfRes) / dfRes <= 1e-8)
    6146             :                 break;
    6147         152 :             dfPrevRes = dfRes;
    6148             :         }
    6149          38 :         if (nZoomLevel == MAX_ZOOM_LEVEL ||
    6150          38 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6151          19 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileYCountZoomLevel0)
    6152             :         {
    6153           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6154             :                      "Could not find an appropriate zoom level");
    6155           0 :             CPLFree(pszWKT);
    6156           0 :             CSLDestroy(papszTO);
    6157           0 :             return nullptr;
    6158             :         }
    6159             : 
    6160          19 :         if (nZoomLevel > 0 && fabs(dfComputedRes - dfRes) / dfRes > 1e-8)
    6161             :         {
    6162          17 :             const char *pszZoomLevelStrategy = CSLFetchNameValueDef(
    6163             :                 papszOptions, "ZOOM_LEVEL_STRATEGY", "AUTO");
    6164          17 :             if (EQUAL(pszZoomLevelStrategy, "LOWER"))
    6165             :             {
    6166           1 :                 nZoomLevel--;
    6167             :             }
    6168          16 :             else if (EQUAL(pszZoomLevelStrategy, "UPPER"))
    6169             :             {
    6170             :                 /* do nothing */
    6171             :             }
    6172             :             else
    6173             :             {
    6174          15 :                 if (dfPrevRes / dfComputedRes < dfComputedRes / dfRes)
    6175          13 :                     nZoomLevel--;
    6176             :             }
    6177             :         }
    6178             :     }
    6179             : 
    6180          20 :     dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6181             : 
    6182          20 :     double dfMinX = adfExtent[0];
    6183          20 :     double dfMinY = adfExtent[1];
    6184          20 :     double dfMaxX = adfExtent[2];
    6185          20 :     double dfMaxY = adfExtent[3];
    6186             : 
    6187          20 :     nXSize = static_cast<int>(0.5 + (dfMaxX - dfMinX) / dfRes);
    6188          20 :     nYSize = static_cast<int>(0.5 + (dfMaxY - dfMinY) / dfRes);
    6189          20 :     gt[1] = dfRes;
    6190          20 :     gt[5] = -dfRes;
    6191             : 
    6192          20 :     const GDALDataType eDT = poSrcDS->GetRasterBand(1)->GetRasterDataType();
    6193          20 :     int nTargetBands = nBands;
    6194             :     /* For grey level or RGB, if there's reprojection involved, add an alpha */
    6195             :     /* channel */
    6196          37 :     if (eDT == GDT_UInt8 &&
    6197          13 :         ((nBands == 1 &&
    6198          17 :           poSrcDS->GetRasterBand(1)->GetColorTable() == nullptr) ||
    6199             :          nBands == 3))
    6200             :     {
    6201          30 :         OGRSpatialReference oSrcSRS;
    6202          15 :         oSrcSRS.SetFromUserInput(poSrcDS->GetProjectionRef());
    6203          15 :         oSrcSRS.AutoIdentifyEPSG();
    6204          30 :         if (oSrcSRS.GetAuthorityCode(nullptr) == nullptr ||
    6205          15 :             atoi(oSrcSRS.GetAuthorityCode(nullptr)) != nEPSGCode)
    6206             :         {
    6207          13 :             nTargetBands++;
    6208             :         }
    6209             :     }
    6210             : 
    6211          20 :     GDALResampleAlg eResampleAlg = GRA_Bilinear;
    6212          20 :     const char *pszResampling = CSLFetchNameValue(papszOptions, "RESAMPLING");
    6213          20 :     if (pszResampling)
    6214             :     {
    6215           6 :         for (size_t iAlg = 0;
    6216           6 :              iAlg < sizeof(asResamplingAlg) / sizeof(asResamplingAlg[0]);
    6217             :              iAlg++)
    6218             :         {
    6219           6 :             if (EQUAL(pszResampling, asResamplingAlg[iAlg].pszName))
    6220             :             {
    6221           3 :                 eResampleAlg = asResamplingAlg[iAlg].eResampleAlg;
    6222           3 :                 break;
    6223             :             }
    6224             :         }
    6225             :     }
    6226             : 
    6227          16 :     if (nBands == 1 && poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    6228          36 :         eResampleAlg != GRA_NearestNeighbour && eResampleAlg != GRA_Mode)
    6229             :     {
    6230           0 :         CPLError(
    6231             :             CE_Warning, CPLE_AppDefined,
    6232             :             "Input dataset has a color table, which will likely lead to "
    6233             :             "bad results when using a resampling method other than "
    6234             :             "nearest neighbour or mode. Converting the dataset to 24/32 bit "
    6235             :             "(e.g. with gdal_translate -expand rgb/rgba) is advised.");
    6236             :     }
    6237             : 
    6238          40 :     auto poDS = std::make_unique<GDALGeoPackageDataset>();
    6239          20 :     if (!(poDS->Create(pszFilename, nXSize, nYSize, nTargetBands, eDT,
    6240             :                        apszUpdatedOptions)))
    6241             :     {
    6242           1 :         CPLFree(pszWKT);
    6243           1 :         CSLDestroy(papszTO);
    6244           1 :         return nullptr;
    6245             :     }
    6246             : 
    6247             :     // Assign nodata values before the SetGeoTransform call.
    6248             :     // SetGeoTransform will trigger creation of the overview datasets for each
    6249             :     // zoom level and at that point the nodata value needs to be known.
    6250          19 :     int bHasNoData = FALSE;
    6251             :     double dfNoDataValue =
    6252          19 :         poSrcDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    6253          19 :     if (eDT != GDT_UInt8 && bHasNoData)
    6254             :     {
    6255           3 :         poDS->GetRasterBand(1)->SetNoDataValue(dfNoDataValue);
    6256             :     }
    6257             : 
    6258          19 :     poDS->SetGeoTransform(gt);
    6259          19 :     poDS->SetProjection(pszWKT);
    6260          19 :     CPLFree(pszWKT);
    6261          19 :     pszWKT = nullptr;
    6262          24 :     if (nTargetBands == 1 && nBands == 1 &&
    6263           5 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
    6264             :     {
    6265           2 :         poDS->GetRasterBand(1)->SetColorTable(
    6266           1 :             poSrcDS->GetRasterBand(1)->GetColorTable());
    6267             :     }
    6268             : 
    6269             :     hTransformArg =
    6270          19 :         GDALCreateGenImgProjTransformer2(poSrcDS, poDS.get(), papszTO);
    6271          19 :     CSLDestroy(papszTO);
    6272          19 :     if (hTransformArg == nullptr)
    6273             :     {
    6274           0 :         return nullptr;
    6275             :     }
    6276             : 
    6277          19 :     poDS->SetMetadata(poSrcDS->GetMetadata());
    6278             : 
    6279             :     /* -------------------------------------------------------------------- */
    6280             :     /*      Warp the transformer with a linear approximator                 */
    6281             :     /* -------------------------------------------------------------------- */
    6282          19 :     hTransformArg = GDALCreateApproxTransformer(GDALGenImgProjTransform,
    6283             :                                                 hTransformArg, 0.125);
    6284          19 :     GDALApproxTransformerOwnsSubtransformer(hTransformArg, TRUE);
    6285             : 
    6286             :     /* -------------------------------------------------------------------- */
    6287             :     /*      Setup warp options.                                             */
    6288             :     /* -------------------------------------------------------------------- */
    6289          19 :     GDALWarpOptions *psWO = GDALCreateWarpOptions();
    6290             : 
    6291          19 :     psWO->papszWarpOptions = CSLSetNameValue(nullptr, "OPTIMIZE_SIZE", "YES");
    6292          19 :     psWO->papszWarpOptions =
    6293          19 :         CSLSetNameValue(psWO->papszWarpOptions, "SAMPLE_GRID", "YES");
    6294          19 :     if (bHasNoData)
    6295             :     {
    6296           3 :         if (dfNoDataValue == 0.0)
    6297             :         {
    6298             :             // Do not initialize in the case where nodata != 0, since we
    6299             :             // want the GeoPackage driver to return empty tiles at the nodata
    6300             :             // value instead of 0 as GDAL core would
    6301           0 :             psWO->papszWarpOptions =
    6302           0 :                 CSLSetNameValue(psWO->papszWarpOptions, "INIT_DEST", "0");
    6303             :         }
    6304             : 
    6305           3 :         psWO->padfSrcNoDataReal =
    6306           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6307           3 :         psWO->padfSrcNoDataReal[0] = dfNoDataValue;
    6308             : 
    6309           3 :         psWO->padfDstNoDataReal =
    6310           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6311           3 :         psWO->padfDstNoDataReal[0] = dfNoDataValue;
    6312             :     }
    6313          19 :     psWO->eWorkingDataType = eDT;
    6314          19 :     psWO->eResampleAlg = eResampleAlg;
    6315             : 
    6316          19 :     psWO->hSrcDS = poSrcDS;
    6317          19 :     psWO->hDstDS = poDS.get();
    6318             : 
    6319          19 :     psWO->pfnTransformer = GDALApproxTransform;
    6320          19 :     psWO->pTransformerArg = hTransformArg;
    6321             : 
    6322          19 :     psWO->pfnProgress = pfnProgress;
    6323          19 :     psWO->pProgressArg = pProgressData;
    6324             : 
    6325             :     /* -------------------------------------------------------------------- */
    6326             :     /*      Setup band mapping.                                             */
    6327             :     /* -------------------------------------------------------------------- */
    6328             : 
    6329          19 :     if (nBands == 2 || nBands == 4)
    6330           1 :         psWO->nBandCount = nBands - 1;
    6331             :     else
    6332          18 :         psWO->nBandCount = nBands;
    6333             : 
    6334          19 :     psWO->panSrcBands =
    6335          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6336          19 :     psWO->panDstBands =
    6337          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6338             : 
    6339          46 :     for (int i = 0; i < psWO->nBandCount; i++)
    6340             :     {
    6341          27 :         psWO->panSrcBands[i] = i + 1;
    6342          27 :         psWO->panDstBands[i] = i + 1;
    6343             :     }
    6344             : 
    6345          19 :     if (nBands == 2 || nBands == 4)
    6346             :     {
    6347           1 :         psWO->nSrcAlphaBand = nBands;
    6348             :     }
    6349          19 :     if (nTargetBands == 2 || nTargetBands == 4)
    6350             :     {
    6351          13 :         psWO->nDstAlphaBand = nTargetBands;
    6352             :     }
    6353             : 
    6354             :     /* -------------------------------------------------------------------- */
    6355             :     /*      Initialize and execute the warp.                                */
    6356             :     /* -------------------------------------------------------------------- */
    6357          38 :     GDALWarpOperation oWO;
    6358             : 
    6359          19 :     CPLErr eErr = oWO.Initialize(psWO);
    6360          19 :     if (eErr == CE_None)
    6361             :     {
    6362             :         /*if( bMulti )
    6363             :             eErr = oWO.ChunkAndWarpMulti( 0, 0, nXSize, nYSize );
    6364             :         else*/
    6365          19 :         eErr = oWO.ChunkAndWarpImage(0, 0, nXSize, nYSize);
    6366             :     }
    6367          19 :     if (eErr != CE_None)
    6368             :     {
    6369           0 :         poDS.reset();
    6370             :     }
    6371             : 
    6372          19 :     GDALDestroyTransformer(hTransformArg);
    6373          19 :     GDALDestroyWarpOptions(psWO);
    6374             : 
    6375          19 :     if (poDS)
    6376          19 :         poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    6377             : 
    6378          19 :     return poDS.release();
    6379             : }
    6380             : 
    6381             : /************************************************************************/
    6382             : /*                        ParseCompressionOptions()                     */
    6383             : /************************************************************************/
    6384             : 
    6385         459 : void GDALGeoPackageDataset::ParseCompressionOptions(char **papszOptions)
    6386             : {
    6387         459 :     const char *pszZLevel = CSLFetchNameValue(papszOptions, "ZLEVEL");
    6388         459 :     if (pszZLevel)
    6389           0 :         m_nZLevel = atoi(pszZLevel);
    6390             : 
    6391         459 :     const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
    6392         459 :     if (pszQuality)
    6393           0 :         m_nQuality = atoi(pszQuality);
    6394             : 
    6395         459 :     const char *pszDither = CSLFetchNameValue(papszOptions, "DITHER");
    6396         459 :     if (pszDither)
    6397           0 :         m_bDither = CPLTestBool(pszDither);
    6398         459 : }
    6399             : 
    6400             : /************************************************************************/
    6401             : /*                          RegisterWebPExtension()                     */
    6402             : /************************************************************************/
    6403             : 
    6404          11 : bool GDALGeoPackageDataset::RegisterWebPExtension()
    6405             : {
    6406          11 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6407           0 :         return false;
    6408             : 
    6409          11 :     char *pszSQL = sqlite3_mprintf(
    6410             :         "INSERT INTO gpkg_extensions "
    6411             :         "(table_name, column_name, extension_name, definition, scope) "
    6412             :         "VALUES "
    6413             :         "('%q', 'tile_data', 'gpkg_webp', "
    6414             :         "'http://www.geopackage.org/spec120/#extension_tiles_webp', "
    6415             :         "'read-write')",
    6416             :         m_osRasterTable.c_str());
    6417          11 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6418          11 :     sqlite3_free(pszSQL);
    6419             : 
    6420          11 :     return OGRERR_NONE == eErr;
    6421             : }
    6422             : 
    6423             : /************************************************************************/
    6424             : /*                       RegisterZoomOtherExtension()                   */
    6425             : /************************************************************************/
    6426             : 
    6427           1 : bool GDALGeoPackageDataset::RegisterZoomOtherExtension()
    6428             : {
    6429           1 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6430           0 :         return false;
    6431             : 
    6432           1 :     char *pszSQL = sqlite3_mprintf(
    6433             :         "INSERT INTO gpkg_extensions "
    6434             :         "(table_name, column_name, extension_name, definition, scope) "
    6435             :         "VALUES "
    6436             :         "('%q', 'tile_data', 'gpkg_zoom_other', "
    6437             :         "'http://www.geopackage.org/spec120/#extension_zoom_other_intervals', "
    6438             :         "'read-write')",
    6439             :         m_osRasterTable.c_str());
    6440           1 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6441           1 :     sqlite3_free(pszSQL);
    6442           1 :     return OGRERR_NONE == eErr;
    6443             : }
    6444             : 
    6445             : /************************************************************************/
    6446             : /*                              GetLayer()                              */
    6447             : /************************************************************************/
    6448             : 
    6449       16013 : const OGRLayer *GDALGeoPackageDataset::GetLayer(int iLayer) const
    6450             : 
    6451             : {
    6452       16013 :     if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
    6453           7 :         return nullptr;
    6454             :     else
    6455       16006 :         return m_apoLayers[iLayer].get();
    6456             : }
    6457             : 
    6458             : /************************************************************************/
    6459             : /*                           LaunderName()                              */
    6460             : /************************************************************************/
    6461             : 
    6462             : /** Launder identifiers (table, column names) according to guidance at
    6463             :  * https://www.geopackage.org/guidance/getting-started.html:
    6464             :  * "For maximum interoperability, start your database identifiers (table names,
    6465             :  * column names, etc.) with a lowercase character and only use lowercase
    6466             :  * characters, numbers 0-9, and underscores (_)."
    6467             :  */
    6468             : 
    6469             : /* static */
    6470           5 : std::string GDALGeoPackageDataset::LaunderName(const std::string &osStr)
    6471             : {
    6472           5 :     char *pszASCII = CPLUTF8ForceToASCII(osStr.c_str(), '_');
    6473          10 :     const std::string osStrASCII(pszASCII);
    6474           5 :     CPLFree(pszASCII);
    6475             : 
    6476          10 :     std::string osRet;
    6477           5 :     osRet.reserve(osStrASCII.size());
    6478             : 
    6479          29 :     for (size_t i = 0; i < osStrASCII.size(); ++i)
    6480             :     {
    6481          24 :         if (osRet.empty())
    6482             :         {
    6483           5 :             if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6484             :             {
    6485           2 :                 osRet += (osStrASCII[i] - 'A' + 'a');
    6486             :             }
    6487           3 :             else if (osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z')
    6488             :             {
    6489           2 :                 osRet += osStrASCII[i];
    6490             :             }
    6491             :             else
    6492             :             {
    6493           1 :                 continue;
    6494             :             }
    6495             :         }
    6496          19 :         else if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6497             :         {
    6498          11 :             osRet += (osStrASCII[i] - 'A' + 'a');
    6499             :         }
    6500           9 :         else if ((osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z') ||
    6501          14 :                  (osStrASCII[i] >= '0' && osStrASCII[i] <= '9') ||
    6502           5 :                  osStrASCII[i] == '_')
    6503             :         {
    6504           7 :             osRet += osStrASCII[i];
    6505             :         }
    6506             :         else
    6507             :         {
    6508           1 :             osRet += '_';
    6509             :         }
    6510             :     }
    6511             : 
    6512           5 :     if (osRet.empty() && !osStrASCII.empty())
    6513           2 :         return LaunderName(std::string("x").append(osStrASCII));
    6514             : 
    6515           4 :     if (osRet != osStr)
    6516             :     {
    6517           3 :         CPLDebug("PG", "LaunderName('%s') -> '%s'", osStr.c_str(),
    6518             :                  osRet.c_str());
    6519             :     }
    6520             : 
    6521           4 :     return osRet;
    6522             : }
    6523             : 
    6524             : /************************************************************************/
    6525             : /*                          ICreateLayer()                              */
    6526             : /************************************************************************/
    6527             : 
    6528             : OGRLayer *
    6529         871 : GDALGeoPackageDataset::ICreateLayer(const char *pszLayerName,
    6530             :                                     const OGRGeomFieldDefn *poSrcGeomFieldDefn,
    6531             :                                     CSLConstList papszOptions)
    6532             : {
    6533             :     /* -------------------------------------------------------------------- */
    6534             :     /*      Verify we are in update mode.                                   */
    6535             :     /* -------------------------------------------------------------------- */
    6536         871 :     if (!GetUpdate())
    6537             :     {
    6538           0 :         CPLError(CE_Failure, CPLE_NoWriteAccess,
    6539             :                  "Data source %s opened read-only.\n"
    6540             :                  "New layer %s cannot be created.\n",
    6541             :                  m_pszFilename, pszLayerName);
    6542             : 
    6543           0 :         return nullptr;
    6544             :     }
    6545             : 
    6546             :     const bool bLaunder =
    6547         871 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "LAUNDER", "NO"));
    6548             :     const std::string osTableName(bLaunder ? LaunderName(pszLayerName)
    6549        2613 :                                            : std::string(pszLayerName));
    6550             : 
    6551             :     const auto eGType =
    6552         871 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
    6553             :     const auto poSpatialRef =
    6554         871 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
    6555             : 
    6556         871 :     if (!m_bHasGPKGGeometryColumns)
    6557             :     {
    6558           1 :         if (SQLCommand(hDB, pszCREATE_GPKG_GEOMETRY_COLUMNS) != OGRERR_NONE)
    6559             :         {
    6560           0 :             return nullptr;
    6561             :         }
    6562           1 :         m_bHasGPKGGeometryColumns = true;
    6563             :     }
    6564             : 
    6565             :     // Check identifier unicity
    6566         871 :     const char *pszIdentifier = CSLFetchNameValue(papszOptions, "IDENTIFIER");
    6567         871 :     if (pszIdentifier != nullptr && pszIdentifier[0] == '\0')
    6568           0 :         pszIdentifier = nullptr;
    6569         871 :     if (pszIdentifier != nullptr)
    6570             :     {
    6571          13 :         for (auto &poLayer : m_apoLayers)
    6572             :         {
    6573             :             const char *pszOtherIdentifier =
    6574           9 :                 poLayer->GetMetadataItem("IDENTIFIER");
    6575           9 :             if (pszOtherIdentifier == nullptr)
    6576           6 :                 pszOtherIdentifier = poLayer->GetName();
    6577          18 :             if (pszOtherIdentifier != nullptr &&
    6578          12 :                 EQUAL(pszOtherIdentifier, pszIdentifier) &&
    6579           3 :                 !EQUAL(poLayer->GetName(), osTableName.c_str()))
    6580             :             {
    6581           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6582             :                          "Identifier %s is already used by table %s",
    6583             :                          pszIdentifier, poLayer->GetName());
    6584           2 :                 return nullptr;
    6585             :             }
    6586             :         }
    6587             : 
    6588             :         // In case there would be table in gpkg_contents not listed as a
    6589             :         // vector layer
    6590           4 :         char *pszSQL = sqlite3_mprintf(
    6591             :             "SELECT table_name FROM gpkg_contents WHERE identifier = '%q' "
    6592             :             "LIMIT 2",
    6593             :             pszIdentifier);
    6594           4 :         auto oResult = SQLQuery(hDB, pszSQL);
    6595           4 :         sqlite3_free(pszSQL);
    6596           8 :         if (oResult && oResult->RowCount() > 0 &&
    6597           9 :             oResult->GetValue(0, 0) != nullptr &&
    6598           1 :             !EQUAL(oResult->GetValue(0, 0), osTableName.c_str()))
    6599             :         {
    6600           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6601             :                      "Identifier %s is already used by table %s", pszIdentifier,
    6602             :                      oResult->GetValue(0, 0));
    6603           1 :             return nullptr;
    6604             :         }
    6605             :     }
    6606             : 
    6607             :     /* Read GEOMETRY_NAME option */
    6608             :     const char *pszGeomColumnName =
    6609         868 :         CSLFetchNameValue(papszOptions, "GEOMETRY_NAME");
    6610         868 :     if (pszGeomColumnName == nullptr) /* deprecated name */
    6611         782 :         pszGeomColumnName = CSLFetchNameValue(papszOptions, "GEOMETRY_COLUMN");
    6612         868 :     if (pszGeomColumnName == nullptr && poSrcGeomFieldDefn)
    6613             :     {
    6614         704 :         pszGeomColumnName = poSrcGeomFieldDefn->GetNameRef();
    6615         704 :         if (pszGeomColumnName && pszGeomColumnName[0] == 0)
    6616         700 :             pszGeomColumnName = nullptr;
    6617             :     }
    6618         868 :     if (pszGeomColumnName == nullptr)
    6619         778 :         pszGeomColumnName = "geom";
    6620             :     const bool bGeomNullable =
    6621         868 :         CPLFetchBool(papszOptions, "GEOMETRY_NULLABLE", true);
    6622             : 
    6623             :     /* Read FID option */
    6624         868 :     const char *pszFIDColumnName = CSLFetchNameValue(papszOptions, "FID");
    6625         868 :     if (pszFIDColumnName == nullptr)
    6626         789 :         pszFIDColumnName = "fid";
    6627             : 
    6628         868 :     if (CPLTestBool(CPLGetConfigOption("GPKG_NAME_CHECK", "YES")))
    6629             :     {
    6630         868 :         if (strspn(pszFIDColumnName, "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") > 0)
    6631             :         {
    6632           2 :             CPLError(CE_Failure, CPLE_AppDefined,
    6633             :                      "The primary key (%s) name may not contain special "
    6634             :                      "characters or spaces",
    6635             :                      pszFIDColumnName);
    6636           2 :             return nullptr;
    6637             :         }
    6638             : 
    6639             :         /* Avoiding gpkg prefixes is not an official requirement, but seems wise
    6640             :          */
    6641         866 :         if (STARTS_WITH(osTableName.c_str(), "gpkg"))
    6642             :         {
    6643           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6644             :                      "The layer name may not begin with 'gpkg' as it is a "
    6645             :                      "reserved geopackage prefix");
    6646           0 :             return nullptr;
    6647             :         }
    6648             : 
    6649             :         /* Preemptively try and avoid sqlite3 syntax errors due to  */
    6650             :         /* illegal characters. */
    6651         866 :         if (strspn(osTableName.c_str(), "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") >
    6652             :             0)
    6653             :         {
    6654           0 :             CPLError(
    6655             :                 CE_Failure, CPLE_AppDefined,
    6656             :                 "The layer name may not contain special characters or spaces");
    6657           0 :             return nullptr;
    6658             :         }
    6659             :     }
    6660             : 
    6661             :     /* Check for any existing layers that already use this name */
    6662        1074 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6663             :          iLayer++)
    6664             :     {
    6665         209 :         if (EQUAL(osTableName.c_str(), m_apoLayers[iLayer]->GetName()))
    6666             :         {
    6667             :             const char *pszOverwrite =
    6668           2 :                 CSLFetchNameValue(papszOptions, "OVERWRITE");
    6669           2 :             if (pszOverwrite != nullptr && CPLTestBool(pszOverwrite))
    6670             :             {
    6671           1 :                 DeleteLayer(iLayer);
    6672             :             }
    6673             :             else
    6674             :             {
    6675           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6676             :                          "Layer %s already exists, CreateLayer failed.\n"
    6677             :                          "Use the layer creation option OVERWRITE=YES to "
    6678             :                          "replace it.",
    6679             :                          osTableName.c_str());
    6680           1 :                 return nullptr;
    6681             :             }
    6682             :         }
    6683             :     }
    6684             : 
    6685         865 :     if (m_apoLayers.size() == 1)
    6686             :     {
    6687             :         // Async RTree building doesn't play well with multiple layer:
    6688             :         // SQLite3 locks being hold for a long time, random failed commits,
    6689             :         // etc.
    6690          82 :         m_apoLayers[0]->FinishOrDisableThreadedRTree();
    6691             :     }
    6692             : 
    6693             :     /* Create a blank layer. */
    6694             :     auto poLayer =
    6695        1730 :         std::make_unique<OGRGeoPackageTableLayer>(this, osTableName.c_str());
    6696             : 
    6697         865 :     OGRSpatialReference *poSRS = nullptr;
    6698         865 :     if (poSpatialRef)
    6699             :     {
    6700         256 :         poSRS = poSpatialRef->Clone();
    6701         256 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    6702             :     }
    6703        1731 :     poLayer->SetCreationParameters(
    6704             :         eGType,
    6705         866 :         bLaunder ? LaunderName(pszGeomColumnName).c_str() : pszGeomColumnName,
    6706             :         bGeomNullable, poSRS, CSLFetchNameValue(papszOptions, "SRID"),
    6707        1730 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetCoordinatePrecision()
    6708             :                            : OGRGeomCoordinatePrecision(),
    6709         865 :         CPLTestBool(
    6710             :             CSLFetchNameValueDef(papszOptions, "DISCARD_COORD_LSB", "NO")),
    6711         865 :         CPLTestBool(CSLFetchNameValueDef(
    6712             :             papszOptions, "UNDO_DISCARD_COORD_LSB_ON_READING", "NO")),
    6713         866 :         bLaunder ? LaunderName(pszFIDColumnName).c_str() : pszFIDColumnName,
    6714             :         pszIdentifier, CSLFetchNameValue(papszOptions, "DESCRIPTION"));
    6715         865 :     if (poSRS)
    6716             :     {
    6717         256 :         poSRS->Release();
    6718             :     }
    6719             : 
    6720         865 :     poLayer->SetLaunder(bLaunder);
    6721             : 
    6722             :     /* Should we create a spatial index ? */
    6723         865 :     const char *pszSI = CSLFetchNameValue(papszOptions, "SPATIAL_INDEX");
    6724         865 :     int bCreateSpatialIndex = (pszSI == nullptr || CPLTestBool(pszSI));
    6725         865 :     if (eGType != wkbNone && bCreateSpatialIndex)
    6726             :     {
    6727         765 :         poLayer->SetDeferredSpatialIndexCreation(true);
    6728             :     }
    6729             : 
    6730         865 :     poLayer->SetPrecisionFlag(CPLFetchBool(papszOptions, "PRECISION", true));
    6731         865 :     poLayer->SetTruncateFieldsFlag(
    6732         865 :         CPLFetchBool(papszOptions, "TRUNCATE_FIELDS", false));
    6733         865 :     if (eGType == wkbNone)
    6734             :     {
    6735          78 :         const char *pszASpatialVariant = CSLFetchNameValueDef(
    6736             :             papszOptions, "ASPATIAL_VARIANT",
    6737          78 :             m_bNonSpatialTablesNonRegisteredInGpkgContentsFound
    6738             :                 ? "NOT_REGISTERED"
    6739             :                 : "GPKG_ATTRIBUTES");
    6740          78 :         GPKGASpatialVariant eASpatialVariant = GPKG_ATTRIBUTES;
    6741          78 :         if (EQUAL(pszASpatialVariant, "GPKG_ATTRIBUTES"))
    6742          66 :             eASpatialVariant = GPKG_ATTRIBUTES;
    6743          12 :         else if (EQUAL(pszASpatialVariant, "OGR_ASPATIAL"))
    6744             :         {
    6745           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6746             :                      "ASPATIAL_VARIANT=OGR_ASPATIAL is no longer supported");
    6747           0 :             return nullptr;
    6748             :         }
    6749          12 :         else if (EQUAL(pszASpatialVariant, "NOT_REGISTERED"))
    6750          12 :             eASpatialVariant = NOT_REGISTERED;
    6751             :         else
    6752             :         {
    6753           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6754             :                      "Unsupported value for ASPATIAL_VARIANT: %s",
    6755             :                      pszASpatialVariant);
    6756           0 :             return nullptr;
    6757             :         }
    6758          78 :         poLayer->SetASpatialVariant(eASpatialVariant);
    6759             :     }
    6760             : 
    6761             :     const char *pszDateTimePrecision =
    6762         865 :         CSLFetchNameValueDef(papszOptions, "DATETIME_PRECISION", "AUTO");
    6763         865 :     if (EQUAL(pszDateTimePrecision, "MILLISECOND"))
    6764             :     {
    6765           2 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6766             :     }
    6767         863 :     else if (EQUAL(pszDateTimePrecision, "SECOND"))
    6768             :     {
    6769           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6770           0 :             CPLError(
    6771             :                 CE_Warning, CPLE_AppDefined,
    6772             :                 "DATETIME_PRECISION=SECOND is only valid since GeoPackage 1.4");
    6773           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::SECOND);
    6774             :     }
    6775         862 :     else if (EQUAL(pszDateTimePrecision, "MINUTE"))
    6776             :     {
    6777           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6778           0 :             CPLError(
    6779             :                 CE_Warning, CPLE_AppDefined,
    6780             :                 "DATETIME_PRECISION=MINUTE is only valid since GeoPackage 1.4");
    6781           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MINUTE);
    6782             :     }
    6783         861 :     else if (EQUAL(pszDateTimePrecision, "AUTO"))
    6784             :     {
    6785         860 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6786          13 :             poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6787             :     }
    6788             :     else
    6789             :     {
    6790           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    6791             :                  "Unsupported value for DATETIME_PRECISION: %s",
    6792             :                  pszDateTimePrecision);
    6793           1 :         return nullptr;
    6794             :     }
    6795             : 
    6796             :     // If there was an ogr_empty_table table, we can remove it
    6797             :     // But do it at dataset closing, otherwise locking performance issues
    6798             :     // can arise (probably when transactions are used).
    6799         864 :     m_bRemoveOGREmptyTable = true;
    6800             : 
    6801         864 :     m_apoLayers.emplace_back(std::move(poLayer));
    6802         864 :     return m_apoLayers.back().get();
    6803             : }
    6804             : 
    6805             : /************************************************************************/
    6806             : /*                          FindLayerIndex()                            */
    6807             : /************************************************************************/
    6808             : 
    6809          27 : int GDALGeoPackageDataset::FindLayerIndex(const char *pszLayerName)
    6810             : 
    6811             : {
    6812          42 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6813             :          iLayer++)
    6814             :     {
    6815          28 :         if (EQUAL(pszLayerName, m_apoLayers[iLayer]->GetName()))
    6816          13 :             return iLayer;
    6817             :     }
    6818          14 :     return -1;
    6819             : }
    6820             : 
    6821             : /************************************************************************/
    6822             : /*                       DeleteLayerCommon()                            */
    6823             : /************************************************************************/
    6824             : 
    6825          42 : OGRErr GDALGeoPackageDataset::DeleteLayerCommon(const char *pszLayerName)
    6826             : {
    6827             :     // Temporary remove foreign key checks
    6828             :     const GPKGTemporaryForeignKeyCheckDisabler
    6829          42 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6830             : 
    6831          42 :     char *pszSQL = sqlite3_mprintf(
    6832             :         "DELETE FROM gpkg_contents WHERE lower(table_name) = lower('%q')",
    6833             :         pszLayerName);
    6834          42 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    6835          42 :     sqlite3_free(pszSQL);
    6836             : 
    6837          42 :     if (eErr == OGRERR_NONE && HasExtensionsTable())
    6838             :     {
    6839          40 :         pszSQL = sqlite3_mprintf(
    6840             :             "DELETE FROM gpkg_extensions WHERE lower(table_name) = lower('%q')",
    6841             :             pszLayerName);
    6842          40 :         eErr = SQLCommand(hDB, pszSQL);
    6843          40 :         sqlite3_free(pszSQL);
    6844             :     }
    6845             : 
    6846          42 :     if (eErr == OGRERR_NONE && HasMetadataTables())
    6847             :     {
    6848             :         // Delete from gpkg_metadata metadata records that are only referenced
    6849             :         // by the table we are about to drop
    6850          12 :         pszSQL = sqlite3_mprintf(
    6851             :             "DELETE FROM gpkg_metadata WHERE id IN ("
    6852             :             "SELECT DISTINCT md_file_id FROM "
    6853             :             "gpkg_metadata_reference WHERE "
    6854             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6855             :             "AND id NOT IN ("
    6856             :             "SELECT DISTINCT md_file_id FROM gpkg_metadata_reference WHERE "
    6857             :             "md_file_id IN (SELECT DISTINCT md_file_id FROM "
    6858             :             "gpkg_metadata_reference WHERE "
    6859             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6860             :             "AND lower(table_name) <> lower('%q'))",
    6861             :             pszLayerName, pszLayerName, pszLayerName);
    6862          12 :         eErr = SQLCommand(hDB, pszSQL);
    6863          12 :         sqlite3_free(pszSQL);
    6864             : 
    6865          12 :         if (eErr == OGRERR_NONE)
    6866             :         {
    6867             :             pszSQL =
    6868          12 :                 sqlite3_mprintf("DELETE FROM gpkg_metadata_reference WHERE "
    6869             :                                 "lower(table_name) = lower('%q')",
    6870             :                                 pszLayerName);
    6871          12 :             eErr = SQLCommand(hDB, pszSQL);
    6872          12 :             sqlite3_free(pszSQL);
    6873             :         }
    6874             :     }
    6875             : 
    6876          42 :     if (eErr == OGRERR_NONE && HasGpkgextRelationsTable())
    6877             :     {
    6878             :         // Remove reference to potential corresponding mapping table in
    6879             :         // gpkg_extensions
    6880           4 :         pszSQL = sqlite3_mprintf(
    6881             :             "DELETE FROM gpkg_extensions WHERE "
    6882             :             "extension_name IN ('related_tables', "
    6883             :             "'gpkg_related_tables') AND lower(table_name) = "
    6884             :             "(SELECT lower(mapping_table_name) FROM gpkgext_relations WHERE "
    6885             :             "lower(base_table_name) = lower('%q') OR "
    6886             :             "lower(related_table_name) = lower('%q') OR "
    6887             :             "lower(mapping_table_name) = lower('%q'))",
    6888             :             pszLayerName, pszLayerName, pszLayerName);
    6889           4 :         eErr = SQLCommand(hDB, pszSQL);
    6890           4 :         sqlite3_free(pszSQL);
    6891             : 
    6892           4 :         if (eErr == OGRERR_NONE)
    6893             :         {
    6894             :             // Remove reference to potential corresponding mapping table in
    6895             :             // gpkgext_relations
    6896             :             pszSQL =
    6897           4 :                 sqlite3_mprintf("DELETE FROM gpkgext_relations WHERE "
    6898             :                                 "lower(base_table_name) = lower('%q') OR "
    6899             :                                 "lower(related_table_name) = lower('%q') OR "
    6900             :                                 "lower(mapping_table_name) = lower('%q')",
    6901             :                                 pszLayerName, pszLayerName, pszLayerName);
    6902           4 :             eErr = SQLCommand(hDB, pszSQL);
    6903           4 :             sqlite3_free(pszSQL);
    6904             :         }
    6905             : 
    6906           4 :         if (eErr == OGRERR_NONE && HasExtensionsTable())
    6907             :         {
    6908             :             // If there is no longer any mapping table, then completely
    6909             :             // remove any reference to the extension in gpkg_extensions
    6910             :             // as mandated per the related table specification.
    6911             :             OGRErr err;
    6912           4 :             if (SQLGetInteger(hDB,
    6913             :                               "SELECT COUNT(*) FROM gpkg_extensions WHERE "
    6914             :                               "extension_name IN ('related_tables', "
    6915             :                               "'gpkg_related_tables') AND "
    6916             :                               "lower(table_name) != 'gpkgext_relations'",
    6917           4 :                               &err) == 0)
    6918             :             {
    6919           2 :                 eErr = SQLCommand(hDB, "DELETE FROM gpkg_extensions WHERE "
    6920             :                                        "extension_name IN ('related_tables', "
    6921             :                                        "'gpkg_related_tables')");
    6922             :             }
    6923             : 
    6924           4 :             ClearCachedRelationships();
    6925             :         }
    6926             :     }
    6927             : 
    6928          42 :     if (eErr == OGRERR_NONE)
    6929             :     {
    6930          42 :         pszSQL = sqlite3_mprintf("DROP TABLE \"%w\"", pszLayerName);
    6931          42 :         eErr = SQLCommand(hDB, pszSQL);
    6932          42 :         sqlite3_free(pszSQL);
    6933             :     }
    6934             : 
    6935             :     // Check foreign key integrity
    6936          42 :     if (eErr == OGRERR_NONE)
    6937             :     {
    6938          42 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    6939             :     }
    6940             : 
    6941          84 :     return eErr;
    6942             : }
    6943             : 
    6944             : /************************************************************************/
    6945             : /*                            DeleteLayer()                             */
    6946             : /************************************************************************/
    6947             : 
    6948          39 : OGRErr GDALGeoPackageDataset::DeleteLayer(int iLayer)
    6949             : {
    6950          77 :     if (!GetUpdate() || iLayer < 0 ||
    6951          38 :         iLayer >= static_cast<int>(m_apoLayers.size()))
    6952           2 :         return OGRERR_FAILURE;
    6953             : 
    6954          37 :     m_apoLayers[iLayer]->ResetReading();
    6955          37 :     m_apoLayers[iLayer]->SyncToDisk();
    6956             : 
    6957          74 :     CPLString osLayerName = m_apoLayers[iLayer]->GetName();
    6958             : 
    6959          37 :     CPLDebug("GPKG", "DeleteLayer(%s)", osLayerName.c_str());
    6960             : 
    6961             :     // Temporary remove foreign key checks
    6962             :     const GPKGTemporaryForeignKeyCheckDisabler
    6963          37 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6964             : 
    6965          37 :     OGRErr eErr = SoftStartTransaction();
    6966             : 
    6967          37 :     if (eErr == OGRERR_NONE)
    6968             :     {
    6969          37 :         if (m_apoLayers[iLayer]->HasSpatialIndex())
    6970          34 :             m_apoLayers[iLayer]->DropSpatialIndex();
    6971             : 
    6972             :         char *pszSQL =
    6973          37 :             sqlite3_mprintf("DELETE FROM gpkg_geometry_columns WHERE "
    6974             :                             "lower(table_name) = lower('%q')",
    6975             :                             osLayerName.c_str());
    6976          37 :         eErr = SQLCommand(hDB, pszSQL);
    6977          37 :         sqlite3_free(pszSQL);
    6978             :     }
    6979             : 
    6980          37 :     if (eErr == OGRERR_NONE && HasDataColumnsTable())
    6981             :     {
    6982           1 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_data_columns WHERE "
    6983             :                                        "lower(table_name) = lower('%q')",
    6984             :                                        osLayerName.c_str());
    6985           1 :         eErr = SQLCommand(hDB, pszSQL);
    6986           1 :         sqlite3_free(pszSQL);
    6987             :     }
    6988             : 
    6989             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    6990          37 :     if (eErr == OGRERR_NONE && m_bHasGPKGOGRContents)
    6991             :     {
    6992          37 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_ogr_contents WHERE "
    6993             :                                        "lower(table_name) = lower('%q')",
    6994             :                                        osLayerName.c_str());
    6995          37 :         eErr = SQLCommand(hDB, pszSQL);
    6996          37 :         sqlite3_free(pszSQL);
    6997             :     }
    6998             : #endif
    6999             : 
    7000          37 :     if (eErr == OGRERR_NONE)
    7001             :     {
    7002          37 :         eErr = DeleteLayerCommon(osLayerName.c_str());
    7003             :     }
    7004             : 
    7005          37 :     if (eErr == OGRERR_NONE)
    7006             :     {
    7007          37 :         eErr = SoftCommitTransaction();
    7008          37 :         if (eErr == OGRERR_NONE)
    7009             :         {
    7010             :             /* Delete the layer object */
    7011          37 :             m_apoLayers.erase(m_apoLayers.begin() + iLayer);
    7012             :         }
    7013             :     }
    7014             :     else
    7015             :     {
    7016           0 :         SoftRollbackTransaction();
    7017             :     }
    7018             : 
    7019          37 :     return eErr;
    7020             : }
    7021             : 
    7022             : /************************************************************************/
    7023             : /*                       DeleteRasterLayer()                            */
    7024             : /************************************************************************/
    7025             : 
    7026           2 : OGRErr GDALGeoPackageDataset::DeleteRasterLayer(const char *pszLayerName)
    7027             : {
    7028             :     // Temporary remove foreign key checks
    7029             :     const GPKGTemporaryForeignKeyCheckDisabler
    7030           2 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7031             : 
    7032           2 :     OGRErr eErr = SoftStartTransaction();
    7033             : 
    7034           2 :     if (eErr == OGRERR_NONE)
    7035             :     {
    7036           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix WHERE "
    7037             :                                        "lower(table_name) = lower('%q')",
    7038             :                                        pszLayerName);
    7039           2 :         eErr = SQLCommand(hDB, pszSQL);
    7040           2 :         sqlite3_free(pszSQL);
    7041             :     }
    7042             : 
    7043           2 :     if (eErr == OGRERR_NONE)
    7044             :     {
    7045           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix_set WHERE "
    7046             :                                        "lower(table_name) = lower('%q')",
    7047             :                                        pszLayerName);
    7048           2 :         eErr = SQLCommand(hDB, pszSQL);
    7049           2 :         sqlite3_free(pszSQL);
    7050             :     }
    7051             : 
    7052           2 :     if (eErr == OGRERR_NONE && HasGriddedCoverageAncillaryTable())
    7053             :     {
    7054             :         char *pszSQL =
    7055           1 :             sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_coverage_ancillary "
    7056             :                             "WHERE lower(tile_matrix_set_name) = lower('%q')",
    7057             :                             pszLayerName);
    7058           1 :         eErr = SQLCommand(hDB, pszSQL);
    7059           1 :         sqlite3_free(pszSQL);
    7060             : 
    7061           1 :         if (eErr == OGRERR_NONE)
    7062             :         {
    7063             :             pszSQL =
    7064           1 :                 sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_tile_ancillary "
    7065             :                                 "WHERE lower(tpudt_name) = lower('%q')",
    7066             :                                 pszLayerName);
    7067           1 :             eErr = SQLCommand(hDB, pszSQL);
    7068           1 :             sqlite3_free(pszSQL);
    7069             :         }
    7070             :     }
    7071             : 
    7072           2 :     if (eErr == OGRERR_NONE)
    7073             :     {
    7074           2 :         eErr = DeleteLayerCommon(pszLayerName);
    7075             :     }
    7076             : 
    7077           2 :     if (eErr == OGRERR_NONE)
    7078             :     {
    7079           2 :         eErr = SoftCommitTransaction();
    7080             :     }
    7081             :     else
    7082             :     {
    7083           0 :         SoftRollbackTransaction();
    7084             :     }
    7085             : 
    7086           4 :     return eErr;
    7087             : }
    7088             : 
    7089             : /************************************************************************/
    7090             : /*                    DeleteVectorOrRasterLayer()                       */
    7091             : /************************************************************************/
    7092             : 
    7093          13 : bool GDALGeoPackageDataset::DeleteVectorOrRasterLayer(const char *pszLayerName)
    7094             : {
    7095             : 
    7096          13 :     int idx = FindLayerIndex(pszLayerName);
    7097          13 :     if (idx >= 0)
    7098             :     {
    7099           5 :         DeleteLayer(idx);
    7100           5 :         return true;
    7101             :     }
    7102             : 
    7103             :     char *pszSQL =
    7104           8 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7105             :                         "lower(table_name) = lower('%q') "
    7106             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7107             :                         pszLayerName);
    7108           8 :     bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7109           8 :     sqlite3_free(pszSQL);
    7110           8 :     if (bIsRasterTable)
    7111             :     {
    7112           2 :         DeleteRasterLayer(pszLayerName);
    7113           2 :         return true;
    7114             :     }
    7115           6 :     return false;
    7116             : }
    7117             : 
    7118           7 : bool GDALGeoPackageDataset::RenameVectorOrRasterLayer(
    7119             :     const char *pszLayerName, const char *pszNewLayerName)
    7120             : {
    7121           7 :     int idx = FindLayerIndex(pszLayerName);
    7122           7 :     if (idx >= 0)
    7123             :     {
    7124           4 :         m_apoLayers[idx]->Rename(pszNewLayerName);
    7125           4 :         return true;
    7126             :     }
    7127             : 
    7128             :     char *pszSQL =
    7129           3 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7130             :                         "lower(table_name) = lower('%q') "
    7131             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7132             :                         pszLayerName);
    7133           3 :     const bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7134           3 :     sqlite3_free(pszSQL);
    7135             : 
    7136           3 :     if (bIsRasterTable)
    7137             :     {
    7138           2 :         return RenameRasterLayer(pszLayerName, pszNewLayerName);
    7139             :     }
    7140             : 
    7141           1 :     return false;
    7142             : }
    7143             : 
    7144           2 : bool GDALGeoPackageDataset::RenameRasterLayer(const char *pszLayerName,
    7145             :                                               const char *pszNewLayerName)
    7146             : {
    7147           4 :     std::string osSQL;
    7148             : 
    7149           2 :     char *pszSQL = sqlite3_mprintf(
    7150             :         "SELECT 1 FROM sqlite_master WHERE lower(name) = lower('%q') "
    7151             :         "AND type IN ('table', 'view')",
    7152             :         pszNewLayerName);
    7153           2 :     const bool bAlreadyExists = SQLGetInteger(GetDB(), pszSQL, nullptr) == 1;
    7154           2 :     sqlite3_free(pszSQL);
    7155           2 :     if (bAlreadyExists)
    7156             :     {
    7157           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Table %s already exists",
    7158             :                  pszNewLayerName);
    7159           0 :         return false;
    7160             :     }
    7161             : 
    7162             :     // Temporary remove foreign key checks
    7163             :     const GPKGTemporaryForeignKeyCheckDisabler
    7164           4 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7165             : 
    7166           2 :     if (SoftStartTransaction() != OGRERR_NONE)
    7167             :     {
    7168           0 :         return false;
    7169             :     }
    7170             : 
    7171           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET table_name = '%q' WHERE "
    7172             :                              "lower(table_name) = lower('%q');",
    7173             :                              pszNewLayerName, pszLayerName);
    7174           2 :     osSQL = pszSQL;
    7175           2 :     sqlite3_free(pszSQL);
    7176             : 
    7177           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' WHERE "
    7178             :                              "lower(identifier) = lower('%q');",
    7179             :                              pszNewLayerName, pszLayerName);
    7180           2 :     osSQL += pszSQL;
    7181           2 :     sqlite3_free(pszSQL);
    7182             : 
    7183             :     pszSQL =
    7184           2 :         sqlite3_mprintf("UPDATE gpkg_tile_matrix SET table_name = '%q' WHERE "
    7185             :                         "lower(table_name) = lower('%q');",
    7186             :                         pszNewLayerName, pszLayerName);
    7187           2 :     osSQL += pszSQL;
    7188           2 :     sqlite3_free(pszSQL);
    7189             : 
    7190           2 :     pszSQL = sqlite3_mprintf(
    7191             :         "UPDATE gpkg_tile_matrix_set SET table_name = '%q' WHERE "
    7192             :         "lower(table_name) = lower('%q');",
    7193             :         pszNewLayerName, pszLayerName);
    7194           2 :     osSQL += pszSQL;
    7195           2 :     sqlite3_free(pszSQL);
    7196             : 
    7197           2 :     if (HasGriddedCoverageAncillaryTable())
    7198             :     {
    7199           1 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_2d_gridded_coverage_ancillary "
    7200             :                                  "SET tile_matrix_set_name = '%q' WHERE "
    7201             :                                  "lower(tile_matrix_set_name) = lower('%q');",
    7202             :                                  pszNewLayerName, pszLayerName);
    7203           1 :         osSQL += pszSQL;
    7204           1 :         sqlite3_free(pszSQL);
    7205             : 
    7206           1 :         pszSQL = sqlite3_mprintf(
    7207             :             "UPDATE gpkg_2d_gridded_tile_ancillary SET tpudt_name = '%q' WHERE "
    7208             :             "lower(tpudt_name) = lower('%q');",
    7209             :             pszNewLayerName, pszLayerName);
    7210           1 :         osSQL += pszSQL;
    7211           1 :         sqlite3_free(pszSQL);
    7212             :     }
    7213             : 
    7214           2 :     if (HasExtensionsTable())
    7215             :     {
    7216           2 :         pszSQL = sqlite3_mprintf(
    7217             :             "UPDATE gpkg_extensions SET table_name = '%q' WHERE "
    7218             :             "lower(table_name) = lower('%q');",
    7219             :             pszNewLayerName, pszLayerName);
    7220           2 :         osSQL += pszSQL;
    7221           2 :         sqlite3_free(pszSQL);
    7222             :     }
    7223             : 
    7224           2 :     if (HasMetadataTables())
    7225             :     {
    7226           1 :         pszSQL = sqlite3_mprintf(
    7227             :             "UPDATE gpkg_metadata_reference SET table_name = '%q' WHERE "
    7228             :             "lower(table_name) = lower('%q');",
    7229             :             pszNewLayerName, pszLayerName);
    7230           1 :         osSQL += pszSQL;
    7231           1 :         sqlite3_free(pszSQL);
    7232             :     }
    7233             : 
    7234           2 :     if (HasDataColumnsTable())
    7235             :     {
    7236           0 :         pszSQL = sqlite3_mprintf(
    7237             :             "UPDATE gpkg_data_columns SET table_name = '%q' WHERE "
    7238             :             "lower(table_name) = lower('%q');",
    7239             :             pszNewLayerName, pszLayerName);
    7240           0 :         osSQL += pszSQL;
    7241           0 :         sqlite3_free(pszSQL);
    7242             :     }
    7243             : 
    7244           2 :     if (HasQGISLayerStyles())
    7245             :     {
    7246             :         // Update QGIS styles
    7247             :         pszSQL =
    7248           0 :             sqlite3_mprintf("UPDATE layer_styles SET f_table_name = '%q' WHERE "
    7249             :                             "lower(f_table_name) = lower('%q');",
    7250             :                             pszNewLayerName, pszLayerName);
    7251           0 :         osSQL += pszSQL;
    7252           0 :         sqlite3_free(pszSQL);
    7253             :     }
    7254             : 
    7255             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7256           2 :     if (m_bHasGPKGOGRContents)
    7257             :     {
    7258           2 :         pszSQL = sqlite3_mprintf(
    7259             :             "UPDATE gpkg_ogr_contents SET table_name = '%q' WHERE "
    7260             :             "lower(table_name) = lower('%q');",
    7261             :             pszNewLayerName, pszLayerName);
    7262           2 :         osSQL += pszSQL;
    7263           2 :         sqlite3_free(pszSQL);
    7264             :     }
    7265             : #endif
    7266             : 
    7267           2 :     if (HasGpkgextRelationsTable())
    7268             :     {
    7269           0 :         pszSQL = sqlite3_mprintf(
    7270             :             "UPDATE gpkgext_relations SET base_table_name = '%q' WHERE "
    7271             :             "lower(base_table_name) = lower('%q');",
    7272             :             pszNewLayerName, pszLayerName);
    7273           0 :         osSQL += pszSQL;
    7274           0 :         sqlite3_free(pszSQL);
    7275             : 
    7276           0 :         pszSQL = sqlite3_mprintf(
    7277             :             "UPDATE gpkgext_relations SET related_table_name = '%q' WHERE "
    7278             :             "lower(related_table_name) = lower('%q');",
    7279             :             pszNewLayerName, pszLayerName);
    7280           0 :         osSQL += pszSQL;
    7281           0 :         sqlite3_free(pszSQL);
    7282             : 
    7283           0 :         pszSQL = sqlite3_mprintf(
    7284             :             "UPDATE gpkgext_relations SET mapping_table_name = '%q' WHERE "
    7285             :             "lower(mapping_table_name) = lower('%q');",
    7286             :             pszNewLayerName, pszLayerName);
    7287           0 :         osSQL += pszSQL;
    7288           0 :         sqlite3_free(pszSQL);
    7289             :     }
    7290             : 
    7291             :     // Drop all triggers for the layer
    7292           2 :     pszSQL = sqlite3_mprintf("SELECT name FROM sqlite_master WHERE type = "
    7293             :                              "'trigger' AND tbl_name = '%q'",
    7294             :                              pszLayerName);
    7295           2 :     auto oTriggerResult = SQLQuery(GetDB(), pszSQL);
    7296           2 :     sqlite3_free(pszSQL);
    7297           2 :     if (oTriggerResult)
    7298             :     {
    7299          14 :         for (int i = 0; i < oTriggerResult->RowCount(); i++)
    7300             :         {
    7301          12 :             const char *pszTriggerName = oTriggerResult->GetValue(0, i);
    7302          12 :             pszSQL = sqlite3_mprintf("DROP TRIGGER IF EXISTS \"%w\";",
    7303             :                                      pszTriggerName);
    7304          12 :             osSQL += pszSQL;
    7305          12 :             sqlite3_free(pszSQL);
    7306             :         }
    7307             :     }
    7308             : 
    7309           2 :     pszSQL = sqlite3_mprintf("ALTER TABLE \"%w\" RENAME TO \"%w\";",
    7310             :                              pszLayerName, pszNewLayerName);
    7311           2 :     osSQL += pszSQL;
    7312           2 :     sqlite3_free(pszSQL);
    7313             : 
    7314             :     // Recreate all zoom/tile triggers
    7315           2 :     if (oTriggerResult)
    7316             :     {
    7317           2 :         osSQL += CreateRasterTriggersSQL(pszNewLayerName);
    7318             :     }
    7319             : 
    7320           2 :     OGRErr eErr = SQLCommand(GetDB(), osSQL.c_str());
    7321             : 
    7322             :     // Check foreign key integrity
    7323           2 :     if (eErr == OGRERR_NONE)
    7324             :     {
    7325           2 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    7326             :     }
    7327             : 
    7328           2 :     if (eErr == OGRERR_NONE)
    7329             :     {
    7330           2 :         eErr = SoftCommitTransaction();
    7331             :     }
    7332             :     else
    7333             :     {
    7334           0 :         SoftRollbackTransaction();
    7335             :     }
    7336             : 
    7337           2 :     return eErr == OGRERR_NONE;
    7338             : }
    7339             : 
    7340             : /************************************************************************/
    7341             : /*                       TestCapability()                               */
    7342             : /************************************************************************/
    7343             : 
    7344         525 : int GDALGeoPackageDataset::TestCapability(const char *pszCap) const
    7345             : {
    7346         525 :     if (EQUAL(pszCap, ODsCCreateLayer) || EQUAL(pszCap, ODsCDeleteLayer) ||
    7347         341 :         EQUAL(pszCap, "RenameLayer"))
    7348             :     {
    7349         184 :         return GetUpdate();
    7350             :     }
    7351         341 :     else if (EQUAL(pszCap, ODsCCurveGeometries))
    7352          12 :         return TRUE;
    7353         329 :     else if (EQUAL(pszCap, ODsCMeasuredGeometries))
    7354           8 :         return TRUE;
    7355         321 :     else if (EQUAL(pszCap, ODsCZGeometries))
    7356           8 :         return TRUE;
    7357         313 :     else if (EQUAL(pszCap, ODsCRandomLayerWrite) ||
    7358         313 :              EQUAL(pszCap, GDsCAddRelationship) ||
    7359         313 :              EQUAL(pszCap, GDsCDeleteRelationship) ||
    7360         313 :              EQUAL(pszCap, GDsCUpdateRelationship) ||
    7361         313 :              EQUAL(pszCap, ODsCAddFieldDomain) ||
    7362         311 :              EQUAL(pszCap, ODsCUpdateFieldDomain) ||
    7363         309 :              EQUAL(pszCap, ODsCDeleteFieldDomain))
    7364             :     {
    7365           6 :         return GetUpdate();
    7366             :     }
    7367             : 
    7368         307 :     return OGRSQLiteBaseDataSource::TestCapability(pszCap);
    7369             : }
    7370             : 
    7371             : /************************************************************************/
    7372             : /*                       ResetReadingAllLayers()                        */
    7373             : /************************************************************************/
    7374             : 
    7375         205 : void GDALGeoPackageDataset::ResetReadingAllLayers()
    7376             : {
    7377         415 :     for (auto &poLayer : m_apoLayers)
    7378             :     {
    7379         210 :         poLayer->ResetReading();
    7380             :     }
    7381         205 : }
    7382             : 
    7383             : /************************************************************************/
    7384             : /*                             ExecuteSQL()                             */
    7385             : /************************************************************************/
    7386             : 
    7387             : static const char *const apszFuncsWithSideEffects[] = {
    7388             :     "CreateSpatialIndex",
    7389             :     "DisableSpatialIndex",
    7390             :     "HasSpatialIndex",
    7391             :     "RegisterGeometryExtension",
    7392             : };
    7393             : 
    7394        5704 : OGRLayer *GDALGeoPackageDataset::ExecuteSQL(const char *pszSQLCommand,
    7395             :                                             OGRGeometry *poSpatialFilter,
    7396             :                                             const char *pszDialect)
    7397             : 
    7398             : {
    7399        5704 :     m_bHasReadMetadataFromStorage = false;
    7400             : 
    7401        5704 :     FlushMetadata();
    7402             : 
    7403        5722 :     while (*pszSQLCommand != '\0' &&
    7404        5722 :            isspace(static_cast<unsigned char>(*pszSQLCommand)))
    7405          18 :         pszSQLCommand++;
    7406             : 
    7407       11408 :     CPLString osSQLCommand(pszSQLCommand);
    7408        5704 :     if (!osSQLCommand.empty() && osSQLCommand.back() == ';')
    7409          48 :         osSQLCommand.pop_back();
    7410             : 
    7411       11407 :     if (osSQLCommand.ifind("AsGPB(ST_") != std::string::npos ||
    7412        5703 :         osSQLCommand.ifind("AsGPB( ST_") != std::string::npos)
    7413             :     {
    7414           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    7415             :                  "Use of AsGPB(ST_xxx(...)) found in \"%s\". Since GDAL 3.13, "
    7416             :                  "ST_xxx() functions return a GeoPackage geometry when used "
    7417             :                  "with a GeoPackage connection, and the use of AsGPB() is no "
    7418             :                  "longer needed. It is here automatically removed",
    7419             :                  osSQLCommand.c_str());
    7420           1 :         osSQLCommand.replaceAll("AsGPB(ST_", "(ST_");
    7421           1 :         osSQLCommand.replaceAll("AsGPB( ST_", "(ST_");
    7422             :     }
    7423             : 
    7424        5704 :     if (pszDialect == nullptr || !EQUAL(pszDialect, "DEBUG"))
    7425             :     {
    7426             :         // Some SQL commands will influence the feature count behind our
    7427             :         // back, so disable it in that case.
    7428             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7429             :         const bool bInsertOrDelete =
    7430        5635 :             osSQLCommand.ifind("insert into ") != std::string::npos ||
    7431        2514 :             osSQLCommand.ifind("insert or replace into ") !=
    7432        8149 :                 std::string::npos ||
    7433        2477 :             osSQLCommand.ifind("delete from ") != std::string::npos;
    7434             :         const bool bRollback =
    7435        5635 :             osSQLCommand.ifind("rollback ") != std::string::npos;
    7436             : #endif
    7437             : 
    7438        7518 :         for (auto &poLayer : m_apoLayers)
    7439             :         {
    7440        1883 :             if (poLayer->SyncToDisk() != OGRERR_NONE)
    7441           0 :                 return nullptr;
    7442             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7443        2087 :             if (bRollback ||
    7444         204 :                 (bInsertOrDelete &&
    7445         204 :                  osSQLCommand.ifind(poLayer->GetName()) != std::string::npos))
    7446             :             {
    7447         202 :                 poLayer->DisableFeatureCount();
    7448             :             }
    7449             : #endif
    7450             :         }
    7451             :     }
    7452             : 
    7453        5704 :     if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 0") ||
    7454        5703 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=0") ||
    7455        5703 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =0") ||
    7456        5703 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 0"))
    7457             :     {
    7458           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, false);
    7459             :     }
    7460        5703 :     else if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 1") ||
    7461        5702 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=1") ||
    7462        5702 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =1") ||
    7463        5702 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 1"))
    7464             :     {
    7465           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, true);
    7466             :     }
    7467             : 
    7468             :     /* -------------------------------------------------------------------- */
    7469             :     /*      DEBUG "SELECT nolock" command.                                  */
    7470             :     /* -------------------------------------------------------------------- */
    7471        5773 :     if (pszDialect != nullptr && EQUAL(pszDialect, "DEBUG") &&
    7472          69 :         EQUAL(osSQLCommand, "SELECT nolock"))
    7473             :     {
    7474           3 :         return new OGRSQLiteSingleFeatureLayer(osSQLCommand, m_bNoLock ? 1 : 0);
    7475             :     }
    7476             : 
    7477             :     /* -------------------------------------------------------------------- */
    7478             :     /*      Special case DELLAYER: command.                                 */
    7479             :     /* -------------------------------------------------------------------- */
    7480        5701 :     if (STARTS_WITH_CI(osSQLCommand, "DELLAYER:"))
    7481             :     {
    7482           4 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DELLAYER:");
    7483             : 
    7484           4 :         while (*pszLayerName == ' ')
    7485           0 :             pszLayerName++;
    7486             : 
    7487           4 :         if (!DeleteVectorOrRasterLayer(pszLayerName))
    7488             :         {
    7489           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7490             :                      pszLayerName);
    7491             :         }
    7492           4 :         return nullptr;
    7493             :     }
    7494             : 
    7495             :     /* -------------------------------------------------------------------- */
    7496             :     /*      Special case RECOMPUTE EXTENT ON command.                       */
    7497             :     /* -------------------------------------------------------------------- */
    7498        5697 :     if (STARTS_WITH_CI(osSQLCommand, "RECOMPUTE EXTENT ON "))
    7499             :     {
    7500             :         const char *pszLayerName =
    7501           4 :             osSQLCommand.c_str() + strlen("RECOMPUTE EXTENT ON ");
    7502             : 
    7503           4 :         while (*pszLayerName == ' ')
    7504           0 :             pszLayerName++;
    7505             : 
    7506           4 :         int idx = FindLayerIndex(pszLayerName);
    7507           4 :         if (idx >= 0)
    7508             :         {
    7509           4 :             m_apoLayers[idx]->RecomputeExtent();
    7510             :         }
    7511             :         else
    7512           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7513             :                      pszLayerName);
    7514           4 :         return nullptr;
    7515             :     }
    7516             : 
    7517             :     /* -------------------------------------------------------------------- */
    7518             :     /*      Intercept DROP TABLE                                            */
    7519             :     /* -------------------------------------------------------------------- */
    7520        5693 :     if (STARTS_WITH_CI(osSQLCommand, "DROP TABLE "))
    7521             :     {
    7522           9 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DROP TABLE ");
    7523             : 
    7524           9 :         while (*pszLayerName == ' ')
    7525           0 :             pszLayerName++;
    7526             : 
    7527           9 :         if (DeleteVectorOrRasterLayer(SQLUnescape(pszLayerName)))
    7528           4 :             return nullptr;
    7529             :     }
    7530             : 
    7531             :     /* -------------------------------------------------------------------- */
    7532             :     /*      Intercept ALTER TABLE src_table RENAME TO dst_table             */
    7533             :     /*      and       ALTER TABLE table RENAME COLUMN src_name TO dst_name  */
    7534             :     /*      and       ALTER TABLE table DROP COLUMN col_name                */
    7535             :     /*                                                                      */
    7536             :     /*      We do this because SQLite mechanisms can't deal with updating   */
    7537             :     /*      literal values in gpkg_ tables that refer to table and column   */
    7538             :     /*      names.                                                          */
    7539             :     /* -------------------------------------------------------------------- */
    7540        5689 :     if (STARTS_WITH_CI(osSQLCommand, "ALTER TABLE "))
    7541             :     {
    7542           9 :         char **papszTokens = SQLTokenize(osSQLCommand);
    7543             :         /* ALTER TABLE src_table RENAME TO dst_table */
    7544          16 :         if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "RENAME") &&
    7545           7 :             EQUAL(papszTokens[4], "TO"))
    7546             :         {
    7547           7 :             const char *pszSrcTableName = papszTokens[2];
    7548           7 :             const char *pszDstTableName = papszTokens[5];
    7549           7 :             if (RenameVectorOrRasterLayer(SQLUnescape(pszSrcTableName),
    7550          14 :                                           SQLUnescape(pszDstTableName)))
    7551             :             {
    7552           6 :                 CSLDestroy(papszTokens);
    7553           6 :                 return nullptr;
    7554             :             }
    7555             :         }
    7556             :         /* ALTER TABLE table RENAME COLUMN src_name TO dst_name */
    7557           2 :         else if (CSLCount(papszTokens) == 8 &&
    7558           1 :                  EQUAL(papszTokens[3], "RENAME") &&
    7559           3 :                  EQUAL(papszTokens[4], "COLUMN") && EQUAL(papszTokens[6], "TO"))
    7560             :         {
    7561           1 :             const char *pszTableName = papszTokens[2];
    7562           1 :             const char *pszSrcColumn = papszTokens[5];
    7563           1 :             const char *pszDstColumn = papszTokens[7];
    7564             :             OGRGeoPackageTableLayer *poLayer =
    7565           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7566           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7567           1 :             if (poLayer)
    7568             :             {
    7569           2 :                 int nSrcFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7570           2 :                     SQLUnescape(pszSrcColumn));
    7571           1 :                 if (nSrcFieldIdx >= 0)
    7572             :                 {
    7573             :                     // OFTString or any type will do as we just alter the name
    7574             :                     // so it will be ignored.
    7575           1 :                     OGRFieldDefn oFieldDefn(SQLUnescape(pszDstColumn),
    7576           1 :                                             OFTString);
    7577           1 :                     poLayer->AlterFieldDefn(nSrcFieldIdx, &oFieldDefn,
    7578             :                                             ALTER_NAME_FLAG);
    7579           1 :                     CSLDestroy(papszTokens);
    7580           1 :                     return nullptr;
    7581             :                 }
    7582             :             }
    7583             :         }
    7584             :         /* ALTER TABLE table DROP COLUMN col_name */
    7585           2 :         else if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "DROP") &&
    7586           1 :                  EQUAL(papszTokens[4], "COLUMN"))
    7587             :         {
    7588           1 :             const char *pszTableName = papszTokens[2];
    7589           1 :             const char *pszColumnName = papszTokens[5];
    7590             :             OGRGeoPackageTableLayer *poLayer =
    7591           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7592           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7593           1 :             if (poLayer)
    7594             :             {
    7595           2 :                 int nFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7596           2 :                     SQLUnescape(pszColumnName));
    7597           1 :                 if (nFieldIdx >= 0)
    7598             :                 {
    7599           1 :                     poLayer->DeleteField(nFieldIdx);
    7600           1 :                     CSLDestroy(papszTokens);
    7601           1 :                     return nullptr;
    7602             :                 }
    7603             :             }
    7604             :         }
    7605           1 :         CSLDestroy(papszTokens);
    7606             :     }
    7607             : 
    7608        5681 :     if (ProcessTransactionSQL(osSQLCommand))
    7609             :     {
    7610         253 :         return nullptr;
    7611             :     }
    7612             : 
    7613        5428 :     if (EQUAL(osSQLCommand, "VACUUM"))
    7614             :     {
    7615          13 :         ResetReadingAllLayers();
    7616             :     }
    7617        5415 :     else if (STARTS_WITH_CI(osSQLCommand, "DELETE FROM "))
    7618             :     {
    7619             :         // Optimize truncation of a table, especially if it has a spatial
    7620             :         // index.
    7621          23 :         const CPLStringList aosTokens(SQLTokenize(osSQLCommand));
    7622          23 :         if (aosTokens.size() == 3)
    7623             :         {
    7624          16 :             const char *pszTableName = aosTokens[2];
    7625             :             OGRGeoPackageTableLayer *poLayer =
    7626           8 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7627          24 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7628          16 :             if (poLayer)
    7629             :             {
    7630           8 :                 poLayer->Truncate();
    7631           8 :                 return nullptr;
    7632             :             }
    7633             :         }
    7634             :     }
    7635        5392 :     else if (pszDialect != nullptr && EQUAL(pszDialect, "INDIRECT_SQLITE"))
    7636           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter, "SQLITE");
    7637        5391 :     else if (pszDialect != nullptr && !EQUAL(pszDialect, "") &&
    7638          67 :              !EQUAL(pszDialect, "NATIVE") && !EQUAL(pszDialect, "SQLITE") &&
    7639          67 :              !EQUAL(pszDialect, "DEBUG"))
    7640           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter,
    7641           1 :                                        pszDialect);
    7642             : 
    7643             :     /* -------------------------------------------------------------------- */
    7644             :     /*      Prepare statement.                                              */
    7645             :     /* -------------------------------------------------------------------- */
    7646        5418 :     sqlite3_stmt *hSQLStmt = nullptr;
    7647             : 
    7648             :     /* This will speed-up layer creation */
    7649             :     /* ORDER BY are costly to evaluate and are not necessary to establish */
    7650             :     /* the layer definition. */
    7651        5418 :     bool bUseStatementForGetNextFeature = true;
    7652        5418 :     bool bEmptyLayer = false;
    7653       10836 :     CPLString osSQLCommandTruncated(osSQLCommand);
    7654             : 
    7655       17970 :     if (osSQLCommand.ifind("SELECT ") == 0 &&
    7656        6276 :         CPLString(osSQLCommand.substr(1)).ifind("SELECT ") ==
    7657         823 :             std::string::npos &&
    7658         823 :         osSQLCommand.ifind(" UNION ") == std::string::npos &&
    7659        7099 :         osSQLCommand.ifind(" INTERSECT ") == std::string::npos &&
    7660         823 :         osSQLCommand.ifind(" EXCEPT ") == std::string::npos)
    7661             :     {
    7662         823 :         size_t nOrderByPos = osSQLCommand.ifind(" ORDER BY ");
    7663         823 :         if (nOrderByPos != std::string::npos)
    7664             :         {
    7665           9 :             osSQLCommandTruncated.resize(nOrderByPos);
    7666           9 :             bUseStatementForGetNextFeature = false;
    7667             :         }
    7668             :     }
    7669             : 
    7670        5418 :     int rc = prepareSql(hDB, osSQLCommandTruncated.c_str(),
    7671        5418 :                         static_cast<int>(osSQLCommandTruncated.size()),
    7672             :                         &hSQLStmt, nullptr);
    7673             : 
    7674        5418 :     if (rc != SQLITE_OK)
    7675             :     {
    7676           9 :         CPLError(CE_Failure, CPLE_AppDefined,
    7677             :                  "In ExecuteSQL(): sqlite3_prepare_v2(%s): %s",
    7678             :                  osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7679             : 
    7680           9 :         if (hSQLStmt != nullptr)
    7681             :         {
    7682           0 :             sqlite3_finalize(hSQLStmt);
    7683             :         }
    7684             : 
    7685           9 :         return nullptr;
    7686             :     }
    7687             : 
    7688             :     /* -------------------------------------------------------------------- */
    7689             :     /*      Do we get a resultset?                                          */
    7690             :     /* -------------------------------------------------------------------- */
    7691        5409 :     rc = sqlite3_step(hSQLStmt);
    7692             : 
    7693        7057 :     for (auto &poLayer : m_apoLayers)
    7694             :     {
    7695        1648 :         poLayer->RunDeferredDropRTreeTableIfNecessary();
    7696             :     }
    7697             : 
    7698        5409 :     if (rc != SQLITE_ROW)
    7699             :     {
    7700        4634 :         if (rc != SQLITE_DONE)
    7701             :         {
    7702           7 :             CPLError(CE_Failure, CPLE_AppDefined,
    7703             :                      "In ExecuteSQL(): sqlite3_step(%s):\n  %s",
    7704             :                      osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7705             : 
    7706           7 :             sqlite3_finalize(hSQLStmt);
    7707           7 :             return nullptr;
    7708             :         }
    7709             : 
    7710        4627 :         if (EQUAL(osSQLCommand, "VACUUM"))
    7711             :         {
    7712          13 :             sqlite3_finalize(hSQLStmt);
    7713             :             /* VACUUM rewrites the DB, so we need to reset the application id */
    7714          13 :             SetApplicationAndUserVersionId();
    7715          13 :             return nullptr;
    7716             :         }
    7717             : 
    7718        4614 :         if (!STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7719             :         {
    7720        4487 :             sqlite3_finalize(hSQLStmt);
    7721        4487 :             return nullptr;
    7722             :         }
    7723             : 
    7724         127 :         bUseStatementForGetNextFeature = false;
    7725         127 :         bEmptyLayer = true;
    7726             :     }
    7727             : 
    7728             :     /* -------------------------------------------------------------------- */
    7729             :     /*      Special case for some functions which must be run               */
    7730             :     /*      only once                                                       */
    7731             :     /* -------------------------------------------------------------------- */
    7732         902 :     if (STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7733             :     {
    7734        4134 :         for (unsigned int i = 0; i < sizeof(apszFuncsWithSideEffects) /
    7735             :                                          sizeof(apszFuncsWithSideEffects[0]);
    7736             :              i++)
    7737             :         {
    7738        3333 :             if (EQUALN(apszFuncsWithSideEffects[i], osSQLCommand.c_str() + 7,
    7739             :                        strlen(apszFuncsWithSideEffects[i])))
    7740             :             {
    7741         112 :                 if (sqlite3_column_count(hSQLStmt) == 1 &&
    7742          56 :                     sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7743             :                 {
    7744          56 :                     int ret = sqlite3_column_int(hSQLStmt, 0);
    7745             : 
    7746          56 :                     sqlite3_finalize(hSQLStmt);
    7747             : 
    7748             :                     return new OGRSQLiteSingleFeatureLayer(
    7749          56 :                         apszFuncsWithSideEffects[i], ret);
    7750             :                 }
    7751             :             }
    7752             :         }
    7753             :     }
    7754          45 :     else if (STARTS_WITH_CI(osSQLCommand, "PRAGMA "))
    7755             :     {
    7756          63 :         if (sqlite3_column_count(hSQLStmt) == 1 &&
    7757          18 :             sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7758             :         {
    7759          15 :             int ret = sqlite3_column_int(hSQLStmt, 0);
    7760             : 
    7761          15 :             sqlite3_finalize(hSQLStmt);
    7762             : 
    7763          15 :             return new OGRSQLiteSingleFeatureLayer(osSQLCommand.c_str() + 7,
    7764          15 :                                                    ret);
    7765             :         }
    7766          33 :         else if (sqlite3_column_count(hSQLStmt) == 1 &&
    7767           3 :                  sqlite3_column_type(hSQLStmt, 0) == SQLITE_TEXT)
    7768             :         {
    7769             :             const char *pszRet = reinterpret_cast<const char *>(
    7770           3 :                 sqlite3_column_text(hSQLStmt, 0));
    7771             : 
    7772             :             OGRLayer *poRet = new OGRSQLiteSingleFeatureLayer(
    7773           3 :                 osSQLCommand.c_str() + 7, pszRet);
    7774             : 
    7775           3 :             sqlite3_finalize(hSQLStmt);
    7776             : 
    7777           3 :             return poRet;
    7778             :         }
    7779             :     }
    7780             : 
    7781             :     /* -------------------------------------------------------------------- */
    7782             :     /*      Create layer.                                                   */
    7783             :     /* -------------------------------------------------------------------- */
    7784             : 
    7785             :     auto poLayer = std::make_unique<OGRGeoPackageSelectLayer>(
    7786             :         this, osSQLCommand, hSQLStmt, bUseStatementForGetNextFeature,
    7787        1656 :         bEmptyLayer);
    7788             : 
    7789         831 :     if (poSpatialFilter != nullptr &&
    7790           3 :         poLayer->GetLayerDefn()->GetGeomFieldCount() > 0)
    7791           3 :         poLayer->SetSpatialFilter(0, poSpatialFilter);
    7792             : 
    7793         828 :     return poLayer.release();
    7794             : }
    7795             : 
    7796             : /************************************************************************/
    7797             : /*                          ReleaseResultSet()                          */
    7798             : /************************************************************************/
    7799             : 
    7800         861 : void GDALGeoPackageDataset::ReleaseResultSet(OGRLayer *poLayer)
    7801             : 
    7802             : {
    7803         861 :     delete poLayer;
    7804         861 : }
    7805             : 
    7806             : /************************************************************************/
    7807             : /*                         HasExtensionsTable()                         */
    7808             : /************************************************************************/
    7809             : 
    7810        7034 : bool GDALGeoPackageDataset::HasExtensionsTable()
    7811             : {
    7812        7034 :     return SQLGetInteger(
    7813             :                hDB,
    7814             :                "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_extensions' "
    7815             :                "AND type IN ('table', 'view')",
    7816        7034 :                nullptr) == 1;
    7817             : }
    7818             : 
    7819             : /************************************************************************/
    7820             : /*                    CheckUnknownExtensions()                          */
    7821             : /************************************************************************/
    7822             : 
    7823        1567 : void GDALGeoPackageDataset::CheckUnknownExtensions(bool bCheckRasterTable)
    7824             : {
    7825        1567 :     if (!HasExtensionsTable())
    7826         209 :         return;
    7827             : 
    7828        1358 :     char *pszSQL = nullptr;
    7829        1358 :     if (!bCheckRasterTable)
    7830        1149 :         pszSQL = sqlite3_mprintf(
    7831             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7832             :             "WHERE (table_name IS NULL "
    7833             :             "AND extension_name IS NOT NULL "
    7834             :             "AND definition IS NOT NULL "
    7835             :             "AND scope IS NOT NULL "
    7836             :             "AND extension_name NOT IN ("
    7837             :             "'gdal_aspatial', "
    7838             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7839             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7840             :                                        // 17-066r1 finalization
    7841             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7842             :             "'gpkg_metadata', "
    7843             :             "'gpkg_schema', "
    7844             :             "'gpkg_crs_wkt', "
    7845             :             "'gpkg_crs_wkt_1_1', "
    7846             :             "'related_tables', 'gpkg_related_tables')) "
    7847             : #ifdef WORKAROUND_SQLITE3_BUGS
    7848             :             "OR 0 "
    7849             : #endif
    7850             :             "LIMIT 1000");
    7851             :     else
    7852         209 :         pszSQL = sqlite3_mprintf(
    7853             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7854             :             "WHERE (lower(table_name) = lower('%q') "
    7855             :             "AND extension_name IS NOT NULL "
    7856             :             "AND definition IS NOT NULL "
    7857             :             "AND scope IS NOT NULL "
    7858             :             "AND extension_name NOT IN ("
    7859             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7860             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7861             :                                        // 17-066r1 finalization
    7862             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7863             :             "'gpkg_metadata', "
    7864             :             "'gpkg_schema', "
    7865             :             "'gpkg_crs_wkt', "
    7866             :             "'gpkg_crs_wkt_1_1', "
    7867             :             "'related_tables', 'gpkg_related_tables')) "
    7868             : #ifdef WORKAROUND_SQLITE3_BUGS
    7869             :             "OR 0 "
    7870             : #endif
    7871             :             "LIMIT 1000",
    7872             :             m_osRasterTable.c_str());
    7873             : 
    7874        2716 :     auto oResultTable = SQLQuery(GetDB(), pszSQL);
    7875        1358 :     sqlite3_free(pszSQL);
    7876        1358 :     if (oResultTable && oResultTable->RowCount() > 0)
    7877             :     {
    7878          42 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    7879             :         {
    7880          21 :             const char *pszExtName = oResultTable->GetValue(0, i);
    7881          21 :             const char *pszDefinition = oResultTable->GetValue(1, i);
    7882          21 :             const char *pszScope = oResultTable->GetValue(2, i);
    7883          21 :             if (pszExtName == nullptr || pszDefinition == nullptr ||
    7884             :                 pszScope == nullptr)
    7885             :             {
    7886           0 :                 continue;
    7887             :             }
    7888             : 
    7889          21 :             if (EQUAL(pszExtName, "gpkg_webp"))
    7890             :             {
    7891          15 :                 if (GDALGetDriverByName("WEBP") == nullptr)
    7892             :                 {
    7893           1 :                     CPLError(
    7894             :                         CE_Warning, CPLE_AppDefined,
    7895             :                         "Table %s contains WEBP tiles, but GDAL configured "
    7896             :                         "without WEBP support. Data will be missing",
    7897             :                         m_osRasterTable.c_str());
    7898             :                 }
    7899          15 :                 m_eTF = GPKG_TF_WEBP;
    7900          15 :                 continue;
    7901             :             }
    7902           6 :             if (EQUAL(pszExtName, "gpkg_zoom_other"))
    7903             :             {
    7904           2 :                 m_bZoomOther = true;
    7905           2 :                 continue;
    7906             :             }
    7907             : 
    7908           4 :             if (GetUpdate() && EQUAL(pszScope, "write-only"))
    7909             :             {
    7910           1 :                 CPLError(
    7911             :                     CE_Warning, CPLE_AppDefined,
    7912             :                     "Database relies on the '%s' (%s) extension that should "
    7913             :                     "be implemented for safe write-support, but is not "
    7914             :                     "currently. "
    7915             :                     "Update of that database are strongly discouraged to avoid "
    7916             :                     "corruption.",
    7917             :                     pszExtName, pszDefinition);
    7918             :             }
    7919           3 :             else if (GetUpdate() && EQUAL(pszScope, "read-write"))
    7920             :             {
    7921           1 :                 CPLError(
    7922             :                     CE_Warning, CPLE_AppDefined,
    7923             :                     "Database relies on the '%s' (%s) extension that should "
    7924             :                     "be implemented in order to read/write it safely, but is "
    7925             :                     "not currently. "
    7926             :                     "Some data may be missing while reading that database, and "
    7927             :                     "updates are strongly discouraged.",
    7928             :                     pszExtName, pszDefinition);
    7929             :             }
    7930           2 :             else if (EQUAL(pszScope, "read-write") &&
    7931             :                      // None of the NGA extensions at
    7932             :                      // http://ngageoint.github.io/GeoPackage/docs/extensions/
    7933             :                      // affect read-only scenarios
    7934           1 :                      !STARTS_WITH(pszExtName, "nga_"))
    7935             :             {
    7936           1 :                 CPLError(
    7937             :                     CE_Warning, CPLE_AppDefined,
    7938             :                     "Database relies on the '%s' (%s) extension that should "
    7939             :                     "be implemented in order to read it safely, but is not "
    7940             :                     "currently. "
    7941             :                     "Some data may be missing while reading that database.",
    7942             :                     pszExtName, pszDefinition);
    7943             :             }
    7944             :         }
    7945             :     }
    7946             : }
    7947             : 
    7948             : /************************************************************************/
    7949             : /*                         HasGDALAspatialExtension()                       */
    7950             : /************************************************************************/
    7951             : 
    7952        1110 : bool GDALGeoPackageDataset::HasGDALAspatialExtension()
    7953             : {
    7954        1110 :     if (!HasExtensionsTable())
    7955         102 :         return false;
    7956             : 
    7957             :     auto oResultTable = SQLQuery(hDB, "SELECT * FROM gpkg_extensions "
    7958             :                                       "WHERE (extension_name = 'gdal_aspatial' "
    7959             :                                       "AND table_name IS NULL "
    7960             :                                       "AND column_name IS NULL)"
    7961             : #ifdef WORKAROUND_SQLITE3_BUGS
    7962             :                                       " OR 0"
    7963             : #endif
    7964        1008 :     );
    7965        1008 :     bool bHasExtension = (oResultTable && oResultTable->RowCount() == 1);
    7966        1008 :     return bHasExtension;
    7967             : }
    7968             : 
    7969             : std::string
    7970         192 : GDALGeoPackageDataset::CreateRasterTriggersSQL(const std::string &osTableName)
    7971             : {
    7972             :     char *pszSQL;
    7973         192 :     std::string osSQL;
    7974             :     /* From D.5. sample_tile_pyramid Table 43. tiles table Trigger
    7975             :      * Definition SQL  */
    7976         192 :     pszSQL = sqlite3_mprintf(
    7977             :         "CREATE TRIGGER \"%w_zoom_insert\" "
    7978             :         "BEFORE INSERT ON \"%w\" "
    7979             :         "FOR EACH ROW BEGIN "
    7980             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7981             :         "constraint: zoom_level not specified for table in "
    7982             :         "gpkg_tile_matrix') "
    7983             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7984             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7985             :         "END; "
    7986             :         "CREATE TRIGGER \"%w_zoom_update\" "
    7987             :         "BEFORE UPDATE OF zoom_level ON \"%w\" "
    7988             :         "FOR EACH ROW BEGIN "
    7989             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7990             :         "constraint: zoom_level not specified for table in "
    7991             :         "gpkg_tile_matrix') "
    7992             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7993             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7994             :         "END; "
    7995             :         "CREATE TRIGGER \"%w_tile_column_insert\" "
    7996             :         "BEFORE INSERT ON \"%w\" "
    7997             :         "FOR EACH ROW BEGIN "
    7998             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7999             :         "constraint: tile_column cannot be < 0') "
    8000             :         "WHERE (NEW.tile_column < 0) ; "
    8001             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8002             :         "constraint: tile_column must by < matrix_width specified for "
    8003             :         "table and zoom level in gpkg_tile_matrix') "
    8004             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    8005             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8006             :         "zoom_level = NEW.zoom_level)); "
    8007             :         "END; "
    8008             :         "CREATE TRIGGER \"%w_tile_column_update\" "
    8009             :         "BEFORE UPDATE OF tile_column ON \"%w\" "
    8010             :         "FOR EACH ROW BEGIN "
    8011             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8012             :         "constraint: tile_column cannot be < 0') "
    8013             :         "WHERE (NEW.tile_column < 0) ; "
    8014             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8015             :         "constraint: tile_column must by < matrix_width specified for "
    8016             :         "table and zoom level in gpkg_tile_matrix') "
    8017             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    8018             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8019             :         "zoom_level = NEW.zoom_level)); "
    8020             :         "END; "
    8021             :         "CREATE TRIGGER \"%w_tile_row_insert\" "
    8022             :         "BEFORE INSERT ON \"%w\" "
    8023             :         "FOR EACH ROW BEGIN "
    8024             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8025             :         "constraint: tile_row cannot be < 0') "
    8026             :         "WHERE (NEW.tile_row < 0) ; "
    8027             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8028             :         "constraint: tile_row must by < matrix_height specified for "
    8029             :         "table and zoom level in gpkg_tile_matrix') "
    8030             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8031             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8032             :         "zoom_level = NEW.zoom_level)); "
    8033             :         "END; "
    8034             :         "CREATE TRIGGER \"%w_tile_row_update\" "
    8035             :         "BEFORE UPDATE OF tile_row ON \"%w\" "
    8036             :         "FOR EACH ROW BEGIN "
    8037             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8038             :         "constraint: tile_row cannot be < 0') "
    8039             :         "WHERE (NEW.tile_row < 0) ; "
    8040             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8041             :         "constraint: tile_row must by < matrix_height specified for "
    8042             :         "table and zoom level in gpkg_tile_matrix') "
    8043             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8044             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8045             :         "zoom_level = NEW.zoom_level)); "
    8046             :         "END; ",
    8047             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8048             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8049             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8050             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8051             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8052             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8053             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8054             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8055             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8056             :         osTableName.c_str());
    8057         192 :     osSQL = pszSQL;
    8058         192 :     sqlite3_free(pszSQL);
    8059         192 :     return osSQL;
    8060             : }
    8061             : 
    8062             : /************************************************************************/
    8063             : /*                  CreateExtensionsTableIfNecessary()                  */
    8064             : /************************************************************************/
    8065             : 
    8066        1256 : OGRErr GDALGeoPackageDataset::CreateExtensionsTableIfNecessary()
    8067             : {
    8068             :     /* Check if the table gpkg_extensions exists */
    8069        1256 :     if (HasExtensionsTable())
    8070         421 :         return OGRERR_NONE;
    8071             : 
    8072             :     /* Requirement 79 : Every extension of a GeoPackage SHALL be registered */
    8073             :     /* in a corresponding row in the gpkg_extensions table. The absence of a */
    8074             :     /* gpkg_extensions table or the absence of rows in gpkg_extensions table */
    8075             :     /* SHALL both indicate the absence of extensions to a GeoPackage. */
    8076         835 :     const char *pszCreateGpkgExtensions =
    8077             :         "CREATE TABLE gpkg_extensions ("
    8078             :         "table_name TEXT,"
    8079             :         "column_name TEXT,"
    8080             :         "extension_name TEXT NOT NULL,"
    8081             :         "definition TEXT NOT NULL,"
    8082             :         "scope TEXT NOT NULL,"
    8083             :         "CONSTRAINT ge_tce UNIQUE (table_name, column_name, extension_name)"
    8084             :         ")";
    8085             : 
    8086         835 :     return SQLCommand(hDB, pszCreateGpkgExtensions);
    8087             : }
    8088             : 
    8089             : /************************************************************************/
    8090             : /*                    OGR_GPKG_Intersects_Spatial_Filter()              */
    8091             : /************************************************************************/
    8092             : 
    8093       23135 : void OGR_GPKG_Intersects_Spatial_Filter(sqlite3_context *pContext, int argc,
    8094             :                                         sqlite3_value **argv)
    8095             : {
    8096       23135 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8097             :     {
    8098           0 :         sqlite3_result_int(pContext, 0);
    8099       23125 :         return;
    8100             :     }
    8101             : 
    8102             :     auto poLayer =
    8103       23135 :         static_cast<OGRGeoPackageTableLayer *>(sqlite3_user_data(pContext));
    8104             : 
    8105       23135 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8106             :     const GByte *pabyBLOB =
    8107       23135 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8108             : 
    8109             :     GPkgHeader sHeader;
    8110       46270 :     if (poLayer->m_bFilterIsEnvelope &&
    8111       23135 :         OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false, 0))
    8112             :     {
    8113       23135 :         if (sHeader.bExtentHasXY)
    8114             :         {
    8115          95 :             OGREnvelope sEnvelope;
    8116          95 :             sEnvelope.MinX = sHeader.MinX;
    8117          95 :             sEnvelope.MinY = sHeader.MinY;
    8118          95 :             sEnvelope.MaxX = sHeader.MaxX;
    8119          95 :             sEnvelope.MaxY = sHeader.MaxY;
    8120          95 :             if (poLayer->m_sFilterEnvelope.Contains(sEnvelope))
    8121             :             {
    8122          31 :                 sqlite3_result_int(pContext, 1);
    8123          31 :                 return;
    8124             :             }
    8125             :         }
    8126             : 
    8127             :         // Check if at least one point falls into the layer filter envelope
    8128             :         // nHeaderLen is > 0 for GeoPackage geometries
    8129       46208 :         if (sHeader.nHeaderLen > 0 &&
    8130       23104 :             OGRWKBIntersectsPessimistic(pabyBLOB + sHeader.nHeaderLen,
    8131       23104 :                                         nBLOBLen - sHeader.nHeaderLen,
    8132       23104 :                                         poLayer->m_sFilterEnvelope))
    8133             :         {
    8134       23094 :             sqlite3_result_int(pContext, 1);
    8135       23094 :             return;
    8136             :         }
    8137             :     }
    8138             : 
    8139             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8140          10 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8141          10 :     if (poGeom == nullptr)
    8142             :     {
    8143             :         // Try also spatialite geometry blobs
    8144           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8145           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8146           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8147             :         {
    8148           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8149           0 :             sqlite3_result_int(pContext, 0);
    8150           0 :             return;
    8151             :         }
    8152           0 :         poGeom.reset(poGeomSpatialite);
    8153             :     }
    8154             : 
    8155          10 :     sqlite3_result_int(pContext, poLayer->FilterGeometry(poGeom.get()));
    8156             : }
    8157             : 
    8158             : /************************************************************************/
    8159             : /*                      OGRGeoPackageSTMinX()                           */
    8160             : /************************************************************************/
    8161             : 
    8162      252317 : static void OGRGeoPackageSTMinX(sqlite3_context *pContext, int argc,
    8163             :                                 sqlite3_value **argv)
    8164             : {
    8165             :     GPkgHeader sHeader;
    8166      252317 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8167             :     {
    8168          17 :         sqlite3_result_null(pContext);
    8169          17 :         return;
    8170             :     }
    8171      252300 :     sqlite3_result_double(pContext, sHeader.MinX);
    8172             : }
    8173             : 
    8174             : /************************************************************************/
    8175             : /*                      OGRGeoPackageSTMinY()                           */
    8176             : /************************************************************************/
    8177             : 
    8178      252301 : static void OGRGeoPackageSTMinY(sqlite3_context *pContext, int argc,
    8179             :                                 sqlite3_value **argv)
    8180             : {
    8181             :     GPkgHeader sHeader;
    8182      252301 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8183             :     {
    8184           1 :         sqlite3_result_null(pContext);
    8185           1 :         return;
    8186             :     }
    8187      252300 :     sqlite3_result_double(pContext, sHeader.MinY);
    8188             : }
    8189             : 
    8190             : /************************************************************************/
    8191             : /*                      OGRGeoPackageSTMaxX()                           */
    8192             : /************************************************************************/
    8193             : 
    8194      252301 : static void OGRGeoPackageSTMaxX(sqlite3_context *pContext, int argc,
    8195             :                                 sqlite3_value **argv)
    8196             : {
    8197             :     GPkgHeader sHeader;
    8198      252301 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8199             :     {
    8200           1 :         sqlite3_result_null(pContext);
    8201           1 :         return;
    8202             :     }
    8203      252300 :     sqlite3_result_double(pContext, sHeader.MaxX);
    8204             : }
    8205             : 
    8206             : /************************************************************************/
    8207             : /*                      OGRGeoPackageSTMaxY()                           */
    8208             : /************************************************************************/
    8209             : 
    8210      252301 : static void OGRGeoPackageSTMaxY(sqlite3_context *pContext, int argc,
    8211             :                                 sqlite3_value **argv)
    8212             : {
    8213             :     GPkgHeader sHeader;
    8214      252301 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8215             :     {
    8216           1 :         sqlite3_result_null(pContext);
    8217           1 :         return;
    8218             :     }
    8219      252300 :     sqlite3_result_double(pContext, sHeader.MaxY);
    8220             : }
    8221             : 
    8222             : /************************************************************************/
    8223             : /*                     OGRGeoPackageSTIsEmpty()                         */
    8224             : /************************************************************************/
    8225             : 
    8226      253727 : static void OGRGeoPackageSTIsEmpty(sqlite3_context *pContext, int argc,
    8227             :                                    sqlite3_value **argv)
    8228             : {
    8229             :     GPkgHeader sHeader;
    8230      253727 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8231             :     {
    8232           2 :         sqlite3_result_null(pContext);
    8233           2 :         return;
    8234             :     }
    8235      253725 :     sqlite3_result_int(pContext, sHeader.bEmpty);
    8236             : }
    8237             : 
    8238             : /************************************************************************/
    8239             : /*                    OGRGeoPackageSTGeometryType()                     */
    8240             : /************************************************************************/
    8241             : 
    8242           7 : static void OGRGeoPackageSTGeometryType(sqlite3_context *pContext, int /*argc*/,
    8243             :                                         sqlite3_value **argv)
    8244             : {
    8245             :     GPkgHeader sHeader;
    8246             : 
    8247           7 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8248             :     const GByte *pabyBLOB =
    8249           7 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8250             :     OGRwkbGeometryType eGeometryType;
    8251             : 
    8252          13 :     if (nBLOBLen < 8 ||
    8253           6 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8254             :     {
    8255           2 :         if (OGRSQLiteGetSpatialiteGeometryHeader(
    8256             :                 pabyBLOB, nBLOBLen, nullptr, &eGeometryType, nullptr, nullptr,
    8257           2 :                 nullptr, nullptr, nullptr) == OGRERR_NONE)
    8258             :         {
    8259           1 :             sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8260             :                                 SQLITE_TRANSIENT);
    8261           4 :             return;
    8262             :         }
    8263             :         else
    8264             :         {
    8265           1 :             sqlite3_result_null(pContext);
    8266           1 :             return;
    8267             :         }
    8268             :     }
    8269             : 
    8270           5 :     if (static_cast<size_t>(nBLOBLen) < sHeader.nHeaderLen + 5)
    8271             :     {
    8272           2 :         sqlite3_result_null(pContext);
    8273           2 :         return;
    8274             :     }
    8275             : 
    8276           3 :     OGRErr err = OGRReadWKBGeometryType(pabyBLOB + sHeader.nHeaderLen,
    8277             :                                         wkbVariantIso, &eGeometryType);
    8278           3 :     if (err != OGRERR_NONE)
    8279           1 :         sqlite3_result_null(pContext);
    8280             :     else
    8281           2 :         sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8282             :                             SQLITE_TRANSIENT);
    8283             : }
    8284             : 
    8285             : /************************************************************************/
    8286             : /*                 OGRGeoPackageSTEnvelopesIntersects()                 */
    8287             : /************************************************************************/
    8288             : 
    8289         118 : static void OGRGeoPackageSTEnvelopesIntersects(sqlite3_context *pContext,
    8290             :                                                int argc, sqlite3_value **argv)
    8291             : {
    8292             :     GPkgHeader sHeader;
    8293         118 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8294             :     {
    8295           2 :         sqlite3_result_int(pContext, FALSE);
    8296         107 :         return;
    8297             :     }
    8298         116 :     const double dfMinX = sqlite3_value_double(argv[1]);
    8299         116 :     if (sHeader.MaxX < dfMinX)
    8300             :     {
    8301          93 :         sqlite3_result_int(pContext, FALSE);
    8302          93 :         return;
    8303             :     }
    8304          23 :     const double dfMinY = sqlite3_value_double(argv[2]);
    8305          23 :     if (sHeader.MaxY < dfMinY)
    8306             :     {
    8307          11 :         sqlite3_result_int(pContext, FALSE);
    8308          11 :         return;
    8309             :     }
    8310          12 :     const double dfMaxX = sqlite3_value_double(argv[3]);
    8311          12 :     if (sHeader.MinX > dfMaxX)
    8312             :     {
    8313           1 :         sqlite3_result_int(pContext, FALSE);
    8314           1 :         return;
    8315             :     }
    8316          11 :     const double dfMaxY = sqlite3_value_double(argv[4]);
    8317          11 :     sqlite3_result_int(pContext, sHeader.MinY <= dfMaxY);
    8318             : }
    8319             : 
    8320             : /************************************************************************/
    8321             : /*              OGRGeoPackageSTEnvelopesIntersectsTwoParams()           */
    8322             : /************************************************************************/
    8323             : 
    8324             : static void
    8325           3 : OGRGeoPackageSTEnvelopesIntersectsTwoParams(sqlite3_context *pContext, int argc,
    8326             :                                             sqlite3_value **argv)
    8327             : {
    8328             :     GPkgHeader sHeader;
    8329           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false, 0))
    8330             :     {
    8331           0 :         sqlite3_result_int(pContext, FALSE);
    8332           2 :         return;
    8333             :     }
    8334             :     GPkgHeader sHeader2;
    8335           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader2, true, false,
    8336             :                                 1))
    8337             :     {
    8338           0 :         sqlite3_result_int(pContext, FALSE);
    8339           0 :         return;
    8340             :     }
    8341           3 :     if (sHeader.MaxX < sHeader2.MinX)
    8342             :     {
    8343           1 :         sqlite3_result_int(pContext, FALSE);
    8344           1 :         return;
    8345             :     }
    8346           2 :     if (sHeader.MaxY < sHeader2.MinY)
    8347             :     {
    8348           0 :         sqlite3_result_int(pContext, FALSE);
    8349           0 :         return;
    8350             :     }
    8351           2 :     if (sHeader.MinX > sHeader2.MaxX)
    8352             :     {
    8353           1 :         sqlite3_result_int(pContext, FALSE);
    8354           1 :         return;
    8355             :     }
    8356           1 :     sqlite3_result_int(pContext, sHeader.MinY <= sHeader2.MaxY);
    8357             : }
    8358             : 
    8359             : /************************************************************************/
    8360             : /*                    OGRGeoPackageGPKGIsAssignable()                   */
    8361             : /************************************************************************/
    8362             : 
    8363           8 : static void OGRGeoPackageGPKGIsAssignable(sqlite3_context *pContext,
    8364             :                                           int /*argc*/, sqlite3_value **argv)
    8365             : {
    8366          15 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8367           7 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8368             :     {
    8369           2 :         sqlite3_result_int(pContext, 0);
    8370           2 :         return;
    8371             :     }
    8372             : 
    8373             :     const char *pszExpected =
    8374           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8375             :     const char *pszActual =
    8376           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8377           6 :     int bIsAssignable = OGR_GT_IsSubClassOf(OGRFromOGCGeomType(pszActual),
    8378             :                                             OGRFromOGCGeomType(pszExpected));
    8379           6 :     sqlite3_result_int(pContext, bIsAssignable);
    8380             : }
    8381             : 
    8382             : /************************************************************************/
    8383             : /*                     OGRGeoPackageSTSRID()                            */
    8384             : /************************************************************************/
    8385             : 
    8386          12 : static void OGRGeoPackageSTSRID(sqlite3_context *pContext, int argc,
    8387             :                                 sqlite3_value **argv)
    8388             : {
    8389             :     GPkgHeader sHeader;
    8390          12 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8391             :     {
    8392           2 :         sqlite3_result_null(pContext);
    8393           2 :         return;
    8394             :     }
    8395          10 :     sqlite3_result_int(pContext, sHeader.iSrsId);
    8396             : }
    8397             : 
    8398             : /************************************************************************/
    8399             : /*                     OGRGeoPackageSetSRID()                           */
    8400             : /************************************************************************/
    8401             : 
    8402          28 : static void OGRGeoPackageSetSRID(sqlite3_context *pContext, int /* argc */,
    8403             :                                  sqlite3_value **argv)
    8404             : {
    8405          28 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8406             :     {
    8407           1 :         sqlite3_result_null(pContext);
    8408           1 :         return;
    8409             :     }
    8410          27 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8411             :     GPkgHeader sHeader;
    8412          27 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8413             :     const GByte *pabyBLOB =
    8414          27 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8415             : 
    8416          54 :     if (nBLOBLen < 8 ||
    8417          27 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8418             :     {
    8419             :         // Try also spatialite geometry blobs
    8420           0 :         OGRGeometry *poGeom = nullptr;
    8421           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeom) !=
    8422             :             OGRERR_NONE)
    8423             :         {
    8424           0 :             sqlite3_result_null(pContext);
    8425           0 :             return;
    8426             :         }
    8427           0 :         size_t nBLOBDestLen = 0;
    8428             :         GByte *pabyDestBLOB =
    8429           0 :             GPkgGeometryFromOGR(poGeom, nDestSRID, nullptr, &nBLOBDestLen);
    8430           0 :         if (!pabyDestBLOB)
    8431             :         {
    8432           0 :             sqlite3_result_null(pContext);
    8433           0 :             return;
    8434             :         }
    8435           0 :         sqlite3_result_blob(pContext, pabyDestBLOB,
    8436             :                             static_cast<int>(nBLOBDestLen), VSIFree);
    8437           0 :         return;
    8438             :     }
    8439             : 
    8440          27 :     GByte *pabyDestBLOB = static_cast<GByte *>(CPLMalloc(nBLOBLen));
    8441          27 :     memcpy(pabyDestBLOB, pabyBLOB, nBLOBLen);
    8442          27 :     int32_t nSRIDToSerialize = nDestSRID;
    8443          27 :     if (OGR_SWAP(sHeader.eByteOrder))
    8444           0 :         nSRIDToSerialize = CPL_SWAP32(nSRIDToSerialize);
    8445          27 :     memcpy(pabyDestBLOB + 4, &nSRIDToSerialize, 4);
    8446          27 :     sqlite3_result_blob(pContext, pabyDestBLOB, nBLOBLen, VSIFree);
    8447             : }
    8448             : 
    8449             : /************************************************************************/
    8450             : /*                   OGRGeoPackageSTMakeValid()                         */
    8451             : /************************************************************************/
    8452             : 
    8453           3 : static void OGRGeoPackageSTMakeValid(sqlite3_context *pContext, int argc,
    8454             :                                      sqlite3_value **argv)
    8455             : {
    8456           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8457             :     {
    8458           2 :         sqlite3_result_null(pContext);
    8459           2 :         return;
    8460             :     }
    8461           1 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8462             :     const GByte *pabyBLOB =
    8463           1 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8464             : 
    8465             :     GPkgHeader sHeader;
    8466           1 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8467             :     {
    8468           0 :         sqlite3_result_null(pContext);
    8469           0 :         return;
    8470             :     }
    8471             : 
    8472             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8473           1 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8474           1 :     if (poGeom == nullptr)
    8475             :     {
    8476             :         // Try also spatialite geometry blobs
    8477           0 :         OGRGeometry *poGeomPtr = nullptr;
    8478           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8479             :             OGRERR_NONE)
    8480             :         {
    8481           0 :             sqlite3_result_null(pContext);
    8482           0 :             return;
    8483             :         }
    8484           0 :         poGeom.reset(poGeomPtr);
    8485             :     }
    8486           1 :     auto poValid = std::unique_ptr<OGRGeometry>(poGeom->MakeValid());
    8487           1 :     if (poValid == nullptr)
    8488             :     {
    8489           0 :         sqlite3_result_null(pContext);
    8490           0 :         return;
    8491             :     }
    8492             : 
    8493           1 :     size_t nBLOBDestLen = 0;
    8494           1 :     GByte *pabyDestBLOB = GPkgGeometryFromOGR(poValid.get(), sHeader.iSrsId,
    8495             :                                               nullptr, &nBLOBDestLen);
    8496           1 :     if (!pabyDestBLOB)
    8497             :     {
    8498           0 :         sqlite3_result_null(pContext);
    8499           0 :         return;
    8500             :     }
    8501           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8502             :                         VSIFree);
    8503             : }
    8504             : 
    8505             : /************************************************************************/
    8506             : /*                   OGRGeoPackageSTArea()                              */
    8507             : /************************************************************************/
    8508             : 
    8509          19 : static void OGRGeoPackageSTArea(sqlite3_context *pContext, int /*argc*/,
    8510             :                                 sqlite3_value **argv)
    8511             : {
    8512          19 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8513             :     {
    8514           1 :         sqlite3_result_null(pContext);
    8515          15 :         return;
    8516             :     }
    8517          18 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8518             :     const GByte *pabyBLOB =
    8519          18 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8520             : 
    8521             :     GPkgHeader sHeader;
    8522           0 :     std::unique_ptr<OGRGeometry> poGeom;
    8523          18 :     if (GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) == OGRERR_NONE)
    8524             :     {
    8525          16 :         if (sHeader.bEmpty)
    8526             :         {
    8527           3 :             sqlite3_result_double(pContext, 0);
    8528          13 :             return;
    8529             :         }
    8530          13 :         const GByte *pabyWkb = pabyBLOB + sHeader.nHeaderLen;
    8531          13 :         size_t nWKBSize = nBLOBLen - sHeader.nHeaderLen;
    8532             :         bool bNeedSwap;
    8533             :         uint32_t nType;
    8534          13 :         if (OGRWKBGetGeomType(pabyWkb, nWKBSize, bNeedSwap, nType))
    8535             :         {
    8536          13 :             if (nType == wkbPolygon || nType == wkbPolygon25D ||
    8537          11 :                 nType == wkbPolygon + 1000 ||  // wkbPolygonZ
    8538          10 :                 nType == wkbPolygonM || nType == wkbPolygonZM)
    8539             :             {
    8540             :                 double dfArea;
    8541           5 :                 if (OGRWKBPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8542             :                 {
    8543           5 :                     sqlite3_result_double(pContext, dfArea);
    8544           5 :                     return;
    8545           0 :                 }
    8546             :             }
    8547           8 :             else if (nType == wkbMultiPolygon || nType == wkbMultiPolygon25D ||
    8548           6 :                      nType == wkbMultiPolygon + 1000 ||  // wkbMultiPolygonZ
    8549           5 :                      nType == wkbMultiPolygonM || nType == wkbMultiPolygonZM)
    8550             :             {
    8551             :                 double dfArea;
    8552           5 :                 if (OGRWKBMultiPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8553             :                 {
    8554           5 :                     sqlite3_result_double(pContext, dfArea);
    8555           5 :                     return;
    8556             :                 }
    8557             :             }
    8558             :         }
    8559             : 
    8560             :         // For curve geometries, fallback to OGRGeometry methods
    8561           3 :         poGeom.reset(GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8562             :     }
    8563             :     else
    8564             :     {
    8565             :         // Try also spatialite geometry blobs
    8566           2 :         OGRGeometry *poGeomPtr = nullptr;
    8567           2 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8568             :             OGRERR_NONE)
    8569             :         {
    8570           1 :             sqlite3_result_null(pContext);
    8571           1 :             return;
    8572             :         }
    8573           1 :         poGeom.reset(poGeomPtr);
    8574             :     }
    8575           4 :     auto poSurface = dynamic_cast<OGRSurface *>(poGeom.get());
    8576           4 :     if (poSurface == nullptr)
    8577             :     {
    8578           2 :         auto poMultiSurface = dynamic_cast<OGRMultiSurface *>(poGeom.get());
    8579           2 :         if (poMultiSurface == nullptr)
    8580             :         {
    8581           1 :             sqlite3_result_double(pContext, 0);
    8582             :         }
    8583             :         else
    8584             :         {
    8585           1 :             sqlite3_result_double(pContext, poMultiSurface->get_Area());
    8586             :         }
    8587             :     }
    8588             :     else
    8589             :     {
    8590           2 :         sqlite3_result_double(pContext, poSurface->get_Area());
    8591             :     }
    8592             : }
    8593             : 
    8594             : /************************************************************************/
    8595             : /*                     OGRGeoPackageGeodesicArea()                      */
    8596             : /************************************************************************/
    8597             : 
    8598           5 : static void OGRGeoPackageGeodesicArea(sqlite3_context *pContext, int argc,
    8599             :                                       sqlite3_value **argv)
    8600             : {
    8601           5 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8602             :     {
    8603           1 :         sqlite3_result_null(pContext);
    8604           3 :         return;
    8605             :     }
    8606           4 :     if (sqlite3_value_int(argv[1]) != 1)
    8607             :     {
    8608           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8609             :                  "ST_Area(geom, use_ellipsoid) is only supported for "
    8610             :                  "use_ellipsoid = 1");
    8611             :     }
    8612             : 
    8613           4 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8614             :     const GByte *pabyBLOB =
    8615           4 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8616             :     GPkgHeader sHeader;
    8617           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8618             :     {
    8619           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8620           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8621           1 :         return;
    8622             :     }
    8623             : 
    8624             :     GDALGeoPackageDataset *poDS =
    8625           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8626             : 
    8627             :     std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSrcSRS(
    8628           3 :         poDS->GetSpatialRef(sHeader.iSrsId, true));
    8629           3 :     if (poSrcSRS == nullptr)
    8630             :     {
    8631           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    8632             :                  "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8633           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8634           1 :         return;
    8635             :     }
    8636             : 
    8637             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8638           2 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8639           2 :     if (poGeom == nullptr)
    8640             :     {
    8641             :         // Try also spatialite geometry blobs
    8642           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8643           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8644           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8645             :         {
    8646           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8647           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8648           0 :             return;
    8649             :         }
    8650           0 :         poGeom.reset(poGeomSpatialite);
    8651             :     }
    8652             : 
    8653           2 :     poGeom->assignSpatialReference(poSrcSRS.get());
    8654           2 :     sqlite3_result_double(
    8655             :         pContext, OGR_G_GeodesicArea(OGRGeometry::ToHandle(poGeom.get())));
    8656             : }
    8657             : 
    8658             : /************************************************************************/
    8659             : /*                   OGRGeoPackageLengthOrGeodesicLength()              */
    8660             : /************************************************************************/
    8661             : 
    8662           8 : static void OGRGeoPackageLengthOrGeodesicLength(sqlite3_context *pContext,
    8663             :                                                 int argc, sqlite3_value **argv)
    8664             : {
    8665           8 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8666             :     {
    8667           2 :         sqlite3_result_null(pContext);
    8668           5 :         return;
    8669             :     }
    8670           6 :     if (argc == 2 && sqlite3_value_int(argv[1]) != 1)
    8671             :     {
    8672           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8673             :                  "ST_Length(geom, use_ellipsoid) is only supported for "
    8674             :                  "use_ellipsoid = 1");
    8675             :     }
    8676             : 
    8677           6 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8678             :     const GByte *pabyBLOB =
    8679           6 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8680             :     GPkgHeader sHeader;
    8681           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8682             :     {
    8683           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8684           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8685           2 :         return;
    8686             :     }
    8687             : 
    8688             :     GDALGeoPackageDataset *poDS =
    8689           4 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8690             : 
    8691           0 :     std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSrcSRS;
    8692           4 :     if (argc == 2)
    8693             :     {
    8694           3 :         poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8695           3 :         if (!poSrcSRS)
    8696             :         {
    8697           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    8698             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8699           1 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8700           1 :             return;
    8701             :         }
    8702             :     }
    8703             : 
    8704             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8705           3 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8706           3 :     if (poGeom == nullptr)
    8707             :     {
    8708             :         // Try also spatialite geometry blobs
    8709           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8710           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8711           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8712             :         {
    8713           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8714           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8715           0 :             return;
    8716             :         }
    8717           0 :         poGeom.reset(poGeomSpatialite);
    8718             :     }
    8719             : 
    8720           3 :     if (argc == 2)
    8721           2 :         poGeom->assignSpatialReference(poSrcSRS.get());
    8722             : 
    8723           6 :     sqlite3_result_double(
    8724             :         pContext,
    8725           1 :         argc == 1 ? OGR_G_Length(OGRGeometry::ToHandle(poGeom.get()))
    8726           2 :                   : OGR_G_GeodesicLength(OGRGeometry::ToHandle(poGeom.get())));
    8727             : }
    8728             : 
    8729             : /************************************************************************/
    8730             : /*                      OGRGeoPackageTransform()                        */
    8731             : /************************************************************************/
    8732             : 
    8733             : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8734             :                             sqlite3_value **argv);
    8735             : 
    8736          32 : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8737             :                             sqlite3_value **argv)
    8738             : {
    8739          63 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB ||
    8740          31 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8741             :     {
    8742           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8743          32 :         return;
    8744             :     }
    8745             : 
    8746          30 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8747             :     const GByte *pabyBLOB =
    8748          30 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8749             :     GPkgHeader sHeader;
    8750          30 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8751             :     {
    8752           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8753           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8754           1 :         return;
    8755             :     }
    8756             : 
    8757          29 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8758          29 :     if (sHeader.iSrsId == nDestSRID)
    8759             :     {
    8760             :         // Return blob unmodified
    8761           3 :         sqlite3_result_blob(pContext, pabyBLOB, nBLOBLen, SQLITE_TRANSIENT);
    8762           3 :         return;
    8763             :     }
    8764             : 
    8765             :     GDALGeoPackageDataset *poDS =
    8766          26 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8767             : 
    8768             :     // Try to get the cached coordinate transformation
    8769             :     OGRCoordinateTransformation *poCT;
    8770          26 :     if (poDS->m_nLastCachedCTSrcSRId == sHeader.iSrsId &&
    8771          20 :         poDS->m_nLastCachedCTDstSRId == nDestSRID)
    8772             :     {
    8773          20 :         poCT = poDS->m_poLastCachedCT.get();
    8774             :     }
    8775             :     else
    8776             :     {
    8777             :         std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
    8778           6 :             poSrcSRS(poDS->GetSpatialRef(sHeader.iSrsId, true));
    8779           6 :         if (poSrcSRS == nullptr)
    8780             :         {
    8781           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    8782             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8783           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8784           0 :             return;
    8785             :         }
    8786             : 
    8787             :         std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
    8788           6 :             poDstSRS(poDS->GetSpatialRef(nDestSRID, true));
    8789           6 :         if (poDstSRS == nullptr)
    8790             :         {
    8791           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Target SRID (%d) is invalid",
    8792             :                      nDestSRID);
    8793           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8794           0 :             return;
    8795             :         }
    8796             :         poCT =
    8797           6 :             OGRCreateCoordinateTransformation(poSrcSRS.get(), poDstSRS.get());
    8798           6 :         if (poCT == nullptr)
    8799             :         {
    8800           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8801           0 :             return;
    8802             :         }
    8803             : 
    8804             :         // Cache coordinate transformation for potential later reuse
    8805           6 :         poDS->m_nLastCachedCTSrcSRId = sHeader.iSrsId;
    8806           6 :         poDS->m_nLastCachedCTDstSRId = nDestSRID;
    8807           6 :         poDS->m_poLastCachedCT.reset(poCT);
    8808           6 :         poCT = poDS->m_poLastCachedCT.get();
    8809             :     }
    8810             : 
    8811          26 :     if (sHeader.nHeaderLen >= 8)
    8812             :     {
    8813          26 :         std::vector<GByte> &abyNewBLOB = poDS->m_abyWKBTransformCache;
    8814          26 :         abyNewBLOB.resize(nBLOBLen);
    8815          26 :         memcpy(abyNewBLOB.data(), pabyBLOB, nBLOBLen);
    8816             : 
    8817          26 :         OGREnvelope3D oEnv3d;
    8818          26 :         if (!OGRWKBTransform(abyNewBLOB.data() + sHeader.nHeaderLen,
    8819          26 :                              nBLOBLen - sHeader.nHeaderLen, poCT,
    8820          78 :                              poDS->m_oWKBTransformCache, oEnv3d) ||
    8821          26 :             !GPkgUpdateHeader(abyNewBLOB.data(), nBLOBLen, nDestSRID,
    8822             :                               oEnv3d.MinX, oEnv3d.MaxX, oEnv3d.MinY,
    8823             :                               oEnv3d.MaxY, oEnv3d.MinZ, oEnv3d.MaxZ))
    8824             :         {
    8825           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8826           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8827           0 :             return;
    8828             :         }
    8829             : 
    8830          26 :         sqlite3_result_blob(pContext, abyNewBLOB.data(), nBLOBLen,
    8831             :                             SQLITE_TRANSIENT);
    8832          26 :         return;
    8833             :     }
    8834             : 
    8835             :     // Try also spatialite geometry blobs
    8836           0 :     OGRGeometry *poGeomSpatialite = nullptr;
    8837           0 :     if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8838           0 :                                           &poGeomSpatialite) != OGRERR_NONE)
    8839             :     {
    8840           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8841           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8842           0 :         return;
    8843             :     }
    8844           0 :     auto poGeom = std::unique_ptr<OGRGeometry>(poGeomSpatialite);
    8845             : 
    8846           0 :     if (poGeom->transform(poCT) != OGRERR_NONE)
    8847             :     {
    8848           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8849           0 :         return;
    8850             :     }
    8851             : 
    8852           0 :     size_t nBLOBDestLen = 0;
    8853             :     GByte *pabyDestBLOB =
    8854           0 :         GPkgGeometryFromOGR(poGeom.get(), nDestSRID, nullptr, &nBLOBDestLen);
    8855           0 :     if (!pabyDestBLOB)
    8856             :     {
    8857           0 :         sqlite3_result_null(pContext);
    8858           0 :         return;
    8859             :     }
    8860           0 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8861             :                         VSIFree);
    8862             : }
    8863             : 
    8864             : /************************************************************************/
    8865             : /*                      OGRGeoPackageSridFromAuthCRS()                  */
    8866             : /************************************************************************/
    8867             : 
    8868           4 : static void OGRGeoPackageSridFromAuthCRS(sqlite3_context *pContext,
    8869             :                                          int /*argc*/, sqlite3_value **argv)
    8870             : {
    8871           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8872           3 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8873             :     {
    8874           2 :         sqlite3_result_int(pContext, -1);
    8875           2 :         return;
    8876             :     }
    8877             : 
    8878             :     GDALGeoPackageDataset *poDS =
    8879           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8880             : 
    8881           2 :     char *pszSQL = sqlite3_mprintf(
    8882             :         "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
    8883             :         "lower(organization) = lower('%q') AND organization_coordsys_id = %d",
    8884           2 :         sqlite3_value_text(argv[0]), sqlite3_value_int(argv[1]));
    8885           2 :     OGRErr err = OGRERR_NONE;
    8886           2 :     int nSRSId = SQLGetInteger(poDS->GetDB(), pszSQL, &err);
    8887           2 :     sqlite3_free(pszSQL);
    8888           2 :     if (err != OGRERR_NONE)
    8889           1 :         nSRSId = -1;
    8890           2 :     sqlite3_result_int(pContext, nSRSId);
    8891             : }
    8892             : 
    8893             : /************************************************************************/
    8894             : /*                    OGRGeoPackageImportFromEPSG()                     */
    8895             : /************************************************************************/
    8896             : 
    8897           4 : static void OGRGeoPackageImportFromEPSG(sqlite3_context *pContext, int /*argc*/,
    8898             :                                         sqlite3_value **argv)
    8899             : {
    8900           4 :     if (sqlite3_value_type(argv[0]) != SQLITE_INTEGER)
    8901             :     {
    8902           1 :         sqlite3_result_int(pContext, -1);
    8903           2 :         return;
    8904             :     }
    8905             : 
    8906             :     GDALGeoPackageDataset *poDS =
    8907           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8908           3 :     OGRSpatialReference oSRS;
    8909           3 :     if (oSRS.importFromEPSG(sqlite3_value_int(argv[0])) != OGRERR_NONE)
    8910             :     {
    8911           1 :         sqlite3_result_int(pContext, -1);
    8912           1 :         return;
    8913             :     }
    8914             : 
    8915           2 :     sqlite3_result_int(pContext, poDS->GetSrsId(&oSRS));
    8916             : }
    8917             : 
    8918             : /************************************************************************/
    8919             : /*               OGRGeoPackageRegisterGeometryExtension()               */
    8920             : /************************************************************************/
    8921             : 
    8922           1 : static void OGRGeoPackageRegisterGeometryExtension(sqlite3_context *pContext,
    8923             :                                                    int /*argc*/,
    8924             :                                                    sqlite3_value **argv)
    8925             : {
    8926           1 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8927           2 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT ||
    8928           1 :         sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    8929             :     {
    8930           0 :         sqlite3_result_int(pContext, 0);
    8931           0 :         return;
    8932             :     }
    8933             : 
    8934             :     const char *pszTableName =
    8935           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8936             :     const char *pszGeomName =
    8937           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8938             :     const char *pszGeomType =
    8939           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    8940             : 
    8941             :     GDALGeoPackageDataset *poDS =
    8942           1 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8943             : 
    8944           1 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8945           1 :         poDS->GetLayerByName(pszTableName));
    8946           1 :     if (poLyr == nullptr)
    8947             :     {
    8948           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8949           0 :         sqlite3_result_int(pContext, 0);
    8950           0 :         return;
    8951             :     }
    8952           1 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8953             :     {
    8954           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8955           0 :         sqlite3_result_int(pContext, 0);
    8956           0 :         return;
    8957             :     }
    8958           1 :     const OGRwkbGeometryType eGeomType = OGRFromOGCGeomType(pszGeomType);
    8959           1 :     if (eGeomType == wkbUnknown)
    8960             :     {
    8961           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry type name");
    8962           0 :         sqlite3_result_int(pContext, 0);
    8963           0 :         return;
    8964             :     }
    8965             : 
    8966           1 :     sqlite3_result_int(
    8967             :         pContext,
    8968           1 :         static_cast<int>(poLyr->CreateGeometryExtensionIfNecessary(eGeomType)));
    8969             : }
    8970             : 
    8971             : /************************************************************************/
    8972             : /*                  OGRGeoPackageCreateSpatialIndex()                   */
    8973             : /************************************************************************/
    8974             : 
    8975          14 : static void OGRGeoPackageCreateSpatialIndex(sqlite3_context *pContext,
    8976             :                                             int /*argc*/, sqlite3_value **argv)
    8977             : {
    8978          27 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8979          13 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8980             :     {
    8981           2 :         sqlite3_result_int(pContext, 0);
    8982           2 :         return;
    8983             :     }
    8984             : 
    8985             :     const char *pszTableName =
    8986          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8987             :     const char *pszGeomName =
    8988          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8989             :     GDALGeoPackageDataset *poDS =
    8990          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8991             : 
    8992          12 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8993          12 :         poDS->GetLayerByName(pszTableName));
    8994          12 :     if (poLyr == nullptr)
    8995             :     {
    8996           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8997           1 :         sqlite3_result_int(pContext, 0);
    8998           1 :         return;
    8999             :     }
    9000          11 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9001             :     {
    9002           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9003           1 :         sqlite3_result_int(pContext, 0);
    9004           1 :         return;
    9005             :     }
    9006             : 
    9007          10 :     sqlite3_result_int(pContext, poLyr->CreateSpatialIndex());
    9008             : }
    9009             : 
    9010             : /************************************************************************/
    9011             : /*                  OGRGeoPackageDisableSpatialIndex()                  */
    9012             : /************************************************************************/
    9013             : 
    9014          12 : static void OGRGeoPackageDisableSpatialIndex(sqlite3_context *pContext,
    9015             :                                              int /*argc*/, sqlite3_value **argv)
    9016             : {
    9017          23 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9018          11 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9019             :     {
    9020           2 :         sqlite3_result_int(pContext, 0);
    9021           2 :         return;
    9022             :     }
    9023             : 
    9024             :     const char *pszTableName =
    9025          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9026             :     const char *pszGeomName =
    9027          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9028             :     GDALGeoPackageDataset *poDS =
    9029          10 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9030             : 
    9031          10 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9032          10 :         poDS->GetLayerByName(pszTableName));
    9033          10 :     if (poLyr == nullptr)
    9034             :     {
    9035           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9036           1 :         sqlite3_result_int(pContext, 0);
    9037           1 :         return;
    9038             :     }
    9039           9 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9040             :     {
    9041           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9042           1 :         sqlite3_result_int(pContext, 0);
    9043           1 :         return;
    9044             :     }
    9045             : 
    9046           8 :     sqlite3_result_int(pContext, poLyr->DropSpatialIndex(true));
    9047             : }
    9048             : 
    9049             : /************************************************************************/
    9050             : /*                  OGRGeoPackageHasSpatialIndex()                      */
    9051             : /************************************************************************/
    9052             : 
    9053          29 : static void OGRGeoPackageHasSpatialIndex(sqlite3_context *pContext,
    9054             :                                          int /*argc*/, sqlite3_value **argv)
    9055             : {
    9056          57 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9057          28 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9058             :     {
    9059           2 :         sqlite3_result_int(pContext, 0);
    9060           2 :         return;
    9061             :     }
    9062             : 
    9063             :     const char *pszTableName =
    9064          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9065             :     const char *pszGeomName =
    9066          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9067             :     GDALGeoPackageDataset *poDS =
    9068          27 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9069             : 
    9070          27 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9071          27 :         poDS->GetLayerByName(pszTableName));
    9072          27 :     if (poLyr == nullptr)
    9073             :     {
    9074           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9075           1 :         sqlite3_result_int(pContext, 0);
    9076           1 :         return;
    9077             :     }
    9078          26 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9079             :     {
    9080           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9081           1 :         sqlite3_result_int(pContext, 0);
    9082           1 :         return;
    9083             :     }
    9084             : 
    9085          25 :     poLyr->RunDeferredCreationIfNecessary();
    9086          25 :     poLyr->CreateSpatialIndexIfNecessary();
    9087             : 
    9088          25 :     sqlite3_result_int(pContext, poLyr->HasSpatialIndex());
    9089             : }
    9090             : 
    9091             : /************************************************************************/
    9092             : /*                       GPKG_hstore_get_value()                        */
    9093             : /************************************************************************/
    9094             : 
    9095           4 : static void GPKG_hstore_get_value(sqlite3_context *pContext, int /*argc*/,
    9096             :                                   sqlite3_value **argv)
    9097             : {
    9098           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9099           3 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9100             :     {
    9101           2 :         sqlite3_result_null(pContext);
    9102           2 :         return;
    9103             :     }
    9104             : 
    9105             :     const char *pszHStore =
    9106           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9107             :     const char *pszSearchedKey =
    9108           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9109           2 :     char *pszValue = OGRHStoreGetValue(pszHStore, pszSearchedKey);
    9110           2 :     if (pszValue != nullptr)
    9111           1 :         sqlite3_result_text(pContext, pszValue, -1, CPLFree);
    9112             :     else
    9113           1 :         sqlite3_result_null(pContext);
    9114             : }
    9115             : 
    9116             : /************************************************************************/
    9117             : /*                      GPKG_GDAL_GetMemFileFromBlob()                  */
    9118             : /************************************************************************/
    9119             : 
    9120         105 : static CPLString GPKG_GDAL_GetMemFileFromBlob(sqlite3_value **argv)
    9121             : {
    9122         105 :     int nBytes = sqlite3_value_bytes(argv[0]);
    9123             :     const GByte *pabyBLOB =
    9124         105 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    9125             :     CPLString osMemFileName(
    9126         105 :         VSIMemGenerateHiddenFilename("GPKG_GDAL_GetMemFileFromBlob"));
    9127         105 :     VSILFILE *fp = VSIFileFromMemBuffer(
    9128             :         osMemFileName.c_str(), const_cast<GByte *>(pabyBLOB), nBytes, FALSE);
    9129         105 :     VSIFCloseL(fp);
    9130         105 :     return osMemFileName;
    9131             : }
    9132             : 
    9133             : /************************************************************************/
    9134             : /*                       GPKG_GDAL_GetMimeType()                        */
    9135             : /************************************************************************/
    9136             : 
    9137          35 : static void GPKG_GDAL_GetMimeType(sqlite3_context *pContext, int /*argc*/,
    9138             :                                   sqlite3_value **argv)
    9139             : {
    9140          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9141             :     {
    9142           0 :         sqlite3_result_null(pContext);
    9143           0 :         return;
    9144             :     }
    9145             : 
    9146          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9147             :     GDALDriver *poDriver =
    9148          35 :         GDALDriver::FromHandle(GDALIdentifyDriver(osMemFileName, nullptr));
    9149          35 :     if (poDriver != nullptr)
    9150             :     {
    9151          35 :         const char *pszRes = nullptr;
    9152          35 :         if (EQUAL(poDriver->GetDescription(), "PNG"))
    9153          23 :             pszRes = "image/png";
    9154          12 :         else if (EQUAL(poDriver->GetDescription(), "JPEG"))
    9155           6 :             pszRes = "image/jpeg";
    9156           6 :         else if (EQUAL(poDriver->GetDescription(), "WEBP"))
    9157           6 :             pszRes = "image/x-webp";
    9158           0 :         else if (EQUAL(poDriver->GetDescription(), "GTIFF"))
    9159           0 :             pszRes = "image/tiff";
    9160             :         else
    9161           0 :             pszRes = CPLSPrintf("gdal/%s", poDriver->GetDescription());
    9162          35 :         sqlite3_result_text(pContext, pszRes, -1, SQLITE_TRANSIENT);
    9163             :     }
    9164             :     else
    9165           0 :         sqlite3_result_null(pContext);
    9166          35 :     VSIUnlink(osMemFileName);
    9167             : }
    9168             : 
    9169             : /************************************************************************/
    9170             : /*                       GPKG_GDAL_GetBandCount()                       */
    9171             : /************************************************************************/
    9172             : 
    9173          35 : static void GPKG_GDAL_GetBandCount(sqlite3_context *pContext, int /*argc*/,
    9174             :                                    sqlite3_value **argv)
    9175             : {
    9176          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9177             :     {
    9178           0 :         sqlite3_result_null(pContext);
    9179           0 :         return;
    9180             :     }
    9181             : 
    9182          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9183             :     auto poDS = std::unique_ptr<GDALDataset>(
    9184             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9185          70 :                           nullptr, nullptr, nullptr));
    9186          35 :     if (poDS != nullptr)
    9187             :     {
    9188          35 :         sqlite3_result_int(pContext, poDS->GetRasterCount());
    9189             :     }
    9190             :     else
    9191           0 :         sqlite3_result_null(pContext);
    9192          35 :     VSIUnlink(osMemFileName);
    9193             : }
    9194             : 
    9195             : /************************************************************************/
    9196             : /*                       GPKG_GDAL_HasColorTable()                      */
    9197             : /************************************************************************/
    9198             : 
    9199          35 : static void GPKG_GDAL_HasColorTable(sqlite3_context *pContext, int /*argc*/,
    9200             :                                     sqlite3_value **argv)
    9201             : {
    9202          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9203             :     {
    9204           0 :         sqlite3_result_null(pContext);
    9205           0 :         return;
    9206             :     }
    9207             : 
    9208          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9209             :     auto poDS = std::unique_ptr<GDALDataset>(
    9210             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9211          70 :                           nullptr, nullptr, nullptr));
    9212          35 :     if (poDS != nullptr)
    9213             :     {
    9214          35 :         sqlite3_result_int(
    9215          46 :             pContext, poDS->GetRasterCount() == 1 &&
    9216          11 :                           poDS->GetRasterBand(1)->GetColorTable() != nullptr);
    9217             :     }
    9218             :     else
    9219           0 :         sqlite3_result_null(pContext);
    9220          35 :     VSIUnlink(osMemFileName);
    9221             : }
    9222             : 
    9223             : /************************************************************************/
    9224             : /*                      GetRasterLayerDataset()                         */
    9225             : /************************************************************************/
    9226             : 
    9227             : GDALDataset *
    9228          12 : GDALGeoPackageDataset::GetRasterLayerDataset(const char *pszLayerName)
    9229             : {
    9230          12 :     const auto oIter = m_oCachedRasterDS.find(pszLayerName);
    9231          12 :     if (oIter != m_oCachedRasterDS.end())
    9232          10 :         return oIter->second.get();
    9233             : 
    9234             :     auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
    9235           4 :         (std::string("GPKG:\"") + m_pszFilename + "\":" + pszLayerName).c_str(),
    9236           4 :         GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR));
    9237           2 :     if (!poDS)
    9238             :     {
    9239           0 :         return nullptr;
    9240             :     }
    9241           2 :     m_oCachedRasterDS[pszLayerName] = std::move(poDS);
    9242           2 :     return m_oCachedRasterDS[pszLayerName].get();
    9243             : }
    9244             : 
    9245             : /************************************************************************/
    9246             : /*                   GPKG_gdal_get_layer_pixel_value()                  */
    9247             : /************************************************************************/
    9248             : 
    9249             : // NOTE: keep in sync implementations in ogrsqlitesqlfunctionscommon.cpp
    9250             : // and ogrgeopackagedatasource.cpp
    9251          13 : static void GPKG_gdal_get_layer_pixel_value(sqlite3_context *pContext, int argc,
    9252             :                                             sqlite3_value **argv)
    9253             : {
    9254          13 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9255             :     {
    9256           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9257             :                  "Invalid arguments to gdal_get_layer_pixel_value()");
    9258           1 :         sqlite3_result_null(pContext);
    9259           1 :         return;
    9260             :     }
    9261             : 
    9262             :     const char *pszLayerName =
    9263          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9264             : 
    9265             :     GDALGeoPackageDataset *poGlobalDS =
    9266          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9267          12 :     auto poDS = poGlobalDS->GetRasterLayerDataset(pszLayerName);
    9268          12 :     if (!poDS)
    9269             :     {
    9270           0 :         sqlite3_result_null(pContext);
    9271           0 :         return;
    9272             :     }
    9273             : 
    9274          12 :     OGRSQLite_gdal_get_pixel_value_common("gdal_get_layer_pixel_value",
    9275             :                                           pContext, argc, argv, poDS);
    9276             : }
    9277             : 
    9278             : /************************************************************************/
    9279             : /*                       GPKG_ogr_layer_Extent()                        */
    9280             : /************************************************************************/
    9281             : 
    9282           3 : static void GPKG_ogr_layer_Extent(sqlite3_context *pContext, int /*argc*/,
    9283             :                                   sqlite3_value **argv)
    9284             : {
    9285           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9286             :     {
    9287           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Invalid argument type",
    9288             :                  "ogr_layer_Extent");
    9289           1 :         sqlite3_result_null(pContext);
    9290           2 :         return;
    9291             :     }
    9292             : 
    9293             :     const char *pszLayerName =
    9294           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9295             :     GDALGeoPackageDataset *poDS =
    9296           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9297           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9298           2 :     if (!poLayer)
    9299             :     {
    9300           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer",
    9301             :                  "ogr_layer_Extent");
    9302           1 :         sqlite3_result_null(pContext);
    9303           1 :         return;
    9304             :     }
    9305             : 
    9306           1 :     if (poLayer->GetGeomType() == wkbNone)
    9307             :     {
    9308           0 :         sqlite3_result_null(pContext);
    9309           0 :         return;
    9310             :     }
    9311             : 
    9312           1 :     OGREnvelope sExtent;
    9313           1 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9314             :     {
    9315           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9316             :                  "ogr_layer_Extent");
    9317           0 :         sqlite3_result_null(pContext);
    9318           0 :         return;
    9319             :     }
    9320             : 
    9321           1 :     OGRPolygon oPoly;
    9322           1 :     auto poRing = std::make_unique<OGRLinearRing>();
    9323           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9324           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MinY);
    9325           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MaxY);
    9326           1 :     poRing->addPoint(sExtent.MinX, sExtent.MaxY);
    9327           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9328           1 :     oPoly.addRing(std::move(poRing));
    9329             : 
    9330           1 :     const auto poSRS = poLayer->GetSpatialRef();
    9331           1 :     const int nSRID = poDS->GetSrsId(poSRS);
    9332           1 :     size_t nBLOBDestLen = 0;
    9333             :     GByte *pabyDestBLOB =
    9334           1 :         GPkgGeometryFromOGR(&oPoly, nSRID, nullptr, &nBLOBDestLen);
    9335           1 :     if (!pabyDestBLOB)
    9336             :     {
    9337           0 :         sqlite3_result_null(pContext);
    9338           0 :         return;
    9339             :     }
    9340           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    9341             :                         VSIFree);
    9342             : }
    9343             : 
    9344             : /************************************************************************/
    9345             : /*                     GPKG_ST_Hilbert_X_Y_TableName()                  */
    9346             : /************************************************************************/
    9347             : 
    9348           8 : static void GPKG_ST_Hilbert_X_Y_TableName(sqlite3_context *pContext,
    9349             :                                           [[maybe_unused]] int argc,
    9350             :                                           sqlite3_value **argv)
    9351             : {
    9352           8 :     CPLAssert(argc == 3);
    9353           8 :     const double dfX = sqlite3_value_double(argv[0]);
    9354           8 :     const double dfY = sqlite3_value_double(argv[1]);
    9355             : 
    9356           8 :     if (sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    9357             :     {
    9358           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9359             :                  "%s: Invalid argument type for 3rd argument. Text expected",
    9360             :                  "ST_Hilbert()");
    9361           1 :         sqlite3_result_null(pContext);
    9362           6 :         return;
    9363             :     }
    9364             : 
    9365             :     const char *pszLayerName =
    9366           7 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    9367             :     GDALGeoPackageDataset *poDS =
    9368           7 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9369           7 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9370           7 :     if (!poLayer)
    9371             :     {
    9372           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer '%s'",
    9373             :                  "ST_Hilbert()", pszLayerName);
    9374           1 :         sqlite3_result_null(pContext);
    9375           1 :         return;
    9376             :     }
    9377             : 
    9378           6 :     OGREnvelope sExtent;
    9379           6 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9380             :     {
    9381           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9382             :                  "ST_Hilbert()");
    9383           0 :         sqlite3_result_null(pContext);
    9384           0 :         return;
    9385             :     }
    9386           6 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9387           3 :           dfY <= sExtent.MaxY))
    9388             :     {
    9389           4 :         CPLError(CE_Warning, CPLE_AppDefined,
    9390             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9391             :                  dfX, dfY);
    9392           4 :         sqlite3_result_null(pContext);
    9393           4 :         return;
    9394             :     }
    9395           2 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9396             : }
    9397             : 
    9398             : /************************************************************************/
    9399             : /*                     GPKG_ST_Hilbert_Geom_BBOX()                      */
    9400             : /************************************************************************/
    9401             : 
    9402           6 : static void GPKG_ST_Hilbert_Geom_BBOX(sqlite3_context *pContext, int argc,
    9403             :                                       sqlite3_value **argv)
    9404             : {
    9405           6 :     CPLAssert(argc == 5);
    9406             :     GPkgHeader sHeader;
    9407           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    9408             :     {
    9409           1 :         sqlite3_result_null(pContext);
    9410           5 :         return;
    9411             :     }
    9412           5 :     const double dfX = (sHeader.MinX + sHeader.MaxX) / 2;
    9413           5 :     const double dfY = (sHeader.MinY + sHeader.MaxY) / 2;
    9414             : 
    9415           5 :     OGREnvelope sExtent;
    9416           5 :     sExtent.MinX = sqlite3_value_double(argv[1]);
    9417           5 :     sExtent.MinY = sqlite3_value_double(argv[2]);
    9418           5 :     sExtent.MaxX = sqlite3_value_double(argv[3]);
    9419           5 :     sExtent.MaxY = sqlite3_value_double(argv[4]);
    9420           5 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9421           2 :           dfY <= sExtent.MaxY))
    9422             :     {
    9423           4 :         CPLError(CE_Warning, CPLE_AppDefined,
    9424             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9425             :                  dfX, dfY);
    9426           4 :         sqlite3_result_null(pContext);
    9427           4 :         return;
    9428             :     }
    9429           1 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9430             : }
    9431             : 
    9432             : /************************************************************************/
    9433             : /*                     GPKG_ST_Hilbert_Geom_TableName()                 */
    9434             : /************************************************************************/
    9435             : 
    9436           4 : static void GPKG_ST_Hilbert_Geom_TableName(sqlite3_context *pContext, int argc,
    9437             :                                            sqlite3_value **argv)
    9438             : {
    9439           4 :     CPLAssert(argc == 2);
    9440             :     GPkgHeader sHeader;
    9441           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    9442             :     {
    9443           1 :         sqlite3_result_null(pContext);
    9444           3 :         return;
    9445             :     }
    9446           3 :     const double dfX = (sHeader.MinX + sHeader.MaxX) / 2;
    9447           3 :     const double dfY = (sHeader.MinY + sHeader.MaxY) / 2;
    9448             : 
    9449           3 :     if (sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9450             :     {
    9451           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9452             :                  "%s: Invalid argument type for 2nd argument. Text expected",
    9453             :                  "ST_Hilbert()");
    9454           1 :         sqlite3_result_null(pContext);
    9455           1 :         return;
    9456             :     }
    9457             : 
    9458             :     const char *pszLayerName =
    9459           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9460             :     GDALGeoPackageDataset *poDS =
    9461           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9462           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9463           2 :     if (!poLayer)
    9464             :     {
    9465           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer '%s'",
    9466             :                  "ST_Hilbert()", pszLayerName);
    9467           1 :         sqlite3_result_null(pContext);
    9468           1 :         return;
    9469             :     }
    9470             : 
    9471           1 :     OGREnvelope sExtent;
    9472           1 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9473             :     {
    9474           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9475             :                  "ST_Hilbert()");
    9476           0 :         sqlite3_result_null(pContext);
    9477           0 :         return;
    9478             :     }
    9479           1 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9480           1 :           dfY <= sExtent.MaxY))
    9481             :     {
    9482           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9483             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9484             :                  dfX, dfY);
    9485           0 :         sqlite3_result_null(pContext);
    9486           0 :         return;
    9487             :     }
    9488           1 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9489             : }
    9490             : 
    9491             : /************************************************************************/
    9492             : /*                      InstallSQLFunctions()                           */
    9493             : /************************************************************************/
    9494             : 
    9495             : #ifndef SQLITE_DETERMINISTIC
    9496             : #define SQLITE_DETERMINISTIC 0
    9497             : #endif
    9498             : 
    9499             : #ifndef SQLITE_INNOCUOUS
    9500             : #define SQLITE_INNOCUOUS 0
    9501             : #endif
    9502             : 
    9503             : #ifndef UTF8_INNOCUOUS
    9504             : #define UTF8_INNOCUOUS (SQLITE_UTF8 | SQLITE_DETERMINISTIC | SQLITE_INNOCUOUS)
    9505             : #endif
    9506             : 
    9507        2274 : void GDALGeoPackageDataset::InstallSQLFunctions()
    9508             : {
    9509        2274 :     InitSpatialite();
    9510             : 
    9511             :     // Enable SpatiaLite 4.3 GPKG mode, i.e. that SpatiaLite functions
    9512             :     // that take geometries will accept and return GPKG encoded geometries without
    9513             :     // explicit conversion.
    9514             :     // Use sqlite3_exec() instead of SQLCommand() since we don't want verbose
    9515             :     // error.
    9516        2274 :     sqlite3_exec(hDB, "SELECT EnableGpkgMode()", nullptr, nullptr, nullptr);
    9517             : 
    9518             :     /* Used by RTree Spatial Index Extension */
    9519        2274 :     sqlite3_create_function(hDB, "ST_MinX", 1, UTF8_INNOCUOUS, nullptr,
    9520             :                             OGRGeoPackageSTMinX, nullptr, nullptr);
    9521        2274 :     sqlite3_create_function(hDB, "ST_MinY", 1, UTF8_INNOCUOUS, nullptr,
    9522             :                             OGRGeoPackageSTMinY, nullptr, nullptr);
    9523        2274 :     sqlite3_create_function(hDB, "ST_MaxX", 1, UTF8_INNOCUOUS, nullptr,
    9524             :                             OGRGeoPackageSTMaxX, nullptr, nullptr);
    9525        2274 :     sqlite3_create_function(hDB, "ST_MaxY", 1, UTF8_INNOCUOUS, nullptr,
    9526             :                             OGRGeoPackageSTMaxY, nullptr, nullptr);
    9527        2274 :     sqlite3_create_function(hDB, "ST_IsEmpty", 1, UTF8_INNOCUOUS, nullptr,
    9528             :                             OGRGeoPackageSTIsEmpty, nullptr, nullptr);
    9529             : 
    9530             :     /* Used by Geometry Type Triggers Extension */
    9531        2274 :     sqlite3_create_function(hDB, "ST_GeometryType", 1, UTF8_INNOCUOUS, nullptr,
    9532             :                             OGRGeoPackageSTGeometryType, nullptr, nullptr);
    9533        2274 :     sqlite3_create_function(hDB, "GPKG_IsAssignable", 2, UTF8_INNOCUOUS,
    9534             :                             nullptr, OGRGeoPackageGPKGIsAssignable, nullptr,
    9535             :                             nullptr);
    9536             : 
    9537             :     /* Used by Geometry SRS ID Triggers Extension */
    9538        2274 :     sqlite3_create_function(hDB, "ST_SRID", 1, UTF8_INNOCUOUS, nullptr,
    9539             :                             OGRGeoPackageSTSRID, nullptr, nullptr);
    9540             : 
    9541             :     /* Spatialite-like functions */
    9542        2274 :     sqlite3_create_function(hDB, "CreateSpatialIndex", 2, SQLITE_UTF8, this,
    9543             :                             OGRGeoPackageCreateSpatialIndex, nullptr, nullptr);
    9544        2274 :     sqlite3_create_function(hDB, "DisableSpatialIndex", 2, SQLITE_UTF8, this,
    9545             :                             OGRGeoPackageDisableSpatialIndex, nullptr, nullptr);
    9546        2274 :     sqlite3_create_function(hDB, "HasSpatialIndex", 2, SQLITE_UTF8, this,
    9547             :                             OGRGeoPackageHasSpatialIndex, nullptr, nullptr);
    9548             : 
    9549             :     // HSTORE functions
    9550        2274 :     sqlite3_create_function(hDB, "hstore_get_value", 2, UTF8_INNOCUOUS, nullptr,
    9551             :                             GPKG_hstore_get_value, nullptr, nullptr);
    9552             : 
    9553             :     // Override a few Spatialite functions to work with gpkg_spatial_ref_sys
    9554        2274 :     sqlite3_create_function(hDB, "ST_Transform", 2, UTF8_INNOCUOUS, this,
    9555             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9556        2274 :     sqlite3_create_function(hDB, "Transform", 2, UTF8_INNOCUOUS, this,
    9557             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9558        2274 :     sqlite3_create_function(hDB, "SridFromAuthCRS", 2, SQLITE_UTF8, this,
    9559             :                             OGRGeoPackageSridFromAuthCRS, nullptr, nullptr);
    9560             : 
    9561        2274 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9562             :                             OGRGeoPackageSTEnvelopesIntersectsTwoParams,
    9563             :                             nullptr, nullptr);
    9564        2274 :     sqlite3_create_function(
    9565             :         hDB, "ST_EnvelopesIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9566             :         OGRGeoPackageSTEnvelopesIntersectsTwoParams, nullptr, nullptr);
    9567             : 
    9568        2274 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 5, UTF8_INNOCUOUS, nullptr,
    9569             :                             OGRGeoPackageSTEnvelopesIntersects, nullptr,
    9570             :                             nullptr);
    9571        2274 :     sqlite3_create_function(hDB, "ST_EnvelopesIntersects", 5, UTF8_INNOCUOUS,
    9572             :                             nullptr, OGRGeoPackageSTEnvelopesIntersects,
    9573             :                             nullptr, nullptr);
    9574             : 
    9575             :     // Implementation that directly hacks the GeoPackage geometry blob header
    9576        2274 :     sqlite3_create_function(hDB, "SetSRID", 2, UTF8_INNOCUOUS, nullptr,
    9577             :                             OGRGeoPackageSetSRID, nullptr, nullptr);
    9578             : 
    9579             :     // GDAL specific function
    9580        2274 :     sqlite3_create_function(hDB, "ImportFromEPSG", 1, SQLITE_UTF8, this,
    9581             :                             OGRGeoPackageImportFromEPSG, nullptr, nullptr);
    9582             : 
    9583             :     // May be used by ogrmerge.py
    9584        2274 :     sqlite3_create_function(hDB, "RegisterGeometryExtension", 3, SQLITE_UTF8,
    9585             :                             this, OGRGeoPackageRegisterGeometryExtension,
    9586             :                             nullptr, nullptr);
    9587             : 
    9588        2274 :     if (OGRGeometryFactory::haveGEOS())
    9589             :     {
    9590        2274 :         sqlite3_create_function(hDB, "ST_MakeValid", 1, UTF8_INNOCUOUS, nullptr,
    9591             :                                 OGRGeoPackageSTMakeValid, nullptr, nullptr);
    9592             :     }
    9593             : 
    9594        2274 :     sqlite3_create_function(hDB, "ST_Length", 1, UTF8_INNOCUOUS, nullptr,
    9595             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9596             :                             nullptr);
    9597        2274 :     sqlite3_create_function(hDB, "ST_Length", 2, UTF8_INNOCUOUS, this,
    9598             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9599             :                             nullptr);
    9600             : 
    9601        2274 :     sqlite3_create_function(hDB, "ST_Area", 1, UTF8_INNOCUOUS, nullptr,
    9602             :                             OGRGeoPackageSTArea, nullptr, nullptr);
    9603        2274 :     sqlite3_create_function(hDB, "ST_Area", 2, UTF8_INNOCUOUS, this,
    9604             :                             OGRGeoPackageGeodesicArea, nullptr, nullptr);
    9605             : 
    9606             :     // Debug functions
    9607        2274 :     if (CPLTestBool(CPLGetConfigOption("GPKG_DEBUG", "FALSE")))
    9608             :     {
    9609         422 :         sqlite3_create_function(hDB, "GDAL_GetMimeType", 1,
    9610             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9611             :                                 GPKG_GDAL_GetMimeType, nullptr, nullptr);
    9612         422 :         sqlite3_create_function(hDB, "GDAL_GetBandCount", 1,
    9613             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9614             :                                 GPKG_GDAL_GetBandCount, nullptr, nullptr);
    9615         422 :         sqlite3_create_function(hDB, "GDAL_HasColorTable", 1,
    9616             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9617             :                                 GPKG_GDAL_HasColorTable, nullptr, nullptr);
    9618             :     }
    9619             : 
    9620        2274 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 5, SQLITE_UTF8,
    9621             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9622             :                             nullptr);
    9623        2274 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 6, SQLITE_UTF8,
    9624             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9625             :                             nullptr);
    9626             : 
    9627             :     // Function from VirtualOGR
    9628        2274 :     sqlite3_create_function(hDB, "ogr_layer_Extent", 1, SQLITE_UTF8, this,
    9629             :                             GPKG_ogr_layer_Extent, nullptr, nullptr);
    9630             : 
    9631        2274 :     m_pSQLFunctionData = OGRSQLiteRegisterSQLFunctionsCommon(hDB);
    9632             : 
    9633             :     // ST_Hilbert() inspired from https://duckdb.org/docs/stable/core_extensions/spatial/functions#st_hilbert
    9634             :     // Override the generic version of OGRSQLiteRegisterSQLFunctionsCommon()
    9635             : 
    9636             :     // X,Y,table_name
    9637        2274 :     sqlite3_create_function(hDB, "ST_Hilbert", 2 + 1, UTF8_INNOCUOUS, this,
    9638             :                             GPKG_ST_Hilbert_X_Y_TableName, nullptr, nullptr);
    9639             : 
    9640             :     // geometry,minX,minY,maxX,maxY
    9641        2274 :     sqlite3_create_function(hDB, "ST_Hilbert", 1 + 4, UTF8_INNOCUOUS, nullptr,
    9642             :                             GPKG_ST_Hilbert_Geom_BBOX, nullptr, nullptr);
    9643             : 
    9644             :     // geometry,table_name
    9645        2274 :     sqlite3_create_function(hDB, "ST_Hilbert", 1 + 1, UTF8_INNOCUOUS, this,
    9646             :                             GPKG_ST_Hilbert_Geom_TableName, nullptr, nullptr);
    9647        2274 : }
    9648             : 
    9649             : /************************************************************************/
    9650             : /*                         OpenOrCreateDB()                             */
    9651             : /************************************************************************/
    9652             : 
    9653        2278 : bool GDALGeoPackageDataset::OpenOrCreateDB(int flags)
    9654             : {
    9655        2278 :     const bool bSuccess = OGRSQLiteBaseDataSource::OpenOrCreateDB(
    9656             :         flags, /*bRegisterOGR2SQLiteExtensions=*/false,
    9657             :         /*bLoadExtensions=*/true);
    9658        2278 :     if (!bSuccess)
    9659           9 :         return false;
    9660             : 
    9661             :     // Turning on recursive_triggers is needed so that DELETE triggers fire
    9662             :     // in a INSERT OR REPLACE statement. In particular this is needed to
    9663             :     // make sure gpkg_ogr_contents.feature_count is properly updated.
    9664        2269 :     SQLCommand(hDB, "PRAGMA recursive_triggers = 1");
    9665             : 
    9666        2269 :     InstallSQLFunctions();
    9667             : 
    9668             :     const char *pszSqlitePragma =
    9669        2269 :         CPLGetConfigOption("OGR_SQLITE_PRAGMA", nullptr);
    9670        2269 :     OGRErr eErr = OGRERR_NONE;
    9671           6 :     if ((!pszSqlitePragma || !strstr(pszSqlitePragma, "trusted_schema")) &&
    9672             :         // Older sqlite versions don't have this pragma
    9673        4544 :         SQLGetInteger(hDB, "PRAGMA trusted_schema", &eErr) == 0 &&
    9674        2269 :         eErr == OGRERR_NONE)
    9675             :     {
    9676        2269 :         bool bNeedsTrustedSchema = false;
    9677             : 
    9678             :         // Current SQLite versions require PRAGMA trusted_schema = 1 to be
    9679             :         // able to use the RTree from triggers, which is only needed when
    9680             :         // modifying the RTree.
    9681        5573 :         if (((flags & SQLITE_OPEN_READWRITE) != 0 ||
    9682        3503 :              (flags & SQLITE_OPEN_CREATE) != 0) &&
    9683        1234 :             OGRSQLiteRTreeRequiresTrustedSchemaOn())
    9684             :         {
    9685        1234 :             bNeedsTrustedSchema = true;
    9686             :         }
    9687             : 
    9688             : #ifdef HAVE_SPATIALITE
    9689             :         // Spatialite <= 5.1.0 doesn't declare its functions as SQLITE_INNOCUOUS
    9690        1035 :         if (!bNeedsTrustedSchema && HasExtensionsTable() &&
    9691         944 :             SQLGetInteger(
    9692             :                 hDB,
    9693             :                 "SELECT 1 FROM gpkg_extensions WHERE "
    9694             :                 "extension_name ='gdal_spatialite_computed_geom_column'",
    9695           1 :                 nullptr) == 1 &&
    9696        3304 :             SpatialiteRequiresTrustedSchemaOn() && AreSpatialiteTriggersSafe())
    9697             :         {
    9698           1 :             bNeedsTrustedSchema = true;
    9699             :         }
    9700             : #endif
    9701             : 
    9702        2269 :         if (bNeedsTrustedSchema)
    9703             :         {
    9704        1235 :             CPLDebug("GPKG", "Setting PRAGMA trusted_schema = 1");
    9705        1235 :             SQLCommand(hDB, "PRAGMA trusted_schema = 1");
    9706             :         }
    9707             :     }
    9708             : 
    9709             :     const char *pszPreludeStatements =
    9710        2269 :         CSLFetchNameValue(papszOpenOptions, "PRELUDE_STATEMENTS");
    9711        2269 :     if (pszPreludeStatements)
    9712             :     {
    9713           2 :         if (SQLCommand(hDB, pszPreludeStatements) != OGRERR_NONE)
    9714           0 :             return false;
    9715             :     }
    9716             : 
    9717        2269 :     return true;
    9718             : }
    9719             : 
    9720             : /************************************************************************/
    9721             : /*                   GetLayerWithGetSpatialWhereByName()                */
    9722             : /************************************************************************/
    9723             : 
    9724             : std::pair<OGRLayer *, IOGRSQLiteGetSpatialWhere *>
    9725          90 : GDALGeoPackageDataset::GetLayerWithGetSpatialWhereByName(const char *pszName)
    9726             : {
    9727             :     OGRGeoPackageLayer *poRet =
    9728          90 :         cpl::down_cast<OGRGeoPackageLayer *>(GetLayerByName(pszName));
    9729          90 :     return std::pair(poRet, poRet);
    9730             : }
    9731             : 
    9732             : /************************************************************************/
    9733             : /*                       CommitTransaction()                            */
    9734             : /************************************************************************/
    9735             : 
    9736         332 : OGRErr GDALGeoPackageDataset::CommitTransaction()
    9737             : 
    9738             : {
    9739         332 :     if (m_nSoftTransactionLevel == 1)
    9740             :     {
    9741         326 :         FlushMetadata();
    9742         703 :         for (auto &poLayer : m_apoLayers)
    9743             :         {
    9744         377 :             poLayer->DoJobAtTransactionCommit();
    9745             :         }
    9746             :     }
    9747             : 
    9748         332 :     return OGRSQLiteBaseDataSource::CommitTransaction();
    9749             : }
    9750             : 
    9751             : /************************************************************************/
    9752             : /*                     RollbackTransaction()                            */
    9753             : /************************************************************************/
    9754             : 
    9755          35 : OGRErr GDALGeoPackageDataset::RollbackTransaction()
    9756             : 
    9757             : {
    9758             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9759          70 :     std::vector<bool> abAddTriggers;
    9760          35 :     std::vector<bool> abTriggersDeletedInTransaction;
    9761             : #endif
    9762          35 :     if (m_nSoftTransactionLevel == 1)
    9763             :     {
    9764          34 :         FlushMetadata();
    9765          70 :         for (auto &poLayer : m_apoLayers)
    9766             :         {
    9767             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9768          36 :             abAddTriggers.push_back(poLayer->GetAddOGRFeatureCountTriggers());
    9769          36 :             abTriggersDeletedInTransaction.push_back(
    9770          36 :                 poLayer->GetOGRFeatureCountTriggersDeletedInTransaction());
    9771          36 :             poLayer->SetAddOGRFeatureCountTriggers(false);
    9772             : #endif
    9773          36 :             poLayer->DoJobAtTransactionRollback();
    9774             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9775          36 :             poLayer->DisableFeatureCount();
    9776             : #endif
    9777             :         }
    9778             :     }
    9779             : 
    9780          35 :     const OGRErr eErr = OGRSQLiteBaseDataSource::RollbackTransaction();
    9781             : 
    9782             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9783          35 :     if (!abAddTriggers.empty())
    9784             :     {
    9785          68 :         for (size_t i = 0; i < m_apoLayers.size(); ++i)
    9786             :         {
    9787          36 :             auto &poLayer = m_apoLayers[i];
    9788          36 :             if (abTriggersDeletedInTransaction[i])
    9789             :             {
    9790           7 :                 poLayer->SetOGRFeatureCountTriggersEnabled(true);
    9791             :             }
    9792             :             else
    9793             :             {
    9794          29 :                 poLayer->SetAddOGRFeatureCountTriggers(abAddTriggers[i]);
    9795             :             }
    9796             :         }
    9797             :     }
    9798             : #endif
    9799          70 :     return eErr;
    9800             : }
    9801             : 
    9802             : /************************************************************************/
    9803             : /*                       GetGeometryTypeString()                        */
    9804             : /************************************************************************/
    9805             : 
    9806             : const char *
    9807        1621 : GDALGeoPackageDataset::GetGeometryTypeString(OGRwkbGeometryType eType)
    9808             : {
    9809        1621 :     const char *pszGPKGGeomType = OGRToOGCGeomType(eType);
    9810        1633 :     if (EQUAL(pszGPKGGeomType, "GEOMETRYCOLLECTION") &&
    9811          12 :         CPLTestBool(CPLGetConfigOption("OGR_GPKG_GEOMCOLLECTION", "NO")))
    9812             :     {
    9813           0 :         pszGPKGGeomType = "GEOMCOLLECTION";
    9814             :     }
    9815        1621 :     return pszGPKGGeomType;
    9816             : }
    9817             : 
    9818             : /************************************************************************/
    9819             : /*                           GetFieldDomainNames()                      */
    9820             : /************************************************************************/
    9821             : 
    9822             : std::vector<std::string>
    9823          12 : GDALGeoPackageDataset::GetFieldDomainNames(CSLConstList) const
    9824             : {
    9825          12 :     if (!HasDataColumnConstraintsTable())
    9826           3 :         return std::vector<std::string>();
    9827             : 
    9828          18 :     std::vector<std::string> oDomainNamesList;
    9829             : 
    9830           9 :     std::unique_ptr<SQLResult> oResultTable;
    9831             :     {
    9832             :         std::string osSQL =
    9833             :             "SELECT DISTINCT constraint_name "
    9834             :             "FROM gpkg_data_column_constraints "
    9835             :             "WHERE constraint_name NOT LIKE '_%_domain_description' "
    9836             :             "ORDER BY constraint_name "
    9837           9 :             "LIMIT 10000"  // to avoid denial of service
    9838             :             ;
    9839           9 :         oResultTable = SQLQuery(hDB, osSQL.c_str());
    9840           9 :         if (!oResultTable)
    9841           0 :             return oDomainNamesList;
    9842             :     }
    9843             : 
    9844           9 :     if (oResultTable->RowCount() == 10000)
    9845             :     {
    9846           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9847             :                  "Number of rows returned for field domain names has been "
    9848             :                  "truncated.");
    9849             :     }
    9850           9 :     else if (oResultTable->RowCount() > 0)
    9851             :     {
    9852           8 :         oDomainNamesList.reserve(oResultTable->RowCount());
    9853         105 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    9854             :         {
    9855          97 :             const char *pszConstraintName = oResultTable->GetValue(0, i);
    9856          97 :             if (!pszConstraintName)
    9857           0 :                 continue;
    9858             : 
    9859          97 :             oDomainNamesList.emplace_back(pszConstraintName);
    9860             :         }
    9861             :     }
    9862             : 
    9863           9 :     return oDomainNamesList;
    9864             : }
    9865             : 
    9866             : /************************************************************************/
    9867             : /*                           GetFieldDomain()                           */
    9868             : /************************************************************************/
    9869             : 
    9870             : const OGRFieldDomain *
    9871         138 : GDALGeoPackageDataset::GetFieldDomain(const std::string &name) const
    9872             : {
    9873         138 :     const auto baseRet = GDALDataset::GetFieldDomain(name);
    9874         138 :     if (baseRet)
    9875          43 :         return baseRet;
    9876             : 
    9877          95 :     if (!HasDataColumnConstraintsTable())
    9878           4 :         return nullptr;
    9879             : 
    9880          91 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
    9881          91 :     const char *min_is_inclusive =
    9882          91 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
    9883          91 :     const char *max_is_inclusive =
    9884          91 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
    9885             : 
    9886          91 :     std::unique_ptr<SQLResult> oResultTable;
    9887             :     // Note: for coded domains, we use a little trick by using a dummy
    9888             :     // _{domainname}_domain_description enum that has a single entry whose
    9889             :     // description is the description of the main domain.
    9890             :     {
    9891          91 :         char *pszSQL = sqlite3_mprintf(
    9892             :             "SELECT constraint_type, value, min, %s, "
    9893             :             "max, %s, description, constraint_name "
    9894             :             "FROM gpkg_data_column_constraints "
    9895             :             "WHERE constraint_name IN ('%q', "
    9896             :             "'_%q_domain_description') "
    9897             :             "AND length(constraint_type) < 100 "  // to
    9898             :                                                   // avoid
    9899             :                                                   // denial
    9900             :                                                   // of
    9901             :                                                   // service
    9902             :             "AND (value IS NULL OR length(value) < "
    9903             :             "10000) "  // to avoid denial
    9904             :                        // of service
    9905             :             "AND (description IS NULL OR "
    9906             :             "length(description) < 10000) "  // to
    9907             :                                              // avoid
    9908             :                                              // denial
    9909             :                                              // of
    9910             :                                              // service
    9911             :             "ORDER BY value "
    9912             :             "LIMIT 10000",  // to avoid denial of
    9913             :                             // service
    9914             :             min_is_inclusive, max_is_inclusive, name.c_str(), name.c_str());
    9915          91 :         oResultTable = SQLQuery(hDB, pszSQL);
    9916          91 :         sqlite3_free(pszSQL);
    9917          91 :         if (!oResultTable)
    9918           0 :             return nullptr;
    9919             :     }
    9920          91 :     if (oResultTable->RowCount() == 0)
    9921             :     {
    9922          33 :         return nullptr;
    9923             :     }
    9924          58 :     if (oResultTable->RowCount() == 10000)
    9925             :     {
    9926           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9927             :                  "Number of rows returned for field domain %s has been "
    9928             :                  "truncated.",
    9929             :                  name.c_str());
    9930             :     }
    9931             : 
    9932             :     // Try to find the field domain data type from fields that implement it
    9933          58 :     int nFieldType = -1;
    9934          58 :     OGRFieldSubType eSubType = OFSTNone;
    9935          58 :     if (HasDataColumnsTable())
    9936             :     {
    9937          53 :         char *pszSQL = sqlite3_mprintf(
    9938             :             "SELECT table_name, column_name FROM gpkg_data_columns WHERE "
    9939             :             "constraint_name = '%q' LIMIT 10",
    9940             :             name.c_str());
    9941         106 :         auto oResultTable2 = SQLQuery(hDB, pszSQL);
    9942          53 :         sqlite3_free(pszSQL);
    9943          53 :         if (oResultTable2 && oResultTable2->RowCount() >= 1)
    9944             :         {
    9945          58 :             for (int iRecord = 0; iRecord < oResultTable2->RowCount();
    9946             :                  iRecord++)
    9947             :             {
    9948          29 :                 const char *pszTableName = oResultTable2->GetValue(0, iRecord);
    9949          29 :                 const char *pszColumnName = oResultTable2->GetValue(1, iRecord);
    9950          29 :                 if (pszTableName == nullptr || pszColumnName == nullptr)
    9951           0 :                     continue;
    9952             :                 OGRLayer *poLayer =
    9953          58 :                     const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    9954          29 :                         pszTableName);
    9955          29 :                 if (poLayer)
    9956             :                 {
    9957          29 :                     const auto poFDefn = poLayer->GetLayerDefn();
    9958          29 :                     int nIdx = poFDefn->GetFieldIndex(pszColumnName);
    9959          29 :                     if (nIdx >= 0)
    9960             :                     {
    9961          29 :                         const auto poFieldDefn = poFDefn->GetFieldDefn(nIdx);
    9962          29 :                         const auto eType = poFieldDefn->GetType();
    9963          29 :                         if (nFieldType < 0)
    9964             :                         {
    9965          29 :                             nFieldType = eType;
    9966          29 :                             eSubType = poFieldDefn->GetSubType();
    9967             :                         }
    9968           0 :                         else if ((eType == OFTInteger64 || eType == OFTReal) &&
    9969             :                                  nFieldType == OFTInteger)
    9970             :                         {
    9971             :                             // ok
    9972             :                         }
    9973           0 :                         else if (eType == OFTInteger &&
    9974           0 :                                  (nFieldType == OFTInteger64 ||
    9975             :                                   nFieldType == OFTReal))
    9976             :                         {
    9977           0 :                             nFieldType = OFTInteger;
    9978           0 :                             eSubType = OFSTNone;
    9979             :                         }
    9980           0 :                         else if (nFieldType != eType)
    9981             :                         {
    9982           0 :                             nFieldType = -1;
    9983           0 :                             eSubType = OFSTNone;
    9984           0 :                             break;
    9985             :                         }
    9986             :                     }
    9987             :                 }
    9988             :             }
    9989             :         }
    9990             :     }
    9991             : 
    9992          58 :     std::unique_ptr<OGRFieldDomain> poDomain;
    9993         116 :     std::vector<OGRCodedValue> asValues;
    9994          58 :     bool error = false;
    9995         116 :     CPLString osLastConstraintType;
    9996          58 :     int nFieldTypeFromEnumCode = -1;
    9997         116 :     std::string osConstraintDescription;
    9998         116 :     std::string osDescrConstraintName("_");
    9999          58 :     osDescrConstraintName += name;
   10000          58 :     osDescrConstraintName += "_domain_description";
   10001         145 :     for (int iRecord = 0; iRecord < oResultTable->RowCount(); iRecord++)
   10002             :     {
   10003          91 :         const char *pszConstraintType = oResultTable->GetValue(0, iRecord);
   10004          91 :         if (pszConstraintType == nullptr)
   10005           2 :             continue;
   10006          91 :         const char *pszValue = oResultTable->GetValue(1, iRecord);
   10007          91 :         const char *pszMin = oResultTable->GetValue(2, iRecord);
   10008             :         const bool bIsMinIncluded =
   10009          91 :             oResultTable->GetValueAsInteger(3, iRecord) == 1;
   10010          91 :         const char *pszMax = oResultTable->GetValue(4, iRecord);
   10011             :         const bool bIsMaxIncluded =
   10012          91 :             oResultTable->GetValueAsInteger(5, iRecord) == 1;
   10013          91 :         const char *pszDescription = oResultTable->GetValue(6, iRecord);
   10014          91 :         const char *pszConstraintName = oResultTable->GetValue(7, iRecord);
   10015             : 
   10016          91 :         if (!osLastConstraintType.empty() && osLastConstraintType != "enum")
   10017             :         {
   10018           1 :             CPLError(CE_Failure, CPLE_AppDefined,
   10019             :                      "Only constraint of type 'enum' can have multiple rows");
   10020           1 :             error = true;
   10021           4 :             break;
   10022             :         }
   10023             : 
   10024          90 :         if (strcmp(pszConstraintType, "enum") == 0)
   10025             :         {
   10026          63 :             if (pszValue == nullptr)
   10027             :             {
   10028           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10029             :                          "NULL in 'value' column of enumeration");
   10030           1 :                 error = true;
   10031           1 :                 break;
   10032             :             }
   10033          62 :             if (osDescrConstraintName == pszConstraintName)
   10034             :             {
   10035           2 :                 if (pszDescription)
   10036             :                 {
   10037           2 :                     osConstraintDescription = pszDescription;
   10038             :                 }
   10039           2 :                 continue;
   10040             :             }
   10041          60 :             if (asValues.empty())
   10042             :             {
   10043          30 :                 asValues.reserve(oResultTable->RowCount() + 1);
   10044             :             }
   10045             :             OGRCodedValue cv;
   10046             :             // intended: the 'value' column in GPKG is actually the code
   10047          60 :             cv.pszCode = VSI_STRDUP_VERBOSE(pszValue);
   10048          60 :             if (cv.pszCode == nullptr)
   10049             :             {
   10050           0 :                 error = true;
   10051           0 :                 break;
   10052             :             }
   10053          60 :             if (pszDescription)
   10054             :             {
   10055          48 :                 cv.pszValue = VSI_STRDUP_VERBOSE(pszDescription);
   10056          48 :                 if (cv.pszValue == nullptr)
   10057             :                 {
   10058           0 :                     VSIFree(cv.pszCode);
   10059           0 :                     error = true;
   10060           0 :                     break;
   10061             :                 }
   10062             :             }
   10063             :             else
   10064             :             {
   10065          12 :                 cv.pszValue = nullptr;
   10066             :             }
   10067             : 
   10068             :             // If we can't get the data type from field definition, guess it
   10069             :             // from code.
   10070          60 :             if (nFieldType < 0 && nFieldTypeFromEnumCode != OFTString)
   10071             :             {
   10072          36 :                 switch (CPLGetValueType(cv.pszCode))
   10073             :                 {
   10074          26 :                     case CPL_VALUE_INTEGER:
   10075             :                     {
   10076          26 :                         if (nFieldTypeFromEnumCode != OFTReal &&
   10077             :                             nFieldTypeFromEnumCode != OFTInteger64)
   10078             :                         {
   10079          18 :                             const auto nVal = CPLAtoGIntBig(cv.pszCode);
   10080          34 :                             if (nVal < std::numeric_limits<int>::min() ||
   10081          16 :                                 nVal > std::numeric_limits<int>::max())
   10082             :                             {
   10083           6 :                                 nFieldTypeFromEnumCode = OFTInteger64;
   10084             :                             }
   10085             :                             else
   10086             :                             {
   10087          12 :                                 nFieldTypeFromEnumCode = OFTInteger;
   10088             :                             }
   10089             :                         }
   10090          26 :                         break;
   10091             :                     }
   10092             : 
   10093           6 :                     case CPL_VALUE_REAL:
   10094           6 :                         nFieldTypeFromEnumCode = OFTReal;
   10095           6 :                         break;
   10096             : 
   10097           4 :                     case CPL_VALUE_STRING:
   10098           4 :                         nFieldTypeFromEnumCode = OFTString;
   10099           4 :                         break;
   10100             :                 }
   10101             :             }
   10102             : 
   10103          60 :             asValues.emplace_back(cv);
   10104             :         }
   10105          27 :         else if (strcmp(pszConstraintType, "range") == 0)
   10106             :         {
   10107             :             OGRField sMin;
   10108             :             OGRField sMax;
   10109          20 :             OGR_RawField_SetUnset(&sMin);
   10110          20 :             OGR_RawField_SetUnset(&sMax);
   10111          20 :             if (nFieldType != OFTInteger && nFieldType != OFTInteger64)
   10112          11 :                 nFieldType = OFTReal;
   10113          39 :             if (pszMin != nullptr &&
   10114          19 :                 CPLAtof(pszMin) != -std::numeric_limits<double>::infinity())
   10115             :             {
   10116          15 :                 if (nFieldType == OFTInteger)
   10117           6 :                     sMin.Integer = atoi(pszMin);
   10118           9 :                 else if (nFieldType == OFTInteger64)
   10119           3 :                     sMin.Integer64 = CPLAtoGIntBig(pszMin);
   10120             :                 else /* if( nFieldType == OFTReal ) */
   10121           6 :                     sMin.Real = CPLAtof(pszMin);
   10122             :             }
   10123          39 :             if (pszMax != nullptr &&
   10124          19 :                 CPLAtof(pszMax) != std::numeric_limits<double>::infinity())
   10125             :             {
   10126          15 :                 if (nFieldType == OFTInteger)
   10127           6 :                     sMax.Integer = atoi(pszMax);
   10128           9 :                 else if (nFieldType == OFTInteger64)
   10129           3 :                     sMax.Integer64 = CPLAtoGIntBig(pszMax);
   10130             :                 else /* if( nFieldType == OFTReal ) */
   10131           6 :                     sMax.Real = CPLAtof(pszMax);
   10132             :             }
   10133          20 :             poDomain = std::make_unique<OGRRangeFieldDomain>(
   10134          20 :                 name, pszDescription ? pszDescription : "",
   10135          40 :                 static_cast<OGRFieldType>(nFieldType), eSubType, sMin,
   10136          20 :                 bIsMinIncluded, sMax, bIsMaxIncluded);
   10137             :         }
   10138           7 :         else if (strcmp(pszConstraintType, "glob") == 0)
   10139             :         {
   10140           6 :             if (pszValue == nullptr)
   10141             :             {
   10142           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10143             :                          "NULL in 'value' column of glob");
   10144           1 :                 error = true;
   10145           1 :                 break;
   10146             :             }
   10147           5 :             if (nFieldType < 0)
   10148           1 :                 nFieldType = OFTString;
   10149           5 :             poDomain = std::make_unique<OGRGlobFieldDomain>(
   10150           5 :                 name, pszDescription ? pszDescription : "",
   10151          15 :                 static_cast<OGRFieldType>(nFieldType), eSubType, pszValue);
   10152             :         }
   10153             :         else
   10154             :         {
   10155           1 :             CPLError(CE_Failure, CPLE_AppDefined,
   10156             :                      "Unhandled constraint_type: %s", pszConstraintType);
   10157           1 :             error = true;
   10158           1 :             break;
   10159             :         }
   10160             : 
   10161          85 :         osLastConstraintType = pszConstraintType;
   10162             :     }
   10163             : 
   10164          58 :     if (!asValues.empty())
   10165             :     {
   10166          30 :         if (nFieldType < 0)
   10167          18 :             nFieldType = nFieldTypeFromEnumCode;
   10168          30 :         poDomain = std::make_unique<OGRCodedFieldDomain>(
   10169             :             name, osConstraintDescription,
   10170          60 :             static_cast<OGRFieldType>(nFieldType), eSubType,
   10171          60 :             std::move(asValues));
   10172             :     }
   10173             : 
   10174          58 :     if (error)
   10175             :     {
   10176           4 :         return nullptr;
   10177             :     }
   10178             : 
   10179          54 :     m_oMapFieldDomains[name] = std::move(poDomain);
   10180          54 :     return GDALDataset::GetFieldDomain(name);
   10181             : }
   10182             : 
   10183             : /************************************************************************/
   10184             : /*                           AddFieldDomain()                           */
   10185             : /************************************************************************/
   10186             : 
   10187          19 : bool GDALGeoPackageDataset::AddFieldDomain(
   10188             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10189             : {
   10190          38 :     const std::string domainName(domain->GetName());
   10191          19 :     if (!GetUpdate())
   10192             :     {
   10193           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10194             :                  "AddFieldDomain() not supported on read-only dataset");
   10195           0 :         return false;
   10196             :     }
   10197          19 :     if (GetFieldDomain(domainName) != nullptr)
   10198             :     {
   10199           1 :         failureReason = "A domain of identical name already exists";
   10200           1 :         return false;
   10201             :     }
   10202          18 :     if (!CreateColumnsTableAndColumnConstraintsTablesIfNecessary())
   10203           0 :         return false;
   10204             : 
   10205          18 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
   10206          18 :     const char *min_is_inclusive =
   10207          18 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
   10208          18 :     const char *max_is_inclusive =
   10209          18 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
   10210             : 
   10211          18 :     const auto &osDescription = domain->GetDescription();
   10212          18 :     switch (domain->GetDomainType())
   10213             :     {
   10214          11 :         case OFDT_CODED:
   10215             :         {
   10216             :             const auto poCodedDomain =
   10217          11 :                 cpl::down_cast<const OGRCodedFieldDomain *>(domain.get());
   10218          11 :             if (!osDescription.empty())
   10219             :             {
   10220             :                 // We use a little trick by using a dummy
   10221             :                 // _{domainname}_domain_description enum that has a single
   10222             :                 // entry whose description is the description of the main
   10223             :                 // domain.
   10224           1 :                 char *pszSQL = sqlite3_mprintf(
   10225             :                     "INSERT INTO gpkg_data_column_constraints ("
   10226             :                     "constraint_name, constraint_type, value, "
   10227             :                     "min, %s, max, %s, "
   10228             :                     "description) VALUES ("
   10229             :                     "'_%q_domain_description', 'enum', '', NULL, NULL, NULL, "
   10230             :                     "NULL, %Q)",
   10231             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10232             :                     osDescription.c_str());
   10233           1 :                 CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
   10234           1 :                 sqlite3_free(pszSQL);
   10235             :             }
   10236          11 :             const auto &enumeration = poCodedDomain->GetEnumeration();
   10237          33 :             for (int i = 0; enumeration[i].pszCode != nullptr; ++i)
   10238             :             {
   10239          22 :                 char *pszSQL = sqlite3_mprintf(
   10240             :                     "INSERT INTO gpkg_data_column_constraints ("
   10241             :                     "constraint_name, constraint_type, value, "
   10242             :                     "min, %s, max, %s, "
   10243             :                     "description) VALUES ("
   10244             :                     "'%q', 'enum', '%q', NULL, NULL, NULL, NULL, %Q)",
   10245             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10246          22 :                     enumeration[i].pszCode, enumeration[i].pszValue);
   10247          22 :                 bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10248          22 :                 sqlite3_free(pszSQL);
   10249          22 :                 if (!ok)
   10250           0 :                     return false;
   10251             :             }
   10252          11 :             break;
   10253             :         }
   10254             : 
   10255           6 :         case OFDT_RANGE:
   10256             :         {
   10257             :             const auto poRangeDomain =
   10258           6 :                 cpl::down_cast<const OGRRangeFieldDomain *>(domain.get());
   10259           6 :             const auto eFieldType = poRangeDomain->GetFieldType();
   10260           6 :             if (eFieldType != OFTInteger && eFieldType != OFTInteger64 &&
   10261             :                 eFieldType != OFTReal)
   10262             :             {
   10263             :                 failureReason = "Only range domains of numeric type are "
   10264           0 :                                 "supported in GeoPackage";
   10265           0 :                 return false;
   10266             :             }
   10267             : 
   10268           6 :             double dfMin = -std::numeric_limits<double>::infinity();
   10269           6 :             double dfMax = std::numeric_limits<double>::infinity();
   10270           6 :             bool bMinIsInclusive = true;
   10271           6 :             const auto &sMin = poRangeDomain->GetMin(bMinIsInclusive);
   10272           6 :             bool bMaxIsInclusive = true;
   10273           6 :             const auto &sMax = poRangeDomain->GetMax(bMaxIsInclusive);
   10274           6 :             if (eFieldType == OFTInteger)
   10275             :             {
   10276           2 :                 if (!OGR_RawField_IsUnset(&sMin))
   10277           2 :                     dfMin = sMin.Integer;
   10278           2 :                 if (!OGR_RawField_IsUnset(&sMax))
   10279           2 :                     dfMax = sMax.Integer;
   10280             :             }
   10281           4 :             else if (eFieldType == OFTInteger64)
   10282             :             {
   10283           1 :                 if (!OGR_RawField_IsUnset(&sMin))
   10284           1 :                     dfMin = static_cast<double>(sMin.Integer64);
   10285           1 :                 if (!OGR_RawField_IsUnset(&sMax))
   10286           1 :                     dfMax = static_cast<double>(sMax.Integer64);
   10287             :             }
   10288             :             else /* if( eFieldType == OFTReal ) */
   10289             :             {
   10290           3 :                 if (!OGR_RawField_IsUnset(&sMin))
   10291           3 :                     dfMin = sMin.Real;
   10292           3 :                 if (!OGR_RawField_IsUnset(&sMax))
   10293           3 :                     dfMax = sMax.Real;
   10294             :             }
   10295             : 
   10296           6 :             sqlite3_stmt *hInsertStmt = nullptr;
   10297             :             const char *pszSQL =
   10298           6 :                 CPLSPrintf("INSERT INTO gpkg_data_column_constraints ("
   10299             :                            "constraint_name, constraint_type, value, "
   10300             :                            "min, %s, max, %s, "
   10301             :                            "description) VALUES ("
   10302             :                            "?, 'range', NULL, ?, ?, ?, ?, ?)",
   10303             :                            min_is_inclusive, max_is_inclusive);
   10304           6 :             if (SQLPrepareWithError(hDB, pszSQL, -1, &hInsertStmt, nullptr) !=
   10305             :                 SQLITE_OK)
   10306             :             {
   10307           0 :                 return false;
   10308             :             }
   10309           6 :             sqlite3_bind_text(hInsertStmt, 1, domainName.c_str(),
   10310           6 :                               static_cast<int>(domainName.size()),
   10311             :                               SQLITE_TRANSIENT);
   10312           6 :             sqlite3_bind_double(hInsertStmt, 2, dfMin);
   10313           6 :             sqlite3_bind_int(hInsertStmt, 3, bMinIsInclusive ? 1 : 0);
   10314           6 :             sqlite3_bind_double(hInsertStmt, 4, dfMax);
   10315           6 :             sqlite3_bind_int(hInsertStmt, 5, bMaxIsInclusive ? 1 : 0);
   10316           6 :             if (osDescription.empty())
   10317             :             {
   10318           3 :                 sqlite3_bind_null(hInsertStmt, 6);
   10319             :             }
   10320             :             else
   10321             :             {
   10322           3 :                 sqlite3_bind_text(hInsertStmt, 6, osDescription.c_str(),
   10323           3 :                                   static_cast<int>(osDescription.size()),
   10324             :                                   SQLITE_TRANSIENT);
   10325             :             }
   10326           6 :             const int sqlite_err = sqlite3_step(hInsertStmt);
   10327           6 :             sqlite3_finalize(hInsertStmt);
   10328           6 :             if (sqlite_err != SQLITE_OK && sqlite_err != SQLITE_DONE)
   10329             :             {
   10330           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10331             :                          "failed to execute insertion '%s': %s", pszSQL,
   10332             :                          sqlite3_errmsg(hDB));
   10333           0 :                 return false;
   10334             :             }
   10335             : 
   10336           6 :             break;
   10337             :         }
   10338             : 
   10339           1 :         case OFDT_GLOB:
   10340             :         {
   10341             :             const auto poGlobDomain =
   10342           1 :                 cpl::down_cast<const OGRGlobFieldDomain *>(domain.get());
   10343           2 :             char *pszSQL = sqlite3_mprintf(
   10344             :                 "INSERT INTO gpkg_data_column_constraints ("
   10345             :                 "constraint_name, constraint_type, value, "
   10346             :                 "min, %s, max, %s, "
   10347             :                 "description) VALUES ("
   10348             :                 "'%q', 'glob', '%q', NULL, NULL, NULL, NULL, %Q)",
   10349             :                 min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10350           1 :                 poGlobDomain->GetGlob().c_str(),
   10351           2 :                 osDescription.empty() ? nullptr : osDescription.c_str());
   10352           1 :             bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10353           1 :             sqlite3_free(pszSQL);
   10354           1 :             if (!ok)
   10355           0 :                 return false;
   10356             : 
   10357           1 :             break;
   10358             :         }
   10359             :     }
   10360             : 
   10361          18 :     m_oMapFieldDomains[domainName] = std::move(domain);
   10362          18 :     return true;
   10363             : }
   10364             : 
   10365             : /************************************************************************/
   10366             : /*                        UpdateFieldDomain()                           */
   10367             : /************************************************************************/
   10368             : 
   10369           3 : bool GDALGeoPackageDataset::UpdateFieldDomain(
   10370             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10371             : {
   10372           6 :     const std::string domainName(domain->GetName());
   10373           3 :     if (eAccess != GA_Update)
   10374             :     {
   10375           1 :         CPLError(CE_Failure, CPLE_NotSupported,
   10376             :                  "UpdateFieldDomain() not supported on read-only dataset");
   10377           1 :         return false;
   10378             :     }
   10379             : 
   10380           2 :     if (GetFieldDomain(domainName) == nullptr)
   10381             :     {
   10382           1 :         failureReason = "The domain should already exist to be updated";
   10383           1 :         return false;
   10384             :     }
   10385             : 
   10386           1 :     bool bRet = SoftStartTransaction() == OGRERR_NONE;
   10387           1 :     if (bRet)
   10388             :     {
   10389           2 :         bRet = DeleteFieldDomain(domainName, failureReason) &&
   10390           1 :                AddFieldDomain(std::move(domain), failureReason);
   10391           1 :         if (bRet)
   10392           1 :             bRet = SoftCommitTransaction() == OGRERR_NONE;
   10393             :         else
   10394           0 :             SoftRollbackTransaction();
   10395             :     }
   10396           1 :     return bRet;
   10397             : }
   10398             : 
   10399             : /************************************************************************/
   10400             : /*                         DeleteFieldDomain()                          */
   10401             : /************************************************************************/
   10402             : 
   10403          18 : bool GDALGeoPackageDataset::DeleteFieldDomain(const std::string &name,
   10404             :                                               std::string &failureReason)
   10405             : {
   10406          18 :     if (eAccess != GA_Update)
   10407             :     {
   10408           1 :         CPLError(CE_Failure, CPLE_NotSupported,
   10409             :                  "DeleteFieldDomain() not supported on read-only dataset");
   10410           1 :         return false;
   10411             :     }
   10412          17 :     if (GetFieldDomain(name) == nullptr)
   10413             :     {
   10414           1 :         failureReason = "Domain does not exist";
   10415           1 :         return false;
   10416             :     }
   10417             : 
   10418             :     char *pszSQL =
   10419          16 :         sqlite3_mprintf("DELETE FROM gpkg_data_column_constraints WHERE "
   10420             :                         "constraint_name IN ('%q', '_%q_domain_description')",
   10421             :                         name.c_str(), name.c_str());
   10422          16 :     const bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10423          16 :     sqlite3_free(pszSQL);
   10424          16 :     if (ok)
   10425          16 :         m_oMapFieldDomains.erase(name);
   10426          16 :     return ok;
   10427             : }
   10428             : 
   10429             : /************************************************************************/
   10430             : /*                          AddRelationship()                           */
   10431             : /************************************************************************/
   10432             : 
   10433          24 : bool GDALGeoPackageDataset::AddRelationship(
   10434             :     std::unique_ptr<GDALRelationship> &&relationship,
   10435             :     std::string &failureReason)
   10436             : {
   10437          24 :     if (!GetUpdate())
   10438             :     {
   10439           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10440             :                  "AddRelationship() not supported on read-only dataset");
   10441           0 :         return false;
   10442             :     }
   10443             : 
   10444             :     const std::string osRelationshipName = GenerateNameForRelationship(
   10445          24 :         relationship->GetLeftTableName().c_str(),
   10446          24 :         relationship->GetRightTableName().c_str(),
   10447          96 :         relationship->GetRelatedTableType().c_str());
   10448             :     // sanity checks
   10449          24 :     if (GetRelationship(osRelationshipName) != nullptr)
   10450             :     {
   10451           1 :         failureReason = "A relationship of identical name already exists";
   10452           1 :         return false;
   10453             :     }
   10454             : 
   10455          23 :     if (!ValidateRelationship(relationship.get(), failureReason))
   10456             :     {
   10457          14 :         return false;
   10458             :     }
   10459             : 
   10460           9 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
   10461             :     {
   10462           0 :         return false;
   10463             :     }
   10464           9 :     if (!CreateRelationsTableIfNecessary())
   10465             :     {
   10466           0 :         failureReason = "Could not create gpkgext_relations table";
   10467           0 :         return false;
   10468             :     }
   10469           9 :     if (SQLGetInteger(GetDB(),
   10470             :                       "SELECT 1 FROM gpkg_extensions WHERE "
   10471             :                       "table_name = 'gpkgext_relations'",
   10472           9 :                       nullptr) != 1)
   10473             :     {
   10474           4 :         if (OGRERR_NONE !=
   10475           4 :             SQLCommand(
   10476             :                 GetDB(),
   10477             :                 "INSERT INTO gpkg_extensions "
   10478             :                 "(table_name,column_name,extension_name,definition,scope) "
   10479             :                 "VALUES ('gpkgext_relations', NULL, 'gpkg_related_tables', "
   10480             :                 "'http://www.geopackage.org/18-000.html', "
   10481             :                 "'read-write')"))
   10482             :         {
   10483             :             failureReason =
   10484           0 :                 "Could not create gpkg_extensions entry for gpkgext_relations";
   10485           0 :             return false;
   10486             :         }
   10487             :     }
   10488             : 
   10489           9 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10490           9 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10491           9 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10492           9 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10493             : 
   10494          18 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10495           9 :     if (osRelatedTableType.empty())
   10496             :     {
   10497           5 :         osRelatedTableType = "features";
   10498             :     }
   10499             : 
   10500             :     // generate mapping table if not set
   10501          18 :     CPLString osMappingTableName = relationship->GetMappingTableName();
   10502           9 :     if (osMappingTableName.empty())
   10503             :     {
   10504           3 :         int nIndex = 1;
   10505           3 :         osMappingTableName = osLeftTableName + "_" + osRightTableName;
   10506           3 :         while (FindLayerIndex(osMappingTableName.c_str()) >= 0)
   10507             :         {
   10508           0 :             nIndex += 1;
   10509             :             osMappingTableName.Printf("%s_%s_%d", osLeftTableName.c_str(),
   10510           0 :                                       osRightTableName.c_str(), nIndex);
   10511             :         }
   10512             : 
   10513             :         // determine whether base/related keys are unique
   10514           3 :         bool bBaseKeyIsUnique = false;
   10515             :         {
   10516             :             const std::set<std::string> uniqueBaseFieldsUC =
   10517             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10518           6 :                                                osLeftTableName.c_str());
   10519           6 :             if (uniqueBaseFieldsUC.find(
   10520           3 :                     CPLString(aosLeftTableFields[0]).toupper()) !=
   10521           6 :                 uniqueBaseFieldsUC.end())
   10522             :             {
   10523           2 :                 bBaseKeyIsUnique = true;
   10524             :             }
   10525             :         }
   10526           3 :         bool bRelatedKeyIsUnique = false;
   10527             :         {
   10528             :             const std::set<std::string> uniqueRelatedFieldsUC =
   10529             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10530           6 :                                                osRightTableName.c_str());
   10531           6 :             if (uniqueRelatedFieldsUC.find(
   10532           3 :                     CPLString(aosRightTableFields[0]).toupper()) !=
   10533           6 :                 uniqueRelatedFieldsUC.end())
   10534             :             {
   10535           2 :                 bRelatedKeyIsUnique = true;
   10536             :             }
   10537             :         }
   10538             : 
   10539             :         // create mapping table
   10540             : 
   10541           3 :         std::string osBaseIdDefinition = "base_id INTEGER";
   10542           3 :         if (bBaseKeyIsUnique)
   10543             :         {
   10544           2 :             char *pszSQL = sqlite3_mprintf(
   10545             :                 " CONSTRAINT 'fk_base_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10546             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10547             :                 "DEFERRED",
   10548             :                 osMappingTableName.c_str(), osLeftTableName.c_str(),
   10549           2 :                 aosLeftTableFields[0].c_str());
   10550           2 :             osBaseIdDefinition += pszSQL;
   10551           2 :             sqlite3_free(pszSQL);
   10552             :         }
   10553             : 
   10554           3 :         std::string osRelatedIdDefinition = "related_id INTEGER";
   10555           3 :         if (bRelatedKeyIsUnique)
   10556             :         {
   10557           2 :             char *pszSQL = sqlite3_mprintf(
   10558             :                 " CONSTRAINT 'fk_related_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10559             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10560             :                 "DEFERRED",
   10561             :                 osMappingTableName.c_str(), osRightTableName.c_str(),
   10562           2 :                 aosRightTableFields[0].c_str());
   10563           2 :             osRelatedIdDefinition += pszSQL;
   10564           2 :             sqlite3_free(pszSQL);
   10565             :         }
   10566             : 
   10567           3 :         char *pszSQL = sqlite3_mprintf("CREATE TABLE \"%w\" ("
   10568             :                                        "id INTEGER PRIMARY KEY AUTOINCREMENT, "
   10569             :                                        "%s, %s);",
   10570             :                                        osMappingTableName.c_str(),
   10571             :                                        osBaseIdDefinition.c_str(),
   10572             :                                        osRelatedIdDefinition.c_str());
   10573           3 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
   10574           3 :         sqlite3_free(pszSQL);
   10575           3 :         if (eErr != OGRERR_NONE)
   10576             :         {
   10577             :             failureReason =
   10578           0 :                 ("Could not create mapping table " + osMappingTableName)
   10579           0 :                     .c_str();
   10580           0 :             return false;
   10581             :         }
   10582             : 
   10583             :         /*
   10584             :          * Strictly speaking we should NOT be inserting the mapping table into gpkg_contents.
   10585             :          * The related tables extension explicitly states that the mapping table should only be
   10586             :          * in the gpkgext_relations table and not in gpkg_contents. (See also discussion at
   10587             :          * https://github.com/opengeospatial/geopackage/issues/679).
   10588             :          *
   10589             :          * However, if we don't insert the mapping table into gpkg_contents then it is no longer
   10590             :          * visible to some clients (eg ESRI software only allows opening tables that are present
   10591             :          * in gpkg_contents). So we'll do this anyway, for maximum compatibility and flexibility.
   10592             :          *
   10593             :          * More related discussion is at https://github.com/OSGeo/gdal/pull/9258
   10594             :          */
   10595           3 :         pszSQL = sqlite3_mprintf(
   10596             :             "INSERT INTO gpkg_contents "
   10597             :             "(table_name,data_type,identifier,description,last_change,srs_id) "
   10598             :             "VALUES "
   10599             :             "('%q','attributes','%q','Mapping table for relationship between "
   10600             :             "%q and %q',%s,0)",
   10601             :             osMappingTableName.c_str(), /*table_name*/
   10602             :             osMappingTableName.c_str(), /*identifier*/
   10603             :             osLeftTableName.c_str(),    /*description left table name*/
   10604             :             osRightTableName.c_str(),   /*description right table name*/
   10605           6 :             GDALGeoPackageDataset::GetCurrentDateEscapedSQL().c_str());
   10606             : 
   10607             :         // Note -- we explicitly ignore failures here, because hey, we aren't really
   10608             :         // supposed to be adding this table to gpkg_contents anyway!
   10609           3 :         (void)SQLCommand(hDB, pszSQL);
   10610           3 :         sqlite3_free(pszSQL);
   10611             : 
   10612           3 :         pszSQL = sqlite3_mprintf(
   10613             :             "CREATE INDEX \"idx_%w_base_id\" ON \"%w\" (base_id);",
   10614             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10615           3 :         eErr = SQLCommand(hDB, pszSQL);
   10616           3 :         sqlite3_free(pszSQL);
   10617           3 :         if (eErr != OGRERR_NONE)
   10618             :         {
   10619           0 :             failureReason = ("Could not create index for " +
   10620           0 :                              osMappingTableName + " (base_id)")
   10621           0 :                                 .c_str();
   10622           0 :             return false;
   10623             :         }
   10624             : 
   10625           3 :         pszSQL = sqlite3_mprintf(
   10626             :             "CREATE INDEX \"idx_%qw_related_id\" ON \"%w\" (related_id);",
   10627             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10628           3 :         eErr = SQLCommand(hDB, pszSQL);
   10629           3 :         sqlite3_free(pszSQL);
   10630           3 :         if (eErr != OGRERR_NONE)
   10631             :         {
   10632           0 :             failureReason = ("Could not create index for " +
   10633           0 :                              osMappingTableName + " (related_id)")
   10634           0 :                                 .c_str();
   10635           0 :             return false;
   10636             :         }
   10637             :     }
   10638             :     else
   10639             :     {
   10640             :         // validate mapping table structure
   10641           6 :         if (OGRGeoPackageTableLayer *poLayer =
   10642           6 :                 cpl::down_cast<OGRGeoPackageTableLayer *>(
   10643           6 :                     GetLayerByName(osMappingTableName)))
   10644             :         {
   10645           4 :             if (poLayer->GetLayerDefn()->GetFieldIndex("base_id") < 0)
   10646             :             {
   10647             :                 failureReason =
   10648           2 :                     ("Field base_id must exist in " + osMappingTableName)
   10649           1 :                         .c_str();
   10650           1 :                 return false;
   10651             :             }
   10652           3 :             if (poLayer->GetLayerDefn()->GetFieldIndex("related_id") < 0)
   10653             :             {
   10654             :                 failureReason =
   10655           2 :                     ("Field related_id must exist in " + osMappingTableName)
   10656           1 :                         .c_str();
   10657           1 :                 return false;
   10658             :             }
   10659             :         }
   10660             :         else
   10661             :         {
   10662             :             failureReason =
   10663           2 :                 ("Could not retrieve table " + osMappingTableName).c_str();
   10664           2 :             return false;
   10665             :         }
   10666             :     }
   10667             : 
   10668           5 :     char *pszSQL = sqlite3_mprintf(
   10669             :         "INSERT INTO gpkg_extensions "
   10670             :         "(table_name,column_name,extension_name,definition,scope) "
   10671             :         "VALUES ('%q', NULL, 'gpkg_related_tables', "
   10672             :         "'http://www.geopackage.org/18-000.html', "
   10673             :         "'read-write')",
   10674             :         osMappingTableName.c_str());
   10675           5 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10676           5 :     sqlite3_free(pszSQL);
   10677           5 :     if (eErr != OGRERR_NONE)
   10678             :     {
   10679           0 :         failureReason = ("Could not insert mapping table " +
   10680           0 :                          osMappingTableName + " into gpkg_extensions")
   10681           0 :                             .c_str();
   10682           0 :         return false;
   10683             :     }
   10684             : 
   10685          15 :     pszSQL = sqlite3_mprintf(
   10686             :         "INSERT INTO gpkgext_relations "
   10687             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10688             :         "primary_column,relation_name,mapping_table_name) "
   10689             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10690           5 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10691           5 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10692             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10693           5 :     eErr = SQLCommand(hDB, pszSQL);
   10694           5 :     sqlite3_free(pszSQL);
   10695           5 :     if (eErr != OGRERR_NONE)
   10696             :     {
   10697           0 :         failureReason = "Could not insert relationship into gpkgext_relations";
   10698           0 :         return false;
   10699             :     }
   10700             : 
   10701           5 :     ClearCachedRelationships();
   10702           5 :     LoadRelationships();
   10703           5 :     return true;
   10704             : }
   10705             : 
   10706             : /************************************************************************/
   10707             : /*                         DeleteRelationship()                         */
   10708             : /************************************************************************/
   10709             : 
   10710           4 : bool GDALGeoPackageDataset::DeleteRelationship(const std::string &name,
   10711             :                                                std::string &failureReason)
   10712             : {
   10713           4 :     if (eAccess != GA_Update)
   10714             :     {
   10715           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10716             :                  "DeleteRelationship() not supported on read-only dataset");
   10717           0 :         return false;
   10718             :     }
   10719             : 
   10720             :     // ensure relationships are up to date before we try to remove one
   10721           4 :     ClearCachedRelationships();
   10722           4 :     LoadRelationships();
   10723             : 
   10724           8 :     std::string osMappingTableName;
   10725             :     {
   10726           4 :         const GDALRelationship *poRelationship = GetRelationship(name);
   10727           4 :         if (poRelationship == nullptr)
   10728             :         {
   10729           1 :             failureReason = "Could not find relationship with name " + name;
   10730           1 :             return false;
   10731             :         }
   10732             : 
   10733           3 :         osMappingTableName = poRelationship->GetMappingTableName();
   10734             :     }
   10735             : 
   10736             :     // DeleteLayerCommon will delete existing relationship objects, so we can't
   10737             :     // refer to poRelationship or any of its members previously obtained here
   10738           3 :     if (DeleteLayerCommon(osMappingTableName.c_str()) != OGRERR_NONE)
   10739             :     {
   10740             :         failureReason =
   10741           0 :             "Could not remove mapping layer name " + osMappingTableName;
   10742             : 
   10743             :         // relationships may have been left in an inconsistent state -- reload
   10744             :         // them now
   10745           0 :         ClearCachedRelationships();
   10746           0 :         LoadRelationships();
   10747           0 :         return false;
   10748             :     }
   10749             : 
   10750           3 :     ClearCachedRelationships();
   10751           3 :     LoadRelationships();
   10752           3 :     return true;
   10753             : }
   10754             : 
   10755             : /************************************************************************/
   10756             : /*                        UpdateRelationship()                          */
   10757             : /************************************************************************/
   10758             : 
   10759           6 : bool GDALGeoPackageDataset::UpdateRelationship(
   10760             :     std::unique_ptr<GDALRelationship> &&relationship,
   10761             :     std::string &failureReason)
   10762             : {
   10763           6 :     if (eAccess != GA_Update)
   10764             :     {
   10765           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10766             :                  "UpdateRelationship() not supported on read-only dataset");
   10767           0 :         return false;
   10768             :     }
   10769             : 
   10770             :     // ensure relationships are up to date before we try to update one
   10771           6 :     ClearCachedRelationships();
   10772           6 :     LoadRelationships();
   10773             : 
   10774           6 :     const std::string &osRelationshipName = relationship->GetName();
   10775           6 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10776           6 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10777           6 :     const std::string &osMappingTableName = relationship->GetMappingTableName();
   10778           6 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10779           6 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10780             : 
   10781             :     // sanity checks
   10782             :     {
   10783             :         const GDALRelationship *poExistingRelationship =
   10784           6 :             GetRelationship(osRelationshipName);
   10785           6 :         if (poExistingRelationship == nullptr)
   10786             :         {
   10787             :             failureReason =
   10788           1 :                 "The relationship should already exist to be updated";
   10789           1 :             return false;
   10790             :         }
   10791             : 
   10792           5 :         if (!ValidateRelationship(relationship.get(), failureReason))
   10793             :         {
   10794           2 :             return false;
   10795             :         }
   10796             : 
   10797             :         // we don't permit changes to the participating tables
   10798           3 :         if (osLeftTableName != poExistingRelationship->GetLeftTableName())
   10799             :         {
   10800           0 :             failureReason = ("Cannot change base table from " +
   10801           0 :                              poExistingRelationship->GetLeftTableName() +
   10802           0 :                              " to " + osLeftTableName)
   10803           0 :                                 .c_str();
   10804           0 :             return false;
   10805             :         }
   10806           3 :         if (osRightTableName != poExistingRelationship->GetRightTableName())
   10807             :         {
   10808           0 :             failureReason = ("Cannot change related table from " +
   10809           0 :                              poExistingRelationship->GetRightTableName() +
   10810           0 :                              " to " + osRightTableName)
   10811           0 :                                 .c_str();
   10812           0 :             return false;
   10813             :         }
   10814           3 :         if (osMappingTableName != poExistingRelationship->GetMappingTableName())
   10815             :         {
   10816           0 :             failureReason = ("Cannot change mapping table from " +
   10817           0 :                              poExistingRelationship->GetMappingTableName() +
   10818           0 :                              " to " + osMappingTableName)
   10819           0 :                                 .c_str();
   10820           0 :             return false;
   10821             :         }
   10822             :     }
   10823             : 
   10824           6 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10825           3 :     if (osRelatedTableType.empty())
   10826             :     {
   10827           0 :         osRelatedTableType = "features";
   10828             :     }
   10829             : 
   10830           3 :     char *pszSQL = sqlite3_mprintf(
   10831             :         "DELETE FROM gpkgext_relations WHERE mapping_table_name='%q'",
   10832             :         osMappingTableName.c_str());
   10833           3 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10834           3 :     sqlite3_free(pszSQL);
   10835           3 :     if (eErr != OGRERR_NONE)
   10836             :     {
   10837             :         failureReason =
   10838           0 :             "Could not delete old relationship from gpkgext_relations";
   10839           0 :         return false;
   10840             :     }
   10841             : 
   10842           9 :     pszSQL = sqlite3_mprintf(
   10843             :         "INSERT INTO gpkgext_relations "
   10844             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10845             :         "primary_column,relation_name,mapping_table_name) "
   10846             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10847           3 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10848           3 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10849             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10850           3 :     eErr = SQLCommand(hDB, pszSQL);
   10851           3 :     sqlite3_free(pszSQL);
   10852           3 :     if (eErr != OGRERR_NONE)
   10853             :     {
   10854             :         failureReason =
   10855           0 :             "Could not insert updated relationship into gpkgext_relations";
   10856           0 :         return false;
   10857             :     }
   10858             : 
   10859           3 :     ClearCachedRelationships();
   10860           3 :     LoadRelationships();
   10861           3 :     return true;
   10862             : }
   10863             : 
   10864             : /************************************************************************/
   10865             : /*                    GetSqliteMasterContent()                          */
   10866             : /************************************************************************/
   10867             : 
   10868             : const std::vector<SQLSqliteMasterContent> &
   10869           2 : GDALGeoPackageDataset::GetSqliteMasterContent()
   10870             : {
   10871           2 :     if (m_aoSqliteMasterContent.empty())
   10872             :     {
   10873             :         auto oResultTable =
   10874           2 :             SQLQuery(hDB, "SELECT sql, type, tbl_name FROM sqlite_master");
   10875           1 :         if (oResultTable)
   10876             :         {
   10877          58 :             for (int rowCnt = 0; rowCnt < oResultTable->RowCount(); ++rowCnt)
   10878             :             {
   10879         114 :                 SQLSqliteMasterContent row;
   10880          57 :                 const char *pszSQL = oResultTable->GetValue(0, rowCnt);
   10881          57 :                 row.osSQL = pszSQL ? pszSQL : "";
   10882          57 :                 const char *pszType = oResultTable->GetValue(1, rowCnt);
   10883          57 :                 row.osType = pszType ? pszType : "";
   10884          57 :                 const char *pszTableName = oResultTable->GetValue(2, rowCnt);
   10885          57 :                 row.osTableName = pszTableName ? pszTableName : "";
   10886          57 :                 m_aoSqliteMasterContent.emplace_back(std::move(row));
   10887             :             }
   10888             :         }
   10889             :     }
   10890           2 :     return m_aoSqliteMasterContent;
   10891             : }

Generated by: LCOV version 1.14