LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/gpkg - ogrgeopackagedatasource.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 4047 4513 89.7 %
Date: 2025-11-08 06:46:40 Functions: 138 138 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 "gdalwarper.h"
      18             : #include "gdal_utils.h"
      19             : #include "ogrgeopackageutility.h"
      20             : #include "ogrsqliteutility.h"
      21             : #include "ogr_wkb.h"
      22             : #include "vrt/vrtdataset.h"
      23             : 
      24             : #include "tilematrixset.hpp"
      25             : 
      26             : #include <cstdlib>
      27             : 
      28             : #include <algorithm>
      29             : #include <limits>
      30             : #include <sstream>
      31             : 
      32             : #define COMPILATION_ALLOWED
      33             : #define DEFINE_OGRSQLiteSQLFunctionsSetCaseSensitiveLike
      34             : #include "ogrsqlitesqlfunctionscommon.cpp"
      35             : 
      36             : // Keep in sync prototype of those 2 functions between gdalopeninfo.cpp,
      37             : // ogrsqlitedatasource.cpp and ogrgeopackagedatasource.cpp
      38             : void GDALOpenInfoDeclareFileNotToOpen(const char *pszFilename,
      39             :                                       const GByte *pabyHeader,
      40             :                                       int nHeaderBytes);
      41             : void GDALOpenInfoUnDeclareFileNotToOpen(const char *pszFilename);
      42             : 
      43             : /************************************************************************/
      44             : /*                             Tiling schemes                           */
      45             : /************************************************************************/
      46             : 
      47             : typedef struct
      48             : {
      49             :     const char *pszName;
      50             :     int nEPSGCode;
      51             :     double dfMinX;
      52             :     double dfMaxY;
      53             :     int nTileXCountZoomLevel0;
      54             :     int nTileYCountZoomLevel0;
      55             :     int nTileWidth;
      56             :     int nTileHeight;
      57             :     double dfPixelXSizeZoomLevel0;
      58             :     double dfPixelYSizeZoomLevel0;
      59             : } TilingSchemeDefinition;
      60             : 
      61             : static const TilingSchemeDefinition asTilingSchemes[] = {
      62             :     /* See http://portal.opengeospatial.org/files/?artifact_id=35326 (WMTS 1.0),
      63             :        Annex E.3 */
      64             :     {"GoogleCRS84Quad", 4326, -180.0, 180.0, 1, 1, 256, 256, 360.0 / 256,
      65             :      360.0 / 256},
      66             : 
      67             :     /* See global-mercator at
      68             :        http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification */
      69             :     {"PseudoTMS_GlobalMercator", 3857, -20037508.34, 20037508.34, 2, 2, 256,
      70             :      256, 78271.516, 78271.516},
      71             : };
      72             : 
      73             : // Setting it above 30 would lead to integer overflow ((1 << 31) > INT_MAX)
      74             : constexpr int MAX_ZOOM_LEVEL = 30;
      75             : 
      76             : /************************************************************************/
      77             : /*                     GetTilingScheme()                                */
      78             : /************************************************************************/
      79             : 
      80             : static std::unique_ptr<TilingSchemeDefinition>
      81         570 : GetTilingScheme(const char *pszName)
      82             : {
      83         570 :     if (EQUAL(pszName, "CUSTOM"))
      84         442 :         return nullptr;
      85             : 
      86         256 :     for (const auto &tilingScheme : asTilingSchemes)
      87             :     {
      88         195 :         if (EQUAL(pszName, tilingScheme.pszName))
      89             :         {
      90          67 :             return std::make_unique<TilingSchemeDefinition>(tilingScheme);
      91             :         }
      92             :     }
      93             : 
      94          61 :     if (EQUAL(pszName, "PseudoTMS_GlobalGeodetic"))
      95           6 :         pszName = "InspireCRS84Quad";
      96             : 
      97         122 :     auto poTM = gdal::TileMatrixSet::parse(pszName);
      98          61 :     if (poTM == nullptr)
      99           1 :         return nullptr;
     100          60 :     if (!poTM->haveAllLevelsSameTopLeft())
     101             :     {
     102           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     103             :                  "Unsupported tiling scheme: not all zoom levels have same top "
     104             :                  "left corner");
     105           0 :         return nullptr;
     106             :     }
     107          60 :     if (!poTM->haveAllLevelsSameTileSize())
     108             :     {
     109           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     110             :                  "Unsupported tiling scheme: not all zoom levels have same "
     111             :                  "tile size");
     112           0 :         return nullptr;
     113             :     }
     114          60 :     if (!poTM->hasOnlyPowerOfTwoVaryingScales())
     115             :     {
     116           1 :         CPLError(CE_Failure, CPLE_NotSupported,
     117             :                  "Unsupported tiling scheme: resolution of consecutive zoom "
     118             :                  "levels is not always 2");
     119           1 :         return nullptr;
     120             :     }
     121          59 :     if (poTM->hasVariableMatrixWidth())
     122             :     {
     123           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     124             :                  "Unsupported tiling scheme: some levels have variable matrix "
     125             :                  "width");
     126           0 :         return nullptr;
     127             :     }
     128         118 :     auto poTilingScheme = std::make_unique<TilingSchemeDefinition>();
     129          59 :     poTilingScheme->pszName = pszName;
     130             : 
     131         118 :     OGRSpatialReference oSRS;
     132          59 :     if (oSRS.SetFromUserInput(poTM->crs().c_str()) != OGRERR_NONE)
     133             :     {
     134           0 :         return nullptr;
     135             :     }
     136          59 :     if (poTM->crs() == "http://www.opengis.net/def/crs/OGC/1.3/CRS84")
     137             :     {
     138           6 :         poTilingScheme->nEPSGCode = 4326;
     139             :     }
     140             :     else
     141             :     {
     142          53 :         const char *pszAuthName = oSRS.GetAuthorityName(nullptr);
     143          53 :         const char *pszAuthCode = oSRS.GetAuthorityCode(nullptr);
     144          53 :         if (pszAuthName == nullptr || !EQUAL(pszAuthName, "EPSG") ||
     145             :             pszAuthCode == nullptr)
     146             :         {
     147           0 :             CPLError(CE_Failure, CPLE_NotSupported,
     148             :                      "Unsupported tiling scheme: only EPSG CRS supported");
     149           0 :             return nullptr;
     150             :         }
     151          53 :         poTilingScheme->nEPSGCode = atoi(pszAuthCode);
     152             :     }
     153          59 :     const auto &zoomLevel0 = poTM->tileMatrixList()[0];
     154          59 :     poTilingScheme->dfMinX = zoomLevel0.mTopLeftX;
     155          59 :     poTilingScheme->dfMaxY = zoomLevel0.mTopLeftY;
     156          59 :     poTilingScheme->nTileXCountZoomLevel0 = zoomLevel0.mMatrixWidth;
     157          59 :     poTilingScheme->nTileYCountZoomLevel0 = zoomLevel0.mMatrixHeight;
     158          59 :     poTilingScheme->nTileWidth = zoomLevel0.mTileWidth;
     159          59 :     poTilingScheme->nTileHeight = zoomLevel0.mTileHeight;
     160          59 :     poTilingScheme->dfPixelXSizeZoomLevel0 = zoomLevel0.mResX;
     161          59 :     poTilingScheme->dfPixelYSizeZoomLevel0 = zoomLevel0.mResY;
     162             : 
     163         118 :     const bool bInvertAxis = oSRS.EPSGTreatsAsLatLong() != FALSE ||
     164          59 :                              oSRS.EPSGTreatsAsNorthingEasting() != FALSE;
     165          59 :     if (bInvertAxis)
     166             :     {
     167           6 :         std::swap(poTilingScheme->dfMinX, poTilingScheme->dfMaxY);
     168           6 :         std::swap(poTilingScheme->dfPixelXSizeZoomLevel0,
     169           6 :                   poTilingScheme->dfPixelYSizeZoomLevel0);
     170             :     }
     171          59 :     return poTilingScheme;
     172             : }
     173             : 
     174             : static const char *pszCREATE_GPKG_GEOMETRY_COLUMNS =
     175             :     "CREATE TABLE gpkg_geometry_columns ("
     176             :     "table_name TEXT NOT NULL,"
     177             :     "column_name TEXT NOT NULL,"
     178             :     "geometry_type_name TEXT NOT NULL,"
     179             :     "srs_id INTEGER NOT NULL,"
     180             :     "z TINYINT NOT NULL,"
     181             :     "m TINYINT NOT NULL,"
     182             :     "CONSTRAINT pk_geom_cols PRIMARY KEY (table_name, column_name),"
     183             :     "CONSTRAINT uk_gc_table_name UNIQUE (table_name),"
     184             :     "CONSTRAINT fk_gc_tn FOREIGN KEY (table_name) REFERENCES "
     185             :     "gpkg_contents(table_name),"
     186             :     "CONSTRAINT fk_gc_srs FOREIGN KEY (srs_id) REFERENCES gpkg_spatial_ref_sys "
     187             :     "(srs_id)"
     188             :     ")";
     189             : 
     190         950 : OGRErr GDALGeoPackageDataset::SetApplicationAndUserVersionId()
     191             : {
     192         950 :     CPLAssert(hDB != nullptr);
     193             : 
     194         950 :     const CPLString osPragma(CPLString().Printf("PRAGMA application_id = %u;"
     195             :                                                 "PRAGMA user_version = %u",
     196             :                                                 m_nApplicationId,
     197        1900 :                                                 m_nUserVersion));
     198        1900 :     return SQLCommand(hDB, osPragma.c_str());
     199             : }
     200             : 
     201        2589 : bool GDALGeoPackageDataset::CloseDB()
     202             : {
     203        2589 :     OGRSQLiteUnregisterSQLFunctions(m_pSQLFunctionData);
     204        2589 :     m_pSQLFunctionData = nullptr;
     205        2589 :     return OGRSQLiteBaseDataSource::CloseDB();
     206             : }
     207             : 
     208          11 : bool GDALGeoPackageDataset::ReOpenDB()
     209             : {
     210          11 :     CPLAssert(hDB != nullptr);
     211          11 :     CPLAssert(m_pszFilename != nullptr);
     212             : 
     213          11 :     FinishSpatialite();
     214             : 
     215          11 :     CloseDB();
     216             : 
     217             :     /* And re-open the file */
     218          11 :     return OpenOrCreateDB(SQLITE_OPEN_READWRITE);
     219             : }
     220             : 
     221         824 : static OGRErr GDALGPKGImportFromEPSG(OGRSpatialReference *poSpatialRef,
     222             :                                      int nEPSGCode)
     223             : {
     224         824 :     CPLPushErrorHandler(CPLQuietErrorHandler);
     225         824 :     const OGRErr eErr = poSpatialRef->importFromEPSG(nEPSGCode);
     226         824 :     CPLPopErrorHandler();
     227         824 :     CPLErrorReset();
     228         824 :     return eErr;
     229             : }
     230             : 
     231             : std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
     232        1263 : GDALGeoPackageDataset::GetSpatialRef(int iSrsId, bool bFallbackToEPSG,
     233             :                                      bool bEmitErrorIfNotFound)
     234             : {
     235        1263 :     const auto oIter = m_oMapSrsIdToSrs.find(iSrsId);
     236        1263 :     if (oIter != m_oMapSrsIdToSrs.end())
     237             :     {
     238          90 :         if (oIter->second == nullptr)
     239          33 :             return nullptr;
     240          57 :         oIter->second->Reference();
     241             :         return std::unique_ptr<OGRSpatialReference,
     242          57 :                                OGRSpatialReferenceReleaser>(oIter->second);
     243             :     }
     244             : 
     245        1173 :     if (iSrsId == 0 || iSrsId == -1)
     246             :     {
     247         119 :         OGRSpatialReference *poSpatialRef = new OGRSpatialReference();
     248         119 :         poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     249             : 
     250             :         // See corresponding tests in GDALGeoPackageDataset::GetSrsId
     251         119 :         if (iSrsId == 0)
     252             :         {
     253          29 :             poSpatialRef->SetGeogCS("Undefined geographic SRS", "unknown",
     254             :                                     "unknown", SRS_WGS84_SEMIMAJOR,
     255             :                                     SRS_WGS84_INVFLATTENING);
     256             :         }
     257          90 :         else if (iSrsId == -1)
     258             :         {
     259          90 :             poSpatialRef->SetLocalCS("Undefined Cartesian SRS");
     260          90 :             poSpatialRef->SetLinearUnits(SRS_UL_METER, 1.0);
     261             :         }
     262             : 
     263         119 :         m_oMapSrsIdToSrs[iSrsId] = poSpatialRef;
     264         119 :         poSpatialRef->Reference();
     265             :         return std::unique_ptr<OGRSpatialReference,
     266         119 :                                OGRSpatialReferenceReleaser>(poSpatialRef);
     267             :     }
     268             : 
     269        2108 :     CPLString oSQL;
     270        1054 :     oSQL.Printf("SELECT srs_name, definition, organization, "
     271             :                 "organization_coordsys_id%s%s "
     272             :                 "FROM gpkg_spatial_ref_sys WHERE "
     273             :                 "srs_id = %d LIMIT 2",
     274        1054 :                 m_bHasDefinition12_063 ? ", definition_12_063" : "",
     275        1054 :                 m_bHasEpochColumn ? ", epoch" : "", iSrsId);
     276             : 
     277        2108 :     auto oResult = SQLQuery(hDB, oSQL.c_str());
     278             : 
     279        1054 :     if (!oResult || oResult->RowCount() != 1)
     280             :     {
     281          12 :         if (bFallbackToEPSG)
     282             :         {
     283           7 :             CPLDebug("GPKG",
     284             :                      "unable to read srs_id '%d' from gpkg_spatial_ref_sys",
     285             :                      iSrsId);
     286           7 :             OGRSpatialReference *poSRS = new OGRSpatialReference();
     287           7 :             if (poSRS->importFromEPSG(iSrsId) == OGRERR_NONE)
     288             :             {
     289           5 :                 poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     290             :                 return std::unique_ptr<OGRSpatialReference,
     291           5 :                                        OGRSpatialReferenceReleaser>(poSRS);
     292             :             }
     293           2 :             poSRS->Release();
     294             :         }
     295           5 :         else if (bEmitErrorIfNotFound)
     296             :         {
     297           2 :             CPLError(CE_Warning, CPLE_AppDefined,
     298             :                      "unable to read srs_id '%d' from gpkg_spatial_ref_sys",
     299             :                      iSrsId);
     300           2 :             m_oMapSrsIdToSrs[iSrsId] = nullptr;
     301             :         }
     302           7 :         return nullptr;
     303             :     }
     304             : 
     305        1042 :     const char *pszName = oResult->GetValue(0, 0);
     306        1042 :     if (pszName && EQUAL(pszName, "Undefined SRS"))
     307             :     {
     308         450 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     309         450 :         return nullptr;
     310             :     }
     311         592 :     const char *pszWkt = oResult->GetValue(1, 0);
     312         592 :     if (pszWkt == nullptr)
     313           0 :         return nullptr;
     314         592 :     const char *pszOrganization = oResult->GetValue(2, 0);
     315         592 :     const char *pszOrganizationCoordsysID = oResult->GetValue(3, 0);
     316             :     const char *pszWkt2 =
     317         592 :         m_bHasDefinition12_063 ? oResult->GetValue(4, 0) : nullptr;
     318         592 :     if (pszWkt2 && !EQUAL(pszWkt2, "undefined"))
     319          76 :         pszWkt = pszWkt2;
     320             :     const char *pszCoordinateEpoch =
     321         592 :         m_bHasEpochColumn ? oResult->GetValue(5, 0) : nullptr;
     322             :     const double dfCoordinateEpoch =
     323         592 :         pszCoordinateEpoch ? CPLAtof(pszCoordinateEpoch) : 0.0;
     324             : 
     325         592 :     OGRSpatialReference *poSpatialRef = new OGRSpatialReference();
     326         592 :     poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     327             :     // Try to import first from EPSG code, and then from WKT
     328         592 :     if (!(pszOrganization && pszOrganizationCoordsysID &&
     329         592 :           EQUAL(pszOrganization, "EPSG") &&
     330         572 :           (atoi(pszOrganizationCoordsysID) == iSrsId ||
     331           4 :            (dfCoordinateEpoch > 0 && strstr(pszWkt, "DYNAMIC[") == nullptr)) &&
     332         572 :           GDALGPKGImportFromEPSG(
     333        1184 :               poSpatialRef, atoi(pszOrganizationCoordsysID)) == OGRERR_NONE) &&
     334          20 :         poSpatialRef->importFromWkt(pszWkt) != OGRERR_NONE)
     335             :     {
     336           0 :         CPLError(CE_Warning, CPLE_AppDefined,
     337             :                  "Unable to parse srs_id '%d' well-known text '%s'", iSrsId,
     338             :                  pszWkt);
     339           0 :         delete poSpatialRef;
     340           0 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     341           0 :         return nullptr;
     342             :     }
     343             : 
     344         592 :     poSpatialRef->StripTOWGS84IfKnownDatumAndAllowed();
     345         592 :     poSpatialRef->SetCoordinateEpoch(dfCoordinateEpoch);
     346         592 :     m_oMapSrsIdToSrs[iSrsId] = poSpatialRef;
     347         592 :     poSpatialRef->Reference();
     348             :     return std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>(
     349         592 :         poSpatialRef);
     350             : }
     351             : 
     352         281 : const char *GDALGeoPackageDataset::GetSrsName(const OGRSpatialReference &oSRS)
     353             : {
     354         281 :     const char *pszName = oSRS.GetName();
     355         281 :     if (pszName)
     356         281 :         return pszName;
     357             : 
     358             :     // Something odd.  Return empty.
     359           0 :     return "Unnamed SRS";
     360             : }
     361             : 
     362             : /* Add the definition_12_063 column to an existing gpkg_spatial_ref_sys table */
     363           7 : bool GDALGeoPackageDataset::ConvertGpkgSpatialRefSysToExtensionWkt2(
     364             :     bool bForceEpoch)
     365             : {
     366           7 :     const bool bAddEpoch = (m_nUserVersion >= GPKG_1_4_VERSION || bForceEpoch);
     367             :     auto oResultTable = SQLQuery(
     368             :         hDB, "SELECT srs_name, srs_id, organization, organization_coordsys_id, "
     369          14 :              "definition, description FROM gpkg_spatial_ref_sys LIMIT 100000");
     370           7 :     if (!oResultTable)
     371           0 :         return false;
     372             : 
     373             :     // Temporary remove foreign key checks
     374             :     const GPKGTemporaryForeignKeyCheckDisabler
     375           7 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
     376             : 
     377           7 :     bool bRet = SoftStartTransaction() == OGRERR_NONE;
     378             : 
     379           7 :     if (bRet)
     380             :     {
     381             :         std::string osSQL("CREATE TABLE gpkg_spatial_ref_sys_temp ("
     382             :                           "srs_name TEXT NOT NULL,"
     383             :                           "srs_id INTEGER NOT NULL PRIMARY KEY,"
     384             :                           "organization TEXT NOT NULL,"
     385             :                           "organization_coordsys_id INTEGER NOT NULL,"
     386             :                           "definition TEXT NOT NULL,"
     387             :                           "description TEXT, "
     388           7 :                           "definition_12_063 TEXT NOT NULL");
     389           7 :         if (bAddEpoch)
     390           6 :             osSQL += ", epoch DOUBLE";
     391           7 :         osSQL += ")";
     392           7 :         bRet = SQLCommand(hDB, osSQL.c_str()) == OGRERR_NONE;
     393             :     }
     394             : 
     395           7 :     if (bRet)
     396             :     {
     397          32 :         for (int i = 0; bRet && i < oResultTable->RowCount(); i++)
     398             :         {
     399          25 :             const char *pszSrsName = oResultTable->GetValue(0, i);
     400          25 :             const char *pszSrsId = oResultTable->GetValue(1, i);
     401          25 :             const char *pszOrganization = oResultTable->GetValue(2, i);
     402             :             const char *pszOrganizationCoordsysID =
     403          25 :                 oResultTable->GetValue(3, i);
     404          25 :             const char *pszDefinition = oResultTable->GetValue(4, i);
     405             :             if (pszSrsName == nullptr || pszSrsId == nullptr ||
     406             :                 pszOrganization == nullptr ||
     407             :                 pszOrganizationCoordsysID == nullptr)
     408             :             {
     409             :                 // should not happen as there are NOT NULL constraints
     410             :                 // But a database could lack such NOT NULL constraints or have
     411             :                 // large values that would cause a memory allocation failure.
     412             :             }
     413          25 :             const char *pszDescription = oResultTable->GetValue(5, i);
     414             :             char *pszSQL;
     415             : 
     416          50 :             OGRSpatialReference oSRS;
     417          25 :             if (pszOrganization && pszOrganizationCoordsysID &&
     418          25 :                 EQUAL(pszOrganization, "EPSG"))
     419             :             {
     420           9 :                 oSRS.importFromEPSG(atoi(pszOrganizationCoordsysID));
     421             :             }
     422          34 :             if (!oSRS.IsEmpty() && pszDefinition &&
     423           9 :                 !EQUAL(pszDefinition, "undefined"))
     424             :             {
     425           9 :                 oSRS.SetFromUserInput(pszDefinition);
     426             :             }
     427          25 :             char *pszWKT2 = nullptr;
     428          25 :             if (!oSRS.IsEmpty())
     429             :             {
     430           9 :                 const char *const apszOptionsWkt2[] = {"FORMAT=WKT2_2015",
     431             :                                                        nullptr};
     432           9 :                 oSRS.exportToWkt(&pszWKT2, apszOptionsWkt2);
     433           9 :                 if (pszWKT2 && pszWKT2[0] == '\0')
     434             :                 {
     435           0 :                     CPLFree(pszWKT2);
     436           0 :                     pszWKT2 = nullptr;
     437             :                 }
     438             :             }
     439          25 :             if (pszWKT2 == nullptr)
     440             :             {
     441          16 :                 pszWKT2 = CPLStrdup("undefined");
     442             :             }
     443             : 
     444          25 :             if (pszDescription)
     445             :             {
     446          22 :                 pszSQL = sqlite3_mprintf(
     447             :                     "INSERT INTO gpkg_spatial_ref_sys_temp(srs_name, srs_id, "
     448             :                     "organization, organization_coordsys_id, definition, "
     449             :                     "description, definition_12_063) VALUES ('%q', '%q', '%q', "
     450             :                     "'%q', '%q', '%q', '%q')",
     451             :                     pszSrsName, pszSrsId, pszOrganization,
     452             :                     pszOrganizationCoordsysID, pszDefinition, pszDescription,
     453             :                     pszWKT2);
     454             :             }
     455             :             else
     456             :             {
     457           3 :                 pszSQL = sqlite3_mprintf(
     458             :                     "INSERT INTO gpkg_spatial_ref_sys_temp(srs_name, srs_id, "
     459             :                     "organization, organization_coordsys_id, definition, "
     460             :                     "description, definition_12_063) VALUES ('%q', '%q', '%q', "
     461             :                     "'%q', '%q', NULL, '%q')",
     462             :                     pszSrsName, pszSrsId, pszOrganization,
     463             :                     pszOrganizationCoordsysID, pszDefinition, pszWKT2);
     464             :             }
     465             : 
     466          25 :             CPLFree(pszWKT2);
     467          25 :             bRet &= SQLCommand(hDB, pszSQL) == OGRERR_NONE;
     468          25 :             sqlite3_free(pszSQL);
     469             :         }
     470             :     }
     471             : 
     472           7 :     if (bRet)
     473             :     {
     474           7 :         bRet =
     475           7 :             SQLCommand(hDB, "DROP TABLE gpkg_spatial_ref_sys") == OGRERR_NONE;
     476             :     }
     477           7 :     if (bRet)
     478             :     {
     479           7 :         bRet = SQLCommand(hDB, "ALTER TABLE gpkg_spatial_ref_sys_temp RENAME "
     480             :                                "TO gpkg_spatial_ref_sys") == OGRERR_NONE;
     481             :     }
     482           7 :     if (bRet)
     483             :     {
     484          14 :         bRet = OGRERR_NONE == CreateExtensionsTableIfNecessary() &&
     485           7 :                OGRERR_NONE == SQLCommand(hDB,
     486             :                                          "INSERT INTO gpkg_extensions "
     487             :                                          "(table_name, column_name, "
     488             :                                          "extension_name, definition, scope) "
     489             :                                          "VALUES "
     490             :                                          "('gpkg_spatial_ref_sys', "
     491             :                                          "'definition_12_063', 'gpkg_crs_wkt', "
     492             :                                          "'http://www.geopackage.org/spec120/"
     493             :                                          "#extension_crs_wkt', 'read-write')");
     494             :     }
     495           7 :     if (bRet && bAddEpoch)
     496             :     {
     497           6 :         bRet =
     498             :             OGRERR_NONE ==
     499           6 :                 SQLCommand(hDB, "UPDATE gpkg_extensions SET extension_name = "
     500             :                                 "'gpkg_crs_wkt_1_1' "
     501          12 :                                 "WHERE extension_name = 'gpkg_crs_wkt'") &&
     502             :             OGRERR_NONE ==
     503           6 :                 SQLCommand(
     504             :                     hDB,
     505             :                     "INSERT INTO gpkg_extensions "
     506             :                     "(table_name, column_name, extension_name, definition, "
     507             :                     "scope) "
     508             :                     "VALUES "
     509             :                     "('gpkg_spatial_ref_sys', 'epoch', 'gpkg_crs_wkt_1_1', "
     510             :                     "'http://www.geopackage.org/spec/#extension_crs_wkt', "
     511             :                     "'read-write')");
     512             :     }
     513           7 :     if (bRet)
     514             :     {
     515           7 :         SoftCommitTransaction();
     516           7 :         m_bHasDefinition12_063 = true;
     517           7 :         if (bAddEpoch)
     518           6 :             m_bHasEpochColumn = true;
     519             :     }
     520             :     else
     521             :     {
     522           0 :         SoftRollbackTransaction();
     523             :     }
     524             : 
     525           7 :     return bRet;
     526             : }
     527             : 
     528         913 : int GDALGeoPackageDataset::GetSrsId(const OGRSpatialReference *poSRSIn)
     529             : {
     530         913 :     const char *pszName = poSRSIn ? poSRSIn->GetName() : nullptr;
     531        1319 :     if (!poSRSIn || poSRSIn->IsEmpty() ||
     532         406 :         (pszName && EQUAL(pszName, "Undefined SRS")))
     533             :     {
     534         509 :         OGRErr err = OGRERR_NONE;
     535         509 :         const int nSRSId = SQLGetInteger(
     536             :             hDB,
     537             :             "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE srs_name = "
     538             :             "'Undefined SRS' AND organization = 'GDAL'",
     539             :             &err);
     540         509 :         if (err == OGRERR_NONE)
     541          57 :             return nSRSId;
     542             : 
     543             :         // The below WKT definitions are somehow questionable (using a unknown
     544             :         // unit). For GDAL >= 3.9, they won't be used. They will only be used
     545             :         // for earlier versions.
     546             :         const char *pszSQL;
     547             : #define UNDEFINED_CRS_SRS_ID 99999
     548             :         static_assert(UNDEFINED_CRS_SRS_ID == FIRST_CUSTOM_SRSID - 1);
     549             : #define STRINGIFY(x) #x
     550             : #define XSTRINGIFY(x) STRINGIFY(x)
     551         452 :         if (m_bHasDefinition12_063)
     552             :         {
     553             :             /* clang-format off */
     554           1 :             pszSQL =
     555             :                 "INSERT INTO gpkg_spatial_ref_sys "
     556             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     557             :                 "definition, definition_12_063, description) VALUES "
     558             :                 "('Undefined SRS'," XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ",'GDAL',"
     559             :                 XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ","
     560             :                 "'LOCAL_CS[\"Undefined SRS\",LOCAL_DATUM[\"unknown\",32767],"
     561             :                 "UNIT[\"unknown\",0],AXIS[\"Easting\",EAST],"
     562             :                 "AXIS[\"Northing\",NORTH]]',"
     563             :                 "'ENGCRS[\"Undefined SRS\",EDATUM[\"unknown\"],CS[Cartesian,2],"
     564             :                 "AXIS[\"easting\",east,ORDER[1],LENGTHUNIT[\"unknown\",0]],"
     565             :                 "AXIS[\"northing\",north,ORDER[2],LENGTHUNIT[\"unknown\",0]]]',"
     566             :                 "'Custom undefined coordinate reference system')";
     567             :             /* clang-format on */
     568             :         }
     569             :         else
     570             :         {
     571             :             /* clang-format off */
     572         451 :             pszSQL =
     573             :                 "INSERT INTO gpkg_spatial_ref_sys "
     574             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     575             :                 "definition, description) VALUES "
     576             :                 "('Undefined SRS'," XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ",'GDAL',"
     577             :                 XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ","
     578             :                 "'LOCAL_CS[\"Undefined SRS\",LOCAL_DATUM[\"unknown\",32767],"
     579             :                 "UNIT[\"unknown\",0],AXIS[\"Easting\",EAST],"
     580             :                 "AXIS[\"Northing\",NORTH]]',"
     581             :                 "'Custom undefined coordinate reference system')";
     582             :             /* clang-format on */
     583             :         }
     584         452 :         if (SQLCommand(hDB, pszSQL) == OGRERR_NONE)
     585         452 :             return UNDEFINED_CRS_SRS_ID;
     586             : #undef UNDEFINED_CRS_SRS_ID
     587             : #undef XSTRINGIFY
     588             : #undef STRINGIFY
     589           0 :         return -1;
     590             :     }
     591             : 
     592         808 :     std::unique_ptr<OGRSpatialReference> poSRS(poSRSIn->Clone());
     593             : 
     594         404 :     if (poSRS->IsGeographic() || poSRS->IsLocal())
     595             :     {
     596             :         // See corresponding tests in GDALGeoPackageDataset::GetSpatialRef
     597         140 :         if (pszName != nullptr && strlen(pszName) > 0)
     598             :         {
     599         140 :             if (EQUAL(pszName, "Undefined geographic SRS"))
     600           2 :                 return 0;
     601             : 
     602         138 :             if (EQUAL(pszName, "Undefined Cartesian SRS"))
     603           1 :                 return -1;
     604             :         }
     605             :     }
     606             : 
     607         401 :     const char *pszAuthorityName = poSRS->GetAuthorityName(nullptr);
     608             : 
     609         401 :     if (pszAuthorityName == nullptr || strlen(pszAuthorityName) == 0)
     610             :     {
     611             :         // Try to force identify an EPSG code.
     612          26 :         poSRS->AutoIdentifyEPSG();
     613             : 
     614          26 :         pszAuthorityName = poSRS->GetAuthorityName(nullptr);
     615          26 :         if (pszAuthorityName != nullptr && EQUAL(pszAuthorityName, "EPSG"))
     616             :         {
     617           0 :             const char *pszAuthorityCode = poSRS->GetAuthorityCode(nullptr);
     618           0 :             if (pszAuthorityCode != nullptr && strlen(pszAuthorityCode) > 0)
     619             :             {
     620             :                 /* Import 'clean' SRS */
     621           0 :                 poSRS->importFromEPSG(atoi(pszAuthorityCode));
     622             : 
     623           0 :                 pszAuthorityName = poSRS->GetAuthorityName(nullptr);
     624             :             }
     625             :         }
     626             : 
     627          26 :         poSRS->SetCoordinateEpoch(poSRSIn->GetCoordinateEpoch());
     628             :     }
     629             : 
     630             :     // Check whether the EPSG authority code is already mapped to a
     631             :     // SRS ID.
     632         401 :     char *pszSQL = nullptr;
     633         401 :     int nSRSId = DEFAULT_SRID;
     634         401 :     int nAuthorityCode = 0;
     635         401 :     OGRErr err = OGRERR_NONE;
     636         401 :     bool bCanUseAuthorityCode = false;
     637         401 :     const char *const apszIsSameOptions[] = {
     638             :         "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES",
     639             :         "IGNORE_COORDINATE_EPOCH=YES", nullptr};
     640         401 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0)
     641             :     {
     642         375 :         const char *pszAuthorityCode = poSRS->GetAuthorityCode(nullptr);
     643         375 :         if (pszAuthorityCode)
     644             :         {
     645         375 :             if (CPLGetValueType(pszAuthorityCode) == CPL_VALUE_INTEGER)
     646             :             {
     647         375 :                 nAuthorityCode = atoi(pszAuthorityCode);
     648             :             }
     649             :             else
     650             :             {
     651           0 :                 CPLDebug("GPKG",
     652             :                          "SRS has %s:%s identification, but the code not "
     653             :                          "being an integer value cannot be stored as such "
     654             :                          "in the database.",
     655             :                          pszAuthorityName, pszAuthorityCode);
     656           0 :                 pszAuthorityName = nullptr;
     657             :             }
     658             :         }
     659             :     }
     660             : 
     661         776 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     662         375 :         poSRSIn->GetCoordinateEpoch() == 0)
     663             :     {
     664             :         pszSQL =
     665         370 :             sqlite3_mprintf("SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     666             :                             "upper(organization) = upper('%q') AND "
     667             :                             "organization_coordsys_id = %d",
     668             :                             pszAuthorityName, nAuthorityCode);
     669             : 
     670         370 :         nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     671         370 :         sqlite3_free(pszSQL);
     672             : 
     673             :         // Got a match? Return it!
     674         370 :         if (OGRERR_NONE == err)
     675             :         {
     676         116 :             auto poRefSRS = GetSpatialRef(nSRSId);
     677             :             bool bOK =
     678         116 :                 (poRefSRS == nullptr ||
     679         117 :                  poSRS->IsSame(poRefSRS.get(), apszIsSameOptions) ||
     680           1 :                  !CPLTestBool(CPLGetConfigOption("OGR_GPKG_CHECK_SRS", "YES")));
     681         116 :             if (bOK)
     682             :             {
     683         115 :                 return nSRSId;
     684             :             }
     685             :             else
     686             :             {
     687           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
     688             :                          "Passed SRS uses %s:%d identification, but its "
     689             :                          "definition is not compatible with the "
     690             :                          "definition of that object already in the database. "
     691             :                          "Registering it as a new entry into the database.",
     692             :                          pszAuthorityName, nAuthorityCode);
     693           1 :                 pszAuthorityName = nullptr;
     694           1 :                 nAuthorityCode = 0;
     695             :             }
     696             :         }
     697             :     }
     698             : 
     699             :     // Translate SRS to WKT.
     700         286 :     CPLCharUniquePtr pszWKT1;
     701         286 :     CPLCharUniquePtr pszWKT2_2015;
     702         286 :     CPLCharUniquePtr pszWKT2_2019;
     703         286 :     const char *const apszOptionsWkt1[] = {"FORMAT=WKT1_GDAL", nullptr};
     704         286 :     const char *const apszOptionsWkt2_2015[] = {"FORMAT=WKT2_2015", nullptr};
     705         286 :     const char *const apszOptionsWkt2_2019[] = {"FORMAT=WKT2_2019", nullptr};
     706             : 
     707         572 :     std::string osEpochTest;
     708         286 :     if (poSRSIn->GetCoordinateEpoch() > 0 && m_bHasEpochColumn)
     709             :     {
     710             :         osEpochTest =
     711           3 :             CPLSPrintf(" AND epoch = %.17g", poSRSIn->GetCoordinateEpoch());
     712             :     }
     713             : 
     714         286 :     if (!(poSRS->IsGeographic() && poSRS->GetAxesCount() == 3))
     715             :     {
     716         277 :         char *pszTmp = nullptr;
     717         277 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt1);
     718         277 :         pszWKT1.reset(pszTmp);
     719         277 :         if (pszWKT1 && pszWKT1.get()[0] == '\0')
     720             :         {
     721           0 :             pszWKT1.reset();
     722             :         }
     723             :     }
     724             :     {
     725         286 :         char *pszTmp = nullptr;
     726         286 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2015);
     727         286 :         pszWKT2_2015.reset(pszTmp);
     728         286 :         if (pszWKT2_2015 && pszWKT2_2015.get()[0] == '\0')
     729             :         {
     730           0 :             pszWKT2_2015.reset();
     731             :         }
     732             :     }
     733             :     {
     734         286 :         char *pszTmp = nullptr;
     735         286 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2019);
     736         286 :         pszWKT2_2019.reset(pszTmp);
     737         286 :         if (pszWKT2_2019 && pszWKT2_2019.get()[0] == '\0')
     738             :         {
     739           0 :             pszWKT2_2019.reset();
     740             :         }
     741             :     }
     742             : 
     743         286 :     if (!pszWKT1 && !pszWKT2_2015 && !pszWKT2_2019)
     744             :     {
     745           0 :         return DEFAULT_SRID;
     746             :     }
     747             : 
     748         286 :     if (poSRSIn->GetCoordinateEpoch() == 0 || m_bHasEpochColumn)
     749             :     {
     750             :         // Search if there is already an existing entry with this WKT
     751         283 :         if (m_bHasDefinition12_063 && (pszWKT2_2015 || pszWKT2_2019))
     752             :         {
     753          42 :             if (pszWKT1)
     754             :             {
     755         144 :                 pszSQL = sqlite3_mprintf(
     756             :                     "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     757             :                     "(definition = '%q' OR definition_12_063 IN ('%q','%q'))%s",
     758             :                     pszWKT1.get(),
     759          72 :                     pszWKT2_2015 ? pszWKT2_2015.get() : "invalid",
     760          72 :                     pszWKT2_2019 ? pszWKT2_2019.get() : "invalid",
     761             :                     osEpochTest.c_str());
     762             :             }
     763             :             else
     764             :             {
     765          24 :                 pszSQL = sqlite3_mprintf(
     766             :                     "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     767             :                     "definition_12_063 IN ('%q', '%q')%s",
     768          12 :                     pszWKT2_2015 ? pszWKT2_2015.get() : "invalid",
     769          12 :                     pszWKT2_2019 ? pszWKT2_2019.get() : "invalid",
     770             :                     osEpochTest.c_str());
     771             :             }
     772             :         }
     773         241 :         else if (pszWKT1)
     774             :         {
     775             :             pszSQL =
     776         238 :                 sqlite3_mprintf("SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     777             :                                 "definition = '%q'%s",
     778             :                                 pszWKT1.get(), osEpochTest.c_str());
     779             :         }
     780             :         else
     781             :         {
     782           3 :             pszSQL = nullptr;
     783             :         }
     784         283 :         if (pszSQL)
     785             :         {
     786         280 :             nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     787         280 :             sqlite3_free(pszSQL);
     788         280 :             if (OGRERR_NONE == err)
     789             :             {
     790           5 :                 return nSRSId;
     791             :             }
     792             :         }
     793             :     }
     794             : 
     795         538 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     796         257 :         poSRSIn->GetCoordinateEpoch() == 0)
     797             :     {
     798         253 :         bool bTryToReuseSRSId = true;
     799         253 :         if (EQUAL(pszAuthorityName, "EPSG"))
     800             :         {
     801         504 :             OGRSpatialReference oSRS_EPSG;
     802         252 :             if (GDALGPKGImportFromEPSG(&oSRS_EPSG, nAuthorityCode) ==
     803             :                 OGRERR_NONE)
     804             :             {
     805         253 :                 if (!poSRS->IsSame(&oSRS_EPSG, apszIsSameOptions) &&
     806           1 :                     CPLTestBool(
     807             :                         CPLGetConfigOption("OGR_GPKG_CHECK_SRS", "YES")))
     808             :                 {
     809           1 :                     bTryToReuseSRSId = false;
     810           1 :                     CPLError(
     811             :                         CE_Warning, CPLE_AppDefined,
     812             :                         "Passed SRS uses %s:%d identification, but its "
     813             :                         "definition is not compatible with the "
     814             :                         "official definition of the object. "
     815             :                         "Registering it as a non-%s entry into the database.",
     816             :                         pszAuthorityName, nAuthorityCode, pszAuthorityName);
     817           1 :                     pszAuthorityName = nullptr;
     818           1 :                     nAuthorityCode = 0;
     819             :                 }
     820             :             }
     821             :         }
     822         253 :         if (bTryToReuseSRSId)
     823             :         {
     824             :             // No match, but maybe we can use the nAuthorityCode as the nSRSId?
     825         252 :             pszSQL = sqlite3_mprintf(
     826             :                 "SELECT Count(*) FROM gpkg_spatial_ref_sys WHERE "
     827             :                 "srs_id = %d",
     828             :                 nAuthorityCode);
     829             : 
     830             :             // Yep, we can!
     831         252 :             if (SQLGetInteger(hDB, pszSQL, nullptr) == 0)
     832         251 :                 bCanUseAuthorityCode = true;
     833         252 :             sqlite3_free(pszSQL);
     834             :         }
     835             :     }
     836             : 
     837         281 :     bool bConvertGpkgSpatialRefSysToExtensionWkt2 = false;
     838         281 :     bool bForceEpoch = false;
     839         284 :     if (!m_bHasDefinition12_063 && pszWKT1 == nullptr &&
     840           3 :         (pszWKT2_2015 != nullptr || pszWKT2_2019 != nullptr))
     841             :     {
     842           3 :         bConvertGpkgSpatialRefSysToExtensionWkt2 = true;
     843             :     }
     844             : 
     845             :     // Add epoch column if needed
     846         281 :     if (poSRSIn->GetCoordinateEpoch() > 0 && !m_bHasEpochColumn)
     847             :     {
     848           3 :         if (m_bHasDefinition12_063)
     849             :         {
     850           0 :             if (SoftStartTransaction() != OGRERR_NONE)
     851           0 :                 return DEFAULT_SRID;
     852           0 :             if (SQLCommand(hDB, "ALTER TABLE gpkg_spatial_ref_sys "
     853           0 :                                 "ADD COLUMN epoch DOUBLE") != OGRERR_NONE ||
     854           0 :                 SQLCommand(hDB, "UPDATE gpkg_extensions SET extension_name = "
     855             :                                 "'gpkg_crs_wkt_1_1' "
     856             :                                 "WHERE extension_name = 'gpkg_crs_wkt'") !=
     857           0 :                     OGRERR_NONE ||
     858           0 :                 SQLCommand(
     859             :                     hDB,
     860             :                     "INSERT INTO gpkg_extensions "
     861             :                     "(table_name, column_name, extension_name, definition, "
     862             :                     "scope) "
     863             :                     "VALUES "
     864             :                     "('gpkg_spatial_ref_sys', 'epoch', 'gpkg_crs_wkt_1_1', "
     865             :                     "'http://www.geopackage.org/spec/#extension_crs_wkt', "
     866             :                     "'read-write')") != OGRERR_NONE)
     867             :             {
     868           0 :                 SoftRollbackTransaction();
     869           0 :                 return DEFAULT_SRID;
     870             :             }
     871             : 
     872           0 :             if (SoftCommitTransaction() != OGRERR_NONE)
     873           0 :                 return DEFAULT_SRID;
     874             : 
     875           0 :             m_bHasEpochColumn = true;
     876             :         }
     877             :         else
     878             :         {
     879           3 :             bConvertGpkgSpatialRefSysToExtensionWkt2 = true;
     880           3 :             bForceEpoch = true;
     881             :         }
     882             :     }
     883             : 
     884         287 :     if (bConvertGpkgSpatialRefSysToExtensionWkt2 &&
     885           6 :         !ConvertGpkgSpatialRefSysToExtensionWkt2(bForceEpoch))
     886             :     {
     887           0 :         return DEFAULT_SRID;
     888             :     }
     889             : 
     890             :     // Reuse the authority code number as SRS_ID if we can
     891         281 :     if (bCanUseAuthorityCode)
     892             :     {
     893         251 :         nSRSId = nAuthorityCode;
     894             :     }
     895             :     // Otherwise, generate a new SRS_ID number (max + 1)
     896             :     else
     897             :     {
     898             :         // Get the current maximum srid in the srs table.
     899          30 :         const int nMaxSRSId = SQLGetInteger(
     900             :             hDB, "SELECT MAX(srs_id) FROM gpkg_spatial_ref_sys", nullptr);
     901          30 :         nSRSId = std::max(FIRST_CUSTOM_SRSID, nMaxSRSId + 1);
     902             :     }
     903             : 
     904         562 :     std::string osEpochColumn;
     905         281 :     std::string osEpochVal;
     906         281 :     if (poSRSIn->GetCoordinateEpoch() > 0)
     907             :     {
     908           5 :         osEpochColumn = ", epoch";
     909           5 :         osEpochVal = CPLSPrintf(", %.17g", poSRSIn->GetCoordinateEpoch());
     910             :     }
     911             : 
     912             :     // Add new SRS row to gpkg_spatial_ref_sys.
     913         281 :     if (m_bHasDefinition12_063)
     914             :     {
     915             :         // Force WKT2_2019 when we have a dynamic CRS and coordinate epoch
     916          45 :         const char *pszWKT2 = poSRSIn->IsDynamic() &&
     917          10 :                                       poSRSIn->GetCoordinateEpoch() > 0 &&
     918           1 :                                       pszWKT2_2019
     919           1 :                                   ? pszWKT2_2019.get()
     920          44 :                               : pszWKT2_2015 ? pszWKT2_2015.get()
     921          97 :                                              : pszWKT2_2019.get();
     922             : 
     923          45 :         if (pszAuthorityName != nullptr && nAuthorityCode > 0)
     924             :         {
     925          99 :             pszSQL = sqlite3_mprintf(
     926             :                 "INSERT INTO gpkg_spatial_ref_sys "
     927             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     928             :                 "definition, definition_12_063%s) VALUES "
     929             :                 "('%q', %d, upper('%q'), %d, '%q', '%q'%s)",
     930          33 :                 osEpochColumn.c_str(), GetSrsName(*poSRS), nSRSId,
     931             :                 pszAuthorityName, nAuthorityCode,
     932          62 :                 pszWKT1 ? pszWKT1.get() : "undefined",
     933             :                 pszWKT2 ? pszWKT2 : "undefined", osEpochVal.c_str());
     934             :         }
     935             :         else
     936             :         {
     937          36 :             pszSQL = sqlite3_mprintf(
     938             :                 "INSERT INTO gpkg_spatial_ref_sys "
     939             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     940             :                 "definition, definition_12_063%s) VALUES "
     941             :                 "('%q', %d, upper('%q'), %d, '%q', '%q'%s)",
     942          12 :                 osEpochColumn.c_str(), GetSrsName(*poSRS), nSRSId, "NONE",
     943          21 :                 nSRSId, pszWKT1 ? pszWKT1.get() : "undefined",
     944             :                 pszWKT2 ? pszWKT2 : "undefined", osEpochVal.c_str());
     945             :         }
     946             :     }
     947             :     else
     948             :     {
     949         236 :         if (pszAuthorityName != nullptr && nAuthorityCode > 0)
     950             :         {
     951         446 :             pszSQL = sqlite3_mprintf(
     952             :                 "INSERT INTO gpkg_spatial_ref_sys "
     953             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     954             :                 "definition) VALUES ('%q', %d, upper('%q'), %d, '%q')",
     955         223 :                 GetSrsName(*poSRS), nSRSId, pszAuthorityName, nAuthorityCode,
     956         446 :                 pszWKT1 ? pszWKT1.get() : "undefined");
     957             :         }
     958             :         else
     959             :         {
     960          26 :             pszSQL = sqlite3_mprintf(
     961             :                 "INSERT INTO gpkg_spatial_ref_sys "
     962             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     963             :                 "definition) VALUES ('%q', %d, upper('%q'), %d, '%q')",
     964          13 :                 GetSrsName(*poSRS), nSRSId, "NONE", nSRSId,
     965          26 :                 pszWKT1 ? pszWKT1.get() : "undefined");
     966             :         }
     967             :     }
     968             : 
     969             :     // Add new row to gpkg_spatial_ref_sys.
     970         281 :     CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
     971             : 
     972             :     // Free everything that was allocated.
     973         281 :     sqlite3_free(pszSQL);
     974             : 
     975         281 :     return nSRSId;
     976             : }
     977             : 
     978             : /************************************************************************/
     979             : /*                       ~GDALGeoPackageDataset()                       */
     980             : /************************************************************************/
     981             : 
     982        5156 : GDALGeoPackageDataset::~GDALGeoPackageDataset()
     983             : {
     984        2578 :     GDALGeoPackageDataset::Close();
     985        5156 : }
     986             : 
     987             : /************************************************************************/
     988             : /*                              Close()                                 */
     989             : /************************************************************************/
     990             : 
     991        4322 : CPLErr GDALGeoPackageDataset::Close()
     992             : {
     993        4322 :     CPLErr eErr = CE_None;
     994        4322 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     995             :     {
     996        1519 :         if (eAccess == GA_Update && m_poParentDS == nullptr &&
     997        4097 :             !m_osRasterTable.empty() && !m_bGeoTransformValid)
     998             :         {
     999           3 :             CPLError(CE_Failure, CPLE_AppDefined,
    1000             :                      "Raster table %s not correctly initialized due to missing "
    1001             :                      "call to SetGeoTransform()",
    1002             :                      m_osRasterTable.c_str());
    1003             :         }
    1004             : 
    1005        5147 :         if (!IsMarkedSuppressOnClose() &&
    1006        2569 :             GDALGeoPackageDataset::FlushCache(true) != CE_None)
    1007             :         {
    1008           7 :             eErr = CE_Failure;
    1009             :         }
    1010             : 
    1011             :         // Destroy bands now since we don't want
    1012             :         // GDALGPKGMBTilesLikeRasterBand::FlushCache() to run after dataset
    1013             :         // destruction
    1014        4395 :         for (int i = 0; i < nBands; i++)
    1015        1817 :             delete papoBands[i];
    1016        2578 :         nBands = 0;
    1017        2578 :         CPLFree(papoBands);
    1018        2578 :         papoBands = nullptr;
    1019             : 
    1020             :         // Destroy overviews before cleaning m_hTempDB as they could still
    1021             :         // need it
    1022        2578 :         m_apoOverviewDS.clear();
    1023             : 
    1024        2578 :         if (m_poParentDS)
    1025             :         {
    1026         325 :             hDB = nullptr;
    1027             :         }
    1028             : 
    1029        2578 :         m_apoLayers.clear();
    1030             : 
    1031             :         std::map<int, OGRSpatialReference *>::iterator oIter =
    1032        2578 :             m_oMapSrsIdToSrs.begin();
    1033        3741 :         for (; oIter != m_oMapSrsIdToSrs.end(); ++oIter)
    1034             :         {
    1035        1163 :             OGRSpatialReference *poSRS = oIter->second;
    1036        1163 :             if (poSRS)
    1037         711 :                 poSRS->Release();
    1038             :         }
    1039             : 
    1040        2578 :         if (!CloseDB())
    1041           0 :             eErr = CE_Failure;
    1042             : 
    1043        2578 :         if (OGRSQLiteBaseDataSource::Close() != CE_None)
    1044           0 :             eErr = CE_Failure;
    1045             :     }
    1046        4322 :     return eErr;
    1047             : }
    1048             : 
    1049             : /************************************************************************/
    1050             : /*                         ICanIWriteBlock()                            */
    1051             : /************************************************************************/
    1052             : 
    1053        5696 : bool GDALGeoPackageDataset::ICanIWriteBlock()
    1054             : {
    1055        5696 :     if (!GetUpdate())
    1056             :     {
    1057           0 :         CPLError(
    1058             :             CE_Failure, CPLE_NotSupported,
    1059             :             "IWriteBlock() not supported on dataset opened in read-only mode");
    1060           0 :         return false;
    1061             :     }
    1062             : 
    1063        5696 :     if (m_pabyCachedTiles == nullptr)
    1064             :     {
    1065           0 :         return false;
    1066             :     }
    1067             : 
    1068        5696 :     if (!m_bGeoTransformValid || m_nSRID == UNKNOWN_SRID)
    1069             :     {
    1070           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    1071             :                  "IWriteBlock() not supported if georeferencing not set");
    1072           0 :         return false;
    1073             :     }
    1074        5696 :     return true;
    1075             : }
    1076             : 
    1077             : /************************************************************************/
    1078             : /*                            IRasterIO()                               */
    1079             : /************************************************************************/
    1080             : 
    1081         132 : CPLErr GDALGeoPackageDataset::IRasterIO(
    1082             :     GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
    1083             :     void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
    1084             :     int nBandCount, BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
    1085             :     GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg)
    1086             : 
    1087             : {
    1088         132 :     CPLErr eErr = OGRSQLiteBaseDataSource::IRasterIO(
    1089             :         eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    1090             :         eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
    1091             :         psExtraArg);
    1092             : 
    1093             :     // If writing all bands, in non-shifted mode, flush all entirely written
    1094             :     // tiles This can avoid "stressing" the block cache with too many dirty
    1095             :     // blocks. Note: this logic would be useless with a per-dataset block cache.
    1096         132 :     if (eErr == CE_None && eRWFlag == GF_Write && nXSize == nBufXSize &&
    1097         123 :         nYSize == nBufYSize && nBandCount == nBands &&
    1098         120 :         m_nShiftXPixelsMod == 0 && m_nShiftYPixelsMod == 0)
    1099             :     {
    1100             :         auto poBand =
    1101         116 :             cpl::down_cast<GDALGPKGMBTilesLikeRasterBand *>(GetRasterBand(1));
    1102             :         int nBlockXSize, nBlockYSize;
    1103         116 :         poBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
    1104         116 :         const int nBlockXStart = DIV_ROUND_UP(nXOff, nBlockXSize);
    1105         116 :         const int nBlockYStart = DIV_ROUND_UP(nYOff, nBlockYSize);
    1106         116 :         const int nBlockXEnd = (nXOff + nXSize) / nBlockXSize;
    1107         116 :         const int nBlockYEnd = (nYOff + nYSize) / nBlockYSize;
    1108         270 :         for (int nBlockY = nBlockXStart; nBlockY < nBlockYEnd; nBlockY++)
    1109             :         {
    1110        4371 :             for (int nBlockX = nBlockYStart; nBlockX < nBlockXEnd; nBlockX++)
    1111             :             {
    1112             :                 GDALRasterBlock *poBlock =
    1113        4217 :                     poBand->AccessibleTryGetLockedBlockRef(nBlockX, nBlockY);
    1114        4217 :                 if (poBlock)
    1115             :                 {
    1116             :                     // GetDirty() should be true in most situation (otherwise
    1117             :                     // it means the block cache is under extreme pressure!)
    1118        4215 :                     if (poBlock->GetDirty())
    1119             :                     {
    1120             :                         // IWriteBlock() on one band will check the dirty state
    1121             :                         // of the corresponding blocks in other bands, to decide
    1122             :                         // if it can call WriteTile(), so we have only to do
    1123             :                         // that on one of the bands
    1124        4215 :                         if (poBlock->Write() != CE_None)
    1125         250 :                             eErr = CE_Failure;
    1126             :                     }
    1127        4215 :                     poBlock->DropLock();
    1128             :                 }
    1129             :             }
    1130             :         }
    1131             :     }
    1132             : 
    1133         132 :     return eErr;
    1134             : }
    1135             : 
    1136             : /************************************************************************/
    1137             : /*                          GetOGRTableLimit()                          */
    1138             : /************************************************************************/
    1139             : 
    1140        4200 : static int GetOGRTableLimit()
    1141             : {
    1142        4200 :     return atoi(CPLGetConfigOption("OGR_TABLE_LIMIT", "10000"));
    1143             : }
    1144             : 
    1145             : /************************************************************************/
    1146             : /*                      GetNameTypeMapFromSQliteMaster()                */
    1147             : /************************************************************************/
    1148             : 
    1149             : const std::map<CPLString, CPLString> &
    1150        1301 : GDALGeoPackageDataset::GetNameTypeMapFromSQliteMaster()
    1151             : {
    1152        1301 :     if (!m_oMapNameToType.empty())
    1153         345 :         return m_oMapNameToType;
    1154             : 
    1155             :     CPLString osSQL(
    1156             :         "SELECT name, type FROM sqlite_master WHERE "
    1157             :         "type IN ('view', 'table') OR "
    1158        1912 :         "(name LIKE 'trigger_%_feature_count_%' AND type = 'trigger')");
    1159         956 :     const int nTableLimit = GetOGRTableLimit();
    1160         956 :     if (nTableLimit > 0)
    1161             :     {
    1162         956 :         osSQL += " LIMIT ";
    1163         956 :         osSQL += CPLSPrintf("%d", 1 + 3 * nTableLimit);
    1164             :     }
    1165             : 
    1166         956 :     auto oResult = SQLQuery(hDB, osSQL);
    1167         956 :     if (oResult)
    1168             :     {
    1169       15887 :         for (int i = 0; i < oResult->RowCount(); i++)
    1170             :         {
    1171       14931 :             const char *pszName = oResult->GetValue(0, i);
    1172       14931 :             const char *pszType = oResult->GetValue(1, i);
    1173       14931 :             m_oMapNameToType[CPLString(pszName).toupper()] = pszType;
    1174             :         }
    1175             :     }
    1176             : 
    1177         956 :     return m_oMapNameToType;
    1178             : }
    1179             : 
    1180             : /************************************************************************/
    1181             : /*                    RemoveTableFromSQLiteMasterCache()                */
    1182             : /************************************************************************/
    1183             : 
    1184          56 : void GDALGeoPackageDataset::RemoveTableFromSQLiteMasterCache(
    1185             :     const char *pszTableName)
    1186             : {
    1187          56 :     m_oMapNameToType.erase(CPLString(pszTableName).toupper());
    1188          56 : }
    1189             : 
    1190             : /************************************************************************/
    1191             : /*                  GetUnknownExtensionsTableSpecific()                 */
    1192             : /************************************************************************/
    1193             : 
    1194             : const std::map<CPLString, std::vector<GPKGExtensionDesc>> &
    1195         912 : GDALGeoPackageDataset::GetUnknownExtensionsTableSpecific()
    1196             : {
    1197         912 :     if (m_bMapTableToExtensionsBuilt)
    1198          92 :         return m_oMapTableToExtensions;
    1199         820 :     m_bMapTableToExtensionsBuilt = true;
    1200             : 
    1201         820 :     if (!HasExtensionsTable())
    1202          51 :         return m_oMapTableToExtensions;
    1203             : 
    1204             :     CPLString osSQL(
    1205             :         "SELECT table_name, extension_name, definition, scope "
    1206             :         "FROM gpkg_extensions WHERE "
    1207             :         "table_name IS NOT NULL "
    1208             :         "AND extension_name IS NOT NULL "
    1209             :         "AND definition IS NOT NULL "
    1210             :         "AND scope IS NOT NULL "
    1211             :         "AND extension_name NOT IN ('gpkg_geom_CIRCULARSTRING', "
    1212             :         "'gpkg_geom_COMPOUNDCURVE', 'gpkg_geom_CURVEPOLYGON', "
    1213             :         "'gpkg_geom_MULTICURVE', "
    1214             :         "'gpkg_geom_MULTISURFACE', 'gpkg_geom_CURVE', 'gpkg_geom_SURFACE', "
    1215             :         "'gpkg_geom_POLYHEDRALSURFACE', 'gpkg_geom_TIN', 'gpkg_geom_TRIANGLE', "
    1216             :         "'gpkg_rtree_index', 'gpkg_geometry_type_trigger', "
    1217             :         "'gpkg_srs_id_trigger', "
    1218             :         "'gpkg_crs_wkt', 'gpkg_crs_wkt_1_1', 'gpkg_schema', "
    1219             :         "'gpkg_related_tables', 'related_tables'"
    1220             : #ifdef HAVE_SPATIALITE
    1221             :         ", 'gdal_spatialite_computed_geom_column'"
    1222             : #endif
    1223        1538 :         ")");
    1224         769 :     const int nTableLimit = GetOGRTableLimit();
    1225         769 :     if (nTableLimit > 0)
    1226             :     {
    1227         769 :         osSQL += " LIMIT ";
    1228         769 :         osSQL += CPLSPrintf("%d", 1 + 10 * nTableLimit);
    1229             :     }
    1230             : 
    1231         769 :     auto oResult = SQLQuery(hDB, osSQL);
    1232         769 :     if (oResult)
    1233             :     {
    1234        1428 :         for (int i = 0; i < oResult->RowCount(); i++)
    1235             :         {
    1236         659 :             const char *pszTableName = oResult->GetValue(0, i);
    1237         659 :             const char *pszExtensionName = oResult->GetValue(1, i);
    1238         659 :             const char *pszDefinition = oResult->GetValue(2, i);
    1239         659 :             const char *pszScope = oResult->GetValue(3, i);
    1240         659 :             if (pszTableName && pszExtensionName && pszDefinition && pszScope)
    1241             :             {
    1242         659 :                 GPKGExtensionDesc oDesc;
    1243         659 :                 oDesc.osExtensionName = pszExtensionName;
    1244         659 :                 oDesc.osDefinition = pszDefinition;
    1245         659 :                 oDesc.osScope = pszScope;
    1246        1318 :                 m_oMapTableToExtensions[CPLString(pszTableName).toupper()]
    1247         659 :                     .push_back(std::move(oDesc));
    1248             :             }
    1249             :         }
    1250             :     }
    1251             : 
    1252         769 :     return m_oMapTableToExtensions;
    1253             : }
    1254             : 
    1255             : /************************************************************************/
    1256             : /*                           GetContents()                              */
    1257             : /************************************************************************/
    1258             : 
    1259             : const std::map<CPLString, GPKGContentsDesc> &
    1260         894 : GDALGeoPackageDataset::GetContents()
    1261             : {
    1262         894 :     if (m_bMapTableToContentsBuilt)
    1263          76 :         return m_oMapTableToContents;
    1264         818 :     m_bMapTableToContentsBuilt = true;
    1265             : 
    1266             :     CPLString osSQL("SELECT table_name, data_type, identifier, "
    1267             :                     "description, min_x, min_y, max_x, max_y "
    1268        1636 :                     "FROM gpkg_contents");
    1269         818 :     const int nTableLimit = GetOGRTableLimit();
    1270         818 :     if (nTableLimit > 0)
    1271             :     {
    1272         818 :         osSQL += " LIMIT ";
    1273         818 :         osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1274             :     }
    1275             : 
    1276         818 :     auto oResult = SQLQuery(hDB, osSQL);
    1277         818 :     if (oResult)
    1278             :     {
    1279        1757 :         for (int i = 0; i < oResult->RowCount(); i++)
    1280             :         {
    1281         939 :             const char *pszTableName = oResult->GetValue(0, i);
    1282         939 :             if (pszTableName == nullptr)
    1283           0 :                 continue;
    1284         939 :             const char *pszDataType = oResult->GetValue(1, i);
    1285         939 :             const char *pszIdentifier = oResult->GetValue(2, i);
    1286         939 :             const char *pszDescription = oResult->GetValue(3, i);
    1287         939 :             const char *pszMinX = oResult->GetValue(4, i);
    1288         939 :             const char *pszMinY = oResult->GetValue(5, i);
    1289         939 :             const char *pszMaxX = oResult->GetValue(6, i);
    1290         939 :             const char *pszMaxY = oResult->GetValue(7, i);
    1291         939 :             GPKGContentsDesc oDesc;
    1292         939 :             if (pszDataType)
    1293         939 :                 oDesc.osDataType = pszDataType;
    1294         939 :             if (pszIdentifier)
    1295         939 :                 oDesc.osIdentifier = pszIdentifier;
    1296         939 :             if (pszDescription)
    1297         938 :                 oDesc.osDescription = pszDescription;
    1298         939 :             if (pszMinX)
    1299         627 :                 oDesc.osMinX = pszMinX;
    1300         939 :             if (pszMinY)
    1301         627 :                 oDesc.osMinY = pszMinY;
    1302         939 :             if (pszMaxX)
    1303         627 :                 oDesc.osMaxX = pszMaxX;
    1304         939 :             if (pszMaxY)
    1305         627 :                 oDesc.osMaxY = pszMaxY;
    1306        1878 :             m_oMapTableToContents[CPLString(pszTableName).toupper()] =
    1307        1878 :                 std::move(oDesc);
    1308             :         }
    1309             :     }
    1310             : 
    1311         818 :     return m_oMapTableToContents;
    1312             : }
    1313             : 
    1314             : /************************************************************************/
    1315             : /*                                Open()                                */
    1316             : /************************************************************************/
    1317             : 
    1318        1276 : int GDALGeoPackageDataset::Open(GDALOpenInfo *poOpenInfo,
    1319             :                                 const std::string &osFilenameInZip)
    1320             : {
    1321        1276 :     m_osFilenameInZip = osFilenameInZip;
    1322        1276 :     CPLAssert(m_apoLayers.empty());
    1323        1276 :     CPLAssert(hDB == nullptr);
    1324             : 
    1325        1276 :     SetDescription(poOpenInfo->pszFilename);
    1326        2552 :     CPLString osFilename(poOpenInfo->pszFilename);
    1327        2552 :     CPLString osSubdatasetTableName;
    1328             :     GByte abyHeaderLetMeHerePlease[100];
    1329        1276 :     const GByte *pabyHeader = poOpenInfo->pabyHeader;
    1330        1276 :     if (STARTS_WITH_CI(poOpenInfo->pszFilename, "GPKG:"))
    1331             :     {
    1332         247 :         char **papszTokens = CSLTokenizeString2(poOpenInfo->pszFilename, ":",
    1333             :                                                 CSLT_HONOURSTRINGS);
    1334         247 :         int nCount = CSLCount(papszTokens);
    1335         247 :         if (nCount < 2)
    1336             :         {
    1337           0 :             CSLDestroy(papszTokens);
    1338           0 :             return FALSE;
    1339             :         }
    1340             : 
    1341         247 :         if (nCount <= 3)
    1342             :         {
    1343         245 :             osFilename = papszTokens[1];
    1344             :         }
    1345             :         /* GPKG:C:\BLA.GPKG:foo */
    1346           2 :         else if (nCount == 4 && strlen(papszTokens[1]) == 1 &&
    1347           2 :                  (papszTokens[2][0] == '/' || papszTokens[2][0] == '\\'))
    1348             :         {
    1349           2 :             osFilename = CPLString(papszTokens[1]) + ":" + papszTokens[2];
    1350             :         }
    1351             :         // GPKG:/vsicurl/http[s]://[user:passwd@]example.com[:8080]/foo.gpkg:bar
    1352           0 :         else if (/*nCount >= 4 && */
    1353           0 :                  (EQUAL(papszTokens[1], "/vsicurl/http") ||
    1354           0 :                   EQUAL(papszTokens[1], "/vsicurl/https")))
    1355             :         {
    1356           0 :             osFilename = CPLString(papszTokens[1]);
    1357           0 :             for (int i = 2; i < nCount - 1; i++)
    1358             :             {
    1359           0 :                 osFilename += ':';
    1360           0 :                 osFilename += papszTokens[i];
    1361             :             }
    1362             :         }
    1363         247 :         if (nCount >= 3)
    1364          14 :             osSubdatasetTableName = papszTokens[nCount - 1];
    1365             : 
    1366         247 :         CSLDestroy(papszTokens);
    1367         247 :         VSILFILE *fp = VSIFOpenL(osFilename, "rb");
    1368         247 :         if (fp != nullptr)
    1369             :         {
    1370         247 :             VSIFReadL(abyHeaderLetMeHerePlease, 1, 100, fp);
    1371         247 :             VSIFCloseL(fp);
    1372             :         }
    1373         247 :         pabyHeader = abyHeaderLetMeHerePlease;
    1374             :     }
    1375        1029 :     else if (poOpenInfo->pabyHeader &&
    1376        1029 :              STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1377             :                          "SQLite format 3"))
    1378             :     {
    1379        1022 :         m_bCallUndeclareFileNotToOpen = true;
    1380        1022 :         GDALOpenInfoDeclareFileNotToOpen(osFilename, poOpenInfo->pabyHeader,
    1381             :                                          poOpenInfo->nHeaderBytes);
    1382             :     }
    1383             : 
    1384        1276 :     eAccess = poOpenInfo->eAccess;
    1385        1276 :     if (!m_osFilenameInZip.empty())
    1386             :     {
    1387           2 :         m_pszFilename = CPLStrdup(CPLSPrintf(
    1388             :             "/vsizip/{%s}/%s", osFilename.c_str(), m_osFilenameInZip.c_str()));
    1389             :     }
    1390             :     else
    1391             :     {
    1392        1274 :         m_pszFilename = CPLStrdup(osFilename);
    1393             :     }
    1394             : 
    1395        1276 :     if (poOpenInfo->papszOpenOptions)
    1396             :     {
    1397         100 :         CSLDestroy(papszOpenOptions);
    1398         100 :         papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
    1399             :     }
    1400             : 
    1401             : #ifdef ENABLE_SQL_GPKG_FORMAT
    1402        1276 :     if (poOpenInfo->pabyHeader &&
    1403        1029 :         STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1404           5 :                     "-- SQL GPKG") &&
    1405           5 :         poOpenInfo->fpL != nullptr)
    1406             :     {
    1407           5 :         if (sqlite3_open_v2(":memory:", &hDB, SQLITE_OPEN_READWRITE, nullptr) !=
    1408             :             SQLITE_OK)
    1409             :         {
    1410           0 :             return FALSE;
    1411             :         }
    1412             : 
    1413           5 :         InstallSQLFunctions();
    1414             : 
    1415             :         // Ingest the lines of the dump
    1416           5 :         VSIFSeekL(poOpenInfo->fpL, 0, SEEK_SET);
    1417             :         const char *pszLine;
    1418          76 :         while ((pszLine = CPLReadLineL(poOpenInfo->fpL)) != nullptr)
    1419             :         {
    1420          71 :             if (STARTS_WITH(pszLine, "--"))
    1421           5 :                 continue;
    1422             : 
    1423          66 :             if (!SQLCheckLineIsSafe(pszLine))
    1424           0 :                 return false;
    1425             : 
    1426          66 :             char *pszErrMsg = nullptr;
    1427          66 :             if (sqlite3_exec(hDB, pszLine, nullptr, nullptr, &pszErrMsg) !=
    1428             :                 SQLITE_OK)
    1429             :             {
    1430           0 :                 if (pszErrMsg)
    1431           0 :                     CPLDebug("SQLITE", "Error %s", pszErrMsg);
    1432             :             }
    1433          66 :             sqlite3_free(pszErrMsg);
    1434           5 :         }
    1435             :     }
    1436             : 
    1437        1271 :     else if (pabyHeader != nullptr)
    1438             : #endif
    1439             :     {
    1440        1271 :         if (poOpenInfo->fpL)
    1441             :         {
    1442             :             // See above comment about -wal locking for the importance of
    1443             :             // closing that file, prior to calling sqlite3_open()
    1444         924 :             VSIFCloseL(poOpenInfo->fpL);
    1445         924 :             poOpenInfo->fpL = nullptr;
    1446             :         }
    1447             : 
    1448             :         /* See if we can open the SQLite database */
    1449        1271 :         if (!OpenOrCreateDB(GetUpdate() ? SQLITE_OPEN_READWRITE
    1450             :                                         : SQLITE_OPEN_READONLY))
    1451           2 :             return FALSE;
    1452             : 
    1453        1269 :         memcpy(&m_nApplicationId, pabyHeader + knApplicationIdPos, 4);
    1454        1269 :         m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    1455        1269 :         memcpy(&m_nUserVersion, pabyHeader + knUserVersionPos, 4);
    1456        1269 :         m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    1457        1269 :         if (m_nApplicationId == GP10_APPLICATION_ID)
    1458             :         {
    1459           7 :             CPLDebug("GPKG", "GeoPackage v1.0");
    1460             :         }
    1461        1262 :         else if (m_nApplicationId == GP11_APPLICATION_ID)
    1462             :         {
    1463           2 :             CPLDebug("GPKG", "GeoPackage v1.1");
    1464             :         }
    1465        1260 :         else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    1466        1256 :                  m_nUserVersion >= GPKG_1_2_VERSION)
    1467             :         {
    1468        1254 :             CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    1469        1254 :                      (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    1470             :         }
    1471             :     }
    1472             : 
    1473             :     /* Requirement 6: The SQLite PRAGMA integrity_check SQL command SHALL return
    1474             :      * “ok” */
    1475             :     /* http://opengis.github.io/geopackage/#_file_integrity */
    1476             :     /* Disable integrity check by default, since it is expensive on big files */
    1477        1274 :     if (CPLTestBool(CPLGetConfigOption("OGR_GPKG_INTEGRITY_CHECK", "NO")) &&
    1478           0 :         OGRERR_NONE != PragmaCheck("integrity_check", "ok", 1))
    1479             :     {
    1480           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1481             :                  "pragma integrity_check on '%s' failed", m_pszFilename);
    1482           0 :         return FALSE;
    1483             :     }
    1484             : 
    1485             :     /* Requirement 7: The SQLite PRAGMA foreign_key_check() SQL with no */
    1486             :     /* parameter value SHALL return an empty result set */
    1487             :     /* http://opengis.github.io/geopackage/#_file_integrity */
    1488             :     /* Disable the check by default, since it is to corrupt databases, and */
    1489             :     /* that causes issues to downstream software that can't open them. */
    1490        1274 :     if (CPLTestBool(CPLGetConfigOption("OGR_GPKG_FOREIGN_KEY_CHECK", "NO")) &&
    1491           0 :         OGRERR_NONE != PragmaCheck("foreign_key_check", "", 0))
    1492             :     {
    1493           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1494             :                  "pragma foreign_key_check on '%s' failed.", m_pszFilename);
    1495           0 :         return FALSE;
    1496             :     }
    1497             : 
    1498             :     /* Check for requirement metadata tables */
    1499             :     /* Requirement 10: gpkg_spatial_ref_sys must exist */
    1500             :     /* Requirement 13: gpkg_contents must exist */
    1501        1274 :     if (SQLGetInteger(hDB,
    1502             :                       "SELECT COUNT(*) FROM sqlite_master WHERE "
    1503             :                       "name IN ('gpkg_spatial_ref_sys', 'gpkg_contents') AND "
    1504             :                       "type IN ('table', 'view')",
    1505        1274 :                       nullptr) != 2)
    1506             :     {
    1507           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1508             :                  "At least one of the required GeoPackage tables, "
    1509             :                  "gpkg_spatial_ref_sys or gpkg_contents, is missing");
    1510           0 :         return FALSE;
    1511             :     }
    1512             : 
    1513        1274 :     DetectSpatialRefSysColumns();
    1514             : 
    1515             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    1516        1274 :     if (SQLGetInteger(hDB,
    1517             :                       "SELECT 1 FROM sqlite_master WHERE "
    1518             :                       "name = 'gpkg_ogr_contents' AND type = 'table'",
    1519        1274 :                       nullptr) == 1)
    1520             :     {
    1521        1266 :         m_bHasGPKGOGRContents = true;
    1522             :     }
    1523             : #endif
    1524             : 
    1525        1274 :     CheckUnknownExtensions();
    1526             : 
    1527        1274 :     int bRet = FALSE;
    1528        1274 :     bool bHasGPKGExtRelations = false;
    1529        1274 :     if (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR)
    1530             :     {
    1531        1087 :         m_bHasGPKGGeometryColumns =
    1532        1087 :             SQLGetInteger(hDB,
    1533             :                           "SELECT 1 FROM sqlite_master WHERE "
    1534             :                           "name = 'gpkg_geometry_columns' AND "
    1535             :                           "type IN ('table', 'view')",
    1536        1087 :                           nullptr) == 1;
    1537        1087 :         bHasGPKGExtRelations = HasGpkgextRelationsTable();
    1538             :     }
    1539        1274 :     if (m_bHasGPKGGeometryColumns)
    1540             :     {
    1541             :         /* Load layer definitions for all tables in gpkg_contents &
    1542             :          * gpkg_geometry_columns */
    1543             :         /* and non-spatial tables as well */
    1544             :         std::string osSQL =
    1545             :             "SELECT c.table_name, c.identifier, 1 as is_spatial, "
    1546             :             "g.column_name, g.geometry_type_name, g.z, g.m, c.min_x, c.min_y, "
    1547             :             "c.max_x, c.max_y, 1 AS is_in_gpkg_contents, "
    1548             :             "(SELECT type FROM sqlite_master WHERE lower(name) = "
    1549             :             "lower(c.table_name) AND type IN ('table', 'view')) AS object_type "
    1550             :             "  FROM gpkg_geometry_columns g "
    1551             :             "  JOIN gpkg_contents c ON (g.table_name = c.table_name)"
    1552             :             "  WHERE "
    1553             :             "  c.table_name <> 'ogr_empty_table' AND"
    1554             :             "  c.data_type = 'features' "
    1555             :             // aspatial: Was the only method available in OGR 2.0 and 2.1
    1556             :             // attributes: GPKG 1.2 or later
    1557             :             "UNION ALL "
    1558             :             "SELECT table_name, identifier, 0 as is_spatial, NULL, NULL, 0, 0, "
    1559             :             "0 AS xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 1 AS "
    1560             :             "is_in_gpkg_contents, "
    1561             :             "(SELECT type FROM sqlite_master WHERE lower(name) = "
    1562             :             "lower(table_name) AND type IN ('table', 'view')) AS object_type "
    1563             :             "  FROM gpkg_contents"
    1564        1086 :             "  WHERE data_type IN ('aspatial', 'attributes') ";
    1565             : 
    1566        2172 :         const char *pszListAllTables = CSLFetchNameValueDef(
    1567        1086 :             poOpenInfo->papszOpenOptions, "LIST_ALL_TABLES", "AUTO");
    1568        1086 :         bool bHasASpatialOrAttributes = HasGDALAspatialExtension();
    1569        1086 :         if (!bHasASpatialOrAttributes)
    1570             :         {
    1571             :             auto oResultTable =
    1572             :                 SQLQuery(hDB, "SELECT * FROM gpkg_contents WHERE "
    1573        1085 :                               "data_type = 'attributes' LIMIT 1");
    1574        1085 :             bHasASpatialOrAttributes =
    1575        1085 :                 (oResultTable && oResultTable->RowCount() == 1);
    1576             :         }
    1577        1086 :         if (bHasGPKGExtRelations)
    1578             :         {
    1579             :             osSQL += "UNION ALL "
    1580             :                      "SELECT mapping_table_name, mapping_table_name, 0 as "
    1581             :                      "is_spatial, NULL, NULL, 0, 0, 0 AS "
    1582             :                      "xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 0 AS "
    1583             :                      "is_in_gpkg_contents, 'table' AS object_type "
    1584             :                      "FROM gpkgext_relations WHERE "
    1585             :                      "lower(mapping_table_name) NOT IN (SELECT "
    1586             :                      "lower(table_name) FROM gpkg_contents) AND "
    1587             :                      "EXISTS (SELECT 1 FROM sqlite_master WHERE "
    1588             :                      "type IN ('table', 'view') AND "
    1589          18 :                      "lower(name) = lower(mapping_table_name))";
    1590             :         }
    1591        1086 :         if (EQUAL(pszListAllTables, "YES") ||
    1592        1085 :             (!bHasASpatialOrAttributes && EQUAL(pszListAllTables, "AUTO")))
    1593             :         {
    1594             :             // vgpkg_ is Spatialite virtual table
    1595             :             osSQL +=
    1596             :                 "UNION ALL "
    1597             :                 "SELECT name, name, 0 as is_spatial, NULL, NULL, 0, 0, 0 AS "
    1598             :                 "xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 0 AS "
    1599             :                 "is_in_gpkg_contents, type AS object_type "
    1600             :                 "FROM sqlite_master WHERE type IN ('table', 'view') "
    1601             :                 "AND name NOT LIKE 'gpkg_%' "
    1602             :                 "AND name NOT LIKE 'vgpkg_%' "
    1603             :                 "AND name NOT LIKE 'rtree_%' AND name NOT LIKE 'sqlite_%' "
    1604             :                 // Avoid reading those views from simple_sewer_features.gpkg
    1605             :                 "AND name NOT IN ('st_spatial_ref_sys', 'spatial_ref_sys', "
    1606             :                 "'st_geometry_columns', 'geometry_columns') "
    1607             :                 "AND lower(name) NOT IN (SELECT lower(table_name) FROM "
    1608        1017 :                 "gpkg_contents)";
    1609        1017 :             if (bHasGPKGExtRelations)
    1610             :             {
    1611             :                 osSQL += " AND lower(name) NOT IN (SELECT "
    1612             :                          "lower(mapping_table_name) FROM "
    1613          13 :                          "gpkgext_relations)";
    1614             :             }
    1615             :         }
    1616        1086 :         const int nTableLimit = GetOGRTableLimit();
    1617        1086 :         if (nTableLimit > 0)
    1618             :         {
    1619        1086 :             osSQL += " LIMIT ";
    1620        1086 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1621             :         }
    1622             : 
    1623        1086 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1624        1086 :         if (!oResult)
    1625             :         {
    1626           0 :             return FALSE;
    1627             :         }
    1628             : 
    1629        1086 :         if (nTableLimit > 0 && oResult->RowCount() > nTableLimit)
    1630             :         {
    1631           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    1632             :                      "File has more than %d vector tables. "
    1633             :                      "Limiting to first %d (can be overridden with "
    1634             :                      "OGR_TABLE_LIMIT config option)",
    1635             :                      nTableLimit, nTableLimit);
    1636           1 :             oResult->LimitRowCount(nTableLimit);
    1637             :         }
    1638             : 
    1639        1086 :         if (oResult->RowCount() > 0)
    1640             :         {
    1641         969 :             bRet = TRUE;
    1642             : 
    1643         969 :             m_apoLayers.reserve(oResult->RowCount());
    1644             : 
    1645        1938 :             std::map<std::string, int> oMapTableRefCount;
    1646        4137 :             for (int i = 0; i < oResult->RowCount(); i++)
    1647             :             {
    1648        3168 :                 const char *pszTableName = oResult->GetValue(0, i);
    1649        3168 :                 if (pszTableName == nullptr)
    1650           0 :                     continue;
    1651        3168 :                 if (++oMapTableRefCount[pszTableName] == 2)
    1652             :                 {
    1653             :                     // This should normally not happen if all constraints are
    1654             :                     // properly set
    1655           2 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1656             :                              "Table %s appearing several times in "
    1657             :                              "gpkg_contents and/or gpkg_geometry_columns",
    1658             :                              pszTableName);
    1659             :                 }
    1660             :             }
    1661             : 
    1662        1938 :             std::set<std::string> oExistingLayers;
    1663        4137 :             for (int i = 0; i < oResult->RowCount(); i++)
    1664             :             {
    1665        3168 :                 const char *pszTableName = oResult->GetValue(0, i);
    1666        3168 :                 if (pszTableName == nullptr)
    1667           2 :                     continue;
    1668             :                 const bool bTableHasSeveralGeomColumns =
    1669        3168 :                     oMapTableRefCount[pszTableName] > 1;
    1670        3168 :                 bool bIsSpatial = CPL_TO_BOOL(oResult->GetValueAsInteger(2, i));
    1671        3168 :                 const char *pszGeomColName = oResult->GetValue(3, i);
    1672        3168 :                 const char *pszGeomType = oResult->GetValue(4, i);
    1673        3168 :                 const char *pszZ = oResult->GetValue(5, i);
    1674        3168 :                 const char *pszM = oResult->GetValue(6, i);
    1675             :                 bool bIsInGpkgContents =
    1676        3168 :                     CPL_TO_BOOL(oResult->GetValueAsInteger(11, i));
    1677        3168 :                 if (!bIsInGpkgContents)
    1678          44 :                     m_bNonSpatialTablesNonRegisteredInGpkgContentsFound = true;
    1679        3168 :                 const char *pszObjectType = oResult->GetValue(12, i);
    1680        3168 :                 if (pszObjectType == nullptr ||
    1681        3167 :                     !(EQUAL(pszObjectType, "table") ||
    1682          21 :                       EQUAL(pszObjectType, "view")))
    1683             :                 {
    1684           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1685             :                              "Table/view %s is referenced in gpkg_contents, "
    1686             :                              "but does not exist",
    1687             :                              pszTableName);
    1688           1 :                     continue;
    1689             :                 }
    1690             :                 // Non-standard and undocumented behavior:
    1691             :                 // if the same table appears to have several geometry columns,
    1692             :                 // handle it for now as multiple layers named
    1693             :                 // "table_name (geom_col_name)"
    1694             :                 // The way we handle that might change in the future (e.g
    1695             :                 // could be a single layer with multiple geometry columns)
    1696             :                 std::string osLayerNameWithGeomColName =
    1697        6317 :                     pszGeomColName ? std::string(pszTableName) + " (" +
    1698             :                                          pszGeomColName + ')'
    1699        6334 :                                    : std::string(pszTableName);
    1700        3167 :                 if (cpl::contains(oExistingLayers, osLayerNameWithGeomColName))
    1701           1 :                     continue;
    1702        3166 :                 oExistingLayers.insert(osLayerNameWithGeomColName);
    1703             :                 const std::string osLayerName =
    1704             :                     bTableHasSeveralGeomColumns
    1705           3 :                         ? std::move(osLayerNameWithGeomColName)
    1706        6335 :                         : std::string(pszTableName);
    1707             :                 auto poLayer = std::make_unique<OGRGeoPackageTableLayer>(
    1708        6332 :                     this, osLayerName.c_str());
    1709        3166 :                 bool bHasZ = pszZ && atoi(pszZ) > 0;
    1710        3166 :                 bool bHasM = pszM && atoi(pszM) > 0;
    1711        3166 :                 if (pszGeomType && EQUAL(pszGeomType, "GEOMETRY"))
    1712             :                 {
    1713         628 :                     if (pszZ && atoi(pszZ) == 2)
    1714           7 :                         bHasZ = false;
    1715         628 :                     if (pszM && atoi(pszM) == 2)
    1716           6 :                         bHasM = false;
    1717             :                 }
    1718        3166 :                 poLayer->SetOpeningParameters(
    1719             :                     pszTableName, pszObjectType, bIsInGpkgContents, bIsSpatial,
    1720             :                     pszGeomColName, pszGeomType, bHasZ, bHasM);
    1721        3166 :                 m_apoLayers.push_back(std::move(poLayer));
    1722             :             }
    1723             :         }
    1724             :     }
    1725             : 
    1726        1274 :     bool bHasTileMatrixSet = false;
    1727        1274 :     if (poOpenInfo->nOpenFlags & GDAL_OF_RASTER)
    1728             :     {
    1729         573 :         bHasTileMatrixSet = SQLGetInteger(hDB,
    1730             :                                           "SELECT 1 FROM sqlite_master WHERE "
    1731             :                                           "name = 'gpkg_tile_matrix_set' AND "
    1732             :                                           "type IN ('table', 'view')",
    1733             :                                           nullptr) == 1;
    1734             :     }
    1735        1274 :     if (bHasTileMatrixSet)
    1736             :     {
    1737             :         std::string osSQL =
    1738             :             "SELECT c.table_name, c.identifier, c.description, c.srs_id, "
    1739             :             "c.min_x, c.min_y, c.max_x, c.max_y, "
    1740             :             "tms.min_x, tms.min_y, tms.max_x, tms.max_y, c.data_type "
    1741             :             "FROM gpkg_contents c JOIN gpkg_tile_matrix_set tms ON "
    1742             :             "c.table_name = tms.table_name WHERE "
    1743         571 :             "data_type IN ('tiles', '2d-gridded-coverage')";
    1744         571 :         if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE"))
    1745             :             osSubdatasetTableName =
    1746           2 :                 CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE");
    1747         571 :         if (!osSubdatasetTableName.empty())
    1748             :         {
    1749          16 :             char *pszTmp = sqlite3_mprintf(" AND c.table_name='%q'",
    1750             :                                            osSubdatasetTableName.c_str());
    1751          16 :             osSQL += pszTmp;
    1752          16 :             sqlite3_free(pszTmp);
    1753          16 :             SetPhysicalFilename(osFilename.c_str());
    1754             :         }
    1755         571 :         const int nTableLimit = GetOGRTableLimit();
    1756         571 :         if (nTableLimit > 0)
    1757             :         {
    1758         571 :             osSQL += " LIMIT ";
    1759         571 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1760             :         }
    1761             : 
    1762         571 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1763         571 :         if (!oResult)
    1764             :         {
    1765           0 :             return FALSE;
    1766             :         }
    1767             : 
    1768         571 :         if (oResult->RowCount() == 0 && !osSubdatasetTableName.empty())
    1769             :         {
    1770           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1771             :                      "Cannot find table '%s' in GeoPackage dataset",
    1772             :                      osSubdatasetTableName.c_str());
    1773             :         }
    1774         570 :         else if (oResult->RowCount() == 1)
    1775             :         {
    1776         274 :             const char *pszTableName = oResult->GetValue(0, 0);
    1777         274 :             const char *pszIdentifier = oResult->GetValue(1, 0);
    1778         274 :             const char *pszDescription = oResult->GetValue(2, 0);
    1779         274 :             const char *pszSRSId = oResult->GetValue(3, 0);
    1780         274 :             const char *pszMinX = oResult->GetValue(4, 0);
    1781         274 :             const char *pszMinY = oResult->GetValue(5, 0);
    1782         274 :             const char *pszMaxX = oResult->GetValue(6, 0);
    1783         274 :             const char *pszMaxY = oResult->GetValue(7, 0);
    1784         274 :             const char *pszTMSMinX = oResult->GetValue(8, 0);
    1785         274 :             const char *pszTMSMinY = oResult->GetValue(9, 0);
    1786         274 :             const char *pszTMSMaxX = oResult->GetValue(10, 0);
    1787         274 :             const char *pszTMSMaxY = oResult->GetValue(11, 0);
    1788         274 :             const char *pszDataType = oResult->GetValue(12, 0);
    1789         274 :             if (pszTableName && pszTMSMinX && pszTMSMinY && pszTMSMaxX &&
    1790             :                 pszTMSMaxY)
    1791             :             {
    1792         548 :                 bRet = OpenRaster(
    1793             :                     pszTableName, pszIdentifier, pszDescription,
    1794         274 :                     pszSRSId ? atoi(pszSRSId) : 0, CPLAtof(pszTMSMinX),
    1795             :                     CPLAtof(pszTMSMinY), CPLAtof(pszTMSMaxX),
    1796             :                     CPLAtof(pszTMSMaxY), pszMinX, pszMinY, pszMaxX, pszMaxY,
    1797         274 :                     EQUAL(pszDataType, "tiles"), poOpenInfo->papszOpenOptions);
    1798             :             }
    1799             :         }
    1800         296 :         else if (oResult->RowCount() >= 1)
    1801             :         {
    1802           5 :             bRet = TRUE;
    1803             : 
    1804           5 :             if (nTableLimit > 0 && oResult->RowCount() > nTableLimit)
    1805             :             {
    1806           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1807             :                          "File has more than %d raster tables. "
    1808             :                          "Limiting to first %d (can be overridden with "
    1809             :                          "OGR_TABLE_LIMIT config option)",
    1810             :                          nTableLimit, nTableLimit);
    1811           1 :                 oResult->LimitRowCount(nTableLimit);
    1812             :             }
    1813             : 
    1814           5 :             int nSDSCount = 0;
    1815        2013 :             for (int i = 0; i < oResult->RowCount(); i++)
    1816             :             {
    1817        2008 :                 const char *pszTableName = oResult->GetValue(0, i);
    1818        2008 :                 const char *pszIdentifier = oResult->GetValue(1, i);
    1819        2008 :                 if (pszTableName == nullptr)
    1820           0 :                     continue;
    1821             :                 m_aosSubDatasets.AddNameValue(
    1822             :                     CPLSPrintf("SUBDATASET_%d_NAME", nSDSCount + 1),
    1823        2008 :                     CPLSPrintf("GPKG:%s:%s", m_pszFilename, pszTableName));
    1824             :                 m_aosSubDatasets.AddNameValue(
    1825             :                     CPLSPrintf("SUBDATASET_%d_DESC", nSDSCount + 1),
    1826             :                     pszIdentifier
    1827        2008 :                         ? CPLSPrintf("%s - %s", pszTableName, pszIdentifier)
    1828        4016 :                         : pszTableName);
    1829        2008 :                 nSDSCount++;
    1830             :             }
    1831             :         }
    1832             :     }
    1833             : 
    1834        1274 :     if (!bRet && (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR))
    1835             :     {
    1836          33 :         if ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE))
    1837             :         {
    1838          22 :             bRet = TRUE;
    1839             :         }
    1840             :         else
    1841             :         {
    1842          11 :             CPLDebug("GPKG",
    1843             :                      "This GeoPackage has no vector content and is opened "
    1844             :                      "in read-only mode. If you open it in update mode, "
    1845             :                      "opening will be successful.");
    1846             :         }
    1847             :     }
    1848             : 
    1849        1274 :     if (eAccess == GA_Update)
    1850             :     {
    1851         259 :         FixupWrongRTreeTrigger();
    1852         259 :         FixupWrongMedataReferenceColumnNameUpdate();
    1853             :     }
    1854             : 
    1855        1274 :     SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    1856             : 
    1857        1274 :     return bRet;
    1858             : }
    1859             : 
    1860             : /************************************************************************/
    1861             : /*                    DetectSpatialRefSysColumns()                      */
    1862             : /************************************************************************/
    1863             : 
    1864        1284 : void GDALGeoPackageDataset::DetectSpatialRefSysColumns()
    1865             : {
    1866             :     // Detect definition_12_063 column
    1867             :     {
    1868        1284 :         sqlite3_stmt *hSQLStmt = nullptr;
    1869        1284 :         int rc = sqlite3_prepare_v2(
    1870             :             hDB, "SELECT definition_12_063 FROM gpkg_spatial_ref_sys ", -1,
    1871             :             &hSQLStmt, nullptr);
    1872        1284 :         if (rc == SQLITE_OK)
    1873             :         {
    1874          85 :             m_bHasDefinition12_063 = true;
    1875          85 :             sqlite3_finalize(hSQLStmt);
    1876             :         }
    1877             :     }
    1878             : 
    1879             :     // Detect epoch column
    1880        1284 :     if (m_bHasDefinition12_063)
    1881             :     {
    1882          85 :         sqlite3_stmt *hSQLStmt = nullptr;
    1883             :         int rc =
    1884          85 :             sqlite3_prepare_v2(hDB, "SELECT epoch FROM gpkg_spatial_ref_sys ",
    1885             :                                -1, &hSQLStmt, nullptr);
    1886          85 :         if (rc == SQLITE_OK)
    1887             :         {
    1888          76 :             m_bHasEpochColumn = true;
    1889          76 :             sqlite3_finalize(hSQLStmt);
    1890             :         }
    1891             :     }
    1892        1284 : }
    1893             : 
    1894             : /************************************************************************/
    1895             : /*                    FixupWrongRTreeTrigger()                          */
    1896             : /************************************************************************/
    1897             : 
    1898         259 : void GDALGeoPackageDataset::FixupWrongRTreeTrigger()
    1899             : {
    1900             :     auto oResult = SQLQuery(
    1901             :         hDB,
    1902             :         "SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND "
    1903         259 :         "NAME LIKE 'rtree_%_update3' AND sql LIKE '% AFTER UPDATE OF % ON %'");
    1904         259 :     if (oResult == nullptr)
    1905           0 :         return;
    1906         259 :     if (oResult->RowCount() > 0)
    1907             :     {
    1908           1 :         CPLDebug("GPKG", "Fixing incorrect trigger(s) related to RTree");
    1909             :     }
    1910         261 :     for (int i = 0; i < oResult->RowCount(); i++)
    1911             :     {
    1912           2 :         const char *pszName = oResult->GetValue(0, i);
    1913           2 :         const char *pszSQL = oResult->GetValue(1, i);
    1914           2 :         const char *pszPtr1 = strstr(pszSQL, " AFTER UPDATE OF ");
    1915           2 :         if (pszPtr1)
    1916             :         {
    1917           2 :             const char *pszPtr = pszPtr1 + strlen(" AFTER UPDATE OF ");
    1918             :             // Skipping over geometry column name
    1919           4 :             while (*pszPtr == ' ')
    1920           2 :                 pszPtr++;
    1921           2 :             if (pszPtr[0] == '"' || pszPtr[0] == '\'')
    1922             :             {
    1923           1 :                 char chStringDelim = pszPtr[0];
    1924           1 :                 pszPtr++;
    1925           9 :                 while (*pszPtr != '\0' && *pszPtr != chStringDelim)
    1926             :                 {
    1927           8 :                     if (*pszPtr == '\\' && pszPtr[1] == chStringDelim)
    1928           0 :                         pszPtr += 2;
    1929             :                     else
    1930           8 :                         pszPtr += 1;
    1931             :                 }
    1932           1 :                 if (*pszPtr == chStringDelim)
    1933           1 :                     pszPtr++;
    1934             :             }
    1935             :             else
    1936             :             {
    1937           1 :                 pszPtr++;
    1938           8 :                 while (*pszPtr != ' ')
    1939           7 :                     pszPtr++;
    1940             :             }
    1941           2 :             if (*pszPtr == ' ')
    1942             :             {
    1943           2 :                 SQLCommand(hDB,
    1944           4 :                            ("DROP TRIGGER \"" + SQLEscapeName(pszName) + "\"")
    1945             :                                .c_str());
    1946           4 :                 CPLString newSQL;
    1947           2 :                 newSQL.assign(pszSQL, pszPtr1 - pszSQL);
    1948           2 :                 newSQL += " AFTER UPDATE";
    1949           2 :                 newSQL += pszPtr;
    1950           2 :                 SQLCommand(hDB, newSQL);
    1951             :             }
    1952             :         }
    1953             :     }
    1954             : }
    1955             : 
    1956             : /************************************************************************/
    1957             : /*             FixupWrongMedataReferenceColumnNameUpdate()              */
    1958             : /************************************************************************/
    1959             : 
    1960         259 : void GDALGeoPackageDataset::FixupWrongMedataReferenceColumnNameUpdate()
    1961             : {
    1962             :     // Fix wrong trigger that was generated by GDAL < 2.4.0
    1963             :     // See https://github.com/qgis/QGIS/issues/42768
    1964             :     auto oResult = SQLQuery(
    1965             :         hDB, "SELECT sql FROM sqlite_master WHERE type = 'trigger' AND "
    1966             :              "NAME ='gpkg_metadata_reference_column_name_update' AND "
    1967         259 :              "sql LIKE '%column_nameIS%'");
    1968         259 :     if (oResult == nullptr)
    1969           0 :         return;
    1970         259 :     if (oResult->RowCount() == 1)
    1971             :     {
    1972           1 :         CPLDebug("GPKG", "Fixing incorrect trigger "
    1973             :                          "gpkg_metadata_reference_column_name_update");
    1974           1 :         const char *pszSQL = oResult->GetValue(0, 0);
    1975             :         std::string osNewSQL(
    1976           3 :             CPLString(pszSQL).replaceAll("column_nameIS", "column_name IS"));
    1977             : 
    1978           1 :         SQLCommand(hDB,
    1979             :                    "DROP TRIGGER gpkg_metadata_reference_column_name_update");
    1980           1 :         SQLCommand(hDB, osNewSQL.c_str());
    1981             :     }
    1982             : }
    1983             : 
    1984             : /************************************************************************/
    1985             : /*                  ClearCachedRelationships()                          */
    1986             : /************************************************************************/
    1987             : 
    1988          36 : void GDALGeoPackageDataset::ClearCachedRelationships()
    1989             : {
    1990          36 :     m_bHasPopulatedRelationships = false;
    1991          36 :     m_osMapRelationships.clear();
    1992          36 : }
    1993             : 
    1994             : /************************************************************************/
    1995             : /*                           LoadRelationships()                        */
    1996             : /************************************************************************/
    1997             : 
    1998          84 : void GDALGeoPackageDataset::LoadRelationships() const
    1999             : {
    2000          84 :     m_osMapRelationships.clear();
    2001             : 
    2002          84 :     std::vector<std::string> oExcludedTables;
    2003          84 :     if (HasGpkgextRelationsTable())
    2004             :     {
    2005          37 :         LoadRelationshipsUsingRelatedTablesExtension();
    2006             : 
    2007          89 :         for (const auto &oRelationship : m_osMapRelationships)
    2008             :         {
    2009             :             oExcludedTables.emplace_back(
    2010          52 :                 oRelationship.second->GetMappingTableName());
    2011             :         }
    2012             :     }
    2013             : 
    2014             :     // Also load relationships defined using foreign keys (i.e. one-to-many
    2015             :     // relationships). Here we must exclude any relationships defined from the
    2016             :     // related tables extension, we don't want them included twice.
    2017          84 :     LoadRelationshipsFromForeignKeys(oExcludedTables);
    2018          84 :     m_bHasPopulatedRelationships = true;
    2019          84 : }
    2020             : 
    2021             : /************************************************************************/
    2022             : /*         LoadRelationshipsUsingRelatedTablesExtension()               */
    2023             : /************************************************************************/
    2024             : 
    2025          37 : void GDALGeoPackageDataset::LoadRelationshipsUsingRelatedTablesExtension() const
    2026             : {
    2027          37 :     m_osMapRelationships.clear();
    2028             : 
    2029             :     auto oResultTable = SQLQuery(
    2030          37 :         hDB, "SELECT base_table_name, base_primary_column, "
    2031             :              "related_table_name, related_primary_column, relation_name, "
    2032          74 :              "mapping_table_name FROM gpkgext_relations");
    2033          37 :     if (oResultTable && oResultTable->RowCount() > 0)
    2034             :     {
    2035          86 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    2036             :         {
    2037          53 :             const char *pszBaseTableName = oResultTable->GetValue(0, i);
    2038          53 :             if (!pszBaseTableName)
    2039             :             {
    2040           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2041             :                          "Could not retrieve base_table_name from "
    2042             :                          "gpkgext_relations");
    2043           1 :                 continue;
    2044             :             }
    2045          53 :             const char *pszBasePrimaryColumn = oResultTable->GetValue(1, i);
    2046          53 :             if (!pszBasePrimaryColumn)
    2047             :             {
    2048           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2049             :                          "Could not retrieve base_primary_column from "
    2050             :                          "gpkgext_relations");
    2051           0 :                 continue;
    2052             :             }
    2053          53 :             const char *pszRelatedTableName = oResultTable->GetValue(2, i);
    2054          53 :             if (!pszRelatedTableName)
    2055             :             {
    2056           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2057             :                          "Could not retrieve related_table_name from "
    2058             :                          "gpkgext_relations");
    2059           0 :                 continue;
    2060             :             }
    2061          53 :             const char *pszRelatedPrimaryColumn = oResultTable->GetValue(3, i);
    2062          53 :             if (!pszRelatedPrimaryColumn)
    2063             :             {
    2064           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2065             :                          "Could not retrieve related_primary_column from "
    2066             :                          "gpkgext_relations");
    2067           0 :                 continue;
    2068             :             }
    2069          53 :             const char *pszRelationName = oResultTable->GetValue(4, i);
    2070          53 :             if (!pszRelationName)
    2071             :             {
    2072           0 :                 CPLError(
    2073             :                     CE_Warning, CPLE_AppDefined,
    2074             :                     "Could not retrieve relation_name from gpkgext_relations");
    2075           0 :                 continue;
    2076             :             }
    2077          53 :             const char *pszMappingTableName = oResultTable->GetValue(5, i);
    2078          53 :             if (!pszMappingTableName)
    2079             :             {
    2080           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2081             :                          "Could not retrieve mapping_table_name from "
    2082             :                          "gpkgext_relations");
    2083           0 :                 continue;
    2084             :             }
    2085             : 
    2086             :             // confirm that mapping table exists
    2087             :             char *pszSQL =
    2088          53 :                 sqlite3_mprintf("SELECT 1 FROM sqlite_master WHERE "
    2089             :                                 "name='%q' AND type IN ('table', 'view')",
    2090             :                                 pszMappingTableName);
    2091          53 :             const int nMappingTableCount = SQLGetInteger(hDB, pszSQL, nullptr);
    2092          53 :             sqlite3_free(pszSQL);
    2093             : 
    2094          55 :             if (nMappingTableCount < 1 &&
    2095           2 :                 !const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    2096           2 :                     pszMappingTableName))
    2097             :             {
    2098           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2099             :                          "Relationship mapping table %s does not exist",
    2100             :                          pszMappingTableName);
    2101           1 :                 continue;
    2102             :             }
    2103             : 
    2104             :             const std::string osRelationName = GenerateNameForRelationship(
    2105         104 :                 pszBaseTableName, pszRelatedTableName, pszRelationName);
    2106             : 
    2107         104 :             std::string osType{};
    2108             :             // defined requirement classes -- for these types the relation name
    2109             :             // will be specific string value from the related tables extension.
    2110             :             // In this case we need to construct a unique relationship name
    2111             :             // based on the related tables
    2112          52 :             if (EQUAL(pszRelationName, "media") ||
    2113          40 :                 EQUAL(pszRelationName, "simple_attributes") ||
    2114          40 :                 EQUAL(pszRelationName, "features") ||
    2115          18 :                 EQUAL(pszRelationName, "attributes") ||
    2116           2 :                 EQUAL(pszRelationName, "tiles"))
    2117             :             {
    2118          50 :                 osType = pszRelationName;
    2119             :             }
    2120             :             else
    2121             :             {
    2122             :                 // user defined types default to features
    2123           2 :                 osType = "features";
    2124             :             }
    2125             : 
    2126             :             auto poRelationship = std::make_unique<GDALRelationship>(
    2127             :                 osRelationName, pszBaseTableName, pszRelatedTableName,
    2128         104 :                 GRC_MANY_TO_MANY);
    2129             : 
    2130         104 :             poRelationship->SetLeftTableFields({pszBasePrimaryColumn});
    2131         104 :             poRelationship->SetRightTableFields({pszRelatedPrimaryColumn});
    2132         104 :             poRelationship->SetLeftMappingTableFields({"base_id"});
    2133         104 :             poRelationship->SetRightMappingTableFields({"related_id"});
    2134          52 :             poRelationship->SetMappingTableName(pszMappingTableName);
    2135          52 :             poRelationship->SetRelatedTableType(osType);
    2136             : 
    2137          52 :             m_osMapRelationships[osRelationName] = std::move(poRelationship);
    2138             :         }
    2139             :     }
    2140          37 : }
    2141             : 
    2142             : /************************************************************************/
    2143             : /*                GenerateNameForRelationship()                         */
    2144             : /************************************************************************/
    2145             : 
    2146          76 : std::string GDALGeoPackageDataset::GenerateNameForRelationship(
    2147             :     const char *pszBaseTableName, const char *pszRelatedTableName,
    2148             :     const char *pszType)
    2149             : {
    2150             :     // defined requirement classes -- for these types the relation name will be
    2151             :     // specific string value from the related tables extension. In this case we
    2152             :     // need to construct a unique relationship name based on the related tables
    2153          76 :     if (EQUAL(pszType, "media") || EQUAL(pszType, "simple_attributes") ||
    2154          53 :         EQUAL(pszType, "features") || EQUAL(pszType, "attributes") ||
    2155           8 :         EQUAL(pszType, "tiles"))
    2156             :     {
    2157         136 :         std::ostringstream stream;
    2158             :         stream << pszBaseTableName << '_' << pszRelatedTableName << '_'
    2159          68 :                << pszType;
    2160          68 :         return stream.str();
    2161             :     }
    2162             :     else
    2163             :     {
    2164             :         // user defined types default to features
    2165           8 :         return pszType;
    2166             :     }
    2167             : }
    2168             : 
    2169             : /************************************************************************/
    2170             : /*                       ValidateRelationship()                         */
    2171             : /************************************************************************/
    2172             : 
    2173          28 : bool GDALGeoPackageDataset::ValidateRelationship(
    2174             :     const GDALRelationship *poRelationship, std::string &failureReason)
    2175             : {
    2176             : 
    2177          28 :     if (poRelationship->GetCardinality() !=
    2178             :         GDALRelationshipCardinality::GRC_MANY_TO_MANY)
    2179             :     {
    2180           3 :         failureReason = "Only many to many relationships are supported";
    2181           3 :         return false;
    2182             :     }
    2183             : 
    2184          50 :     std::string osRelatedTableType = poRelationship->GetRelatedTableType();
    2185          65 :     if (!osRelatedTableType.empty() && osRelatedTableType != "features" &&
    2186          30 :         osRelatedTableType != "media" &&
    2187          20 :         osRelatedTableType != "simple_attributes" &&
    2188          55 :         osRelatedTableType != "attributes" && osRelatedTableType != "tiles")
    2189             :     {
    2190             :         failureReason =
    2191           4 :             ("Related table type " + osRelatedTableType +
    2192             :              " is not a valid value for the GeoPackage specification. "
    2193             :              "Valid values are: features, media, simple_attributes, "
    2194             :              "attributes, tiles.")
    2195           2 :                 .c_str();
    2196           2 :         return false;
    2197             :     }
    2198             : 
    2199          23 :     const std::string &osLeftTableName = poRelationship->GetLeftTableName();
    2200          23 :     OGRGeoPackageLayer *poLeftTable = cpl::down_cast<OGRGeoPackageLayer *>(
    2201          23 :         GetLayerByName(osLeftTableName.c_str()));
    2202          23 :     if (!poLeftTable)
    2203             :     {
    2204           4 :         failureReason = ("Left table " + osLeftTableName +
    2205             :                          " is not an existing layer in the dataset")
    2206           2 :                             .c_str();
    2207           2 :         return false;
    2208             :     }
    2209          21 :     const std::string &osRightTableName = poRelationship->GetRightTableName();
    2210          21 :     OGRGeoPackageLayer *poRightTable = cpl::down_cast<OGRGeoPackageLayer *>(
    2211          21 :         GetLayerByName(osRightTableName.c_str()));
    2212          21 :     if (!poRightTable)
    2213             :     {
    2214           4 :         failureReason = ("Right table " + osRightTableName +
    2215             :                          " is not an existing layer in the dataset")
    2216           2 :                             .c_str();
    2217           2 :         return false;
    2218             :     }
    2219             : 
    2220          19 :     const auto &aosLeftTableFields = poRelationship->GetLeftTableFields();
    2221          19 :     if (aosLeftTableFields.empty())
    2222             :     {
    2223           1 :         failureReason = "No left table fields were specified";
    2224           1 :         return false;
    2225             :     }
    2226          18 :     else if (aosLeftTableFields.size() > 1)
    2227             :     {
    2228             :         failureReason = "Only a single left table field is permitted for the "
    2229           1 :                         "GeoPackage specification";
    2230           1 :         return false;
    2231             :     }
    2232             :     else
    2233             :     {
    2234             :         // validate left field exists
    2235          34 :         if (poLeftTable->GetLayerDefn()->GetFieldIndex(
    2236          37 :                 aosLeftTableFields[0].c_str()) < 0 &&
    2237           3 :             !EQUAL(poLeftTable->GetFIDColumn(), aosLeftTableFields[0].c_str()))
    2238             :         {
    2239           2 :             failureReason = ("Left table field " + aosLeftTableFields[0] +
    2240           2 :                              " does not exist in " + osLeftTableName)
    2241           1 :                                 .c_str();
    2242           1 :             return false;
    2243             :         }
    2244             :     }
    2245             : 
    2246          16 :     const auto &aosRightTableFields = poRelationship->GetRightTableFields();
    2247          16 :     if (aosRightTableFields.empty())
    2248             :     {
    2249           1 :         failureReason = "No right table fields were specified";
    2250           1 :         return false;
    2251             :     }
    2252          15 :     else if (aosRightTableFields.size() > 1)
    2253             :     {
    2254             :         failureReason = "Only a single right table field is permitted for the "
    2255           1 :                         "GeoPackage specification";
    2256           1 :         return false;
    2257             :     }
    2258             :     else
    2259             :     {
    2260             :         // validate right field exists
    2261          28 :         if (poRightTable->GetLayerDefn()->GetFieldIndex(
    2262          32 :                 aosRightTableFields[0].c_str()) < 0 &&
    2263           4 :             !EQUAL(poRightTable->GetFIDColumn(),
    2264             :                    aosRightTableFields[0].c_str()))
    2265             :         {
    2266           4 :             failureReason = ("Right table field " + aosRightTableFields[0] +
    2267           4 :                              " does not exist in " + osRightTableName)
    2268           2 :                                 .c_str();
    2269           2 :             return false;
    2270             :         }
    2271             :     }
    2272             : 
    2273          12 :     return true;
    2274             : }
    2275             : 
    2276             : /************************************************************************/
    2277             : /*                         InitRaster()                                 */
    2278             : /************************************************************************/
    2279             : 
    2280         358 : bool GDALGeoPackageDataset::InitRaster(
    2281             :     GDALGeoPackageDataset *poParentDS, const char *pszTableName, double dfMinX,
    2282             :     double dfMinY, double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2283             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2284             :     const char *pszContentsMaxY, char **papszOpenOptionsIn,
    2285             :     const SQLResult &oResult, int nIdxInResult)
    2286             : {
    2287         358 :     m_osRasterTable = pszTableName;
    2288         358 :     m_dfTMSMinX = dfMinX;
    2289         358 :     m_dfTMSMaxY = dfMaxY;
    2290             : 
    2291             :     // Despite prior checking, the type might be Binary and
    2292             :     // SQLResultGetValue() not working properly on it
    2293         358 :     int nZoomLevel = atoi(oResult.GetValue(0, nIdxInResult));
    2294         358 :     if (nZoomLevel < 0 || nZoomLevel > 65536)
    2295             :     {
    2296           0 :         return false;
    2297             :     }
    2298         358 :     double dfPixelXSize = CPLAtof(oResult.GetValue(1, nIdxInResult));
    2299         358 :     double dfPixelYSize = CPLAtof(oResult.GetValue(2, nIdxInResult));
    2300         358 :     if (dfPixelXSize <= 0 || dfPixelYSize <= 0)
    2301             :     {
    2302           0 :         return false;
    2303             :     }
    2304         358 :     int nTileWidth = atoi(oResult.GetValue(3, nIdxInResult));
    2305         358 :     int nTileHeight = atoi(oResult.GetValue(4, nIdxInResult));
    2306         358 :     if (nTileWidth <= 0 || nTileWidth > 65536 || nTileHeight <= 0 ||
    2307             :         nTileHeight > 65536)
    2308             :     {
    2309           0 :         return false;
    2310             :     }
    2311             :     int nTileMatrixWidth = static_cast<int>(
    2312         716 :         std::min(static_cast<GIntBig>(INT_MAX),
    2313         358 :                  CPLAtoGIntBig(oResult.GetValue(5, nIdxInResult))));
    2314             :     int nTileMatrixHeight = static_cast<int>(
    2315         716 :         std::min(static_cast<GIntBig>(INT_MAX),
    2316         358 :                  CPLAtoGIntBig(oResult.GetValue(6, nIdxInResult))));
    2317         358 :     if (nTileMatrixWidth <= 0 || nTileMatrixHeight <= 0)
    2318             :     {
    2319           0 :         return false;
    2320             :     }
    2321             : 
    2322             :     /* Use content bounds in priority over tile_matrix_set bounds */
    2323         358 :     double dfGDALMinX = dfMinX;
    2324         358 :     double dfGDALMinY = dfMinY;
    2325         358 :     double dfGDALMaxX = dfMaxX;
    2326         358 :     double dfGDALMaxY = dfMaxY;
    2327             :     pszContentsMinX =
    2328         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINX", pszContentsMinX);
    2329             :     pszContentsMinY =
    2330         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINY", pszContentsMinY);
    2331             :     pszContentsMaxX =
    2332         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXX", pszContentsMaxX);
    2333             :     pszContentsMaxY =
    2334         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXY", pszContentsMaxY);
    2335         358 :     if (pszContentsMinX != nullptr && pszContentsMinY != nullptr &&
    2336         358 :         pszContentsMaxX != nullptr && pszContentsMaxY != nullptr)
    2337             :     {
    2338         715 :         if (CPLAtof(pszContentsMinX) < CPLAtof(pszContentsMaxX) &&
    2339         357 :             CPLAtof(pszContentsMinY) < CPLAtof(pszContentsMaxY))
    2340             :         {
    2341         357 :             dfGDALMinX = CPLAtof(pszContentsMinX);
    2342         357 :             dfGDALMinY = CPLAtof(pszContentsMinY);
    2343         357 :             dfGDALMaxX = CPLAtof(pszContentsMaxX);
    2344         357 :             dfGDALMaxY = CPLAtof(pszContentsMaxY);
    2345             :         }
    2346             :         else
    2347             :         {
    2348           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    2349             :                      "Illegal min_x/min_y/max_x/max_y values for %s in open "
    2350             :                      "options and/or gpkg_contents. Using bounds of "
    2351             :                      "gpkg_tile_matrix_set instead",
    2352             :                      pszTableName);
    2353             :         }
    2354             :     }
    2355         358 :     if (dfGDALMinX >= dfGDALMaxX || dfGDALMinY >= dfGDALMaxY)
    2356             :     {
    2357           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2358             :                  "Illegal min_x/min_y/max_x/max_y values for %s", pszTableName);
    2359           0 :         return false;
    2360             :     }
    2361             : 
    2362         358 :     int nBandCount = 0;
    2363             :     const char *pszBAND_COUNT =
    2364         358 :         CSLFetchNameValue(papszOpenOptionsIn, "BAND_COUNT");
    2365         358 :     if (poParentDS)
    2366             :     {
    2367          86 :         nBandCount = poParentDS->GetRasterCount();
    2368             :     }
    2369         272 :     else if (m_eDT != GDT_Byte)
    2370             :     {
    2371          65 :         if (pszBAND_COUNT != nullptr && !EQUAL(pszBAND_COUNT, "AUTO") &&
    2372           0 :             !EQUAL(pszBAND_COUNT, "1"))
    2373             :         {
    2374           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2375             :                      "BAND_COUNT ignored for non-Byte data");
    2376             :         }
    2377          65 :         nBandCount = 1;
    2378             :     }
    2379             :     else
    2380             :     {
    2381         207 :         if (pszBAND_COUNT != nullptr && !EQUAL(pszBAND_COUNT, "AUTO"))
    2382             :         {
    2383          69 :             nBandCount = atoi(pszBAND_COUNT);
    2384          69 :             if (nBandCount == 1)
    2385           5 :                 GetMetadata("IMAGE_STRUCTURE");
    2386             :         }
    2387             :         else
    2388             :         {
    2389         138 :             GetMetadata("IMAGE_STRUCTURE");
    2390         138 :             nBandCount = m_nBandCountFromMetadata;
    2391         138 :             if (nBandCount == 1)
    2392          39 :                 m_eTF = GPKG_TF_PNG;
    2393             :         }
    2394         207 :         if (nBandCount == 1 && !m_osTFFromMetadata.empty())
    2395             :         {
    2396           2 :             m_eTF = GDALGPKGMBTilesGetTileFormat(m_osTFFromMetadata.c_str());
    2397             :         }
    2398         207 :         if (nBandCount <= 0 || nBandCount > 4)
    2399          85 :             nBandCount = 4;
    2400             :     }
    2401             : 
    2402         358 :     return InitRaster(poParentDS, pszTableName, nZoomLevel, nBandCount, dfMinX,
    2403             :                       dfMaxY, dfPixelXSize, dfPixelYSize, nTileWidth,
    2404             :                       nTileHeight, nTileMatrixWidth, nTileMatrixHeight,
    2405         358 :                       dfGDALMinX, dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    2406             : }
    2407             : 
    2408             : /************************************************************************/
    2409             : /*                      ComputeTileAndPixelShifts()                     */
    2410             : /************************************************************************/
    2411             : 
    2412         784 : bool GDALGeoPackageDataset::ComputeTileAndPixelShifts()
    2413             : {
    2414             :     int nTileWidth, nTileHeight;
    2415         784 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2416             : 
    2417             :     // Compute shift between GDAL origin and TileMatrixSet origin
    2418         784 :     const double dfShiftXPixels = (m_gt[0] - m_dfTMSMinX) / m_gt[1];
    2419         784 :     if (!(dfShiftXPixels / nTileWidth >= INT_MIN &&
    2420         781 :           dfShiftXPixels / nTileWidth < INT_MAX))
    2421             :     {
    2422           3 :         return false;
    2423             :     }
    2424         781 :     const int64_t nShiftXPixels =
    2425         781 :         static_cast<int64_t>(floor(0.5 + dfShiftXPixels));
    2426         781 :     m_nShiftXTiles = static_cast<int>(nShiftXPixels / nTileWidth);
    2427         781 :     if (nShiftXPixels < 0 && (nShiftXPixels % nTileWidth) != 0)
    2428          11 :         m_nShiftXTiles--;
    2429         781 :     m_nShiftXPixelsMod =
    2430         781 :         (static_cast<int>(nShiftXPixels % nTileWidth) + nTileWidth) %
    2431             :         nTileWidth;
    2432             : 
    2433         781 :     const double dfShiftYPixels = (m_gt[3] - m_dfTMSMaxY) / m_gt[5];
    2434         781 :     if (!(dfShiftYPixels / nTileHeight >= INT_MIN &&
    2435         781 :           dfShiftYPixels / nTileHeight < INT_MAX))
    2436             :     {
    2437           1 :         return false;
    2438             :     }
    2439         780 :     const int64_t nShiftYPixels =
    2440         780 :         static_cast<int64_t>(floor(0.5 + dfShiftYPixels));
    2441         780 :     m_nShiftYTiles = static_cast<int>(nShiftYPixels / nTileHeight);
    2442         780 :     if (nShiftYPixels < 0 && (nShiftYPixels % nTileHeight) != 0)
    2443          11 :         m_nShiftYTiles--;
    2444         780 :     m_nShiftYPixelsMod =
    2445         780 :         (static_cast<int>(nShiftYPixels % nTileHeight) + nTileHeight) %
    2446             :         nTileHeight;
    2447         780 :     return true;
    2448             : }
    2449             : 
    2450             : /************************************************************************/
    2451             : /*                            AllocCachedTiles()                        */
    2452             : /************************************************************************/
    2453             : 
    2454         780 : bool GDALGeoPackageDataset::AllocCachedTiles()
    2455             : {
    2456             :     int nTileWidth, nTileHeight;
    2457         780 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2458             : 
    2459             :     // We currently need 4 caches because of
    2460             :     // GDALGPKGMBTilesLikePseudoDataset::ReadTile(int nRow, int nCol)
    2461         780 :     const int nCacheCount = 4;
    2462             :     /*
    2463             :             (m_nShiftXPixelsMod != 0 || m_nShiftYPixelsMod != 0) ? 4 :
    2464             :             (GetUpdate() && m_eDT == GDT_Byte) ? 2 : 1;
    2465             :     */
    2466         780 :     m_pabyCachedTiles = static_cast<GByte *>(VSI_MALLOC3_VERBOSE(
    2467             :         cpl::fits_on<int>(nCacheCount * (m_eDT == GDT_Byte ? 4 : 1) *
    2468             :                           m_nDTSize),
    2469             :         nTileWidth, nTileHeight));
    2470         780 :     if (m_pabyCachedTiles == nullptr)
    2471             :     {
    2472           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Too big tiles: %d x %d",
    2473             :                  nTileWidth, nTileHeight);
    2474           0 :         return false;
    2475             :     }
    2476             : 
    2477         780 :     return true;
    2478             : }
    2479             : 
    2480             : /************************************************************************/
    2481             : /*                         InitRaster()                                 */
    2482             : /************************************************************************/
    2483             : 
    2484         597 : bool GDALGeoPackageDataset::InitRaster(
    2485             :     GDALGeoPackageDataset *poParentDS, const char *pszTableName, int nZoomLevel,
    2486             :     int nBandCount, double dfTMSMinX, double dfTMSMaxY, double dfPixelXSize,
    2487             :     double dfPixelYSize, int nTileWidth, int nTileHeight, int nTileMatrixWidth,
    2488             :     int nTileMatrixHeight, double dfGDALMinX, double dfGDALMinY,
    2489             :     double dfGDALMaxX, double dfGDALMaxY)
    2490             : {
    2491         597 :     m_osRasterTable = pszTableName;
    2492         597 :     m_dfTMSMinX = dfTMSMinX;
    2493         597 :     m_dfTMSMaxY = dfTMSMaxY;
    2494         597 :     m_nZoomLevel = nZoomLevel;
    2495         597 :     m_nTileMatrixWidth = nTileMatrixWidth;
    2496         597 :     m_nTileMatrixHeight = nTileMatrixHeight;
    2497             : 
    2498         597 :     m_bGeoTransformValid = true;
    2499         597 :     m_gt[0] = dfGDALMinX;
    2500         597 :     m_gt[1] = dfPixelXSize;
    2501         597 :     m_gt[3] = dfGDALMaxY;
    2502         597 :     m_gt[5] = -dfPixelYSize;
    2503         597 :     double dfRasterXSize = 0.5 + (dfGDALMaxX - dfGDALMinX) / dfPixelXSize;
    2504         597 :     double dfRasterYSize = 0.5 + (dfGDALMaxY - dfGDALMinY) / dfPixelYSize;
    2505         597 :     if (dfRasterXSize > INT_MAX || dfRasterYSize > INT_MAX)
    2506             :     {
    2507           0 :         CPLError(CE_Failure, CPLE_NotSupported, "Too big raster: %f x %f",
    2508             :                  dfRasterXSize, dfRasterYSize);
    2509           0 :         return false;
    2510             :     }
    2511         597 :     nRasterXSize = std::max(1, static_cast<int>(dfRasterXSize));
    2512         597 :     nRasterYSize = std::max(1, static_cast<int>(dfRasterYSize));
    2513             : 
    2514         597 :     if (poParentDS)
    2515             :     {
    2516         325 :         m_poParentDS = poParentDS;
    2517         325 :         eAccess = poParentDS->eAccess;
    2518         325 :         hDB = poParentDS->hDB;
    2519         325 :         m_eTF = poParentDS->m_eTF;
    2520         325 :         m_eDT = poParentDS->m_eDT;
    2521         325 :         m_nDTSize = poParentDS->m_nDTSize;
    2522         325 :         m_dfScale = poParentDS->m_dfScale;
    2523         325 :         m_dfOffset = poParentDS->m_dfOffset;
    2524         325 :         m_dfPrecision = poParentDS->m_dfPrecision;
    2525         325 :         m_usGPKGNull = poParentDS->m_usGPKGNull;
    2526         325 :         m_nQuality = poParentDS->m_nQuality;
    2527         325 :         m_nZLevel = poParentDS->m_nZLevel;
    2528         325 :         m_bDither = poParentDS->m_bDither;
    2529             :         /*m_nSRID = poParentDS->m_nSRID;*/
    2530         325 :         m_osWHERE = poParentDS->m_osWHERE;
    2531         325 :         SetDescription(CPLSPrintf("%s - zoom_level=%d",
    2532         325 :                                   poParentDS->GetDescription(), m_nZoomLevel));
    2533             :     }
    2534             : 
    2535        2091 :     for (int i = 1; i <= nBandCount; i++)
    2536             :     {
    2537             :         auto poNewBand = std::make_unique<GDALGeoPackageRasterBand>(
    2538        1494 :             this, nTileWidth, nTileHeight);
    2539        1494 :         if (poParentDS)
    2540             :         {
    2541         761 :             int bHasNoData = FALSE;
    2542             :             double dfNoDataValue =
    2543         761 :                 poParentDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    2544         761 :             if (bHasNoData)
    2545          24 :                 poNewBand->SetNoDataValueInternal(dfNoDataValue);
    2546             :         }
    2547             : 
    2548        1494 :         if (nBandCount == 1 && m_poCTFromMetadata)
    2549             :         {
    2550           3 :             poNewBand->AssignColorTable(m_poCTFromMetadata.get());
    2551             :         }
    2552        1494 :         if (!m_osNodataValueFromMetadata.empty())
    2553             :         {
    2554           8 :             poNewBand->SetNoDataValueInternal(
    2555             :                 CPLAtof(m_osNodataValueFromMetadata.c_str()));
    2556             :         }
    2557             : 
    2558        1494 :         SetBand(i, std::move(poNewBand));
    2559             :     }
    2560             : 
    2561         597 :     if (!ComputeTileAndPixelShifts())
    2562             :     {
    2563           3 :         CPLError(CE_Failure, CPLE_AppDefined,
    2564             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    2565           3 :         return false;
    2566             :     }
    2567             : 
    2568         594 :     GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    2569         594 :     GDALPamDataset::SetMetadataItem("ZOOM_LEVEL",
    2570             :                                     CPLSPrintf("%d", m_nZoomLevel));
    2571             : 
    2572         594 :     return AllocCachedTiles();
    2573             : }
    2574             : 
    2575             : /************************************************************************/
    2576             : /*                 GDALGPKGMBTilesGetTileFormat()                       */
    2577             : /************************************************************************/
    2578             : 
    2579          80 : GPKGTileFormat GDALGPKGMBTilesGetTileFormat(const char *pszTF)
    2580             : {
    2581          80 :     GPKGTileFormat eTF = GPKG_TF_PNG_JPEG;
    2582          80 :     if (pszTF)
    2583             :     {
    2584          80 :         if (EQUAL(pszTF, "PNG_JPEG") || EQUAL(pszTF, "AUTO"))
    2585           1 :             eTF = GPKG_TF_PNG_JPEG;
    2586          79 :         else if (EQUAL(pszTF, "PNG"))
    2587          46 :             eTF = GPKG_TF_PNG;
    2588          33 :         else if (EQUAL(pszTF, "PNG8"))
    2589           6 :             eTF = GPKG_TF_PNG8;
    2590          27 :         else if (EQUAL(pszTF, "JPEG"))
    2591          14 :             eTF = GPKG_TF_JPEG;
    2592          13 :         else if (EQUAL(pszTF, "WEBP"))
    2593          13 :             eTF = GPKG_TF_WEBP;
    2594             :         else
    2595             :         {
    2596           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2597             :                      "Unsuppoted value for TILE_FORMAT: %s", pszTF);
    2598             :         }
    2599             :     }
    2600          80 :     return eTF;
    2601             : }
    2602             : 
    2603          28 : const char *GDALMBTilesGetTileFormatName(GPKGTileFormat eTF)
    2604             : {
    2605          28 :     switch (eTF)
    2606             :     {
    2607          26 :         case GPKG_TF_PNG:
    2608             :         case GPKG_TF_PNG8:
    2609          26 :             return "png";
    2610           1 :         case GPKG_TF_JPEG:
    2611           1 :             return "jpg";
    2612           1 :         case GPKG_TF_WEBP:
    2613           1 :             return "webp";
    2614           0 :         default:
    2615           0 :             break;
    2616             :     }
    2617           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2618             :              "Unsuppoted value for TILE_FORMAT: %d", static_cast<int>(eTF));
    2619           0 :     return nullptr;
    2620             : }
    2621             : 
    2622             : /************************************************************************/
    2623             : /*                         OpenRaster()                                 */
    2624             : /************************************************************************/
    2625             : 
    2626         274 : bool GDALGeoPackageDataset::OpenRaster(
    2627             :     const char *pszTableName, const char *pszIdentifier,
    2628             :     const char *pszDescription, int nSRSId, double dfMinX, double dfMinY,
    2629             :     double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2630             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2631             :     const char *pszContentsMaxY, bool bIsTiles, char **papszOpenOptionsIn)
    2632             : {
    2633         274 :     if (dfMinX >= dfMaxX || dfMinY >= dfMaxY)
    2634           0 :         return false;
    2635             : 
    2636             :     // Config option just for debug, and for example force set to NaN
    2637             :     // which is not supported
    2638         548 :     CPLString osDataNull = CPLGetConfigOption("GPKG_NODATA", "");
    2639         548 :     CPLString osUom;
    2640         548 :     CPLString osFieldName;
    2641         548 :     CPLString osGridCellEncoding;
    2642         274 :     if (!bIsTiles)
    2643             :     {
    2644          65 :         char *pszSQL = sqlite3_mprintf(
    2645             :             "SELECT datatype, scale, offset, data_null, precision FROM "
    2646             :             "gpkg_2d_gridded_coverage_ancillary "
    2647             :             "WHERE tile_matrix_set_name = '%q' "
    2648             :             "AND datatype IN ('integer', 'float')"
    2649             :             "AND (scale > 0 OR scale IS NULL)",
    2650             :             pszTableName);
    2651          65 :         auto oResult = SQLQuery(hDB, pszSQL);
    2652          65 :         sqlite3_free(pszSQL);
    2653          65 :         if (!oResult || oResult->RowCount() == 0)
    2654             :         {
    2655           0 :             return false;
    2656             :         }
    2657          65 :         const char *pszDataType = oResult->GetValue(0, 0);
    2658          65 :         const char *pszScale = oResult->GetValue(1, 0);
    2659          65 :         const char *pszOffset = oResult->GetValue(2, 0);
    2660          65 :         const char *pszDataNull = oResult->GetValue(3, 0);
    2661          65 :         const char *pszPrecision = oResult->GetValue(4, 0);
    2662          65 :         if (pszDataNull)
    2663          23 :             osDataNull = pszDataNull;
    2664          65 :         if (EQUAL(pszDataType, "float"))
    2665             :         {
    2666           6 :             SetDataType(GDT_Float32);
    2667           6 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    2668             :         }
    2669             :         else
    2670             :         {
    2671          59 :             SetDataType(GDT_Float32);
    2672          59 :             m_eTF = GPKG_TF_PNG_16BIT;
    2673          59 :             const double dfScale = pszScale ? CPLAtof(pszScale) : 1.0;
    2674          59 :             const double dfOffset = pszOffset ? CPLAtof(pszOffset) : 0.0;
    2675          59 :             if (dfScale == 1.0)
    2676             :             {
    2677          59 :                 if (dfOffset == 0.0)
    2678             :                 {
    2679          24 :                     SetDataType(GDT_UInt16);
    2680             :                 }
    2681          35 :                 else if (dfOffset == -32768.0)
    2682             :                 {
    2683          35 :                     SetDataType(GDT_Int16);
    2684             :                 }
    2685             :                 // coverity[tainted_data]
    2686           0 :                 else if (dfOffset == -32767.0 && !osDataNull.empty() &&
    2687           0 :                          CPLAtof(osDataNull) == 65535.0)
    2688             :                 // Given that we will map the nodata value to -32768
    2689             :                 {
    2690           0 :                     SetDataType(GDT_Int16);
    2691             :                 }
    2692             :             }
    2693             : 
    2694             :             // Check that the tile offset and scales are compatible of a
    2695             :             // final integer result.
    2696          59 :             if (m_eDT != GDT_Float32)
    2697             :             {
    2698             :                 // coverity[tainted_data]
    2699          59 :                 if (dfScale == 1.0 && dfOffset == -32768.0 &&
    2700         118 :                     !osDataNull.empty() && CPLAtof(osDataNull) == 65535.0)
    2701             :                 {
    2702             :                     // Given that we will map the nodata value to -32768
    2703           9 :                     pszSQL = sqlite3_mprintf(
    2704             :                         "SELECT 1 FROM "
    2705             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2706             :                         "tpudt_name = '%q' "
    2707             :                         "AND NOT ((offset = 0.0 or offset = 1.0) "
    2708             :                         "AND scale = 1.0) "
    2709             :                         "LIMIT 1",
    2710             :                         pszTableName);
    2711             :                 }
    2712             :                 else
    2713             :                 {
    2714          50 :                     pszSQL = sqlite3_mprintf(
    2715             :                         "SELECT 1 FROM "
    2716             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2717             :                         "tpudt_name = '%q' "
    2718             :                         "AND NOT (offset = 0.0 AND scale = 1.0) LIMIT 1",
    2719             :                         pszTableName);
    2720             :                 }
    2721          59 :                 sqlite3_stmt *hSQLStmt = nullptr;
    2722             :                 int rc =
    2723          59 :                     SQLPrepareWithError(hDB, pszSQL, -1, &hSQLStmt, nullptr);
    2724             : 
    2725          59 :                 if (rc == SQLITE_OK)
    2726             :                 {
    2727          59 :                     if (sqlite3_step(hSQLStmt) == SQLITE_ROW)
    2728             :                     {
    2729           8 :                         SetDataType(GDT_Float32);
    2730             :                     }
    2731          59 :                     sqlite3_finalize(hSQLStmt);
    2732             :                 }
    2733          59 :                 sqlite3_free(pszSQL);
    2734             :             }
    2735             : 
    2736          59 :             SetGlobalOffsetScale(dfOffset, dfScale);
    2737             :         }
    2738          65 :         if (pszPrecision)
    2739          65 :             m_dfPrecision = CPLAtof(pszPrecision);
    2740             : 
    2741             :         // Request those columns in a separate query, so as to keep
    2742             :         // compatibility with pre OGC 17-066r1 databases
    2743             :         pszSQL =
    2744          65 :             sqlite3_mprintf("SELECT uom, field_name, grid_cell_encoding FROM "
    2745             :                             "gpkg_2d_gridded_coverage_ancillary "
    2746             :                             "WHERE tile_matrix_set_name = '%q'",
    2747             :                             pszTableName);
    2748          65 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    2749          65 :         oResult = SQLQuery(hDB, pszSQL);
    2750          65 :         CPLPopErrorHandler();
    2751          65 :         sqlite3_free(pszSQL);
    2752          65 :         if (oResult && oResult->RowCount() == 1)
    2753             :         {
    2754          64 :             const char *pszUom = oResult->GetValue(0, 0);
    2755          64 :             if (pszUom)
    2756           2 :                 osUom = pszUom;
    2757          64 :             const char *pszFieldName = oResult->GetValue(1, 0);
    2758          64 :             if (pszFieldName)
    2759          64 :                 osFieldName = pszFieldName;
    2760          64 :             const char *pszGridCellEncoding = oResult->GetValue(2, 0);
    2761          64 :             if (pszGridCellEncoding)
    2762          64 :                 osGridCellEncoding = pszGridCellEncoding;
    2763             :         }
    2764             :     }
    2765             : 
    2766         274 :     m_bRecordInsertedInGPKGContent = true;
    2767         274 :     m_nSRID = nSRSId;
    2768             : 
    2769         547 :     if (auto poSRS = GetSpatialRef(nSRSId))
    2770             :     {
    2771         273 :         m_oSRS = *(poSRS.get());
    2772             :     }
    2773             : 
    2774             :     /* Various sanity checks added in the SELECT */
    2775         274 :     char *pszQuotedTableName = sqlite3_mprintf("'%q'", pszTableName);
    2776         548 :     CPLString osQuotedTableName(pszQuotedTableName);
    2777         274 :     sqlite3_free(pszQuotedTableName);
    2778         274 :     char *pszSQL = sqlite3_mprintf(
    2779             :         "SELECT zoom_level, pixel_x_size, pixel_y_size, tile_width, "
    2780             :         "tile_height, matrix_width, matrix_height "
    2781             :         "FROM gpkg_tile_matrix tm "
    2782             :         "WHERE table_name = %s "
    2783             :         // INT_MAX would be the theoretical maximum value to avoid
    2784             :         // overflows, but that's already a insane value.
    2785             :         "AND zoom_level >= 0 AND zoom_level <= 65536 "
    2786             :         "AND pixel_x_size > 0 AND pixel_y_size > 0 "
    2787             :         "AND tile_width >= 1 AND tile_width <= 65536 "
    2788             :         "AND tile_height >= 1 AND tile_height <= 65536 "
    2789             :         "AND matrix_width >= 1 AND matrix_height >= 1",
    2790             :         osQuotedTableName.c_str());
    2791         548 :     CPLString osSQL(pszSQL);
    2792             :     const char *pszZoomLevel =
    2793         274 :         CSLFetchNameValue(papszOpenOptionsIn, "ZOOM_LEVEL");
    2794         274 :     if (pszZoomLevel)
    2795             :     {
    2796           5 :         if (GetUpdate())
    2797           1 :             osSQL += CPLSPrintf(" AND zoom_level <= %d", atoi(pszZoomLevel));
    2798             :         else
    2799             :         {
    2800             :             osSQL += CPLSPrintf(
    2801             :                 " AND (zoom_level = %d OR (zoom_level < %d AND EXISTS(SELECT 1 "
    2802             :                 "FROM %s WHERE zoom_level = tm.zoom_level LIMIT 1)))",
    2803             :                 atoi(pszZoomLevel), atoi(pszZoomLevel),
    2804           4 :                 osQuotedTableName.c_str());
    2805             :         }
    2806             :     }
    2807             :     // In read-only mode, only lists non empty zoom levels
    2808         269 :     else if (!GetUpdate())
    2809             :     {
    2810             :         osSQL += CPLSPrintf(" AND EXISTS(SELECT 1 FROM %s WHERE zoom_level = "
    2811             :                             "tm.zoom_level LIMIT 1)",
    2812         215 :                             osQuotedTableName.c_str());
    2813             :     }
    2814             :     else  // if( pszZoomLevel == nullptr )
    2815             :     {
    2816             :         osSQL +=
    2817             :             CPLSPrintf(" AND zoom_level <= (SELECT MAX(zoom_level) FROM %s)",
    2818          54 :                        osQuotedTableName.c_str());
    2819             :     }
    2820         274 :     osSQL += " ORDER BY zoom_level DESC";
    2821             :     // To avoid denial of service.
    2822         274 :     osSQL += " LIMIT 100";
    2823             : 
    2824         548 :     auto oResult = SQLQuery(hDB, osSQL.c_str());
    2825         274 :     if (!oResult || oResult->RowCount() == 0)
    2826             :     {
    2827         114 :         if (oResult && oResult->RowCount() == 0 && pszContentsMinX != nullptr &&
    2828         114 :             pszContentsMinY != nullptr && pszContentsMaxX != nullptr &&
    2829             :             pszContentsMaxY != nullptr)
    2830             :         {
    2831          56 :             osSQL = pszSQL;
    2832          56 :             osSQL += " ORDER BY zoom_level DESC";
    2833          56 :             if (!GetUpdate())
    2834          30 :                 osSQL += " LIMIT 1";
    2835          56 :             oResult = SQLQuery(hDB, osSQL.c_str());
    2836             :         }
    2837          57 :         if (!oResult || oResult->RowCount() == 0)
    2838             :         {
    2839           1 :             if (oResult && pszZoomLevel != nullptr)
    2840             :             {
    2841           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2842             :                          "ZOOM_LEVEL is probably not valid w.r.t tile "
    2843             :                          "table content");
    2844             :             }
    2845           1 :             sqlite3_free(pszSQL);
    2846           1 :             return false;
    2847             :         }
    2848             :     }
    2849         273 :     sqlite3_free(pszSQL);
    2850             : 
    2851             :     // If USE_TILE_EXTENT=YES, then query the tile table to find which tiles
    2852             :     // actually exist.
    2853             : 
    2854             :     // CAUTION: Do not move those variables inside inner scope !
    2855         546 :     CPLString osContentsMinX, osContentsMinY, osContentsMaxX, osContentsMaxY;
    2856             : 
    2857         273 :     if (CPLTestBool(
    2858             :             CSLFetchNameValueDef(papszOpenOptionsIn, "USE_TILE_EXTENT", "NO")))
    2859             :     {
    2860          13 :         pszSQL = sqlite3_mprintf(
    2861             :             "SELECT MIN(tile_column), MIN(tile_row), MAX(tile_column), "
    2862             :             "MAX(tile_row) FROM \"%w\" WHERE zoom_level = %d",
    2863             :             pszTableName, atoi(oResult->GetValue(0, 0)));
    2864          13 :         auto oResult2 = SQLQuery(hDB, pszSQL);
    2865          13 :         sqlite3_free(pszSQL);
    2866          26 :         if (!oResult2 || oResult2->RowCount() == 0 ||
    2867             :             // Can happen if table is empty
    2868          38 :             oResult2->GetValue(0, 0) == nullptr ||
    2869             :             // Can happen if table has no NOT NULL constraint on tile_row
    2870             :             // and that all tile_row are NULL
    2871          12 :             oResult2->GetValue(1, 0) == nullptr)
    2872             :         {
    2873           1 :             return false;
    2874             :         }
    2875          12 :         const double dfPixelXSize = CPLAtof(oResult->GetValue(1, 0));
    2876          12 :         const double dfPixelYSize = CPLAtof(oResult->GetValue(2, 0));
    2877          12 :         const int nTileWidth = atoi(oResult->GetValue(3, 0));
    2878          12 :         const int nTileHeight = atoi(oResult->GetValue(4, 0));
    2879             :         osContentsMinX =
    2880          24 :             CPLSPrintf("%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2881          12 :                                              atoi(oResult2->GetValue(0, 0)));
    2882             :         osContentsMaxY =
    2883          24 :             CPLSPrintf("%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2884          12 :                                              atoi(oResult2->GetValue(1, 0)));
    2885             :         osContentsMaxX = CPLSPrintf(
    2886          24 :             "%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2887          12 :                                   (1 + atoi(oResult2->GetValue(2, 0))));
    2888             :         osContentsMinY = CPLSPrintf(
    2889          24 :             "%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2890          12 :                                   (1 + atoi(oResult2->GetValue(3, 0))));
    2891          12 :         pszContentsMinX = osContentsMinX.c_str();
    2892          12 :         pszContentsMinY = osContentsMinY.c_str();
    2893          12 :         pszContentsMaxX = osContentsMaxX.c_str();
    2894          12 :         pszContentsMaxY = osContentsMaxY.c_str();
    2895             :     }
    2896             : 
    2897         272 :     if (!InitRaster(nullptr, pszTableName, dfMinX, dfMinY, dfMaxX, dfMaxY,
    2898             :                     pszContentsMinX, pszContentsMinY, pszContentsMaxX,
    2899         272 :                     pszContentsMaxY, papszOpenOptionsIn, *oResult, 0))
    2900             :     {
    2901           3 :         return false;
    2902             :     }
    2903             : 
    2904         269 :     auto poBand = cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(1));
    2905         269 :     if (!osDataNull.empty())
    2906             :     {
    2907          23 :         double dfGPKGNoDataValue = CPLAtof(osDataNull);
    2908          23 :         if (m_eTF == GPKG_TF_PNG_16BIT)
    2909             :         {
    2910          21 :             if (dfGPKGNoDataValue < 0 || dfGPKGNoDataValue > 65535 ||
    2911          21 :                 static_cast<int>(dfGPKGNoDataValue) != dfGPKGNoDataValue)
    2912             :             {
    2913           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2914             :                          "data_null = %.17g is invalid for integer data_type",
    2915             :                          dfGPKGNoDataValue);
    2916             :             }
    2917             :             else
    2918             :             {
    2919          21 :                 m_usGPKGNull = static_cast<GUInt16>(dfGPKGNoDataValue);
    2920          21 :                 if (m_eDT == GDT_Int16 && m_usGPKGNull > 32767)
    2921           9 :                     dfGPKGNoDataValue = -32768.0;
    2922          12 :                 else if (m_eDT == GDT_Float32)
    2923             :                 {
    2924             :                     // Pick a value that is unlikely to be hit with offset &
    2925             :                     // scale
    2926           4 :                     dfGPKGNoDataValue = -std::numeric_limits<float>::max();
    2927             :                 }
    2928          21 :                 poBand->SetNoDataValueInternal(dfGPKGNoDataValue);
    2929             :             }
    2930             :         }
    2931             :         else
    2932             :         {
    2933           2 :             poBand->SetNoDataValueInternal(
    2934           2 :                 static_cast<float>(dfGPKGNoDataValue));
    2935             :         }
    2936             :     }
    2937         269 :     if (!osUom.empty())
    2938             :     {
    2939           2 :         poBand->SetUnitTypeInternal(osUom);
    2940             :     }
    2941         269 :     if (!osFieldName.empty())
    2942             :     {
    2943          64 :         GetRasterBand(1)->GDALRasterBand::SetDescription(osFieldName);
    2944             :     }
    2945         269 :     if (!osGridCellEncoding.empty())
    2946             :     {
    2947          64 :         if (osGridCellEncoding == "grid-value-is-center")
    2948             :         {
    2949          15 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2950             :                                             GDALMD_AOP_POINT);
    2951             :         }
    2952          49 :         else if (osGridCellEncoding == "grid-value-is-area")
    2953             :         {
    2954          45 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2955             :                                             GDALMD_AOP_AREA);
    2956             :         }
    2957             :         else
    2958             :         {
    2959           4 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2960             :                                             GDALMD_AOP_POINT);
    2961           4 :             GetRasterBand(1)->GDALRasterBand::SetMetadataItem(
    2962             :                 "GRID_CELL_ENCODING", osGridCellEncoding);
    2963             :         }
    2964             :     }
    2965             : 
    2966         269 :     CheckUnknownExtensions(true);
    2967             : 
    2968             :     // Do this after CheckUnknownExtensions() so that m_eTF is set to
    2969             :     // GPKG_TF_WEBP if the table already registers the gpkg_webp extension
    2970         269 :     const char *pszTF = CSLFetchNameValue(papszOpenOptionsIn, "TILE_FORMAT");
    2971         269 :     if (pszTF)
    2972             :     {
    2973           4 :         if (!GetUpdate())
    2974             :         {
    2975           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2976             :                      "TILE_FORMAT open option ignored in read-only mode");
    2977             :         }
    2978           4 :         else if (m_eTF == GPKG_TF_PNG_16BIT ||
    2979           4 :                  m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    2980             :         {
    2981           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2982             :                      "TILE_FORMAT open option ignored on gridded coverages");
    2983             :         }
    2984             :         else
    2985             :         {
    2986           4 :             GPKGTileFormat eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    2987           4 :             if (eTF == GPKG_TF_WEBP && m_eTF != eTF)
    2988             :             {
    2989           1 :                 if (!RegisterWebPExtension())
    2990           0 :                     return false;
    2991             :             }
    2992           4 :             m_eTF = eTF;
    2993             :         }
    2994             :     }
    2995             : 
    2996         269 :     ParseCompressionOptions(papszOpenOptionsIn);
    2997             : 
    2998         269 :     m_osWHERE = CSLFetchNameValueDef(papszOpenOptionsIn, "WHERE", "");
    2999             : 
    3000             :     // Set metadata
    3001         269 :     if (pszIdentifier && pszIdentifier[0])
    3002         269 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", pszIdentifier);
    3003         269 :     if (pszDescription && pszDescription[0])
    3004          21 :         GDALPamDataset::SetMetadataItem("DESCRIPTION", pszDescription);
    3005             : 
    3006             :     // Add overviews
    3007         354 :     for (int i = 1; i < oResult->RowCount(); i++)
    3008             :     {
    3009          86 :         auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3010          86 :         poOvrDS->ShareLockWithParentDataset(this);
    3011         172 :         if (!poOvrDS->InitRaster(this, pszTableName, dfMinX, dfMinY, dfMaxX,
    3012             :                                  dfMaxY, pszContentsMinX, pszContentsMinY,
    3013             :                                  pszContentsMaxX, pszContentsMaxY,
    3014          86 :                                  papszOpenOptionsIn, *oResult, i))
    3015             :         {
    3016           0 :             break;
    3017             :         }
    3018             : 
    3019             :         int nTileWidth, nTileHeight;
    3020          86 :         poOvrDS->GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3021             :         const bool bStop =
    3022          87 :             (eAccess == GA_ReadOnly && poOvrDS->GetRasterXSize() < nTileWidth &&
    3023           1 :              poOvrDS->GetRasterYSize() < nTileHeight);
    3024             : 
    3025          86 :         m_apoOverviewDS.push_back(std::move(poOvrDS));
    3026             : 
    3027          86 :         if (bStop)
    3028             :         {
    3029           1 :             break;
    3030             :         }
    3031             :     }
    3032             : 
    3033         269 :     return true;
    3034             : }
    3035             : 
    3036             : /************************************************************************/
    3037             : /*                           GetSpatialRef()                            */
    3038             : /************************************************************************/
    3039             : 
    3040          17 : const OGRSpatialReference *GDALGeoPackageDataset::GetSpatialRef() const
    3041             : {
    3042          17 :     if (GetLayerCount())
    3043           1 :         return GDALDataset::GetSpatialRef();
    3044          16 :     return GetSpatialRefRasterOnly();
    3045             : }
    3046             : 
    3047             : /************************************************************************/
    3048             : /*                      GetSpatialRefRasterOnly()                       */
    3049             : /************************************************************************/
    3050             : 
    3051             : const OGRSpatialReference *
    3052          17 : GDALGeoPackageDataset::GetSpatialRefRasterOnly() const
    3053             : 
    3054             : {
    3055          17 :     return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
    3056             : }
    3057             : 
    3058             : /************************************************************************/
    3059             : /*                           SetSpatialRef()                            */
    3060             : /************************************************************************/
    3061             : 
    3062         152 : CPLErr GDALGeoPackageDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    3063             : {
    3064         152 :     if (nBands == 0)
    3065             :     {
    3066           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3067             :                  "SetProjection() not supported on a dataset with 0 band");
    3068           1 :         return CE_Failure;
    3069             :     }
    3070         151 :     if (eAccess != GA_Update)
    3071             :     {
    3072           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3073             :                  "SetProjection() not supported on read-only dataset");
    3074           1 :         return CE_Failure;
    3075             :     }
    3076             : 
    3077         150 :     const int nSRID = GetSrsId(poSRS);
    3078         300 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3079         150 :     if (poTS && nSRID != poTS->nEPSGCode)
    3080             :     {
    3081           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3082             :                  "Projection should be EPSG:%d for %s tiling scheme",
    3083           1 :                  poTS->nEPSGCode, m_osTilingScheme.c_str());
    3084           1 :         return CE_Failure;
    3085             :     }
    3086             : 
    3087         149 :     m_nSRID = nSRID;
    3088         149 :     m_oSRS.Clear();
    3089         149 :     if (poSRS)
    3090         148 :         m_oSRS = *poSRS;
    3091             : 
    3092         149 :     if (m_bRecordInsertedInGPKGContent)
    3093             :     {
    3094         121 :         char *pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET srs_id = %d "
    3095             :                                        "WHERE lower(table_name) = lower('%q')",
    3096             :                                        m_nSRID, m_osRasterTable.c_str());
    3097         121 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3098         121 :         sqlite3_free(pszSQL);
    3099         121 :         if (eErr != OGRERR_NONE)
    3100           0 :             return CE_Failure;
    3101             : 
    3102         121 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_tile_matrix_set SET srs_id = %d "
    3103             :                                  "WHERE lower(table_name) = lower('%q')",
    3104             :                                  m_nSRID, m_osRasterTable.c_str());
    3105         121 :         eErr = SQLCommand(hDB, pszSQL);
    3106         121 :         sqlite3_free(pszSQL);
    3107         121 :         if (eErr != OGRERR_NONE)
    3108           0 :             return CE_Failure;
    3109             :     }
    3110             : 
    3111         149 :     return CE_None;
    3112             : }
    3113             : 
    3114             : /************************************************************************/
    3115             : /*                          GetGeoTransform()                           */
    3116             : /************************************************************************/
    3117             : 
    3118          33 : CPLErr GDALGeoPackageDataset::GetGeoTransform(GDALGeoTransform &gt) const
    3119             : {
    3120          33 :     gt = m_gt;
    3121          33 :     if (!m_bGeoTransformValid)
    3122           2 :         return CE_Failure;
    3123             :     else
    3124          31 :         return CE_None;
    3125             : }
    3126             : 
    3127             : /************************************************************************/
    3128             : /*                          SetGeoTransform()                           */
    3129             : /************************************************************************/
    3130             : 
    3131         192 : CPLErr GDALGeoPackageDataset::SetGeoTransform(const GDALGeoTransform &gt)
    3132             : {
    3133         192 :     if (nBands == 0)
    3134             :     {
    3135           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3136             :                  "SetGeoTransform() not supported on a dataset with 0 band");
    3137           2 :         return CE_Failure;
    3138             :     }
    3139         190 :     if (eAccess != GA_Update)
    3140             :     {
    3141           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3142             :                  "SetGeoTransform() not supported on read-only dataset");
    3143           1 :         return CE_Failure;
    3144             :     }
    3145         189 :     if (m_bGeoTransformValid)
    3146             :     {
    3147           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3148             :                  "Cannot modify geotransform once set");
    3149           1 :         return CE_Failure;
    3150             :     }
    3151         188 :     if (gt[2] != 0.0 || gt[4] != 0 || gt[5] > 0.0)
    3152             :     {
    3153           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3154             :                  "Only north-up non rotated geotransform supported");
    3155           0 :         return CE_Failure;
    3156             :     }
    3157             : 
    3158         188 :     if (m_nZoomLevel < 0)
    3159             :     {
    3160         187 :         const auto poTS = GetTilingScheme(m_osTilingScheme);
    3161         187 :         if (poTS)
    3162             :         {
    3163          20 :             double dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3164          20 :             double dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3165         199 :             for (m_nZoomLevel = 0; m_nZoomLevel < MAX_ZOOM_LEVEL;
    3166         179 :                  m_nZoomLevel++)
    3167             :             {
    3168         198 :                 double dfExpectedPixelXSize =
    3169         198 :                     dfPixelXSizeZoomLevel0 / (1 << m_nZoomLevel);
    3170         198 :                 double dfExpectedPixelYSize =
    3171         198 :                     dfPixelYSizeZoomLevel0 / (1 << m_nZoomLevel);
    3172         198 :                 if (fabs(gt[1] - dfExpectedPixelXSize) <
    3173         217 :                         1e-8 * dfExpectedPixelXSize &&
    3174          19 :                     fabs(fabs(gt[5]) - dfExpectedPixelYSize) <
    3175          19 :                         1e-8 * dfExpectedPixelYSize)
    3176             :                 {
    3177          19 :                     break;
    3178             :                 }
    3179             :             }
    3180          20 :             if (m_nZoomLevel == MAX_ZOOM_LEVEL)
    3181             :             {
    3182           1 :                 m_nZoomLevel = -1;
    3183           1 :                 CPLError(
    3184             :                     CE_Failure, CPLE_NotSupported,
    3185             :                     "Could not find an appropriate zoom level of %s tiling "
    3186             :                     "scheme that matches raster pixel size",
    3187             :                     m_osTilingScheme.c_str());
    3188           1 :                 return CE_Failure;
    3189             :             }
    3190             :         }
    3191             :     }
    3192             : 
    3193         187 :     m_gt = gt;
    3194         187 :     m_bGeoTransformValid = true;
    3195             : 
    3196         187 :     return FinalizeRasterRegistration();
    3197             : }
    3198             : 
    3199             : /************************************************************************/
    3200             : /*                      FinalizeRasterRegistration()                    */
    3201             : /************************************************************************/
    3202             : 
    3203         187 : CPLErr GDALGeoPackageDataset::FinalizeRasterRegistration()
    3204             : {
    3205             :     OGRErr eErr;
    3206             : 
    3207         187 :     m_dfTMSMinX = m_gt[0];
    3208         187 :     m_dfTMSMaxY = m_gt[3];
    3209             : 
    3210             :     int nTileWidth, nTileHeight;
    3211         187 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3212             : 
    3213         187 :     if (m_nZoomLevel < 0)
    3214             :     {
    3215         167 :         m_nZoomLevel = 0;
    3216         241 :         while ((nRasterXSize >> m_nZoomLevel) > nTileWidth ||
    3217         167 :                (nRasterYSize >> m_nZoomLevel) > nTileHeight)
    3218          74 :             m_nZoomLevel++;
    3219             :     }
    3220             : 
    3221         187 :     double dfPixelXSizeZoomLevel0 = m_gt[1] * (1 << m_nZoomLevel);
    3222         187 :     double dfPixelYSizeZoomLevel0 = fabs(m_gt[5]) * (1 << m_nZoomLevel);
    3223             :     int nTileXCountZoomLevel0 =
    3224         187 :         std::max(1, DIV_ROUND_UP((nRasterXSize >> m_nZoomLevel), nTileWidth));
    3225             :     int nTileYCountZoomLevel0 =
    3226         187 :         std::max(1, DIV_ROUND_UP((nRasterYSize >> m_nZoomLevel), nTileHeight));
    3227             : 
    3228         374 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3229         187 :     if (poTS)
    3230             :     {
    3231          20 :         CPLAssert(m_nZoomLevel >= 0);
    3232          20 :         m_dfTMSMinX = poTS->dfMinX;
    3233          20 :         m_dfTMSMaxY = poTS->dfMaxY;
    3234          20 :         dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3235          20 :         dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3236          20 :         nTileXCountZoomLevel0 = poTS->nTileXCountZoomLevel0;
    3237          20 :         nTileYCountZoomLevel0 = poTS->nTileYCountZoomLevel0;
    3238             :     }
    3239         187 :     m_nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << m_nZoomLevel);
    3240         187 :     m_nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << m_nZoomLevel);
    3241             : 
    3242         187 :     if (!ComputeTileAndPixelShifts())
    3243             :     {
    3244           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    3245             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    3246           1 :         return CE_Failure;
    3247             :     }
    3248             : 
    3249         186 :     if (!AllocCachedTiles())
    3250             :     {
    3251           0 :         return CE_Failure;
    3252             :     }
    3253             : 
    3254         186 :     double dfGDALMinX = m_gt[0];
    3255         186 :     double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3256         186 :     double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3257         186 :     double dfGDALMaxY = m_gt[3];
    3258             : 
    3259         186 :     if (SoftStartTransaction() != OGRERR_NONE)
    3260           0 :         return CE_Failure;
    3261             : 
    3262             :     const char *pszCurrentDate =
    3263         186 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3264             :     CPLString osInsertGpkgContentsFormatting(
    3265             :         "INSERT INTO gpkg_contents "
    3266             :         "(table_name,data_type,identifier,description,min_x,min_y,max_x,max_y,"
    3267             :         "last_change,srs_id) VALUES "
    3268         372 :         "('%q','%q','%q','%q',%.17g,%.17g,%.17g,%.17g,");
    3269         186 :     osInsertGpkgContentsFormatting += (pszCurrentDate) ? "'%q'" : "%s";
    3270         186 :     osInsertGpkgContentsFormatting += ",%d)";
    3271         372 :     char *pszSQL = sqlite3_mprintf(
    3272             :         osInsertGpkgContentsFormatting.c_str(), m_osRasterTable.c_str(),
    3273         186 :         (m_eDT == GDT_Byte) ? "tiles" : "2d-gridded-coverage",
    3274             :         m_osIdentifier.c_str(), m_osDescription.c_str(), dfGDALMinX, dfGDALMinY,
    3275             :         dfGDALMaxX, dfGDALMaxY,
    3276             :         pszCurrentDate ? pszCurrentDate
    3277             :                        : "strftime('%Y-%m-%dT%H:%M:%fZ','now')",
    3278             :         m_nSRID);
    3279             : 
    3280         186 :     eErr = SQLCommand(hDB, pszSQL);
    3281         186 :     sqlite3_free(pszSQL);
    3282         186 :     if (eErr != OGRERR_NONE)
    3283             :     {
    3284           8 :         SoftRollbackTransaction();
    3285           8 :         return CE_Failure;
    3286             :     }
    3287             : 
    3288         178 :     double dfTMSMaxX = m_dfTMSMinX + nTileXCountZoomLevel0 * nTileWidth *
    3289             :                                          dfPixelXSizeZoomLevel0;
    3290         178 :     double dfTMSMinY = m_dfTMSMaxY - nTileYCountZoomLevel0 * nTileHeight *
    3291             :                                          dfPixelYSizeZoomLevel0;
    3292             : 
    3293             :     pszSQL =
    3294         178 :         sqlite3_mprintf("INSERT INTO gpkg_tile_matrix_set "
    3295             :                         "(table_name,srs_id,min_x,min_y,max_x,max_y) VALUES "
    3296             :                         "('%q',%d,%.17g,%.17g,%.17g,%.17g)",
    3297             :                         m_osRasterTable.c_str(), m_nSRID, m_dfTMSMinX,
    3298             :                         dfTMSMinY, dfTMSMaxX, m_dfTMSMaxY);
    3299         178 :     eErr = SQLCommand(hDB, pszSQL);
    3300         178 :     sqlite3_free(pszSQL);
    3301         178 :     if (eErr != OGRERR_NONE)
    3302             :     {
    3303           0 :         SoftRollbackTransaction();
    3304           0 :         return CE_Failure;
    3305             :     }
    3306             : 
    3307         178 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3308             : 
    3309         591 :     for (int i = 0; i <= m_nZoomLevel; i++)
    3310             :     {
    3311         413 :         double dfPixelXSizeZoomLevel = 0.0;
    3312         413 :         double dfPixelYSizeZoomLevel = 0.0;
    3313         413 :         int nTileMatrixWidth = 0;
    3314         413 :         int nTileMatrixHeight = 0;
    3315         413 :         if (EQUAL(m_osTilingScheme, "CUSTOM"))
    3316             :         {
    3317         232 :             dfPixelXSizeZoomLevel = m_gt[1] * (1 << (m_nZoomLevel - i));
    3318         232 :             dfPixelYSizeZoomLevel = fabs(m_gt[5]) * (1 << (m_nZoomLevel - i));
    3319             :         }
    3320             :         else
    3321             :         {
    3322         181 :             dfPixelXSizeZoomLevel = dfPixelXSizeZoomLevel0 / (1 << i);
    3323         181 :             dfPixelYSizeZoomLevel = dfPixelYSizeZoomLevel0 / (1 << i);
    3324             :         }
    3325         413 :         nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << i);
    3326         413 :         nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << i);
    3327             : 
    3328         413 :         pszSQL = sqlite3_mprintf(
    3329             :             "INSERT INTO gpkg_tile_matrix "
    3330             :             "(table_name,zoom_level,matrix_width,matrix_height,tile_width,tile_"
    3331             :             "height,pixel_x_size,pixel_y_size) VALUES "
    3332             :             "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3333             :             m_osRasterTable.c_str(), i, nTileMatrixWidth, nTileMatrixHeight,
    3334             :             nTileWidth, nTileHeight, dfPixelXSizeZoomLevel,
    3335             :             dfPixelYSizeZoomLevel);
    3336         413 :         eErr = SQLCommand(hDB, pszSQL);
    3337         413 :         sqlite3_free(pszSQL);
    3338         413 :         if (eErr != OGRERR_NONE)
    3339             :         {
    3340           0 :             SoftRollbackTransaction();
    3341           0 :             return CE_Failure;
    3342             :         }
    3343             : 
    3344         413 :         if (i < m_nZoomLevel)
    3345             :         {
    3346         470 :             auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3347         235 :             poOvrDS->ShareLockWithParentDataset(this);
    3348         235 :             poOvrDS->InitRaster(this, m_osRasterTable, i, nBands, m_dfTMSMinX,
    3349             :                                 m_dfTMSMaxY, dfPixelXSizeZoomLevel,
    3350             :                                 dfPixelYSizeZoomLevel, nTileWidth, nTileHeight,
    3351             :                                 nTileMatrixWidth, nTileMatrixHeight, dfGDALMinX,
    3352             :                                 dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    3353             : 
    3354         235 :             m_apoOverviewDS[m_nZoomLevel - 1 - i] = std::move(poOvrDS);
    3355             :         }
    3356             :     }
    3357             : 
    3358         178 :     if (!m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.empty())
    3359             :     {
    3360          40 :         eErr = SQLCommand(
    3361             :             hDB, m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.c_str());
    3362          40 :         m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.clear();
    3363          40 :         if (eErr != OGRERR_NONE)
    3364             :         {
    3365           0 :             SoftRollbackTransaction();
    3366           0 :             return CE_Failure;
    3367             :         }
    3368             :     }
    3369             : 
    3370         178 :     SoftCommitTransaction();
    3371             : 
    3372         178 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3373         178 :     m_bRecordInsertedInGPKGContent = true;
    3374             : 
    3375         178 :     return CE_None;
    3376             : }
    3377             : 
    3378             : /************************************************************************/
    3379             : /*                             FlushCache()                             */
    3380             : /************************************************************************/
    3381             : 
    3382        2773 : CPLErr GDALGeoPackageDataset::FlushCache(bool bAtClosing)
    3383             : {
    3384        2773 :     if (m_bInFlushCache)
    3385           0 :         return CE_None;
    3386             : 
    3387        2773 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3388             :     {
    3389        2770 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3390             :     }
    3391             : 
    3392        2773 :     if (m_bRemoveOGREmptyTable)
    3393             :     {
    3394         738 :         m_bRemoveOGREmptyTable = false;
    3395         738 :         RemoveOGREmptyTable();
    3396             :     }
    3397             : 
    3398        2773 :     CPLErr eErr = IFlushCacheWithErrCode(bAtClosing);
    3399             : 
    3400        2773 :     FlushMetadata();
    3401             : 
    3402        2773 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3403             :     {
    3404             :         // Needed again as above IFlushCacheWithErrCode()
    3405             :         // may have call GDALGeoPackageRasterBand::InvalidateStatistics()
    3406             :         // which modifies metadata
    3407        2773 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3408             :     }
    3409             : 
    3410        2773 :     return eErr;
    3411             : }
    3412             : 
    3413        5008 : CPLErr GDALGeoPackageDataset::IFlushCacheWithErrCode(bool bAtClosing)
    3414             : 
    3415             : {
    3416        5008 :     if (m_bInFlushCache)
    3417        2168 :         return CE_None;
    3418        2840 :     m_bInFlushCache = true;
    3419        2840 :     if (hDB && eAccess == GA_ReadOnly && bAtClosing)
    3420             :     {
    3421             :         // Clean-up metadata that will go to PAM by removing items that
    3422             :         // are reconstructed.
    3423        2056 :         CPLStringList aosMD;
    3424        1651 :         for (CSLConstList papszIter = GetMetadata(); papszIter && *papszIter;
    3425             :              ++papszIter)
    3426             :         {
    3427         623 :             char *pszKey = nullptr;
    3428         623 :             CPLParseNameValue(*papszIter, &pszKey);
    3429        1246 :             if (pszKey &&
    3430         623 :                 (EQUAL(pszKey, "AREA_OR_POINT") ||
    3431         477 :                  EQUAL(pszKey, "IDENTIFIER") || EQUAL(pszKey, "DESCRIPTION") ||
    3432         256 :                  EQUAL(pszKey, "ZOOM_LEVEL") ||
    3433         653 :                  STARTS_WITH(pszKey, "GPKG_METADATA_ITEM_")))
    3434             :             {
    3435             :                 // remove it
    3436             :             }
    3437             :             else
    3438             :             {
    3439          30 :                 aosMD.AddString(*papszIter);
    3440             :             }
    3441         623 :             CPLFree(pszKey);
    3442             :         }
    3443        1028 :         oMDMD.SetMetadata(aosMD.List());
    3444        1028 :         oMDMD.SetMetadata(nullptr, "IMAGE_STRUCTURE");
    3445             : 
    3446        2056 :         GDALPamDataset::FlushCache(bAtClosing);
    3447             :     }
    3448             :     else
    3449             :     {
    3450             :         // Short circuit GDALPamDataset to avoid serialization to .aux.xml
    3451        1812 :         GDALDataset::FlushCache(bAtClosing);
    3452             :     }
    3453             : 
    3454        6944 :     for (auto &poLayer : m_apoLayers)
    3455             :     {
    3456        4104 :         poLayer->RunDeferredCreationIfNecessary();
    3457        4104 :         poLayer->CreateSpatialIndexIfNecessary();
    3458             :     }
    3459             : 
    3460             :     // Update raster table last_change column in gpkg_contents if needed
    3461        2840 :     if (m_bHasModifiedTiles)
    3462             :     {
    3463         540 :         for (int i = 1; i <= nBands; ++i)
    3464             :         {
    3465             :             auto poBand =
    3466         359 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    3467         359 :             if (!poBand->HaveStatsMetadataBeenSetInThisSession())
    3468             :             {
    3469         346 :                 poBand->InvalidateStatistics();
    3470         346 :                 if (psPam && psPam->pszPamFilename)
    3471         346 :                     VSIUnlink(psPam->pszPamFilename);
    3472             :             }
    3473             :         }
    3474             : 
    3475         181 :         UpdateGpkgContentsLastChange(m_osRasterTable);
    3476             : 
    3477         181 :         m_bHasModifiedTiles = false;
    3478             :     }
    3479             : 
    3480        2840 :     CPLErr eErr = FlushTiles();
    3481             : 
    3482        2840 :     m_bInFlushCache = false;
    3483        2840 :     return eErr;
    3484             : }
    3485             : 
    3486             : /************************************************************************/
    3487             : /*                       GetCurrentDateEscapedSQL()                      */
    3488             : /************************************************************************/
    3489             : 
    3490        2080 : std::string GDALGeoPackageDataset::GetCurrentDateEscapedSQL()
    3491             : {
    3492             :     const char *pszCurrentDate =
    3493        2080 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3494        2080 :     if (pszCurrentDate)
    3495          10 :         return '\'' + SQLEscapeLiteral(pszCurrentDate) + '\'';
    3496        2075 :     return "strftime('%Y-%m-%dT%H:%M:%fZ','now')";
    3497             : }
    3498             : 
    3499             : /************************************************************************/
    3500             : /*                    UpdateGpkgContentsLastChange()                    */
    3501             : /************************************************************************/
    3502             : 
    3503             : OGRErr
    3504         909 : GDALGeoPackageDataset::UpdateGpkgContentsLastChange(const char *pszTableName)
    3505             : {
    3506             :     char *pszSQL =
    3507         909 :         sqlite3_mprintf("UPDATE gpkg_contents SET "
    3508             :                         "last_change = %s "
    3509             :                         "WHERE lower(table_name) = lower('%q')",
    3510        1818 :                         GetCurrentDateEscapedSQL().c_str(), pszTableName);
    3511         909 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    3512         909 :     sqlite3_free(pszSQL);
    3513         909 :     return eErr;
    3514             : }
    3515             : 
    3516             : /************************************************************************/
    3517             : /*                          IBuildOverviews()                           */
    3518             : /************************************************************************/
    3519             : 
    3520          20 : CPLErr GDALGeoPackageDataset::IBuildOverviews(
    3521             :     const char *pszResampling, int nOverviews, const int *panOverviewList,
    3522             :     int nBandsIn, const int * /*panBandList*/, GDALProgressFunc pfnProgress,
    3523             :     void *pProgressData, CSLConstList papszOptions)
    3524             : {
    3525          20 :     if (GetAccess() != GA_Update)
    3526             :     {
    3527           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3528             :                  "Overview building not supported on a database opened in "
    3529             :                  "read-only mode");
    3530           1 :         return CE_Failure;
    3531             :     }
    3532          19 :     if (m_poParentDS != nullptr)
    3533             :     {
    3534           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3535             :                  "Overview building not supported on overview dataset");
    3536           1 :         return CE_Failure;
    3537             :     }
    3538             : 
    3539          18 :     if (nOverviews == 0)
    3540             :     {
    3541           5 :         for (auto &poOvrDS : m_apoOverviewDS)
    3542           3 :             poOvrDS->FlushCache(false);
    3543             : 
    3544           2 :         SoftStartTransaction();
    3545             : 
    3546           2 :         if (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    3547             :         {
    3548           1 :             char *pszSQL = sqlite3_mprintf(
    3549             :                 "DELETE FROM gpkg_2d_gridded_tile_ancillary WHERE id IN "
    3550             :                 "(SELECT y.id FROM \"%w\" x "
    3551             :                 "JOIN gpkg_2d_gridded_tile_ancillary y "
    3552             :                 "ON x.id = y.tpudt_id AND y.tpudt_name = '%q' AND "
    3553             :                 "x.zoom_level < %d)",
    3554             :                 m_osRasterTable.c_str(), m_osRasterTable.c_str(), m_nZoomLevel);
    3555           1 :             OGRErr eErr = SQLCommand(hDB, pszSQL);
    3556           1 :             sqlite3_free(pszSQL);
    3557           1 :             if (eErr != OGRERR_NONE)
    3558             :             {
    3559           0 :                 SoftRollbackTransaction();
    3560           0 :                 return CE_Failure;
    3561             :             }
    3562             :         }
    3563             : 
    3564             :         char *pszSQL =
    3565           2 :             sqlite3_mprintf("DELETE FROM \"%w\" WHERE zoom_level < %d",
    3566             :                             m_osRasterTable.c_str(), m_nZoomLevel);
    3567           2 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3568           2 :         sqlite3_free(pszSQL);
    3569           2 :         if (eErr != OGRERR_NONE)
    3570             :         {
    3571           0 :             SoftRollbackTransaction();
    3572           0 :             return CE_Failure;
    3573             :         }
    3574             : 
    3575           2 :         SoftCommitTransaction();
    3576             : 
    3577           2 :         return CE_None;
    3578             :     }
    3579             : 
    3580          16 :     if (nBandsIn != nBands)
    3581             :     {
    3582           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3583             :                  "Generation of overviews in GPKG only"
    3584             :                  "supported when operating on all bands.");
    3585           0 :         return CE_Failure;
    3586             :     }
    3587             : 
    3588          16 :     if (m_apoOverviewDS.empty())
    3589             :     {
    3590           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3591             :                  "Image too small to support overviews");
    3592           0 :         return CE_Failure;
    3593             :     }
    3594             : 
    3595          16 :     FlushCache(false);
    3596          60 :     for (int i = 0; i < nOverviews; i++)
    3597             :     {
    3598          47 :         if (panOverviewList[i] < 2)
    3599             :         {
    3600           1 :             CPLError(CE_Failure, CPLE_IllegalArg,
    3601             :                      "Overview factor must be >= 2");
    3602           1 :             return CE_Failure;
    3603             :         }
    3604             : 
    3605          46 :         bool bFound = false;
    3606          46 :         int jCandidate = -1;
    3607          46 :         int nMaxOvFactor = 0;
    3608         196 :         for (int j = 0; j < static_cast<int>(m_apoOverviewDS.size()); j++)
    3609             :         {
    3610         190 :             const auto poODS = m_apoOverviewDS[j].get();
    3611             :             const int nOvFactor =
    3612         190 :                 static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3613             : 
    3614         190 :             nMaxOvFactor = nOvFactor;
    3615             : 
    3616         190 :             if (nOvFactor == panOverviewList[i])
    3617             :             {
    3618          40 :                 bFound = true;
    3619          40 :                 break;
    3620             :             }
    3621             : 
    3622         150 :             if (jCandidate < 0 && nOvFactor > panOverviewList[i])
    3623           1 :                 jCandidate = j;
    3624             :         }
    3625             : 
    3626          46 :         if (!bFound)
    3627             :         {
    3628             :             /* Mostly for debug */
    3629           6 :             if (!CPLTestBool(CPLGetConfigOption(
    3630             :                     "ALLOW_GPKG_ZOOM_OTHER_EXTENSION", "YES")))
    3631             :             {
    3632           2 :                 CPLString osOvrList;
    3633           4 :                 for (const auto &poODS : m_apoOverviewDS)
    3634             :                 {
    3635             :                     const int nOvFactor =
    3636           2 :                         static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3637             : 
    3638           2 :                     if (!osOvrList.empty())
    3639           0 :                         osOvrList += ' ';
    3640           2 :                     osOvrList += CPLSPrintf("%d", nOvFactor);
    3641             :                 }
    3642           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    3643             :                          "Only overviews %s can be computed",
    3644             :                          osOvrList.c_str());
    3645           2 :                 return CE_Failure;
    3646             :             }
    3647             :             else
    3648             :             {
    3649           4 :                 int nOvFactor = panOverviewList[i];
    3650           4 :                 if (jCandidate < 0)
    3651           3 :                     jCandidate = static_cast<int>(m_apoOverviewDS.size());
    3652             : 
    3653           4 :                 int nOvXSize = std::max(1, GetRasterXSize() / nOvFactor);
    3654           4 :                 int nOvYSize = std::max(1, GetRasterYSize() / nOvFactor);
    3655           4 :                 if (!(jCandidate == static_cast<int>(m_apoOverviewDS.size()) &&
    3656           5 :                       nOvFactor == 2 * nMaxOvFactor) &&
    3657           1 :                     !m_bZoomOther)
    3658             :                 {
    3659           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    3660             :                              "Use of overview factor %d causes gpkg_zoom_other "
    3661             :                              "extension to be needed",
    3662             :                              nOvFactor);
    3663           1 :                     RegisterZoomOtherExtension();
    3664           1 :                     m_bZoomOther = true;
    3665             :                 }
    3666             : 
    3667           4 :                 SoftStartTransaction();
    3668             : 
    3669           4 :                 CPLAssert(jCandidate > 0);
    3670             :                 const int nNewZoomLevel =
    3671           4 :                     m_apoOverviewDS[jCandidate - 1]->m_nZoomLevel;
    3672             : 
    3673             :                 char *pszSQL;
    3674             :                 OGRErr eErr;
    3675          24 :                 for (int k = 0; k <= jCandidate; k++)
    3676             :                 {
    3677          60 :                     pszSQL = sqlite3_mprintf(
    3678             :                         "UPDATE gpkg_tile_matrix SET zoom_level = %d "
    3679             :                         "WHERE lower(table_name) = lower('%q') AND zoom_level "
    3680             :                         "= %d",
    3681          20 :                         m_nZoomLevel - k + 1, m_osRasterTable.c_str(),
    3682          20 :                         m_nZoomLevel - k);
    3683          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3684          20 :                     sqlite3_free(pszSQL);
    3685          20 :                     if (eErr != OGRERR_NONE)
    3686             :                     {
    3687           0 :                         SoftRollbackTransaction();
    3688           0 :                         return CE_Failure;
    3689             :                     }
    3690             : 
    3691             :                     pszSQL =
    3692          20 :                         sqlite3_mprintf("UPDATE \"%w\" SET zoom_level = %d "
    3693             :                                         "WHERE zoom_level = %d",
    3694             :                                         m_osRasterTable.c_str(),
    3695          20 :                                         m_nZoomLevel - k + 1, m_nZoomLevel - k);
    3696          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3697          20 :                     sqlite3_free(pszSQL);
    3698          20 :                     if (eErr != OGRERR_NONE)
    3699             :                     {
    3700           0 :                         SoftRollbackTransaction();
    3701           0 :                         return CE_Failure;
    3702             :                     }
    3703             :                 }
    3704             : 
    3705           4 :                 double dfGDALMinX = m_gt[0];
    3706           4 :                 double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3707           4 :                 double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3708           4 :                 double dfGDALMaxY = m_gt[3];
    3709           4 :                 double dfPixelXSizeZoomLevel = m_gt[1] * nOvFactor;
    3710           4 :                 double dfPixelYSizeZoomLevel = fabs(m_gt[5]) * nOvFactor;
    3711             :                 int nTileWidth, nTileHeight;
    3712           4 :                 GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3713           4 :                 int nTileMatrixWidth = DIV_ROUND_UP(nOvXSize, nTileWidth);
    3714           4 :                 int nTileMatrixHeight = DIV_ROUND_UP(nOvYSize, nTileHeight);
    3715           4 :                 pszSQL = sqlite3_mprintf(
    3716             :                     "INSERT INTO gpkg_tile_matrix "
    3717             :                     "(table_name,zoom_level,matrix_width,matrix_height,tile_"
    3718             :                     "width,tile_height,pixel_x_size,pixel_y_size) VALUES "
    3719             :                     "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3720             :                     m_osRasterTable.c_str(), nNewZoomLevel, nTileMatrixWidth,
    3721             :                     nTileMatrixHeight, nTileWidth, nTileHeight,
    3722             :                     dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel);
    3723           4 :                 eErr = SQLCommand(hDB, pszSQL);
    3724           4 :                 sqlite3_free(pszSQL);
    3725           4 :                 if (eErr != OGRERR_NONE)
    3726             :                 {
    3727           0 :                     SoftRollbackTransaction();
    3728           0 :                     return CE_Failure;
    3729             :                 }
    3730             : 
    3731           4 :                 SoftCommitTransaction();
    3732             : 
    3733           4 :                 m_nZoomLevel++; /* this change our zoom level as well as
    3734             :                                    previous overviews */
    3735          20 :                 for (int k = 0; k < jCandidate; k++)
    3736          16 :                     m_apoOverviewDS[k]->m_nZoomLevel++;
    3737             : 
    3738           4 :                 auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3739           4 :                 poOvrDS->ShareLockWithParentDataset(this);
    3740           4 :                 poOvrDS->InitRaster(
    3741             :                     this, m_osRasterTable, nNewZoomLevel, nBands, m_dfTMSMinX,
    3742             :                     m_dfTMSMaxY, dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel,
    3743             :                     nTileWidth, nTileHeight, nTileMatrixWidth,
    3744             :                     nTileMatrixHeight, dfGDALMinX, dfGDALMinY, dfGDALMaxX,
    3745             :                     dfGDALMaxY);
    3746           4 :                 m_apoOverviewDS.insert(m_apoOverviewDS.begin() + jCandidate,
    3747           8 :                                        std::move(poOvrDS));
    3748             :             }
    3749             :         }
    3750             :     }
    3751             : 
    3752             :     GDALRasterBand ***papapoOverviewBands = static_cast<GDALRasterBand ***>(
    3753          13 :         CPLCalloc(sizeof(GDALRasterBand **), nBands));
    3754          13 :     CPLErr eErr = CE_None;
    3755          49 :     for (int iBand = 0; eErr == CE_None && iBand < nBands; iBand++)
    3756             :     {
    3757          72 :         papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
    3758          36 :             CPLCalloc(sizeof(GDALRasterBand *), nOverviews));
    3759          36 :         int iCurOverview = 0;
    3760         185 :         for (int i = 0; i < nOverviews; i++)
    3761             :         {
    3762         149 :             bool bFound = false;
    3763         724 :             for (const auto &poODS : m_apoOverviewDS)
    3764             :             {
    3765             :                 const int nOvFactor =
    3766         724 :                     static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3767             : 
    3768         724 :                 if (nOvFactor == panOverviewList[i])
    3769             :                 {
    3770         298 :                     papapoOverviewBands[iBand][iCurOverview] =
    3771         149 :                         poODS->GetRasterBand(iBand + 1);
    3772         149 :                     iCurOverview++;
    3773         149 :                     bFound = true;
    3774         149 :                     break;
    3775             :                 }
    3776             :             }
    3777         149 :             if (!bFound)
    3778             :             {
    3779           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3780             :                          "Could not find dataset corresponding to ov factor %d",
    3781           0 :                          panOverviewList[i]);
    3782           0 :                 eErr = CE_Failure;
    3783             :             }
    3784             :         }
    3785          36 :         if (eErr == CE_None)
    3786             :         {
    3787          36 :             CPLAssert(iCurOverview == nOverviews);
    3788             :         }
    3789             :     }
    3790             : 
    3791          13 :     if (eErr == CE_None)
    3792          13 :         eErr = GDALRegenerateOverviewsMultiBand(
    3793          13 :             nBands, papoBands, nOverviews, papapoOverviewBands, pszResampling,
    3794             :             pfnProgress, pProgressData, papszOptions);
    3795             : 
    3796          49 :     for (int iBand = 0; iBand < nBands; iBand++)
    3797             :     {
    3798          36 :         CPLFree(papapoOverviewBands[iBand]);
    3799             :     }
    3800          13 :     CPLFree(papapoOverviewBands);
    3801             : 
    3802          13 :     return eErr;
    3803             : }
    3804             : 
    3805             : /************************************************************************/
    3806             : /*                            GetFileList()                             */
    3807             : /************************************************************************/
    3808             : 
    3809          38 : char **GDALGeoPackageDataset::GetFileList()
    3810             : {
    3811          38 :     TryLoadXML();
    3812          38 :     return GDALPamDataset::GetFileList();
    3813             : }
    3814             : 
    3815             : /************************************************************************/
    3816             : /*                      GetMetadataDomainList()                         */
    3817             : /************************************************************************/
    3818             : 
    3819          46 : char **GDALGeoPackageDataset::GetMetadataDomainList()
    3820             : {
    3821          46 :     GetMetadata();
    3822          46 :     if (!m_osRasterTable.empty())
    3823           5 :         GetMetadata("GEOPACKAGE");
    3824          46 :     return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
    3825          46 :                                    TRUE, "SUBDATASETS", nullptr);
    3826             : }
    3827             : 
    3828             : /************************************************************************/
    3829             : /*                        CheckMetadataDomain()                         */
    3830             : /************************************************************************/
    3831             : 
    3832        5916 : const char *GDALGeoPackageDataset::CheckMetadataDomain(const char *pszDomain)
    3833             : {
    3834        6101 :     if (pszDomain != nullptr && EQUAL(pszDomain, "GEOPACKAGE") &&
    3835         185 :         m_osRasterTable.empty())
    3836             :     {
    3837           4 :         CPLError(
    3838             :             CE_Warning, CPLE_IllegalArg,
    3839             :             "Using GEOPACKAGE for a non-raster geopackage is not supported. "
    3840             :             "Using default domain instead");
    3841           4 :         return nullptr;
    3842             :     }
    3843        5912 :     return pszDomain;
    3844             : }
    3845             : 
    3846             : /************************************************************************/
    3847             : /*                           HasMetadataTables()                        */
    3848             : /************************************************************************/
    3849             : 
    3850        5602 : bool GDALGeoPackageDataset::HasMetadataTables() const
    3851             : {
    3852        5602 :     if (m_nHasMetadataTables < 0)
    3853             :     {
    3854             :         const int nCount =
    3855        2127 :             SQLGetInteger(hDB,
    3856             :                           "SELECT COUNT(*) FROM sqlite_master WHERE name IN "
    3857             :                           "('gpkg_metadata', 'gpkg_metadata_reference') "
    3858             :                           "AND type IN ('table', 'view')",
    3859             :                           nullptr);
    3860        2127 :         m_nHasMetadataTables = nCount == 2;
    3861             :     }
    3862        5602 :     return CPL_TO_BOOL(m_nHasMetadataTables);
    3863             : }
    3864             : 
    3865             : /************************************************************************/
    3866             : /*                         HasDataColumnsTable()                        */
    3867             : /************************************************************************/
    3868             : 
    3869        1264 : bool GDALGeoPackageDataset::HasDataColumnsTable() const
    3870             : {
    3871        2528 :     const int nCount = SQLGetInteger(
    3872        1264 :         hDB,
    3873             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_data_columns'"
    3874             :         "AND type IN ('table', 'view')",
    3875             :         nullptr);
    3876        1264 :     return nCount == 1;
    3877             : }
    3878             : 
    3879             : /************************************************************************/
    3880             : /*                    HasDataColumnConstraintsTable()                   */
    3881             : /************************************************************************/
    3882             : 
    3883         158 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTable() const
    3884             : {
    3885         158 :     const int nCount = SQLGetInteger(hDB,
    3886             :                                      "SELECT 1 FROM sqlite_master WHERE name = "
    3887             :                                      "'gpkg_data_column_constraints'"
    3888             :                                      "AND type IN ('table', 'view')",
    3889             :                                      nullptr);
    3890         158 :     return nCount == 1;
    3891             : }
    3892             : 
    3893             : /************************************************************************/
    3894             : /*                  HasDataColumnConstraintsTableGPKG_1_0()             */
    3895             : /************************************************************************/
    3896             : 
    3897         109 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTableGPKG_1_0() const
    3898             : {
    3899         109 :     if (m_nApplicationId != GP10_APPLICATION_ID)
    3900         107 :         return false;
    3901             :     // In GPKG 1.0, the columns were named minIsInclusive, maxIsInclusive
    3902             :     // They were changed in 1.1 to min_is_inclusive, max_is_inclusive
    3903           2 :     bool bRet = false;
    3904           2 :     sqlite3_stmt *hSQLStmt = nullptr;
    3905           2 :     int rc = sqlite3_prepare_v2(hDB,
    3906             :                                 "SELECT minIsInclusive, maxIsInclusive FROM "
    3907             :                                 "gpkg_data_column_constraints",
    3908             :                                 -1, &hSQLStmt, nullptr);
    3909           2 :     if (rc == SQLITE_OK)
    3910             :     {
    3911           2 :         bRet = true;
    3912           2 :         sqlite3_finalize(hSQLStmt);
    3913             :     }
    3914           2 :     return bRet;
    3915             : }
    3916             : 
    3917             : /************************************************************************/
    3918             : /*      CreateColumnsTableAndColumnConstraintsTablesIfNecessary()       */
    3919             : /************************************************************************/
    3920             : 
    3921          50 : bool GDALGeoPackageDataset::
    3922             :     CreateColumnsTableAndColumnConstraintsTablesIfNecessary()
    3923             : {
    3924          50 :     if (!HasDataColumnsTable())
    3925             :     {
    3926             :         // Geopackage < 1.3 had
    3927             :         // CONSTRAINT fk_gdc_tn FOREIGN KEY (table_name) REFERENCES
    3928             :         // gpkg_contents(table_name) instead of the unique constraint.
    3929          10 :         if (OGRERR_NONE !=
    3930          10 :             SQLCommand(
    3931             :                 GetDB(),
    3932             :                 "CREATE TABLE gpkg_data_columns ("
    3933             :                 "table_name TEXT NOT NULL,"
    3934             :                 "column_name TEXT NOT NULL,"
    3935             :                 "name TEXT,"
    3936             :                 "title TEXT,"
    3937             :                 "description TEXT,"
    3938             :                 "mime_type TEXT,"
    3939             :                 "constraint_name TEXT,"
    3940             :                 "CONSTRAINT pk_gdc PRIMARY KEY (table_name, column_name),"
    3941             :                 "CONSTRAINT gdc_tn UNIQUE (table_name, name));"))
    3942             :         {
    3943           0 :             return false;
    3944             :         }
    3945             :     }
    3946          50 :     if (!HasDataColumnConstraintsTable())
    3947             :     {
    3948          22 :         const char *min_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3949          11 :                                            ? "min_is_inclusive"
    3950             :                                            : "minIsInclusive";
    3951          22 :         const char *max_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3952          11 :                                            ? "max_is_inclusive"
    3953             :                                            : "maxIsInclusive";
    3954             : 
    3955             :         const std::string osSQL(
    3956             :             CPLSPrintf("CREATE TABLE gpkg_data_column_constraints ("
    3957             :                        "constraint_name TEXT NOT NULL,"
    3958             :                        "constraint_type TEXT NOT NULL,"
    3959             :                        "value TEXT,"
    3960             :                        "min NUMERIC,"
    3961             :                        "%s BOOLEAN,"
    3962             :                        "max NUMERIC,"
    3963             :                        "%s BOOLEAN,"
    3964             :                        "description TEXT,"
    3965             :                        "CONSTRAINT gdcc_ntv UNIQUE (constraint_name, "
    3966             :                        "constraint_type, value));",
    3967          11 :                        min_is_inclusive, max_is_inclusive));
    3968          11 :         if (OGRERR_NONE != SQLCommand(GetDB(), osSQL.c_str()))
    3969             :         {
    3970           0 :             return false;
    3971             :         }
    3972             :     }
    3973          50 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    3974             :     {
    3975           0 :         return false;
    3976             :     }
    3977          50 :     if (SQLGetInteger(GetDB(),
    3978             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3979             :                       "table_name = 'gpkg_data_columns'",
    3980          50 :                       nullptr) != 1)
    3981             :     {
    3982          11 :         if (OGRERR_NONE !=
    3983          11 :             SQLCommand(
    3984             :                 GetDB(),
    3985             :                 "INSERT INTO gpkg_extensions "
    3986             :                 "(table_name,column_name,extension_name,definition,scope) "
    3987             :                 "VALUES ('gpkg_data_columns', NULL, 'gpkg_schema', "
    3988             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    3989             :                 "'read-write')"))
    3990             :         {
    3991           0 :             return false;
    3992             :         }
    3993             :     }
    3994          50 :     if (SQLGetInteger(GetDB(),
    3995             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3996             :                       "table_name = 'gpkg_data_column_constraints'",
    3997          50 :                       nullptr) != 1)
    3998             :     {
    3999          11 :         if (OGRERR_NONE !=
    4000          11 :             SQLCommand(
    4001             :                 GetDB(),
    4002             :                 "INSERT INTO gpkg_extensions "
    4003             :                 "(table_name,column_name,extension_name,definition,scope) "
    4004             :                 "VALUES ('gpkg_data_column_constraints', NULL, 'gpkg_schema', "
    4005             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    4006             :                 "'read-write')"))
    4007             :         {
    4008           0 :             return false;
    4009             :         }
    4010             :     }
    4011             : 
    4012          50 :     return true;
    4013             : }
    4014             : 
    4015             : /************************************************************************/
    4016             : /*                        HasGpkgextRelationsTable()                    */
    4017             : /************************************************************************/
    4018             : 
    4019        1244 : bool GDALGeoPackageDataset::HasGpkgextRelationsTable() const
    4020             : {
    4021        2488 :     const int nCount = SQLGetInteger(
    4022        1244 :         hDB,
    4023             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkgext_relations'"
    4024             :         "AND type IN ('table', 'view')",
    4025             :         nullptr);
    4026        1244 :     return nCount == 1;
    4027             : }
    4028             : 
    4029             : /************************************************************************/
    4030             : /*                    CreateRelationsTableIfNecessary()                 */
    4031             : /************************************************************************/
    4032             : 
    4033           9 : bool GDALGeoPackageDataset::CreateRelationsTableIfNecessary()
    4034             : {
    4035           9 :     if (HasGpkgextRelationsTable())
    4036             :     {
    4037           5 :         return true;
    4038             :     }
    4039             : 
    4040           4 :     if (OGRERR_NONE !=
    4041           4 :         SQLCommand(GetDB(), "CREATE TABLE gpkgext_relations ("
    4042             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    4043             :                             "base_table_name TEXT NOT NULL,"
    4044             :                             "base_primary_column TEXT NOT NULL DEFAULT 'id',"
    4045             :                             "related_table_name TEXT NOT NULL,"
    4046             :                             "related_primary_column TEXT NOT NULL DEFAULT 'id',"
    4047             :                             "relation_name TEXT NOT NULL,"
    4048             :                             "mapping_table_name TEXT NOT NULL UNIQUE);"))
    4049             :     {
    4050           0 :         return false;
    4051             :     }
    4052             : 
    4053           4 :     return true;
    4054             : }
    4055             : 
    4056             : /************************************************************************/
    4057             : /*                        HasQGISLayerStyles()                          */
    4058             : /************************************************************************/
    4059             : 
    4060          11 : bool GDALGeoPackageDataset::HasQGISLayerStyles() const
    4061             : {
    4062             :     // QGIS layer_styles extension:
    4063             :     // https://github.com/pka/qgpkg/blob/master/qgis_geopackage_extension.md
    4064          11 :     bool bRet = false;
    4065             :     const int nCount =
    4066          11 :         SQLGetInteger(hDB,
    4067             :                       "SELECT 1 FROM sqlite_master WHERE name = 'layer_styles'"
    4068             :                       "AND type = 'table'",
    4069             :                       nullptr);
    4070          11 :     if (nCount == 1)
    4071             :     {
    4072           1 :         sqlite3_stmt *hSQLStmt = nullptr;
    4073           2 :         int rc = sqlite3_prepare_v2(
    4074           1 :             hDB, "SELECT f_table_name, f_geometry_column FROM layer_styles", -1,
    4075             :             &hSQLStmt, nullptr);
    4076           1 :         if (rc == SQLITE_OK)
    4077             :         {
    4078           1 :             bRet = true;
    4079           1 :             sqlite3_finalize(hSQLStmt);
    4080             :         }
    4081             :     }
    4082          11 :     return bRet;
    4083             : }
    4084             : 
    4085             : /************************************************************************/
    4086             : /*                            GetMetadata()                             */
    4087             : /************************************************************************/
    4088             : 
    4089        3883 : char **GDALGeoPackageDataset::GetMetadata(const char *pszDomain)
    4090             : 
    4091             : {
    4092        3883 :     pszDomain = CheckMetadataDomain(pszDomain);
    4093        3883 :     if (pszDomain != nullptr && EQUAL(pszDomain, "SUBDATASETS"))
    4094          66 :         return m_aosSubDatasets.List();
    4095             : 
    4096        3817 :     if (m_bHasReadMetadataFromStorage)
    4097        1757 :         return GDALPamDataset::GetMetadata(pszDomain);
    4098             : 
    4099        2060 :     m_bHasReadMetadataFromStorage = true;
    4100             : 
    4101        2060 :     TryLoadXML();
    4102             : 
    4103        2060 :     if (!HasMetadataTables())
    4104        1550 :         return GDALPamDataset::GetMetadata(pszDomain);
    4105             : 
    4106         510 :     char *pszSQL = nullptr;
    4107         510 :     if (!m_osRasterTable.empty())
    4108             :     {
    4109         170 :         pszSQL = sqlite3_mprintf(
    4110             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4111             :             "mdr.reference_scope FROM gpkg_metadata md "
    4112             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4113             :             "WHERE "
    4114             :             "(mdr.reference_scope = 'geopackage' OR "
    4115             :             "(mdr.reference_scope = 'table' AND lower(mdr.table_name) = "
    4116             :             "lower('%q'))) ORDER BY md.id "
    4117             :             "LIMIT 1000",  // to avoid denial of service
    4118             :             m_osRasterTable.c_str());
    4119             :     }
    4120             :     else
    4121             :     {
    4122         340 :         pszSQL = sqlite3_mprintf(
    4123             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4124             :             "mdr.reference_scope FROM gpkg_metadata md "
    4125             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4126             :             "WHERE "
    4127             :             "mdr.reference_scope = 'geopackage' ORDER BY md.id "
    4128             :             "LIMIT 1000"  // to avoid denial of service
    4129             :         );
    4130             :     }
    4131             : 
    4132        1020 :     auto oResult = SQLQuery(hDB, pszSQL);
    4133         510 :     sqlite3_free(pszSQL);
    4134         510 :     if (!oResult)
    4135             :     {
    4136           0 :         return GDALPamDataset::GetMetadata(pszDomain);
    4137             :     }
    4138             : 
    4139         510 :     char **papszMetadata = CSLDuplicate(GDALPamDataset::GetMetadata());
    4140             : 
    4141             :     /* GDAL metadata */
    4142         700 :     for (int i = 0; i < oResult->RowCount(); i++)
    4143             :     {
    4144         190 :         const char *pszMetadata = oResult->GetValue(0, i);
    4145         190 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4146         190 :         const char *pszMimeType = oResult->GetValue(2, i);
    4147         190 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4148         190 :         if (pszMetadata && pszMDStandardURI && pszMimeType &&
    4149         190 :             pszReferenceScope && EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4150         174 :             EQUAL(pszMimeType, "text/xml"))
    4151             :         {
    4152         174 :             CPLXMLNode *psXMLNode = CPLParseXMLString(pszMetadata);
    4153         174 :             if (psXMLNode)
    4154             :             {
    4155         348 :                 GDALMultiDomainMetadata oLocalMDMD;
    4156         174 :                 oLocalMDMD.XMLInit(psXMLNode, FALSE);
    4157         333 :                 if (!m_osRasterTable.empty() &&
    4158         159 :                     EQUAL(pszReferenceScope, "geopackage"))
    4159             :                 {
    4160           6 :                     oMDMD.SetMetadata(oLocalMDMD.GetMetadata(), "GEOPACKAGE");
    4161             :                 }
    4162             :                 else
    4163             :                 {
    4164             :                     papszMetadata =
    4165         168 :                         CSLMerge(papszMetadata, oLocalMDMD.GetMetadata());
    4166         168 :                     CSLConstList papszDomainList = oLocalMDMD.GetDomainList();
    4167         168 :                     CSLConstList papszIter = papszDomainList;
    4168         447 :                     while (papszIter && *papszIter)
    4169             :                     {
    4170         279 :                         if (EQUAL(*papszIter, "IMAGE_STRUCTURE"))
    4171             :                         {
    4172             :                             CSLConstList papszMD =
    4173         126 :                                 oLocalMDMD.GetMetadata(*papszIter);
    4174             :                             const char *pszBAND_COUNT =
    4175         126 :                                 CSLFetchNameValue(papszMD, "BAND_COUNT");
    4176         126 :                             if (pszBAND_COUNT)
    4177         124 :                                 m_nBandCountFromMetadata = atoi(pszBAND_COUNT);
    4178             : 
    4179             :                             const char *pszCOLOR_TABLE =
    4180         126 :                                 CSLFetchNameValue(papszMD, "COLOR_TABLE");
    4181         126 :                             if (pszCOLOR_TABLE)
    4182             :                             {
    4183             :                                 const CPLStringList aosTokens(
    4184             :                                     CSLTokenizeString2(pszCOLOR_TABLE, "{,",
    4185          26 :                                                        0));
    4186          13 :                                 if ((aosTokens.size() % 4) == 0)
    4187             :                                 {
    4188          13 :                                     const int nColors = aosTokens.size() / 4;
    4189             :                                     m_poCTFromMetadata =
    4190          13 :                                         std::make_unique<GDALColorTable>();
    4191        3341 :                                     for (int iColor = 0; iColor < nColors;
    4192             :                                          ++iColor)
    4193             :                                     {
    4194             :                                         GDALColorEntry sEntry;
    4195        3328 :                                         sEntry.c1 = static_cast<short>(
    4196        3328 :                                             atoi(aosTokens[4 * iColor + 0]));
    4197        3328 :                                         sEntry.c2 = static_cast<short>(
    4198        3328 :                                             atoi(aosTokens[4 * iColor + 1]));
    4199        3328 :                                         sEntry.c3 = static_cast<short>(
    4200        3328 :                                             atoi(aosTokens[4 * iColor + 2]));
    4201        3328 :                                         sEntry.c4 = static_cast<short>(
    4202        3328 :                                             atoi(aosTokens[4 * iColor + 3]));
    4203        3328 :                                         m_poCTFromMetadata->SetColorEntry(
    4204             :                                             iColor, &sEntry);
    4205             :                                     }
    4206             :                                 }
    4207             :                             }
    4208             : 
    4209             :                             const char *pszTILE_FORMAT =
    4210         126 :                                 CSLFetchNameValue(papszMD, "TILE_FORMAT");
    4211         126 :                             if (pszTILE_FORMAT)
    4212             :                             {
    4213           8 :                                 m_osTFFromMetadata = pszTILE_FORMAT;
    4214           8 :                                 oMDMD.SetMetadataItem("TILE_FORMAT",
    4215             :                                                       pszTILE_FORMAT,
    4216             :                                                       "IMAGE_STRUCTURE");
    4217             :                             }
    4218             : 
    4219             :                             const char *pszNodataValue =
    4220         126 :                                 CSLFetchNameValue(papszMD, "NODATA_VALUE");
    4221         126 :                             if (pszNodataValue)
    4222             :                             {
    4223           2 :                                 m_osNodataValueFromMetadata = pszNodataValue;
    4224             :                             }
    4225             :                         }
    4226             : 
    4227         153 :                         else if (!EQUAL(*papszIter, "") &&
    4228          16 :                                  !STARTS_WITH(*papszIter, "BAND_"))
    4229             :                         {
    4230          12 :                             oMDMD.SetMetadata(
    4231           6 :                                 oLocalMDMD.GetMetadata(*papszIter), *papszIter);
    4232             :                         }
    4233         279 :                         papszIter++;
    4234             :                     }
    4235             :                 }
    4236         174 :                 CPLDestroyXMLNode(psXMLNode);
    4237             :             }
    4238             :         }
    4239             :     }
    4240             : 
    4241         510 :     GDALPamDataset::SetMetadata(papszMetadata);
    4242         510 :     CSLDestroy(papszMetadata);
    4243         510 :     papszMetadata = nullptr;
    4244             : 
    4245             :     /* Add non-GDAL metadata now */
    4246         510 :     int nNonGDALMDILocal = 1;
    4247         510 :     int nNonGDALMDIGeopackage = 1;
    4248         700 :     for (int i = 0; i < oResult->RowCount(); i++)
    4249             :     {
    4250         190 :         const char *pszMetadata = oResult->GetValue(0, i);
    4251         190 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4252         190 :         const char *pszMimeType = oResult->GetValue(2, i);
    4253         190 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4254         190 :         if (pszMetadata == nullptr || pszMDStandardURI == nullptr ||
    4255         190 :             pszMimeType == nullptr || pszReferenceScope == nullptr)
    4256             :         {
    4257             :             // should not happen as there are NOT NULL constraints
    4258             :             // But a database could lack such NOT NULL constraints or have
    4259             :             // large values that would cause a memory allocation failure.
    4260           0 :             continue;
    4261             :         }
    4262         190 :         int bIsGPKGScope = EQUAL(pszReferenceScope, "geopackage");
    4263         190 :         if (EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4264         174 :             EQUAL(pszMimeType, "text/xml"))
    4265         174 :             continue;
    4266             : 
    4267          16 :         if (!m_osRasterTable.empty() && bIsGPKGScope)
    4268             :         {
    4269           8 :             oMDMD.SetMetadataItem(
    4270             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDIGeopackage),
    4271             :                 pszMetadata, "GEOPACKAGE");
    4272           8 :             nNonGDALMDIGeopackage++;
    4273             :         }
    4274             :         /*else if( strcmp( pszMDStandardURI, "http://www.isotc211.org/2005/gmd"
    4275             :         ) == 0 && strcmp( pszMimeType, "text/xml" ) == 0 )
    4276             :         {
    4277             :             char* apszMD[2];
    4278             :             apszMD[0] = (char*)pszMetadata;
    4279             :             apszMD[1] = NULL;
    4280             :             oMDMD.SetMetadata(apszMD, "xml:MD_Metadata");
    4281             :         }*/
    4282             :         else
    4283             :         {
    4284           8 :             oMDMD.SetMetadataItem(
    4285             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDILocal),
    4286             :                 pszMetadata);
    4287           8 :             nNonGDALMDILocal++;
    4288             :         }
    4289             :     }
    4290             : 
    4291         510 :     return GDALPamDataset::GetMetadata(pszDomain);
    4292             : }
    4293             : 
    4294             : /************************************************************************/
    4295             : /*                            WriteMetadata()                           */
    4296             : /************************************************************************/
    4297             : 
    4298         724 : void GDALGeoPackageDataset::WriteMetadata(
    4299             :     CPLXMLNode *psXMLNode, /* will be destroyed by the method */
    4300             :     const char *pszTableName)
    4301             : {
    4302         724 :     const bool bIsEmpty = (psXMLNode == nullptr);
    4303         724 :     if (!HasMetadataTables())
    4304             :     {
    4305         524 :         if (bIsEmpty || !CreateMetadataTables())
    4306             :         {
    4307         239 :             CPLDestroyXMLNode(psXMLNode);
    4308         239 :             return;
    4309             :         }
    4310             :     }
    4311             : 
    4312         485 :     char *pszXML = nullptr;
    4313         485 :     if (!bIsEmpty)
    4314             :     {
    4315             :         CPLXMLNode *psMasterXMLNode =
    4316         332 :             CPLCreateXMLNode(nullptr, CXT_Element, "GDALMultiDomainMetadata");
    4317         332 :         psMasterXMLNode->psChild = psXMLNode;
    4318         332 :         pszXML = CPLSerializeXMLTree(psMasterXMLNode);
    4319         332 :         CPLDestroyXMLNode(psMasterXMLNode);
    4320             :     }
    4321             :     // cppcheck-suppress uselessAssignmentPtrArg
    4322         485 :     psXMLNode = nullptr;
    4323             : 
    4324         485 :     char *pszSQL = nullptr;
    4325         485 :     if (pszTableName && pszTableName[0] != '\0')
    4326             :     {
    4327         340 :         pszSQL = sqlite3_mprintf(
    4328             :             "SELECT md.id FROM gpkg_metadata md "
    4329             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4330             :             "WHERE md.md_scope = 'dataset' AND "
    4331             :             "md.md_standard_uri='http://gdal.org' "
    4332             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = 'table' AND "
    4333             :             "lower(mdr.table_name) = lower('%q')",
    4334             :             pszTableName);
    4335             :     }
    4336             :     else
    4337             :     {
    4338         145 :         pszSQL = sqlite3_mprintf(
    4339             :             "SELECT md.id FROM gpkg_metadata md "
    4340             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4341             :             "WHERE md.md_scope = 'dataset' AND "
    4342             :             "md.md_standard_uri='http://gdal.org' "
    4343             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = "
    4344             :             "'geopackage'");
    4345             :     }
    4346             :     OGRErr err;
    4347         485 :     int mdId = SQLGetInteger(hDB, pszSQL, &err);
    4348         485 :     if (err != OGRERR_NONE)
    4349         453 :         mdId = -1;
    4350         485 :     sqlite3_free(pszSQL);
    4351             : 
    4352         485 :     if (bIsEmpty)
    4353             :     {
    4354         153 :         if (mdId >= 0)
    4355             :         {
    4356           6 :             SQLCommand(
    4357             :                 hDB,
    4358             :                 CPLSPrintf(
    4359             :                     "DELETE FROM gpkg_metadata_reference WHERE md_file_id = %d",
    4360             :                     mdId));
    4361           6 :             SQLCommand(
    4362             :                 hDB,
    4363             :                 CPLSPrintf("DELETE FROM gpkg_metadata WHERE id = %d", mdId));
    4364             :         }
    4365             :     }
    4366             :     else
    4367             :     {
    4368         332 :         if (mdId >= 0)
    4369             :         {
    4370          26 :             pszSQL = sqlite3_mprintf(
    4371             :                 "UPDATE gpkg_metadata SET metadata = '%q' WHERE id = %d",
    4372             :                 pszXML, mdId);
    4373             :         }
    4374             :         else
    4375             :         {
    4376             :             pszSQL =
    4377         306 :                 sqlite3_mprintf("INSERT INTO gpkg_metadata (md_scope, "
    4378             :                                 "md_standard_uri, mime_type, metadata) VALUES "
    4379             :                                 "('dataset','http://gdal.org','text/xml','%q')",
    4380             :                                 pszXML);
    4381             :         }
    4382         332 :         SQLCommand(hDB, pszSQL);
    4383         332 :         sqlite3_free(pszSQL);
    4384             : 
    4385         332 :         CPLFree(pszXML);
    4386             : 
    4387         332 :         if (mdId < 0)
    4388             :         {
    4389         306 :             const sqlite_int64 nFID = sqlite3_last_insert_rowid(hDB);
    4390         306 :             if (pszTableName != nullptr && pszTableName[0] != '\0')
    4391             :             {
    4392         294 :                 pszSQL = sqlite3_mprintf(
    4393             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4394             :                     "table_name, timestamp, md_file_id) VALUES "
    4395             :                     "('table', '%q', %s, %d)",
    4396         588 :                     pszTableName, GetCurrentDateEscapedSQL().c_str(),
    4397             :                     static_cast<int>(nFID));
    4398             :             }
    4399             :             else
    4400             :             {
    4401          12 :                 pszSQL = sqlite3_mprintf(
    4402             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4403             :                     "timestamp, md_file_id) VALUES "
    4404             :                     "('geopackage', %s, %d)",
    4405          24 :                     GetCurrentDateEscapedSQL().c_str(), static_cast<int>(nFID));
    4406             :             }
    4407             :         }
    4408             :         else
    4409             :         {
    4410          26 :             pszSQL = sqlite3_mprintf("UPDATE gpkg_metadata_reference SET "
    4411             :                                      "timestamp = %s WHERE md_file_id = %d",
    4412          52 :                                      GetCurrentDateEscapedSQL().c_str(), mdId);
    4413             :         }
    4414         332 :         SQLCommand(hDB, pszSQL);
    4415         332 :         sqlite3_free(pszSQL);
    4416             :     }
    4417             : }
    4418             : 
    4419             : /************************************************************************/
    4420             : /*                        CreateMetadataTables()                        */
    4421             : /************************************************************************/
    4422             : 
    4423         304 : bool GDALGeoPackageDataset::CreateMetadataTables()
    4424             : {
    4425             :     const bool bCreateTriggers =
    4426         304 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "NO"));
    4427             : 
    4428             :     /* From C.10. gpkg_metadata Table 35. gpkg_metadata Table Definition SQL  */
    4429             :     CPLString osSQL = "CREATE TABLE gpkg_metadata ("
    4430             :                       "id INTEGER CONSTRAINT m_pk PRIMARY KEY ASC NOT NULL,"
    4431             :                       "md_scope TEXT NOT NULL DEFAULT 'dataset',"
    4432             :                       "md_standard_uri TEXT NOT NULL,"
    4433             :                       "mime_type TEXT NOT NULL DEFAULT 'text/xml',"
    4434             :                       "metadata TEXT NOT NULL DEFAULT ''"
    4435         608 :                       ")";
    4436             : 
    4437             :     /* From D.2. metadata Table 40. metadata Trigger Definition SQL  */
    4438         304 :     const char *pszMetadataTriggers =
    4439             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_insert' "
    4440             :         "BEFORE INSERT ON 'gpkg_metadata' "
    4441             :         "FOR EACH ROW BEGIN "
    4442             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata violates "
    4443             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4444             :         "collectionSession | series | dataset | featureType | feature | "
    4445             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4446             :         "taxonomy software | service | collectionHardware | "
    4447             :         "nonGeographicDataset | dimensionGroup') "
    4448             :         "WHERE NOT(NEW.md_scope IN "
    4449             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4450             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4451             :         "'catalogue','schema','taxonomy','software','service', "
    4452             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4453             :         "END; "
    4454             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_update' "
    4455             :         "BEFORE UPDATE OF 'md_scope' ON 'gpkg_metadata' "
    4456             :         "FOR EACH ROW BEGIN "
    4457             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata violates "
    4458             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4459             :         "collectionSession | series | dataset | featureType | feature | "
    4460             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4461             :         "taxonomy software | service | collectionHardware | "
    4462             :         "nonGeographicDataset | dimensionGroup') "
    4463             :         "WHERE NOT(NEW.md_scope IN "
    4464             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4465             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4466             :         "'catalogue','schema','taxonomy','software','service', "
    4467             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4468             :         "END";
    4469         304 :     if (bCreateTriggers)
    4470             :     {
    4471           0 :         osSQL += ";";
    4472           0 :         osSQL += pszMetadataTriggers;
    4473             :     }
    4474             : 
    4475             :     /* From C.11. gpkg_metadata_reference Table 36. gpkg_metadata_reference
    4476             :      * Table Definition SQL */
    4477             :     osSQL += ";"
    4478             :              "CREATE TABLE gpkg_metadata_reference ("
    4479             :              "reference_scope TEXT NOT NULL,"
    4480             :              "table_name TEXT,"
    4481             :              "column_name TEXT,"
    4482             :              "row_id_value INTEGER,"
    4483             :              "timestamp DATETIME NOT NULL DEFAULT "
    4484             :              "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    4485             :              "md_file_id INTEGER NOT NULL,"
    4486             :              "md_parent_id INTEGER,"
    4487             :              "CONSTRAINT crmr_mfi_fk FOREIGN KEY (md_file_id) REFERENCES "
    4488             :              "gpkg_metadata(id),"
    4489             :              "CONSTRAINT crmr_mpi_fk FOREIGN KEY (md_parent_id) REFERENCES "
    4490             :              "gpkg_metadata(id)"
    4491         304 :              ")";
    4492             : 
    4493             :     /* From D.3. metadata_reference Table 41. gpkg_metadata_reference Trigger
    4494             :      * Definition SQL   */
    4495         304 :     const char *pszMetadataReferenceTriggers =
    4496             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_insert' "
    4497             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4498             :         "FOR EACH ROW BEGIN "
    4499             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4500             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4501             :         "table\", \"column\", \"row\", \"row/col\"') "
    4502             :         "WHERE NOT NEW.reference_scope IN "
    4503             :         "('geopackage','table','column','row','row/col'); "
    4504             :         "END; "
    4505             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_update' "
    4506             :         "BEFORE UPDATE OF 'reference_scope' ON 'gpkg_metadata_reference' "
    4507             :         "FOR EACH ROW BEGIN "
    4508             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4509             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4510             :         "\"table\", \"column\", \"row\", \"row/col\"') "
    4511             :         "WHERE NOT NEW.reference_scope IN "
    4512             :         "('geopackage','table','column','row','row/col'); "
    4513             :         "END; "
    4514             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_insert' "
    4515             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4516             :         "FOR EACH ROW BEGIN "
    4517             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4518             :         "violates constraint: column name must be NULL when reference_scope "
    4519             :         "is \"geopackage\", \"table\" or \"row\"') "
    4520             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4521             :         "AND NEW.column_name IS NOT NULL); "
    4522             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4523             :         "violates constraint: column name must be defined for the specified "
    4524             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4525             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4526             :         "AND NOT NEW.table_name IN ( "
    4527             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4528             :         "AND name = NEW.table_name "
    4529             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4530             :         "END; "
    4531             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_update' "
    4532             :         "BEFORE UPDATE OF column_name ON 'gpkg_metadata_reference' "
    4533             :         "FOR EACH ROW BEGIN "
    4534             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4535             :         "violates constraint: column name must be NULL when reference_scope "
    4536             :         "is \"geopackage\", \"table\" or \"row\"') "
    4537             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4538             :         "AND NEW.column_name IS NOT NULL); "
    4539             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4540             :         "violates constraint: column name must be defined for the specified "
    4541             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4542             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4543             :         "AND NOT NEW.table_name IN ( "
    4544             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4545             :         "AND name = NEW.table_name "
    4546             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4547             :         "END; "
    4548             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_insert' "
    4549             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4550             :         "FOR EACH ROW BEGIN "
    4551             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4552             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4553             :         "is \"geopackage\", \"table\" or \"column\"') "
    4554             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4555             :         "AND NEW.row_id_value IS NOT NULL; "
    4556             :         "END; "
    4557             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_update' "
    4558             :         "BEFORE UPDATE OF 'row_id_value' ON 'gpkg_metadata_reference' "
    4559             :         "FOR EACH ROW BEGIN "
    4560             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4561             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4562             :         "is \"geopackage\", \"table\" or \"column\"') "
    4563             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4564             :         "AND NEW.row_id_value IS NOT NULL; "
    4565             :         "END; "
    4566             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_insert' "
    4567             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4568             :         "FOR EACH ROW BEGIN "
    4569             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4570             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4571             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4572             :         "WHERE NOT (NEW.timestamp GLOB "
    4573             :         "'[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-"
    4574             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4575             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4576             :         "END; "
    4577             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_update' "
    4578             :         "BEFORE UPDATE OF 'timestamp' ON 'gpkg_metadata_reference' "
    4579             :         "FOR EACH ROW BEGIN "
    4580             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4581             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4582             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4583             :         "WHERE NOT (NEW.timestamp GLOB "
    4584             :         "'[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-"
    4585             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4586             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4587             :         "END";
    4588         304 :     if (bCreateTriggers)
    4589             :     {
    4590           0 :         osSQL += ";";
    4591           0 :         osSQL += pszMetadataReferenceTriggers;
    4592             :     }
    4593             : 
    4594         304 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    4595           2 :         return false;
    4596             : 
    4597         302 :     osSQL += ";";
    4598             :     osSQL += "INSERT INTO gpkg_extensions "
    4599             :              "(table_name, column_name, extension_name, definition, scope) "
    4600             :              "VALUES "
    4601             :              "('gpkg_metadata', NULL, 'gpkg_metadata', "
    4602             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4603         302 :              "'read-write')";
    4604             : 
    4605         302 :     osSQL += ";";
    4606             :     osSQL += "INSERT INTO gpkg_extensions "
    4607             :              "(table_name, column_name, extension_name, definition, scope) "
    4608             :              "VALUES "
    4609             :              "('gpkg_metadata_reference', NULL, 'gpkg_metadata', "
    4610             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4611         302 :              "'read-write')";
    4612             : 
    4613         302 :     const bool bOK = SQLCommand(hDB, osSQL) == OGRERR_NONE;
    4614         302 :     m_nHasMetadataTables = bOK;
    4615         302 :     return bOK;
    4616             : }
    4617             : 
    4618             : /************************************************************************/
    4619             : /*                            FlushMetadata()                           */
    4620             : /************************************************************************/
    4621             : 
    4622        8774 : void GDALGeoPackageDataset::FlushMetadata()
    4623             : {
    4624        8774 :     if (!m_bMetadataDirty || m_poParentDS != nullptr ||
    4625         363 :         m_nCreateMetadataTables == FALSE)
    4626        8417 :         return;
    4627         357 :     m_bMetadataDirty = false;
    4628             : 
    4629         357 :     if (eAccess == GA_ReadOnly)
    4630             :     {
    4631           3 :         return;
    4632             :     }
    4633             : 
    4634         354 :     bool bCanWriteAreaOrPoint =
    4635         706 :         !m_bGridCellEncodingAsCO &&
    4636         352 :         (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT);
    4637         354 :     if (!m_osRasterTable.empty())
    4638             :     {
    4639             :         const char *pszIdentifier =
    4640         144 :             GDALGeoPackageDataset::GetMetadataItem("IDENTIFIER");
    4641             :         const char *pszDescription =
    4642         144 :             GDALGeoPackageDataset::GetMetadataItem("DESCRIPTION");
    4643         173 :         if (!m_bIdentifierAsCO && pszIdentifier != nullptr &&
    4644          29 :             pszIdentifier != m_osIdentifier)
    4645             :         {
    4646          14 :             m_osIdentifier = pszIdentifier;
    4647             :             char *pszSQL =
    4648          14 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4649             :                                 "WHERE lower(table_name) = lower('%q')",
    4650             :                                 pszIdentifier, m_osRasterTable.c_str());
    4651          14 :             SQLCommand(hDB, pszSQL);
    4652          14 :             sqlite3_free(pszSQL);
    4653             :         }
    4654         151 :         if (!m_bDescriptionAsCO && pszDescription != nullptr &&
    4655           7 :             pszDescription != m_osDescription)
    4656             :         {
    4657           7 :             m_osDescription = pszDescription;
    4658             :             char *pszSQL =
    4659           7 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4660             :                                 "WHERE lower(table_name) = lower('%q')",
    4661             :                                 pszDescription, m_osRasterTable.c_str());
    4662           7 :             SQLCommand(hDB, pszSQL);
    4663           7 :             sqlite3_free(pszSQL);
    4664             :         }
    4665         144 :         if (bCanWriteAreaOrPoint)
    4666             :         {
    4667             :             const char *pszAreaOrPoint =
    4668          28 :                 GDALGeoPackageDataset::GetMetadataItem(GDALMD_AREA_OR_POINT);
    4669          28 :             if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_AREA))
    4670             :             {
    4671          23 :                 bCanWriteAreaOrPoint = false;
    4672          23 :                 char *pszSQL = sqlite3_mprintf(
    4673             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4674             :                     "grid_cell_encoding = 'grid-value-is-area' WHERE "
    4675             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4676             :                     m_osRasterTable.c_str());
    4677          23 :                 SQLCommand(hDB, pszSQL);
    4678          23 :                 sqlite3_free(pszSQL);
    4679             :             }
    4680           5 :             else if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_POINT))
    4681             :             {
    4682           1 :                 bCanWriteAreaOrPoint = false;
    4683           1 :                 char *pszSQL = sqlite3_mprintf(
    4684             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4685             :                     "grid_cell_encoding = 'grid-value-is-center' WHERE "
    4686             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4687             :                     m_osRasterTable.c_str());
    4688           1 :                 SQLCommand(hDB, pszSQL);
    4689           1 :                 sqlite3_free(pszSQL);
    4690             :             }
    4691             :         }
    4692             :     }
    4693             : 
    4694         354 :     char **papszMDDup = nullptr;
    4695         559 :     for (char **papszIter = GDALGeoPackageDataset::GetMetadata();
    4696         559 :          papszIter && *papszIter; ++papszIter)
    4697             :     {
    4698         205 :         if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4699          29 :             continue;
    4700         176 :         if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4701           8 :             continue;
    4702         168 :         if (STARTS_WITH_CI(*papszIter, "ZOOM_LEVEL="))
    4703          14 :             continue;
    4704         154 :         if (STARTS_WITH_CI(*papszIter, "GPKG_METADATA_ITEM_"))
    4705           4 :             continue;
    4706         150 :         if ((m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT) &&
    4707          29 :             !bCanWriteAreaOrPoint &&
    4708          26 :             STARTS_WITH_CI(*papszIter, GDALMD_AREA_OR_POINT))
    4709             :         {
    4710          26 :             continue;
    4711             :         }
    4712         124 :         papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4713             :     }
    4714             : 
    4715         354 :     CPLXMLNode *psXMLNode = nullptr;
    4716             :     {
    4717         354 :         GDALMultiDomainMetadata oLocalMDMD;
    4718         354 :         CSLConstList papszDomainList = oMDMD.GetDomainList();
    4719         354 :         CSLConstList papszIter = papszDomainList;
    4720         354 :         oLocalMDMD.SetMetadata(papszMDDup);
    4721         683 :         while (papszIter && *papszIter)
    4722             :         {
    4723         329 :             if (!EQUAL(*papszIter, "") &&
    4724         159 :                 !EQUAL(*papszIter, "IMAGE_STRUCTURE") &&
    4725          15 :                 !EQUAL(*papszIter, "GEOPACKAGE"))
    4726             :             {
    4727           8 :                 oLocalMDMD.SetMetadata(oMDMD.GetMetadata(*papszIter),
    4728             :                                        *papszIter);
    4729             :             }
    4730         329 :             papszIter++;
    4731             :         }
    4732         354 :         if (m_nBandCountFromMetadata > 0)
    4733             :         {
    4734          74 :             oLocalMDMD.SetMetadataItem(
    4735             :                 "BAND_COUNT", CPLSPrintf("%d", m_nBandCountFromMetadata),
    4736             :                 "IMAGE_STRUCTURE");
    4737          74 :             if (nBands == 1)
    4738             :             {
    4739          50 :                 const auto poCT = GetRasterBand(1)->GetColorTable();
    4740          50 :                 if (poCT)
    4741             :                 {
    4742          16 :                     std::string osVal("{");
    4743           8 :                     const int nColorCount = poCT->GetColorEntryCount();
    4744        2056 :                     for (int i = 0; i < nColorCount; ++i)
    4745             :                     {
    4746        2048 :                         if (i > 0)
    4747        2040 :                             osVal += ',';
    4748        2048 :                         const GDALColorEntry *psEntry = poCT->GetColorEntry(i);
    4749             :                         osVal +=
    4750        2048 :                             CPLSPrintf("{%d,%d,%d,%d}", psEntry->c1,
    4751        2048 :                                        psEntry->c2, psEntry->c3, psEntry->c4);
    4752             :                     }
    4753           8 :                     osVal += '}';
    4754           8 :                     oLocalMDMD.SetMetadataItem("COLOR_TABLE", osVal.c_str(),
    4755             :                                                "IMAGE_STRUCTURE");
    4756             :                 }
    4757             :             }
    4758          74 :             if (nBands == 1)
    4759             :             {
    4760          50 :                 const char *pszTILE_FORMAT = nullptr;
    4761          50 :                 switch (m_eTF)
    4762             :                 {
    4763           0 :                     case GPKG_TF_PNG_JPEG:
    4764           0 :                         pszTILE_FORMAT = "JPEG_PNG";
    4765           0 :                         break;
    4766          44 :                     case GPKG_TF_PNG:
    4767          44 :                         break;
    4768           0 :                     case GPKG_TF_PNG8:
    4769           0 :                         pszTILE_FORMAT = "PNG8";
    4770           0 :                         break;
    4771           3 :                     case GPKG_TF_JPEG:
    4772           3 :                         pszTILE_FORMAT = "JPEG";
    4773           3 :                         break;
    4774           3 :                     case GPKG_TF_WEBP:
    4775           3 :                         pszTILE_FORMAT = "WEBP";
    4776           3 :                         break;
    4777           0 :                     case GPKG_TF_PNG_16BIT:
    4778           0 :                         break;
    4779           0 :                     case GPKG_TF_TIFF_32BIT_FLOAT:
    4780           0 :                         break;
    4781             :                 }
    4782          50 :                 if (pszTILE_FORMAT)
    4783           6 :                     oLocalMDMD.SetMetadataItem("TILE_FORMAT", pszTILE_FORMAT,
    4784             :                                                "IMAGE_STRUCTURE");
    4785             :             }
    4786             :         }
    4787         498 :         if (GetRasterCount() > 0 &&
    4788         144 :             GetRasterBand(1)->GetRasterDataType() == GDT_Byte)
    4789             :         {
    4790         114 :             int bHasNoData = FALSE;
    4791             :             const double dfNoDataValue =
    4792         114 :                 GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    4793         114 :             if (bHasNoData)
    4794             :             {
    4795           3 :                 oLocalMDMD.SetMetadataItem("NODATA_VALUE",
    4796             :                                            CPLSPrintf("%.17g", dfNoDataValue),
    4797             :                                            "IMAGE_STRUCTURE");
    4798             :             }
    4799             :         }
    4800         603 :         for (int i = 1; i <= GetRasterCount(); ++i)
    4801             :         {
    4802             :             auto poBand =
    4803         249 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    4804         249 :             poBand->AddImplicitStatistics(false);
    4805         249 :             char **papszMD = GetRasterBand(i)->GetMetadata();
    4806         249 :             poBand->AddImplicitStatistics(true);
    4807         249 :             if (papszMD)
    4808             :             {
    4809          14 :                 oLocalMDMD.SetMetadata(papszMD, CPLSPrintf("BAND_%d", i));
    4810             :             }
    4811             :         }
    4812         354 :         psXMLNode = oLocalMDMD.Serialize();
    4813             :     }
    4814             : 
    4815         354 :     CSLDestroy(papszMDDup);
    4816         354 :     papszMDDup = nullptr;
    4817             : 
    4818         354 :     WriteMetadata(psXMLNode, m_osRasterTable.c_str());
    4819             : 
    4820         354 :     if (!m_osRasterTable.empty())
    4821             :     {
    4822             :         char **papszGeopackageMD =
    4823         144 :             GDALGeoPackageDataset::GetMetadata("GEOPACKAGE");
    4824             : 
    4825         144 :         papszMDDup = nullptr;
    4826         153 :         for (char **papszIter = papszGeopackageMD; papszIter && *papszIter;
    4827             :              ++papszIter)
    4828             :         {
    4829           9 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4830             :         }
    4831             : 
    4832         288 :         GDALMultiDomainMetadata oLocalMDMD;
    4833         144 :         oLocalMDMD.SetMetadata(papszMDDup);
    4834         144 :         CSLDestroy(papszMDDup);
    4835         144 :         papszMDDup = nullptr;
    4836         144 :         psXMLNode = oLocalMDMD.Serialize();
    4837             : 
    4838         144 :         WriteMetadata(psXMLNode, nullptr);
    4839             :     }
    4840             : 
    4841         580 :     for (auto &poLayer : m_apoLayers)
    4842             :     {
    4843         226 :         const char *pszIdentifier = poLayer->GetMetadataItem("IDENTIFIER");
    4844         226 :         const char *pszDescription = poLayer->GetMetadataItem("DESCRIPTION");
    4845         226 :         if (pszIdentifier != nullptr)
    4846             :         {
    4847             :             char *pszSQL =
    4848           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4849             :                                 "WHERE lower(table_name) = lower('%q')",
    4850             :                                 pszIdentifier, poLayer->GetName());
    4851           3 :             SQLCommand(hDB, pszSQL);
    4852           3 :             sqlite3_free(pszSQL);
    4853             :         }
    4854         226 :         if (pszDescription != nullptr)
    4855             :         {
    4856             :             char *pszSQL =
    4857           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4858             :                                 "WHERE lower(table_name) = lower('%q')",
    4859             :                                 pszDescription, poLayer->GetName());
    4860           3 :             SQLCommand(hDB, pszSQL);
    4861           3 :             sqlite3_free(pszSQL);
    4862             :         }
    4863             : 
    4864         226 :         papszMDDup = nullptr;
    4865         616 :         for (char **papszIter = poLayer->GetMetadata(); papszIter && *papszIter;
    4866             :              ++papszIter)
    4867             :         {
    4868         390 :             if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4869           3 :                 continue;
    4870         387 :             if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4871           3 :                 continue;
    4872         384 :             if (STARTS_WITH_CI(*papszIter, "OLMD_FID64="))
    4873           0 :                 continue;
    4874         384 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4875             :         }
    4876             : 
    4877             :         {
    4878         226 :             GDALMultiDomainMetadata oLocalMDMD;
    4879         226 :             char **papszDomainList = poLayer->GetMetadataDomainList();
    4880         226 :             char **papszIter = papszDomainList;
    4881         226 :             oLocalMDMD.SetMetadata(papszMDDup);
    4882         501 :             while (papszIter && *papszIter)
    4883             :             {
    4884         275 :                 if (!EQUAL(*papszIter, ""))
    4885          62 :                     oLocalMDMD.SetMetadata(poLayer->GetMetadata(*papszIter),
    4886             :                                            *papszIter);
    4887         275 :                 papszIter++;
    4888             :             }
    4889         226 :             CSLDestroy(papszDomainList);
    4890         226 :             psXMLNode = oLocalMDMD.Serialize();
    4891             :         }
    4892             : 
    4893         226 :         CSLDestroy(papszMDDup);
    4894         226 :         papszMDDup = nullptr;
    4895             : 
    4896         226 :         WriteMetadata(psXMLNode, poLayer->GetName());
    4897             :     }
    4898             : }
    4899             : 
    4900             : /************************************************************************/
    4901             : /*                          GetMetadataItem()                           */
    4902             : /************************************************************************/
    4903             : 
    4904        1879 : const char *GDALGeoPackageDataset::GetMetadataItem(const char *pszName,
    4905             :                                                    const char *pszDomain)
    4906             : {
    4907        1879 :     pszDomain = CheckMetadataDomain(pszDomain);
    4908        1879 :     return CSLFetchNameValue(GetMetadata(pszDomain), pszName);
    4909             : }
    4910             : 
    4911             : /************************************************************************/
    4912             : /*                            SetMetadata()                             */
    4913             : /************************************************************************/
    4914             : 
    4915         133 : CPLErr GDALGeoPackageDataset::SetMetadata(char **papszMetadata,
    4916             :                                           const char *pszDomain)
    4917             : {
    4918         133 :     pszDomain = CheckMetadataDomain(pszDomain);
    4919         133 :     m_bMetadataDirty = true;
    4920         133 :     GetMetadata(); /* force loading from storage if needed */
    4921         133 :     return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
    4922             : }
    4923             : 
    4924             : /************************************************************************/
    4925             : /*                          SetMetadataItem()                           */
    4926             : /************************************************************************/
    4927             : 
    4928          21 : CPLErr GDALGeoPackageDataset::SetMetadataItem(const char *pszName,
    4929             :                                               const char *pszValue,
    4930             :                                               const char *pszDomain)
    4931             : {
    4932          21 :     pszDomain = CheckMetadataDomain(pszDomain);
    4933          21 :     m_bMetadataDirty = true;
    4934          21 :     GetMetadata(); /* force loading from storage if needed */
    4935          21 :     return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    4936             : }
    4937             : 
    4938             : /************************************************************************/
    4939             : /*                                Create()                              */
    4940             : /************************************************************************/
    4941             : 
    4942         977 : int GDALGeoPackageDataset::Create(const char *pszFilename, int nXSize,
    4943             :                                   int nYSize, int nBandsIn, GDALDataType eDT,
    4944             :                                   char **papszOptions)
    4945             : {
    4946        1954 :     CPLString osCommand;
    4947             : 
    4948             :     /* First, ensure there isn't any such file yet. */
    4949             :     VSIStatBufL sStatBuf;
    4950             : 
    4951         977 :     if (nBandsIn != 0)
    4952             :     {
    4953         226 :         if (eDT == GDT_Byte)
    4954             :         {
    4955         156 :             if (nBandsIn != 1 && nBandsIn != 2 && nBandsIn != 3 &&
    4956             :                 nBandsIn != 4)
    4957             :             {
    4958           1 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4959             :                          "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), "
    4960             :                          "3 (RGB) or 4 (RGBA) band dataset supported for "
    4961             :                          "Byte datatype");
    4962           1 :                 return FALSE;
    4963             :             }
    4964             :         }
    4965          70 :         else if (eDT == GDT_Int16 || eDT == GDT_UInt16 || eDT == GDT_Float32)
    4966             :         {
    4967          43 :             if (nBandsIn != 1)
    4968             :             {
    4969           3 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4970             :                          "Only single band dataset supported for non Byte "
    4971             :                          "datatype");
    4972           3 :                 return FALSE;
    4973             :             }
    4974             :         }
    4975             :         else
    4976             :         {
    4977          27 :             CPLError(CE_Failure, CPLE_NotSupported,
    4978             :                      "Only Byte, Int16, UInt16 or Float32 supported");
    4979          27 :             return FALSE;
    4980             :         }
    4981             :     }
    4982             : 
    4983         946 :     const size_t nFilenameLen = strlen(pszFilename);
    4984         946 :     const bool bGpkgZip =
    4985         941 :         (nFilenameLen > strlen(".gpkg.zip") &&
    4986        1887 :          !STARTS_WITH(pszFilename, "/vsizip/") &&
    4987         941 :          EQUAL(pszFilename + nFilenameLen - strlen(".gpkg.zip"), ".gpkg.zip"));
    4988             : 
    4989             :     const bool bUseTempFile =
    4990         947 :         bGpkgZip || (CPLTestBool(CPLGetConfigOption(
    4991           1 :                          "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", "NO")) &&
    4992           1 :                      (VSIHasOptimizedReadMultiRange(pszFilename) != FALSE ||
    4993           1 :                       EQUAL(CPLGetConfigOption(
    4994             :                                 "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", ""),
    4995         946 :                             "FORCED")));
    4996             : 
    4997         946 :     bool bFileExists = false;
    4998         946 :     if (VSIStatL(pszFilename, &sStatBuf) == 0)
    4999             :     {
    5000          10 :         bFileExists = true;
    5001          20 :         if (nBandsIn == 0 || bUseTempFile ||
    5002          10 :             !CPLTestBool(
    5003             :                 CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")))
    5004             :         {
    5005           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5006             :                      "A file system object called '%s' already exists.",
    5007             :                      pszFilename);
    5008             : 
    5009           0 :             return FALSE;
    5010             :         }
    5011             :     }
    5012             : 
    5013         946 :     if (bUseTempFile)
    5014             :     {
    5015           3 :         if (bGpkgZip)
    5016             :         {
    5017           2 :             std::string osFilenameInZip(CPLGetFilename(pszFilename));
    5018           2 :             osFilenameInZip.resize(osFilenameInZip.size() - strlen(".zip"));
    5019             :             m_osFinalFilename =
    5020           2 :                 std::string("/vsizip/{") + pszFilename + "}/" + osFilenameInZip;
    5021             :         }
    5022             :         else
    5023             :         {
    5024           1 :             m_osFinalFilename = pszFilename;
    5025             :         }
    5026           3 :         m_pszFilename = CPLStrdup(
    5027           6 :             CPLGenerateTempFilenameSafe(CPLGetFilename(pszFilename)).c_str());
    5028           3 :         CPLDebug("GPKG", "Creating temporary file %s", m_pszFilename);
    5029             :     }
    5030             :     else
    5031             :     {
    5032         943 :         m_pszFilename = CPLStrdup(pszFilename);
    5033             :     }
    5034         946 :     m_bNew = true;
    5035         946 :     eAccess = GA_Update;
    5036         946 :     m_bDateTimeWithTZ =
    5037         946 :         EQUAL(CSLFetchNameValueDef(papszOptions, "DATETIME_FORMAT", "WITH_TZ"),
    5038             :               "WITH_TZ");
    5039             : 
    5040             :     // for test/debug purposes only. true is the nominal value
    5041         946 :     m_bPNGSupports2Bands =
    5042         946 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_2BANDS", "TRUE"));
    5043         946 :     m_bPNGSupportsCT =
    5044         946 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_CT", "TRUE"));
    5045             : 
    5046         946 :     if (!OpenOrCreateDB(bFileExists
    5047             :                             ? SQLITE_OPEN_READWRITE
    5048             :                             : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE))
    5049           7 :         return FALSE;
    5050             : 
    5051             :     /* Default to synchronous=off for performance for new file */
    5052        1868 :     if (!bFileExists &&
    5053         929 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5054             :     {
    5055         430 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5056             :     }
    5057             : 
    5058             :     /* OGR UTF-8 support. If we set the UTF-8 Pragma early on, it */
    5059             :     /* will be written into the main file and supported henceforth */
    5060         939 :     SQLCommand(hDB, "PRAGMA encoding = \"UTF-8\"");
    5061             : 
    5062         939 :     if (bFileExists)
    5063             :     {
    5064          10 :         VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
    5065          10 :         if (fp)
    5066             :         {
    5067             :             GByte abyHeader[100];
    5068          10 :             VSIFReadL(abyHeader, 1, sizeof(abyHeader), fp);
    5069          10 :             VSIFCloseL(fp);
    5070             : 
    5071          10 :             memcpy(&m_nApplicationId, abyHeader + knApplicationIdPos, 4);
    5072          10 :             m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    5073          10 :             memcpy(&m_nUserVersion, abyHeader + knUserVersionPos, 4);
    5074          10 :             m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    5075             : 
    5076          10 :             if (m_nApplicationId == GP10_APPLICATION_ID)
    5077             :             {
    5078           0 :                 CPLDebug("GPKG", "GeoPackage v1.0");
    5079             :             }
    5080          10 :             else if (m_nApplicationId == GP11_APPLICATION_ID)
    5081             :             {
    5082           0 :                 CPLDebug("GPKG", "GeoPackage v1.1");
    5083             :             }
    5084          10 :             else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    5085          10 :                      m_nUserVersion >= GPKG_1_2_VERSION)
    5086             :             {
    5087          10 :                 CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    5088          10 :                          (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    5089             :             }
    5090             :         }
    5091             : 
    5092          10 :         DetectSpatialRefSysColumns();
    5093             :     }
    5094             : 
    5095         939 :     const char *pszVersion = CSLFetchNameValue(papszOptions, "VERSION");
    5096         939 :     if (pszVersion && !EQUAL(pszVersion, "AUTO"))
    5097             :     {
    5098          40 :         if (EQUAL(pszVersion, "1.0"))
    5099             :         {
    5100           2 :             m_nApplicationId = GP10_APPLICATION_ID;
    5101           2 :             m_nUserVersion = 0;
    5102             :         }
    5103          38 :         else if (EQUAL(pszVersion, "1.1"))
    5104             :         {
    5105           1 :             m_nApplicationId = GP11_APPLICATION_ID;
    5106           1 :             m_nUserVersion = 0;
    5107             :         }
    5108          37 :         else if (EQUAL(pszVersion, "1.2"))
    5109             :         {
    5110          15 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5111          15 :             m_nUserVersion = GPKG_1_2_VERSION;
    5112             :         }
    5113          22 :         else if (EQUAL(pszVersion, "1.3"))
    5114             :         {
    5115           3 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5116           3 :             m_nUserVersion = GPKG_1_3_VERSION;
    5117             :         }
    5118          19 :         else if (EQUAL(pszVersion, "1.4"))
    5119             :         {
    5120          19 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5121          19 :             m_nUserVersion = GPKG_1_4_VERSION;
    5122             :         }
    5123             :     }
    5124             : 
    5125         939 :     SoftStartTransaction();
    5126             : 
    5127        1878 :     CPLString osSQL;
    5128         939 :     if (!bFileExists)
    5129             :     {
    5130             :         /* Requirement 10: A GeoPackage SHALL include a gpkg_spatial_ref_sys
    5131             :          * table */
    5132             :         /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5133             :         osSQL = "CREATE TABLE gpkg_spatial_ref_sys ("
    5134             :                 "srs_name TEXT NOT NULL,"
    5135             :                 "srs_id INTEGER NOT NULL PRIMARY KEY,"
    5136             :                 "organization TEXT NOT NULL,"
    5137             :                 "organization_coordsys_id INTEGER NOT NULL,"
    5138             :                 "definition  TEXT NOT NULL,"
    5139         929 :                 "description TEXT";
    5140         929 :         if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "CRS_WKT_EXTENSION",
    5141        1110 :                                              "NO")) ||
    5142         181 :             (nBandsIn != 0 && eDT != GDT_Byte))
    5143             :         {
    5144          42 :             m_bHasDefinition12_063 = true;
    5145          42 :             osSQL += ", definition_12_063 TEXT NOT NULL";
    5146          42 :             if (m_nUserVersion >= GPKG_1_4_VERSION)
    5147             :             {
    5148          40 :                 osSQL += ", epoch DOUBLE";
    5149          40 :                 m_bHasEpochColumn = true;
    5150             :             }
    5151             :         }
    5152             :         osSQL += ")"
    5153             :                  ";"
    5154             :                  /* Requirement 11: The gpkg_spatial_ref_sys table in a
    5155             :                     GeoPackage SHALL */
    5156             :                  /* contain a record for EPSG:4326, the geodetic WGS84 SRS */
    5157             :                  /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5158             : 
    5159             :                  "INSERT INTO gpkg_spatial_ref_sys ("
    5160             :                  "srs_name, srs_id, organization, organization_coordsys_id, "
    5161         929 :                  "definition, description";
    5162         929 :         if (m_bHasDefinition12_063)
    5163          42 :             osSQL += ", definition_12_063";
    5164             :         osSQL +=
    5165             :             ") VALUES ("
    5166             :             "'WGS 84 geodetic', 4326, 'EPSG', 4326, '"
    5167             :             "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS "
    5168             :             "84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],"
    5169             :             "AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY["
    5170             :             "\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY["
    5171             :             "\"EPSG\",\"9122\"]],AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\","
    5172             :             "EAST],AUTHORITY[\"EPSG\",\"4326\"]]"
    5173             :             "', 'longitude/latitude coordinates in decimal degrees on the WGS "
    5174         929 :             "84 spheroid'";
    5175         929 :         if (m_bHasDefinition12_063)
    5176             :             osSQL +=
    5177             :                 ", 'GEODCRS[\"WGS 84\", DATUM[\"World Geodetic System 1984\", "
    5178             :                 "ELLIPSOID[\"WGS 84\",6378137, 298.257223563, "
    5179             :                 "LENGTHUNIT[\"metre\", 1.0]]], PRIMEM[\"Greenwich\", 0.0, "
    5180             :                 "ANGLEUNIT[\"degree\",0.0174532925199433]], CS[ellipsoidal, "
    5181             :                 "2], AXIS[\"latitude\", north, ORDER[1]], AXIS[\"longitude\", "
    5182             :                 "east, ORDER[2]], ANGLEUNIT[\"degree\", 0.0174532925199433], "
    5183          42 :                 "ID[\"EPSG\", 4326]]'";
    5184             :         osSQL +=
    5185             :             ")"
    5186             :             ";"
    5187             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5188             :                SHALL */
    5189             :             /* contain a record with an srs_id of -1, an organization of “NONE”,
    5190             :              */
    5191             :             /* an organization_coordsys_id of -1, and definition “undefined” */
    5192             :             /* for undefined Cartesian coordinate reference systems */
    5193             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5194             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5195             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5196         929 :             "definition, description";
    5197         929 :         if (m_bHasDefinition12_063)
    5198          42 :             osSQL += ", definition_12_063";
    5199             :         osSQL += ") VALUES ("
    5200             :                  "'Undefined Cartesian SRS', -1, 'NONE', -1, 'undefined', "
    5201         929 :                  "'undefined Cartesian coordinate reference system'";
    5202         929 :         if (m_bHasDefinition12_063)
    5203          42 :             osSQL += ", 'undefined'";
    5204             :         osSQL +=
    5205             :             ")"
    5206             :             ";"
    5207             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5208             :                SHALL */
    5209             :             /* contain a record with an srs_id of 0, an organization of “NONE”,
    5210             :              */
    5211             :             /* an organization_coordsys_id of 0, and definition “undefined” */
    5212             :             /* for undefined geographic coordinate reference systems */
    5213             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5214             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5215             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5216         929 :             "definition, description";
    5217         929 :         if (m_bHasDefinition12_063)
    5218          42 :             osSQL += ", definition_12_063";
    5219             :         osSQL += ") VALUES ("
    5220             :                  "'Undefined geographic SRS', 0, 'NONE', 0, 'undefined', "
    5221         929 :                  "'undefined geographic coordinate reference system'";
    5222         929 :         if (m_bHasDefinition12_063)
    5223          42 :             osSQL += ", 'undefined'";
    5224             :         osSQL += ")"
    5225             :                  ";"
    5226             :                  /* Requirement 13: A GeoPackage file SHALL include a
    5227             :                     gpkg_contents table */
    5228             :                  /* http://opengis.github.io/geopackage/#_contents */
    5229             :                  "CREATE TABLE gpkg_contents ("
    5230             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5231             :                  "data_type TEXT NOT NULL,"
    5232             :                  "identifier TEXT UNIQUE,"
    5233             :                  "description TEXT DEFAULT '',"
    5234             :                  "last_change DATETIME NOT NULL DEFAULT "
    5235             :                  "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    5236             :                  "min_x DOUBLE, min_y DOUBLE,"
    5237             :                  "max_x DOUBLE, max_y DOUBLE,"
    5238             :                  "srs_id INTEGER,"
    5239             :                  "CONSTRAINT fk_gc_r_srs_id FOREIGN KEY (srs_id) REFERENCES "
    5240             :                  "gpkg_spatial_ref_sys(srs_id)"
    5241         929 :                  ")";
    5242             : 
    5243             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5244         929 :         if (CPLFetchBool(papszOptions, "ADD_GPKG_OGR_CONTENTS", true))
    5245             :         {
    5246         924 :             m_bHasGPKGOGRContents = true;
    5247             :             osSQL += ";"
    5248             :                      "CREATE TABLE gpkg_ogr_contents("
    5249             :                      "table_name TEXT NOT NULL PRIMARY KEY,"
    5250             :                      "feature_count INTEGER DEFAULT NULL"
    5251         924 :                      ")";
    5252             :         }
    5253             : #endif
    5254             : 
    5255             :         /* Requirement 21: A GeoPackage with a gpkg_contents table row with a
    5256             :          * “features” */
    5257             :         /* data_type SHALL contain a gpkg_geometry_columns table or updateable
    5258             :          * view */
    5259             :         /* http://opengis.github.io/geopackage/#_geometry_columns */
    5260             :         const bool bCreateGeometryColumns =
    5261         929 :             CPLTestBool(CPLGetConfigOption("CREATE_GEOMETRY_COLUMNS", "YES"));
    5262         929 :         if (bCreateGeometryColumns)
    5263             :         {
    5264         928 :             m_bHasGPKGGeometryColumns = true;
    5265         928 :             osSQL += ";";
    5266         928 :             osSQL += pszCREATE_GPKG_GEOMETRY_COLUMNS;
    5267             :         }
    5268             :     }
    5269             : 
    5270             :     const bool bCreateTriggers =
    5271         939 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "YES"));
    5272          10 :     if ((bFileExists && nBandsIn != 0 &&
    5273          10 :          SQLGetInteger(
    5274             :              hDB,
    5275             :              "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_tile_matrix_set' "
    5276             :              "AND type in ('table', 'view')",
    5277        1878 :              nullptr) == 0) ||
    5278         938 :         (!bFileExists &&
    5279         929 :          CPLTestBool(CPLGetConfigOption("CREATE_RASTER_TABLES", "YES"))))
    5280             :     {
    5281         929 :         if (!osSQL.empty())
    5282         928 :             osSQL += ";";
    5283             : 
    5284             :         /* From C.5. gpkg_tile_matrix_set Table 28. gpkg_tile_matrix_set Table
    5285             :          * Creation SQL  */
    5286             :         osSQL += "CREATE TABLE gpkg_tile_matrix_set ("
    5287             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5288             :                  "srs_id INTEGER NOT NULL,"
    5289             :                  "min_x DOUBLE NOT NULL,"
    5290             :                  "min_y DOUBLE NOT NULL,"
    5291             :                  "max_x DOUBLE NOT NULL,"
    5292             :                  "max_y DOUBLE NOT NULL,"
    5293             :                  "CONSTRAINT fk_gtms_table_name FOREIGN KEY (table_name) "
    5294             :                  "REFERENCES gpkg_contents(table_name),"
    5295             :                  "CONSTRAINT fk_gtms_srs FOREIGN KEY (srs_id) REFERENCES "
    5296             :                  "gpkg_spatial_ref_sys (srs_id)"
    5297             :                  ")"
    5298             :                  ";"
    5299             : 
    5300             :                  /* From C.6. gpkg_tile_matrix Table 29. gpkg_tile_matrix Table
    5301             :                     Creation SQL */
    5302             :                  "CREATE TABLE gpkg_tile_matrix ("
    5303             :                  "table_name TEXT NOT NULL,"
    5304             :                  "zoom_level INTEGER NOT NULL,"
    5305             :                  "matrix_width INTEGER NOT NULL,"
    5306             :                  "matrix_height INTEGER NOT NULL,"
    5307             :                  "tile_width INTEGER NOT NULL,"
    5308             :                  "tile_height INTEGER NOT NULL,"
    5309             :                  "pixel_x_size DOUBLE NOT NULL,"
    5310             :                  "pixel_y_size DOUBLE NOT NULL,"
    5311             :                  "CONSTRAINT pk_ttm PRIMARY KEY (table_name, zoom_level),"
    5312             :                  "CONSTRAINT fk_tmm_table_name FOREIGN KEY (table_name) "
    5313             :                  "REFERENCES gpkg_contents(table_name)"
    5314         929 :                  ")";
    5315             : 
    5316         929 :         if (bCreateTriggers)
    5317             :         {
    5318             :             /* From D.1. gpkg_tile_matrix Table 39. gpkg_tile_matrix Trigger
    5319             :              * Definition SQL */
    5320         929 :             const char *pszTileMatrixTrigger =
    5321             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_insert' "
    5322             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5323             :                 "FOR EACH ROW BEGIN "
    5324             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5325             :                 "violates constraint: zoom_level cannot be less than 0') "
    5326             :                 "WHERE (NEW.zoom_level < 0); "
    5327             :                 "END; "
    5328             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_update' "
    5329             :                 "BEFORE UPDATE of zoom_level ON 'gpkg_tile_matrix' "
    5330             :                 "FOR EACH ROW BEGIN "
    5331             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5332             :                 "violates constraint: zoom_level cannot be less than 0') "
    5333             :                 "WHERE (NEW.zoom_level < 0); "
    5334             :                 "END; "
    5335             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_insert' "
    5336             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5337             :                 "FOR EACH ROW BEGIN "
    5338             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5339             :                 "violates constraint: matrix_width cannot be less than 1') "
    5340             :                 "WHERE (NEW.matrix_width < 1); "
    5341             :                 "END; "
    5342             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_update' "
    5343             :                 "BEFORE UPDATE OF matrix_width ON 'gpkg_tile_matrix' "
    5344             :                 "FOR EACH ROW BEGIN "
    5345             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5346             :                 "violates constraint: matrix_width cannot be less than 1') "
    5347             :                 "WHERE (NEW.matrix_width < 1); "
    5348             :                 "END; "
    5349             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_insert' "
    5350             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5351             :                 "FOR EACH ROW BEGIN "
    5352             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5353             :                 "violates constraint: matrix_height cannot be less than 1') "
    5354             :                 "WHERE (NEW.matrix_height < 1); "
    5355             :                 "END; "
    5356             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_update' "
    5357             :                 "BEFORE UPDATE OF matrix_height ON 'gpkg_tile_matrix' "
    5358             :                 "FOR EACH ROW BEGIN "
    5359             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5360             :                 "violates constraint: matrix_height cannot be less than 1') "
    5361             :                 "WHERE (NEW.matrix_height < 1); "
    5362             :                 "END; "
    5363             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_insert' "
    5364             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5365             :                 "FOR EACH ROW BEGIN "
    5366             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5367             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5368             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5369             :                 "END; "
    5370             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_update' "
    5371             :                 "BEFORE UPDATE OF pixel_x_size ON 'gpkg_tile_matrix' "
    5372             :                 "FOR EACH ROW BEGIN "
    5373             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5374             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5375             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5376             :                 "END; "
    5377             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_insert' "
    5378             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5379             :                 "FOR EACH ROW BEGIN "
    5380             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5381             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5382             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5383             :                 "END; "
    5384             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_update' "
    5385             :                 "BEFORE UPDATE OF pixel_y_size ON 'gpkg_tile_matrix' "
    5386             :                 "FOR EACH ROW BEGIN "
    5387             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5388             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5389             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5390             :                 "END;";
    5391         929 :             osSQL += ";";
    5392         929 :             osSQL += pszTileMatrixTrigger;
    5393             :         }
    5394             :     }
    5395             : 
    5396         939 :     if (!osSQL.empty() && OGRERR_NONE != SQLCommand(hDB, osSQL))
    5397           1 :         return FALSE;
    5398             : 
    5399         938 :     if (!bFileExists)
    5400             :     {
    5401             :         const char *pszMetadataTables =
    5402         928 :             CSLFetchNameValue(papszOptions, "METADATA_TABLES");
    5403         928 :         if (pszMetadataTables)
    5404          10 :             m_nCreateMetadataTables = int(CPLTestBool(pszMetadataTables));
    5405             : 
    5406         928 :         if (m_nCreateMetadataTables == TRUE && !CreateMetadataTables())
    5407           0 :             return FALSE;
    5408             : 
    5409         928 :         if (m_bHasDefinition12_063)
    5410             :         {
    5411          84 :             if (OGRERR_NONE != CreateExtensionsTableIfNecessary() ||
    5412             :                 OGRERR_NONE !=
    5413          42 :                     SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5414             :                                     "(table_name, column_name, extension_name, "
    5415             :                                     "definition, scope) "
    5416             :                                     "VALUES "
    5417             :                                     "('gpkg_spatial_ref_sys', "
    5418             :                                     "'definition_12_063', 'gpkg_crs_wkt', "
    5419             :                                     "'http://www.geopackage.org/spec120/"
    5420             :                                     "#extension_crs_wkt', 'read-write')"))
    5421             :             {
    5422           0 :                 return FALSE;
    5423             :             }
    5424          42 :             if (m_bHasEpochColumn)
    5425             :             {
    5426          40 :                 if (OGRERR_NONE !=
    5427          40 :                         SQLCommand(
    5428             :                             hDB, "UPDATE gpkg_extensions SET extension_name = "
    5429             :                                  "'gpkg_crs_wkt_1_1' "
    5430          80 :                                  "WHERE extension_name = 'gpkg_crs_wkt'") ||
    5431             :                     OGRERR_NONE !=
    5432          40 :                         SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5433             :                                         "(table_name, column_name, "
    5434             :                                         "extension_name, definition, scope) "
    5435             :                                         "VALUES "
    5436             :                                         "('gpkg_spatial_ref_sys', 'epoch', "
    5437             :                                         "'gpkg_crs_wkt_1_1', "
    5438             :                                         "'http://www.geopackage.org/spec/"
    5439             :                                         "#extension_crs_wkt', "
    5440             :                                         "'read-write')"))
    5441             :                 {
    5442           0 :                     return FALSE;
    5443             :                 }
    5444             :             }
    5445             :         }
    5446             :     }
    5447             : 
    5448         938 :     if (nBandsIn != 0)
    5449             :     {
    5450         190 :         const std::string osTableName = CPLGetBasenameSafe(m_pszFilename);
    5451             :         m_osRasterTable = CSLFetchNameValueDef(papszOptions, "RASTER_TABLE",
    5452         190 :                                                osTableName.c_str());
    5453         190 :         if (m_osRasterTable.empty())
    5454             :         {
    5455           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5456             :                      "RASTER_TABLE must be set to a non empty value");
    5457           0 :             return FALSE;
    5458             :         }
    5459         190 :         m_bIdentifierAsCO =
    5460         190 :             CSLFetchNameValue(papszOptions, "RASTER_IDENTIFIER") != nullptr;
    5461             :         m_osIdentifier = CSLFetchNameValueDef(papszOptions, "RASTER_IDENTIFIER",
    5462         190 :                                               m_osRasterTable);
    5463         190 :         m_bDescriptionAsCO =
    5464         190 :             CSLFetchNameValue(papszOptions, "RASTER_DESCRIPTION") != nullptr;
    5465             :         m_osDescription =
    5466         190 :             CSLFetchNameValueDef(papszOptions, "RASTER_DESCRIPTION", "");
    5467         190 :         SetDataType(eDT);
    5468         190 :         if (eDT == GDT_Int16)
    5469          16 :             SetGlobalOffsetScale(-32768.0, 1.0);
    5470             : 
    5471             :         /* From C.7. sample_tile_pyramid (Informative) Table 31. EXAMPLE: tiles
    5472             :          * table Create Table SQL (Informative) */
    5473             :         char *pszSQL =
    5474         190 :             sqlite3_mprintf("CREATE TABLE \"%w\" ("
    5475             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    5476             :                             "zoom_level INTEGER NOT NULL,"
    5477             :                             "tile_column INTEGER NOT NULL,"
    5478             :                             "tile_row INTEGER NOT NULL,"
    5479             :                             "tile_data BLOB NOT NULL,"
    5480             :                             "UNIQUE (zoom_level, tile_column, tile_row)"
    5481             :                             ")",
    5482             :                             m_osRasterTable.c_str());
    5483         190 :         osSQL = pszSQL;
    5484         190 :         sqlite3_free(pszSQL);
    5485             : 
    5486         190 :         if (bCreateTriggers)
    5487             :         {
    5488         190 :             osSQL += ";";
    5489         190 :             osSQL += CreateRasterTriggersSQL(m_osRasterTable);
    5490             :         }
    5491             : 
    5492         190 :         OGRErr eErr = SQLCommand(hDB, osSQL);
    5493         190 :         if (OGRERR_NONE != eErr)
    5494           0 :             return FALSE;
    5495             : 
    5496         190 :         const char *pszTF = CSLFetchNameValue(papszOptions, "TILE_FORMAT");
    5497         190 :         if (eDT == GDT_Int16 || eDT == GDT_UInt16)
    5498             :         {
    5499          27 :             m_eTF = GPKG_TF_PNG_16BIT;
    5500          27 :             if (pszTF)
    5501             :             {
    5502           1 :                 if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "PNG"))
    5503             :                 {
    5504           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5505             :                              "Only AUTO or PNG supported "
    5506             :                              "as tile format for Int16 / UInt16");
    5507             :                 }
    5508             :             }
    5509             :         }
    5510         163 :         else if (eDT == GDT_Float32)
    5511             :         {
    5512          13 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    5513          13 :             if (pszTF)
    5514             :             {
    5515           5 :                 if (EQUAL(pszTF, "PNG"))
    5516           5 :                     m_eTF = GPKG_TF_PNG_16BIT;
    5517           0 :                 else if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "TIFF"))
    5518             :                 {
    5519           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5520             :                              "Only AUTO, PNG or TIFF supported "
    5521             :                              "as tile format for Float32");
    5522             :                 }
    5523             :             }
    5524             :         }
    5525             :         else
    5526             :         {
    5527         150 :             if (pszTF)
    5528             :             {
    5529          71 :                 m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    5530          71 :                 if (nBandsIn == 1 && m_eTF != GPKG_TF_PNG)
    5531           7 :                     m_bMetadataDirty = true;
    5532             :             }
    5533          79 :             else if (nBandsIn == 1)
    5534          68 :                 m_eTF = GPKG_TF_PNG;
    5535             :         }
    5536             : 
    5537         190 :         if (eDT != GDT_Byte)
    5538             :         {
    5539          40 :             if (!CreateTileGriddedTable(papszOptions))
    5540           0 :                 return FALSE;
    5541             :         }
    5542             : 
    5543         190 :         nRasterXSize = nXSize;
    5544         190 :         nRasterYSize = nYSize;
    5545             : 
    5546             :         const char *pszTileSize =
    5547         190 :             CSLFetchNameValueDef(papszOptions, "BLOCKSIZE", "256");
    5548             :         const char *pszTileWidth =
    5549         190 :             CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", pszTileSize);
    5550             :         const char *pszTileHeight =
    5551         190 :             CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", pszTileSize);
    5552         190 :         int nTileWidth = atoi(pszTileWidth);
    5553         190 :         int nTileHeight = atoi(pszTileHeight);
    5554         190 :         if ((nTileWidth < 8 || nTileWidth > 4096 || nTileHeight < 8 ||
    5555         380 :              nTileHeight > 4096) &&
    5556           1 :             !CPLTestBool(CPLGetConfigOption("GPKG_ALLOW_CRAZY_SETTINGS", "NO")))
    5557             :         {
    5558           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5559             :                      "Invalid block dimensions: %dx%d", nTileWidth,
    5560             :                      nTileHeight);
    5561           0 :             return FALSE;
    5562             :         }
    5563             : 
    5564         513 :         for (int i = 1; i <= nBandsIn; i++)
    5565             :         {
    5566         323 :             SetBand(i, std::make_unique<GDALGeoPackageRasterBand>(
    5567             :                            this, nTileWidth, nTileHeight));
    5568             :         }
    5569             : 
    5570         190 :         GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL",
    5571             :                                         "IMAGE_STRUCTURE");
    5572         190 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", m_osIdentifier);
    5573         190 :         if (!m_osDescription.empty())
    5574           1 :             GDALPamDataset::SetMetadataItem("DESCRIPTION", m_osDescription);
    5575             : 
    5576         190 :         ParseCompressionOptions(papszOptions);
    5577             : 
    5578         190 :         if (m_eTF == GPKG_TF_WEBP)
    5579             :         {
    5580          10 :             if (!RegisterWebPExtension())
    5581           0 :                 return FALSE;
    5582             :         }
    5583             : 
    5584             :         m_osTilingScheme =
    5585         190 :             CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5586         190 :         if (!EQUAL(m_osTilingScheme, "CUSTOM"))
    5587             :         {
    5588          22 :             const auto poTS = GetTilingScheme(m_osTilingScheme);
    5589          22 :             if (!poTS)
    5590           0 :                 return FALSE;
    5591             : 
    5592          43 :             if (nTileWidth != poTS->nTileWidth ||
    5593          21 :                 nTileHeight != poTS->nTileHeight)
    5594             :             {
    5595           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    5596             :                          "Tile dimension should be %dx%d for %s tiling scheme",
    5597           1 :                          poTS->nTileWidth, poTS->nTileHeight,
    5598             :                          m_osTilingScheme.c_str());
    5599           1 :                 return FALSE;
    5600             :             }
    5601             : 
    5602             :             const char *pszZoomLevel =
    5603          21 :                 CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    5604          21 :             if (pszZoomLevel)
    5605             :             {
    5606           1 :                 m_nZoomLevel = atoi(pszZoomLevel);
    5607           1 :                 int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    5608           1 :                 while ((1 << nMaxZoomLevelForThisTM) >
    5609           2 :                            INT_MAX / poTS->nTileXCountZoomLevel0 ||
    5610           1 :                        (1 << nMaxZoomLevelForThisTM) >
    5611           1 :                            INT_MAX / poTS->nTileYCountZoomLevel0)
    5612             :                 {
    5613           0 :                     --nMaxZoomLevelForThisTM;
    5614             :                 }
    5615             : 
    5616           1 :                 if (m_nZoomLevel < 0 || m_nZoomLevel > nMaxZoomLevelForThisTM)
    5617             :                 {
    5618           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    5619             :                              "ZOOM_LEVEL = %s is invalid. It should be in "
    5620             :                              "[0,%d] range",
    5621             :                              pszZoomLevel, nMaxZoomLevelForThisTM);
    5622           0 :                     return FALSE;
    5623             :                 }
    5624             :             }
    5625             : 
    5626             :             // Implicitly sets SRS.
    5627          21 :             OGRSpatialReference oSRS;
    5628          21 :             if (oSRS.importFromEPSG(poTS->nEPSGCode) != OGRERR_NONE)
    5629           0 :                 return FALSE;
    5630          21 :             char *pszWKT = nullptr;
    5631          21 :             oSRS.exportToWkt(&pszWKT);
    5632          21 :             SetProjection(pszWKT);
    5633          21 :             CPLFree(pszWKT);
    5634             :         }
    5635             :         else
    5636             :         {
    5637         168 :             if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5638             :             {
    5639           0 :                 CPLError(
    5640             :                     CE_Failure, CPLE_NotSupported,
    5641             :                     "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5642           0 :                 return false;
    5643             :             }
    5644             :         }
    5645             :     }
    5646             : 
    5647         937 :     if (bFileExists && nBandsIn > 0 && eDT == GDT_Byte)
    5648             :     {
    5649             :         // If there was an ogr_empty_table table, we can remove it
    5650           9 :         RemoveOGREmptyTable();
    5651             :     }
    5652             : 
    5653         937 :     SoftCommitTransaction();
    5654             : 
    5655             :     /* Requirement 2 */
    5656             :     /* We have to do this after there's some content so the database file */
    5657             :     /* is not zero length */
    5658         937 :     SetApplicationAndUserVersionId();
    5659             : 
    5660             :     /* Default to synchronous=off for performance for new file */
    5661        1864 :     if (!bFileExists &&
    5662         927 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5663             :     {
    5664         430 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5665             :     }
    5666             : 
    5667         937 :     return TRUE;
    5668             : }
    5669             : 
    5670             : /************************************************************************/
    5671             : /*                        RemoveOGREmptyTable()                         */
    5672             : /************************************************************************/
    5673             : 
    5674         747 : void GDALGeoPackageDataset::RemoveOGREmptyTable()
    5675             : {
    5676             :     // Run with sqlite3_exec since we don't want errors to be emitted
    5677         747 :     sqlite3_exec(hDB, "DROP TABLE IF EXISTS ogr_empty_table", nullptr, nullptr,
    5678             :                  nullptr);
    5679         747 :     sqlite3_exec(
    5680             :         hDB, "DELETE FROM gpkg_contents WHERE table_name = 'ogr_empty_table'",
    5681             :         nullptr, nullptr, nullptr);
    5682             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5683         747 :     if (m_bHasGPKGOGRContents)
    5684             :     {
    5685         733 :         sqlite3_exec(hDB,
    5686             :                      "DELETE FROM gpkg_ogr_contents WHERE "
    5687             :                      "table_name = 'ogr_empty_table'",
    5688             :                      nullptr, nullptr, nullptr);
    5689             :     }
    5690             : #endif
    5691         747 :     sqlite3_exec(hDB,
    5692             :                  "DELETE FROM gpkg_geometry_columns WHERE "
    5693             :                  "table_name = 'ogr_empty_table'",
    5694             :                  nullptr, nullptr, nullptr);
    5695         747 : }
    5696             : 
    5697             : /************************************************************************/
    5698             : /*                        CreateTileGriddedTable()                      */
    5699             : /************************************************************************/
    5700             : 
    5701          40 : bool GDALGeoPackageDataset::CreateTileGriddedTable(char **papszOptions)
    5702             : {
    5703          80 :     CPLString osSQL;
    5704          40 :     if (!HasGriddedCoverageAncillaryTable())
    5705             :     {
    5706             :         // It doesn't exist. So create gpkg_extensions table if necessary, and
    5707             :         // gpkg_2d_gridded_coverage_ancillary & gpkg_2d_gridded_tile_ancillary,
    5708             :         // and register them as extensions.
    5709          40 :         if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    5710           0 :             return false;
    5711             : 
    5712             :         // Req 1 /table-defs/coverage-ancillary
    5713             :         osSQL = "CREATE TABLE gpkg_2d_gridded_coverage_ancillary ("
    5714             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5715             :                 "tile_matrix_set_name TEXT NOT NULL UNIQUE,"
    5716             :                 "datatype TEXT NOT NULL DEFAULT 'integer',"
    5717             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5718             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5719             :                 "precision REAL DEFAULT 1.0,"
    5720             :                 "data_null REAL,"
    5721             :                 "grid_cell_encoding TEXT DEFAULT 'grid-value-is-center',"
    5722             :                 "uom TEXT,"
    5723             :                 "field_name TEXT DEFAULT 'Height',"
    5724             :                 "quantity_definition TEXT DEFAULT 'Height',"
    5725             :                 "CONSTRAINT fk_g2dgtct_name FOREIGN KEY(tile_matrix_set_name) "
    5726             :                 "REFERENCES gpkg_tile_matrix_set ( table_name ) "
    5727             :                 "CHECK (datatype in ('integer','float')))"
    5728             :                 ";"
    5729             :                 // Requirement 2 /table-defs/tile-ancillary
    5730             :                 "CREATE TABLE gpkg_2d_gridded_tile_ancillary ("
    5731             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5732             :                 "tpudt_name TEXT NOT NULL,"
    5733             :                 "tpudt_id INTEGER NOT NULL,"
    5734             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5735             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5736             :                 "min REAL DEFAULT NULL,"
    5737             :                 "max REAL DEFAULT NULL,"
    5738             :                 "mean REAL DEFAULT NULL,"
    5739             :                 "std_dev REAL DEFAULT NULL,"
    5740             :                 "CONSTRAINT fk_g2dgtat_name FOREIGN KEY (tpudt_name) "
    5741             :                 "REFERENCES gpkg_contents(table_name),"
    5742             :                 "UNIQUE (tpudt_name, tpudt_id))"
    5743             :                 ";"
    5744             :                 // Requirement 6 /gpkg-extensions
    5745             :                 "INSERT INTO gpkg_extensions "
    5746             :                 "(table_name, column_name, extension_name, definition, scope) "
    5747             :                 "VALUES ('gpkg_2d_gridded_coverage_ancillary', NULL, "
    5748             :                 "'gpkg_2d_gridded_coverage', "
    5749             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5750             :                 "'read-write')"
    5751             :                 ";"
    5752             :                 // Requirement 6 /gpkg-extensions
    5753             :                 "INSERT INTO gpkg_extensions "
    5754             :                 "(table_name, column_name, extension_name, definition, scope) "
    5755             :                 "VALUES ('gpkg_2d_gridded_tile_ancillary', NULL, "
    5756             :                 "'gpkg_2d_gridded_coverage', "
    5757             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5758             :                 "'read-write')"
    5759          40 :                 ";";
    5760             :     }
    5761             : 
    5762             :     // Requirement 6 /gpkg-extensions
    5763          40 :     char *pszSQL = sqlite3_mprintf(
    5764             :         "INSERT INTO gpkg_extensions "
    5765             :         "(table_name, column_name, extension_name, definition, scope) "
    5766             :         "VALUES ('%q', 'tile_data', "
    5767             :         "'gpkg_2d_gridded_coverage', "
    5768             :         "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5769             :         "'read-write')",
    5770             :         m_osRasterTable.c_str());
    5771          40 :     osSQL += pszSQL;
    5772          40 :     osSQL += ";";
    5773          40 :     sqlite3_free(pszSQL);
    5774             : 
    5775             :     // Requirement 7 /gpkg-2d-gridded-coverage-ancillary
    5776             :     // Requirement 8 /gpkg-2d-gridded-coverage-ancillary-set-name
    5777             :     // Requirement 9 /gpkg-2d-gridded-coverage-ancillary-datatype
    5778          40 :     m_dfPrecision =
    5779          40 :         CPLAtof(CSLFetchNameValueDef(papszOptions, "PRECISION", "1"));
    5780             :     CPLString osGridCellEncoding(CSLFetchNameValueDef(
    5781          80 :         papszOptions, "GRID_CELL_ENCODING", "grid-value-is-center"));
    5782          40 :     m_bGridCellEncodingAsCO =
    5783          40 :         CSLFetchNameValue(papszOptions, "GRID_CELL_ENCODING") != nullptr;
    5784          80 :     CPLString osUom(CSLFetchNameValueDef(papszOptions, "UOM", ""));
    5785             :     CPLString osFieldName(
    5786          80 :         CSLFetchNameValueDef(papszOptions, "FIELD_NAME", "Height"));
    5787             :     CPLString osQuantityDefinition(
    5788          80 :         CSLFetchNameValueDef(papszOptions, "QUANTITY_DEFINITION", "Height"));
    5789             : 
    5790         121 :     pszSQL = sqlite3_mprintf(
    5791             :         "INSERT INTO gpkg_2d_gridded_coverage_ancillary "
    5792             :         "(tile_matrix_set_name, datatype, scale, offset, precision, "
    5793             :         "grid_cell_encoding, uom, field_name, quantity_definition) "
    5794             :         "VALUES (%Q, '%s', %.17g, %.17g, %.17g, %Q, %Q, %Q, %Q)",
    5795             :         m_osRasterTable.c_str(),
    5796          40 :         (m_eTF == GPKG_TF_PNG_16BIT) ? "integer" : "float", m_dfScale,
    5797             :         m_dfOffset, m_dfPrecision, osGridCellEncoding.c_str(),
    5798          41 :         osUom.empty() ? nullptr : osUom.c_str(), osFieldName.c_str(),
    5799             :         osQuantityDefinition.c_str());
    5800          40 :     m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary = pszSQL;
    5801          40 :     sqlite3_free(pszSQL);
    5802             : 
    5803             :     // Requirement 3 /gpkg-spatial-ref-sys-row
    5804             :     auto oResultTable = SQLQuery(
    5805          80 :         hDB, "SELECT * FROM gpkg_spatial_ref_sys WHERE srs_id = 4979 LIMIT 2");
    5806          40 :     bool bHasEPSG4979 = (oResultTable && oResultTable->RowCount() == 1);
    5807          40 :     if (!bHasEPSG4979)
    5808             :     {
    5809          41 :         if (!m_bHasDefinition12_063 &&
    5810           1 :             !ConvertGpkgSpatialRefSysToExtensionWkt2(/*bForceEpoch=*/false))
    5811             :         {
    5812           0 :             return false;
    5813             :         }
    5814             : 
    5815             :         // This is WKT 2...
    5816          40 :         const char *pszWKT =
    5817             :             "GEODCRS[\"WGS 84\","
    5818             :             "DATUM[\"World Geodetic System 1984\","
    5819             :             "  ELLIPSOID[\"WGS 84\",6378137,298.257223563,"
    5820             :             "LENGTHUNIT[\"metre\",1.0]]],"
    5821             :             "CS[ellipsoidal,3],"
    5822             :             "  AXIS[\"latitude\",north,ORDER[1],ANGLEUNIT[\"degree\","
    5823             :             "0.0174532925199433]],"
    5824             :             "  AXIS[\"longitude\",east,ORDER[2],ANGLEUNIT[\"degree\","
    5825             :             "0.0174532925199433]],"
    5826             :             "  AXIS[\"ellipsoidal height\",up,ORDER[3],"
    5827             :             "LENGTHUNIT[\"metre\",1.0]],"
    5828             :             "ID[\"EPSG\",4979]]";
    5829             : 
    5830          40 :         pszSQL = sqlite3_mprintf(
    5831             :             "INSERT INTO gpkg_spatial_ref_sys "
    5832             :             "(srs_name,srs_id,organization,organization_coordsys_id,"
    5833             :             "definition,definition_12_063) VALUES "
    5834             :             "('WGS 84 3D', 4979, 'EPSG', 4979, 'undefined', '%q')",
    5835             :             pszWKT);
    5836          40 :         osSQL += ";";
    5837          40 :         osSQL += pszSQL;
    5838          40 :         sqlite3_free(pszSQL);
    5839             :     }
    5840             : 
    5841          40 :     return SQLCommand(hDB, osSQL) == OGRERR_NONE;
    5842             : }
    5843             : 
    5844             : /************************************************************************/
    5845             : /*                    HasGriddedCoverageAncillaryTable()                */
    5846             : /************************************************************************/
    5847             : 
    5848          44 : bool GDALGeoPackageDataset::HasGriddedCoverageAncillaryTable()
    5849             : {
    5850             :     auto oResultTable = SQLQuery(
    5851             :         hDB, "SELECT * FROM sqlite_master WHERE type IN ('table', 'view') AND "
    5852          44 :              "name = 'gpkg_2d_gridded_coverage_ancillary'");
    5853          44 :     bool bHasTable = (oResultTable && oResultTable->RowCount() == 1);
    5854          88 :     return bHasTable;
    5855             : }
    5856             : 
    5857             : /************************************************************************/
    5858             : /*                      GetUnderlyingDataset()                          */
    5859             : /************************************************************************/
    5860             : 
    5861           3 : static GDALDataset *GetUnderlyingDataset(GDALDataset *poSrcDS)
    5862             : {
    5863           3 :     if (auto poVRTDS = dynamic_cast<VRTDataset *>(poSrcDS))
    5864             :     {
    5865           0 :         auto poTmpDS = poVRTDS->GetSingleSimpleSource();
    5866           0 :         if (poTmpDS)
    5867           0 :             return poTmpDS;
    5868             :     }
    5869             : 
    5870           3 :     return poSrcDS;
    5871             : }
    5872             : 
    5873             : /************************************************************************/
    5874             : /*                            CreateCopy()                              */
    5875             : /************************************************************************/
    5876             : 
    5877             : typedef struct
    5878             : {
    5879             :     const char *pszName;
    5880             :     GDALResampleAlg eResampleAlg;
    5881             : } WarpResamplingAlg;
    5882             : 
    5883             : static const WarpResamplingAlg asResamplingAlg[] = {
    5884             :     {"NEAREST", GRA_NearestNeighbour},
    5885             :     {"BILINEAR", GRA_Bilinear},
    5886             :     {"CUBIC", GRA_Cubic},
    5887             :     {"CUBICSPLINE", GRA_CubicSpline},
    5888             :     {"LANCZOS", GRA_Lanczos},
    5889             :     {"MODE", GRA_Mode},
    5890             :     {"AVERAGE", GRA_Average},
    5891             :     {"RMS", GRA_RMS},
    5892             : };
    5893             : 
    5894         162 : GDALDataset *GDALGeoPackageDataset::CreateCopy(const char *pszFilename,
    5895             :                                                GDALDataset *poSrcDS,
    5896             :                                                int bStrict, char **papszOptions,
    5897             :                                                GDALProgressFunc pfnProgress,
    5898             :                                                void *pProgressData)
    5899             : {
    5900         162 :     const int nBands = poSrcDS->GetRasterCount();
    5901         162 :     if (nBands == 0)
    5902             :     {
    5903           2 :         GDALDataset *poDS = nullptr;
    5904             :         GDALDriver *poThisDriver =
    5905           2 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5906           2 :         if (poThisDriver != nullptr)
    5907             :         {
    5908           2 :             poDS = poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS,
    5909             :                                                    bStrict, papszOptions,
    5910             :                                                    pfnProgress, pProgressData);
    5911             :         }
    5912           2 :         return poDS;
    5913             :     }
    5914             : 
    5915             :     const char *pszTilingScheme =
    5916         160 :         CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5917             : 
    5918         320 :     CPLStringList apszUpdatedOptions(CSLDuplicate(papszOptions));
    5919         160 :     if (CPLTestBool(
    5920         166 :             CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")) &&
    5921           6 :         CSLFetchNameValue(papszOptions, "RASTER_TABLE") == nullptr)
    5922             :     {
    5923             :         const std::string osBasename(CPLGetBasenameSafe(
    5924           6 :             GetUnderlyingDataset(poSrcDS)->GetDescription()));
    5925           3 :         apszUpdatedOptions.SetNameValue("RASTER_TABLE", osBasename.c_str());
    5926             :     }
    5927             : 
    5928         160 :     if (nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4)
    5929             :     {
    5930           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    5931             :                  "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or "
    5932             :                  "4 (RGBA) band dataset supported");
    5933           1 :         return nullptr;
    5934             :     }
    5935             : 
    5936         159 :     const char *pszUnitType = poSrcDS->GetRasterBand(1)->GetUnitType();
    5937         318 :     if (CSLFetchNameValue(papszOptions, "UOM") == nullptr && pszUnitType &&
    5938         159 :         !EQUAL(pszUnitType, ""))
    5939             :     {
    5940           1 :         apszUpdatedOptions.SetNameValue("UOM", pszUnitType);
    5941             :     }
    5942             : 
    5943         159 :     if (EQUAL(pszTilingScheme, "CUSTOM"))
    5944             :     {
    5945         135 :         if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5946             :         {
    5947           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    5948             :                      "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5949           0 :             return nullptr;
    5950             :         }
    5951             : 
    5952         135 :         GDALGeoPackageDataset *poDS = nullptr;
    5953             :         GDALDriver *poThisDriver =
    5954         135 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5955         135 :         if (poThisDriver != nullptr)
    5956             :         {
    5957         135 :             apszUpdatedOptions.SetNameValue("SKIP_HOLES", "YES");
    5958         135 :             poDS = cpl::down_cast<GDALGeoPackageDataset *>(
    5959             :                 poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS, bStrict,
    5960             :                                                 apszUpdatedOptions, pfnProgress,
    5961         135 :                                                 pProgressData));
    5962             : 
    5963         250 :             if (poDS != nullptr &&
    5964         135 :                 poSrcDS->GetRasterBand(1)->GetRasterDataType() == GDT_Byte &&
    5965             :                 nBands <= 3)
    5966             :             {
    5967          75 :                 poDS->m_nBandCountFromMetadata = nBands;
    5968          75 :                 poDS->m_bMetadataDirty = true;
    5969             :             }
    5970             :         }
    5971         135 :         if (poDS)
    5972         115 :             poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    5973         135 :         return poDS;
    5974             :     }
    5975             : 
    5976          48 :     const auto poTS = GetTilingScheme(pszTilingScheme);
    5977          24 :     if (!poTS)
    5978             :     {
    5979           2 :         return nullptr;
    5980             :     }
    5981          22 :     const int nEPSGCode = poTS->nEPSGCode;
    5982             : 
    5983          44 :     OGRSpatialReference oSRS;
    5984          22 :     if (oSRS.importFromEPSG(nEPSGCode) != OGRERR_NONE)
    5985             :     {
    5986           0 :         return nullptr;
    5987             :     }
    5988          22 :     char *pszWKT = nullptr;
    5989          22 :     oSRS.exportToWkt(&pszWKT);
    5990          22 :     char **papszTO = CSLSetNameValue(nullptr, "DST_SRS", pszWKT);
    5991             : 
    5992          22 :     void *hTransformArg = nullptr;
    5993             : 
    5994             :     // Hack to compensate for GDALSuggestedWarpOutput2() failure (or not
    5995             :     // ideal suggestion with PROJ 8) when reprojecting latitude = +/- 90 to
    5996             :     // EPSG:3857.
    5997          22 :     GDALGeoTransform srcGT;
    5998          22 :     std::unique_ptr<GDALDataset> poTmpDS;
    5999          22 :     bool bEPSG3857Adjust = false;
    6000           8 :     if (nEPSGCode == 3857 && poSrcDS->GetGeoTransform(srcGT) == CE_None &&
    6001          30 :         srcGT[2] == 0 && srcGT[4] == 0 && srcGT[5] < 0)
    6002             :     {
    6003           8 :         const auto poSrcSRS = poSrcDS->GetSpatialRef();
    6004           8 :         if (poSrcSRS && poSrcSRS->IsGeographic())
    6005             :         {
    6006           2 :             double maxLat = srcGT[3];
    6007           2 :             double minLat = srcGT[3] + poSrcDS->GetRasterYSize() * srcGT[5];
    6008             :             // Corresponds to the latitude of below MAX_GM
    6009           2 :             constexpr double MAX_LAT = 85.0511287798066;
    6010           2 :             bool bModified = false;
    6011           2 :             if (maxLat > MAX_LAT)
    6012             :             {
    6013           2 :                 maxLat = MAX_LAT;
    6014           2 :                 bModified = true;
    6015             :             }
    6016           2 :             if (minLat < -MAX_LAT)
    6017             :             {
    6018           2 :                 minLat = -MAX_LAT;
    6019           2 :                 bModified = true;
    6020             :             }
    6021           2 :             if (bModified)
    6022             :             {
    6023           4 :                 CPLStringList aosOptions;
    6024           2 :                 aosOptions.AddString("-of");
    6025           2 :                 aosOptions.AddString("VRT");
    6026           2 :                 aosOptions.AddString("-projwin");
    6027           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", srcGT[0]));
    6028           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", maxLat));
    6029             :                 aosOptions.AddString(CPLSPrintf(
    6030           2 :                     "%.17g", srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1]));
    6031           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", minLat));
    6032             :                 auto psOptions =
    6033           2 :                     GDALTranslateOptionsNew(aosOptions.List(), nullptr);
    6034           2 :                 poTmpDS.reset(GDALDataset::FromHandle(GDALTranslate(
    6035             :                     "", GDALDataset::ToHandle(poSrcDS), psOptions, nullptr)));
    6036           2 :                 GDALTranslateOptionsFree(psOptions);
    6037           2 :                 if (poTmpDS)
    6038             :                 {
    6039           2 :                     bEPSG3857Adjust = true;
    6040           2 :                     hTransformArg = GDALCreateGenImgProjTransformer2(
    6041           2 :                         GDALDataset::FromHandle(poTmpDS.get()), nullptr,
    6042             :                         papszTO);
    6043             :                 }
    6044             :             }
    6045             :         }
    6046             :     }
    6047          22 :     if (hTransformArg == nullptr)
    6048             :     {
    6049             :         hTransformArg =
    6050          20 :             GDALCreateGenImgProjTransformer2(poSrcDS, nullptr, papszTO);
    6051             :     }
    6052             : 
    6053          22 :     if (hTransformArg == nullptr)
    6054             :     {
    6055           1 :         CPLFree(pszWKT);
    6056           1 :         CSLDestroy(papszTO);
    6057           1 :         return nullptr;
    6058             :     }
    6059             : 
    6060          21 :     GDALTransformerInfo *psInfo =
    6061             :         static_cast<GDALTransformerInfo *>(hTransformArg);
    6062          21 :     GDALGeoTransform gt;
    6063             :     double adfExtent[4];
    6064             :     int nXSize, nYSize;
    6065             : 
    6066          21 :     if (GDALSuggestedWarpOutput2(poSrcDS, psInfo->pfnTransform, hTransformArg,
    6067             :                                  gt.data(), &nXSize, &nYSize, adfExtent,
    6068          21 :                                  0) != CE_None)
    6069             :     {
    6070           0 :         CPLFree(pszWKT);
    6071           0 :         CSLDestroy(papszTO);
    6072           0 :         GDALDestroyGenImgProjTransformer(hTransformArg);
    6073           0 :         return nullptr;
    6074             :     }
    6075             : 
    6076          21 :     GDALDestroyGenImgProjTransformer(hTransformArg);
    6077          21 :     hTransformArg = nullptr;
    6078          21 :     poTmpDS.reset();
    6079             : 
    6080          21 :     if (bEPSG3857Adjust)
    6081             :     {
    6082           2 :         constexpr double SPHERICAL_RADIUS = 6378137.0;
    6083           2 :         constexpr double MAX_GM =
    6084             :             SPHERICAL_RADIUS * M_PI;  // 20037508.342789244
    6085           2 :         double maxNorthing = gt[3];
    6086           2 :         double minNorthing = gt[3] + gt[5] * nYSize;
    6087           2 :         bool bChanged = false;
    6088           2 :         if (maxNorthing > MAX_GM)
    6089             :         {
    6090           2 :             bChanged = true;
    6091           2 :             maxNorthing = MAX_GM;
    6092             :         }
    6093           2 :         if (minNorthing < -MAX_GM)
    6094             :         {
    6095           2 :             bChanged = true;
    6096           2 :             minNorthing = -MAX_GM;
    6097             :         }
    6098           2 :         if (bChanged)
    6099             :         {
    6100           2 :             gt[3] = maxNorthing;
    6101           2 :             nYSize = int((maxNorthing - minNorthing) / (-gt[5]) + 0.5);
    6102           2 :             adfExtent[1] = maxNorthing + nYSize * gt[5];
    6103           2 :             adfExtent[3] = maxNorthing;
    6104             :         }
    6105             :     }
    6106             : 
    6107          21 :     double dfComputedRes = gt[1];
    6108          21 :     double dfPrevRes = 0.0;
    6109          21 :     double dfRes = 0.0;
    6110          21 :     int nZoomLevel = 0;  // Used after for.
    6111          21 :     const char *pszZoomLevel = CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    6112          21 :     if (pszZoomLevel)
    6113             :     {
    6114           2 :         nZoomLevel = atoi(pszZoomLevel);
    6115             : 
    6116           2 :         int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    6117           2 :         while ((1 << nMaxZoomLevelForThisTM) >
    6118           4 :                    INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6119           2 :                (1 << nMaxZoomLevelForThisTM) >
    6120           2 :                    INT_MAX / poTS->nTileYCountZoomLevel0)
    6121             :         {
    6122           0 :             --nMaxZoomLevelForThisTM;
    6123             :         }
    6124             : 
    6125           2 :         if (nZoomLevel < 0 || nZoomLevel > nMaxZoomLevelForThisTM)
    6126             :         {
    6127           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6128             :                      "ZOOM_LEVEL = %s is invalid. It should be in [0,%d] range",
    6129             :                      pszZoomLevel, nMaxZoomLevelForThisTM);
    6130           1 :             CPLFree(pszWKT);
    6131           1 :             CSLDestroy(papszTO);
    6132           1 :             return nullptr;
    6133             :         }
    6134             :     }
    6135             :     else
    6136             :     {
    6137         171 :         for (; nZoomLevel < MAX_ZOOM_LEVEL; nZoomLevel++)
    6138             :         {
    6139         171 :             dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6140         171 :             if (dfComputedRes > dfRes ||
    6141         152 :                 fabs(dfComputedRes - dfRes) / dfRes <= 1e-8)
    6142             :                 break;
    6143         152 :             dfPrevRes = dfRes;
    6144             :         }
    6145          38 :         if (nZoomLevel == MAX_ZOOM_LEVEL ||
    6146          38 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6147          19 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileYCountZoomLevel0)
    6148             :         {
    6149           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6150             :                      "Could not find an appropriate zoom level");
    6151           0 :             CPLFree(pszWKT);
    6152           0 :             CSLDestroy(papszTO);
    6153           0 :             return nullptr;
    6154             :         }
    6155             : 
    6156          19 :         if (nZoomLevel > 0 && fabs(dfComputedRes - dfRes) / dfRes > 1e-8)
    6157             :         {
    6158          17 :             const char *pszZoomLevelStrategy = CSLFetchNameValueDef(
    6159             :                 papszOptions, "ZOOM_LEVEL_STRATEGY", "AUTO");
    6160          17 :             if (EQUAL(pszZoomLevelStrategy, "LOWER"))
    6161             :             {
    6162           1 :                 nZoomLevel--;
    6163             :             }
    6164          16 :             else if (EQUAL(pszZoomLevelStrategy, "UPPER"))
    6165             :             {
    6166             :                 /* do nothing */
    6167             :             }
    6168             :             else
    6169             :             {
    6170          15 :                 if (dfPrevRes / dfComputedRes < dfComputedRes / dfRes)
    6171          13 :                     nZoomLevel--;
    6172             :             }
    6173             :         }
    6174             :     }
    6175             : 
    6176          20 :     dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6177             : 
    6178          20 :     double dfMinX = adfExtent[0];
    6179          20 :     double dfMinY = adfExtent[1];
    6180          20 :     double dfMaxX = adfExtent[2];
    6181          20 :     double dfMaxY = adfExtent[3];
    6182             : 
    6183          20 :     nXSize = static_cast<int>(0.5 + (dfMaxX - dfMinX) / dfRes);
    6184          20 :     nYSize = static_cast<int>(0.5 + (dfMaxY - dfMinY) / dfRes);
    6185          20 :     gt[1] = dfRes;
    6186          20 :     gt[5] = -dfRes;
    6187             : 
    6188          20 :     const GDALDataType eDT = poSrcDS->GetRasterBand(1)->GetRasterDataType();
    6189          20 :     int nTargetBands = nBands;
    6190             :     /* For grey level or RGB, if there's reprojection involved, add an alpha */
    6191             :     /* channel */
    6192          37 :     if (eDT == GDT_Byte &&
    6193          13 :         ((nBands == 1 &&
    6194          17 :           poSrcDS->GetRasterBand(1)->GetColorTable() == nullptr) ||
    6195             :          nBands == 3))
    6196             :     {
    6197          30 :         OGRSpatialReference oSrcSRS;
    6198          15 :         oSrcSRS.SetFromUserInput(poSrcDS->GetProjectionRef());
    6199          15 :         oSrcSRS.AutoIdentifyEPSG();
    6200          30 :         if (oSrcSRS.GetAuthorityCode(nullptr) == nullptr ||
    6201          15 :             atoi(oSrcSRS.GetAuthorityCode(nullptr)) != nEPSGCode)
    6202             :         {
    6203          13 :             nTargetBands++;
    6204             :         }
    6205             :     }
    6206             : 
    6207          20 :     GDALResampleAlg eResampleAlg = GRA_Bilinear;
    6208          20 :     const char *pszResampling = CSLFetchNameValue(papszOptions, "RESAMPLING");
    6209          20 :     if (pszResampling)
    6210             :     {
    6211           6 :         for (size_t iAlg = 0;
    6212           6 :              iAlg < sizeof(asResamplingAlg) / sizeof(asResamplingAlg[0]);
    6213             :              iAlg++)
    6214             :         {
    6215           6 :             if (EQUAL(pszResampling, asResamplingAlg[iAlg].pszName))
    6216             :             {
    6217           3 :                 eResampleAlg = asResamplingAlg[iAlg].eResampleAlg;
    6218           3 :                 break;
    6219             :             }
    6220             :         }
    6221             :     }
    6222             : 
    6223          16 :     if (nBands == 1 && poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    6224          36 :         eResampleAlg != GRA_NearestNeighbour && eResampleAlg != GRA_Mode)
    6225             :     {
    6226           0 :         CPLError(
    6227             :             CE_Warning, CPLE_AppDefined,
    6228             :             "Input dataset has a color table, which will likely lead to "
    6229             :             "bad results when using a resampling method other than "
    6230             :             "nearest neighbour or mode. Converting the dataset to 24/32 bit "
    6231             :             "(e.g. with gdal_translate -expand rgb/rgba) is advised.");
    6232             :     }
    6233             : 
    6234          40 :     auto poDS = std::make_unique<GDALGeoPackageDataset>();
    6235          20 :     if (!(poDS->Create(pszFilename, nXSize, nYSize, nTargetBands, eDT,
    6236             :                        apszUpdatedOptions)))
    6237             :     {
    6238           1 :         CPLFree(pszWKT);
    6239           1 :         CSLDestroy(papszTO);
    6240           1 :         return nullptr;
    6241             :     }
    6242             : 
    6243             :     // Assign nodata values before the SetGeoTransform call.
    6244             :     // SetGeoTransform will trigger creation of the overview datasets for each
    6245             :     // zoom level and at that point the nodata value needs to be known.
    6246          19 :     int bHasNoData = FALSE;
    6247             :     double dfNoDataValue =
    6248          19 :         poSrcDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    6249          19 :     if (eDT != GDT_Byte && bHasNoData)
    6250             :     {
    6251           3 :         poDS->GetRasterBand(1)->SetNoDataValue(dfNoDataValue);
    6252             :     }
    6253             : 
    6254          19 :     poDS->SetGeoTransform(gt);
    6255          19 :     poDS->SetProjection(pszWKT);
    6256          19 :     CPLFree(pszWKT);
    6257          19 :     pszWKT = nullptr;
    6258          24 :     if (nTargetBands == 1 && nBands == 1 &&
    6259           5 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
    6260             :     {
    6261           2 :         poDS->GetRasterBand(1)->SetColorTable(
    6262           1 :             poSrcDS->GetRasterBand(1)->GetColorTable());
    6263             :     }
    6264             : 
    6265             :     hTransformArg =
    6266          19 :         GDALCreateGenImgProjTransformer2(poSrcDS, poDS.get(), papszTO);
    6267          19 :     CSLDestroy(papszTO);
    6268          19 :     if (hTransformArg == nullptr)
    6269             :     {
    6270           0 :         return nullptr;
    6271             :     }
    6272             : 
    6273          19 :     poDS->SetMetadata(poSrcDS->GetMetadata());
    6274             : 
    6275             :     /* -------------------------------------------------------------------- */
    6276             :     /*      Warp the transformer with a linear approximator                 */
    6277             :     /* -------------------------------------------------------------------- */
    6278          19 :     hTransformArg = GDALCreateApproxTransformer(GDALGenImgProjTransform,
    6279             :                                                 hTransformArg, 0.125);
    6280          19 :     GDALApproxTransformerOwnsSubtransformer(hTransformArg, TRUE);
    6281             : 
    6282             :     /* -------------------------------------------------------------------- */
    6283             :     /*      Setup warp options.                                             */
    6284             :     /* -------------------------------------------------------------------- */
    6285          19 :     GDALWarpOptions *psWO = GDALCreateWarpOptions();
    6286             : 
    6287          19 :     psWO->papszWarpOptions = CSLSetNameValue(nullptr, "OPTIMIZE_SIZE", "YES");
    6288          19 :     psWO->papszWarpOptions =
    6289          19 :         CSLSetNameValue(psWO->papszWarpOptions, "SAMPLE_GRID", "YES");
    6290          19 :     if (bHasNoData)
    6291             :     {
    6292           3 :         if (dfNoDataValue == 0.0)
    6293             :         {
    6294             :             // Do not initialize in the case where nodata != 0, since we
    6295             :             // want the GeoPackage driver to return empty tiles at the nodata
    6296             :             // value instead of 0 as GDAL core would
    6297           0 :             psWO->papszWarpOptions =
    6298           0 :                 CSLSetNameValue(psWO->papszWarpOptions, "INIT_DEST", "0");
    6299             :         }
    6300             : 
    6301           3 :         psWO->padfSrcNoDataReal =
    6302           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6303           3 :         psWO->padfSrcNoDataReal[0] = dfNoDataValue;
    6304             : 
    6305           3 :         psWO->padfDstNoDataReal =
    6306           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6307           3 :         psWO->padfDstNoDataReal[0] = dfNoDataValue;
    6308             :     }
    6309          19 :     psWO->eWorkingDataType = eDT;
    6310          19 :     psWO->eResampleAlg = eResampleAlg;
    6311             : 
    6312          19 :     psWO->hSrcDS = poSrcDS;
    6313          19 :     psWO->hDstDS = poDS.get();
    6314             : 
    6315          19 :     psWO->pfnTransformer = GDALApproxTransform;
    6316          19 :     psWO->pTransformerArg = hTransformArg;
    6317             : 
    6318          19 :     psWO->pfnProgress = pfnProgress;
    6319          19 :     psWO->pProgressArg = pProgressData;
    6320             : 
    6321             :     /* -------------------------------------------------------------------- */
    6322             :     /*      Setup band mapping.                                             */
    6323             :     /* -------------------------------------------------------------------- */
    6324             : 
    6325          19 :     if (nBands == 2 || nBands == 4)
    6326           1 :         psWO->nBandCount = nBands - 1;
    6327             :     else
    6328          18 :         psWO->nBandCount = nBands;
    6329             : 
    6330          19 :     psWO->panSrcBands =
    6331          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6332          19 :     psWO->panDstBands =
    6333          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6334             : 
    6335          46 :     for (int i = 0; i < psWO->nBandCount; i++)
    6336             :     {
    6337          27 :         psWO->panSrcBands[i] = i + 1;
    6338          27 :         psWO->panDstBands[i] = i + 1;
    6339             :     }
    6340             : 
    6341          19 :     if (nBands == 2 || nBands == 4)
    6342             :     {
    6343           1 :         psWO->nSrcAlphaBand = nBands;
    6344             :     }
    6345          19 :     if (nTargetBands == 2 || nTargetBands == 4)
    6346             :     {
    6347          13 :         psWO->nDstAlphaBand = nTargetBands;
    6348             :     }
    6349             : 
    6350             :     /* -------------------------------------------------------------------- */
    6351             :     /*      Initialize and execute the warp.                                */
    6352             :     /* -------------------------------------------------------------------- */
    6353          38 :     GDALWarpOperation oWO;
    6354             : 
    6355          19 :     CPLErr eErr = oWO.Initialize(psWO);
    6356          19 :     if (eErr == CE_None)
    6357             :     {
    6358             :         /*if( bMulti )
    6359             :             eErr = oWO.ChunkAndWarpMulti( 0, 0, nXSize, nYSize );
    6360             :         else*/
    6361          19 :         eErr = oWO.ChunkAndWarpImage(0, 0, nXSize, nYSize);
    6362             :     }
    6363          19 :     if (eErr != CE_None)
    6364             :     {
    6365           0 :         poDS.reset();
    6366             :     }
    6367             : 
    6368          19 :     GDALDestroyTransformer(hTransformArg);
    6369          19 :     GDALDestroyWarpOptions(psWO);
    6370             : 
    6371          19 :     if (poDS)
    6372          19 :         poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    6373             : 
    6374          19 :     return poDS.release();
    6375             : }
    6376             : 
    6377             : /************************************************************************/
    6378             : /*                        ParseCompressionOptions()                     */
    6379             : /************************************************************************/
    6380             : 
    6381         459 : void GDALGeoPackageDataset::ParseCompressionOptions(char **papszOptions)
    6382             : {
    6383         459 :     const char *pszZLevel = CSLFetchNameValue(papszOptions, "ZLEVEL");
    6384         459 :     if (pszZLevel)
    6385           0 :         m_nZLevel = atoi(pszZLevel);
    6386             : 
    6387         459 :     const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
    6388         459 :     if (pszQuality)
    6389           0 :         m_nQuality = atoi(pszQuality);
    6390             : 
    6391         459 :     const char *pszDither = CSLFetchNameValue(papszOptions, "DITHER");
    6392         459 :     if (pszDither)
    6393           0 :         m_bDither = CPLTestBool(pszDither);
    6394         459 : }
    6395             : 
    6396             : /************************************************************************/
    6397             : /*                          RegisterWebPExtension()                     */
    6398             : /************************************************************************/
    6399             : 
    6400          11 : bool GDALGeoPackageDataset::RegisterWebPExtension()
    6401             : {
    6402          11 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6403           0 :         return false;
    6404             : 
    6405          11 :     char *pszSQL = sqlite3_mprintf(
    6406             :         "INSERT INTO gpkg_extensions "
    6407             :         "(table_name, column_name, extension_name, definition, scope) "
    6408             :         "VALUES "
    6409             :         "('%q', 'tile_data', 'gpkg_webp', "
    6410             :         "'http://www.geopackage.org/spec120/#extension_tiles_webp', "
    6411             :         "'read-write')",
    6412             :         m_osRasterTable.c_str());
    6413          11 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6414          11 :     sqlite3_free(pszSQL);
    6415             : 
    6416          11 :     return OGRERR_NONE == eErr;
    6417             : }
    6418             : 
    6419             : /************************************************************************/
    6420             : /*                       RegisterZoomOtherExtension()                   */
    6421             : /************************************************************************/
    6422             : 
    6423           1 : bool GDALGeoPackageDataset::RegisterZoomOtherExtension()
    6424             : {
    6425           1 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6426           0 :         return false;
    6427             : 
    6428           1 :     char *pszSQL = sqlite3_mprintf(
    6429             :         "INSERT INTO gpkg_extensions "
    6430             :         "(table_name, column_name, extension_name, definition, scope) "
    6431             :         "VALUES "
    6432             :         "('%q', 'tile_data', 'gpkg_zoom_other', "
    6433             :         "'http://www.geopackage.org/spec120/#extension_zoom_other_intervals', "
    6434             :         "'read-write')",
    6435             :         m_osRasterTable.c_str());
    6436           1 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6437           1 :     sqlite3_free(pszSQL);
    6438           1 :     return OGRERR_NONE == eErr;
    6439             : }
    6440             : 
    6441             : /************************************************************************/
    6442             : /*                              GetLayer()                              */
    6443             : /************************************************************************/
    6444             : 
    6445       15901 : const OGRLayer *GDALGeoPackageDataset::GetLayer(int iLayer) const
    6446             : 
    6447             : {
    6448       15901 :     if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
    6449           7 :         return nullptr;
    6450             :     else
    6451       15894 :         return m_apoLayers[iLayer].get();
    6452             : }
    6453             : 
    6454             : /************************************************************************/
    6455             : /*                           LaunderName()                              */
    6456             : /************************************************************************/
    6457             : 
    6458             : /** Launder identifiers (table, column names) according to guidance at
    6459             :  * https://www.geopackage.org/guidance/getting-started.html:
    6460             :  * "For maximum interoperability, start your database identifiers (table names,
    6461             :  * column names, etc.) with a lowercase character and only use lowercase
    6462             :  * characters, numbers 0-9, and underscores (_)."
    6463             :  */
    6464             : 
    6465             : /* static */
    6466           5 : std::string GDALGeoPackageDataset::LaunderName(const std::string &osStr)
    6467             : {
    6468           5 :     char *pszASCII = CPLUTF8ForceToASCII(osStr.c_str(), '_');
    6469          10 :     const std::string osStrASCII(pszASCII);
    6470           5 :     CPLFree(pszASCII);
    6471             : 
    6472          10 :     std::string osRet;
    6473           5 :     osRet.reserve(osStrASCII.size());
    6474             : 
    6475          29 :     for (size_t i = 0; i < osStrASCII.size(); ++i)
    6476             :     {
    6477          24 :         if (osRet.empty())
    6478             :         {
    6479           5 :             if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6480             :             {
    6481           2 :                 osRet += (osStrASCII[i] - 'A' + 'a');
    6482             :             }
    6483           3 :             else if (osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z')
    6484             :             {
    6485           2 :                 osRet += osStrASCII[i];
    6486             :             }
    6487             :             else
    6488             :             {
    6489           1 :                 continue;
    6490             :             }
    6491             :         }
    6492          19 :         else if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6493             :         {
    6494          11 :             osRet += (osStrASCII[i] - 'A' + 'a');
    6495             :         }
    6496           9 :         else if ((osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z') ||
    6497          14 :                  (osStrASCII[i] >= '0' && osStrASCII[i] <= '9') ||
    6498           5 :                  osStrASCII[i] == '_')
    6499             :         {
    6500           7 :             osRet += osStrASCII[i];
    6501             :         }
    6502             :         else
    6503             :         {
    6504           1 :             osRet += '_';
    6505             :         }
    6506             :     }
    6507             : 
    6508           5 :     if (osRet.empty() && !osStrASCII.empty())
    6509           2 :         return LaunderName(std::string("x").append(osStrASCII));
    6510             : 
    6511           4 :     if (osRet != osStr)
    6512             :     {
    6513           3 :         CPLDebug("PG", "LaunderName('%s') -> '%s'", osStr.c_str(),
    6514             :                  osRet.c_str());
    6515             :     }
    6516             : 
    6517           4 :     return osRet;
    6518             : }
    6519             : 
    6520             : /************************************************************************/
    6521             : /*                          ICreateLayer()                              */
    6522             : /************************************************************************/
    6523             : 
    6524             : OGRLayer *
    6525         844 : GDALGeoPackageDataset::ICreateLayer(const char *pszLayerName,
    6526             :                                     const OGRGeomFieldDefn *poSrcGeomFieldDefn,
    6527             :                                     CSLConstList papszOptions)
    6528             : {
    6529             :     /* -------------------------------------------------------------------- */
    6530             :     /*      Verify we are in update mode.                                   */
    6531             :     /* -------------------------------------------------------------------- */
    6532         844 :     if (!GetUpdate())
    6533             :     {
    6534           0 :         CPLError(CE_Failure, CPLE_NoWriteAccess,
    6535             :                  "Data source %s opened read-only.\n"
    6536             :                  "New layer %s cannot be created.\n",
    6537             :                  m_pszFilename, pszLayerName);
    6538             : 
    6539           0 :         return nullptr;
    6540             :     }
    6541             : 
    6542             :     const bool bLaunder =
    6543         844 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "LAUNDER", "NO"));
    6544             :     const std::string osTableName(bLaunder ? LaunderName(pszLayerName)
    6545        2532 :                                            : std::string(pszLayerName));
    6546             : 
    6547             :     const auto eGType =
    6548         844 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
    6549             :     const auto poSpatialRef =
    6550         844 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
    6551             : 
    6552         844 :     if (!m_bHasGPKGGeometryColumns)
    6553             :     {
    6554           1 :         if (SQLCommand(hDB, pszCREATE_GPKG_GEOMETRY_COLUMNS) != OGRERR_NONE)
    6555             :         {
    6556           0 :             return nullptr;
    6557             :         }
    6558           1 :         m_bHasGPKGGeometryColumns = true;
    6559             :     }
    6560             : 
    6561             :     // Check identifier unicity
    6562         844 :     const char *pszIdentifier = CSLFetchNameValue(papszOptions, "IDENTIFIER");
    6563         844 :     if (pszIdentifier != nullptr && pszIdentifier[0] == '\0')
    6564           0 :         pszIdentifier = nullptr;
    6565         844 :     if (pszIdentifier != nullptr)
    6566             :     {
    6567          13 :         for (auto &poLayer : m_apoLayers)
    6568             :         {
    6569             :             const char *pszOtherIdentifier =
    6570           9 :                 poLayer->GetMetadataItem("IDENTIFIER");
    6571           9 :             if (pszOtherIdentifier == nullptr)
    6572           6 :                 pszOtherIdentifier = poLayer->GetName();
    6573          18 :             if (pszOtherIdentifier != nullptr &&
    6574          12 :                 EQUAL(pszOtherIdentifier, pszIdentifier) &&
    6575           3 :                 !EQUAL(poLayer->GetName(), osTableName.c_str()))
    6576             :             {
    6577           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6578             :                          "Identifier %s is already used by table %s",
    6579             :                          pszIdentifier, poLayer->GetName());
    6580           2 :                 return nullptr;
    6581             :             }
    6582             :         }
    6583             : 
    6584             :         // In case there would be table in gpkg_contents not listed as a
    6585             :         // vector layer
    6586           4 :         char *pszSQL = sqlite3_mprintf(
    6587             :             "SELECT table_name FROM gpkg_contents WHERE identifier = '%q' "
    6588             :             "LIMIT 2",
    6589             :             pszIdentifier);
    6590           4 :         auto oResult = SQLQuery(hDB, pszSQL);
    6591           4 :         sqlite3_free(pszSQL);
    6592           8 :         if (oResult && oResult->RowCount() > 0 &&
    6593           9 :             oResult->GetValue(0, 0) != nullptr &&
    6594           1 :             !EQUAL(oResult->GetValue(0, 0), osTableName.c_str()))
    6595             :         {
    6596           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6597             :                      "Identifier %s is already used by table %s", pszIdentifier,
    6598             :                      oResult->GetValue(0, 0));
    6599           1 :             return nullptr;
    6600             :         }
    6601             :     }
    6602             : 
    6603             :     /* Read GEOMETRY_NAME option */
    6604             :     const char *pszGeomColumnName =
    6605         841 :         CSLFetchNameValue(papszOptions, "GEOMETRY_NAME");
    6606         841 :     if (pszGeomColumnName == nullptr) /* deprecated name */
    6607         758 :         pszGeomColumnName = CSLFetchNameValue(papszOptions, "GEOMETRY_COLUMN");
    6608         841 :     if (pszGeomColumnName == nullptr && poSrcGeomFieldDefn)
    6609             :     {
    6610         681 :         pszGeomColumnName = poSrcGeomFieldDefn->GetNameRef();
    6611         681 :         if (pszGeomColumnName && pszGeomColumnName[0] == 0)
    6612         677 :             pszGeomColumnName = nullptr;
    6613             :     }
    6614         841 :     if (pszGeomColumnName == nullptr)
    6615         754 :         pszGeomColumnName = "geom";
    6616             :     const bool bGeomNullable =
    6617         841 :         CPLFetchBool(papszOptions, "GEOMETRY_NULLABLE", true);
    6618             : 
    6619             :     /* Read FID option */
    6620         841 :     const char *pszFIDColumnName = CSLFetchNameValue(papszOptions, "FID");
    6621         841 :     if (pszFIDColumnName == nullptr)
    6622         764 :         pszFIDColumnName = "fid";
    6623             : 
    6624         841 :     if (CPLTestBool(CPLGetConfigOption("GPKG_NAME_CHECK", "YES")))
    6625             :     {
    6626         841 :         if (strspn(pszFIDColumnName, "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") > 0)
    6627             :         {
    6628           2 :             CPLError(CE_Failure, CPLE_AppDefined,
    6629             :                      "The primary key (%s) name may not contain special "
    6630             :                      "characters or spaces",
    6631             :                      pszFIDColumnName);
    6632           2 :             return nullptr;
    6633             :         }
    6634             : 
    6635             :         /* Avoiding gpkg prefixes is not an official requirement, but seems wise
    6636             :          */
    6637         839 :         if (STARTS_WITH(osTableName.c_str(), "gpkg"))
    6638             :         {
    6639           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6640             :                      "The layer name may not begin with 'gpkg' as it is a "
    6641             :                      "reserved geopackage prefix");
    6642           0 :             return nullptr;
    6643             :         }
    6644             : 
    6645             :         /* Preemptively try and avoid sqlite3 syntax errors due to  */
    6646             :         /* illegal characters. */
    6647         839 :         if (strspn(osTableName.c_str(), "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") >
    6648             :             0)
    6649             :         {
    6650           0 :             CPLError(
    6651             :                 CE_Failure, CPLE_AppDefined,
    6652             :                 "The layer name may not contain special characters or spaces");
    6653           0 :             return nullptr;
    6654             :         }
    6655             :     }
    6656             : 
    6657             :     /* Check for any existing layers that already use this name */
    6658        1047 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6659             :          iLayer++)
    6660             :     {
    6661         209 :         if (EQUAL(osTableName.c_str(), m_apoLayers[iLayer]->GetName()))
    6662             :         {
    6663             :             const char *pszOverwrite =
    6664           2 :                 CSLFetchNameValue(papszOptions, "OVERWRITE");
    6665           2 :             if (pszOverwrite != nullptr && CPLTestBool(pszOverwrite))
    6666             :             {
    6667           1 :                 DeleteLayer(iLayer);
    6668             :             }
    6669             :             else
    6670             :             {
    6671           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6672             :                          "Layer %s already exists, CreateLayer failed.\n"
    6673             :                          "Use the layer creation option OVERWRITE=YES to "
    6674             :                          "replace it.",
    6675             :                          osTableName.c_str());
    6676           1 :                 return nullptr;
    6677             :             }
    6678             :         }
    6679             :     }
    6680             : 
    6681         838 :     if (m_apoLayers.size() == 1)
    6682             :     {
    6683             :         // Async RTree building doesn't play well with multiple layer:
    6684             :         // SQLite3 locks being hold for a long time, random failed commits,
    6685             :         // etc.
    6686          82 :         m_apoLayers[0]->FinishOrDisableThreadedRTree();
    6687             :     }
    6688             : 
    6689             :     /* Create a blank layer. */
    6690             :     auto poLayer =
    6691        1676 :         std::make_unique<OGRGeoPackageTableLayer>(this, osTableName.c_str());
    6692             : 
    6693         838 :     OGRSpatialReference *poSRS = nullptr;
    6694         838 :     if (poSpatialRef)
    6695             :     {
    6696         251 :         poSRS = poSpatialRef->Clone();
    6697         251 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    6698             :     }
    6699        1677 :     poLayer->SetCreationParameters(
    6700             :         eGType,
    6701         839 :         bLaunder ? LaunderName(pszGeomColumnName).c_str() : pszGeomColumnName,
    6702             :         bGeomNullable, poSRS, CSLFetchNameValue(papszOptions, "SRID"),
    6703        1676 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetCoordinatePrecision()
    6704             :                            : OGRGeomCoordinatePrecision(),
    6705         838 :         CPLTestBool(
    6706             :             CSLFetchNameValueDef(papszOptions, "DISCARD_COORD_LSB", "NO")),
    6707         838 :         CPLTestBool(CSLFetchNameValueDef(
    6708             :             papszOptions, "UNDO_DISCARD_COORD_LSB_ON_READING", "NO")),
    6709         839 :         bLaunder ? LaunderName(pszFIDColumnName).c_str() : pszFIDColumnName,
    6710             :         pszIdentifier, CSLFetchNameValue(papszOptions, "DESCRIPTION"));
    6711         838 :     if (poSRS)
    6712             :     {
    6713         251 :         poSRS->Release();
    6714             :     }
    6715             : 
    6716         838 :     poLayer->SetLaunder(bLaunder);
    6717             : 
    6718             :     /* Should we create a spatial index ? */
    6719         838 :     const char *pszSI = CSLFetchNameValue(papszOptions, "SPATIAL_INDEX");
    6720         838 :     int bCreateSpatialIndex = (pszSI == nullptr || CPLTestBool(pszSI));
    6721         838 :     if (eGType != wkbNone && bCreateSpatialIndex)
    6722             :     {
    6723         739 :         poLayer->SetDeferredSpatialIndexCreation(true);
    6724             :     }
    6725             : 
    6726         838 :     poLayer->SetPrecisionFlag(CPLFetchBool(papszOptions, "PRECISION", true));
    6727         838 :     poLayer->SetTruncateFieldsFlag(
    6728         838 :         CPLFetchBool(papszOptions, "TRUNCATE_FIELDS", false));
    6729         838 :     if (eGType == wkbNone)
    6730             :     {
    6731          77 :         const char *pszASpatialVariant = CSLFetchNameValueDef(
    6732             :             papszOptions, "ASPATIAL_VARIANT",
    6733          77 :             m_bNonSpatialTablesNonRegisteredInGpkgContentsFound
    6734             :                 ? "NOT_REGISTERED"
    6735             :                 : "GPKG_ATTRIBUTES");
    6736          77 :         GPKGASpatialVariant eASpatialVariant = GPKG_ATTRIBUTES;
    6737          77 :         if (EQUAL(pszASpatialVariant, "GPKG_ATTRIBUTES"))
    6738          65 :             eASpatialVariant = GPKG_ATTRIBUTES;
    6739          12 :         else if (EQUAL(pszASpatialVariant, "OGR_ASPATIAL"))
    6740             :         {
    6741           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6742             :                      "ASPATIAL_VARIANT=OGR_ASPATIAL is no longer supported");
    6743           0 :             return nullptr;
    6744             :         }
    6745          12 :         else if (EQUAL(pszASpatialVariant, "NOT_REGISTERED"))
    6746          12 :             eASpatialVariant = NOT_REGISTERED;
    6747             :         else
    6748             :         {
    6749           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6750             :                      "Unsupported value for ASPATIAL_VARIANT: %s",
    6751             :                      pszASpatialVariant);
    6752           0 :             return nullptr;
    6753             :         }
    6754          77 :         poLayer->SetASpatialVariant(eASpatialVariant);
    6755             :     }
    6756             : 
    6757             :     const char *pszDateTimePrecision =
    6758         838 :         CSLFetchNameValueDef(papszOptions, "DATETIME_PRECISION", "AUTO");
    6759         838 :     if (EQUAL(pszDateTimePrecision, "MILLISECOND"))
    6760             :     {
    6761           2 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6762             :     }
    6763         836 :     else if (EQUAL(pszDateTimePrecision, "SECOND"))
    6764             :     {
    6765           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6766           0 :             CPLError(
    6767             :                 CE_Warning, CPLE_AppDefined,
    6768             :                 "DATETIME_PRECISION=SECOND is only valid since GeoPackage 1.4");
    6769           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::SECOND);
    6770             :     }
    6771         835 :     else if (EQUAL(pszDateTimePrecision, "MINUTE"))
    6772             :     {
    6773           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6774           0 :             CPLError(
    6775             :                 CE_Warning, CPLE_AppDefined,
    6776             :                 "DATETIME_PRECISION=MINUTE is only valid since GeoPackage 1.4");
    6777           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MINUTE);
    6778             :     }
    6779         834 :     else if (EQUAL(pszDateTimePrecision, "AUTO"))
    6780             :     {
    6781         833 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6782          13 :             poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6783             :     }
    6784             :     else
    6785             :     {
    6786           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    6787             :                  "Unsupported value for DATETIME_PRECISION: %s",
    6788             :                  pszDateTimePrecision);
    6789           1 :         return nullptr;
    6790             :     }
    6791             : 
    6792             :     // If there was an ogr_empty_table table, we can remove it
    6793             :     // But do it at dataset closing, otherwise locking performance issues
    6794             :     // can arise (probably when transactions are used).
    6795         837 :     m_bRemoveOGREmptyTable = true;
    6796             : 
    6797         837 :     m_apoLayers.emplace_back(std::move(poLayer));
    6798         837 :     return m_apoLayers.back().get();
    6799             : }
    6800             : 
    6801             : /************************************************************************/
    6802             : /*                          FindLayerIndex()                            */
    6803             : /************************************************************************/
    6804             : 
    6805          27 : int GDALGeoPackageDataset::FindLayerIndex(const char *pszLayerName)
    6806             : 
    6807             : {
    6808          42 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6809             :          iLayer++)
    6810             :     {
    6811          28 :         if (EQUAL(pszLayerName, m_apoLayers[iLayer]->GetName()))
    6812          13 :             return iLayer;
    6813             :     }
    6814          14 :     return -1;
    6815             : }
    6816             : 
    6817             : /************************************************************************/
    6818             : /*                       DeleteLayerCommon()                            */
    6819             : /************************************************************************/
    6820             : 
    6821          41 : OGRErr GDALGeoPackageDataset::DeleteLayerCommon(const char *pszLayerName)
    6822             : {
    6823             :     // Temporary remove foreign key checks
    6824             :     const GPKGTemporaryForeignKeyCheckDisabler
    6825          41 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6826             : 
    6827          41 :     char *pszSQL = sqlite3_mprintf(
    6828             :         "DELETE FROM gpkg_contents WHERE lower(table_name) = lower('%q')",
    6829             :         pszLayerName);
    6830          41 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    6831          41 :     sqlite3_free(pszSQL);
    6832             : 
    6833          41 :     if (eErr == OGRERR_NONE && HasExtensionsTable())
    6834             :     {
    6835          39 :         pszSQL = sqlite3_mprintf(
    6836             :             "DELETE FROM gpkg_extensions WHERE lower(table_name) = lower('%q')",
    6837             :             pszLayerName);
    6838          39 :         eErr = SQLCommand(hDB, pszSQL);
    6839          39 :         sqlite3_free(pszSQL);
    6840             :     }
    6841             : 
    6842          41 :     if (eErr == OGRERR_NONE && HasMetadataTables())
    6843             :     {
    6844             :         // Delete from gpkg_metadata metadata records that are only referenced
    6845             :         // by the table we are about to drop
    6846          11 :         pszSQL = sqlite3_mprintf(
    6847             :             "DELETE FROM gpkg_metadata WHERE id IN ("
    6848             :             "SELECT DISTINCT md_file_id FROM "
    6849             :             "gpkg_metadata_reference WHERE "
    6850             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6851             :             "AND id NOT IN ("
    6852             :             "SELECT DISTINCT md_file_id FROM gpkg_metadata_reference WHERE "
    6853             :             "md_file_id IN (SELECT DISTINCT md_file_id FROM "
    6854             :             "gpkg_metadata_reference WHERE "
    6855             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6856             :             "AND lower(table_name) <> lower('%q'))",
    6857             :             pszLayerName, pszLayerName, pszLayerName);
    6858          11 :         eErr = SQLCommand(hDB, pszSQL);
    6859          11 :         sqlite3_free(pszSQL);
    6860             : 
    6861          11 :         if (eErr == OGRERR_NONE)
    6862             :         {
    6863             :             pszSQL =
    6864          11 :                 sqlite3_mprintf("DELETE FROM gpkg_metadata_reference WHERE "
    6865             :                                 "lower(table_name) = lower('%q')",
    6866             :                                 pszLayerName);
    6867          11 :             eErr = SQLCommand(hDB, pszSQL);
    6868          11 :             sqlite3_free(pszSQL);
    6869             :         }
    6870             :     }
    6871             : 
    6872          41 :     if (eErr == OGRERR_NONE && HasGpkgextRelationsTable())
    6873             :     {
    6874             :         // Remove reference to potential corresponding mapping table in
    6875             :         // gpkg_extensions
    6876           4 :         pszSQL = sqlite3_mprintf(
    6877             :             "DELETE FROM gpkg_extensions WHERE "
    6878             :             "extension_name IN ('related_tables', "
    6879             :             "'gpkg_related_tables') AND lower(table_name) = "
    6880             :             "(SELECT lower(mapping_table_name) FROM gpkgext_relations WHERE "
    6881             :             "lower(base_table_name) = lower('%q') OR "
    6882             :             "lower(related_table_name) = lower('%q') OR "
    6883             :             "lower(mapping_table_name) = lower('%q'))",
    6884             :             pszLayerName, pszLayerName, pszLayerName);
    6885           4 :         eErr = SQLCommand(hDB, pszSQL);
    6886           4 :         sqlite3_free(pszSQL);
    6887             : 
    6888           4 :         if (eErr == OGRERR_NONE)
    6889             :         {
    6890             :             // Remove reference to potential corresponding mapping table in
    6891             :             // gpkgext_relations
    6892             :             pszSQL =
    6893           4 :                 sqlite3_mprintf("DELETE FROM gpkgext_relations WHERE "
    6894             :                                 "lower(base_table_name) = lower('%q') OR "
    6895             :                                 "lower(related_table_name) = lower('%q') OR "
    6896             :                                 "lower(mapping_table_name) = lower('%q')",
    6897             :                                 pszLayerName, pszLayerName, pszLayerName);
    6898           4 :             eErr = SQLCommand(hDB, pszSQL);
    6899           4 :             sqlite3_free(pszSQL);
    6900             :         }
    6901             : 
    6902           4 :         if (eErr == OGRERR_NONE && HasExtensionsTable())
    6903             :         {
    6904             :             // If there is no longer any mapping table, then completely
    6905             :             // remove any reference to the extension in gpkg_extensions
    6906             :             // as mandated per the related table specification.
    6907             :             OGRErr err;
    6908           4 :             if (SQLGetInteger(hDB,
    6909             :                               "SELECT COUNT(*) FROM gpkg_extensions WHERE "
    6910             :                               "extension_name IN ('related_tables', "
    6911             :                               "'gpkg_related_tables') AND "
    6912             :                               "lower(table_name) != 'gpkgext_relations'",
    6913           4 :                               &err) == 0)
    6914             :             {
    6915           2 :                 eErr = SQLCommand(hDB, "DELETE FROM gpkg_extensions WHERE "
    6916             :                                        "extension_name IN ('related_tables', "
    6917             :                                        "'gpkg_related_tables')");
    6918             :             }
    6919             : 
    6920           4 :             ClearCachedRelationships();
    6921             :         }
    6922             :     }
    6923             : 
    6924          41 :     if (eErr == OGRERR_NONE)
    6925             :     {
    6926          41 :         pszSQL = sqlite3_mprintf("DROP TABLE \"%w\"", pszLayerName);
    6927          41 :         eErr = SQLCommand(hDB, pszSQL);
    6928          41 :         sqlite3_free(pszSQL);
    6929             :     }
    6930             : 
    6931             :     // Check foreign key integrity
    6932          41 :     if (eErr == OGRERR_NONE)
    6933             :     {
    6934          41 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    6935             :     }
    6936             : 
    6937          82 :     return eErr;
    6938             : }
    6939             : 
    6940             : /************************************************************************/
    6941             : /*                            DeleteLayer()                             */
    6942             : /************************************************************************/
    6943             : 
    6944          38 : OGRErr GDALGeoPackageDataset::DeleteLayer(int iLayer)
    6945             : {
    6946          75 :     if (!GetUpdate() || iLayer < 0 ||
    6947          37 :         iLayer >= static_cast<int>(m_apoLayers.size()))
    6948           2 :         return OGRERR_FAILURE;
    6949             : 
    6950          36 :     m_apoLayers[iLayer]->ResetReading();
    6951          36 :     m_apoLayers[iLayer]->SyncToDisk();
    6952             : 
    6953          72 :     CPLString osLayerName = m_apoLayers[iLayer]->GetName();
    6954             : 
    6955          36 :     CPLDebug("GPKG", "DeleteLayer(%s)", osLayerName.c_str());
    6956             : 
    6957             :     // Temporary remove foreign key checks
    6958             :     const GPKGTemporaryForeignKeyCheckDisabler
    6959          36 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6960             : 
    6961          36 :     OGRErr eErr = SoftStartTransaction();
    6962             : 
    6963          36 :     if (eErr == OGRERR_NONE)
    6964             :     {
    6965          36 :         if (m_apoLayers[iLayer]->HasSpatialIndex())
    6966          33 :             m_apoLayers[iLayer]->DropSpatialIndex();
    6967             : 
    6968             :         char *pszSQL =
    6969          36 :             sqlite3_mprintf("DELETE FROM gpkg_geometry_columns WHERE "
    6970             :                             "lower(table_name) = lower('%q')",
    6971             :                             osLayerName.c_str());
    6972          36 :         eErr = SQLCommand(hDB, pszSQL);
    6973          36 :         sqlite3_free(pszSQL);
    6974             :     }
    6975             : 
    6976          36 :     if (eErr == OGRERR_NONE && HasDataColumnsTable())
    6977             :     {
    6978           1 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_data_columns WHERE "
    6979             :                                        "lower(table_name) = lower('%q')",
    6980             :                                        osLayerName.c_str());
    6981           1 :         eErr = SQLCommand(hDB, pszSQL);
    6982           1 :         sqlite3_free(pszSQL);
    6983             :     }
    6984             : 
    6985             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    6986          36 :     if (eErr == OGRERR_NONE && m_bHasGPKGOGRContents)
    6987             :     {
    6988          36 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_ogr_contents WHERE "
    6989             :                                        "lower(table_name) = lower('%q')",
    6990             :                                        osLayerName.c_str());
    6991          36 :         eErr = SQLCommand(hDB, pszSQL);
    6992          36 :         sqlite3_free(pszSQL);
    6993             :     }
    6994             : #endif
    6995             : 
    6996          36 :     if (eErr == OGRERR_NONE)
    6997             :     {
    6998          36 :         eErr = DeleteLayerCommon(osLayerName.c_str());
    6999             :     }
    7000             : 
    7001          36 :     if (eErr == OGRERR_NONE)
    7002             :     {
    7003          36 :         eErr = SoftCommitTransaction();
    7004          36 :         if (eErr == OGRERR_NONE)
    7005             :         {
    7006             :             /* Delete the layer object */
    7007          36 :             m_apoLayers.erase(m_apoLayers.begin() + iLayer);
    7008             :         }
    7009             :     }
    7010             :     else
    7011             :     {
    7012           0 :         SoftRollbackTransaction();
    7013             :     }
    7014             : 
    7015          36 :     return eErr;
    7016             : }
    7017             : 
    7018             : /************************************************************************/
    7019             : /*                       DeleteRasterLayer()                            */
    7020             : /************************************************************************/
    7021             : 
    7022           2 : OGRErr GDALGeoPackageDataset::DeleteRasterLayer(const char *pszLayerName)
    7023             : {
    7024             :     // Temporary remove foreign key checks
    7025             :     const GPKGTemporaryForeignKeyCheckDisabler
    7026           2 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7027             : 
    7028           2 :     OGRErr eErr = SoftStartTransaction();
    7029             : 
    7030           2 :     if (eErr == OGRERR_NONE)
    7031             :     {
    7032           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix WHERE "
    7033             :                                        "lower(table_name) = lower('%q')",
    7034             :                                        pszLayerName);
    7035           2 :         eErr = SQLCommand(hDB, pszSQL);
    7036           2 :         sqlite3_free(pszSQL);
    7037             :     }
    7038             : 
    7039           2 :     if (eErr == OGRERR_NONE)
    7040             :     {
    7041           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix_set WHERE "
    7042             :                                        "lower(table_name) = lower('%q')",
    7043             :                                        pszLayerName);
    7044           2 :         eErr = SQLCommand(hDB, pszSQL);
    7045           2 :         sqlite3_free(pszSQL);
    7046             :     }
    7047             : 
    7048           2 :     if (eErr == OGRERR_NONE && HasGriddedCoverageAncillaryTable())
    7049             :     {
    7050             :         char *pszSQL =
    7051           1 :             sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_coverage_ancillary "
    7052             :                             "WHERE lower(tile_matrix_set_name) = lower('%q')",
    7053             :                             pszLayerName);
    7054           1 :         eErr = SQLCommand(hDB, pszSQL);
    7055           1 :         sqlite3_free(pszSQL);
    7056             : 
    7057           1 :         if (eErr == OGRERR_NONE)
    7058             :         {
    7059             :             pszSQL =
    7060           1 :                 sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_tile_ancillary "
    7061             :                                 "WHERE lower(tpudt_name) = lower('%q')",
    7062             :                                 pszLayerName);
    7063           1 :             eErr = SQLCommand(hDB, pszSQL);
    7064           1 :             sqlite3_free(pszSQL);
    7065             :         }
    7066             :     }
    7067             : 
    7068           2 :     if (eErr == OGRERR_NONE)
    7069             :     {
    7070           2 :         eErr = DeleteLayerCommon(pszLayerName);
    7071             :     }
    7072             : 
    7073           2 :     if (eErr == OGRERR_NONE)
    7074             :     {
    7075           2 :         eErr = SoftCommitTransaction();
    7076             :     }
    7077             :     else
    7078             :     {
    7079           0 :         SoftRollbackTransaction();
    7080             :     }
    7081             : 
    7082           4 :     return eErr;
    7083             : }
    7084             : 
    7085             : /************************************************************************/
    7086             : /*                    DeleteVectorOrRasterLayer()                       */
    7087             : /************************************************************************/
    7088             : 
    7089          13 : bool GDALGeoPackageDataset::DeleteVectorOrRasterLayer(const char *pszLayerName)
    7090             : {
    7091             : 
    7092          13 :     int idx = FindLayerIndex(pszLayerName);
    7093          13 :     if (idx >= 0)
    7094             :     {
    7095           5 :         DeleteLayer(idx);
    7096           5 :         return true;
    7097             :     }
    7098             : 
    7099             :     char *pszSQL =
    7100           8 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7101             :                         "lower(table_name) = lower('%q') "
    7102             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7103             :                         pszLayerName);
    7104           8 :     bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7105           8 :     sqlite3_free(pszSQL);
    7106           8 :     if (bIsRasterTable)
    7107             :     {
    7108           2 :         DeleteRasterLayer(pszLayerName);
    7109           2 :         return true;
    7110             :     }
    7111           6 :     return false;
    7112             : }
    7113             : 
    7114           7 : bool GDALGeoPackageDataset::RenameVectorOrRasterLayer(
    7115             :     const char *pszLayerName, const char *pszNewLayerName)
    7116             : {
    7117           7 :     int idx = FindLayerIndex(pszLayerName);
    7118           7 :     if (idx >= 0)
    7119             :     {
    7120           4 :         m_apoLayers[idx]->Rename(pszNewLayerName);
    7121           4 :         return true;
    7122             :     }
    7123             : 
    7124             :     char *pszSQL =
    7125           3 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7126             :                         "lower(table_name) = lower('%q') "
    7127             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7128             :                         pszLayerName);
    7129           3 :     const bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7130           3 :     sqlite3_free(pszSQL);
    7131             : 
    7132           3 :     if (bIsRasterTable)
    7133             :     {
    7134           2 :         return RenameRasterLayer(pszLayerName, pszNewLayerName);
    7135             :     }
    7136             : 
    7137           1 :     return false;
    7138             : }
    7139             : 
    7140           2 : bool GDALGeoPackageDataset::RenameRasterLayer(const char *pszLayerName,
    7141             :                                               const char *pszNewLayerName)
    7142             : {
    7143           4 :     std::string osSQL;
    7144             : 
    7145           2 :     char *pszSQL = sqlite3_mprintf(
    7146             :         "SELECT 1 FROM sqlite_master WHERE lower(name) = lower('%q') "
    7147             :         "AND type IN ('table', 'view')",
    7148             :         pszNewLayerName);
    7149           2 :     const bool bAlreadyExists = SQLGetInteger(GetDB(), pszSQL, nullptr) == 1;
    7150           2 :     sqlite3_free(pszSQL);
    7151           2 :     if (bAlreadyExists)
    7152             :     {
    7153           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Table %s already exists",
    7154             :                  pszNewLayerName);
    7155           0 :         return false;
    7156             :     }
    7157             : 
    7158             :     // Temporary remove foreign key checks
    7159             :     const GPKGTemporaryForeignKeyCheckDisabler
    7160           4 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7161             : 
    7162           2 :     if (SoftStartTransaction() != OGRERR_NONE)
    7163             :     {
    7164           0 :         return false;
    7165             :     }
    7166             : 
    7167           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET table_name = '%q' WHERE "
    7168             :                              "lower(table_name) = lower('%q');",
    7169             :                              pszNewLayerName, pszLayerName);
    7170           2 :     osSQL = pszSQL;
    7171           2 :     sqlite3_free(pszSQL);
    7172             : 
    7173           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' WHERE "
    7174             :                              "lower(identifier) = lower('%q');",
    7175             :                              pszNewLayerName, pszLayerName);
    7176           2 :     osSQL += pszSQL;
    7177           2 :     sqlite3_free(pszSQL);
    7178             : 
    7179             :     pszSQL =
    7180           2 :         sqlite3_mprintf("UPDATE gpkg_tile_matrix SET table_name = '%q' WHERE "
    7181             :                         "lower(table_name) = lower('%q');",
    7182             :                         pszNewLayerName, pszLayerName);
    7183           2 :     osSQL += pszSQL;
    7184           2 :     sqlite3_free(pszSQL);
    7185             : 
    7186           2 :     pszSQL = sqlite3_mprintf(
    7187             :         "UPDATE gpkg_tile_matrix_set SET table_name = '%q' WHERE "
    7188             :         "lower(table_name) = lower('%q');",
    7189             :         pszNewLayerName, pszLayerName);
    7190           2 :     osSQL += pszSQL;
    7191           2 :     sqlite3_free(pszSQL);
    7192             : 
    7193           2 :     if (HasGriddedCoverageAncillaryTable())
    7194             :     {
    7195           1 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_2d_gridded_coverage_ancillary "
    7196             :                                  "SET tile_matrix_set_name = '%q' WHERE "
    7197             :                                  "lower(tile_matrix_set_name) = lower('%q');",
    7198             :                                  pszNewLayerName, pszLayerName);
    7199           1 :         osSQL += pszSQL;
    7200           1 :         sqlite3_free(pszSQL);
    7201             : 
    7202           1 :         pszSQL = sqlite3_mprintf(
    7203             :             "UPDATE gpkg_2d_gridded_tile_ancillary SET tpudt_name = '%q' WHERE "
    7204             :             "lower(tpudt_name) = lower('%q');",
    7205             :             pszNewLayerName, pszLayerName);
    7206           1 :         osSQL += pszSQL;
    7207           1 :         sqlite3_free(pszSQL);
    7208             :     }
    7209             : 
    7210           2 :     if (HasExtensionsTable())
    7211             :     {
    7212           2 :         pszSQL = sqlite3_mprintf(
    7213             :             "UPDATE gpkg_extensions SET table_name = '%q' WHERE "
    7214             :             "lower(table_name) = lower('%q');",
    7215             :             pszNewLayerName, pszLayerName);
    7216           2 :         osSQL += pszSQL;
    7217           2 :         sqlite3_free(pszSQL);
    7218             :     }
    7219             : 
    7220           2 :     if (HasMetadataTables())
    7221             :     {
    7222           1 :         pszSQL = sqlite3_mprintf(
    7223             :             "UPDATE gpkg_metadata_reference SET table_name = '%q' WHERE "
    7224             :             "lower(table_name) = lower('%q');",
    7225             :             pszNewLayerName, pszLayerName);
    7226           1 :         osSQL += pszSQL;
    7227           1 :         sqlite3_free(pszSQL);
    7228             :     }
    7229             : 
    7230           2 :     if (HasDataColumnsTable())
    7231             :     {
    7232           0 :         pszSQL = sqlite3_mprintf(
    7233             :             "UPDATE gpkg_data_columns SET table_name = '%q' WHERE "
    7234             :             "lower(table_name) = lower('%q');",
    7235             :             pszNewLayerName, pszLayerName);
    7236           0 :         osSQL += pszSQL;
    7237           0 :         sqlite3_free(pszSQL);
    7238             :     }
    7239             : 
    7240           2 :     if (HasQGISLayerStyles())
    7241             :     {
    7242             :         // Update QGIS styles
    7243             :         pszSQL =
    7244           0 :             sqlite3_mprintf("UPDATE layer_styles SET f_table_name = '%q' WHERE "
    7245             :                             "lower(f_table_name) = lower('%q');",
    7246             :                             pszNewLayerName, pszLayerName);
    7247           0 :         osSQL += pszSQL;
    7248           0 :         sqlite3_free(pszSQL);
    7249             :     }
    7250             : 
    7251             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7252           2 :     if (m_bHasGPKGOGRContents)
    7253             :     {
    7254           2 :         pszSQL = sqlite3_mprintf(
    7255             :             "UPDATE gpkg_ogr_contents SET table_name = '%q' WHERE "
    7256             :             "lower(table_name) = lower('%q');",
    7257             :             pszNewLayerName, pszLayerName);
    7258           2 :         osSQL += pszSQL;
    7259           2 :         sqlite3_free(pszSQL);
    7260             :     }
    7261             : #endif
    7262             : 
    7263           2 :     if (HasGpkgextRelationsTable())
    7264             :     {
    7265           0 :         pszSQL = sqlite3_mprintf(
    7266             :             "UPDATE gpkgext_relations SET base_table_name = '%q' WHERE "
    7267             :             "lower(base_table_name) = lower('%q');",
    7268             :             pszNewLayerName, pszLayerName);
    7269           0 :         osSQL += pszSQL;
    7270           0 :         sqlite3_free(pszSQL);
    7271             : 
    7272           0 :         pszSQL = sqlite3_mprintf(
    7273             :             "UPDATE gpkgext_relations SET related_table_name = '%q' WHERE "
    7274             :             "lower(related_table_name) = lower('%q');",
    7275             :             pszNewLayerName, pszLayerName);
    7276           0 :         osSQL += pszSQL;
    7277           0 :         sqlite3_free(pszSQL);
    7278             : 
    7279           0 :         pszSQL = sqlite3_mprintf(
    7280             :             "UPDATE gpkgext_relations SET mapping_table_name = '%q' WHERE "
    7281             :             "lower(mapping_table_name) = lower('%q');",
    7282             :             pszNewLayerName, pszLayerName);
    7283           0 :         osSQL += pszSQL;
    7284           0 :         sqlite3_free(pszSQL);
    7285             :     }
    7286             : 
    7287             :     // Drop all triggers for the layer
    7288           2 :     pszSQL = sqlite3_mprintf("SELECT name FROM sqlite_master WHERE type = "
    7289             :                              "'trigger' AND tbl_name = '%q'",
    7290             :                              pszLayerName);
    7291           2 :     auto oTriggerResult = SQLQuery(GetDB(), pszSQL);
    7292           2 :     sqlite3_free(pszSQL);
    7293           2 :     if (oTriggerResult)
    7294             :     {
    7295          14 :         for (int i = 0; i < oTriggerResult->RowCount(); i++)
    7296             :         {
    7297          12 :             const char *pszTriggerName = oTriggerResult->GetValue(0, i);
    7298          12 :             pszSQL = sqlite3_mprintf("DROP TRIGGER IF EXISTS \"%w\";",
    7299             :                                      pszTriggerName);
    7300          12 :             osSQL += pszSQL;
    7301          12 :             sqlite3_free(pszSQL);
    7302             :         }
    7303             :     }
    7304             : 
    7305           2 :     pszSQL = sqlite3_mprintf("ALTER TABLE \"%w\" RENAME TO \"%w\";",
    7306             :                              pszLayerName, pszNewLayerName);
    7307           2 :     osSQL += pszSQL;
    7308           2 :     sqlite3_free(pszSQL);
    7309             : 
    7310             :     // Recreate all zoom/tile triggers
    7311           2 :     if (oTriggerResult)
    7312             :     {
    7313           2 :         osSQL += CreateRasterTriggersSQL(pszNewLayerName);
    7314             :     }
    7315             : 
    7316           2 :     OGRErr eErr = SQLCommand(GetDB(), osSQL.c_str());
    7317             : 
    7318             :     // Check foreign key integrity
    7319           2 :     if (eErr == OGRERR_NONE)
    7320             :     {
    7321           2 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    7322             :     }
    7323             : 
    7324           2 :     if (eErr == OGRERR_NONE)
    7325             :     {
    7326           2 :         eErr = SoftCommitTransaction();
    7327             :     }
    7328             :     else
    7329             :     {
    7330           0 :         SoftRollbackTransaction();
    7331             :     }
    7332             : 
    7333           2 :     return eErr == OGRERR_NONE;
    7334             : }
    7335             : 
    7336             : /************************************************************************/
    7337             : /*                       TestCapability()                               */
    7338             : /************************************************************************/
    7339             : 
    7340         508 : int GDALGeoPackageDataset::TestCapability(const char *pszCap) const
    7341             : {
    7342         508 :     if (EQUAL(pszCap, ODsCCreateLayer) || EQUAL(pszCap, ODsCDeleteLayer) ||
    7343         329 :         EQUAL(pszCap, "RenameLayer"))
    7344             :     {
    7345         179 :         return GetUpdate();
    7346             :     }
    7347         329 :     else if (EQUAL(pszCap, ODsCCurveGeometries))
    7348          12 :         return TRUE;
    7349         317 :     else if (EQUAL(pszCap, ODsCMeasuredGeometries))
    7350           8 :         return TRUE;
    7351         309 :     else if (EQUAL(pszCap, ODsCZGeometries))
    7352           8 :         return TRUE;
    7353         301 :     else if (EQUAL(pszCap, ODsCRandomLayerWrite) ||
    7354         301 :              EQUAL(pszCap, GDsCAddRelationship) ||
    7355         301 :              EQUAL(pszCap, GDsCDeleteRelationship) ||
    7356         301 :              EQUAL(pszCap, GDsCUpdateRelationship) ||
    7357         301 :              EQUAL(pszCap, ODsCAddFieldDomain) ||
    7358         299 :              EQUAL(pszCap, ODsCUpdateFieldDomain) ||
    7359         297 :              EQUAL(pszCap, ODsCDeleteFieldDomain))
    7360             :     {
    7361           6 :         return GetUpdate();
    7362             :     }
    7363             : 
    7364         295 :     return OGRSQLiteBaseDataSource::TestCapability(pszCap);
    7365             : }
    7366             : 
    7367             : /************************************************************************/
    7368             : /*                       ResetReadingAllLayers()                        */
    7369             : /************************************************************************/
    7370             : 
    7371         205 : void GDALGeoPackageDataset::ResetReadingAllLayers()
    7372             : {
    7373         415 :     for (auto &poLayer : m_apoLayers)
    7374             :     {
    7375         210 :         poLayer->ResetReading();
    7376             :     }
    7377         205 : }
    7378             : 
    7379             : /************************************************************************/
    7380             : /*                             ExecuteSQL()                             */
    7381             : /************************************************************************/
    7382             : 
    7383             : static const char *const apszFuncsWithSideEffects[] = {
    7384             :     "CreateSpatialIndex",
    7385             :     "DisableSpatialIndex",
    7386             :     "HasSpatialIndex",
    7387             :     "RegisterGeometryExtension",
    7388             : };
    7389             : 
    7390        5652 : OGRLayer *GDALGeoPackageDataset::ExecuteSQL(const char *pszSQLCommand,
    7391             :                                             OGRGeometry *poSpatialFilter,
    7392             :                                             const char *pszDialect)
    7393             : 
    7394             : {
    7395        5652 :     m_bHasReadMetadataFromStorage = false;
    7396             : 
    7397        5652 :     FlushMetadata();
    7398             : 
    7399        5670 :     while (*pszSQLCommand != '\0' &&
    7400        5670 :            isspace(static_cast<unsigned char>(*pszSQLCommand)))
    7401          18 :         pszSQLCommand++;
    7402             : 
    7403       11304 :     CPLString osSQLCommand(pszSQLCommand);
    7404        5652 :     if (!osSQLCommand.empty() && osSQLCommand.back() == ';')
    7405          48 :         osSQLCommand.pop_back();
    7406             : 
    7407        5652 :     if (pszDialect == nullptr || !EQUAL(pszDialect, "DEBUG"))
    7408             :     {
    7409             :         // Some SQL commands will influence the feature count behind our
    7410             :         // back, so disable it in that case.
    7411             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7412             :         const bool bInsertOrDelete =
    7413        5583 :             osSQLCommand.ifind("insert into ") != std::string::npos ||
    7414        2462 :             osSQLCommand.ifind("insert or replace into ") !=
    7415        8045 :                 std::string::npos ||
    7416        2425 :             osSQLCommand.ifind("delete from ") != std::string::npos;
    7417             :         const bool bRollback =
    7418        5583 :             osSQLCommand.ifind("rollback ") != std::string::npos;
    7419             : #endif
    7420             : 
    7421        7414 :         for (auto &poLayer : m_apoLayers)
    7422             :         {
    7423        1831 :             if (poLayer->SyncToDisk() != OGRERR_NONE)
    7424           0 :                 return nullptr;
    7425             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7426        2036 :             if (bRollback ||
    7427         205 :                 (bInsertOrDelete &&
    7428         205 :                  osSQLCommand.ifind(poLayer->GetName()) != std::string::npos))
    7429             :             {
    7430         203 :                 poLayer->DisableFeatureCount();
    7431             :             }
    7432             : #endif
    7433             :         }
    7434             :     }
    7435             : 
    7436        5652 :     if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 0") ||
    7437        5651 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=0") ||
    7438        5651 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =0") ||
    7439        5651 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 0"))
    7440             :     {
    7441           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, false);
    7442             :     }
    7443        5651 :     else if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 1") ||
    7444        5650 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=1") ||
    7445        5650 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =1") ||
    7446        5650 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 1"))
    7447             :     {
    7448           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, true);
    7449             :     }
    7450             : 
    7451             :     /* -------------------------------------------------------------------- */
    7452             :     /*      DEBUG "SELECT nolock" command.                                  */
    7453             :     /* -------------------------------------------------------------------- */
    7454        5721 :     if (pszDialect != nullptr && EQUAL(pszDialect, "DEBUG") &&
    7455          69 :         EQUAL(osSQLCommand, "SELECT nolock"))
    7456             :     {
    7457           3 :         return new OGRSQLiteSingleFeatureLayer(osSQLCommand, m_bNoLock ? 1 : 0);
    7458             :     }
    7459             : 
    7460             :     /* -------------------------------------------------------------------- */
    7461             :     /*      Special case DELLAYER: command.                                 */
    7462             :     /* -------------------------------------------------------------------- */
    7463        5649 :     if (STARTS_WITH_CI(osSQLCommand, "DELLAYER:"))
    7464             :     {
    7465           4 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DELLAYER:");
    7466             : 
    7467           4 :         while (*pszLayerName == ' ')
    7468           0 :             pszLayerName++;
    7469             : 
    7470           4 :         if (!DeleteVectorOrRasterLayer(pszLayerName))
    7471             :         {
    7472           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7473             :                      pszLayerName);
    7474             :         }
    7475           4 :         return nullptr;
    7476             :     }
    7477             : 
    7478             :     /* -------------------------------------------------------------------- */
    7479             :     /*      Special case RECOMPUTE EXTENT ON command.                       */
    7480             :     /* -------------------------------------------------------------------- */
    7481        5645 :     if (STARTS_WITH_CI(osSQLCommand, "RECOMPUTE EXTENT ON "))
    7482             :     {
    7483             :         const char *pszLayerName =
    7484           4 :             osSQLCommand.c_str() + strlen("RECOMPUTE EXTENT ON ");
    7485             : 
    7486           4 :         while (*pszLayerName == ' ')
    7487           0 :             pszLayerName++;
    7488             : 
    7489           4 :         int idx = FindLayerIndex(pszLayerName);
    7490           4 :         if (idx >= 0)
    7491             :         {
    7492           4 :             m_apoLayers[idx]->RecomputeExtent();
    7493             :         }
    7494             :         else
    7495           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7496             :                      pszLayerName);
    7497           4 :         return nullptr;
    7498             :     }
    7499             : 
    7500             :     /* -------------------------------------------------------------------- */
    7501             :     /*      Intercept DROP TABLE                                            */
    7502             :     /* -------------------------------------------------------------------- */
    7503        5641 :     if (STARTS_WITH_CI(osSQLCommand, "DROP TABLE "))
    7504             :     {
    7505           9 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DROP TABLE ");
    7506             : 
    7507           9 :         while (*pszLayerName == ' ')
    7508           0 :             pszLayerName++;
    7509             : 
    7510           9 :         if (DeleteVectorOrRasterLayer(SQLUnescape(pszLayerName)))
    7511           4 :             return nullptr;
    7512             :     }
    7513             : 
    7514             :     /* -------------------------------------------------------------------- */
    7515             :     /*      Intercept ALTER TABLE src_table RENAME TO dst_table             */
    7516             :     /*      and       ALTER TABLE table RENAME COLUMN src_name TO dst_name  */
    7517             :     /*      and       ALTER TABLE table DROP COLUMN col_name                */
    7518             :     /*                                                                      */
    7519             :     /*      We do this because SQLite mechanisms can't deal with updating   */
    7520             :     /*      literal values in gpkg_ tables that refer to table and column   */
    7521             :     /*      names.                                                          */
    7522             :     /* -------------------------------------------------------------------- */
    7523        5637 :     if (STARTS_WITH_CI(osSQLCommand, "ALTER TABLE "))
    7524             :     {
    7525           9 :         char **papszTokens = SQLTokenize(osSQLCommand);
    7526             :         /* ALTER TABLE src_table RENAME TO dst_table */
    7527          16 :         if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "RENAME") &&
    7528           7 :             EQUAL(papszTokens[4], "TO"))
    7529             :         {
    7530           7 :             const char *pszSrcTableName = papszTokens[2];
    7531           7 :             const char *pszDstTableName = papszTokens[5];
    7532           7 :             if (RenameVectorOrRasterLayer(SQLUnescape(pszSrcTableName),
    7533          14 :                                           SQLUnescape(pszDstTableName)))
    7534             :             {
    7535           6 :                 CSLDestroy(papszTokens);
    7536           6 :                 return nullptr;
    7537             :             }
    7538             :         }
    7539             :         /* ALTER TABLE table RENAME COLUMN src_name TO dst_name */
    7540           2 :         else if (CSLCount(papszTokens) == 8 &&
    7541           1 :                  EQUAL(papszTokens[3], "RENAME") &&
    7542           3 :                  EQUAL(papszTokens[4], "COLUMN") && EQUAL(papszTokens[6], "TO"))
    7543             :         {
    7544           1 :             const char *pszTableName = papszTokens[2];
    7545           1 :             const char *pszSrcColumn = papszTokens[5];
    7546           1 :             const char *pszDstColumn = papszTokens[7];
    7547             :             OGRGeoPackageTableLayer *poLayer =
    7548           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7549           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7550           1 :             if (poLayer)
    7551             :             {
    7552           2 :                 int nSrcFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7553           2 :                     SQLUnescape(pszSrcColumn));
    7554           1 :                 if (nSrcFieldIdx >= 0)
    7555             :                 {
    7556             :                     // OFTString or any type will do as we just alter the name
    7557             :                     // so it will be ignored.
    7558           1 :                     OGRFieldDefn oFieldDefn(SQLUnescape(pszDstColumn),
    7559           1 :                                             OFTString);
    7560           1 :                     poLayer->AlterFieldDefn(nSrcFieldIdx, &oFieldDefn,
    7561             :                                             ALTER_NAME_FLAG);
    7562           1 :                     CSLDestroy(papszTokens);
    7563           1 :                     return nullptr;
    7564             :                 }
    7565             :             }
    7566             :         }
    7567             :         /* ALTER TABLE table DROP COLUMN col_name */
    7568           2 :         else if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "DROP") &&
    7569           1 :                  EQUAL(papszTokens[4], "COLUMN"))
    7570             :         {
    7571           1 :             const char *pszTableName = papszTokens[2];
    7572           1 :             const char *pszColumnName = papszTokens[5];
    7573             :             OGRGeoPackageTableLayer *poLayer =
    7574           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7575           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7576           1 :             if (poLayer)
    7577             :             {
    7578           2 :                 int nFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7579           2 :                     SQLUnescape(pszColumnName));
    7580           1 :                 if (nFieldIdx >= 0)
    7581             :                 {
    7582           1 :                     poLayer->DeleteField(nFieldIdx);
    7583           1 :                     CSLDestroy(papszTokens);
    7584           1 :                     return nullptr;
    7585             :                 }
    7586             :             }
    7587             :         }
    7588           1 :         CSLDestroy(papszTokens);
    7589             :     }
    7590             : 
    7591        5629 :     if (ProcessTransactionSQL(osSQLCommand))
    7592             :     {
    7593         253 :         return nullptr;
    7594             :     }
    7595             : 
    7596        5376 :     if (EQUAL(osSQLCommand, "VACUUM"))
    7597             :     {
    7598          13 :         ResetReadingAllLayers();
    7599             :     }
    7600        5363 :     else if (STARTS_WITH_CI(osSQLCommand, "DELETE FROM "))
    7601             :     {
    7602             :         // Optimize truncation of a table, especially if it has a spatial
    7603             :         // index.
    7604          24 :         const CPLStringList aosTokens(SQLTokenize(osSQLCommand));
    7605          24 :         if (aosTokens.size() == 3)
    7606             :         {
    7607          16 :             const char *pszTableName = aosTokens[2];
    7608             :             OGRGeoPackageTableLayer *poLayer =
    7609           8 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7610          24 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7611          16 :             if (poLayer)
    7612             :             {
    7613           8 :                 poLayer->Truncate();
    7614           8 :                 return nullptr;
    7615             :             }
    7616             :         }
    7617             :     }
    7618        5339 :     else if (pszDialect != nullptr && EQUAL(pszDialect, "INDIRECT_SQLITE"))
    7619           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter, "SQLITE");
    7620        5338 :     else if (pszDialect != nullptr && !EQUAL(pszDialect, "") &&
    7621          67 :              !EQUAL(pszDialect, "NATIVE") && !EQUAL(pszDialect, "SQLITE") &&
    7622          67 :              !EQUAL(pszDialect, "DEBUG"))
    7623           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter,
    7624           1 :                                        pszDialect);
    7625             : 
    7626             :     /* -------------------------------------------------------------------- */
    7627             :     /*      Prepare statement.                                              */
    7628             :     /* -------------------------------------------------------------------- */
    7629        5366 :     sqlite3_stmt *hSQLStmt = nullptr;
    7630             : 
    7631             :     /* This will speed-up layer creation */
    7632             :     /* ORDER BY are costly to evaluate and are not necessary to establish */
    7633             :     /* the layer definition. */
    7634        5366 :     bool bUseStatementForGetNextFeature = true;
    7635        5366 :     bool bEmptyLayer = false;
    7636       10732 :     CPLString osSQLCommandTruncated(osSQLCommand);
    7637             : 
    7638       17708 :     if (osSQLCommand.ifind("SELECT ") == 0 &&
    7639        6171 :         CPLString(osSQLCommand.substr(1)).ifind("SELECT ") ==
    7640         770 :             std::string::npos &&
    7641         770 :         osSQLCommand.ifind(" UNION ") == std::string::npos &&
    7642        6941 :         osSQLCommand.ifind(" INTERSECT ") == std::string::npos &&
    7643         770 :         osSQLCommand.ifind(" EXCEPT ") == std::string::npos)
    7644             :     {
    7645         770 :         size_t nOrderByPos = osSQLCommand.ifind(" ORDER BY ");
    7646         770 :         if (nOrderByPos != std::string::npos)
    7647             :         {
    7648           9 :             osSQLCommandTruncated.resize(nOrderByPos);
    7649           9 :             bUseStatementForGetNextFeature = false;
    7650             :         }
    7651             :     }
    7652             : 
    7653        5366 :     int rc = prepareSql(hDB, osSQLCommandTruncated.c_str(),
    7654        5366 :                         static_cast<int>(osSQLCommandTruncated.size()),
    7655             :                         &hSQLStmt, nullptr);
    7656             : 
    7657        5366 :     if (rc != SQLITE_OK)
    7658             :     {
    7659           9 :         CPLError(CE_Failure, CPLE_AppDefined,
    7660             :                  "In ExecuteSQL(): sqlite3_prepare_v2(%s): %s",
    7661             :                  osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7662             : 
    7663           9 :         if (hSQLStmt != nullptr)
    7664             :         {
    7665           0 :             sqlite3_finalize(hSQLStmt);
    7666             :         }
    7667             : 
    7668           9 :         return nullptr;
    7669             :     }
    7670             : 
    7671             :     /* -------------------------------------------------------------------- */
    7672             :     /*      Do we get a resultset?                                          */
    7673             :     /* -------------------------------------------------------------------- */
    7674        5357 :     rc = sqlite3_step(hSQLStmt);
    7675             : 
    7676        6953 :     for (auto &poLayer : m_apoLayers)
    7677             :     {
    7678        1596 :         poLayer->RunDeferredDropRTreeTableIfNecessary();
    7679             :     }
    7680             : 
    7681        5357 :     if (rc != SQLITE_ROW)
    7682             :     {
    7683        4635 :         if (rc != SQLITE_DONE)
    7684             :         {
    7685           7 :             CPLError(CE_Failure, CPLE_AppDefined,
    7686             :                      "In ExecuteSQL(): sqlite3_step(%s):\n  %s",
    7687             :                      osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7688             : 
    7689           7 :             sqlite3_finalize(hSQLStmt);
    7690           7 :             return nullptr;
    7691             :         }
    7692             : 
    7693        4628 :         if (EQUAL(osSQLCommand, "VACUUM"))
    7694             :         {
    7695          13 :             sqlite3_finalize(hSQLStmt);
    7696             :             /* VACUUM rewrites the DB, so we need to reset the application id */
    7697          13 :             SetApplicationAndUserVersionId();
    7698          13 :             return nullptr;
    7699             :         }
    7700             : 
    7701        4615 :         if (!STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7702             :         {
    7703        4488 :             sqlite3_finalize(hSQLStmt);
    7704        4488 :             return nullptr;
    7705             :         }
    7706             : 
    7707         127 :         bUseStatementForGetNextFeature = false;
    7708         127 :         bEmptyLayer = true;
    7709             :     }
    7710             : 
    7711             :     /* -------------------------------------------------------------------- */
    7712             :     /*      Special case for some functions which must be run               */
    7713             :     /*      only once                                                       */
    7714             :     /* -------------------------------------------------------------------- */
    7715         849 :     if (STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7716             :     {
    7717        3869 :         for (unsigned int i = 0; i < sizeof(apszFuncsWithSideEffects) /
    7718             :                                          sizeof(apszFuncsWithSideEffects[0]);
    7719             :              i++)
    7720             :         {
    7721        3121 :             if (EQUALN(apszFuncsWithSideEffects[i], osSQLCommand.c_str() + 7,
    7722             :                        strlen(apszFuncsWithSideEffects[i])))
    7723             :             {
    7724         112 :                 if (sqlite3_column_count(hSQLStmt) == 1 &&
    7725          56 :                     sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7726             :                 {
    7727          56 :                     int ret = sqlite3_column_int(hSQLStmt, 0);
    7728             : 
    7729          56 :                     sqlite3_finalize(hSQLStmt);
    7730             : 
    7731             :                     return new OGRSQLiteSingleFeatureLayer(
    7732          56 :                         apszFuncsWithSideEffects[i], ret);
    7733             :                 }
    7734             :             }
    7735             :         }
    7736             :     }
    7737          45 :     else if (STARTS_WITH_CI(osSQLCommand, "PRAGMA "))
    7738             :     {
    7739          63 :         if (sqlite3_column_count(hSQLStmt) == 1 &&
    7740          18 :             sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7741             :         {
    7742          15 :             int ret = sqlite3_column_int(hSQLStmt, 0);
    7743             : 
    7744          15 :             sqlite3_finalize(hSQLStmt);
    7745             : 
    7746          15 :             return new OGRSQLiteSingleFeatureLayer(osSQLCommand.c_str() + 7,
    7747          15 :                                                    ret);
    7748             :         }
    7749          33 :         else if (sqlite3_column_count(hSQLStmt) == 1 &&
    7750           3 :                  sqlite3_column_type(hSQLStmt, 0) == SQLITE_TEXT)
    7751             :         {
    7752             :             const char *pszRet = reinterpret_cast<const char *>(
    7753           3 :                 sqlite3_column_text(hSQLStmt, 0));
    7754             : 
    7755             :             OGRLayer *poRet = new OGRSQLiteSingleFeatureLayer(
    7756           3 :                 osSQLCommand.c_str() + 7, pszRet);
    7757             : 
    7758           3 :             sqlite3_finalize(hSQLStmt);
    7759             : 
    7760           3 :             return poRet;
    7761             :         }
    7762             :     }
    7763             : 
    7764             :     /* -------------------------------------------------------------------- */
    7765             :     /*      Create layer.                                                   */
    7766             :     /* -------------------------------------------------------------------- */
    7767             : 
    7768             :     auto poLayer = std::make_unique<OGRGeoPackageSelectLayer>(
    7769             :         this, osSQLCommand, hSQLStmt, bUseStatementForGetNextFeature,
    7770        1550 :         bEmptyLayer);
    7771             : 
    7772         778 :     if (poSpatialFilter != nullptr &&
    7773           3 :         poLayer->GetLayerDefn()->GetGeomFieldCount() > 0)
    7774           3 :         poLayer->SetSpatialFilter(0, poSpatialFilter);
    7775             : 
    7776         775 :     return poLayer.release();
    7777             : }
    7778             : 
    7779             : /************************************************************************/
    7780             : /*                          ReleaseResultSet()                          */
    7781             : /************************************************************************/
    7782             : 
    7783         808 : void GDALGeoPackageDataset::ReleaseResultSet(OGRLayer *poLayer)
    7784             : 
    7785             : {
    7786         808 :     delete poLayer;
    7787         808 : }
    7788             : 
    7789             : /************************************************************************/
    7790             : /*                         HasExtensionsTable()                         */
    7791             : /************************************************************************/
    7792             : 
    7793        6892 : bool GDALGeoPackageDataset::HasExtensionsTable()
    7794             : {
    7795        6892 :     return SQLGetInteger(
    7796             :                hDB,
    7797             :                "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_extensions' "
    7798             :                "AND type IN ('table', 'view')",
    7799        6892 :                nullptr) == 1;
    7800             : }
    7801             : 
    7802             : /************************************************************************/
    7803             : /*                    CheckUnknownExtensions()                          */
    7804             : /************************************************************************/
    7805             : 
    7806        1543 : void GDALGeoPackageDataset::CheckUnknownExtensions(bool bCheckRasterTable)
    7807             : {
    7808        1543 :     if (!HasExtensionsTable())
    7809         208 :         return;
    7810             : 
    7811        1335 :     char *pszSQL = nullptr;
    7812        1335 :     if (!bCheckRasterTable)
    7813        1126 :         pszSQL = sqlite3_mprintf(
    7814             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7815             :             "WHERE (table_name IS NULL "
    7816             :             "AND extension_name IS NOT NULL "
    7817             :             "AND definition IS NOT NULL "
    7818             :             "AND scope IS NOT NULL "
    7819             :             "AND extension_name NOT IN ("
    7820             :             "'gdal_aspatial', "
    7821             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7822             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7823             :                                        // 17-066r1 finalization
    7824             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7825             :             "'gpkg_metadata', "
    7826             :             "'gpkg_schema', "
    7827             :             "'gpkg_crs_wkt', "
    7828             :             "'gpkg_crs_wkt_1_1', "
    7829             :             "'related_tables', 'gpkg_related_tables')) "
    7830             : #ifdef WORKAROUND_SQLITE3_BUGS
    7831             :             "OR 0 "
    7832             : #endif
    7833             :             "LIMIT 1000");
    7834             :     else
    7835         209 :         pszSQL = sqlite3_mprintf(
    7836             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7837             :             "WHERE (lower(table_name) = lower('%q') "
    7838             :             "AND extension_name IS NOT NULL "
    7839             :             "AND definition IS NOT NULL "
    7840             :             "AND scope IS NOT NULL "
    7841             :             "AND extension_name NOT IN ("
    7842             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7843             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7844             :                                        // 17-066r1 finalization
    7845             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7846             :             "'gpkg_metadata', "
    7847             :             "'gpkg_schema', "
    7848             :             "'gpkg_crs_wkt', "
    7849             :             "'gpkg_crs_wkt_1_1', "
    7850             :             "'related_tables', 'gpkg_related_tables')) "
    7851             : #ifdef WORKAROUND_SQLITE3_BUGS
    7852             :             "OR 0 "
    7853             : #endif
    7854             :             "LIMIT 1000",
    7855             :             m_osRasterTable.c_str());
    7856             : 
    7857        2670 :     auto oResultTable = SQLQuery(GetDB(), pszSQL);
    7858        1335 :     sqlite3_free(pszSQL);
    7859        1335 :     if (oResultTable && oResultTable->RowCount() > 0)
    7860             :     {
    7861          42 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    7862             :         {
    7863          21 :             const char *pszExtName = oResultTable->GetValue(0, i);
    7864          21 :             const char *pszDefinition = oResultTable->GetValue(1, i);
    7865          21 :             const char *pszScope = oResultTable->GetValue(2, i);
    7866          21 :             if (pszExtName == nullptr || pszDefinition == nullptr ||
    7867             :                 pszScope == nullptr)
    7868             :             {
    7869           0 :                 continue;
    7870             :             }
    7871             : 
    7872          21 :             if (EQUAL(pszExtName, "gpkg_webp"))
    7873             :             {
    7874          15 :                 if (GDALGetDriverByName("WEBP") == nullptr)
    7875             :                 {
    7876           1 :                     CPLError(
    7877             :                         CE_Warning, CPLE_AppDefined,
    7878             :                         "Table %s contains WEBP tiles, but GDAL configured "
    7879             :                         "without WEBP support. Data will be missing",
    7880             :                         m_osRasterTable.c_str());
    7881             :                 }
    7882          15 :                 m_eTF = GPKG_TF_WEBP;
    7883          15 :                 continue;
    7884             :             }
    7885           6 :             if (EQUAL(pszExtName, "gpkg_zoom_other"))
    7886             :             {
    7887           2 :                 m_bZoomOther = true;
    7888           2 :                 continue;
    7889             :             }
    7890             : 
    7891           4 :             if (GetUpdate() && EQUAL(pszScope, "write-only"))
    7892             :             {
    7893           1 :                 CPLError(
    7894             :                     CE_Warning, CPLE_AppDefined,
    7895             :                     "Database relies on the '%s' (%s) extension that should "
    7896             :                     "be implemented for safe write-support, but is not "
    7897             :                     "currently. "
    7898             :                     "Update of that database are strongly discouraged to avoid "
    7899             :                     "corruption.",
    7900             :                     pszExtName, pszDefinition);
    7901             :             }
    7902           3 :             else if (GetUpdate() && EQUAL(pszScope, "read-write"))
    7903             :             {
    7904           1 :                 CPLError(
    7905             :                     CE_Warning, CPLE_AppDefined,
    7906             :                     "Database relies on the '%s' (%s) extension that should "
    7907             :                     "be implemented in order to read/write it safely, but is "
    7908             :                     "not currently. "
    7909             :                     "Some data may be missing while reading that database, and "
    7910             :                     "updates are strongly discouraged.",
    7911             :                     pszExtName, pszDefinition);
    7912             :             }
    7913           2 :             else if (EQUAL(pszScope, "read-write") &&
    7914             :                      // None of the NGA extensions at
    7915             :                      // http://ngageoint.github.io/GeoPackage/docs/extensions/
    7916             :                      // affect read-only scenarios
    7917           1 :                      !STARTS_WITH(pszExtName, "nga_"))
    7918             :             {
    7919           1 :                 CPLError(
    7920             :                     CE_Warning, CPLE_AppDefined,
    7921             :                     "Database relies on the '%s' (%s) extension that should "
    7922             :                     "be implemented in order to read it safely, but is not "
    7923             :                     "currently. "
    7924             :                     "Some data may be missing while reading that database.",
    7925             :                     pszExtName, pszDefinition);
    7926             :             }
    7927             :         }
    7928             :     }
    7929             : }
    7930             : 
    7931             : /************************************************************************/
    7932             : /*                         HasGDALAspatialExtension()                       */
    7933             : /************************************************************************/
    7934             : 
    7935        1086 : bool GDALGeoPackageDataset::HasGDALAspatialExtension()
    7936             : {
    7937        1086 :     if (!HasExtensionsTable())
    7938         101 :         return false;
    7939             : 
    7940             :     auto oResultTable = SQLQuery(hDB, "SELECT * FROM gpkg_extensions "
    7941             :                                       "WHERE (extension_name = 'gdal_aspatial' "
    7942             :                                       "AND table_name IS NULL "
    7943             :                                       "AND column_name IS NULL)"
    7944             : #ifdef WORKAROUND_SQLITE3_BUGS
    7945             :                                       " OR 0"
    7946             : #endif
    7947         985 :     );
    7948         985 :     bool bHasExtension = (oResultTable && oResultTable->RowCount() == 1);
    7949         985 :     return bHasExtension;
    7950             : }
    7951             : 
    7952             : std::string
    7953         192 : GDALGeoPackageDataset::CreateRasterTriggersSQL(const std::string &osTableName)
    7954             : {
    7955             :     char *pszSQL;
    7956         192 :     std::string osSQL;
    7957             :     /* From D.5. sample_tile_pyramid Table 43. tiles table Trigger
    7958             :      * Definition SQL  */
    7959         192 :     pszSQL = sqlite3_mprintf(
    7960             :         "CREATE TRIGGER \"%w_zoom_insert\" "
    7961             :         "BEFORE INSERT ON \"%w\" "
    7962             :         "FOR EACH ROW BEGIN "
    7963             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7964             :         "constraint: zoom_level not specified for table in "
    7965             :         "gpkg_tile_matrix') "
    7966             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7967             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7968             :         "END; "
    7969             :         "CREATE TRIGGER \"%w_zoom_update\" "
    7970             :         "BEFORE UPDATE OF zoom_level ON \"%w\" "
    7971             :         "FOR EACH ROW BEGIN "
    7972             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7973             :         "constraint: zoom_level not specified for table in "
    7974             :         "gpkg_tile_matrix') "
    7975             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7976             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7977             :         "END; "
    7978             :         "CREATE TRIGGER \"%w_tile_column_insert\" "
    7979             :         "BEFORE INSERT ON \"%w\" "
    7980             :         "FOR EACH ROW BEGIN "
    7981             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7982             :         "constraint: tile_column cannot be < 0') "
    7983             :         "WHERE (NEW.tile_column < 0) ; "
    7984             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7985             :         "constraint: tile_column must by < matrix_width specified for "
    7986             :         "table and zoom level in gpkg_tile_matrix') "
    7987             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    7988             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    7989             :         "zoom_level = NEW.zoom_level)); "
    7990             :         "END; "
    7991             :         "CREATE TRIGGER \"%w_tile_column_update\" "
    7992             :         "BEFORE UPDATE OF tile_column ON \"%w\" "
    7993             :         "FOR EACH ROW BEGIN "
    7994             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7995             :         "constraint: tile_column cannot be < 0') "
    7996             :         "WHERE (NEW.tile_column < 0) ; "
    7997             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7998             :         "constraint: tile_column must by < matrix_width specified for "
    7999             :         "table and zoom level in gpkg_tile_matrix') "
    8000             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    8001             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8002             :         "zoom_level = NEW.zoom_level)); "
    8003             :         "END; "
    8004             :         "CREATE TRIGGER \"%w_tile_row_insert\" "
    8005             :         "BEFORE INSERT ON \"%w\" "
    8006             :         "FOR EACH ROW BEGIN "
    8007             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8008             :         "constraint: tile_row cannot be < 0') "
    8009             :         "WHERE (NEW.tile_row < 0) ; "
    8010             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8011             :         "constraint: tile_row must by < matrix_height specified for "
    8012             :         "table and zoom level in gpkg_tile_matrix') "
    8013             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8014             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8015             :         "zoom_level = NEW.zoom_level)); "
    8016             :         "END; "
    8017             :         "CREATE TRIGGER \"%w_tile_row_update\" "
    8018             :         "BEFORE UPDATE OF tile_row ON \"%w\" "
    8019             :         "FOR EACH ROW BEGIN "
    8020             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8021             :         "constraint: tile_row cannot be < 0') "
    8022             :         "WHERE (NEW.tile_row < 0) ; "
    8023             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8024             :         "constraint: tile_row must by < matrix_height specified for "
    8025             :         "table and zoom level in gpkg_tile_matrix') "
    8026             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8027             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8028             :         "zoom_level = NEW.zoom_level)); "
    8029             :         "END; ",
    8030             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8031             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8032             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8033             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8034             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8035             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8036             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8037             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8038             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8039             :         osTableName.c_str());
    8040         192 :     osSQL = pszSQL;
    8041         192 :     sqlite3_free(pszSQL);
    8042         192 :     return osSQL;
    8043             : }
    8044             : 
    8045             : /************************************************************************/
    8046             : /*                  CreateExtensionsTableIfNecessary()                  */
    8047             : /************************************************************************/
    8048             : 
    8049        1226 : OGRErr GDALGeoPackageDataset::CreateExtensionsTableIfNecessary()
    8050             : {
    8051             :     /* Check if the table gpkg_extensions exists */
    8052        1226 :     if (HasExtensionsTable())
    8053         416 :         return OGRERR_NONE;
    8054             : 
    8055             :     /* Requirement 79 : Every extension of a GeoPackage SHALL be registered */
    8056             :     /* in a corresponding row in the gpkg_extensions table. The absence of a */
    8057             :     /* gpkg_extensions table or the absence of rows in gpkg_extensions table */
    8058             :     /* SHALL both indicate the absence of extensions to a GeoPackage. */
    8059         810 :     const char *pszCreateGpkgExtensions =
    8060             :         "CREATE TABLE gpkg_extensions ("
    8061             :         "table_name TEXT,"
    8062             :         "column_name TEXT,"
    8063             :         "extension_name TEXT NOT NULL,"
    8064             :         "definition TEXT NOT NULL,"
    8065             :         "scope TEXT NOT NULL,"
    8066             :         "CONSTRAINT ge_tce UNIQUE (table_name, column_name, extension_name)"
    8067             :         ")";
    8068             : 
    8069         810 :     return SQLCommand(hDB, pszCreateGpkgExtensions);
    8070             : }
    8071             : 
    8072             : /************************************************************************/
    8073             : /*                    OGR_GPKG_Intersects_Spatial_Filter()              */
    8074             : /************************************************************************/
    8075             : 
    8076       23135 : void OGR_GPKG_Intersects_Spatial_Filter(sqlite3_context *pContext, int argc,
    8077             :                                         sqlite3_value **argv)
    8078             : {
    8079       23135 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8080             :     {
    8081           0 :         sqlite3_result_int(pContext, 0);
    8082       23125 :         return;
    8083             :     }
    8084             : 
    8085             :     auto poLayer =
    8086       23135 :         static_cast<OGRGeoPackageTableLayer *>(sqlite3_user_data(pContext));
    8087             : 
    8088       23135 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8089             :     const GByte *pabyBLOB =
    8090       23135 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8091             : 
    8092             :     GPkgHeader sHeader;
    8093       46270 :     if (poLayer->m_bFilterIsEnvelope &&
    8094       23135 :         OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false, 0))
    8095             :     {
    8096       23135 :         if (sHeader.bExtentHasXY)
    8097             :         {
    8098          95 :             OGREnvelope sEnvelope;
    8099          95 :             sEnvelope.MinX = sHeader.MinX;
    8100          95 :             sEnvelope.MinY = sHeader.MinY;
    8101          95 :             sEnvelope.MaxX = sHeader.MaxX;
    8102          95 :             sEnvelope.MaxY = sHeader.MaxY;
    8103          95 :             if (poLayer->m_sFilterEnvelope.Contains(sEnvelope))
    8104             :             {
    8105          31 :                 sqlite3_result_int(pContext, 1);
    8106          31 :                 return;
    8107             :             }
    8108             :         }
    8109             : 
    8110             :         // Check if at least one point falls into the layer filter envelope
    8111             :         // nHeaderLen is > 0 for GeoPackage geometries
    8112       46208 :         if (sHeader.nHeaderLen > 0 &&
    8113       23104 :             OGRWKBIntersectsPessimistic(pabyBLOB + sHeader.nHeaderLen,
    8114       23104 :                                         nBLOBLen - sHeader.nHeaderLen,
    8115       23104 :                                         poLayer->m_sFilterEnvelope))
    8116             :         {
    8117       23094 :             sqlite3_result_int(pContext, 1);
    8118       23094 :             return;
    8119             :         }
    8120             :     }
    8121             : 
    8122             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8123          10 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8124          10 :     if (poGeom == nullptr)
    8125             :     {
    8126             :         // Try also spatialite geometry blobs
    8127           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8128           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8129           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8130             :         {
    8131           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8132           0 :             sqlite3_result_int(pContext, 0);
    8133           0 :             return;
    8134             :         }
    8135           0 :         poGeom.reset(poGeomSpatialite);
    8136             :     }
    8137             : 
    8138          10 :     sqlite3_result_int(pContext, poLayer->FilterGeometry(poGeom.get()));
    8139             : }
    8140             : 
    8141             : /************************************************************************/
    8142             : /*                      OGRGeoPackageSTMinX()                           */
    8143             : /************************************************************************/
    8144             : 
    8145      252254 : static void OGRGeoPackageSTMinX(sqlite3_context *pContext, int argc,
    8146             :                                 sqlite3_value **argv)
    8147             : {
    8148             :     GPkgHeader sHeader;
    8149      252254 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8150             :     {
    8151           3 :         sqlite3_result_null(pContext);
    8152           3 :         return;
    8153             :     }
    8154      252251 :     sqlite3_result_double(pContext, sHeader.MinX);
    8155             : }
    8156             : 
    8157             : /************************************************************************/
    8158             : /*                      OGRGeoPackageSTMinY()                           */
    8159             : /************************************************************************/
    8160             : 
    8161      252252 : static void OGRGeoPackageSTMinY(sqlite3_context *pContext, int argc,
    8162             :                                 sqlite3_value **argv)
    8163             : {
    8164             :     GPkgHeader sHeader;
    8165      252252 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8166             :     {
    8167           1 :         sqlite3_result_null(pContext);
    8168           1 :         return;
    8169             :     }
    8170      252251 :     sqlite3_result_double(pContext, sHeader.MinY);
    8171             : }
    8172             : 
    8173             : /************************************************************************/
    8174             : /*                      OGRGeoPackageSTMaxX()                           */
    8175             : /************************************************************************/
    8176             : 
    8177      252252 : static void OGRGeoPackageSTMaxX(sqlite3_context *pContext, int argc,
    8178             :                                 sqlite3_value **argv)
    8179             : {
    8180             :     GPkgHeader sHeader;
    8181      252252 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8182             :     {
    8183           1 :         sqlite3_result_null(pContext);
    8184           1 :         return;
    8185             :     }
    8186      252251 :     sqlite3_result_double(pContext, sHeader.MaxX);
    8187             : }
    8188             : 
    8189             : /************************************************************************/
    8190             : /*                      OGRGeoPackageSTMaxY()                           */
    8191             : /************************************************************************/
    8192             : 
    8193      252252 : static void OGRGeoPackageSTMaxY(sqlite3_context *pContext, int argc,
    8194             :                                 sqlite3_value **argv)
    8195             : {
    8196             :     GPkgHeader sHeader;
    8197      252252 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8198             :     {
    8199           1 :         sqlite3_result_null(pContext);
    8200           1 :         return;
    8201             :     }
    8202      252251 :     sqlite3_result_double(pContext, sHeader.MaxY);
    8203             : }
    8204             : 
    8205             : /************************************************************************/
    8206             : /*                     OGRGeoPackageSTIsEmpty()                         */
    8207             : /************************************************************************/
    8208             : 
    8209      253663 : static void OGRGeoPackageSTIsEmpty(sqlite3_context *pContext, int argc,
    8210             :                                    sqlite3_value **argv)
    8211             : {
    8212             :     GPkgHeader sHeader;
    8213      253663 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8214             :     {
    8215           2 :         sqlite3_result_null(pContext);
    8216           2 :         return;
    8217             :     }
    8218      253661 :     sqlite3_result_int(pContext, sHeader.bEmpty);
    8219             : }
    8220             : 
    8221             : /************************************************************************/
    8222             : /*                    OGRGeoPackageSTGeometryType()                     */
    8223             : /************************************************************************/
    8224             : 
    8225           7 : static void OGRGeoPackageSTGeometryType(sqlite3_context *pContext, int /*argc*/,
    8226             :                                         sqlite3_value **argv)
    8227             : {
    8228             :     GPkgHeader sHeader;
    8229             : 
    8230           7 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8231             :     const GByte *pabyBLOB =
    8232           7 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8233             :     OGRwkbGeometryType eGeometryType;
    8234             : 
    8235          13 :     if (nBLOBLen < 8 ||
    8236           6 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8237             :     {
    8238           2 :         if (OGRSQLiteGetSpatialiteGeometryHeader(
    8239             :                 pabyBLOB, nBLOBLen, nullptr, &eGeometryType, nullptr, nullptr,
    8240           2 :                 nullptr, nullptr, nullptr) == OGRERR_NONE)
    8241             :         {
    8242           1 :             sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8243             :                                 SQLITE_TRANSIENT);
    8244           4 :             return;
    8245             :         }
    8246             :         else
    8247             :         {
    8248           1 :             sqlite3_result_null(pContext);
    8249           1 :             return;
    8250             :         }
    8251             :     }
    8252             : 
    8253           5 :     if (static_cast<size_t>(nBLOBLen) < sHeader.nHeaderLen + 5)
    8254             :     {
    8255           2 :         sqlite3_result_null(pContext);
    8256           2 :         return;
    8257             :     }
    8258             : 
    8259           3 :     OGRErr err = OGRReadWKBGeometryType(pabyBLOB + sHeader.nHeaderLen,
    8260             :                                         wkbVariantIso, &eGeometryType);
    8261           3 :     if (err != OGRERR_NONE)
    8262           1 :         sqlite3_result_null(pContext);
    8263             :     else
    8264           2 :         sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8265             :                             SQLITE_TRANSIENT);
    8266             : }
    8267             : 
    8268             : /************************************************************************/
    8269             : /*                 OGRGeoPackageSTEnvelopesIntersects()                 */
    8270             : /************************************************************************/
    8271             : 
    8272         118 : static void OGRGeoPackageSTEnvelopesIntersects(sqlite3_context *pContext,
    8273             :                                                int argc, sqlite3_value **argv)
    8274             : {
    8275             :     GPkgHeader sHeader;
    8276         118 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8277             :     {
    8278           2 :         sqlite3_result_int(pContext, FALSE);
    8279         107 :         return;
    8280             :     }
    8281         116 :     const double dfMinX = sqlite3_value_double(argv[1]);
    8282         116 :     if (sHeader.MaxX < dfMinX)
    8283             :     {
    8284          93 :         sqlite3_result_int(pContext, FALSE);
    8285          93 :         return;
    8286             :     }
    8287          23 :     const double dfMinY = sqlite3_value_double(argv[2]);
    8288          23 :     if (sHeader.MaxY < dfMinY)
    8289             :     {
    8290          11 :         sqlite3_result_int(pContext, FALSE);
    8291          11 :         return;
    8292             :     }
    8293          12 :     const double dfMaxX = sqlite3_value_double(argv[3]);
    8294          12 :     if (sHeader.MinX > dfMaxX)
    8295             :     {
    8296           1 :         sqlite3_result_int(pContext, FALSE);
    8297           1 :         return;
    8298             :     }
    8299          11 :     const double dfMaxY = sqlite3_value_double(argv[4]);
    8300          11 :     sqlite3_result_int(pContext, sHeader.MinY <= dfMaxY);
    8301             : }
    8302             : 
    8303             : /************************************************************************/
    8304             : /*              OGRGeoPackageSTEnvelopesIntersectsTwoParams()           */
    8305             : /************************************************************************/
    8306             : 
    8307             : static void
    8308           3 : OGRGeoPackageSTEnvelopesIntersectsTwoParams(sqlite3_context *pContext, int argc,
    8309             :                                             sqlite3_value **argv)
    8310             : {
    8311             :     GPkgHeader sHeader;
    8312           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false, 0))
    8313             :     {
    8314           0 :         sqlite3_result_int(pContext, FALSE);
    8315           2 :         return;
    8316             :     }
    8317             :     GPkgHeader sHeader2;
    8318           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader2, true, false,
    8319             :                                 1))
    8320             :     {
    8321           0 :         sqlite3_result_int(pContext, FALSE);
    8322           0 :         return;
    8323             :     }
    8324           3 :     if (sHeader.MaxX < sHeader2.MinX)
    8325             :     {
    8326           1 :         sqlite3_result_int(pContext, FALSE);
    8327           1 :         return;
    8328             :     }
    8329           2 :     if (sHeader.MaxY < sHeader2.MinY)
    8330             :     {
    8331           0 :         sqlite3_result_int(pContext, FALSE);
    8332           0 :         return;
    8333             :     }
    8334           2 :     if (sHeader.MinX > sHeader2.MaxX)
    8335             :     {
    8336           1 :         sqlite3_result_int(pContext, FALSE);
    8337           1 :         return;
    8338             :     }
    8339           1 :     sqlite3_result_int(pContext, sHeader.MinY <= sHeader2.MaxY);
    8340             : }
    8341             : 
    8342             : /************************************************************************/
    8343             : /*                    OGRGeoPackageGPKGIsAssignable()                   */
    8344             : /************************************************************************/
    8345             : 
    8346           8 : static void OGRGeoPackageGPKGIsAssignable(sqlite3_context *pContext,
    8347             :                                           int /*argc*/, sqlite3_value **argv)
    8348             : {
    8349          15 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8350           7 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8351             :     {
    8352           2 :         sqlite3_result_int(pContext, 0);
    8353           2 :         return;
    8354             :     }
    8355             : 
    8356             :     const char *pszExpected =
    8357           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8358             :     const char *pszActual =
    8359           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8360           6 :     int bIsAssignable = OGR_GT_IsSubClassOf(OGRFromOGCGeomType(pszActual),
    8361             :                                             OGRFromOGCGeomType(pszExpected));
    8362           6 :     sqlite3_result_int(pContext, bIsAssignable);
    8363             : }
    8364             : 
    8365             : /************************************************************************/
    8366             : /*                     OGRGeoPackageSTSRID()                            */
    8367             : /************************************************************************/
    8368             : 
    8369          12 : static void OGRGeoPackageSTSRID(sqlite3_context *pContext, int argc,
    8370             :                                 sqlite3_value **argv)
    8371             : {
    8372             :     GPkgHeader sHeader;
    8373          12 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8374             :     {
    8375           2 :         sqlite3_result_null(pContext);
    8376           2 :         return;
    8377             :     }
    8378          10 :     sqlite3_result_int(pContext, sHeader.iSrsId);
    8379             : }
    8380             : 
    8381             : /************************************************************************/
    8382             : /*                     OGRGeoPackageSetSRID()                           */
    8383             : /************************************************************************/
    8384             : 
    8385          28 : static void OGRGeoPackageSetSRID(sqlite3_context *pContext, int /* argc */,
    8386             :                                  sqlite3_value **argv)
    8387             : {
    8388          28 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8389             :     {
    8390           1 :         sqlite3_result_null(pContext);
    8391           1 :         return;
    8392             :     }
    8393          27 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8394             :     GPkgHeader sHeader;
    8395          27 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8396             :     const GByte *pabyBLOB =
    8397          27 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8398             : 
    8399          54 :     if (nBLOBLen < 8 ||
    8400          27 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8401             :     {
    8402             :         // Try also spatialite geometry blobs
    8403           0 :         OGRGeometry *poGeom = nullptr;
    8404           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeom) !=
    8405             :             OGRERR_NONE)
    8406             :         {
    8407           0 :             sqlite3_result_null(pContext);
    8408           0 :             return;
    8409             :         }
    8410           0 :         size_t nBLOBDestLen = 0;
    8411             :         GByte *pabyDestBLOB =
    8412           0 :             GPkgGeometryFromOGR(poGeom, nDestSRID, nullptr, &nBLOBDestLen);
    8413           0 :         if (!pabyDestBLOB)
    8414             :         {
    8415           0 :             sqlite3_result_null(pContext);
    8416           0 :             return;
    8417             :         }
    8418           0 :         sqlite3_result_blob(pContext, pabyDestBLOB,
    8419             :                             static_cast<int>(nBLOBDestLen), VSIFree);
    8420           0 :         return;
    8421             :     }
    8422             : 
    8423          27 :     GByte *pabyDestBLOB = static_cast<GByte *>(CPLMalloc(nBLOBLen));
    8424          27 :     memcpy(pabyDestBLOB, pabyBLOB, nBLOBLen);
    8425          27 :     int32_t nSRIDToSerialize = nDestSRID;
    8426          27 :     if (OGR_SWAP(sHeader.eByteOrder))
    8427           0 :         nSRIDToSerialize = CPL_SWAP32(nSRIDToSerialize);
    8428          27 :     memcpy(pabyDestBLOB + 4, &nSRIDToSerialize, 4);
    8429          27 :     sqlite3_result_blob(pContext, pabyDestBLOB, nBLOBLen, VSIFree);
    8430             : }
    8431             : 
    8432             : /************************************************************************/
    8433             : /*                   OGRGeoPackageSTMakeValid()                         */
    8434             : /************************************************************************/
    8435             : 
    8436           3 : static void OGRGeoPackageSTMakeValid(sqlite3_context *pContext, int argc,
    8437             :                                      sqlite3_value **argv)
    8438             : {
    8439           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8440             :     {
    8441           2 :         sqlite3_result_null(pContext);
    8442           2 :         return;
    8443             :     }
    8444           1 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8445             :     const GByte *pabyBLOB =
    8446           1 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8447             : 
    8448             :     GPkgHeader sHeader;
    8449           1 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8450             :     {
    8451           0 :         sqlite3_result_null(pContext);
    8452           0 :         return;
    8453             :     }
    8454             : 
    8455             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8456           1 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8457           1 :     if (poGeom == nullptr)
    8458             :     {
    8459             :         // Try also spatialite geometry blobs
    8460           0 :         OGRGeometry *poGeomPtr = nullptr;
    8461           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8462             :             OGRERR_NONE)
    8463             :         {
    8464           0 :             sqlite3_result_null(pContext);
    8465           0 :             return;
    8466             :         }
    8467           0 :         poGeom.reset(poGeomPtr);
    8468             :     }
    8469           1 :     auto poValid = std::unique_ptr<OGRGeometry>(poGeom->MakeValid());
    8470           1 :     if (poValid == nullptr)
    8471             :     {
    8472           0 :         sqlite3_result_null(pContext);
    8473           0 :         return;
    8474             :     }
    8475             : 
    8476           1 :     size_t nBLOBDestLen = 0;
    8477           1 :     GByte *pabyDestBLOB = GPkgGeometryFromOGR(poValid.get(), sHeader.iSrsId,
    8478             :                                               nullptr, &nBLOBDestLen);
    8479           1 :     if (!pabyDestBLOB)
    8480             :     {
    8481           0 :         sqlite3_result_null(pContext);
    8482           0 :         return;
    8483             :     }
    8484           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8485             :                         VSIFree);
    8486             : }
    8487             : 
    8488             : /************************************************************************/
    8489             : /*                   OGRGeoPackageSTArea()                              */
    8490             : /************************************************************************/
    8491             : 
    8492          19 : static void OGRGeoPackageSTArea(sqlite3_context *pContext, int /*argc*/,
    8493             :                                 sqlite3_value **argv)
    8494             : {
    8495          19 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8496             :     {
    8497           1 :         sqlite3_result_null(pContext);
    8498          15 :         return;
    8499             :     }
    8500          18 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8501             :     const GByte *pabyBLOB =
    8502          18 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8503             : 
    8504             :     GPkgHeader sHeader;
    8505           0 :     std::unique_ptr<OGRGeometry> poGeom;
    8506          18 :     if (GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) == OGRERR_NONE)
    8507             :     {
    8508          16 :         if (sHeader.bEmpty)
    8509             :         {
    8510           3 :             sqlite3_result_double(pContext, 0);
    8511          13 :             return;
    8512             :         }
    8513          13 :         const GByte *pabyWkb = pabyBLOB + sHeader.nHeaderLen;
    8514          13 :         size_t nWKBSize = nBLOBLen - sHeader.nHeaderLen;
    8515             :         bool bNeedSwap;
    8516             :         uint32_t nType;
    8517          13 :         if (OGRWKBGetGeomType(pabyWkb, nWKBSize, bNeedSwap, nType))
    8518             :         {
    8519          13 :             if (nType == wkbPolygon || nType == wkbPolygon25D ||
    8520          11 :                 nType == wkbPolygon + 1000 ||  // wkbPolygonZ
    8521          10 :                 nType == wkbPolygonM || nType == wkbPolygonZM)
    8522             :             {
    8523             :                 double dfArea;
    8524           5 :                 if (OGRWKBPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8525             :                 {
    8526           5 :                     sqlite3_result_double(pContext, dfArea);
    8527           5 :                     return;
    8528           0 :                 }
    8529             :             }
    8530           8 :             else if (nType == wkbMultiPolygon || nType == wkbMultiPolygon25D ||
    8531           6 :                      nType == wkbMultiPolygon + 1000 ||  // wkbMultiPolygonZ
    8532           5 :                      nType == wkbMultiPolygonM || nType == wkbMultiPolygonZM)
    8533             :             {
    8534             :                 double dfArea;
    8535           5 :                 if (OGRWKBMultiPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8536             :                 {
    8537           5 :                     sqlite3_result_double(pContext, dfArea);
    8538           5 :                     return;
    8539             :                 }
    8540             :             }
    8541             :         }
    8542             : 
    8543             :         // For curve geometries, fallback to OGRGeometry methods
    8544           3 :         poGeom.reset(GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8545             :     }
    8546             :     else
    8547             :     {
    8548             :         // Try also spatialite geometry blobs
    8549           2 :         OGRGeometry *poGeomPtr = nullptr;
    8550           2 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8551             :             OGRERR_NONE)
    8552             :         {
    8553           1 :             sqlite3_result_null(pContext);
    8554           1 :             return;
    8555             :         }
    8556           1 :         poGeom.reset(poGeomPtr);
    8557             :     }
    8558           4 :     auto poSurface = dynamic_cast<OGRSurface *>(poGeom.get());
    8559           4 :     if (poSurface == nullptr)
    8560             :     {
    8561           2 :         auto poMultiSurface = dynamic_cast<OGRMultiSurface *>(poGeom.get());
    8562           2 :         if (poMultiSurface == nullptr)
    8563             :         {
    8564           1 :             sqlite3_result_double(pContext, 0);
    8565             :         }
    8566             :         else
    8567             :         {
    8568           1 :             sqlite3_result_double(pContext, poMultiSurface->get_Area());
    8569             :         }
    8570             :     }
    8571             :     else
    8572             :     {
    8573           2 :         sqlite3_result_double(pContext, poSurface->get_Area());
    8574             :     }
    8575             : }
    8576             : 
    8577             : /************************************************************************/
    8578             : /*                     OGRGeoPackageGeodesicArea()                      */
    8579             : /************************************************************************/
    8580             : 
    8581           5 : static void OGRGeoPackageGeodesicArea(sqlite3_context *pContext, int argc,
    8582             :                                       sqlite3_value **argv)
    8583             : {
    8584           5 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8585             :     {
    8586           1 :         sqlite3_result_null(pContext);
    8587           3 :         return;
    8588             :     }
    8589           4 :     if (sqlite3_value_int(argv[1]) != 1)
    8590             :     {
    8591           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8592             :                  "ST_Area(geom, use_ellipsoid) is only supported for "
    8593             :                  "use_ellipsoid = 1");
    8594             :     }
    8595             : 
    8596           4 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8597             :     const GByte *pabyBLOB =
    8598           4 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8599             :     GPkgHeader sHeader;
    8600           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8601             :     {
    8602           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8603           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8604           1 :         return;
    8605             :     }
    8606             : 
    8607             :     GDALGeoPackageDataset *poDS =
    8608           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8609             : 
    8610             :     std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSrcSRS(
    8611           3 :         poDS->GetSpatialRef(sHeader.iSrsId, true));
    8612           3 :     if (poSrcSRS == nullptr)
    8613             :     {
    8614           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    8615             :                  "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8616           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8617           1 :         return;
    8618             :     }
    8619             : 
    8620             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8621           2 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8622           2 :     if (poGeom == nullptr)
    8623             :     {
    8624             :         // Try also spatialite geometry blobs
    8625           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8626           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8627           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8628             :         {
    8629           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8630           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8631           0 :             return;
    8632             :         }
    8633           0 :         poGeom.reset(poGeomSpatialite);
    8634             :     }
    8635             : 
    8636           2 :     poGeom->assignSpatialReference(poSrcSRS.get());
    8637           2 :     sqlite3_result_double(
    8638             :         pContext, OGR_G_GeodesicArea(OGRGeometry::ToHandle(poGeom.get())));
    8639             : }
    8640             : 
    8641             : /************************************************************************/
    8642             : /*                   OGRGeoPackageLengthOrGeodesicLength()              */
    8643             : /************************************************************************/
    8644             : 
    8645           8 : static void OGRGeoPackageLengthOrGeodesicLength(sqlite3_context *pContext,
    8646             :                                                 int argc, sqlite3_value **argv)
    8647             : {
    8648           8 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8649             :     {
    8650           2 :         sqlite3_result_null(pContext);
    8651           5 :         return;
    8652             :     }
    8653           6 :     if (argc == 2 && sqlite3_value_int(argv[1]) != 1)
    8654             :     {
    8655           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8656             :                  "ST_Length(geom, use_ellipsoid) is only supported for "
    8657             :                  "use_ellipsoid = 1");
    8658             :     }
    8659             : 
    8660           6 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8661             :     const GByte *pabyBLOB =
    8662           6 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8663             :     GPkgHeader sHeader;
    8664           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8665             :     {
    8666           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8667           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8668           2 :         return;
    8669             :     }
    8670             : 
    8671             :     GDALGeoPackageDataset *poDS =
    8672           4 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8673             : 
    8674           0 :     std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSrcSRS;
    8675           4 :     if (argc == 2)
    8676             :     {
    8677           3 :         poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8678           3 :         if (!poSrcSRS)
    8679             :         {
    8680           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    8681             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8682           1 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8683           1 :             return;
    8684             :         }
    8685             :     }
    8686             : 
    8687             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8688           3 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8689           3 :     if (poGeom == nullptr)
    8690             :     {
    8691             :         // Try also spatialite geometry blobs
    8692           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8693           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8694           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8695             :         {
    8696           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8697           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8698           0 :             return;
    8699             :         }
    8700           0 :         poGeom.reset(poGeomSpatialite);
    8701             :     }
    8702             : 
    8703           3 :     if (argc == 2)
    8704           2 :         poGeom->assignSpatialReference(poSrcSRS.get());
    8705             : 
    8706           6 :     sqlite3_result_double(
    8707             :         pContext,
    8708           1 :         argc == 1 ? OGR_G_Length(OGRGeometry::ToHandle(poGeom.get()))
    8709           2 :                   : OGR_G_GeodesicLength(OGRGeometry::ToHandle(poGeom.get())));
    8710             : }
    8711             : 
    8712             : /************************************************************************/
    8713             : /*                      OGRGeoPackageTransform()                        */
    8714             : /************************************************************************/
    8715             : 
    8716             : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8717             :                             sqlite3_value **argv);
    8718             : 
    8719          32 : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8720             :                             sqlite3_value **argv)
    8721             : {
    8722          63 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB ||
    8723          31 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8724             :     {
    8725           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8726          32 :         return;
    8727             :     }
    8728             : 
    8729          30 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8730             :     const GByte *pabyBLOB =
    8731          30 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8732             :     GPkgHeader sHeader;
    8733          30 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8734             :     {
    8735           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8736           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8737           1 :         return;
    8738             :     }
    8739             : 
    8740          29 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8741          29 :     if (sHeader.iSrsId == nDestSRID)
    8742             :     {
    8743             :         // Return blob unmodified
    8744           3 :         sqlite3_result_blob(pContext, pabyBLOB, nBLOBLen, SQLITE_TRANSIENT);
    8745           3 :         return;
    8746             :     }
    8747             : 
    8748             :     GDALGeoPackageDataset *poDS =
    8749          26 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8750             : 
    8751             :     // Try to get the cached coordinate transformation
    8752             :     OGRCoordinateTransformation *poCT;
    8753          26 :     if (poDS->m_nLastCachedCTSrcSRId == sHeader.iSrsId &&
    8754          20 :         poDS->m_nLastCachedCTDstSRId == nDestSRID)
    8755             :     {
    8756          20 :         poCT = poDS->m_poLastCachedCT.get();
    8757             :     }
    8758             :     else
    8759             :     {
    8760             :         std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
    8761           6 :             poSrcSRS(poDS->GetSpatialRef(sHeader.iSrsId, true));
    8762           6 :         if (poSrcSRS == nullptr)
    8763             :         {
    8764           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    8765             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8766           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8767           0 :             return;
    8768             :         }
    8769             : 
    8770             :         std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
    8771           6 :             poDstSRS(poDS->GetSpatialRef(nDestSRID, true));
    8772           6 :         if (poDstSRS == nullptr)
    8773             :         {
    8774           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Target SRID (%d) is invalid",
    8775             :                      nDestSRID);
    8776           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8777           0 :             return;
    8778             :         }
    8779             :         poCT =
    8780           6 :             OGRCreateCoordinateTransformation(poSrcSRS.get(), poDstSRS.get());
    8781           6 :         if (poCT == nullptr)
    8782             :         {
    8783           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8784           0 :             return;
    8785             :         }
    8786             : 
    8787             :         // Cache coordinate transformation for potential later reuse
    8788           6 :         poDS->m_nLastCachedCTSrcSRId = sHeader.iSrsId;
    8789           6 :         poDS->m_nLastCachedCTDstSRId = nDestSRID;
    8790           6 :         poDS->m_poLastCachedCT.reset(poCT);
    8791           6 :         poCT = poDS->m_poLastCachedCT.get();
    8792             :     }
    8793             : 
    8794          26 :     if (sHeader.nHeaderLen >= 8)
    8795             :     {
    8796          26 :         std::vector<GByte> &abyNewBLOB = poDS->m_abyWKBTransformCache;
    8797          26 :         abyNewBLOB.resize(nBLOBLen);
    8798          26 :         memcpy(abyNewBLOB.data(), pabyBLOB, nBLOBLen);
    8799             : 
    8800          26 :         OGREnvelope3D oEnv3d;
    8801          26 :         if (!OGRWKBTransform(abyNewBLOB.data() + sHeader.nHeaderLen,
    8802          26 :                              nBLOBLen - sHeader.nHeaderLen, poCT,
    8803          78 :                              poDS->m_oWKBTransformCache, oEnv3d) ||
    8804          26 :             !GPkgUpdateHeader(abyNewBLOB.data(), nBLOBLen, nDestSRID,
    8805             :                               oEnv3d.MinX, oEnv3d.MaxX, oEnv3d.MinY,
    8806             :                               oEnv3d.MaxY, oEnv3d.MinZ, oEnv3d.MaxZ))
    8807             :         {
    8808           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8809           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8810           0 :             return;
    8811             :         }
    8812             : 
    8813          26 :         sqlite3_result_blob(pContext, abyNewBLOB.data(), nBLOBLen,
    8814             :                             SQLITE_TRANSIENT);
    8815          26 :         return;
    8816             :     }
    8817             : 
    8818             :     // Try also spatialite geometry blobs
    8819           0 :     OGRGeometry *poGeomSpatialite = nullptr;
    8820           0 :     if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8821           0 :                                           &poGeomSpatialite) != OGRERR_NONE)
    8822             :     {
    8823           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8824           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8825           0 :         return;
    8826             :     }
    8827           0 :     auto poGeom = std::unique_ptr<OGRGeometry>(poGeomSpatialite);
    8828             : 
    8829           0 :     if (poGeom->transform(poCT) != OGRERR_NONE)
    8830             :     {
    8831           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8832           0 :         return;
    8833             :     }
    8834             : 
    8835           0 :     size_t nBLOBDestLen = 0;
    8836             :     GByte *pabyDestBLOB =
    8837           0 :         GPkgGeometryFromOGR(poGeom.get(), nDestSRID, nullptr, &nBLOBDestLen);
    8838           0 :     if (!pabyDestBLOB)
    8839             :     {
    8840           0 :         sqlite3_result_null(pContext);
    8841           0 :         return;
    8842             :     }
    8843           0 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8844             :                         VSIFree);
    8845             : }
    8846             : 
    8847             : /************************************************************************/
    8848             : /*                      OGRGeoPackageSridFromAuthCRS()                  */
    8849             : /************************************************************************/
    8850             : 
    8851           4 : static void OGRGeoPackageSridFromAuthCRS(sqlite3_context *pContext,
    8852             :                                          int /*argc*/, sqlite3_value **argv)
    8853             : {
    8854           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8855           3 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8856             :     {
    8857           2 :         sqlite3_result_int(pContext, -1);
    8858           2 :         return;
    8859             :     }
    8860             : 
    8861             :     GDALGeoPackageDataset *poDS =
    8862           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8863             : 
    8864           2 :     char *pszSQL = sqlite3_mprintf(
    8865             :         "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
    8866             :         "lower(organization) = lower('%q') AND organization_coordsys_id = %d",
    8867           2 :         sqlite3_value_text(argv[0]), sqlite3_value_int(argv[1]));
    8868           2 :     OGRErr err = OGRERR_NONE;
    8869           2 :     int nSRSId = SQLGetInteger(poDS->GetDB(), pszSQL, &err);
    8870           2 :     sqlite3_free(pszSQL);
    8871           2 :     if (err != OGRERR_NONE)
    8872           1 :         nSRSId = -1;
    8873           2 :     sqlite3_result_int(pContext, nSRSId);
    8874             : }
    8875             : 
    8876             : /************************************************************************/
    8877             : /*                    OGRGeoPackageImportFromEPSG()                     */
    8878             : /************************************************************************/
    8879             : 
    8880           4 : static void OGRGeoPackageImportFromEPSG(sqlite3_context *pContext, int /*argc*/,
    8881             :                                         sqlite3_value **argv)
    8882             : {
    8883           4 :     if (sqlite3_value_type(argv[0]) != SQLITE_INTEGER)
    8884             :     {
    8885           1 :         sqlite3_result_int(pContext, -1);
    8886           2 :         return;
    8887             :     }
    8888             : 
    8889             :     GDALGeoPackageDataset *poDS =
    8890           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8891           3 :     OGRSpatialReference oSRS;
    8892           3 :     if (oSRS.importFromEPSG(sqlite3_value_int(argv[0])) != OGRERR_NONE)
    8893             :     {
    8894           1 :         sqlite3_result_int(pContext, -1);
    8895           1 :         return;
    8896             :     }
    8897             : 
    8898           2 :     sqlite3_result_int(pContext, poDS->GetSrsId(&oSRS));
    8899             : }
    8900             : 
    8901             : /************************************************************************/
    8902             : /*               OGRGeoPackageRegisterGeometryExtension()               */
    8903             : /************************************************************************/
    8904             : 
    8905           1 : static void OGRGeoPackageRegisterGeometryExtension(sqlite3_context *pContext,
    8906             :                                                    int /*argc*/,
    8907             :                                                    sqlite3_value **argv)
    8908             : {
    8909           1 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8910           2 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT ||
    8911           1 :         sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    8912             :     {
    8913           0 :         sqlite3_result_int(pContext, 0);
    8914           0 :         return;
    8915             :     }
    8916             : 
    8917             :     const char *pszTableName =
    8918           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8919             :     const char *pszGeomName =
    8920           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8921             :     const char *pszGeomType =
    8922           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    8923             : 
    8924             :     GDALGeoPackageDataset *poDS =
    8925           1 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8926             : 
    8927           1 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8928           1 :         poDS->GetLayerByName(pszTableName));
    8929           1 :     if (poLyr == nullptr)
    8930             :     {
    8931           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8932           0 :         sqlite3_result_int(pContext, 0);
    8933           0 :         return;
    8934             :     }
    8935           1 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8936             :     {
    8937           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8938           0 :         sqlite3_result_int(pContext, 0);
    8939           0 :         return;
    8940             :     }
    8941           1 :     const OGRwkbGeometryType eGeomType = OGRFromOGCGeomType(pszGeomType);
    8942           1 :     if (eGeomType == wkbUnknown)
    8943             :     {
    8944           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry type name");
    8945           0 :         sqlite3_result_int(pContext, 0);
    8946           0 :         return;
    8947             :     }
    8948             : 
    8949           1 :     sqlite3_result_int(
    8950             :         pContext,
    8951           1 :         static_cast<int>(poLyr->CreateGeometryExtensionIfNecessary(eGeomType)));
    8952             : }
    8953             : 
    8954             : /************************************************************************/
    8955             : /*                  OGRGeoPackageCreateSpatialIndex()                   */
    8956             : /************************************************************************/
    8957             : 
    8958          14 : static void OGRGeoPackageCreateSpatialIndex(sqlite3_context *pContext,
    8959             :                                             int /*argc*/, sqlite3_value **argv)
    8960             : {
    8961          27 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8962          13 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8963             :     {
    8964           2 :         sqlite3_result_int(pContext, 0);
    8965           2 :         return;
    8966             :     }
    8967             : 
    8968             :     const char *pszTableName =
    8969          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8970             :     const char *pszGeomName =
    8971          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8972             :     GDALGeoPackageDataset *poDS =
    8973          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8974             : 
    8975          12 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8976          12 :         poDS->GetLayerByName(pszTableName));
    8977          12 :     if (poLyr == nullptr)
    8978             :     {
    8979           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8980           1 :         sqlite3_result_int(pContext, 0);
    8981           1 :         return;
    8982             :     }
    8983          11 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8984             :     {
    8985           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8986           1 :         sqlite3_result_int(pContext, 0);
    8987           1 :         return;
    8988             :     }
    8989             : 
    8990          10 :     sqlite3_result_int(pContext, poLyr->CreateSpatialIndex());
    8991             : }
    8992             : 
    8993             : /************************************************************************/
    8994             : /*                  OGRGeoPackageDisableSpatialIndex()                  */
    8995             : /************************************************************************/
    8996             : 
    8997          12 : static void OGRGeoPackageDisableSpatialIndex(sqlite3_context *pContext,
    8998             :                                              int /*argc*/, sqlite3_value **argv)
    8999             : {
    9000          23 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9001          11 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9002             :     {
    9003           2 :         sqlite3_result_int(pContext, 0);
    9004           2 :         return;
    9005             :     }
    9006             : 
    9007             :     const char *pszTableName =
    9008          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9009             :     const char *pszGeomName =
    9010          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9011             :     GDALGeoPackageDataset *poDS =
    9012          10 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9013             : 
    9014          10 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9015          10 :         poDS->GetLayerByName(pszTableName));
    9016          10 :     if (poLyr == nullptr)
    9017             :     {
    9018           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9019           1 :         sqlite3_result_int(pContext, 0);
    9020           1 :         return;
    9021             :     }
    9022           9 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9023             :     {
    9024           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9025           1 :         sqlite3_result_int(pContext, 0);
    9026           1 :         return;
    9027             :     }
    9028             : 
    9029           8 :     sqlite3_result_int(pContext, poLyr->DropSpatialIndex(true));
    9030             : }
    9031             : 
    9032             : /************************************************************************/
    9033             : /*                  OGRGeoPackageHasSpatialIndex()                      */
    9034             : /************************************************************************/
    9035             : 
    9036          29 : static void OGRGeoPackageHasSpatialIndex(sqlite3_context *pContext,
    9037             :                                          int /*argc*/, sqlite3_value **argv)
    9038             : {
    9039          57 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9040          28 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9041             :     {
    9042           2 :         sqlite3_result_int(pContext, 0);
    9043           2 :         return;
    9044             :     }
    9045             : 
    9046             :     const char *pszTableName =
    9047          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9048             :     const char *pszGeomName =
    9049          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9050             :     GDALGeoPackageDataset *poDS =
    9051          27 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9052             : 
    9053          27 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9054          27 :         poDS->GetLayerByName(pszTableName));
    9055          27 :     if (poLyr == nullptr)
    9056             :     {
    9057           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9058           1 :         sqlite3_result_int(pContext, 0);
    9059           1 :         return;
    9060             :     }
    9061          26 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9062             :     {
    9063           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9064           1 :         sqlite3_result_int(pContext, 0);
    9065           1 :         return;
    9066             :     }
    9067             : 
    9068          25 :     poLyr->RunDeferredCreationIfNecessary();
    9069          25 :     poLyr->CreateSpatialIndexIfNecessary();
    9070             : 
    9071          25 :     sqlite3_result_int(pContext, poLyr->HasSpatialIndex());
    9072             : }
    9073             : 
    9074             : /************************************************************************/
    9075             : /*                       GPKG_hstore_get_value()                        */
    9076             : /************************************************************************/
    9077             : 
    9078           4 : static void GPKG_hstore_get_value(sqlite3_context *pContext, int /*argc*/,
    9079             :                                   sqlite3_value **argv)
    9080             : {
    9081           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9082           3 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9083             :     {
    9084           2 :         sqlite3_result_null(pContext);
    9085           2 :         return;
    9086             :     }
    9087             : 
    9088             :     const char *pszHStore =
    9089           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9090             :     const char *pszSearchedKey =
    9091           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9092           2 :     char *pszValue = OGRHStoreGetValue(pszHStore, pszSearchedKey);
    9093           2 :     if (pszValue != nullptr)
    9094           1 :         sqlite3_result_text(pContext, pszValue, -1, CPLFree);
    9095             :     else
    9096           1 :         sqlite3_result_null(pContext);
    9097             : }
    9098             : 
    9099             : /************************************************************************/
    9100             : /*                      GPKG_GDAL_GetMemFileFromBlob()                  */
    9101             : /************************************************************************/
    9102             : 
    9103         105 : static CPLString GPKG_GDAL_GetMemFileFromBlob(sqlite3_value **argv)
    9104             : {
    9105         105 :     int nBytes = sqlite3_value_bytes(argv[0]);
    9106             :     const GByte *pabyBLOB =
    9107         105 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    9108             :     CPLString osMemFileName(
    9109         105 :         VSIMemGenerateHiddenFilename("GPKG_GDAL_GetMemFileFromBlob"));
    9110         105 :     VSILFILE *fp = VSIFileFromMemBuffer(
    9111             :         osMemFileName.c_str(), const_cast<GByte *>(pabyBLOB), nBytes, FALSE);
    9112         105 :     VSIFCloseL(fp);
    9113         105 :     return osMemFileName;
    9114             : }
    9115             : 
    9116             : /************************************************************************/
    9117             : /*                       GPKG_GDAL_GetMimeType()                        */
    9118             : /************************************************************************/
    9119             : 
    9120          35 : static void GPKG_GDAL_GetMimeType(sqlite3_context *pContext, int /*argc*/,
    9121             :                                   sqlite3_value **argv)
    9122             : {
    9123          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9124             :     {
    9125           0 :         sqlite3_result_null(pContext);
    9126           0 :         return;
    9127             :     }
    9128             : 
    9129          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9130             :     GDALDriver *poDriver =
    9131          35 :         GDALDriver::FromHandle(GDALIdentifyDriver(osMemFileName, nullptr));
    9132          35 :     if (poDriver != nullptr)
    9133             :     {
    9134          35 :         const char *pszRes = nullptr;
    9135          35 :         if (EQUAL(poDriver->GetDescription(), "PNG"))
    9136          23 :             pszRes = "image/png";
    9137          12 :         else if (EQUAL(poDriver->GetDescription(), "JPEG"))
    9138           6 :             pszRes = "image/jpeg";
    9139           6 :         else if (EQUAL(poDriver->GetDescription(), "WEBP"))
    9140           6 :             pszRes = "image/x-webp";
    9141           0 :         else if (EQUAL(poDriver->GetDescription(), "GTIFF"))
    9142           0 :             pszRes = "image/tiff";
    9143             :         else
    9144           0 :             pszRes = CPLSPrintf("gdal/%s", poDriver->GetDescription());
    9145          35 :         sqlite3_result_text(pContext, pszRes, -1, SQLITE_TRANSIENT);
    9146             :     }
    9147             :     else
    9148           0 :         sqlite3_result_null(pContext);
    9149          35 :     VSIUnlink(osMemFileName);
    9150             : }
    9151             : 
    9152             : /************************************************************************/
    9153             : /*                       GPKG_GDAL_GetBandCount()                       */
    9154             : /************************************************************************/
    9155             : 
    9156          35 : static void GPKG_GDAL_GetBandCount(sqlite3_context *pContext, int /*argc*/,
    9157             :                                    sqlite3_value **argv)
    9158             : {
    9159          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9160             :     {
    9161           0 :         sqlite3_result_null(pContext);
    9162           0 :         return;
    9163             :     }
    9164             : 
    9165          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9166             :     auto poDS = std::unique_ptr<GDALDataset>(
    9167             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9168          70 :                           nullptr, nullptr, nullptr));
    9169          35 :     if (poDS != nullptr)
    9170             :     {
    9171          35 :         sqlite3_result_int(pContext, poDS->GetRasterCount());
    9172             :     }
    9173             :     else
    9174           0 :         sqlite3_result_null(pContext);
    9175          35 :     VSIUnlink(osMemFileName);
    9176             : }
    9177             : 
    9178             : /************************************************************************/
    9179             : /*                       GPKG_GDAL_HasColorTable()                      */
    9180             : /************************************************************************/
    9181             : 
    9182          35 : static void GPKG_GDAL_HasColorTable(sqlite3_context *pContext, int /*argc*/,
    9183             :                                     sqlite3_value **argv)
    9184             : {
    9185          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9186             :     {
    9187           0 :         sqlite3_result_null(pContext);
    9188           0 :         return;
    9189             :     }
    9190             : 
    9191          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9192             :     auto poDS = std::unique_ptr<GDALDataset>(
    9193             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9194          70 :                           nullptr, nullptr, nullptr));
    9195          35 :     if (poDS != nullptr)
    9196             :     {
    9197          35 :         sqlite3_result_int(
    9198          46 :             pContext, poDS->GetRasterCount() == 1 &&
    9199          11 :                           poDS->GetRasterBand(1)->GetColorTable() != nullptr);
    9200             :     }
    9201             :     else
    9202           0 :         sqlite3_result_null(pContext);
    9203          35 :     VSIUnlink(osMemFileName);
    9204             : }
    9205             : 
    9206             : /************************************************************************/
    9207             : /*                      GetRasterLayerDataset()                         */
    9208             : /************************************************************************/
    9209             : 
    9210             : GDALDataset *
    9211          12 : GDALGeoPackageDataset::GetRasterLayerDataset(const char *pszLayerName)
    9212             : {
    9213          12 :     const auto oIter = m_oCachedRasterDS.find(pszLayerName);
    9214          12 :     if (oIter != m_oCachedRasterDS.end())
    9215          10 :         return oIter->second.get();
    9216             : 
    9217             :     auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
    9218           4 :         (std::string("GPKG:\"") + m_pszFilename + "\":" + pszLayerName).c_str(),
    9219           4 :         GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR));
    9220           2 :     if (!poDS)
    9221             :     {
    9222           0 :         return nullptr;
    9223             :     }
    9224           2 :     m_oCachedRasterDS[pszLayerName] = std::move(poDS);
    9225           2 :     return m_oCachedRasterDS[pszLayerName].get();
    9226             : }
    9227             : 
    9228             : /************************************************************************/
    9229             : /*                   GPKG_gdal_get_layer_pixel_value()                  */
    9230             : /************************************************************************/
    9231             : 
    9232             : // NOTE: keep in sync implementations in ogrsqlitesqlfunctionscommon.cpp
    9233             : // and ogrgeopackagedatasource.cpp
    9234          13 : static void GPKG_gdal_get_layer_pixel_value(sqlite3_context *pContext, int argc,
    9235             :                                             sqlite3_value **argv)
    9236             : {
    9237          13 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9238             :     {
    9239           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9240             :                  "Invalid arguments to gdal_get_layer_pixel_value()");
    9241           1 :         sqlite3_result_null(pContext);
    9242           1 :         return;
    9243             :     }
    9244             : 
    9245             :     const char *pszLayerName =
    9246          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9247             : 
    9248             :     GDALGeoPackageDataset *poGlobalDS =
    9249          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9250          12 :     auto poDS = poGlobalDS->GetRasterLayerDataset(pszLayerName);
    9251          12 :     if (!poDS)
    9252             :     {
    9253           0 :         sqlite3_result_null(pContext);
    9254           0 :         return;
    9255             :     }
    9256             : 
    9257          12 :     OGRSQLite_gdal_get_pixel_value_common("gdal_get_layer_pixel_value",
    9258             :                                           pContext, argc, argv, poDS);
    9259             : }
    9260             : 
    9261             : /************************************************************************/
    9262             : /*                       GPKG_ogr_layer_Extent()                        */
    9263             : /************************************************************************/
    9264             : 
    9265           3 : static void GPKG_ogr_layer_Extent(sqlite3_context *pContext, int /*argc*/,
    9266             :                                   sqlite3_value **argv)
    9267             : {
    9268           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9269             :     {
    9270           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Invalid argument type",
    9271             :                  "ogr_layer_Extent");
    9272           1 :         sqlite3_result_null(pContext);
    9273           2 :         return;
    9274             :     }
    9275             : 
    9276             :     const char *pszLayerName =
    9277           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9278             :     GDALGeoPackageDataset *poDS =
    9279           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9280           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9281           2 :     if (!poLayer)
    9282             :     {
    9283           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer",
    9284             :                  "ogr_layer_Extent");
    9285           1 :         sqlite3_result_null(pContext);
    9286           1 :         return;
    9287             :     }
    9288             : 
    9289           1 :     if (poLayer->GetGeomType() == wkbNone)
    9290             :     {
    9291           0 :         sqlite3_result_null(pContext);
    9292           0 :         return;
    9293             :     }
    9294             : 
    9295           1 :     OGREnvelope sExtent;
    9296           1 :     if (poLayer->GetExtent(&sExtent) != OGRERR_NONE)
    9297             :     {
    9298           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9299             :                  "ogr_layer_Extent");
    9300           0 :         sqlite3_result_null(pContext);
    9301           0 :         return;
    9302             :     }
    9303             : 
    9304           1 :     OGRPolygon oPoly;
    9305           1 :     auto poRing = std::make_unique<OGRLinearRing>();
    9306           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9307           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MinY);
    9308           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MaxY);
    9309           1 :     poRing->addPoint(sExtent.MinX, sExtent.MaxY);
    9310           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9311           1 :     oPoly.addRing(std::move(poRing));
    9312             : 
    9313           1 :     const auto poSRS = poLayer->GetSpatialRef();
    9314           1 :     const int nSRID = poDS->GetSrsId(poSRS);
    9315           1 :     size_t nBLOBDestLen = 0;
    9316             :     GByte *pabyDestBLOB =
    9317           1 :         GPkgGeometryFromOGR(&oPoly, nSRID, nullptr, &nBLOBDestLen);
    9318           1 :     if (!pabyDestBLOB)
    9319             :     {
    9320           0 :         sqlite3_result_null(pContext);
    9321           0 :         return;
    9322             :     }
    9323           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    9324             :                         VSIFree);
    9325             : }
    9326             : 
    9327             : /************************************************************************/
    9328             : /*                      InstallSQLFunctions()                           */
    9329             : /************************************************************************/
    9330             : 
    9331             : #ifndef SQLITE_DETERMINISTIC
    9332             : #define SQLITE_DETERMINISTIC 0
    9333             : #endif
    9334             : 
    9335             : #ifndef SQLITE_INNOCUOUS
    9336             : #define SQLITE_INNOCUOUS 0
    9337             : #endif
    9338             : 
    9339             : #ifndef UTF8_INNOCUOUS
    9340             : #define UTF8_INNOCUOUS (SQLITE_UTF8 | SQLITE_DETERMINISTIC | SQLITE_INNOCUOUS)
    9341             : #endif
    9342             : 
    9343        2224 : void GDALGeoPackageDataset::InstallSQLFunctions()
    9344             : {
    9345        2224 :     InitSpatialite();
    9346             : 
    9347             :     // Enable SpatiaLite 4.3 "amphibious" mode, i.e. that SpatiaLite functions
    9348             :     // that take geometries will accept GPKG encoded geometries without
    9349             :     // explicit conversion.
    9350             :     // Use sqlite3_exec() instead of SQLCommand() since we don't want verbose
    9351             :     // error.
    9352        2224 :     sqlite3_exec(hDB, "SELECT EnableGpkgAmphibiousMode()", nullptr, nullptr,
    9353             :                  nullptr);
    9354             : 
    9355             :     /* Used by RTree Spatial Index Extension */
    9356        2224 :     sqlite3_create_function(hDB, "ST_MinX", 1, UTF8_INNOCUOUS, nullptr,
    9357             :                             OGRGeoPackageSTMinX, nullptr, nullptr);
    9358        2224 :     sqlite3_create_function(hDB, "ST_MinY", 1, UTF8_INNOCUOUS, nullptr,
    9359             :                             OGRGeoPackageSTMinY, nullptr, nullptr);
    9360        2224 :     sqlite3_create_function(hDB, "ST_MaxX", 1, UTF8_INNOCUOUS, nullptr,
    9361             :                             OGRGeoPackageSTMaxX, nullptr, nullptr);
    9362        2224 :     sqlite3_create_function(hDB, "ST_MaxY", 1, UTF8_INNOCUOUS, nullptr,
    9363             :                             OGRGeoPackageSTMaxY, nullptr, nullptr);
    9364        2224 :     sqlite3_create_function(hDB, "ST_IsEmpty", 1, UTF8_INNOCUOUS, nullptr,
    9365             :                             OGRGeoPackageSTIsEmpty, nullptr, nullptr);
    9366             : 
    9367             :     /* Used by Geometry Type Triggers Extension */
    9368        2224 :     sqlite3_create_function(hDB, "ST_GeometryType", 1, UTF8_INNOCUOUS, nullptr,
    9369             :                             OGRGeoPackageSTGeometryType, nullptr, nullptr);
    9370        2224 :     sqlite3_create_function(hDB, "GPKG_IsAssignable", 2, UTF8_INNOCUOUS,
    9371             :                             nullptr, OGRGeoPackageGPKGIsAssignable, nullptr,
    9372             :                             nullptr);
    9373             : 
    9374             :     /* Used by Geometry SRS ID Triggers Extension */
    9375        2224 :     sqlite3_create_function(hDB, "ST_SRID", 1, UTF8_INNOCUOUS, nullptr,
    9376             :                             OGRGeoPackageSTSRID, nullptr, nullptr);
    9377             : 
    9378             :     /* Spatialite-like functions */
    9379        2224 :     sqlite3_create_function(hDB, "CreateSpatialIndex", 2, SQLITE_UTF8, this,
    9380             :                             OGRGeoPackageCreateSpatialIndex, nullptr, nullptr);
    9381        2224 :     sqlite3_create_function(hDB, "DisableSpatialIndex", 2, SQLITE_UTF8, this,
    9382             :                             OGRGeoPackageDisableSpatialIndex, nullptr, nullptr);
    9383        2224 :     sqlite3_create_function(hDB, "HasSpatialIndex", 2, SQLITE_UTF8, this,
    9384             :                             OGRGeoPackageHasSpatialIndex, nullptr, nullptr);
    9385             : 
    9386             :     // HSTORE functions
    9387        2224 :     sqlite3_create_function(hDB, "hstore_get_value", 2, UTF8_INNOCUOUS, nullptr,
    9388             :                             GPKG_hstore_get_value, nullptr, nullptr);
    9389             : 
    9390             :     // Override a few Spatialite functions to work with gpkg_spatial_ref_sys
    9391        2224 :     sqlite3_create_function(hDB, "ST_Transform", 2, UTF8_INNOCUOUS, this,
    9392             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9393        2224 :     sqlite3_create_function(hDB, "Transform", 2, UTF8_INNOCUOUS, this,
    9394             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9395        2224 :     sqlite3_create_function(hDB, "SridFromAuthCRS", 2, SQLITE_UTF8, this,
    9396             :                             OGRGeoPackageSridFromAuthCRS, nullptr, nullptr);
    9397             : 
    9398        2224 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9399             :                             OGRGeoPackageSTEnvelopesIntersectsTwoParams,
    9400             :                             nullptr, nullptr);
    9401        2224 :     sqlite3_create_function(
    9402             :         hDB, "ST_EnvelopesIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9403             :         OGRGeoPackageSTEnvelopesIntersectsTwoParams, nullptr, nullptr);
    9404             : 
    9405        2224 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 5, UTF8_INNOCUOUS, nullptr,
    9406             :                             OGRGeoPackageSTEnvelopesIntersects, nullptr,
    9407             :                             nullptr);
    9408        2224 :     sqlite3_create_function(hDB, "ST_EnvelopesIntersects", 5, UTF8_INNOCUOUS,
    9409             :                             nullptr, OGRGeoPackageSTEnvelopesIntersects,
    9410             :                             nullptr, nullptr);
    9411             : 
    9412             :     // Implementation that directly hacks the GeoPackage geometry blob header
    9413        2224 :     sqlite3_create_function(hDB, "SetSRID", 2, UTF8_INNOCUOUS, nullptr,
    9414             :                             OGRGeoPackageSetSRID, nullptr, nullptr);
    9415             : 
    9416             :     // GDAL specific function
    9417        2224 :     sqlite3_create_function(hDB, "ImportFromEPSG", 1, SQLITE_UTF8, this,
    9418             :                             OGRGeoPackageImportFromEPSG, nullptr, nullptr);
    9419             : 
    9420             :     // May be used by ogrmerge.py
    9421        2224 :     sqlite3_create_function(hDB, "RegisterGeometryExtension", 3, SQLITE_UTF8,
    9422             :                             this, OGRGeoPackageRegisterGeometryExtension,
    9423             :                             nullptr, nullptr);
    9424             : 
    9425        2224 :     if (OGRGeometryFactory::haveGEOS())
    9426             :     {
    9427        2224 :         sqlite3_create_function(hDB, "ST_MakeValid", 1, UTF8_INNOCUOUS, nullptr,
    9428             :                                 OGRGeoPackageSTMakeValid, nullptr, nullptr);
    9429             :     }
    9430             : 
    9431        2224 :     sqlite3_create_function(hDB, "ST_Length", 1, UTF8_INNOCUOUS, nullptr,
    9432             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9433             :                             nullptr);
    9434        2224 :     sqlite3_create_function(hDB, "ST_Length", 2, UTF8_INNOCUOUS, this,
    9435             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9436             :                             nullptr);
    9437             : 
    9438        2224 :     sqlite3_create_function(hDB, "ST_Area", 1, UTF8_INNOCUOUS, nullptr,
    9439             :                             OGRGeoPackageSTArea, nullptr, nullptr);
    9440        2224 :     sqlite3_create_function(hDB, "ST_Area", 2, UTF8_INNOCUOUS, this,
    9441             :                             OGRGeoPackageGeodesicArea, nullptr, nullptr);
    9442             : 
    9443             :     // Debug functions
    9444        2224 :     if (CPLTestBool(CPLGetConfigOption("GPKG_DEBUG", "FALSE")))
    9445             :     {
    9446         422 :         sqlite3_create_function(hDB, "GDAL_GetMimeType", 1,
    9447             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9448             :                                 GPKG_GDAL_GetMimeType, nullptr, nullptr);
    9449         422 :         sqlite3_create_function(hDB, "GDAL_GetBandCount", 1,
    9450             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9451             :                                 GPKG_GDAL_GetBandCount, nullptr, nullptr);
    9452         422 :         sqlite3_create_function(hDB, "GDAL_HasColorTable", 1,
    9453             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9454             :                                 GPKG_GDAL_HasColorTable, nullptr, nullptr);
    9455             :     }
    9456             : 
    9457        2224 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 5, SQLITE_UTF8,
    9458             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9459             :                             nullptr);
    9460        2224 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 6, SQLITE_UTF8,
    9461             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9462             :                             nullptr);
    9463             : 
    9464             :     // Function from VirtualOGR
    9465        2224 :     sqlite3_create_function(hDB, "ogr_layer_Extent", 1, SQLITE_UTF8, this,
    9466             :                             GPKG_ogr_layer_Extent, nullptr, nullptr);
    9467             : 
    9468        2224 :     m_pSQLFunctionData = OGRSQLiteRegisterSQLFunctionsCommon(hDB);
    9469        2224 : }
    9470             : 
    9471             : /************************************************************************/
    9472             : /*                         OpenOrCreateDB()                             */
    9473             : /************************************************************************/
    9474             : 
    9475        2228 : bool GDALGeoPackageDataset::OpenOrCreateDB(int flags)
    9476             : {
    9477        2228 :     const bool bSuccess = OGRSQLiteBaseDataSource::OpenOrCreateDB(
    9478             :         flags, /*bRegisterOGR2SQLiteExtensions=*/false,
    9479             :         /*bLoadExtensions=*/true);
    9480        2228 :     if (!bSuccess)
    9481           9 :         return false;
    9482             : 
    9483             :     // Turning on recursive_triggers is needed so that DELETE triggers fire
    9484             :     // in a INSERT OR REPLACE statement. In particular this is needed to
    9485             :     // make sure gpkg_ogr_contents.feature_count is properly updated.
    9486        2219 :     SQLCommand(hDB, "PRAGMA recursive_triggers = 1");
    9487             : 
    9488        2219 :     InstallSQLFunctions();
    9489             : 
    9490             :     const char *pszSqlitePragma =
    9491        2219 :         CPLGetConfigOption("OGR_SQLITE_PRAGMA", nullptr);
    9492        2219 :     OGRErr eErr = OGRERR_NONE;
    9493           6 :     if ((!pszSqlitePragma || !strstr(pszSqlitePragma, "trusted_schema")) &&
    9494             :         // Older sqlite versions don't have this pragma
    9495        4444 :         SQLGetInteger(hDB, "PRAGMA trusted_schema", &eErr) == 0 &&
    9496        2219 :         eErr == OGRERR_NONE)
    9497             :     {
    9498        2219 :         bool bNeedsTrustedSchema = false;
    9499             : 
    9500             :         // Current SQLite versions require PRAGMA trusted_schema = 1 to be
    9501             :         // able to use the RTree from triggers, which is only needed when
    9502             :         // modifying the RTree.
    9503        5449 :         if (((flags & SQLITE_OPEN_READWRITE) != 0 ||
    9504        3427 :              (flags & SQLITE_OPEN_CREATE) != 0) &&
    9505        1208 :             OGRSQLiteRTreeRequiresTrustedSchemaOn())
    9506             :         {
    9507        1208 :             bNeedsTrustedSchema = true;
    9508             :         }
    9509             : 
    9510             : #ifdef HAVE_SPATIALITE
    9511             :         // Spatialite <= 5.1.0 doesn't declare its functions as SQLITE_INNOCUOUS
    9512        1011 :         if (!bNeedsTrustedSchema && HasExtensionsTable() &&
    9513         921 :             SQLGetInteger(
    9514             :                 hDB,
    9515             :                 "SELECT 1 FROM gpkg_extensions WHERE "
    9516             :                 "extension_name ='gdal_spatialite_computed_geom_column'",
    9517           1 :                 nullptr) == 1 &&
    9518        3230 :             SpatialiteRequiresTrustedSchemaOn() && AreSpatialiteTriggersSafe())
    9519             :         {
    9520           1 :             bNeedsTrustedSchema = true;
    9521             :         }
    9522             : #endif
    9523             : 
    9524        2219 :         if (bNeedsTrustedSchema)
    9525             :         {
    9526        1209 :             CPLDebug("GPKG", "Setting PRAGMA trusted_schema = 1");
    9527        1209 :             SQLCommand(hDB, "PRAGMA trusted_schema = 1");
    9528             :         }
    9529             :     }
    9530             : 
    9531             :     const char *pszPreludeStatements =
    9532        2219 :         CSLFetchNameValue(papszOpenOptions, "PRELUDE_STATEMENTS");
    9533        2219 :     if (pszPreludeStatements)
    9534             :     {
    9535           2 :         if (SQLCommand(hDB, pszPreludeStatements) != OGRERR_NONE)
    9536           0 :             return false;
    9537             :     }
    9538             : 
    9539        2219 :     return true;
    9540             : }
    9541             : 
    9542             : /************************************************************************/
    9543             : /*                   GetLayerWithGetSpatialWhereByName()                */
    9544             : /************************************************************************/
    9545             : 
    9546             : std::pair<OGRLayer *, IOGRSQLiteGetSpatialWhere *>
    9547          90 : GDALGeoPackageDataset::GetLayerWithGetSpatialWhereByName(const char *pszName)
    9548             : {
    9549             :     OGRGeoPackageLayer *poRet =
    9550          90 :         cpl::down_cast<OGRGeoPackageLayer *>(GetLayerByName(pszName));
    9551          90 :     return std::pair(poRet, poRet);
    9552             : }
    9553             : 
    9554             : /************************************************************************/
    9555             : /*                       CommitTransaction()                            */
    9556             : /************************************************************************/
    9557             : 
    9558         321 : OGRErr GDALGeoPackageDataset::CommitTransaction()
    9559             : 
    9560             : {
    9561         321 :     if (m_nSoftTransactionLevel == 1)
    9562             :     {
    9563         315 :         FlushMetadata();
    9564         681 :         for (auto &poLayer : m_apoLayers)
    9565             :         {
    9566         366 :             poLayer->DoJobAtTransactionCommit();
    9567             :         }
    9568             :     }
    9569             : 
    9570         321 :     return OGRSQLiteBaseDataSource::CommitTransaction();
    9571             : }
    9572             : 
    9573             : /************************************************************************/
    9574             : /*                     RollbackTransaction()                            */
    9575             : /************************************************************************/
    9576             : 
    9577          35 : OGRErr GDALGeoPackageDataset::RollbackTransaction()
    9578             : 
    9579             : {
    9580             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9581          70 :     std::vector<bool> abAddTriggers;
    9582          35 :     std::vector<bool> abTriggersDeletedInTransaction;
    9583             : #endif
    9584          35 :     if (m_nSoftTransactionLevel == 1)
    9585             :     {
    9586          34 :         FlushMetadata();
    9587          70 :         for (auto &poLayer : m_apoLayers)
    9588             :         {
    9589             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9590          36 :             abAddTriggers.push_back(poLayer->GetAddOGRFeatureCountTriggers());
    9591          36 :             abTriggersDeletedInTransaction.push_back(
    9592          36 :                 poLayer->GetOGRFeatureCountTriggersDeletedInTransaction());
    9593          36 :             poLayer->SetAddOGRFeatureCountTriggers(false);
    9594             : #endif
    9595          36 :             poLayer->DoJobAtTransactionRollback();
    9596             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9597          36 :             poLayer->DisableFeatureCount();
    9598             : #endif
    9599             :         }
    9600             :     }
    9601             : 
    9602          35 :     const OGRErr eErr = OGRSQLiteBaseDataSource::RollbackTransaction();
    9603             : 
    9604             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9605          35 :     if (!abAddTriggers.empty())
    9606             :     {
    9607          68 :         for (size_t i = 0; i < m_apoLayers.size(); ++i)
    9608             :         {
    9609          36 :             auto &poLayer = m_apoLayers[i];
    9610          36 :             if (abTriggersDeletedInTransaction[i])
    9611             :             {
    9612           7 :                 poLayer->SetOGRFeatureCountTriggersEnabled(true);
    9613             :             }
    9614             :             else
    9615             :             {
    9616          29 :                 poLayer->SetAddOGRFeatureCountTriggers(abAddTriggers[i]);
    9617             :             }
    9618             :         }
    9619             :     }
    9620             : #endif
    9621          70 :     return eErr;
    9622             : }
    9623             : 
    9624             : /************************************************************************/
    9625             : /*                       GetGeometryTypeString()                        */
    9626             : /************************************************************************/
    9627             : 
    9628             : const char *
    9629        1569 : GDALGeoPackageDataset::GetGeometryTypeString(OGRwkbGeometryType eType)
    9630             : {
    9631        1569 :     const char *pszGPKGGeomType = OGRToOGCGeomType(eType);
    9632        1581 :     if (EQUAL(pszGPKGGeomType, "GEOMETRYCOLLECTION") &&
    9633          12 :         CPLTestBool(CPLGetConfigOption("OGR_GPKG_GEOMCOLLECTION", "NO")))
    9634             :     {
    9635           0 :         pszGPKGGeomType = "GEOMCOLLECTION";
    9636             :     }
    9637        1569 :     return pszGPKGGeomType;
    9638             : }
    9639             : 
    9640             : /************************************************************************/
    9641             : /*                           GetFieldDomainNames()                      */
    9642             : /************************************************************************/
    9643             : 
    9644             : std::vector<std::string>
    9645          13 : GDALGeoPackageDataset::GetFieldDomainNames(CSLConstList) const
    9646             : {
    9647          13 :     if (!HasDataColumnConstraintsTable())
    9648           4 :         return std::vector<std::string>();
    9649             : 
    9650          18 :     std::vector<std::string> oDomainNamesList;
    9651             : 
    9652           9 :     std::unique_ptr<SQLResult> oResultTable;
    9653             :     {
    9654             :         std::string osSQL =
    9655             :             "SELECT DISTINCT constraint_name "
    9656             :             "FROM gpkg_data_column_constraints "
    9657             :             "WHERE constraint_name NOT LIKE '_%_domain_description' "
    9658             :             "ORDER BY constraint_name "
    9659           9 :             "LIMIT 10000"  // to avoid denial of service
    9660             :             ;
    9661           9 :         oResultTable = SQLQuery(hDB, osSQL.c_str());
    9662           9 :         if (!oResultTable)
    9663           0 :             return oDomainNamesList;
    9664             :     }
    9665             : 
    9666           9 :     if (oResultTable->RowCount() == 10000)
    9667             :     {
    9668           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9669             :                  "Number of rows returned for field domain names has been "
    9670             :                  "truncated.");
    9671             :     }
    9672           9 :     else if (oResultTable->RowCount() > 0)
    9673             :     {
    9674           8 :         oDomainNamesList.reserve(oResultTable->RowCount());
    9675         105 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    9676             :         {
    9677          97 :             const char *pszConstraintName = oResultTable->GetValue(0, i);
    9678          97 :             if (!pszConstraintName)
    9679           0 :                 continue;
    9680             : 
    9681          97 :             oDomainNamesList.emplace_back(pszConstraintName);
    9682             :         }
    9683             :     }
    9684             : 
    9685           9 :     return oDomainNamesList;
    9686             : }
    9687             : 
    9688             : /************************************************************************/
    9689             : /*                           GetFieldDomain()                           */
    9690             : /************************************************************************/
    9691             : 
    9692             : const OGRFieldDomain *
    9693         138 : GDALGeoPackageDataset::GetFieldDomain(const std::string &name) const
    9694             : {
    9695         138 :     const auto baseRet = GDALDataset::GetFieldDomain(name);
    9696         138 :     if (baseRet)
    9697          43 :         return baseRet;
    9698             : 
    9699          95 :     if (!HasDataColumnConstraintsTable())
    9700           4 :         return nullptr;
    9701             : 
    9702          91 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
    9703          91 :     const char *min_is_inclusive =
    9704          91 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
    9705          91 :     const char *max_is_inclusive =
    9706          91 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
    9707             : 
    9708          91 :     std::unique_ptr<SQLResult> oResultTable;
    9709             :     // Note: for coded domains, we use a little trick by using a dummy
    9710             :     // _{domainname}_domain_description enum that has a single entry whose
    9711             :     // description is the description of the main domain.
    9712             :     {
    9713          91 :         char *pszSQL = sqlite3_mprintf(
    9714             :             "SELECT constraint_type, value, min, %s, "
    9715             :             "max, %s, description, constraint_name "
    9716             :             "FROM gpkg_data_column_constraints "
    9717             :             "WHERE constraint_name IN ('%q', "
    9718             :             "'_%q_domain_description') "
    9719             :             "AND length(constraint_type) < 100 "  // to
    9720             :                                                   // avoid
    9721             :                                                   // denial
    9722             :                                                   // of
    9723             :                                                   // service
    9724             :             "AND (value IS NULL OR length(value) < "
    9725             :             "10000) "  // to avoid denial
    9726             :                        // of service
    9727             :             "AND (description IS NULL OR "
    9728             :             "length(description) < 10000) "  // to
    9729             :                                              // avoid
    9730             :                                              // denial
    9731             :                                              // of
    9732             :                                              // service
    9733             :             "ORDER BY value "
    9734             :             "LIMIT 10000",  // to avoid denial of
    9735             :                             // service
    9736             :             min_is_inclusive, max_is_inclusive, name.c_str(), name.c_str());
    9737          91 :         oResultTable = SQLQuery(hDB, pszSQL);
    9738          91 :         sqlite3_free(pszSQL);
    9739          91 :         if (!oResultTable)
    9740           0 :             return nullptr;
    9741             :     }
    9742          91 :     if (oResultTable->RowCount() == 0)
    9743             :     {
    9744          33 :         return nullptr;
    9745             :     }
    9746          58 :     if (oResultTable->RowCount() == 10000)
    9747             :     {
    9748           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9749             :                  "Number of rows returned for field domain %s has been "
    9750             :                  "truncated.",
    9751             :                  name.c_str());
    9752             :     }
    9753             : 
    9754             :     // Try to find the field domain data type from fields that implement it
    9755          58 :     int nFieldType = -1;
    9756          58 :     OGRFieldSubType eSubType = OFSTNone;
    9757          58 :     if (HasDataColumnsTable())
    9758             :     {
    9759          53 :         char *pszSQL = sqlite3_mprintf(
    9760             :             "SELECT table_name, column_name FROM gpkg_data_columns WHERE "
    9761             :             "constraint_name = '%q' LIMIT 10",
    9762             :             name.c_str());
    9763         106 :         auto oResultTable2 = SQLQuery(hDB, pszSQL);
    9764          53 :         sqlite3_free(pszSQL);
    9765          53 :         if (oResultTable2 && oResultTable2->RowCount() >= 1)
    9766             :         {
    9767          58 :             for (int iRecord = 0; iRecord < oResultTable2->RowCount();
    9768             :                  iRecord++)
    9769             :             {
    9770          29 :                 const char *pszTableName = oResultTable2->GetValue(0, iRecord);
    9771          29 :                 const char *pszColumnName = oResultTable2->GetValue(1, iRecord);
    9772          29 :                 if (pszTableName == nullptr || pszColumnName == nullptr)
    9773           0 :                     continue;
    9774             :                 OGRLayer *poLayer =
    9775          58 :                     const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    9776          29 :                         pszTableName);
    9777          29 :                 if (poLayer)
    9778             :                 {
    9779          29 :                     const auto poFDefn = poLayer->GetLayerDefn();
    9780          29 :                     int nIdx = poFDefn->GetFieldIndex(pszColumnName);
    9781          29 :                     if (nIdx >= 0)
    9782             :                     {
    9783          29 :                         const auto poFieldDefn = poFDefn->GetFieldDefn(nIdx);
    9784          29 :                         const auto eType = poFieldDefn->GetType();
    9785          29 :                         if (nFieldType < 0)
    9786             :                         {
    9787          29 :                             nFieldType = eType;
    9788          29 :                             eSubType = poFieldDefn->GetSubType();
    9789             :                         }
    9790           0 :                         else if ((eType == OFTInteger64 || eType == OFTReal) &&
    9791             :                                  nFieldType == OFTInteger)
    9792             :                         {
    9793             :                             // ok
    9794             :                         }
    9795           0 :                         else if (eType == OFTInteger &&
    9796           0 :                                  (nFieldType == OFTInteger64 ||
    9797             :                                   nFieldType == OFTReal))
    9798             :                         {
    9799           0 :                             nFieldType = OFTInteger;
    9800           0 :                             eSubType = OFSTNone;
    9801             :                         }
    9802           0 :                         else if (nFieldType != eType)
    9803             :                         {
    9804           0 :                             nFieldType = -1;
    9805           0 :                             eSubType = OFSTNone;
    9806           0 :                             break;
    9807             :                         }
    9808             :                     }
    9809             :                 }
    9810             :             }
    9811             :         }
    9812             :     }
    9813             : 
    9814          58 :     std::unique_ptr<OGRFieldDomain> poDomain;
    9815         116 :     std::vector<OGRCodedValue> asValues;
    9816          58 :     bool error = false;
    9817         116 :     CPLString osLastConstraintType;
    9818          58 :     int nFieldTypeFromEnumCode = -1;
    9819         116 :     std::string osConstraintDescription;
    9820         116 :     std::string osDescrConstraintName("_");
    9821          58 :     osDescrConstraintName += name;
    9822          58 :     osDescrConstraintName += "_domain_description";
    9823         145 :     for (int iRecord = 0; iRecord < oResultTable->RowCount(); iRecord++)
    9824             :     {
    9825          91 :         const char *pszConstraintType = oResultTable->GetValue(0, iRecord);
    9826          91 :         if (pszConstraintType == nullptr)
    9827           2 :             continue;
    9828          91 :         const char *pszValue = oResultTable->GetValue(1, iRecord);
    9829          91 :         const char *pszMin = oResultTable->GetValue(2, iRecord);
    9830             :         const bool bIsMinIncluded =
    9831          91 :             oResultTable->GetValueAsInteger(3, iRecord) == 1;
    9832          91 :         const char *pszMax = oResultTable->GetValue(4, iRecord);
    9833             :         const bool bIsMaxIncluded =
    9834          91 :             oResultTable->GetValueAsInteger(5, iRecord) == 1;
    9835          91 :         const char *pszDescription = oResultTable->GetValue(6, iRecord);
    9836          91 :         const char *pszConstraintName = oResultTable->GetValue(7, iRecord);
    9837             : 
    9838          91 :         if (!osLastConstraintType.empty() && osLastConstraintType != "enum")
    9839             :         {
    9840           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    9841             :                      "Only constraint of type 'enum' can have multiple rows");
    9842           1 :             error = true;
    9843           4 :             break;
    9844             :         }
    9845             : 
    9846          90 :         if (strcmp(pszConstraintType, "enum") == 0)
    9847             :         {
    9848          63 :             if (pszValue == nullptr)
    9849             :             {
    9850           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    9851             :                          "NULL in 'value' column of enumeration");
    9852           1 :                 error = true;
    9853           1 :                 break;
    9854             :             }
    9855          62 :             if (osDescrConstraintName == pszConstraintName)
    9856             :             {
    9857           2 :                 if (pszDescription)
    9858             :                 {
    9859           2 :                     osConstraintDescription = pszDescription;
    9860             :                 }
    9861           2 :                 continue;
    9862             :             }
    9863          60 :             if (asValues.empty())
    9864             :             {
    9865          30 :                 asValues.reserve(oResultTable->RowCount() + 1);
    9866             :             }
    9867             :             OGRCodedValue cv;
    9868             :             // intended: the 'value' column in GPKG is actually the code
    9869          60 :             cv.pszCode = VSI_STRDUP_VERBOSE(pszValue);
    9870          60 :             if (cv.pszCode == nullptr)
    9871             :             {
    9872           0 :                 error = true;
    9873           0 :                 break;
    9874             :             }
    9875          60 :             if (pszDescription)
    9876             :             {
    9877          48 :                 cv.pszValue = VSI_STRDUP_VERBOSE(pszDescription);
    9878          48 :                 if (cv.pszValue == nullptr)
    9879             :                 {
    9880           0 :                     VSIFree(cv.pszCode);
    9881           0 :                     error = true;
    9882           0 :                     break;
    9883             :                 }
    9884             :             }
    9885             :             else
    9886             :             {
    9887          12 :                 cv.pszValue = nullptr;
    9888             :             }
    9889             : 
    9890             :             // If we can't get the data type from field definition, guess it
    9891             :             // from code.
    9892          60 :             if (nFieldType < 0 && nFieldTypeFromEnumCode != OFTString)
    9893             :             {
    9894          36 :                 switch (CPLGetValueType(cv.pszCode))
    9895             :                 {
    9896          26 :                     case CPL_VALUE_INTEGER:
    9897             :                     {
    9898          26 :                         if (nFieldTypeFromEnumCode != OFTReal &&
    9899             :                             nFieldTypeFromEnumCode != OFTInteger64)
    9900             :                         {
    9901          18 :                             const auto nVal = CPLAtoGIntBig(cv.pszCode);
    9902          34 :                             if (nVal < std::numeric_limits<int>::min() ||
    9903          16 :                                 nVal > std::numeric_limits<int>::max())
    9904             :                             {
    9905           6 :                                 nFieldTypeFromEnumCode = OFTInteger64;
    9906             :                             }
    9907             :                             else
    9908             :                             {
    9909          12 :                                 nFieldTypeFromEnumCode = OFTInteger;
    9910             :                             }
    9911             :                         }
    9912          26 :                         break;
    9913             :                     }
    9914             : 
    9915           6 :                     case CPL_VALUE_REAL:
    9916           6 :                         nFieldTypeFromEnumCode = OFTReal;
    9917           6 :                         break;
    9918             : 
    9919           4 :                     case CPL_VALUE_STRING:
    9920           4 :                         nFieldTypeFromEnumCode = OFTString;
    9921           4 :                         break;
    9922             :                 }
    9923             :             }
    9924             : 
    9925          60 :             asValues.emplace_back(cv);
    9926             :         }
    9927          27 :         else if (strcmp(pszConstraintType, "range") == 0)
    9928             :         {
    9929             :             OGRField sMin;
    9930             :             OGRField sMax;
    9931          20 :             OGR_RawField_SetUnset(&sMin);
    9932          20 :             OGR_RawField_SetUnset(&sMax);
    9933          20 :             if (nFieldType != OFTInteger && nFieldType != OFTInteger64)
    9934          11 :                 nFieldType = OFTReal;
    9935          39 :             if (pszMin != nullptr &&
    9936          19 :                 CPLAtof(pszMin) != -std::numeric_limits<double>::infinity())
    9937             :             {
    9938          15 :                 if (nFieldType == OFTInteger)
    9939           6 :                     sMin.Integer = atoi(pszMin);
    9940           9 :                 else if (nFieldType == OFTInteger64)
    9941           3 :                     sMin.Integer64 = CPLAtoGIntBig(pszMin);
    9942             :                 else /* if( nFieldType == OFTReal ) */
    9943           6 :                     sMin.Real = CPLAtof(pszMin);
    9944             :             }
    9945          39 :             if (pszMax != nullptr &&
    9946          19 :                 CPLAtof(pszMax) != std::numeric_limits<double>::infinity())
    9947             :             {
    9948          15 :                 if (nFieldType == OFTInteger)
    9949           6 :                     sMax.Integer = atoi(pszMax);
    9950           9 :                 else if (nFieldType == OFTInteger64)
    9951           3 :                     sMax.Integer64 = CPLAtoGIntBig(pszMax);
    9952             :                 else /* if( nFieldType == OFTReal ) */
    9953           6 :                     sMax.Real = CPLAtof(pszMax);
    9954             :             }
    9955          20 :             poDomain = std::make_unique<OGRRangeFieldDomain>(
    9956          20 :                 name, pszDescription ? pszDescription : "",
    9957          40 :                 static_cast<OGRFieldType>(nFieldType), eSubType, sMin,
    9958          20 :                 bIsMinIncluded, sMax, bIsMaxIncluded);
    9959             :         }
    9960           7 :         else if (strcmp(pszConstraintType, "glob") == 0)
    9961             :         {
    9962           6 :             if (pszValue == nullptr)
    9963             :             {
    9964           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    9965             :                          "NULL in 'value' column of glob");
    9966           1 :                 error = true;
    9967           1 :                 break;
    9968             :             }
    9969           5 :             if (nFieldType < 0)
    9970           1 :                 nFieldType = OFTString;
    9971           5 :             poDomain = std::make_unique<OGRGlobFieldDomain>(
    9972           5 :                 name, pszDescription ? pszDescription : "",
    9973          15 :                 static_cast<OGRFieldType>(nFieldType), eSubType, pszValue);
    9974             :         }
    9975             :         else
    9976             :         {
    9977           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    9978             :                      "Unhandled constraint_type: %s", pszConstraintType);
    9979           1 :             error = true;
    9980           1 :             break;
    9981             :         }
    9982             : 
    9983          85 :         osLastConstraintType = pszConstraintType;
    9984             :     }
    9985             : 
    9986          58 :     if (!asValues.empty())
    9987             :     {
    9988          30 :         if (nFieldType < 0)
    9989          18 :             nFieldType = nFieldTypeFromEnumCode;
    9990          30 :         poDomain = std::make_unique<OGRCodedFieldDomain>(
    9991             :             name, osConstraintDescription,
    9992          60 :             static_cast<OGRFieldType>(nFieldType), eSubType,
    9993          60 :             std::move(asValues));
    9994             :     }
    9995             : 
    9996          58 :     if (error)
    9997             :     {
    9998           4 :         return nullptr;
    9999             :     }
   10000             : 
   10001          54 :     m_oMapFieldDomains[name] = std::move(poDomain);
   10002          54 :     return GDALDataset::GetFieldDomain(name);
   10003             : }
   10004             : 
   10005             : /************************************************************************/
   10006             : /*                           AddFieldDomain()                           */
   10007             : /************************************************************************/
   10008             : 
   10009          19 : bool GDALGeoPackageDataset::AddFieldDomain(
   10010             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10011             : {
   10012          38 :     const std::string domainName(domain->GetName());
   10013          19 :     if (!GetUpdate())
   10014             :     {
   10015           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10016             :                  "AddFieldDomain() not supported on read-only dataset");
   10017           0 :         return false;
   10018             :     }
   10019          19 :     if (GetFieldDomain(domainName) != nullptr)
   10020             :     {
   10021           1 :         failureReason = "A domain of identical name already exists";
   10022           1 :         return false;
   10023             :     }
   10024          18 :     if (!CreateColumnsTableAndColumnConstraintsTablesIfNecessary())
   10025           0 :         return false;
   10026             : 
   10027          18 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
   10028          18 :     const char *min_is_inclusive =
   10029          18 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
   10030          18 :     const char *max_is_inclusive =
   10031          18 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
   10032             : 
   10033          18 :     const auto &osDescription = domain->GetDescription();
   10034          18 :     switch (domain->GetDomainType())
   10035             :     {
   10036          11 :         case OFDT_CODED:
   10037             :         {
   10038             :             const auto poCodedDomain =
   10039          11 :                 cpl::down_cast<const OGRCodedFieldDomain *>(domain.get());
   10040          11 :             if (!osDescription.empty())
   10041             :             {
   10042             :                 // We use a little trick by using a dummy
   10043             :                 // _{domainname}_domain_description enum that has a single
   10044             :                 // entry whose description is the description of the main
   10045             :                 // domain.
   10046           1 :                 char *pszSQL = sqlite3_mprintf(
   10047             :                     "INSERT INTO gpkg_data_column_constraints ("
   10048             :                     "constraint_name, constraint_type, value, "
   10049             :                     "min, %s, max, %s, "
   10050             :                     "description) VALUES ("
   10051             :                     "'_%q_domain_description', 'enum', '', NULL, NULL, NULL, "
   10052             :                     "NULL, %Q)",
   10053             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10054             :                     osDescription.c_str());
   10055           1 :                 CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
   10056           1 :                 sqlite3_free(pszSQL);
   10057             :             }
   10058          11 :             const auto &enumeration = poCodedDomain->GetEnumeration();
   10059          33 :             for (int i = 0; enumeration[i].pszCode != nullptr; ++i)
   10060             :             {
   10061          22 :                 char *pszSQL = sqlite3_mprintf(
   10062             :                     "INSERT INTO gpkg_data_column_constraints ("
   10063             :                     "constraint_name, constraint_type, value, "
   10064             :                     "min, %s, max, %s, "
   10065             :                     "description) VALUES ("
   10066             :                     "'%q', 'enum', '%q', NULL, NULL, NULL, NULL, %Q)",
   10067             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10068          22 :                     enumeration[i].pszCode, enumeration[i].pszValue);
   10069          22 :                 bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10070          22 :                 sqlite3_free(pszSQL);
   10071          22 :                 if (!ok)
   10072           0 :                     return false;
   10073             :             }
   10074          11 :             break;
   10075             :         }
   10076             : 
   10077           6 :         case OFDT_RANGE:
   10078             :         {
   10079             :             const auto poRangeDomain =
   10080           6 :                 cpl::down_cast<const OGRRangeFieldDomain *>(domain.get());
   10081           6 :             const auto eFieldType = poRangeDomain->GetFieldType();
   10082           6 :             if (eFieldType != OFTInteger && eFieldType != OFTInteger64 &&
   10083             :                 eFieldType != OFTReal)
   10084             :             {
   10085             :                 failureReason = "Only range domains of numeric type are "
   10086           0 :                                 "supported in GeoPackage";
   10087           0 :                 return false;
   10088             :             }
   10089             : 
   10090           6 :             double dfMin = -std::numeric_limits<double>::infinity();
   10091           6 :             double dfMax = std::numeric_limits<double>::infinity();
   10092           6 :             bool bMinIsInclusive = true;
   10093           6 :             const auto &sMin = poRangeDomain->GetMin(bMinIsInclusive);
   10094           6 :             bool bMaxIsInclusive = true;
   10095           6 :             const auto &sMax = poRangeDomain->GetMax(bMaxIsInclusive);
   10096           6 :             if (eFieldType == OFTInteger)
   10097             :             {
   10098           2 :                 if (!OGR_RawField_IsUnset(&sMin))
   10099           2 :                     dfMin = sMin.Integer;
   10100           2 :                 if (!OGR_RawField_IsUnset(&sMax))
   10101           2 :                     dfMax = sMax.Integer;
   10102             :             }
   10103           4 :             else if (eFieldType == OFTInteger64)
   10104             :             {
   10105           1 :                 if (!OGR_RawField_IsUnset(&sMin))
   10106           1 :                     dfMin = static_cast<double>(sMin.Integer64);
   10107           1 :                 if (!OGR_RawField_IsUnset(&sMax))
   10108           1 :                     dfMax = static_cast<double>(sMax.Integer64);
   10109             :             }
   10110             :             else /* if( eFieldType == OFTReal ) */
   10111             :             {
   10112           3 :                 if (!OGR_RawField_IsUnset(&sMin))
   10113           3 :                     dfMin = sMin.Real;
   10114           3 :                 if (!OGR_RawField_IsUnset(&sMax))
   10115           3 :                     dfMax = sMax.Real;
   10116             :             }
   10117             : 
   10118           6 :             sqlite3_stmt *hInsertStmt = nullptr;
   10119             :             const char *pszSQL =
   10120           6 :                 CPLSPrintf("INSERT INTO gpkg_data_column_constraints ("
   10121             :                            "constraint_name, constraint_type, value, "
   10122             :                            "min, %s, max, %s, "
   10123             :                            "description) VALUES ("
   10124             :                            "?, 'range', NULL, ?, ?, ?, ?, ?)",
   10125             :                            min_is_inclusive, max_is_inclusive);
   10126           6 :             if (SQLPrepareWithError(hDB, pszSQL, -1, &hInsertStmt, nullptr) !=
   10127             :                 SQLITE_OK)
   10128             :             {
   10129           0 :                 return false;
   10130             :             }
   10131           6 :             sqlite3_bind_text(hInsertStmt, 1, domainName.c_str(),
   10132           6 :                               static_cast<int>(domainName.size()),
   10133             :                               SQLITE_TRANSIENT);
   10134           6 :             sqlite3_bind_double(hInsertStmt, 2, dfMin);
   10135           6 :             sqlite3_bind_int(hInsertStmt, 3, bMinIsInclusive ? 1 : 0);
   10136           6 :             sqlite3_bind_double(hInsertStmt, 4, dfMax);
   10137           6 :             sqlite3_bind_int(hInsertStmt, 5, bMaxIsInclusive ? 1 : 0);
   10138           6 :             if (osDescription.empty())
   10139             :             {
   10140           3 :                 sqlite3_bind_null(hInsertStmt, 6);
   10141             :             }
   10142             :             else
   10143             :             {
   10144           3 :                 sqlite3_bind_text(hInsertStmt, 6, osDescription.c_str(),
   10145           3 :                                   static_cast<int>(osDescription.size()),
   10146             :                                   SQLITE_TRANSIENT);
   10147             :             }
   10148           6 :             const int sqlite_err = sqlite3_step(hInsertStmt);
   10149           6 :             sqlite3_finalize(hInsertStmt);
   10150           6 :             if (sqlite_err != SQLITE_OK && sqlite_err != SQLITE_DONE)
   10151             :             {
   10152           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10153             :                          "failed to execute insertion '%s': %s", pszSQL,
   10154             :                          sqlite3_errmsg(hDB));
   10155           0 :                 return false;
   10156             :             }
   10157             : 
   10158           6 :             break;
   10159             :         }
   10160             : 
   10161           1 :         case OFDT_GLOB:
   10162             :         {
   10163             :             const auto poGlobDomain =
   10164           1 :                 cpl::down_cast<const OGRGlobFieldDomain *>(domain.get());
   10165           2 :             char *pszSQL = sqlite3_mprintf(
   10166             :                 "INSERT INTO gpkg_data_column_constraints ("
   10167             :                 "constraint_name, constraint_type, value, "
   10168             :                 "min, %s, max, %s, "
   10169             :                 "description) VALUES ("
   10170             :                 "'%q', 'glob', '%q', NULL, NULL, NULL, NULL, %Q)",
   10171             :                 min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10172           1 :                 poGlobDomain->GetGlob().c_str(),
   10173           2 :                 osDescription.empty() ? nullptr : osDescription.c_str());
   10174           1 :             bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10175           1 :             sqlite3_free(pszSQL);
   10176           1 :             if (!ok)
   10177           0 :                 return false;
   10178             : 
   10179           1 :             break;
   10180             :         }
   10181             :     }
   10182             : 
   10183          18 :     m_oMapFieldDomains[domainName] = std::move(domain);
   10184          18 :     return true;
   10185             : }
   10186             : 
   10187             : /************************************************************************/
   10188             : /*                        UpdateFieldDomain()                           */
   10189             : /************************************************************************/
   10190             : 
   10191           3 : bool GDALGeoPackageDataset::UpdateFieldDomain(
   10192             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10193             : {
   10194           6 :     const std::string domainName(domain->GetName());
   10195           3 :     if (eAccess != GA_Update)
   10196             :     {
   10197           1 :         CPLError(CE_Failure, CPLE_NotSupported,
   10198             :                  "UpdateFieldDomain() not supported on read-only dataset");
   10199           1 :         return false;
   10200             :     }
   10201             : 
   10202           2 :     if (GetFieldDomain(domainName) == nullptr)
   10203             :     {
   10204           1 :         failureReason = "The domain should already exist to be updated";
   10205           1 :         return false;
   10206             :     }
   10207             : 
   10208           1 :     bool bRet = SoftStartTransaction() == OGRERR_NONE;
   10209           1 :     if (bRet)
   10210             :     {
   10211           2 :         bRet = DeleteFieldDomain(domainName, failureReason) &&
   10212           1 :                AddFieldDomain(std::move(domain), failureReason);
   10213           1 :         if (bRet)
   10214           1 :             bRet = SoftCommitTransaction() == OGRERR_NONE;
   10215             :         else
   10216           0 :             SoftRollbackTransaction();
   10217             :     }
   10218           1 :     return bRet;
   10219             : }
   10220             : 
   10221             : /************************************************************************/
   10222             : /*                         DeleteFieldDomain()                          */
   10223             : /************************************************************************/
   10224             : 
   10225          18 : bool GDALGeoPackageDataset::DeleteFieldDomain(const std::string &name,
   10226             :                                               std::string &failureReason)
   10227             : {
   10228          18 :     if (eAccess != GA_Update)
   10229             :     {
   10230           1 :         CPLError(CE_Failure, CPLE_NotSupported,
   10231             :                  "DeleteFieldDomain() not supported on read-only dataset");
   10232           1 :         return false;
   10233             :     }
   10234          17 :     if (GetFieldDomain(name) == nullptr)
   10235             :     {
   10236           1 :         failureReason = "Domain does not exist";
   10237           1 :         return false;
   10238             :     }
   10239             : 
   10240             :     char *pszSQL =
   10241          16 :         sqlite3_mprintf("DELETE FROM gpkg_data_column_constraints WHERE "
   10242             :                         "constraint_name IN ('%q', '_%q_domain_description')",
   10243             :                         name.c_str(), name.c_str());
   10244          16 :     const bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10245          16 :     sqlite3_free(pszSQL);
   10246          16 :     if (ok)
   10247          16 :         m_oMapFieldDomains.erase(name);
   10248          16 :     return ok;
   10249             : }
   10250             : 
   10251             : /************************************************************************/
   10252             : /*                          AddRelationship()                           */
   10253             : /************************************************************************/
   10254             : 
   10255          24 : bool GDALGeoPackageDataset::AddRelationship(
   10256             :     std::unique_ptr<GDALRelationship> &&relationship,
   10257             :     std::string &failureReason)
   10258             : {
   10259          24 :     if (!GetUpdate())
   10260             :     {
   10261           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10262             :                  "AddRelationship() not supported on read-only dataset");
   10263           0 :         return false;
   10264             :     }
   10265             : 
   10266             :     const std::string osRelationshipName = GenerateNameForRelationship(
   10267          24 :         relationship->GetLeftTableName().c_str(),
   10268          24 :         relationship->GetRightTableName().c_str(),
   10269          96 :         relationship->GetRelatedTableType().c_str());
   10270             :     // sanity checks
   10271          24 :     if (GetRelationship(osRelationshipName) != nullptr)
   10272             :     {
   10273           1 :         failureReason = "A relationship of identical name already exists";
   10274           1 :         return false;
   10275             :     }
   10276             : 
   10277          23 :     if (!ValidateRelationship(relationship.get(), failureReason))
   10278             :     {
   10279          14 :         return false;
   10280             :     }
   10281             : 
   10282           9 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
   10283             :     {
   10284           0 :         return false;
   10285             :     }
   10286           9 :     if (!CreateRelationsTableIfNecessary())
   10287             :     {
   10288           0 :         failureReason = "Could not create gpkgext_relations table";
   10289           0 :         return false;
   10290             :     }
   10291           9 :     if (SQLGetInteger(GetDB(),
   10292             :                       "SELECT 1 FROM gpkg_extensions WHERE "
   10293             :                       "table_name = 'gpkgext_relations'",
   10294           9 :                       nullptr) != 1)
   10295             :     {
   10296           4 :         if (OGRERR_NONE !=
   10297           4 :             SQLCommand(
   10298             :                 GetDB(),
   10299             :                 "INSERT INTO gpkg_extensions "
   10300             :                 "(table_name,column_name,extension_name,definition,scope) "
   10301             :                 "VALUES ('gpkgext_relations', NULL, 'gpkg_related_tables', "
   10302             :                 "'http://www.geopackage.org/18-000.html', "
   10303             :                 "'read-write')"))
   10304             :         {
   10305             :             failureReason =
   10306           0 :                 "Could not create gpkg_extensions entry for gpkgext_relations";
   10307           0 :             return false;
   10308             :         }
   10309             :     }
   10310             : 
   10311           9 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10312           9 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10313           9 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10314           9 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10315             : 
   10316          18 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10317           9 :     if (osRelatedTableType.empty())
   10318             :     {
   10319           5 :         osRelatedTableType = "features";
   10320             :     }
   10321             : 
   10322             :     // generate mapping table if not set
   10323          18 :     CPLString osMappingTableName = relationship->GetMappingTableName();
   10324           9 :     if (osMappingTableName.empty())
   10325             :     {
   10326           3 :         int nIndex = 1;
   10327           3 :         osMappingTableName = osLeftTableName + "_" + osRightTableName;
   10328           3 :         while (FindLayerIndex(osMappingTableName.c_str()) >= 0)
   10329             :         {
   10330           0 :             nIndex += 1;
   10331             :             osMappingTableName.Printf("%s_%s_%d", osLeftTableName.c_str(),
   10332           0 :                                       osRightTableName.c_str(), nIndex);
   10333             :         }
   10334             : 
   10335             :         // determine whether base/related keys are unique
   10336           3 :         bool bBaseKeyIsUnique = false;
   10337             :         {
   10338             :             const std::set<std::string> uniqueBaseFieldsUC =
   10339             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10340           6 :                                                osLeftTableName.c_str());
   10341           6 :             if (uniqueBaseFieldsUC.find(
   10342           3 :                     CPLString(aosLeftTableFields[0]).toupper()) !=
   10343           6 :                 uniqueBaseFieldsUC.end())
   10344             :             {
   10345           2 :                 bBaseKeyIsUnique = true;
   10346             :             }
   10347             :         }
   10348           3 :         bool bRelatedKeyIsUnique = false;
   10349             :         {
   10350             :             const std::set<std::string> uniqueRelatedFieldsUC =
   10351             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10352           6 :                                                osRightTableName.c_str());
   10353           6 :             if (uniqueRelatedFieldsUC.find(
   10354           3 :                     CPLString(aosRightTableFields[0]).toupper()) !=
   10355           6 :                 uniqueRelatedFieldsUC.end())
   10356             :             {
   10357           2 :                 bRelatedKeyIsUnique = true;
   10358             :             }
   10359             :         }
   10360             : 
   10361             :         // create mapping table
   10362             : 
   10363           3 :         std::string osBaseIdDefinition = "base_id INTEGER";
   10364           3 :         if (bBaseKeyIsUnique)
   10365             :         {
   10366           2 :             char *pszSQL = sqlite3_mprintf(
   10367             :                 " CONSTRAINT 'fk_base_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10368             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10369             :                 "DEFERRED",
   10370             :                 osMappingTableName.c_str(), osLeftTableName.c_str(),
   10371           2 :                 aosLeftTableFields[0].c_str());
   10372           2 :             osBaseIdDefinition += pszSQL;
   10373           2 :             sqlite3_free(pszSQL);
   10374             :         }
   10375             : 
   10376           3 :         std::string osRelatedIdDefinition = "related_id INTEGER";
   10377           3 :         if (bRelatedKeyIsUnique)
   10378             :         {
   10379           2 :             char *pszSQL = sqlite3_mprintf(
   10380             :                 " CONSTRAINT 'fk_related_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10381             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10382             :                 "DEFERRED",
   10383             :                 osMappingTableName.c_str(), osRightTableName.c_str(),
   10384           2 :                 aosRightTableFields[0].c_str());
   10385           2 :             osRelatedIdDefinition += pszSQL;
   10386           2 :             sqlite3_free(pszSQL);
   10387             :         }
   10388             : 
   10389           3 :         char *pszSQL = sqlite3_mprintf("CREATE TABLE \"%w\" ("
   10390             :                                        "id INTEGER PRIMARY KEY AUTOINCREMENT, "
   10391             :                                        "%s, %s);",
   10392             :                                        osMappingTableName.c_str(),
   10393             :                                        osBaseIdDefinition.c_str(),
   10394             :                                        osRelatedIdDefinition.c_str());
   10395           3 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
   10396           3 :         sqlite3_free(pszSQL);
   10397           3 :         if (eErr != OGRERR_NONE)
   10398             :         {
   10399             :             failureReason =
   10400           0 :                 ("Could not create mapping table " + osMappingTableName)
   10401           0 :                     .c_str();
   10402           0 :             return false;
   10403             :         }
   10404             : 
   10405             :         /*
   10406             :          * Strictly speaking we should NOT be inserting the mapping table into gpkg_contents.
   10407             :          * The related tables extension explicitly states that the mapping table should only be
   10408             :          * in the gpkgext_relations table and not in gpkg_contents. (See also discussion at
   10409             :          * https://github.com/opengeospatial/geopackage/issues/679).
   10410             :          *
   10411             :          * However, if we don't insert the mapping table into gpkg_contents then it is no longer
   10412             :          * visible to some clients (eg ESRI software only allows opening tables that are present
   10413             :          * in gpkg_contents). So we'll do this anyway, for maximum compatibility and flexibility.
   10414             :          *
   10415             :          * More related discussion is at https://github.com/OSGeo/gdal/pull/9258
   10416             :          */
   10417           3 :         pszSQL = sqlite3_mprintf(
   10418             :             "INSERT INTO gpkg_contents "
   10419             :             "(table_name,data_type,identifier,description,last_change,srs_id) "
   10420             :             "VALUES "
   10421             :             "('%q','attributes','%q','Mapping table for relationship between "
   10422             :             "%q and %q',%s,0)",
   10423             :             osMappingTableName.c_str(), /*table_name*/
   10424             :             osMappingTableName.c_str(), /*identifier*/
   10425             :             osLeftTableName.c_str(),    /*description left table name*/
   10426             :             osRightTableName.c_str(),   /*description right table name*/
   10427           6 :             GDALGeoPackageDataset::GetCurrentDateEscapedSQL().c_str());
   10428             : 
   10429             :         // Note -- we explicitly ignore failures here, because hey, we aren't really
   10430             :         // supposed to be adding this table to gpkg_contents anyway!
   10431           3 :         (void)SQLCommand(hDB, pszSQL);
   10432           3 :         sqlite3_free(pszSQL);
   10433             : 
   10434           3 :         pszSQL = sqlite3_mprintf(
   10435             :             "CREATE INDEX \"idx_%w_base_id\" ON \"%w\" (base_id);",
   10436             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10437           3 :         eErr = SQLCommand(hDB, pszSQL);
   10438           3 :         sqlite3_free(pszSQL);
   10439           3 :         if (eErr != OGRERR_NONE)
   10440             :         {
   10441           0 :             failureReason = ("Could not create index for " +
   10442           0 :                              osMappingTableName + " (base_id)")
   10443           0 :                                 .c_str();
   10444           0 :             return false;
   10445             :         }
   10446             : 
   10447           3 :         pszSQL = sqlite3_mprintf(
   10448             :             "CREATE INDEX \"idx_%qw_related_id\" ON \"%w\" (related_id);",
   10449             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10450           3 :         eErr = SQLCommand(hDB, pszSQL);
   10451           3 :         sqlite3_free(pszSQL);
   10452           3 :         if (eErr != OGRERR_NONE)
   10453             :         {
   10454           0 :             failureReason = ("Could not create index for " +
   10455           0 :                              osMappingTableName + " (related_id)")
   10456           0 :                                 .c_str();
   10457           0 :             return false;
   10458             :         }
   10459             :     }
   10460             :     else
   10461             :     {
   10462             :         // validate mapping table structure
   10463           6 :         if (OGRGeoPackageTableLayer *poLayer =
   10464           6 :                 cpl::down_cast<OGRGeoPackageTableLayer *>(
   10465           6 :                     GetLayerByName(osMappingTableName)))
   10466             :         {
   10467           4 :             if (poLayer->GetLayerDefn()->GetFieldIndex("base_id") < 0)
   10468             :             {
   10469             :                 failureReason =
   10470           2 :                     ("Field base_id must exist in " + osMappingTableName)
   10471           1 :                         .c_str();
   10472           1 :                 return false;
   10473             :             }
   10474           3 :             if (poLayer->GetLayerDefn()->GetFieldIndex("related_id") < 0)
   10475             :             {
   10476             :                 failureReason =
   10477           2 :                     ("Field related_id must exist in " + osMappingTableName)
   10478           1 :                         .c_str();
   10479           1 :                 return false;
   10480             :             }
   10481             :         }
   10482             :         else
   10483             :         {
   10484             :             failureReason =
   10485           2 :                 ("Could not retrieve table " + osMappingTableName).c_str();
   10486           2 :             return false;
   10487             :         }
   10488             :     }
   10489             : 
   10490           5 :     char *pszSQL = sqlite3_mprintf(
   10491             :         "INSERT INTO gpkg_extensions "
   10492             :         "(table_name,column_name,extension_name,definition,scope) "
   10493             :         "VALUES ('%q', NULL, 'gpkg_related_tables', "
   10494             :         "'http://www.geopackage.org/18-000.html', "
   10495             :         "'read-write')",
   10496             :         osMappingTableName.c_str());
   10497           5 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10498           5 :     sqlite3_free(pszSQL);
   10499           5 :     if (eErr != OGRERR_NONE)
   10500             :     {
   10501           0 :         failureReason = ("Could not insert mapping table " +
   10502           0 :                          osMappingTableName + " into gpkg_extensions")
   10503           0 :                             .c_str();
   10504           0 :         return false;
   10505             :     }
   10506             : 
   10507          15 :     pszSQL = sqlite3_mprintf(
   10508             :         "INSERT INTO gpkgext_relations "
   10509             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10510             :         "primary_column,relation_name,mapping_table_name) "
   10511             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10512           5 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10513           5 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10514             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10515           5 :     eErr = SQLCommand(hDB, pszSQL);
   10516           5 :     sqlite3_free(pszSQL);
   10517           5 :     if (eErr != OGRERR_NONE)
   10518             :     {
   10519           0 :         failureReason = "Could not insert relationship into gpkgext_relations";
   10520           0 :         return false;
   10521             :     }
   10522             : 
   10523           5 :     ClearCachedRelationships();
   10524           5 :     LoadRelationships();
   10525           5 :     return true;
   10526             : }
   10527             : 
   10528             : /************************************************************************/
   10529             : /*                         DeleteRelationship()                         */
   10530             : /************************************************************************/
   10531             : 
   10532           4 : bool GDALGeoPackageDataset::DeleteRelationship(const std::string &name,
   10533             :                                                std::string &failureReason)
   10534             : {
   10535           4 :     if (eAccess != GA_Update)
   10536             :     {
   10537           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10538             :                  "DeleteRelationship() not supported on read-only dataset");
   10539           0 :         return false;
   10540             :     }
   10541             : 
   10542             :     // ensure relationships are up to date before we try to remove one
   10543           4 :     ClearCachedRelationships();
   10544           4 :     LoadRelationships();
   10545             : 
   10546           8 :     std::string osMappingTableName;
   10547             :     {
   10548           4 :         const GDALRelationship *poRelationship = GetRelationship(name);
   10549           4 :         if (poRelationship == nullptr)
   10550             :         {
   10551           1 :             failureReason = "Could not find relationship with name " + name;
   10552           1 :             return false;
   10553             :         }
   10554             : 
   10555           3 :         osMappingTableName = poRelationship->GetMappingTableName();
   10556             :     }
   10557             : 
   10558             :     // DeleteLayerCommon will delete existing relationship objects, so we can't
   10559             :     // refer to poRelationship or any of its members previously obtained here
   10560           3 :     if (DeleteLayerCommon(osMappingTableName.c_str()) != OGRERR_NONE)
   10561             :     {
   10562             :         failureReason =
   10563           0 :             "Could not remove mapping layer name " + osMappingTableName;
   10564             : 
   10565             :         // relationships may have been left in an inconsistent state -- reload
   10566             :         // them now
   10567           0 :         ClearCachedRelationships();
   10568           0 :         LoadRelationships();
   10569           0 :         return false;
   10570             :     }
   10571             : 
   10572           3 :     ClearCachedRelationships();
   10573           3 :     LoadRelationships();
   10574           3 :     return true;
   10575             : }
   10576             : 
   10577             : /************************************************************************/
   10578             : /*                        UpdateRelationship()                          */
   10579             : /************************************************************************/
   10580             : 
   10581           6 : bool GDALGeoPackageDataset::UpdateRelationship(
   10582             :     std::unique_ptr<GDALRelationship> &&relationship,
   10583             :     std::string &failureReason)
   10584             : {
   10585           6 :     if (eAccess != GA_Update)
   10586             :     {
   10587           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10588             :                  "UpdateRelationship() not supported on read-only dataset");
   10589           0 :         return false;
   10590             :     }
   10591             : 
   10592             :     // ensure relationships are up to date before we try to update one
   10593           6 :     ClearCachedRelationships();
   10594           6 :     LoadRelationships();
   10595             : 
   10596           6 :     const std::string &osRelationshipName = relationship->GetName();
   10597           6 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10598           6 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10599           6 :     const std::string &osMappingTableName = relationship->GetMappingTableName();
   10600           6 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10601           6 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10602             : 
   10603             :     // sanity checks
   10604             :     {
   10605             :         const GDALRelationship *poExistingRelationship =
   10606           6 :             GetRelationship(osRelationshipName);
   10607           6 :         if (poExistingRelationship == nullptr)
   10608             :         {
   10609             :             failureReason =
   10610           1 :                 "The relationship should already exist to be updated";
   10611           1 :             return false;
   10612             :         }
   10613             : 
   10614           5 :         if (!ValidateRelationship(relationship.get(), failureReason))
   10615             :         {
   10616           2 :             return false;
   10617             :         }
   10618             : 
   10619             :         // we don't permit changes to the participating tables
   10620           3 :         if (osLeftTableName != poExistingRelationship->GetLeftTableName())
   10621             :         {
   10622           0 :             failureReason = ("Cannot change base table from " +
   10623           0 :                              poExistingRelationship->GetLeftTableName() +
   10624           0 :                              " to " + osLeftTableName)
   10625           0 :                                 .c_str();
   10626           0 :             return false;
   10627             :         }
   10628           3 :         if (osRightTableName != poExistingRelationship->GetRightTableName())
   10629             :         {
   10630           0 :             failureReason = ("Cannot change related table from " +
   10631           0 :                              poExistingRelationship->GetRightTableName() +
   10632           0 :                              " to " + osRightTableName)
   10633           0 :                                 .c_str();
   10634           0 :             return false;
   10635             :         }
   10636           3 :         if (osMappingTableName != poExistingRelationship->GetMappingTableName())
   10637             :         {
   10638           0 :             failureReason = ("Cannot change mapping table from " +
   10639           0 :                              poExistingRelationship->GetMappingTableName() +
   10640           0 :                              " to " + osMappingTableName)
   10641           0 :                                 .c_str();
   10642           0 :             return false;
   10643             :         }
   10644             :     }
   10645             : 
   10646           6 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10647           3 :     if (osRelatedTableType.empty())
   10648             :     {
   10649           0 :         osRelatedTableType = "features";
   10650             :     }
   10651             : 
   10652           3 :     char *pszSQL = sqlite3_mprintf(
   10653             :         "DELETE FROM gpkgext_relations WHERE mapping_table_name='%q'",
   10654             :         osMappingTableName.c_str());
   10655           3 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10656           3 :     sqlite3_free(pszSQL);
   10657           3 :     if (eErr != OGRERR_NONE)
   10658             :     {
   10659             :         failureReason =
   10660           0 :             "Could not delete old relationship from gpkgext_relations";
   10661           0 :         return false;
   10662             :     }
   10663             : 
   10664           9 :     pszSQL = sqlite3_mprintf(
   10665             :         "INSERT INTO gpkgext_relations "
   10666             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10667             :         "primary_column,relation_name,mapping_table_name) "
   10668             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10669           3 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10670           3 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10671             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10672           3 :     eErr = SQLCommand(hDB, pszSQL);
   10673           3 :     sqlite3_free(pszSQL);
   10674           3 :     if (eErr != OGRERR_NONE)
   10675             :     {
   10676             :         failureReason =
   10677           0 :             "Could not insert updated relationship into gpkgext_relations";
   10678           0 :         return false;
   10679             :     }
   10680             : 
   10681           3 :     ClearCachedRelationships();
   10682           3 :     LoadRelationships();
   10683           3 :     return true;
   10684             : }
   10685             : 
   10686             : /************************************************************************/
   10687             : /*                    GetSqliteMasterContent()                          */
   10688             : /************************************************************************/
   10689             : 
   10690             : const std::vector<SQLSqliteMasterContent> &
   10691           2 : GDALGeoPackageDataset::GetSqliteMasterContent()
   10692             : {
   10693           2 :     if (m_aoSqliteMasterContent.empty())
   10694             :     {
   10695             :         auto oResultTable =
   10696           2 :             SQLQuery(hDB, "SELECT sql, type, tbl_name FROM sqlite_master");
   10697           1 :         if (oResultTable)
   10698             :         {
   10699          58 :             for (int rowCnt = 0; rowCnt < oResultTable->RowCount(); ++rowCnt)
   10700             :             {
   10701         114 :                 SQLSqliteMasterContent row;
   10702          57 :                 const char *pszSQL = oResultTable->GetValue(0, rowCnt);
   10703          57 :                 row.osSQL = pszSQL ? pszSQL : "";
   10704          57 :                 const char *pszType = oResultTable->GetValue(1, rowCnt);
   10705          57 :                 row.osType = pszType ? pszType : "";
   10706          57 :                 const char *pszTableName = oResultTable->GetValue(2, rowCnt);
   10707          57 :                 row.osTableName = pszTableName ? pszTableName : "";
   10708          57 :                 m_aoSqliteMasterContent.emplace_back(std::move(row));
   10709             :             }
   10710             :         }
   10711             :     }
   10712           2 :     return m_aoSqliteMasterContent;
   10713             : }

Generated by: LCOV version 1.14