LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/gpkg - ogrgeopackagedatasource.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 4127 4601 89.7 %
Date: 2026-11-25 13:58:27 Functions: 141 141 100.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GeoPackage Translator
       4             :  * Purpose:  Implements GDALGeoPackageDataset class
       5             :  * Author:   Paul Ramsey <pramsey@boundlessgeo.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2013, Paul Ramsey <pramsey@boundlessgeo.com>
       9             :  * Copyright (c) 2014, Even Rouault <even dot rouault at spatialys.com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "ogr_geopackage.h"
      15             : #include "ogr_p.h"
      16             : #include "ogr_swq.h"
      17             : #include "gdal_alg.h"
      18             : #include "gdalwarper.h"
      19             : #include "gdal_utils.h"
      20             : #include "ogrgeopackageutility.h"
      21             : #include "ogrsqliteutility.h"
      22             : #include "ogr_wkb.h"
      23             : #include "vrt/vrtdataset.h"
      24             : 
      25             : #include "tilematrixset.hpp"
      26             : 
      27             : #include <cstdlib>
      28             : 
      29             : #include <algorithm>
      30             : #include <limits>
      31             : #include <sstream>
      32             : 
      33             : #define COMPILATION_ALLOWED
      34             : #define DEFINE_OGRSQLiteSQLFunctionsSetCaseSensitiveLike
      35             : #include "ogrsqlitesqlfunctionscommon.cpp"
      36             : 
      37             : // Keep in sync prototype of those 2 functions between gdalopeninfo.cpp,
      38             : // ogrsqlitedatasource.cpp and ogrgeopackagedatasource.cpp
      39             : void GDALOpenInfoDeclareFileNotToOpen(const char *pszFilename,
      40             :                                       const GByte *pabyHeader,
      41             :                                       int nHeaderBytes);
      42             : void GDALOpenInfoUnDeclareFileNotToOpen(const char *pszFilename);
      43             : 
      44             : /************************************************************************/
      45             : /*                            Tiling schemes                            */
      46             : /************************************************************************/
      47             : 
      48             : typedef struct
      49             : {
      50             :     const char *pszName;
      51             :     int nEPSGCode;
      52             :     double dfMinX;
      53             :     double dfMaxY;
      54             :     int nTileXCountZoomLevel0;
      55             :     int nTileYCountZoomLevel0;
      56             :     int nTileWidth;
      57             :     int nTileHeight;
      58             :     double dfPixelXSizeZoomLevel0;
      59             :     double dfPixelYSizeZoomLevel0;
      60             : } TilingSchemeDefinition;
      61             : 
      62             : static const TilingSchemeDefinition asTilingSchemes[] = {
      63             :     /* See http://portal.opengeospatial.org/files/?artifact_id=35326 (WMTS 1.0),
      64             :        Annex E.3 */
      65             :     {"GoogleCRS84Quad", 4326, -180.0, 180.0, 1, 1, 256, 256, 360.0 / 256,
      66             :      360.0 / 256},
      67             : 
      68             :     /* See global-mercator at
      69             :        http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification */
      70             :     {"PseudoTMS_GlobalMercator", 3857, -20037508.34, 20037508.34, 2, 2, 256,
      71             :      256, 78271.516, 78271.516},
      72             : };
      73             : 
      74             : // Setting it above 30 would lead to integer overflow ((1 << 31) > INT_MAX)
      75             : constexpr int MAX_ZOOM_LEVEL = 30;
      76             : 
      77             : /************************************************************************/
      78             : /*                          GetTilingScheme()                           */
      79             : /************************************************************************/
      80             : 
      81             : static std::unique_ptr<TilingSchemeDefinition>
      82         594 : GetTilingScheme(const char *pszName)
      83             : {
      84         594 :     if (EQUAL(pszName, "CUSTOM"))
      85         466 :         return nullptr;
      86             : 
      87         256 :     for (const auto &tilingScheme : asTilingSchemes)
      88             :     {
      89         195 :         if (EQUAL(pszName, tilingScheme.pszName))
      90             :         {
      91          67 :             return std::make_unique<TilingSchemeDefinition>(tilingScheme);
      92             :         }
      93             :     }
      94             : 
      95          61 :     if (EQUAL(pszName, "PseudoTMS_GlobalGeodetic"))
      96           6 :         pszName = "InspireCRS84Quad";
      97             : 
      98         122 :     auto poTM = gdal::TileMatrixSet::parse(pszName);
      99          61 :     if (poTM == nullptr)
     100           1 :         return nullptr;
     101          60 :     if (!poTM->haveAllLevelsSameTopLeft())
     102             :     {
     103           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     104             :                  "Unsupported tiling scheme: not all zoom levels have same top "
     105             :                  "left corner");
     106           0 :         return nullptr;
     107             :     }
     108          60 :     if (!poTM->haveAllLevelsSameTileSize())
     109             :     {
     110           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     111             :                  "Unsupported tiling scheme: not all zoom levels have same "
     112             :                  "tile size");
     113           0 :         return nullptr;
     114             :     }
     115          60 :     if (!poTM->hasOnlyPowerOfTwoVaryingScales())
     116             :     {
     117           1 :         CPLError(CE_Failure, CPLE_NotSupported,
     118             :                  "Unsupported tiling scheme: resolution of consecutive zoom "
     119             :                  "levels is not always 2");
     120           1 :         return nullptr;
     121             :     }
     122          59 :     if (poTM->hasVariableMatrixWidth())
     123             :     {
     124           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     125             :                  "Unsupported tiling scheme: some levels have variable matrix "
     126             :                  "width");
     127           0 :         return nullptr;
     128             :     }
     129         118 :     auto poTilingScheme = std::make_unique<TilingSchemeDefinition>();
     130          59 :     poTilingScheme->pszName = pszName;
     131             : 
     132         118 :     OGRSpatialReference oSRS;
     133          59 :     if (oSRS.SetFromUserInput(poTM->crs().c_str()) != OGRERR_NONE)
     134             :     {
     135           0 :         return nullptr;
     136             :     }
     137          59 :     if (poTM->crs() == "http://www.opengis.net/def/crs/OGC/1.3/CRS84")
     138             :     {
     139           6 :         poTilingScheme->nEPSGCode = 4326;
     140             :     }
     141             :     else
     142             :     {
     143          53 :         const char *pszAuthName = oSRS.GetAuthorityName();
     144          53 :         const char *pszAuthCode = oSRS.GetAuthorityCode();
     145          53 :         if (pszAuthName == nullptr || !EQUAL(pszAuthName, "EPSG") ||
     146             :             pszAuthCode == nullptr)
     147             :         {
     148           0 :             CPLError(CE_Failure, CPLE_NotSupported,
     149             :                      "Unsupported tiling scheme: only EPSG CRS supported");
     150           0 :             return nullptr;
     151             :         }
     152          53 :         poTilingScheme->nEPSGCode = atoi(pszAuthCode);
     153             :     }
     154          59 :     const auto &zoomLevel0 = poTM->tileMatrixList()[0];
     155          59 :     poTilingScheme->dfMinX = zoomLevel0.mTopLeftX;
     156          59 :     poTilingScheme->dfMaxY = zoomLevel0.mTopLeftY;
     157          59 :     poTilingScheme->nTileXCountZoomLevel0 = zoomLevel0.mMatrixWidth;
     158          59 :     poTilingScheme->nTileYCountZoomLevel0 = zoomLevel0.mMatrixHeight;
     159          59 :     poTilingScheme->nTileWidth = zoomLevel0.mTileWidth;
     160          59 :     poTilingScheme->nTileHeight = zoomLevel0.mTileHeight;
     161          59 :     poTilingScheme->dfPixelXSizeZoomLevel0 = zoomLevel0.mResX;
     162          59 :     poTilingScheme->dfPixelYSizeZoomLevel0 = zoomLevel0.mResY;
     163             : 
     164         118 :     const bool bInvertAxis = oSRS.EPSGTreatsAsLatLong() != FALSE ||
     165          59 :                              oSRS.EPSGTreatsAsNorthingEasting() != FALSE;
     166          59 :     if (bInvertAxis)
     167             :     {
     168           6 :         std::swap(poTilingScheme->dfMinX, poTilingScheme->dfMaxY);
     169           6 :         std::swap(poTilingScheme->dfPixelXSizeZoomLevel0,
     170           6 :                   poTilingScheme->dfPixelYSizeZoomLevel0);
     171             :     }
     172          59 :     return poTilingScheme;
     173             : }
     174             : 
     175             : static const char *pszCREATE_GPKG_GEOMETRY_COLUMNS =
     176             :     "CREATE TABLE gpkg_geometry_columns ("
     177             :     "table_name TEXT NOT NULL,"
     178             :     "column_name TEXT NOT NULL,"
     179             :     "geometry_type_name TEXT NOT NULL,"
     180             :     "srs_id INTEGER NOT NULL,"
     181             :     "z TINYINT NOT NULL,"
     182             :     "m TINYINT NOT NULL,"
     183             :     "CONSTRAINT pk_geom_cols PRIMARY KEY (table_name, column_name),"
     184             :     "CONSTRAINT uk_gc_table_name UNIQUE (table_name),"
     185             :     "CONSTRAINT fk_gc_tn FOREIGN KEY (table_name) REFERENCES "
     186             :     "gpkg_contents(table_name),"
     187             :     "CONSTRAINT fk_gc_srs FOREIGN KEY (srs_id) REFERENCES gpkg_spatial_ref_sys "
     188             :     "(srs_id)"
     189             :     ")";
     190             : 
     191        1134 : OGRErr GDALGeoPackageDataset::SetApplicationAndUserVersionId()
     192             : {
     193        1134 :     CPLAssert(hDB != nullptr);
     194             : 
     195        1134 :     const CPLString osPragma(CPLString().Printf("PRAGMA application_id = %u;"
     196             :                                                 "PRAGMA user_version = %u",
     197             :                                                 m_nApplicationId,
     198        2268 :                                                 m_nUserVersion));
     199        2268 :     return SQLCommand(hDB, osPragma.c_str());
     200             : }
     201             : 
     202        2997 : bool GDALGeoPackageDataset::CloseDB()
     203             : {
     204        2997 :     OGRSQLiteUnregisterSQLFunctions(m_pSQLFunctionData);
     205        2997 :     m_pSQLFunctionData = nullptr;
     206        2997 :     return OGRSQLiteBaseDataSource::CloseDB();
     207             : }
     208             : 
     209          12 : bool GDALGeoPackageDataset::ReOpenDB()
     210             : {
     211          12 :     CPLAssert(hDB != nullptr);
     212          12 :     CPLAssert(m_pszFilename != nullptr);
     213             : 
     214          12 :     FinishSpatialite();
     215             : 
     216          12 :     CloseDB();
     217             : 
     218             :     /* And re-open the file */
     219          12 :     return OpenOrCreateDB(SQLITE_OPEN_READWRITE);
     220             : }
     221             : 
     222        1005 : static OGRErr GDALGPKGImportFromEPSG(OGRSpatialReference *poSpatialRef,
     223             :                                      int nEPSGCode)
     224             : {
     225        1005 :     CPLPushErrorHandler(CPLQuietErrorHandler);
     226        1005 :     const OGRErr eErr = poSpatialRef->importFromEPSG(nEPSGCode);
     227        1005 :     CPLPopErrorHandler();
     228        1005 :     CPLErrorReset();
     229        1005 :     return eErr;
     230             : }
     231             : 
     232             : OGRSpatialReferenceRefCountedPtr
     233        1470 : GDALGeoPackageDataset::GetSpatialRef(int iSrsId, bool bFallbackToEPSG,
     234             :                                      bool bEmitErrorIfNotFound)
     235             : {
     236        1470 :     const auto oIter = m_oMapSrsIdToSrs.find(iSrsId);
     237        1470 :     if (oIter != m_oMapSrsIdToSrs.end())
     238             :     {
     239         103 :         return oIter->second;
     240             :     }
     241             : 
     242        1367 :     if (iSrsId == 0 || iSrsId == -1)
     243             :     {
     244         124 :         auto poSpatialRef = OGRSpatialReferenceRefCountedPtr::makeInstance();
     245         124 :         poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     246             : 
     247             :         // See corresponding tests in GDALGeoPackageDataset::GetSrsId
     248         124 :         if (iSrsId == 0)
     249             :         {
     250          31 :             poSpatialRef->SetGeogCS("Undefined geographic SRS", "unknown",
     251             :                                     "unknown", SRS_WGS84_SEMIMAJOR,
     252             :                                     SRS_WGS84_INVFLATTENING);
     253             :         }
     254          93 :         else if (iSrsId == -1)
     255             :         {
     256          93 :             poSpatialRef->SetLocalCS("Undefined Cartesian SRS");
     257          93 :             poSpatialRef->SetLinearUnits(SRS_UL_METER, 1.0);
     258             :         }
     259             : 
     260         248 :         return m_oMapSrsIdToSrs.insert({iSrsId, std::move(poSpatialRef)})
     261         124 :             .first->second;
     262             :     }
     263             : 
     264        2486 :     CPLString oSQL;
     265        1243 :     oSQL.Printf("SELECT srs_name, definition, organization, "
     266             :                 "organization_coordsys_id%s%s "
     267             :                 "FROM gpkg_spatial_ref_sys WHERE "
     268             :                 "srs_id = %d LIMIT 2",
     269        1243 :                 m_bHasDefinition12_063 ? ", definition_12_063" : "",
     270        1243 :                 m_bHasEpochColumn ? ", epoch" : "", iSrsId);
     271             : 
     272        2486 :     auto oResult = SQLQuery(hDB, oSQL.c_str());
     273             : 
     274        1243 :     if (!oResult || oResult->RowCount() != 1)
     275             :     {
     276          12 :         if (bFallbackToEPSG)
     277             :         {
     278           7 :             CPLDebug("GPKG",
     279             :                      "unable to read srs_id '%d' from gpkg_spatial_ref_sys",
     280             :                      iSrsId);
     281           7 :             auto poSRS = OGRSpatialReferenceRefCountedPtr::makeInstance();
     282           7 :             if (poSRS->importFromEPSG(iSrsId) == OGRERR_NONE)
     283             :             {
     284           5 :                 poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     285           5 :                 return poSRS;
     286             :             }
     287             :         }
     288           5 :         else if (bEmitErrorIfNotFound)
     289             :         {
     290           2 :             CPLError(CE_Warning, CPLE_AppDefined,
     291             :                      "unable to read srs_id '%d' from gpkg_spatial_ref_sys",
     292             :                      iSrsId);
     293           2 :             m_oMapSrsIdToSrs[iSrsId] = nullptr;
     294             :         }
     295           7 :         return nullptr;
     296             :     }
     297             : 
     298        1231 :     const char *pszName = oResult->GetValue(0, 0);
     299        1231 :     if (pszName && EQUAL(pszName, "Undefined SRS"))
     300             :     {
     301         520 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     302         520 :         return nullptr;
     303             :     }
     304         711 :     const char *pszWkt = oResult->GetValue(1, 0);
     305         711 :     if (pszWkt == nullptr)
     306           0 :         return nullptr;
     307         711 :     const char *pszOrganization = oResult->GetValue(2, 0);
     308         711 :     const char *pszOrganizationCoordsysID = oResult->GetValue(3, 0);
     309             :     const char *pszWkt2 =
     310         711 :         m_bHasDefinition12_063 ? oResult->GetValue(4, 0) : nullptr;
     311         711 :     if (pszWkt2 && !EQUAL(pszWkt2, "undefined"))
     312          76 :         pszWkt = pszWkt2;
     313             :     const char *pszCoordinateEpoch =
     314         711 :         m_bHasEpochColumn ? oResult->GetValue(5, 0) : nullptr;
     315             :     const double dfCoordinateEpoch =
     316         711 :         pszCoordinateEpoch ? CPLAtof(pszCoordinateEpoch) : 0.0;
     317             : 
     318        1422 :     auto poSpatialRef = OGRSpatialReferenceRefCountedPtr::makeInstance();
     319         711 :     poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     320             :     // Try to import first from EPSG code, and then from WKT
     321         711 :     if (!(pszOrganization && pszOrganizationCoordsysID &&
     322         711 :           EQUAL(pszOrganization, "EPSG") &&
     323         687 :           (atoi(pszOrganizationCoordsysID) == iSrsId ||
     324           4 :            (dfCoordinateEpoch > 0 && strstr(pszWkt, "DYNAMIC[") == nullptr)) &&
     325         687 :           GDALGPKGImportFromEPSG(poSpatialRef.get(),
     326             :                                  atoi(pszOrganizationCoordsysID)) ==
     327        1422 :               OGRERR_NONE) &&
     328          24 :         poSpatialRef->importFromWkt(pszWkt) != OGRERR_NONE)
     329             :     {
     330           0 :         CPLError(CE_Warning, CPLE_AppDefined,
     331             :                  "Unable to parse srs_id '%d' well-known text '%s'", iSrsId,
     332             :                  pszWkt);
     333           0 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     334           0 :         return nullptr;
     335             :     }
     336             : 
     337         711 :     poSpatialRef->StripTOWGS84IfKnownDatumAndAllowed();
     338         711 :     poSpatialRef->SetCoordinateEpoch(dfCoordinateEpoch);
     339        1422 :     return m_oMapSrsIdToSrs.insert({iSrsId, std::move(poSpatialRef)})
     340         711 :         .first->second;
     341             : }
     342             : 
     343         349 : const char *GDALGeoPackageDataset::GetSrsName(const OGRSpatialReference &oSRS)
     344             : {
     345         349 :     const char *pszName = oSRS.GetName();
     346         349 :     if (pszName)
     347         349 :         return pszName;
     348             : 
     349             :     // Something odd.  Return empty.
     350           0 :     return "Unnamed SRS";
     351             : }
     352             : 
     353             : /* Add the definition_12_063 column to an existing gpkg_spatial_ref_sys table */
     354           7 : bool GDALGeoPackageDataset::ConvertGpkgSpatialRefSysToExtensionWkt2(
     355             :     bool bForceEpoch)
     356             : {
     357           7 :     const bool bAddEpoch = (m_nUserVersion >= GPKG_1_4_VERSION || bForceEpoch);
     358             :     auto oResultTable = SQLQuery(
     359             :         hDB, "SELECT srs_name, srs_id, organization, organization_coordsys_id, "
     360          14 :              "definition, description FROM gpkg_spatial_ref_sys LIMIT 100000");
     361           7 :     if (!oResultTable)
     362           0 :         return false;
     363             : 
     364             :     // Temporary remove foreign key checks
     365             :     const GPKGTemporaryForeignKeyCheckDisabler
     366           7 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
     367             : 
     368           7 :     bool bRet = SoftStartTransaction() == OGRERR_NONE;
     369             : 
     370           7 :     if (bRet)
     371             :     {
     372             :         std::string osSQL("CREATE TABLE gpkg_spatial_ref_sys_temp ("
     373             :                           "srs_name TEXT NOT NULL,"
     374             :                           "srs_id INTEGER NOT NULL PRIMARY KEY,"
     375             :                           "organization TEXT NOT NULL,"
     376             :                           "organization_coordsys_id INTEGER NOT NULL,"
     377             :                           "definition TEXT NOT NULL,"
     378             :                           "description TEXT, "
     379           7 :                           "definition_12_063 TEXT NOT NULL");
     380           7 :         if (bAddEpoch)
     381           6 :             osSQL += ", epoch DOUBLE";
     382           7 :         osSQL += ")";
     383           7 :         bRet = SQLCommand(hDB, osSQL.c_str()) == OGRERR_NONE;
     384             :     }
     385             : 
     386           7 :     if (bRet)
     387             :     {
     388          32 :         for (int i = 0; bRet && i < oResultTable->RowCount(); i++)
     389             :         {
     390          25 :             const char *pszSrsName = oResultTable->GetValue(0, i);
     391          25 :             const char *pszSrsId = oResultTable->GetValue(1, i);
     392          25 :             const char *pszOrganization = oResultTable->GetValue(2, i);
     393             :             const char *pszOrganizationCoordsysID =
     394          25 :                 oResultTable->GetValue(3, i);
     395          25 :             const char *pszDefinition = oResultTable->GetValue(4, i);
     396             :             if (pszSrsName == nullptr || pszSrsId == nullptr ||
     397             :                 pszOrganization == nullptr ||
     398             :                 pszOrganizationCoordsysID == nullptr)
     399             :             {
     400             :                 // should not happen as there are NOT NULL constraints
     401             :                 // But a database could lack such NOT NULL constraints or have
     402             :                 // large values that would cause a memory allocation failure.
     403             :             }
     404          25 :             const char *pszDescription = oResultTable->GetValue(5, i);
     405             :             char *pszSQL;
     406             : 
     407          50 :             OGRSpatialReference oSRS;
     408          25 :             if (pszOrganization && pszOrganizationCoordsysID &&
     409          25 :                 EQUAL(pszOrganization, "EPSG"))
     410             :             {
     411           9 :                 oSRS.importFromEPSG(atoi(pszOrganizationCoordsysID));
     412             :             }
     413          34 :             if (!oSRS.IsEmpty() && pszDefinition &&
     414           9 :                 !EQUAL(pszDefinition, "undefined"))
     415             :             {
     416           9 :                 oSRS.SetFromUserInput(pszDefinition);
     417             :             }
     418          25 :             char *pszWKT2 = nullptr;
     419          25 :             if (!oSRS.IsEmpty())
     420             :             {
     421           9 :                 const char *const apszOptionsWkt2[] = {"FORMAT=WKT2_2015",
     422             :                                                        nullptr};
     423           9 :                 oSRS.exportToWkt(&pszWKT2, apszOptionsWkt2);
     424           9 :                 if (pszWKT2 && pszWKT2[0] == '\0')
     425             :                 {
     426           0 :                     CPLFree(pszWKT2);
     427           0 :                     pszWKT2 = nullptr;
     428             :                 }
     429             :             }
     430          25 :             if (pszWKT2 == nullptr)
     431             :             {
     432          16 :                 pszWKT2 = CPLStrdup("undefined");
     433             :             }
     434             : 
     435          25 :             if (pszDescription)
     436             :             {
     437          22 :                 pszSQL = sqlite3_mprintf(
     438             :                     "INSERT INTO gpkg_spatial_ref_sys_temp(srs_name, srs_id, "
     439             :                     "organization, organization_coordsys_id, definition, "
     440             :                     "description, definition_12_063) VALUES ('%q', '%q', '%q', "
     441             :                     "'%q', '%q', '%q', '%q')",
     442             :                     pszSrsName, pszSrsId, pszOrganization,
     443             :                     pszOrganizationCoordsysID, pszDefinition, pszDescription,
     444             :                     pszWKT2);
     445             :             }
     446             :             else
     447             :             {
     448           3 :                 pszSQL = sqlite3_mprintf(
     449             :                     "INSERT INTO gpkg_spatial_ref_sys_temp(srs_name, srs_id, "
     450             :                     "organization, organization_coordsys_id, definition, "
     451             :                     "description, definition_12_063) VALUES ('%q', '%q', '%q', "
     452             :                     "'%q', '%q', NULL, '%q')",
     453             :                     pszSrsName, pszSrsId, pszOrganization,
     454             :                     pszOrganizationCoordsysID, pszDefinition, pszWKT2);
     455             :             }
     456             : 
     457          25 :             CPLFree(pszWKT2);
     458          25 :             bRet &= SQLCommand(hDB, pszSQL) == OGRERR_NONE;
     459          25 :             sqlite3_free(pszSQL);
     460             :         }
     461             :     }
     462             : 
     463           7 :     if (bRet)
     464             :     {
     465           7 :         bRet =
     466           7 :             SQLCommand(hDB, "DROP TABLE gpkg_spatial_ref_sys") == OGRERR_NONE;
     467             :     }
     468           7 :     if (bRet)
     469             :     {
     470           7 :         bRet = SQLCommand(hDB, "ALTER TABLE gpkg_spatial_ref_sys_temp RENAME "
     471             :                                "TO gpkg_spatial_ref_sys") == OGRERR_NONE;
     472             :     }
     473           7 :     if (bRet)
     474             :     {
     475          14 :         bRet = OGRERR_NONE == CreateExtensionsTableIfNecessary() &&
     476           7 :                OGRERR_NONE == SQLCommand(hDB,
     477             :                                          "INSERT INTO gpkg_extensions "
     478             :                                          "(table_name, column_name, "
     479             :                                          "extension_name, definition, scope) "
     480             :                                          "VALUES "
     481             :                                          "('gpkg_spatial_ref_sys', "
     482             :                                          "'definition_12_063', 'gpkg_crs_wkt', "
     483             :                                          "'http://www.geopackage.org/spec120/"
     484             :                                          "#extension_crs_wkt', 'read-write')");
     485             :     }
     486           7 :     if (bRet && bAddEpoch)
     487             :     {
     488           6 :         bRet =
     489             :             OGRERR_NONE ==
     490           6 :                 SQLCommand(hDB, "UPDATE gpkg_extensions SET extension_name = "
     491             :                                 "'gpkg_crs_wkt_1_1' "
     492          12 :                                 "WHERE extension_name = 'gpkg_crs_wkt'") &&
     493             :             OGRERR_NONE ==
     494           6 :                 SQLCommand(
     495             :                     hDB,
     496             :                     "INSERT INTO gpkg_extensions "
     497             :                     "(table_name, column_name, extension_name, definition, "
     498             :                     "scope) "
     499             :                     "VALUES "
     500             :                     "('gpkg_spatial_ref_sys', 'epoch', 'gpkg_crs_wkt_1_1', "
     501             :                     "'http://www.geopackage.org/spec/#extension_crs_wkt', "
     502             :                     "'read-write')");
     503             :     }
     504           7 :     if (bRet)
     505             :     {
     506           7 :         SoftCommitTransaction();
     507           7 :         m_bHasDefinition12_063 = true;
     508           7 :         if (bAddEpoch)
     509           6 :             m_bHasEpochColumn = true;
     510             :     }
     511             :     else
     512             :     {
     513           0 :         SoftRollbackTransaction();
     514             :     }
     515             : 
     516           7 :     return bRet;
     517             : }
     518             : 
     519        1108 : int GDALGeoPackageDataset::GetSrsId(const OGRSpatialReference *poSRSIn)
     520             : {
     521        1108 :     const char *pszName = poSRSIn ? poSRSIn->GetName() : nullptr;
     522        1614 :     if (!poSRSIn || poSRSIn->IsEmpty() ||
     523         506 :         (pszName && EQUAL(pszName, "Undefined SRS")))
     524             :     {
     525         604 :         OGRErr err = OGRERR_NONE;
     526         604 :         const int nSRSId = SQLGetInteger(
     527             :             hDB,
     528             :             "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE srs_name = "
     529             :             "'Undefined SRS' AND organization = 'GDAL'",
     530             :             &err);
     531         604 :         if (err == OGRERR_NONE)
     532          60 :             return nSRSId;
     533             : 
     534             :         // The below WKT definitions are somehow questionable (using an unknown
     535             :         // unit). For GDAL >= 3.9, they won't be used. They will only be used
     536             :         // for earlier versions.
     537             :         const char *pszSQL;
     538             : #define UNDEFINED_CRS_SRS_ID 99999
     539             :         static_assert(UNDEFINED_CRS_SRS_ID == FIRST_CUSTOM_SRSID - 1);
     540             : #define STRINGIFY(x) #x
     541             : #define XSTRINGIFY(x) STRINGIFY(x)
     542         544 :         if (m_bHasDefinition12_063)
     543             :         {
     544             :             /* clang-format off */
     545           1 :             pszSQL =
     546             :                 "INSERT INTO gpkg_spatial_ref_sys "
     547             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     548             :                 "definition, definition_12_063, description) VALUES "
     549             :                 "('Undefined SRS'," XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ",'GDAL',"
     550             :                 XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ","
     551             :                 "'LOCAL_CS[\"Undefined SRS\",LOCAL_DATUM[\"unknown\",32767],"
     552             :                 "UNIT[\"unknown\",0],AXIS[\"Easting\",EAST],"
     553             :                 "AXIS[\"Northing\",NORTH]]',"
     554             :                 "'ENGCRS[\"Undefined SRS\",EDATUM[\"unknown\"],CS[Cartesian,2],"
     555             :                 "AXIS[\"easting\",east,ORDER[1],LENGTHUNIT[\"unknown\",0]],"
     556             :                 "AXIS[\"northing\",north,ORDER[2],LENGTHUNIT[\"unknown\",0]]]',"
     557             :                 "'Custom undefined coordinate reference system')";
     558             :             /* clang-format on */
     559             :         }
     560             :         else
     561             :         {
     562             :             /* clang-format off */
     563         543 :             pszSQL =
     564             :                 "INSERT INTO gpkg_spatial_ref_sys "
     565             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     566             :                 "definition, description) VALUES "
     567             :                 "('Undefined SRS'," XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ",'GDAL',"
     568             :                 XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ","
     569             :                 "'LOCAL_CS[\"Undefined SRS\",LOCAL_DATUM[\"unknown\",32767],"
     570             :                 "UNIT[\"unknown\",0],AXIS[\"Easting\",EAST],"
     571             :                 "AXIS[\"Northing\",NORTH]]',"
     572             :                 "'Custom undefined coordinate reference system')";
     573             :             /* clang-format on */
     574             :         }
     575         544 :         if (SQLCommand(hDB, pszSQL) == OGRERR_NONE)
     576         544 :             return UNDEFINED_CRS_SRS_ID;
     577             : #undef UNDEFINED_CRS_SRS_ID
     578             : #undef XSTRINGIFY
     579             : #undef STRINGIFY
     580           0 :         return -1;
     581             :     }
     582             : 
     583        1008 :     auto poSRS = OGRSpatialReferenceRefCountedPtr::makeClone(poSRSIn);
     584         504 :     if (poSRS->IsGeographic() || poSRS->IsLocal())
     585             :     {
     586             :         // See corresponding tests in GDALGeoPackageDataset::GetSpatialRef
     587         173 :         if (pszName != nullptr && strlen(pszName) > 0)
     588             :         {
     589         173 :             if (EQUAL(pszName, "Undefined geographic SRS"))
     590           2 :                 return 0;
     591             : 
     592         171 :             if (EQUAL(pszName, "Undefined Cartesian SRS"))
     593           1 :                 return -1;
     594             :         }
     595             :     }
     596             : 
     597         501 :     const char *pszAuthorityName = poSRS->GetAuthorityName();
     598             : 
     599         501 :     if (pszAuthorityName == nullptr || strlen(pszAuthorityName) == 0)
     600             :     {
     601             :         // Try to force identify an EPSG code.
     602          28 :         poSRS->AutoIdentifyEPSG();
     603             : 
     604          28 :         pszAuthorityName = poSRS->GetAuthorityName();
     605          28 :         if (pszAuthorityName != nullptr && EQUAL(pszAuthorityName, "EPSG"))
     606             :         {
     607           0 :             const char *pszAuthorityCode = poSRS->GetAuthorityCode();
     608           0 :             if (pszAuthorityCode != nullptr && strlen(pszAuthorityCode) > 0)
     609             :             {
     610             :                 /* Import 'clean' SRS */
     611           0 :                 poSRS->importFromEPSG(atoi(pszAuthorityCode));
     612             : 
     613           0 :                 pszAuthorityName = poSRS->GetAuthorityName();
     614             :             }
     615             :         }
     616             : 
     617          28 :         poSRS->SetCoordinateEpoch(poSRSIn->GetCoordinateEpoch());
     618             :     }
     619             : 
     620             :     // Check whether the EPSG authority code is already mapped to a
     621             :     // SRS ID.
     622         501 :     char *pszSQL = nullptr;
     623         501 :     int nSRSId = DEFAULT_SRID;
     624         501 :     int nAuthorityCode = 0;
     625         501 :     OGRErr err = OGRERR_NONE;
     626         501 :     bool bCanUseAuthorityCode = false;
     627         501 :     const char *const apszIsSameOptions[] = {
     628             :         "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES",
     629             :         "IGNORE_COORDINATE_EPOCH=YES", nullptr};
     630         501 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0)
     631             :     {
     632         473 :         const char *pszAuthorityCode = poSRS->GetAuthorityCode();
     633         473 :         if (pszAuthorityCode)
     634             :         {
     635         473 :             if (CPLGetValueType(pszAuthorityCode) == CPL_VALUE_INTEGER)
     636             :             {
     637         473 :                 nAuthorityCode = atoi(pszAuthorityCode);
     638             :             }
     639             :             else
     640             :             {
     641           0 :                 CPLDebug("GPKG",
     642             :                          "SRS has %s:%s identification, but the code not "
     643             :                          "being an integer value cannot be stored as such "
     644             :                          "in the database.",
     645             :                          pszAuthorityName, pszAuthorityCode);
     646           0 :                 pszAuthorityName = nullptr;
     647             :             }
     648             :         }
     649             :     }
     650             : 
     651         974 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     652         473 :         poSRSIn->GetCoordinateEpoch() == 0)
     653             :     {
     654             :         pszSQL =
     655         468 :             sqlite3_mprintf("SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     656             :                             "upper(organization) = upper('%q') AND "
     657             :                             "organization_coordsys_id = %d",
     658             :                             pszAuthorityName, nAuthorityCode);
     659             : 
     660         468 :         nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     661         468 :         sqlite3_free(pszSQL);
     662             : 
     663             :         // Got a match? Return it!
     664         468 :         if (OGRERR_NONE == err)
     665             :         {
     666         148 :             auto poRefSRS = GetSpatialRef(nSRSId);
     667             :             bool bOK =
     668         148 :                 (poRefSRS == nullptr ||
     669         149 :                  poSRS->IsSame(poRefSRS.get(), apszIsSameOptions) ||
     670           1 :                  !CPLTestBool(CPLGetConfigOption("OGR_GPKG_CHECK_SRS", "YES")));
     671         148 :             if (bOK)
     672             :             {
     673         147 :                 return nSRSId;
     674             :             }
     675             :             else
     676             :             {
     677           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
     678             :                          "Passed SRS uses %s:%d identification, but its "
     679             :                          "definition is not compatible with the "
     680             :                          "definition of that object already in the database. "
     681             :                          "Registering it as a new entry into the database.",
     682             :                          pszAuthorityName, nAuthorityCode);
     683           1 :                 pszAuthorityName = nullptr;
     684           1 :                 nAuthorityCode = 0;
     685             :             }
     686             :         }
     687             :     }
     688             : 
     689             :     // Translate SRS to WKT.
     690         354 :     CPLCharUniquePtr pszWKT1;
     691         354 :     CPLCharUniquePtr pszWKT2_2015;
     692         354 :     CPLCharUniquePtr pszWKT2_2019;
     693         354 :     const char *const apszOptionsWkt1[] = {"FORMAT=WKT1_GDAL", nullptr};
     694         354 :     const char *const apszOptionsWkt2_2015[] = {"FORMAT=WKT2_2015", nullptr};
     695         354 :     const char *const apszOptionsWkt2_2019[] = {"FORMAT=WKT2_2019", nullptr};
     696             : 
     697         708 :     std::string osEpochTest;
     698         354 :     if (poSRSIn->GetCoordinateEpoch() > 0 && m_bHasEpochColumn)
     699             :     {
     700             :         osEpochTest =
     701           3 :             CPLSPrintf(" AND epoch = %.17g", poSRSIn->GetCoordinateEpoch());
     702             :     }
     703             : 
     704         699 :     if (!(poSRS->IsGeographic() && poSRS->GetAxesCount() == 3) &&
     705         345 :         !poSRS->IsDerivedGeographic())
     706             :     {
     707         690 :         CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
     708         345 :         char *pszTmp = nullptr;
     709         345 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt1);
     710         345 :         pszWKT1.reset(pszTmp);
     711         345 :         if (pszWKT1 && pszWKT1.get()[0] == '\0')
     712             :         {
     713           0 :             pszWKT1.reset();
     714             :         }
     715             :     }
     716             :     {
     717         708 :         CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
     718         354 :         char *pszTmp = nullptr;
     719         354 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2015);
     720         354 :         pszWKT2_2015.reset(pszTmp);
     721         354 :         if (pszWKT2_2015 && pszWKT2_2015.get()[0] == '\0')
     722             :         {
     723           0 :             pszWKT2_2015.reset();
     724             :         }
     725             :     }
     726             :     {
     727         354 :         char *pszTmp = nullptr;
     728         354 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2019);
     729         354 :         pszWKT2_2019.reset(pszTmp);
     730         354 :         if (pszWKT2_2019 && pszWKT2_2019.get()[0] == '\0')
     731             :         {
     732           0 :             pszWKT2_2019.reset();
     733             :         }
     734             :     }
     735             : 
     736         354 :     if (!pszWKT1 && !pszWKT2_2015 && !pszWKT2_2019)
     737             :     {
     738           0 :         return DEFAULT_SRID;
     739             :     }
     740             : 
     741         354 :     if (poSRSIn->GetCoordinateEpoch() == 0 || m_bHasEpochColumn)
     742             :     {
     743             :         // Search if there is already an existing entry with this WKT
     744         351 :         if (m_bHasDefinition12_063 && (pszWKT2_2015 || pszWKT2_2019))
     745             :         {
     746          42 :             if (pszWKT1)
     747             :             {
     748         144 :                 pszSQL = sqlite3_mprintf(
     749             :                     "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     750             :                     "(definition = '%q' OR definition_12_063 IN ('%q','%q'))%s",
     751             :                     pszWKT1.get(),
     752          72 :                     pszWKT2_2015 ? pszWKT2_2015.get() : "invalid",
     753          72 :                     pszWKT2_2019 ? pszWKT2_2019.get() : "invalid",
     754             :                     osEpochTest.c_str());
     755             :             }
     756             :             else
     757             :             {
     758          24 :                 pszSQL = sqlite3_mprintf(
     759             :                     "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     760             :                     "definition_12_063 IN ('%q', '%q')%s",
     761          12 :                     pszWKT2_2015 ? pszWKT2_2015.get() : "invalid",
     762          12 :                     pszWKT2_2019 ? pszWKT2_2019.get() : "invalid",
     763             :                     osEpochTest.c_str());
     764             :             }
     765             :         }
     766         309 :         else if (pszWKT1)
     767             :         {
     768             :             pszSQL =
     769         306 :                 sqlite3_mprintf("SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     770             :                                 "definition = '%q'%s",
     771             :                                 pszWKT1.get(), osEpochTest.c_str());
     772             :         }
     773             :         else
     774             :         {
     775           3 :             pszSQL = nullptr;
     776             :         }
     777         351 :         if (pszSQL)
     778             :         {
     779         348 :             nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     780         348 :             sqlite3_free(pszSQL);
     781         348 :             if (OGRERR_NONE == err)
     782             :             {
     783           5 :                 return nSRSId;
     784             :             }
     785             :         }
     786             :     }
     787             : 
     788         672 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     789         323 :         poSRSIn->GetCoordinateEpoch() == 0)
     790             :     {
     791         319 :         bool bTryToReuseSRSId = true;
     792         319 :         if (EQUAL(pszAuthorityName, "EPSG"))
     793             :         {
     794         636 :             OGRSpatialReference oSRS_EPSG;
     795         318 :             if (GDALGPKGImportFromEPSG(&oSRS_EPSG, nAuthorityCode) ==
     796             :                 OGRERR_NONE)
     797             :             {
     798         319 :                 if (!poSRS->IsSame(&oSRS_EPSG, apszIsSameOptions) &&
     799           1 :                     CPLTestBool(
     800             :                         CPLGetConfigOption("OGR_GPKG_CHECK_SRS", "YES")))
     801             :                 {
     802           1 :                     bTryToReuseSRSId = false;
     803           1 :                     CPLError(
     804             :                         CE_Warning, CPLE_AppDefined,
     805             :                         "Passed SRS uses %s:%d identification, but its "
     806             :                         "definition is not compatible with the "
     807             :                         "official definition of the object. "
     808             :                         "Registering it as a non-%s entry into the database.",
     809             :                         pszAuthorityName, nAuthorityCode, pszAuthorityName);
     810           1 :                     pszAuthorityName = nullptr;
     811           1 :                     nAuthorityCode = 0;
     812             :                 }
     813             :             }
     814             :         }
     815         319 :         if (bTryToReuseSRSId)
     816             :         {
     817             :             // No match, but maybe we can use the nAuthorityCode as the nSRSId?
     818         318 :             pszSQL = sqlite3_mprintf(
     819             :                 "SELECT Count(*) FROM gpkg_spatial_ref_sys WHERE "
     820             :                 "srs_id = %d",
     821             :                 nAuthorityCode);
     822             : 
     823             :             // Yep, we can!
     824         318 :             if (SQLGetInteger(hDB, pszSQL, nullptr) == 0)
     825         317 :                 bCanUseAuthorityCode = true;
     826         318 :             sqlite3_free(pszSQL);
     827             :         }
     828             :     }
     829             : 
     830         349 :     bool bConvertGpkgSpatialRefSysToExtensionWkt2 = false;
     831         349 :     bool bForceEpoch = false;
     832         352 :     if (!m_bHasDefinition12_063 && pszWKT1 == nullptr &&
     833           3 :         (pszWKT2_2015 != nullptr || pszWKT2_2019 != nullptr))
     834             :     {
     835           3 :         bConvertGpkgSpatialRefSysToExtensionWkt2 = true;
     836             :     }
     837             : 
     838             :     // Add epoch column if needed
     839         349 :     if (poSRSIn->GetCoordinateEpoch() > 0 && !m_bHasEpochColumn)
     840             :     {
     841           3 :         if (m_bHasDefinition12_063)
     842             :         {
     843           0 :             if (SoftStartTransaction() != OGRERR_NONE)
     844           0 :                 return DEFAULT_SRID;
     845           0 :             if (SQLCommand(hDB, "ALTER TABLE gpkg_spatial_ref_sys "
     846           0 :                                 "ADD COLUMN epoch DOUBLE") != OGRERR_NONE ||
     847           0 :                 SQLCommand(hDB, "UPDATE gpkg_extensions SET extension_name = "
     848             :                                 "'gpkg_crs_wkt_1_1' "
     849             :                                 "WHERE extension_name = 'gpkg_crs_wkt'") !=
     850           0 :                     OGRERR_NONE ||
     851           0 :                 SQLCommand(
     852             :                     hDB,
     853             :                     "INSERT INTO gpkg_extensions "
     854             :                     "(table_name, column_name, extension_name, definition, "
     855             :                     "scope) "
     856             :                     "VALUES "
     857             :                     "('gpkg_spatial_ref_sys', 'epoch', 'gpkg_crs_wkt_1_1', "
     858             :                     "'http://www.geopackage.org/spec/#extension_crs_wkt', "
     859             :                     "'read-write')") != OGRERR_NONE)
     860             :             {
     861           0 :                 SoftRollbackTransaction();
     862           0 :                 return DEFAULT_SRID;
     863             :             }
     864             : 
     865           0 :             if (SoftCommitTransaction() != OGRERR_NONE)
     866           0 :                 return DEFAULT_SRID;
     867             : 
     868           0 :             m_bHasEpochColumn = true;
     869             :         }
     870             :         else
     871             :         {
     872           3 :             bConvertGpkgSpatialRefSysToExtensionWkt2 = true;
     873           3 :             bForceEpoch = true;
     874             :         }
     875             :     }
     876             : 
     877         355 :     if (bConvertGpkgSpatialRefSysToExtensionWkt2 &&
     878           6 :         !ConvertGpkgSpatialRefSysToExtensionWkt2(bForceEpoch))
     879             :     {
     880           0 :         return DEFAULT_SRID;
     881             :     }
     882             : 
     883             :     // Reuse the authority code number as SRS_ID if we can
     884         349 :     if (bCanUseAuthorityCode)
     885             :     {
     886         317 :         nSRSId = nAuthorityCode;
     887             :     }
     888             :     // Otherwise, generate a new SRS_ID number (max + 1)
     889             :     else
     890             :     {
     891             :         // Get the current maximum srid in the srs table.
     892          32 :         const int nMaxSRSId = SQLGetInteger(
     893             :             hDB, "SELECT MAX(srs_id) FROM gpkg_spatial_ref_sys", nullptr);
     894          32 :         nSRSId = std::max(FIRST_CUSTOM_SRSID, nMaxSRSId + 1);
     895             :     }
     896             : 
     897         698 :     std::string osEpochColumn;
     898         349 :     std::string osEpochVal;
     899         349 :     if (poSRSIn->GetCoordinateEpoch() > 0)
     900             :     {
     901           5 :         osEpochColumn = ", epoch";
     902           5 :         osEpochVal = CPLSPrintf(", %.17g", poSRSIn->GetCoordinateEpoch());
     903             :     }
     904             : 
     905             :     // Add new SRS row to gpkg_spatial_ref_sys.
     906         349 :     if (m_bHasDefinition12_063)
     907             :     {
     908             :         // Force WKT2_2019 when we have a dynamic CRS and coordinate epoch
     909          45 :         const char *pszWKT2 = poSRSIn->IsDynamic() &&
     910          10 :                                       poSRSIn->GetCoordinateEpoch() > 0 &&
     911           1 :                                       pszWKT2_2019
     912           1 :                                   ? pszWKT2_2019.get()
     913          44 :                               : pszWKT2_2015 ? pszWKT2_2015.get()
     914          97 :                                              : pszWKT2_2019.get();
     915             : 
     916          45 :         if (pszAuthorityName != nullptr && nAuthorityCode > 0)
     917             :         {
     918          99 :             pszSQL = sqlite3_mprintf(
     919             :                 "INSERT INTO gpkg_spatial_ref_sys "
     920             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     921             :                 "definition, definition_12_063%s) VALUES "
     922             :                 "('%q', %d, upper('%q'), %d, '%q', '%q'%s)",
     923          33 :                 osEpochColumn.c_str(), GetSrsName(*poSRS), nSRSId,
     924             :                 pszAuthorityName, nAuthorityCode,
     925          62 :                 pszWKT1 ? pszWKT1.get() : "undefined",
     926             :                 pszWKT2 ? pszWKT2 : "undefined", osEpochVal.c_str());
     927             :         }
     928             :         else
     929             :         {
     930          36 :             pszSQL = sqlite3_mprintf(
     931             :                 "INSERT INTO gpkg_spatial_ref_sys "
     932             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     933             :                 "definition, definition_12_063%s) VALUES "
     934             :                 "('%q', %d, upper('%q'), %d, '%q', '%q'%s)",
     935          12 :                 osEpochColumn.c_str(), GetSrsName(*poSRS), nSRSId, "NONE",
     936          21 :                 nSRSId, pszWKT1 ? pszWKT1.get() : "undefined",
     937             :                 pszWKT2 ? pszWKT2 : "undefined", osEpochVal.c_str());
     938             :         }
     939             :     }
     940             :     else
     941             :     {
     942         304 :         if (pszAuthorityName != nullptr && nAuthorityCode > 0)
     943             :         {
     944         578 :             pszSQL = sqlite3_mprintf(
     945             :                 "INSERT INTO gpkg_spatial_ref_sys "
     946             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     947             :                 "definition) VALUES ('%q', %d, upper('%q'), %d, '%q')",
     948         289 :                 GetSrsName(*poSRS), nSRSId, pszAuthorityName, nAuthorityCode,
     949         578 :                 pszWKT1 ? pszWKT1.get() : "undefined");
     950             :         }
     951             :         else
     952             :         {
     953          30 :             pszSQL = sqlite3_mprintf(
     954             :                 "INSERT INTO gpkg_spatial_ref_sys "
     955             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     956             :                 "definition) VALUES ('%q', %d, upper('%q'), %d, '%q')",
     957          15 :                 GetSrsName(*poSRS), nSRSId, "NONE", nSRSId,
     958          30 :                 pszWKT1 ? pszWKT1.get() : "undefined");
     959             :         }
     960             :     }
     961             : 
     962             :     // Add new row to gpkg_spatial_ref_sys.
     963         349 :     CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
     964             : 
     965             :     // Free everything that was allocated.
     966         349 :     sqlite3_free(pszSQL);
     967             : 
     968         349 :     return nSRSId;
     969             : }
     970             : 
     971             : /************************************************************************/
     972             : /*                       ~GDALGeoPackageDataset()                       */
     973             : /************************************************************************/
     974             : 
     975        5970 : GDALGeoPackageDataset::~GDALGeoPackageDataset()
     976             : {
     977        2985 :     GDALGeoPackageDataset::Close();
     978        5970 : }
     979             : 
     980             : /************************************************************************/
     981             : /*                               Close()                                */
     982             : /************************************************************************/
     983             : 
     984        5009 : CPLErr GDALGeoPackageDataset::Close(GDALProgressFunc, void *)
     985             : {
     986        5009 :     CPLErr eErr = CE_None;
     987        5009 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     988             :     {
     989        1744 :         if (eAccess == GA_Update && m_poParentDS == nullptr &&
     990        4729 :             !m_osRasterTable.empty() && !m_bGeoTransformValid)
     991             :         {
     992           3 :             CPLError(CE_Failure, CPLE_AppDefined,
     993             :                      "Raster table %s not correctly initialized due to missing "
     994             :                      "call to SetGeoTransform()",
     995             :                      m_osRasterTable.c_str());
     996             :         }
     997             : 
     998        5951 :         if (!IsMarkedSuppressOnClose() &&
     999        2966 :             GDALGeoPackageDataset::FlushCache(true) != CE_None)
    1000             :         {
    1001           7 :             eErr = CE_Failure;
    1002             :         }
    1003             : 
    1004             :         // Destroy bands now since we don't want
    1005             :         // GDALGPKGMBTilesLikeRasterBand::FlushCache() to run after dataset
    1006             :         // destruction
    1007        4846 :         for (int i = 0; i < nBands; i++)
    1008        1861 :             delete papoBands[i];
    1009        2985 :         nBands = 0;
    1010        2985 :         CPLFree(papoBands);
    1011        2985 :         papoBands = nullptr;
    1012             : 
    1013             :         // Destroy overviews before cleaning m_hTempDB as they could still
    1014             :         // need it
    1015        2985 :         m_apoOverviewDS.clear();
    1016             : 
    1017        2985 :         if (m_poParentDS)
    1018             :         {
    1019         333 :             hDB = nullptr;
    1020             :         }
    1021             : 
    1022        2985 :         m_apoLayers.clear();
    1023             : 
    1024        2985 :         m_oMapSrsIdToSrs.clear();
    1025             : 
    1026        2985 :         if (!CloseDB())
    1027           0 :             eErr = CE_Failure;
    1028             : 
    1029        2985 :         if (OGRSQLiteBaseDataSource::Close() != CE_None)
    1030           0 :             eErr = CE_Failure;
    1031             :     }
    1032        5009 :     return eErr;
    1033             : }
    1034             : 
    1035             : /************************************************************************/
    1036             : /*                          ICanIWriteBlock()                           */
    1037             : /************************************************************************/
    1038             : 
    1039        5708 : bool GDALGeoPackageDataset::ICanIWriteBlock()
    1040             : {
    1041        5708 :     if (!GetUpdate())
    1042             :     {
    1043           0 :         CPLError(
    1044             :             CE_Failure, CPLE_NotSupported,
    1045             :             "IWriteBlock() not supported on dataset opened in read-only mode");
    1046           0 :         return false;
    1047             :     }
    1048             : 
    1049        5708 :     if (m_pabyCachedTiles == nullptr)
    1050             :     {
    1051           0 :         return false;
    1052             :     }
    1053             : 
    1054        5708 :     if (!m_bGeoTransformValid || m_nSRID == UNKNOWN_SRID)
    1055             :     {
    1056           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    1057             :                  "IWriteBlock() not supported if georeferencing not set");
    1058           0 :         return false;
    1059             :     }
    1060        5708 :     return true;
    1061             : }
    1062             : 
    1063             : /************************************************************************/
    1064             : /*                             IRasterIO()                              */
    1065             : /************************************************************************/
    1066             : 
    1067         141 : CPLErr GDALGeoPackageDataset::IRasterIO(
    1068             :     GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
    1069             :     void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
    1070             :     int nBandCount, BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
    1071             :     GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg)
    1072             : 
    1073             : {
    1074         141 :     CPLErr eErr = OGRSQLiteBaseDataSource::IRasterIO(
    1075             :         eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    1076             :         eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
    1077             :         psExtraArg);
    1078             : 
    1079             :     // If writing all bands, in non-shifted mode, flush all entirely written
    1080             :     // tiles This can avoid "stressing" the block cache with too many dirty
    1081             :     // blocks. Note: this logic would be useless with a per-dataset block cache.
    1082         141 :     if (eErr == CE_None && eRWFlag == GF_Write && nXSize == nBufXSize &&
    1083         130 :         nYSize == nBufYSize && nBandCount == nBands &&
    1084         127 :         m_nShiftXPixelsMod == 0 && m_nShiftYPixelsMod == 0)
    1085             :     {
    1086             :         auto poBand =
    1087         123 :             cpl::down_cast<GDALGPKGMBTilesLikeRasterBand *>(GetRasterBand(1));
    1088             :         int nBlockXSize, nBlockYSize;
    1089         123 :         poBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
    1090         123 :         const int nBlockXStart = DIV_ROUND_UP(nXOff, nBlockXSize);
    1091         123 :         const int nBlockYStart = DIV_ROUND_UP(nYOff, nBlockYSize);
    1092         123 :         const int nBlockXEnd = (nXOff + nXSize) / nBlockXSize;
    1093         123 :         const int nBlockYEnd = (nYOff + nYSize) / nBlockYSize;
    1094         281 :         for (int nBlockY = nBlockXStart; nBlockY < nBlockYEnd; nBlockY++)
    1095             :         {
    1096        4375 :             for (int nBlockX = nBlockYStart; nBlockX < nBlockXEnd; nBlockX++)
    1097             :             {
    1098             :                 GDALRasterBlock *poBlock =
    1099        4217 :                     poBand->AccessibleTryGetLockedBlockRef(nBlockX, nBlockY);
    1100        4217 :                 if (poBlock)
    1101             :                 {
    1102             :                     // GetDirty() should be true in most situation (otherwise
    1103             :                     // it means the block cache is under extreme pressure!)
    1104        4215 :                     if (poBlock->GetDirty())
    1105             :                     {
    1106             :                         // IWriteBlock() on one band will check the dirty state
    1107             :                         // of the corresponding blocks in other bands, to decide
    1108             :                         // if it can call WriteTile(), so we have only to do
    1109             :                         // that on one of the bands
    1110        4215 :                         if (poBlock->Write() != CE_None)
    1111         250 :                             eErr = CE_Failure;
    1112             :                     }
    1113        4215 :                     poBlock->DropLock();
    1114             :                 }
    1115             :             }
    1116             :         }
    1117             :     }
    1118             : 
    1119         141 :     return eErr;
    1120             : }
    1121             : 
    1122             : /************************************************************************/
    1123             : /*                          GetOGRTableLimit()                          */
    1124             : /************************************************************************/
    1125             : 
    1126        5159 : static int GetOGRTableLimit()
    1127             : {
    1128        5159 :     return atoi(CPLGetConfigOption("OGR_TABLE_LIMIT", "10000"));
    1129             : }
    1130             : 
    1131             : /************************************************************************/
    1132             : /*                   GetNameTypeMapFromSQliteMaster()                   */
    1133             : /************************************************************************/
    1134             : 
    1135             : const std::map<CPLString, CPLString> &
    1136        1607 : GDALGeoPackageDataset::GetNameTypeMapFromSQliteMaster()
    1137             : {
    1138        1607 :     if (!m_oMapNameToType.empty())
    1139         439 :         return m_oMapNameToType;
    1140             : 
    1141             :     CPLString osSQL(
    1142             :         "SELECT name, type FROM sqlite_master WHERE "
    1143             :         "type IN ('view', 'table') OR "
    1144        2336 :         "(name LIKE 'trigger_%_feature_count_%' AND type = 'trigger')");
    1145        1168 :     const int nTableLimit = GetOGRTableLimit();
    1146        1168 :     if (nTableLimit > 0)
    1147             :     {
    1148        1168 :         osSQL += " LIMIT ";
    1149        1168 :         osSQL += CPLSPrintf("%d", 1 + 3 * nTableLimit);
    1150             :     }
    1151             : 
    1152        1168 :     auto oResult = SQLQuery(hDB, osSQL);
    1153        1168 :     if (oResult)
    1154             :     {
    1155       19389 :         for (int i = 0; i < oResult->RowCount(); i++)
    1156             :         {
    1157       18221 :             const char *pszName = oResult->GetValue(0, i);
    1158       18221 :             const char *pszType = oResult->GetValue(1, i);
    1159       18221 :             m_oMapNameToType[CPLString(pszName).toupper()] = pszType;
    1160             :         }
    1161             :     }
    1162             : 
    1163        1168 :     return m_oMapNameToType;
    1164             : }
    1165             : 
    1166             : /************************************************************************/
    1167             : /*                  RemoveTableFromSQLiteMasterCache()                  */
    1168             : /************************************************************************/
    1169             : 
    1170          58 : void GDALGeoPackageDataset::RemoveTableFromSQLiteMasterCache(
    1171             :     const char *pszTableName)
    1172             : {
    1173          58 :     m_oMapNameToType.erase(CPLString(pszTableName).toupper());
    1174          58 : }
    1175             : 
    1176             : /************************************************************************/
    1177             : /*                 GetUnknownExtensionsTableSpecific()                  */
    1178             : /************************************************************************/
    1179             : 
    1180             : const std::map<CPLString, std::vector<GPKGExtensionDesc>> &
    1181        1076 : GDALGeoPackageDataset::GetUnknownExtensionsTableSpecific()
    1182             : {
    1183        1076 :     if (m_bMapTableToExtensionsBuilt)
    1184         107 :         return m_oMapTableToExtensions;
    1185         969 :     m_bMapTableToExtensionsBuilt = true;
    1186             : 
    1187         969 :     if (!HasExtensionsTable())
    1188          52 :         return m_oMapTableToExtensions;
    1189             : 
    1190             :     CPLString osSQL(
    1191             :         "SELECT table_name, extension_name, definition, scope "
    1192             :         "FROM gpkg_extensions WHERE "
    1193             :         "table_name IS NOT NULL "
    1194             :         "AND extension_name IS NOT NULL "
    1195             :         "AND definition IS NOT NULL "
    1196             :         "AND scope IS NOT NULL "
    1197             :         "AND extension_name NOT IN ('gpkg_geom_CIRCULARSTRING', "
    1198             :         "'gpkg_geom_COMPOUNDCURVE', 'gpkg_geom_CURVEPOLYGON', "
    1199             :         "'gpkg_geom_MULTICURVE', "
    1200             :         "'gpkg_geom_MULTISURFACE', 'gpkg_geom_CURVE', 'gpkg_geom_SURFACE', "
    1201             :         "'gpkg_geom_POLYHEDRALSURFACE', 'gpkg_geom_TIN', 'gpkg_geom_TRIANGLE', "
    1202             :         "'gpkg_rtree_index', 'gpkg_geometry_type_trigger', "
    1203             :         "'gpkg_srs_id_trigger', "
    1204             :         "'gpkg_crs_wkt', 'gpkg_crs_wkt_1_1', 'gpkg_schema', "
    1205             :         "'gpkg_related_tables', 'related_tables'"
    1206             : #ifdef HAVE_SPATIALITE
    1207             :         ", 'gdal_spatialite_computed_geom_column'"
    1208             : #endif
    1209        1834 :         ")");
    1210         917 :     const int nTableLimit = GetOGRTableLimit();
    1211         917 :     if (nTableLimit > 0)
    1212             :     {
    1213         917 :         osSQL += " LIMIT ";
    1214         917 :         osSQL += CPLSPrintf("%d", 1 + 10 * nTableLimit);
    1215             :     }
    1216             : 
    1217         917 :     auto oResult = SQLQuery(hDB, osSQL);
    1218         917 :     if (oResult)
    1219             :     {
    1220        1739 :         for (int i = 0; i < oResult->RowCount(); i++)
    1221             :         {
    1222         822 :             const char *pszTableName = oResult->GetValue(0, i);
    1223         822 :             const char *pszExtensionName = oResult->GetValue(1, i);
    1224         822 :             const char *pszDefinition = oResult->GetValue(2, i);
    1225         822 :             const char *pszScope = oResult->GetValue(3, i);
    1226         822 :             if (pszTableName && pszExtensionName && pszDefinition && pszScope)
    1227             :             {
    1228         822 :                 GPKGExtensionDesc oDesc;
    1229         822 :                 oDesc.osExtensionName = pszExtensionName;
    1230         822 :                 oDesc.osDefinition = pszDefinition;
    1231         822 :                 oDesc.osScope = pszScope;
    1232        1644 :                 m_oMapTableToExtensions[CPLString(pszTableName).toupper()]
    1233         822 :                     .push_back(std::move(oDesc));
    1234             :             }
    1235             :         }
    1236             :     }
    1237             : 
    1238         917 :     return m_oMapTableToExtensions;
    1239             : }
    1240             : 
    1241             : /************************************************************************/
    1242             : /*                            GetContents()                             */
    1243             : /************************************************************************/
    1244             : 
    1245             : const std::map<CPLString, GPKGContentsDesc> &
    1246        1057 : GDALGeoPackageDataset::GetContents()
    1247             : {
    1248        1057 :     if (m_bMapTableToContentsBuilt)
    1249          90 :         return m_oMapTableToContents;
    1250         967 :     m_bMapTableToContentsBuilt = true;
    1251             : 
    1252             :     CPLString osSQL("SELECT table_name, data_type, identifier, "
    1253             :                     "description, min_x, min_y, max_x, max_y "
    1254        1934 :                     "FROM gpkg_contents");
    1255         967 :     const int nTableLimit = GetOGRTableLimit();
    1256         967 :     if (nTableLimit > 0)
    1257             :     {
    1258         967 :         osSQL += " LIMIT ";
    1259         967 :         osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1260             :     }
    1261             : 
    1262         967 :     auto oResult = SQLQuery(hDB, osSQL);
    1263         967 :     if (oResult)
    1264             :     {
    1265        2081 :         for (int i = 0; i < oResult->RowCount(); i++)
    1266             :         {
    1267        1114 :             const char *pszTableName = oResult->GetValue(0, i);
    1268        1114 :             if (pszTableName == nullptr)
    1269           0 :                 continue;
    1270        1114 :             const char *pszDataType = oResult->GetValue(1, i);
    1271        1114 :             const char *pszIdentifier = oResult->GetValue(2, i);
    1272        1114 :             const char *pszDescription = oResult->GetValue(3, i);
    1273        1114 :             const char *pszMinX = oResult->GetValue(4, i);
    1274        1114 :             const char *pszMinY = oResult->GetValue(5, i);
    1275        1114 :             const char *pszMaxX = oResult->GetValue(6, i);
    1276        1114 :             const char *pszMaxY = oResult->GetValue(7, i);
    1277        1114 :             GPKGContentsDesc oDesc;
    1278        1114 :             if (pszDataType)
    1279        1114 :                 oDesc.osDataType = pszDataType;
    1280        1114 :             if (pszIdentifier)
    1281        1114 :                 oDesc.osIdentifier = pszIdentifier;
    1282        1114 :             if (pszDescription)
    1283        1113 :                 oDesc.osDescription = pszDescription;
    1284        1114 :             if (pszMinX)
    1285         765 :                 oDesc.osMinX = pszMinX;
    1286        1114 :             if (pszMinY)
    1287         765 :                 oDesc.osMinY = pszMinY;
    1288        1114 :             if (pszMaxX)
    1289         765 :                 oDesc.osMaxX = pszMaxX;
    1290        1114 :             if (pszMaxY)
    1291         765 :                 oDesc.osMaxY = pszMaxY;
    1292        2228 :             m_oMapTableToContents[CPLString(pszTableName).toupper()] =
    1293        2228 :                 std::move(oDesc);
    1294             :         }
    1295             :     }
    1296             : 
    1297         967 :     return m_oMapTableToContents;
    1298             : }
    1299             : 
    1300             : /************************************************************************/
    1301             : /*                                Open()                                */
    1302             : /************************************************************************/
    1303             : 
    1304        1491 : int GDALGeoPackageDataset::Open(GDALOpenInfo *poOpenInfo,
    1305             :                                 const std::string &osFilenameInZip)
    1306             : {
    1307        1491 :     m_osFilenameInZip = osFilenameInZip;
    1308        1491 :     CPLAssert(m_apoLayers.empty());
    1309        1491 :     CPLAssert(hDB == nullptr);
    1310             : 
    1311        1491 :     SetDescription(poOpenInfo->pszFilename);
    1312        2982 :     CPLString osFilename(poOpenInfo->pszFilename);
    1313        2982 :     CPLString osSubdatasetTableName;
    1314             :     GByte abyHeaderLetMeHerePlease[100];
    1315        1491 :     const GByte *pabyHeader = poOpenInfo->pabyHeader;
    1316        1491 :     if (STARTS_WITH_CI(poOpenInfo->pszFilename, "GPKG:"))
    1317             :     {
    1318         313 :         char **papszTokens = CSLTokenizeString2(poOpenInfo->pszFilename, ":",
    1319             :                                                 CSLT_HONOURSTRINGS);
    1320         313 :         int nCount = CSLCount(papszTokens);
    1321         313 :         if (nCount < 2)
    1322             :         {
    1323           0 :             CSLDestroy(papszTokens);
    1324           0 :             return FALSE;
    1325             :         }
    1326             : 
    1327         313 :         if (nCount <= 3)
    1328             :         {
    1329         311 :             osFilename = papszTokens[1];
    1330             :         }
    1331             :         /* GPKG:C:\BLA.GPKG:foo */
    1332           2 :         else if (nCount == 4 && strlen(papszTokens[1]) == 1 &&
    1333           2 :                  (papszTokens[2][0] == '/' || papszTokens[2][0] == '\\'))
    1334             :         {
    1335           2 :             osFilename = CPLString(papszTokens[1]) + ":" + papszTokens[2];
    1336             :         }
    1337             :         // GPKG:/vsicurl/http[s]://[user:passwd@]example.com[:8080]/foo.gpkg:bar
    1338           0 :         else if (/*nCount >= 4 && */
    1339           0 :                  (EQUAL(papszTokens[1], "/vsicurl/http") ||
    1340           0 :                   EQUAL(papszTokens[1], "/vsicurl/https")))
    1341             :         {
    1342           0 :             osFilename = CPLString(papszTokens[1]);
    1343           0 :             for (int i = 2; i < nCount - 1; i++)
    1344             :             {
    1345           0 :                 osFilename += ':';
    1346           0 :                 osFilename += papszTokens[i];
    1347             :             }
    1348             :         }
    1349         313 :         if (nCount >= 3)
    1350          14 :             osSubdatasetTableName = papszTokens[nCount - 1];
    1351             : 
    1352         313 :         CSLDestroy(papszTokens);
    1353         313 :         VSILFILE *fp = VSIFOpenL(osFilename, "rb");
    1354         313 :         if (fp != nullptr)
    1355             :         {
    1356         313 :             VSIFReadL(abyHeaderLetMeHerePlease, 1, 100, fp);
    1357         313 :             VSIFCloseL(fp);
    1358             :         }
    1359         313 :         pabyHeader = abyHeaderLetMeHerePlease;
    1360             :     }
    1361        1178 :     else if (poOpenInfo->pabyHeader &&
    1362        1178 :              STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1363             :                          "SQLite format 3"))
    1364             :     {
    1365        1171 :         m_bCallUndeclareFileNotToOpen = true;
    1366        1171 :         GDALOpenInfoDeclareFileNotToOpen(osFilename, poOpenInfo->pabyHeader,
    1367             :                                          poOpenInfo->nHeaderBytes);
    1368             :     }
    1369             : 
    1370        1491 :     eAccess = poOpenInfo->eAccess;
    1371        1491 :     if (!m_osFilenameInZip.empty())
    1372             :     {
    1373           2 :         m_pszFilename = CPLStrdup(CPLSPrintf(
    1374             :             "/vsizip/{%s}/%s", osFilename.c_str(), m_osFilenameInZip.c_str()));
    1375             :     }
    1376             :     else
    1377             :     {
    1378        1489 :         m_pszFilename = CPLStrdup(osFilename);
    1379             :     }
    1380             : 
    1381        1491 :     if (poOpenInfo->papszOpenOptions)
    1382             :     {
    1383         100 :         CSLDestroy(papszOpenOptions);
    1384         100 :         papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
    1385             :     }
    1386             : 
    1387             : #ifdef ENABLE_SQL_GPKG_FORMAT
    1388        1491 :     if (poOpenInfo->pabyHeader &&
    1389        1178 :         STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1390           5 :                     "-- SQL GPKG") &&
    1391           5 :         poOpenInfo->fpL != nullptr)
    1392             :     {
    1393           5 :         if (sqlite3_open_v2(":memory:", &hDB, SQLITE_OPEN_READWRITE, nullptr) !=
    1394             :             SQLITE_OK)
    1395             :         {
    1396           0 :             return FALSE;
    1397             :         }
    1398             : 
    1399           5 :         InstallSQLFunctions();
    1400             : 
    1401             :         // Ingest the lines of the dump
    1402           5 :         VSIFSeekL(poOpenInfo->fpL, 0, SEEK_SET);
    1403             :         const char *pszLine;
    1404          76 :         while ((pszLine = CPLReadLineL(poOpenInfo->fpL)) != nullptr)
    1405             :         {
    1406          71 :             if (STARTS_WITH(pszLine, "--"))
    1407           5 :                 continue;
    1408             : 
    1409          66 :             if (!SQLCheckLineIsSafe(pszLine))
    1410           0 :                 return false;
    1411             : 
    1412          66 :             char *pszErrMsg = nullptr;
    1413          66 :             if (sqlite3_exec(hDB, pszLine, nullptr, nullptr, &pszErrMsg) !=
    1414             :                 SQLITE_OK)
    1415             :             {
    1416           0 :                 if (pszErrMsg)
    1417           0 :                     CPLDebug("SQLITE", "Error %s", pszErrMsg);
    1418             :             }
    1419          66 :             sqlite3_free(pszErrMsg);
    1420           5 :         }
    1421             :     }
    1422             : 
    1423        1486 :     else if (pabyHeader != nullptr)
    1424             : #endif
    1425             :     {
    1426        1486 :         if (poOpenInfo->fpL)
    1427             :         {
    1428             :             // See above comment about -wal locking for the importance of
    1429             :             // closing that file, prior to calling sqlite3_open()
    1430        1051 :             VSIFCloseL(poOpenInfo->fpL);
    1431        1051 :             poOpenInfo->fpL = nullptr;
    1432             :         }
    1433             : 
    1434             :         /* See if we can open the SQLite database */
    1435        1486 :         if (!OpenOrCreateDB(GetUpdate() ? SQLITE_OPEN_READWRITE
    1436             :                                         : SQLITE_OPEN_READONLY))
    1437           3 :             return FALSE;
    1438             : 
    1439        1483 :         memcpy(&m_nApplicationId, pabyHeader + knApplicationIdPos, 4);
    1440        1483 :         m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    1441        1483 :         memcpy(&m_nUserVersion, pabyHeader + knUserVersionPos, 4);
    1442        1483 :         m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    1443        1483 :         if (m_nApplicationId == GP10_APPLICATION_ID)
    1444             :         {
    1445          12 :             CPLDebug("GPKG", "GeoPackage v1.0");
    1446             :         }
    1447        1471 :         else if (m_nApplicationId == GP11_APPLICATION_ID)
    1448             :         {
    1449           2 :             CPLDebug("GPKG", "GeoPackage v1.1");
    1450             :         }
    1451        1469 :         else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    1452        1465 :                  m_nUserVersion >= GPKG_1_2_VERSION)
    1453             :         {
    1454        1463 :             CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    1455        1463 :                      (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    1456             :         }
    1457             :     }
    1458             : 
    1459             :     /* Requirement 6: The SQLite PRAGMA integrity_check SQL command SHALL return
    1460             :      * “ok” */
    1461             :     /* http://opengis.github.io/geopackage/#_file_integrity */
    1462             :     /* Disable integrity check by default, since it is expensive on big files */
    1463        1488 :     if (CPLTestBool(CPLGetConfigOption("OGR_GPKG_INTEGRITY_CHECK", "NO")) &&
    1464           0 :         OGRERR_NONE != PragmaCheck("integrity_check", "ok", 1))
    1465             :     {
    1466           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1467             :                  "pragma integrity_check on '%s' failed", m_pszFilename);
    1468           0 :         return FALSE;
    1469             :     }
    1470             : 
    1471             :     /* Requirement 7: The SQLite PRAGMA foreign_key_check() SQL with no */
    1472             :     /* parameter value SHALL return an empty result set */
    1473             :     /* http://opengis.github.io/geopackage/#_file_integrity */
    1474             :     /* Disable the check by default, since it is to corrupt databases, and */
    1475             :     /* that causes issues to downstream software that can't open them. */
    1476        1488 :     if (CPLTestBool(CPLGetConfigOption("OGR_GPKG_FOREIGN_KEY_CHECK", "NO")) &&
    1477           0 :         OGRERR_NONE != PragmaCheck("foreign_key_check", "", 0))
    1478             :     {
    1479           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1480             :                  "pragma foreign_key_check on '%s' failed.", m_pszFilename);
    1481           0 :         return FALSE;
    1482             :     }
    1483             : 
    1484             :     /* Check for requirement metadata tables */
    1485             :     /* Requirement 10: gpkg_spatial_ref_sys must exist */
    1486             :     /* Requirement 13: gpkg_contents must exist */
    1487        1488 :     if (SQLGetInteger(hDB,
    1488             :                       "SELECT COUNT(*) FROM sqlite_master WHERE "
    1489             :                       "name IN ('gpkg_spatial_ref_sys', 'gpkg_contents') AND "
    1490             :                       "type IN ('table', 'view')",
    1491        1488 :                       nullptr) != 2)
    1492             :     {
    1493           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1494             :                  "At least one of the required GeoPackage tables, "
    1495             :                  "gpkg_spatial_ref_sys or gpkg_contents, is missing");
    1496           0 :         return FALSE;
    1497             :     }
    1498             : 
    1499        1488 :     DetectSpatialRefSysColumns();
    1500             : 
    1501             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    1502        1488 :     if (SQLGetInteger(hDB,
    1503             :                       "SELECT 1 FROM sqlite_master WHERE "
    1504             :                       "name = 'gpkg_ogr_contents' AND type = 'table'",
    1505        1488 :                       nullptr) == 1)
    1506             :     {
    1507        1477 :         m_bHasGPKGOGRContents = true;
    1508             :     }
    1509             : #endif
    1510             : 
    1511        1488 :     CheckUnknownExtensions();
    1512             : 
    1513        1488 :     int bRet = FALSE;
    1514        1488 :     bool bHasGPKGExtRelations = false;
    1515        1488 :     if (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR)
    1516             :     {
    1517        1436 :         m_bHasGPKGGeometryColumns =
    1518        1436 :             SQLGetInteger(hDB,
    1519             :                           "SELECT 1 FROM sqlite_master WHERE "
    1520             :                           "name = 'gpkg_geometry_columns' AND "
    1521             :                           "type IN ('table', 'view')",
    1522        1436 :                           nullptr) == 1;
    1523        1436 :         bHasGPKGExtRelations = HasGpkgextRelationsTable();
    1524             :     }
    1525        1488 :     if (m_bHasGPKGGeometryColumns)
    1526             :     {
    1527             :         /* Load layer definitions for all tables in gpkg_contents &
    1528             :          * gpkg_geometry_columns */
    1529             :         /* and non-spatial tables as well */
    1530             :         std::string osSQL =
    1531             :             "SELECT c.table_name, c.identifier, 1 as is_spatial, "
    1532             :             "g.column_name, g.geometry_type_name, g.z, g.m, c.min_x, c.min_y, "
    1533             :             "c.max_x, c.max_y, 1 AS is_in_gpkg_contents, "
    1534             :             "(SELECT type FROM sqlite_master WHERE lower(name) = "
    1535             :             "lower(c.table_name) AND type IN ('table', 'view')) AS object_type "
    1536             :             "  FROM gpkg_geometry_columns g "
    1537             :             "  JOIN gpkg_contents c ON (g.table_name = c.table_name)"
    1538             :             "  WHERE "
    1539             :             "  c.table_name <> 'ogr_empty_table' AND"
    1540             :             "  c.data_type = 'features' "
    1541             :             // aspatial: Was the only method available in OGR 2.0 and 2.1
    1542             :             // attributes: GPKG 1.2 or later
    1543             :             "UNION ALL "
    1544             :             "SELECT table_name, identifier, 0 as is_spatial, NULL, NULL, 0, 0, "
    1545             :             "0 AS xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 1 AS "
    1546             :             "is_in_gpkg_contents, "
    1547             :             "(SELECT type FROM sqlite_master WHERE lower(name) = "
    1548             :             "lower(table_name) AND type IN ('table', 'view')) AS object_type "
    1549             :             "  FROM gpkg_contents"
    1550        1432 :             "  WHERE data_type IN ('aspatial', 'attributes') ";
    1551             : 
    1552        2864 :         const char *pszListAllTables = CSLFetchNameValueDef(
    1553        1432 :             poOpenInfo->papszOpenOptions, "LIST_ALL_TABLES", "AUTO");
    1554        1432 :         bool bHasASpatialOrAttributes = HasGDALAspatialExtension();
    1555        1432 :         if (!bHasASpatialOrAttributes)
    1556             :         {
    1557             :             auto oResultTable =
    1558             :                 SQLQuery(hDB, "SELECT * FROM gpkg_contents WHERE "
    1559        1431 :                               "data_type = 'attributes' LIMIT 1");
    1560        1431 :             bHasASpatialOrAttributes =
    1561        1431 :                 (oResultTable && oResultTable->RowCount() == 1);
    1562             :         }
    1563        1432 :         if (bHasGPKGExtRelations)
    1564             :         {
    1565             :             osSQL += "UNION ALL "
    1566             :                      "SELECT mapping_table_name, mapping_table_name, 0 as "
    1567             :                      "is_spatial, NULL, NULL, 0, 0, 0 AS "
    1568             :                      "xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 0 AS "
    1569             :                      "is_in_gpkg_contents, 'table' AS object_type "
    1570             :                      "FROM gpkgext_relations WHERE "
    1571             :                      "lower(mapping_table_name) NOT IN (SELECT "
    1572             :                      "lower(table_name) FROM gpkg_contents) AND "
    1573             :                      "EXISTS (SELECT 1 FROM sqlite_master WHERE "
    1574             :                      "type IN ('table', 'view') AND "
    1575          20 :                      "lower(name) = lower(mapping_table_name))";
    1576             :         }
    1577        1432 :         if (EQUAL(pszListAllTables, "YES") ||
    1578        1431 :             (!bHasASpatialOrAttributes && EQUAL(pszListAllTables, "AUTO")))
    1579             :         {
    1580             :             // vgpkg_ is Spatialite virtual table
    1581             :             osSQL +=
    1582             :                 "UNION ALL "
    1583             :                 "SELECT name, name, 0 as is_spatial, NULL, NULL, 0, 0, 0 AS "
    1584             :                 "xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 0 AS "
    1585             :                 "is_in_gpkg_contents, type AS object_type "
    1586             :                 "FROM sqlite_master WHERE type IN ('table', 'view') "
    1587             :                 "AND name NOT LIKE 'gpkg_%' "
    1588             :                 "AND name NOT LIKE 'vgpkg_%' "
    1589             :                 "AND name NOT LIKE 'rtree_%' AND name NOT LIKE 'sqlite_%' "
    1590             :                 // Avoid reading those views from simple_sewer_features.gpkg
    1591             :                 "AND name NOT IN ('st_spatial_ref_sys', 'spatial_ref_sys', "
    1592             :                 "'st_geometry_columns', 'geometry_columns') "
    1593             :                 "AND lower(name) NOT IN (SELECT lower(table_name) FROM "
    1594        1362 :                 "gpkg_contents)";
    1595        1362 :             if (bHasGPKGExtRelations)
    1596             :             {
    1597             :                 osSQL += " AND lower(name) NOT IN (SELECT "
    1598             :                          "lower(mapping_table_name) FROM "
    1599          15 :                          "gpkgext_relations)";
    1600             :             }
    1601             :         }
    1602        1432 :         const int nTableLimit = GetOGRTableLimit();
    1603        1432 :         if (nTableLimit > 0)
    1604             :         {
    1605        1432 :             osSQL += " LIMIT ";
    1606        1432 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1607             :         }
    1608             : 
    1609        1432 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1610        1432 :         if (!oResult)
    1611             :         {
    1612           0 :             return FALSE;
    1613             :         }
    1614             : 
    1615        1432 :         if (nTableLimit > 0 && oResult->RowCount() > nTableLimit)
    1616             :         {
    1617           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    1618             :                      "File has more than %d vector tables. "
    1619             :                      "Limiting to first %d (can be overridden with "
    1620             :                      "OGR_TABLE_LIMIT config option)",
    1621             :                      nTableLimit, nTableLimit);
    1622           1 :             oResult->LimitRowCount(nTableLimit);
    1623             :         }
    1624             : 
    1625        1432 :         if (oResult->RowCount() > 0)
    1626             :         {
    1627        1173 :             bRet = TRUE;
    1628             : 
    1629        1173 :             m_apoLayers.reserve(oResult->RowCount());
    1630             : 
    1631        2346 :             std::map<std::string, int> oMapTableRefCount;
    1632        4574 :             for (int i = 0; i < oResult->RowCount(); i++)
    1633             :             {
    1634        3401 :                 const char *pszTableName = oResult->GetValue(0, i);
    1635        3401 :                 if (pszTableName == nullptr)
    1636           0 :                     continue;
    1637        3401 :                 if (++oMapTableRefCount[pszTableName] == 2)
    1638             :                 {
    1639             :                     // This should normally not happen if all constraints are
    1640             :                     // properly set
    1641           2 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1642             :                              "Table %s appearing several times in "
    1643             :                              "gpkg_contents and/or gpkg_geometry_columns",
    1644             :                              pszTableName);
    1645             :                 }
    1646             :             }
    1647             : 
    1648        2346 :             std::set<std::string> oExistingLayers;
    1649        4574 :             for (int i = 0; i < oResult->RowCount(); i++)
    1650             :             {
    1651        3401 :                 const char *pszTableName = oResult->GetValue(0, i);
    1652        3401 :                 if (pszTableName == nullptr)
    1653           2 :                     continue;
    1654             :                 const bool bTableHasSeveralGeomColumns =
    1655        3401 :                     oMapTableRefCount[pszTableName] > 1;
    1656        3401 :                 bool bIsSpatial = CPL_TO_BOOL(oResult->GetValueAsInteger(2, i));
    1657        3401 :                 const char *pszGeomColName = oResult->GetValue(3, i);
    1658        3401 :                 const char *pszGeomType = oResult->GetValue(4, i);
    1659        3401 :                 const char *pszZ = oResult->GetValue(5, i);
    1660        3401 :                 const char *pszM = oResult->GetValue(6, i);
    1661             :                 bool bIsInGpkgContents =
    1662        3401 :                     CPL_TO_BOOL(oResult->GetValueAsInteger(11, i));
    1663        3401 :                 if (!bIsInGpkgContents)
    1664          46 :                     m_bNonSpatialTablesNonRegisteredInGpkgContentsFound = true;
    1665        3401 :                 const char *pszObjectType = oResult->GetValue(12, i);
    1666        3401 :                 if (pszObjectType == nullptr ||
    1667        3400 :                     !(EQUAL(pszObjectType, "table") ||
    1668          21 :                       EQUAL(pszObjectType, "view")))
    1669             :                 {
    1670           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1671             :                              "Table/view %s is referenced in gpkg_contents, "
    1672             :                              "but does not exist",
    1673             :                              pszTableName);
    1674           1 :                     continue;
    1675             :                 }
    1676             :                 // Non-standard and undocumented behavior:
    1677             :                 // if the same table appears to have several geometry columns,
    1678             :                 // handle it for now as multiple layers named
    1679             :                 // "table_name (geom_col_name)"
    1680             :                 // The way we handle that might change in the future (e.g
    1681             :                 // could be a single layer with multiple geometry columns)
    1682             :                 std::string osLayerNameWithGeomColName =
    1683        7240 :                     pszGeomColName ? std::string(pszTableName) + " (" +
    1684             :                                          pszGeomColName + ')'
    1685        6800 :                                    : std::string(pszTableName);
    1686        3400 :                 if (cpl::contains(oExistingLayers, osLayerNameWithGeomColName))
    1687           1 :                     continue;
    1688        3399 :                 oExistingLayers.insert(osLayerNameWithGeomColName);
    1689             :                 const std::string osLayerName =
    1690             :                     bTableHasSeveralGeomColumns
    1691           3 :                         ? std::move(osLayerNameWithGeomColName)
    1692        6801 :                         : std::string(pszTableName);
    1693             :                 auto poLayer = std::make_unique<OGRGeoPackageTableLayer>(
    1694        6798 :                     this, osLayerName.c_str());
    1695        3399 :                 bool bHasZ = pszZ && atoi(pszZ) > 0;
    1696        3399 :                 bool bHasM = pszM && atoi(pszM) > 0;
    1697        3399 :                 if (pszGeomType && EQUAL(pszGeomType, "GEOMETRY"))
    1698             :                 {
    1699         731 :                     if (pszZ && atoi(pszZ) == 2)
    1700          14 :                         bHasZ = false;
    1701         731 :                     if (pszM && atoi(pszM) == 2)
    1702           6 :                         bHasM = false;
    1703             :                 }
    1704        3399 :                 poLayer->SetOpeningParameters(
    1705             :                     pszTableName, pszObjectType, bIsInGpkgContents, bIsSpatial,
    1706             :                     pszGeomColName, pszGeomType, bHasZ, bHasM);
    1707        3399 :                 m_apoLayers.push_back(std::move(poLayer));
    1708             :             }
    1709             :         }
    1710             :     }
    1711             : 
    1712        1488 :     bool bHasTileMatrixSet = false;
    1713        1488 :     if (poOpenInfo->nOpenFlags & GDAL_OF_RASTER)
    1714             :     {
    1715         678 :         bHasTileMatrixSet = SQLGetInteger(hDB,
    1716             :                                           "SELECT 1 FROM sqlite_master WHERE "
    1717             :                                           "name = 'gpkg_tile_matrix_set' AND "
    1718             :                                           "type IN ('table', 'view')",
    1719             :                                           nullptr) == 1;
    1720             :     }
    1721        1488 :     if (bHasTileMatrixSet)
    1722             :     {
    1723             :         std::string osSQL =
    1724             :             "SELECT c.table_name, c.identifier, c.description, c.srs_id, "
    1725             :             "c.min_x, c.min_y, c.max_x, c.max_y, "
    1726             :             "tms.min_x, tms.min_y, tms.max_x, tms.max_y, c.data_type "
    1727             :             "FROM gpkg_contents c JOIN gpkg_tile_matrix_set tms ON "
    1728             :             "c.table_name = tms.table_name WHERE "
    1729         675 :             "data_type IN ('tiles', '2d-gridded-coverage')";
    1730         675 :         if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE"))
    1731             :             osSubdatasetTableName =
    1732           2 :                 CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE");
    1733         675 :         if (!osSubdatasetTableName.empty())
    1734             :         {
    1735          16 :             char *pszTmp = sqlite3_mprintf(" AND c.table_name='%q'",
    1736             :                                            osSubdatasetTableName.c_str());
    1737          16 :             osSQL += pszTmp;
    1738          16 :             sqlite3_free(pszTmp);
    1739          16 :             SetPhysicalFilename(osFilename.c_str());
    1740             :         }
    1741         675 :         const int nTableLimit = GetOGRTableLimit();
    1742         675 :         if (nTableLimit > 0)
    1743             :         {
    1744         675 :             osSQL += " LIMIT ";
    1745         675 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1746             :         }
    1747             : 
    1748         675 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1749         675 :         if (!oResult)
    1750             :         {
    1751           0 :             return FALSE;
    1752             :         }
    1753             : 
    1754         675 :         if (oResult->RowCount() == 0 && !osSubdatasetTableName.empty())
    1755             :         {
    1756           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1757             :                      "Cannot find table '%s' in GeoPackage dataset",
    1758             :                      osSubdatasetTableName.c_str());
    1759             :         }
    1760         674 :         else if (oResult->RowCount() == 1)
    1761             :         {
    1762         288 :             const char *pszTableName = oResult->GetValue(0, 0);
    1763         288 :             const char *pszIdentifier = oResult->GetValue(1, 0);
    1764         288 :             const char *pszDescription = oResult->GetValue(2, 0);
    1765         288 :             const char *pszSRSId = oResult->GetValue(3, 0);
    1766         288 :             const char *pszMinX = oResult->GetValue(4, 0);
    1767         288 :             const char *pszMinY = oResult->GetValue(5, 0);
    1768         288 :             const char *pszMaxX = oResult->GetValue(6, 0);
    1769         288 :             const char *pszMaxY = oResult->GetValue(7, 0);
    1770         288 :             const char *pszTMSMinX = oResult->GetValue(8, 0);
    1771         288 :             const char *pszTMSMinY = oResult->GetValue(9, 0);
    1772         288 :             const char *pszTMSMaxX = oResult->GetValue(10, 0);
    1773         288 :             const char *pszTMSMaxY = oResult->GetValue(11, 0);
    1774         288 :             const char *pszDataType = oResult->GetValue(12, 0);
    1775         288 :             if (pszTableName && pszTMSMinX && pszTMSMinY && pszTMSMaxX &&
    1776             :                 pszTMSMaxY)
    1777             :             {
    1778         576 :                 bRet = OpenRaster(
    1779             :                     pszTableName, pszIdentifier, pszDescription,
    1780         288 :                     pszSRSId ? atoi(pszSRSId) : 0, CPLAtof(pszTMSMinX),
    1781             :                     CPLAtof(pszTMSMinY), CPLAtof(pszTMSMaxX),
    1782             :                     CPLAtof(pszTMSMaxY), pszMinX, pszMinY, pszMaxX, pszMaxY,
    1783         288 :                     EQUAL(pszDataType, "tiles"), poOpenInfo->papszOpenOptions);
    1784             :             }
    1785             :         }
    1786         386 :         else if (oResult->RowCount() >= 1)
    1787             :         {
    1788           5 :             bRet = TRUE;
    1789             : 
    1790           5 :             if (nTableLimit > 0 && oResult->RowCount() > nTableLimit)
    1791             :             {
    1792           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1793             :                          "File has more than %d raster tables. "
    1794             :                          "Limiting to first %d (can be overridden with "
    1795             :                          "OGR_TABLE_LIMIT config option)",
    1796             :                          nTableLimit, nTableLimit);
    1797           1 :                 oResult->LimitRowCount(nTableLimit);
    1798             :             }
    1799             : 
    1800           5 :             int nSDSCount = 0;
    1801        2013 :             for (int i = 0; i < oResult->RowCount(); i++)
    1802             :             {
    1803        2008 :                 const char *pszTableName = oResult->GetValue(0, i);
    1804        2008 :                 const char *pszIdentifier = oResult->GetValue(1, i);
    1805        2008 :                 if (pszTableName == nullptr)
    1806           0 :                     continue;
    1807             :                 m_aosSubDatasets.AddNameValue(
    1808             :                     CPLSPrintf("SUBDATASET_%d_NAME", nSDSCount + 1),
    1809        2008 :                     CPLSPrintf("GPKG:%s:%s", m_pszFilename, pszTableName));
    1810             :                 m_aosSubDatasets.AddNameValue(
    1811             :                     CPLSPrintf("SUBDATASET_%d_DESC", nSDSCount + 1),
    1812             :                     pszIdentifier
    1813        2008 :                         ? CPLSPrintf("%s - %s", pszTableName, pszIdentifier)
    1814        4016 :                         : pszTableName);
    1815        2008 :                 nSDSCount++;
    1816             :             }
    1817             :         }
    1818             :     }
    1819             : 
    1820        1488 :     if (!bRet && (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR))
    1821             :     {
    1822          36 :         if ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE))
    1823             :         {
    1824          23 :             bRet = TRUE;
    1825             :         }
    1826             :         else
    1827             :         {
    1828          13 :             CPLDebug("GPKG",
    1829             :                      "This GeoPackage has no vector content and is opened "
    1830             :                      "in read-only mode. If you open it in update mode, "
    1831             :                      "opening will be successful.");
    1832             :         }
    1833             :     }
    1834             : 
    1835        1488 :     if (eAccess == GA_Update)
    1836             :     {
    1837         291 :         FixupWrongRTreeTrigger();
    1838         291 :         FixupWrongMedataReferenceColumnNameUpdate();
    1839             :     }
    1840             : 
    1841        1488 :     SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    1842             : 
    1843        1488 :     return bRet;
    1844             : }
    1845             : 
    1846             : /************************************************************************/
    1847             : /*                     DetectSpatialRefSysColumns()                     */
    1848             : /************************************************************************/
    1849             : 
    1850        1498 : void GDALGeoPackageDataset::DetectSpatialRefSysColumns()
    1851             : {
    1852             :     // Detect definition_12_063 column
    1853             :     {
    1854        1498 :         sqlite3_stmt *hSQLStmt = nullptr;
    1855        1498 :         int rc = sqlite3_prepare_v2(
    1856             :             hDB, "SELECT definition_12_063 FROM gpkg_spatial_ref_sys ", -1,
    1857             :             &hSQLStmt, nullptr);
    1858        1498 :         if (rc == SQLITE_OK)
    1859             :         {
    1860          85 :             m_bHasDefinition12_063 = true;
    1861          85 :             sqlite3_finalize(hSQLStmt);
    1862             :         }
    1863             :     }
    1864             : 
    1865             :     // Detect epoch column
    1866        1498 :     if (m_bHasDefinition12_063)
    1867             :     {
    1868          85 :         sqlite3_stmt *hSQLStmt = nullptr;
    1869             :         int rc =
    1870          85 :             sqlite3_prepare_v2(hDB, "SELECT epoch FROM gpkg_spatial_ref_sys ",
    1871             :                                -1, &hSQLStmt, nullptr);
    1872          85 :         if (rc == SQLITE_OK)
    1873             :         {
    1874          76 :             m_bHasEpochColumn = true;
    1875          76 :             sqlite3_finalize(hSQLStmt);
    1876             :         }
    1877             :     }
    1878        1498 : }
    1879             : 
    1880             : /************************************************************************/
    1881             : /*                       FixupWrongRTreeTrigger()                       */
    1882             : /************************************************************************/
    1883             : 
    1884         291 : void GDALGeoPackageDataset::FixupWrongRTreeTrigger()
    1885             : {
    1886             :     auto oResult = SQLQuery(
    1887             :         hDB,
    1888             :         "SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND "
    1889         291 :         "NAME LIKE 'rtree_%_update3' AND sql LIKE '% AFTER UPDATE OF % ON %'");
    1890         291 :     if (oResult == nullptr)
    1891           0 :         return;
    1892         291 :     if (oResult->RowCount() > 0)
    1893             :     {
    1894           1 :         CPLDebug("GPKG", "Fixing incorrect trigger(s) related to RTree");
    1895             :     }
    1896         293 :     for (int i = 0; i < oResult->RowCount(); i++)
    1897             :     {
    1898           2 :         const char *pszName = oResult->GetValue(0, i);
    1899           2 :         const char *pszSQL = oResult->GetValue(1, i);
    1900           2 :         const char *pszPtr1 = strstr(pszSQL, " AFTER UPDATE OF ");
    1901           2 :         if (pszPtr1)
    1902             :         {
    1903           2 :             const char *pszPtr = pszPtr1 + strlen(" AFTER UPDATE OF ");
    1904             :             // Skipping over geometry column name
    1905           4 :             while (*pszPtr == ' ')
    1906           2 :                 pszPtr++;
    1907           2 :             if (pszPtr[0] == '"' || pszPtr[0] == '\'')
    1908             :             {
    1909           1 :                 char chStringDelim = pszPtr[0];
    1910           1 :                 pszPtr++;
    1911           5 :                 while (*pszPtr != '\0' && *pszPtr != chStringDelim)
    1912             :                 {
    1913           4 :                     if (*pszPtr == '\\' && pszPtr[1] == chStringDelim)
    1914           0 :                         pszPtr += 2;
    1915             :                     else
    1916           4 :                         pszPtr += 1;
    1917             :                 }
    1918           1 :                 if (*pszPtr == chStringDelim)
    1919           1 :                     pszPtr++;
    1920             :             }
    1921             :             else
    1922             :             {
    1923           1 :                 pszPtr++;
    1924           4 :                 while (*pszPtr != ' ')
    1925           3 :                     pszPtr++;
    1926             :             }
    1927           2 :             if (*pszPtr == ' ')
    1928             :             {
    1929           2 :                 SQLCommand(hDB,
    1930           4 :                            ("DROP TRIGGER \"" + SQLEscapeName(pszName) + "\"")
    1931             :                                .c_str());
    1932           4 :                 CPLString newSQL;
    1933           2 :                 newSQL.assign(pszSQL, pszPtr1 - pszSQL);
    1934           2 :                 newSQL += " AFTER UPDATE";
    1935           2 :                 newSQL += pszPtr;
    1936           2 :                 SQLCommand(hDB, newSQL);
    1937             :             }
    1938             :         }
    1939             :     }
    1940             : }
    1941             : 
    1942             : /************************************************************************/
    1943             : /*             FixupWrongMedataReferenceColumnNameUpdate()              */
    1944             : /************************************************************************/
    1945             : 
    1946         291 : void GDALGeoPackageDataset::FixupWrongMedataReferenceColumnNameUpdate()
    1947             : {
    1948             :     // Fix wrong trigger that was generated by GDAL < 2.4.0
    1949             :     // See https://github.com/qgis/QGIS/issues/42768
    1950             :     auto oResult = SQLQuery(
    1951             :         hDB, "SELECT sql FROM sqlite_master WHERE type = 'trigger' AND "
    1952             :              "NAME ='gpkg_metadata_reference_column_name_update' AND "
    1953         291 :              "sql LIKE '%column_nameIS%'");
    1954         291 :     if (oResult == nullptr)
    1955           0 :         return;
    1956         291 :     if (oResult->RowCount() == 1)
    1957             :     {
    1958           1 :         CPLDebug("GPKG", "Fixing incorrect trigger "
    1959             :                          "gpkg_metadata_reference_column_name_update");
    1960           1 :         const char *pszSQL = oResult->GetValue(0, 0);
    1961             :         std::string osNewSQL(
    1962           3 :             CPLString(pszSQL).replaceAll("column_nameIS", "column_name IS"));
    1963             : 
    1964           1 :         SQLCommand(hDB,
    1965             :                    "DROP TRIGGER gpkg_metadata_reference_column_name_update");
    1966           1 :         SQLCommand(hDB, osNewSQL.c_str());
    1967             :     }
    1968             : }
    1969             : 
    1970             : /************************************************************************/
    1971             : /*                      ClearCachedRelationships()                      */
    1972             : /************************************************************************/
    1973             : 
    1974          38 : void GDALGeoPackageDataset::ClearCachedRelationships()
    1975             : {
    1976          38 :     m_bHasPopulatedRelationships = false;
    1977          38 :     m_osMapRelationships.clear();
    1978          38 : }
    1979             : 
    1980             : /************************************************************************/
    1981             : /*                         LoadRelationships()                          */
    1982             : /************************************************************************/
    1983             : 
    1984         106 : void GDALGeoPackageDataset::LoadRelationships() const
    1985             : {
    1986         106 :     m_osMapRelationships.clear();
    1987             : 
    1988         106 :     std::vector<std::string> oExcludedTables;
    1989         106 :     if (HasGpkgextRelationsTable())
    1990             :     {
    1991          41 :         LoadRelationshipsUsingRelatedTablesExtension();
    1992             : 
    1993          98 :         for (const auto &oRelationship : m_osMapRelationships)
    1994             :         {
    1995             :             oExcludedTables.emplace_back(
    1996          57 :                 oRelationship.second->GetMappingTableName());
    1997             :         }
    1998             :     }
    1999             : 
    2000             :     // Also load relationships defined using foreign keys (i.e. one-to-many
    2001             :     // relationships). Here we must exclude any relationships defined from the
    2002             :     // related tables extension, we don't want them included twice.
    2003         106 :     LoadRelationshipsFromForeignKeys(oExcludedTables);
    2004         106 :     m_bHasPopulatedRelationships = true;
    2005         106 : }
    2006             : 
    2007             : /************************************************************************/
    2008             : /*            LoadRelationshipsUsingRelatedTablesExtension()            */
    2009             : /************************************************************************/
    2010             : 
    2011          41 : void GDALGeoPackageDataset::LoadRelationshipsUsingRelatedTablesExtension() const
    2012             : {
    2013          41 :     m_osMapRelationships.clear();
    2014             : 
    2015             :     auto oResultTable = SQLQuery(
    2016          41 :         hDB, "SELECT base_table_name, base_primary_column, "
    2017             :              "related_table_name, related_primary_column, relation_name, "
    2018          82 :              "mapping_table_name FROM gpkgext_relations");
    2019          41 :     if (oResultTable && oResultTable->RowCount() > 0)
    2020             :     {
    2021          95 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    2022             :         {
    2023          58 :             const char *pszBaseTableName = oResultTable->GetValue(0, i);
    2024          58 :             if (!pszBaseTableName)
    2025             :             {
    2026           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2027             :                          "Could not retrieve base_table_name from "
    2028             :                          "gpkgext_relations");
    2029           1 :                 continue;
    2030             :             }
    2031          58 :             const char *pszBasePrimaryColumn = oResultTable->GetValue(1, i);
    2032          58 :             if (!pszBasePrimaryColumn)
    2033             :             {
    2034           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2035             :                          "Could not retrieve base_primary_column from "
    2036             :                          "gpkgext_relations");
    2037           0 :                 continue;
    2038             :             }
    2039          58 :             const char *pszRelatedTableName = oResultTable->GetValue(2, i);
    2040          58 :             if (!pszRelatedTableName)
    2041             :             {
    2042           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2043             :                          "Could not retrieve related_table_name from "
    2044             :                          "gpkgext_relations");
    2045           0 :                 continue;
    2046             :             }
    2047          58 :             const char *pszRelatedPrimaryColumn = oResultTable->GetValue(3, i);
    2048          58 :             if (!pszRelatedPrimaryColumn)
    2049             :             {
    2050           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2051             :                          "Could not retrieve related_primary_column from "
    2052             :                          "gpkgext_relations");
    2053           0 :                 continue;
    2054             :             }
    2055          58 :             const char *pszRelationName = oResultTable->GetValue(4, i);
    2056          58 :             if (!pszRelationName)
    2057             :             {
    2058           0 :                 CPLError(
    2059             :                     CE_Warning, CPLE_AppDefined,
    2060             :                     "Could not retrieve relation_name from gpkgext_relations");
    2061           0 :                 continue;
    2062             :             }
    2063          58 :             const char *pszMappingTableName = oResultTable->GetValue(5, i);
    2064          58 :             if (!pszMappingTableName)
    2065             :             {
    2066           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2067             :                          "Could not retrieve mapping_table_name from "
    2068             :                          "gpkgext_relations");
    2069           0 :                 continue;
    2070             :             }
    2071             : 
    2072             :             // confirm that mapping table exists
    2073             :             char *pszSQL =
    2074          58 :                 sqlite3_mprintf("SELECT 1 FROM sqlite_master WHERE "
    2075             :                                 "name='%q' AND type IN ('table', 'view')",
    2076             :                                 pszMappingTableName);
    2077          58 :             const int nMappingTableCount = SQLGetInteger(hDB, pszSQL, nullptr);
    2078          58 :             sqlite3_free(pszSQL);
    2079             : 
    2080          59 :             if (nMappingTableCount < 1 &&
    2081           1 :                 !const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    2082           1 :                     pszMappingTableName))
    2083             :             {
    2084           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2085             :                          "Relationship mapping table %s does not exist",
    2086             :                          pszMappingTableName);
    2087           1 :                 continue;
    2088             :             }
    2089             : 
    2090             :             const std::string osRelationName = GenerateNameForRelationship(
    2091         114 :                 pszBaseTableName, pszRelatedTableName, pszRelationName);
    2092             : 
    2093         114 :             std::string osType{};
    2094             :             // defined requirement classes -- for these types the relation name
    2095             :             // will be specific string value from the related tables extension.
    2096             :             // In this case we need to construct a unique relationship name
    2097             :             // based on the related tables
    2098          57 :             if (EQUAL(pszRelationName, "media") ||
    2099          42 :                 EQUAL(pszRelationName, "simple_attributes") ||
    2100          42 :                 EQUAL(pszRelationName, "features") ||
    2101          20 :                 EQUAL(pszRelationName, "attributes") ||
    2102           2 :                 EQUAL(pszRelationName, "tiles"))
    2103             :             {
    2104          55 :                 osType = pszRelationName;
    2105             :             }
    2106             :             else
    2107             :             {
    2108             :                 // user defined types default to features
    2109           2 :                 osType = "features";
    2110             :             }
    2111             : 
    2112             :             auto poRelationship = std::make_unique<GDALRelationship>(
    2113             :                 osRelationName, pszBaseTableName, pszRelatedTableName,
    2114         114 :                 GRC_MANY_TO_MANY);
    2115             : 
    2116         114 :             poRelationship->SetLeftTableFields({pszBasePrimaryColumn});
    2117         114 :             poRelationship->SetRightTableFields({pszRelatedPrimaryColumn});
    2118         114 :             poRelationship->SetLeftMappingTableFields({"base_id"});
    2119         114 :             poRelationship->SetRightMappingTableFields({"related_id"});
    2120          57 :             poRelationship->SetMappingTableName(pszMappingTableName);
    2121          57 :             poRelationship->SetRelatedTableType(osType);
    2122             : 
    2123          57 :             m_osMapRelationships[osRelationName] = std::move(poRelationship);
    2124             :         }
    2125             :     }
    2126          41 : }
    2127             : 
    2128             : /************************************************************************/
    2129             : /*                    GenerateNameForRelationship()                     */
    2130             : /************************************************************************/
    2131             : 
    2132          83 : std::string GDALGeoPackageDataset::GenerateNameForRelationship(
    2133             :     const char *pszBaseTableName, const char *pszRelatedTableName,
    2134             :     const char *pszType)
    2135             : {
    2136             :     // defined requirement classes -- for these types the relation name will be
    2137             :     // specific string value from the related tables extension. In this case we
    2138             :     // need to construct a unique relationship name based on the related tables
    2139          83 :     if (EQUAL(pszType, "media") || EQUAL(pszType, "simple_attributes") ||
    2140          55 :         EQUAL(pszType, "features") || EQUAL(pszType, "attributes") ||
    2141           8 :         EQUAL(pszType, "tiles"))
    2142             :     {
    2143         150 :         std::ostringstream stream;
    2144             :         stream << pszBaseTableName << '_' << pszRelatedTableName << '_'
    2145          75 :                << pszType;
    2146          75 :         return stream.str();
    2147             :     }
    2148             :     else
    2149             :     {
    2150             :         // user defined types default to features
    2151           8 :         return pszType;
    2152             :     }
    2153             : }
    2154             : 
    2155             : /************************************************************************/
    2156             : /*                        ValidateRelationship()                        */
    2157             : /************************************************************************/
    2158             : 
    2159          30 : bool GDALGeoPackageDataset::ValidateRelationship(
    2160             :     const GDALRelationship *poRelationship, std::string &failureReason)
    2161             : {
    2162             : 
    2163          30 :     if (poRelationship->GetCardinality() !=
    2164             :         GDALRelationshipCardinality::GRC_MANY_TO_MANY)
    2165             :     {
    2166           3 :         failureReason = "Only many to many relationships are supported";
    2167           3 :         return false;
    2168             :     }
    2169             : 
    2170          54 :     std::string osRelatedTableType = poRelationship->GetRelatedTableType();
    2171          71 :     if (!osRelatedTableType.empty() && osRelatedTableType != "features" &&
    2172          32 :         osRelatedTableType != "media" &&
    2173          20 :         osRelatedTableType != "simple_attributes" &&
    2174          59 :         osRelatedTableType != "attributes" && osRelatedTableType != "tiles")
    2175             :     {
    2176             :         failureReason =
    2177           4 :             ("Related table type " + osRelatedTableType +
    2178             :              " is not a valid value for the GeoPackage specification. "
    2179             :              "Valid values are: features, media, simple_attributes, "
    2180             :              "attributes, tiles.")
    2181           2 :                 .c_str();
    2182           2 :         return false;
    2183             :     }
    2184             : 
    2185          25 :     const std::string &osLeftTableName = poRelationship->GetLeftTableName();
    2186          25 :     OGRGeoPackageLayer *poLeftTable = cpl::down_cast<OGRGeoPackageLayer *>(
    2187          25 :         GetLayerByName(osLeftTableName.c_str()));
    2188          25 :     if (!poLeftTable)
    2189             :     {
    2190           4 :         failureReason = ("Left table " + osLeftTableName +
    2191             :                          " is not an existing layer in the dataset")
    2192           2 :                             .c_str();
    2193           2 :         return false;
    2194             :     }
    2195          23 :     const std::string &osRightTableName = poRelationship->GetRightTableName();
    2196          23 :     OGRGeoPackageLayer *poRightTable = cpl::down_cast<OGRGeoPackageLayer *>(
    2197          23 :         GetLayerByName(osRightTableName.c_str()));
    2198          23 :     if (!poRightTable)
    2199             :     {
    2200           4 :         failureReason = ("Right table " + osRightTableName +
    2201             :                          " is not an existing layer in the dataset")
    2202           2 :                             .c_str();
    2203           2 :         return false;
    2204             :     }
    2205             : 
    2206          21 :     const auto &aosLeftTableFields = poRelationship->GetLeftTableFields();
    2207          21 :     if (aosLeftTableFields.empty())
    2208             :     {
    2209           1 :         failureReason = "No left table fields were specified";
    2210           1 :         return false;
    2211             :     }
    2212          20 :     else if (aosLeftTableFields.size() > 1)
    2213             :     {
    2214             :         failureReason = "Only a single left table field is permitted for the "
    2215           1 :                         "GeoPackage specification";
    2216           1 :         return false;
    2217             :     }
    2218             :     else
    2219             :     {
    2220             :         // validate left field exists
    2221          38 :         if (poLeftTable->GetLayerDefn()->GetFieldIndex(
    2222          43 :                 aosLeftTableFields[0].c_str()) < 0 &&
    2223           5 :             !EQUAL(poLeftTable->GetFIDColumn(), aosLeftTableFields[0].c_str()))
    2224             :         {
    2225           2 :             failureReason = ("Left table field " + aosLeftTableFields[0] +
    2226           2 :                              " does not exist in " + osLeftTableName)
    2227           1 :                                 .c_str();
    2228           1 :             return false;
    2229             :         }
    2230             :     }
    2231             : 
    2232          18 :     const auto &aosRightTableFields = poRelationship->GetRightTableFields();
    2233          18 :     if (aosRightTableFields.empty())
    2234             :     {
    2235           1 :         failureReason = "No right table fields were specified";
    2236           1 :         return false;
    2237             :     }
    2238          17 :     else if (aosRightTableFields.size() > 1)
    2239             :     {
    2240             :         failureReason = "Only a single right table field is permitted for the "
    2241           1 :                         "GeoPackage specification";
    2242           1 :         return false;
    2243             :     }
    2244             :     else
    2245             :     {
    2246             :         // validate right field exists
    2247          32 :         if (poRightTable->GetLayerDefn()->GetFieldIndex(
    2248          38 :                 aosRightTableFields[0].c_str()) < 0 &&
    2249           6 :             !EQUAL(poRightTable->GetFIDColumn(),
    2250             :                    aosRightTableFields[0].c_str()))
    2251             :         {
    2252           4 :             failureReason = ("Right table field " + aosRightTableFields[0] +
    2253           4 :                              " does not exist in " + osRightTableName)
    2254           2 :                                 .c_str();
    2255           2 :             return false;
    2256             :         }
    2257             :     }
    2258             : 
    2259          14 :     return true;
    2260             : }
    2261             : 
    2262             : /************************************************************************/
    2263             : /*                             InitRaster()                             */
    2264             : /************************************************************************/
    2265             : 
    2266         372 : bool GDALGeoPackageDataset::InitRaster(
    2267             :     GDALGeoPackageDataset *poParentDS, const char *pszTableName, double dfMinX,
    2268             :     double dfMinY, double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2269             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2270             :     const char *pszContentsMaxY, CSLConstList papszOpenOptionsIn,
    2271             :     const SQLResult &oResult, int nIdxInResult)
    2272             : {
    2273         372 :     m_osRasterTable = pszTableName;
    2274         372 :     m_dfTMSMinX = dfMinX;
    2275         372 :     m_dfTMSMaxY = dfMaxY;
    2276             : 
    2277             :     // Despite prior checking, the type might be Binary and
    2278             :     // SQLResultGetValue() not working properly on it
    2279         372 :     int nZoomLevel = atoi(oResult.GetValue(0, nIdxInResult));
    2280         372 :     if (nZoomLevel < 0 || nZoomLevel > 65536)
    2281             :     {
    2282           0 :         return false;
    2283             :     }
    2284         372 :     double dfPixelXSize = CPLAtof(oResult.GetValue(1, nIdxInResult));
    2285         372 :     double dfPixelYSize = CPLAtof(oResult.GetValue(2, nIdxInResult));
    2286         372 :     if (dfPixelXSize <= 0 || dfPixelYSize <= 0)
    2287             :     {
    2288           0 :         return false;
    2289             :     }
    2290         372 :     int nTileWidth = atoi(oResult.GetValue(3, nIdxInResult));
    2291         372 :     int nTileHeight = atoi(oResult.GetValue(4, nIdxInResult));
    2292         372 :     if (nTileWidth <= 0 || nTileWidth > 65536 || nTileHeight <= 0 ||
    2293             :         nTileHeight > 65536)
    2294             :     {
    2295           0 :         return false;
    2296             :     }
    2297             :     int nTileMatrixWidth = static_cast<int>(
    2298         744 :         std::min(static_cast<GIntBig>(INT_MAX),
    2299         372 :                  CPLAtoGIntBig(oResult.GetValue(5, nIdxInResult))));
    2300             :     int nTileMatrixHeight = static_cast<int>(
    2301         744 :         std::min(static_cast<GIntBig>(INT_MAX),
    2302         372 :                  CPLAtoGIntBig(oResult.GetValue(6, nIdxInResult))));
    2303         372 :     if (nTileMatrixWidth <= 0 || nTileMatrixHeight <= 0)
    2304             :     {
    2305           0 :         return false;
    2306             :     }
    2307             : 
    2308             :     /* Use content bounds in priority over tile_matrix_set bounds */
    2309         372 :     double dfGDALMinX = dfMinX;
    2310         372 :     double dfGDALMinY = dfMinY;
    2311         372 :     double dfGDALMaxX = dfMaxX;
    2312         372 :     double dfGDALMaxY = dfMaxY;
    2313             :     pszContentsMinX =
    2314         372 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINX", pszContentsMinX);
    2315             :     pszContentsMinY =
    2316         372 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINY", pszContentsMinY);
    2317             :     pszContentsMaxX =
    2318         372 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXX", pszContentsMaxX);
    2319             :     pszContentsMaxY =
    2320         372 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXY", pszContentsMaxY);
    2321         372 :     if (pszContentsMinX != nullptr && pszContentsMinY != nullptr &&
    2322         372 :         pszContentsMaxX != nullptr && pszContentsMaxY != nullptr)
    2323             :     {
    2324         743 :         if (CPLAtof(pszContentsMinX) < CPLAtof(pszContentsMaxX) &&
    2325         371 :             CPLAtof(pszContentsMinY) < CPLAtof(pszContentsMaxY))
    2326             :         {
    2327         371 :             dfGDALMinX = CPLAtof(pszContentsMinX);
    2328         371 :             dfGDALMinY = CPLAtof(pszContentsMinY);
    2329         371 :             dfGDALMaxX = CPLAtof(pszContentsMaxX);
    2330         371 :             dfGDALMaxY = CPLAtof(pszContentsMaxY);
    2331             :         }
    2332             :         else
    2333             :         {
    2334           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    2335             :                      "Illegal min_x/min_y/max_x/max_y values for %s in open "
    2336             :                      "options and/or gpkg_contents. Using bounds of "
    2337             :                      "gpkg_tile_matrix_set instead",
    2338             :                      pszTableName);
    2339             :         }
    2340             :     }
    2341         372 :     if (dfGDALMinX >= dfGDALMaxX || dfGDALMinY >= dfGDALMaxY)
    2342             :     {
    2343           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2344             :                  "Illegal min_x/min_y/max_x/max_y values for %s", pszTableName);
    2345           0 :         return false;
    2346             :     }
    2347             : 
    2348         372 :     int nBandCount = 0;
    2349             :     const char *pszBAND_COUNT =
    2350         372 :         CSLFetchNameValue(papszOpenOptionsIn, "BAND_COUNT");
    2351         372 :     if (poParentDS)
    2352             :     {
    2353          86 :         nBandCount = poParentDS->GetRasterCount();
    2354             :     }
    2355         286 :     else if (m_eDT != GDT_UInt8)
    2356             :     {
    2357          65 :         if (pszBAND_COUNT != nullptr && !EQUAL(pszBAND_COUNT, "AUTO") &&
    2358           0 :             !EQUAL(pszBAND_COUNT, "1"))
    2359             :         {
    2360           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2361             :                      "BAND_COUNT ignored for non-Byte data");
    2362             :         }
    2363          65 :         nBandCount = 1;
    2364             :     }
    2365             :     else
    2366             :     {
    2367         221 :         if (pszBAND_COUNT != nullptr && !EQUAL(pszBAND_COUNT, "AUTO"))
    2368             :         {
    2369          69 :             nBandCount = atoi(pszBAND_COUNT);
    2370          69 :             if (nBandCount == 1)
    2371           5 :                 GetMetadata(GDAL_MDD_IMAGE_STRUCTURE);
    2372             :         }
    2373             :         else
    2374             :         {
    2375         152 :             GetMetadata(GDAL_MDD_IMAGE_STRUCTURE);
    2376         152 :             nBandCount = m_nBandCountFromMetadata;
    2377         152 :             if (nBandCount == 1)
    2378          49 :                 m_eTF = GPKG_TF_PNG;
    2379             :         }
    2380         221 :         if (nBandCount == 1 && !m_osTFFromMetadata.empty())
    2381             :         {
    2382           2 :             m_eTF = GDALGPKGMBTilesGetTileFormat(m_osTFFromMetadata.c_str());
    2383             :         }
    2384         221 :         if (nBandCount <= 0 || nBandCount > 4)
    2385          88 :             nBandCount = 4;
    2386             :     }
    2387             : 
    2388         372 :     return InitRaster(poParentDS, pszTableName, nZoomLevel, nBandCount, dfMinX,
    2389             :                       dfMaxY, dfPixelXSize, dfPixelYSize, nTileWidth,
    2390             :                       nTileHeight, nTileMatrixWidth, nTileMatrixHeight,
    2391         372 :                       dfGDALMinX, dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    2392             : }
    2393             : 
    2394             : /************************************************************************/
    2395             : /*                     ComputeTileAndPixelShifts()                      */
    2396             : /************************************************************************/
    2397             : 
    2398         815 : bool GDALGeoPackageDataset::ComputeTileAndPixelShifts()
    2399             : {
    2400             :     int nTileWidth, nTileHeight;
    2401         815 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2402             : 
    2403             :     // Compute shift between GDAL origin and TileMatrixSet origin
    2404         815 :     const double dfShiftXPixels = (m_gt[0] - m_dfTMSMinX) / m_gt[1];
    2405         815 :     if (!(dfShiftXPixels / nTileWidth >= INT_MIN &&
    2406         812 :           dfShiftXPixels / nTileWidth < INT_MAX))
    2407             :     {
    2408           3 :         return false;
    2409             :     }
    2410         812 :     const int64_t nShiftXPixels =
    2411         812 :         static_cast<int64_t>(floor(0.5 + dfShiftXPixels));
    2412         812 :     m_nShiftXTiles = static_cast<int>(nShiftXPixels / nTileWidth);
    2413         812 :     if (nShiftXPixels < 0 && (nShiftXPixels % nTileWidth) != 0)
    2414          11 :         m_nShiftXTiles--;
    2415         812 :     m_nShiftXPixelsMod =
    2416         812 :         (static_cast<int>(nShiftXPixels % nTileWidth) + nTileWidth) %
    2417             :         nTileWidth;
    2418             : 
    2419         812 :     const double dfShiftYPixels = (m_gt[3] - m_dfTMSMaxY) / m_gt[5];
    2420         812 :     if (!(dfShiftYPixels / nTileHeight >= INT_MIN &&
    2421         812 :           dfShiftYPixels / nTileHeight < INT_MAX))
    2422             :     {
    2423           1 :         return false;
    2424             :     }
    2425         811 :     const int64_t nShiftYPixels =
    2426         811 :         static_cast<int64_t>(floor(0.5 + dfShiftYPixels));
    2427         811 :     m_nShiftYTiles = static_cast<int>(nShiftYPixels / nTileHeight);
    2428         811 :     if (nShiftYPixels < 0 && (nShiftYPixels % nTileHeight) != 0)
    2429          11 :         m_nShiftYTiles--;
    2430         811 :     m_nShiftYPixelsMod =
    2431         811 :         (static_cast<int>(nShiftYPixels % nTileHeight) + nTileHeight) %
    2432             :         nTileHeight;
    2433         811 :     return true;
    2434             : }
    2435             : 
    2436             : /************************************************************************/
    2437             : /*                          AllocCachedTiles()                          */
    2438             : /************************************************************************/
    2439             : 
    2440         811 : bool GDALGeoPackageDataset::AllocCachedTiles()
    2441             : {
    2442             :     int nTileWidth, nTileHeight;
    2443         811 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2444             : 
    2445             :     // We currently need 4 caches because of
    2446             :     // GDALGPKGMBTilesLikePseudoDataset::ReadTile(int nRow, int nCol)
    2447         811 :     const int nCacheCount = 4;
    2448             :     /*
    2449             :             (m_nShiftXPixelsMod != 0 || m_nShiftYPixelsMod != 0) ? 4 :
    2450             :             (GetUpdate() && m_eDT == GDT_UInt8) ? 2 : 1;
    2451             :     */
    2452         811 :     m_pabyCachedTiles = static_cast<GByte *>(VSI_MALLOC3_VERBOSE(
    2453             :         cpl::fits_on<int>(nCacheCount * (m_eDT == GDT_UInt8 ? 4 : 1) *
    2454             :                           m_nDTSize),
    2455             :         nTileWidth, nTileHeight));
    2456         811 :     if (m_pabyCachedTiles == nullptr)
    2457             :     {
    2458           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Too big tiles: %d x %d",
    2459             :                  nTileWidth, nTileHeight);
    2460           0 :         return false;
    2461             :     }
    2462             : 
    2463         811 :     return true;
    2464             : }
    2465             : 
    2466             : /************************************************************************/
    2467             : /*                             InitRaster()                             */
    2468             : /************************************************************************/
    2469             : 
    2470         619 : bool GDALGeoPackageDataset::InitRaster(
    2471             :     GDALGeoPackageDataset *poParentDS, const char *pszTableName, int nZoomLevel,
    2472             :     int nBandCount, double dfTMSMinX, double dfTMSMaxY, double dfPixelXSize,
    2473             :     double dfPixelYSize, int nTileWidth, int nTileHeight, int nTileMatrixWidth,
    2474             :     int nTileMatrixHeight, double dfGDALMinX, double dfGDALMinY,
    2475             :     double dfGDALMaxX, double dfGDALMaxY)
    2476             : {
    2477         619 :     m_osRasterTable = pszTableName;
    2478         619 :     m_dfTMSMinX = dfTMSMinX;
    2479         619 :     m_dfTMSMaxY = dfTMSMaxY;
    2480         619 :     m_nZoomLevel = nZoomLevel;
    2481         619 :     m_nTileMatrixWidth = nTileMatrixWidth;
    2482         619 :     m_nTileMatrixHeight = nTileMatrixHeight;
    2483             : 
    2484         619 :     m_bGeoTransformValid = true;
    2485         619 :     m_gt[0] = dfGDALMinX;
    2486         619 :     m_gt[1] = dfPixelXSize;
    2487         619 :     m_gt[3] = dfGDALMaxY;
    2488         619 :     m_gt[5] = -dfPixelYSize;
    2489         619 :     double dfRasterXSize = 0.5 + (dfGDALMaxX - dfGDALMinX) / dfPixelXSize;
    2490         619 :     double dfRasterYSize = 0.5 + (dfGDALMaxY - dfGDALMinY) / dfPixelYSize;
    2491         619 :     if (dfRasterXSize > INT_MAX || dfRasterYSize > INT_MAX)
    2492             :     {
    2493           0 :         CPLError(CE_Failure, CPLE_NotSupported, "Too big raster: %f x %f",
    2494             :                  dfRasterXSize, dfRasterYSize);
    2495           0 :         return false;
    2496             :     }
    2497         619 :     nRasterXSize = std::max(1, static_cast<int>(dfRasterXSize));
    2498         619 :     nRasterYSize = std::max(1, static_cast<int>(dfRasterYSize));
    2499             : 
    2500         619 :     if (poParentDS)
    2501             :     {
    2502         333 :         m_poParentDS = poParentDS;
    2503         333 :         eAccess = poParentDS->eAccess;
    2504         333 :         hDB = poParentDS->hDB;
    2505         333 :         m_eTF = poParentDS->m_eTF;
    2506         333 :         m_eDT = poParentDS->m_eDT;
    2507         333 :         m_nDTSize = poParentDS->m_nDTSize;
    2508         333 :         m_dfScale = poParentDS->m_dfScale;
    2509         333 :         m_dfOffset = poParentDS->m_dfOffset;
    2510         333 :         m_dfPrecision = poParentDS->m_dfPrecision;
    2511         333 :         m_usGPKGNull = poParentDS->m_usGPKGNull;
    2512         333 :         m_nQuality = poParentDS->m_nQuality;
    2513         333 :         m_nZLevel = poParentDS->m_nZLevel;
    2514         333 :         m_bDither = poParentDS->m_bDither;
    2515             :         /*m_nSRID = poParentDS->m_nSRID;*/
    2516         333 :         m_osWHERE = poParentDS->m_osWHERE;
    2517         333 :         SetDescription(CPLSPrintf("%s - zoom_level=%d",
    2518         333 :                                   poParentDS->GetDescription(), m_nZoomLevel));
    2519             :     }
    2520             : 
    2521        2146 :     for (int i = 1; i <= nBandCount; i++)
    2522             :     {
    2523             :         auto poNewBand = std::make_unique<GDALGeoPackageRasterBand>(
    2524        1527 :             this, nTileWidth, nTileHeight);
    2525        1527 :         if (poParentDS)
    2526             :         {
    2527         769 :             int bHasNoData = FALSE;
    2528             :             double dfNoDataValue =
    2529         769 :                 poParentDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    2530         769 :             if (bHasNoData)
    2531          24 :                 poNewBand->SetNoDataValueInternal(dfNoDataValue);
    2532             :         }
    2533             : 
    2534        1527 :         if (nBandCount == 1 && m_poCTFromMetadata)
    2535             :         {
    2536           3 :             poNewBand->AssignColorTable(m_poCTFromMetadata.get());
    2537             :         }
    2538        1527 :         if (!m_osNodataValueFromMetadata.empty())
    2539             :         {
    2540           8 :             poNewBand->SetNoDataValueInternal(
    2541             :                 CPLAtof(m_osNodataValueFromMetadata.c_str()));
    2542             :         }
    2543             : 
    2544        1527 :         SetBand(i, std::move(poNewBand));
    2545             :     }
    2546             : 
    2547         619 :     if (!ComputeTileAndPixelShifts())
    2548             :     {
    2549           3 :         CPLError(CE_Failure, CPLE_AppDefined,
    2550             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    2551           3 :         return false;
    2552             :     }
    2553             : 
    2554         616 :     GDALPamDataset::SetMetadataItem(GDALMD_INTERLEAVE, "PIXEL",
    2555             :                                     GDAL_MDD_IMAGE_STRUCTURE);
    2556         616 :     GDALPamDataset::SetMetadataItem("ZOOM_LEVEL",
    2557             :                                     CPLSPrintf("%d", m_nZoomLevel));
    2558             : 
    2559         616 :     return AllocCachedTiles();
    2560             : }
    2561             : 
    2562             : /************************************************************************/
    2563             : /*                    GDALGPKGMBTilesGetTileFormat()                    */
    2564             : /************************************************************************/
    2565             : 
    2566          91 : GPKGTileFormat GDALGPKGMBTilesGetTileFormat(const char *pszTF)
    2567             : {
    2568          91 :     GPKGTileFormat eTF = GPKG_TF_PNG_JPEG;
    2569          91 :     if (pszTF)
    2570             :     {
    2571          91 :         if (EQUAL(pszTF, "PNG_JPEG") || EQUAL(pszTF, "AUTO"))
    2572           1 :             eTF = GPKG_TF_PNG_JPEG;
    2573          90 :         else if (EQUAL(pszTF, "PNG"))
    2574          49 :             eTF = GPKG_TF_PNG;
    2575          41 :         else if (EQUAL(pszTF, "PNG8"))
    2576          10 :             eTF = GPKG_TF_PNG8;
    2577          31 :         else if (EQUAL(pszTF, "JPEG"))
    2578          16 :             eTF = GPKG_TF_JPEG;
    2579          15 :         else if (EQUAL(pszTF, "WEBP"))
    2580          15 :             eTF = GPKG_TF_WEBP;
    2581             :         else
    2582             :         {
    2583           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2584             :                      "Unsuppoted value for TILE_FORMAT: %s", pszTF);
    2585             :         }
    2586             :     }
    2587          91 :     return eTF;
    2588             : }
    2589             : 
    2590          38 : const char *GDALMBTilesGetTileFormatName(GPKGTileFormat eTF)
    2591             : {
    2592          38 :     switch (eTF)
    2593             :     {
    2594          32 :         case GPKG_TF_PNG:
    2595             :         case GPKG_TF_PNG8:
    2596          32 :             return "png";
    2597           3 :         case GPKG_TF_JPEG:
    2598           3 :             return "jpg";
    2599           3 :         case GPKG_TF_WEBP:
    2600           3 :             return "webp";
    2601           0 :         default:
    2602           0 :             break;
    2603             :     }
    2604           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2605             :              "Unsuppoted value for TILE_FORMAT: %d", static_cast<int>(eTF));
    2606           0 :     return nullptr;
    2607             : }
    2608             : 
    2609             : /************************************************************************/
    2610             : /*                             OpenRaster()                             */
    2611             : /************************************************************************/
    2612             : 
    2613         288 : bool GDALGeoPackageDataset::OpenRaster(
    2614             :     const char *pszTableName, const char *pszIdentifier,
    2615             :     const char *pszDescription, int nSRSId, double dfMinX, double dfMinY,
    2616             :     double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2617             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2618             :     const char *pszContentsMaxY, bool bIsTiles, CSLConstList papszOpenOptionsIn)
    2619             : {
    2620         288 :     if (dfMinX >= dfMaxX || dfMinY >= dfMaxY)
    2621           0 :         return false;
    2622             : 
    2623             :     // Config option just for debug, and for example force set to NaN
    2624             :     // which is not supported
    2625         576 :     CPLString osDataNull = CPLGetConfigOption("GPKG_NODATA", "");
    2626         576 :     CPLString osUom;
    2627         576 :     CPLString osFieldName;
    2628         576 :     CPLString osGridCellEncoding;
    2629         288 :     if (!bIsTiles)
    2630             :     {
    2631          65 :         char *pszSQL = sqlite3_mprintf(
    2632             :             "SELECT datatype, scale, offset, data_null, precision FROM "
    2633             :             "gpkg_2d_gridded_coverage_ancillary "
    2634             :             "WHERE tile_matrix_set_name = '%q' "
    2635             :             "AND datatype IN ('integer', 'float')"
    2636             :             "AND (scale > 0 OR scale IS NULL)",
    2637             :             pszTableName);
    2638          65 :         auto oResult = SQLQuery(hDB, pszSQL);
    2639          65 :         sqlite3_free(pszSQL);
    2640          65 :         if (!oResult || oResult->RowCount() == 0)
    2641             :         {
    2642           0 :             return false;
    2643             :         }
    2644          65 :         const char *pszDataType = oResult->GetValue(0, 0);
    2645          65 :         const char *pszScale = oResult->GetValue(1, 0);
    2646          65 :         const char *pszOffset = oResult->GetValue(2, 0);
    2647          65 :         const char *pszDataNull = oResult->GetValue(3, 0);
    2648          65 :         const char *pszPrecision = oResult->GetValue(4, 0);
    2649          65 :         if (pszDataNull)
    2650          23 :             osDataNull = pszDataNull;
    2651          65 :         if (EQUAL(pszDataType, "float"))
    2652             :         {
    2653           6 :             SetDataType(GDT_Float32);
    2654           6 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    2655             :         }
    2656             :         else
    2657             :         {
    2658          59 :             SetDataType(GDT_Float32);
    2659          59 :             m_eTF = GPKG_TF_PNG_16BIT;
    2660          59 :             const double dfScale = pszScale ? CPLAtof(pszScale) : 1.0;
    2661          59 :             const double dfOffset = pszOffset ? CPLAtof(pszOffset) : 0.0;
    2662          59 :             if (dfScale == 1.0)
    2663             :             {
    2664          59 :                 if (dfOffset == 0.0)
    2665             :                 {
    2666          24 :                     SetDataType(GDT_UInt16);
    2667             :                 }
    2668          35 :                 else if (dfOffset == -32768.0)
    2669             :                 {
    2670          35 :                     SetDataType(GDT_Int16);
    2671             :                 }
    2672             :                 // coverity[tainted_data]
    2673           0 :                 else if (dfOffset == -32767.0 && !osDataNull.empty() &&
    2674           0 :                          CPLAtof(osDataNull) == 65535.0)
    2675             :                 // Given that we will map the nodata value to -32768
    2676             :                 {
    2677           0 :                     SetDataType(GDT_Int16);
    2678             :                 }
    2679             :             }
    2680             : 
    2681             :             // Check that the tile offset and scales are compatible with a
    2682             :             // final integer result.
    2683          59 :             if (m_eDT != GDT_Float32)
    2684             :             {
    2685             :                 // coverity[tainted_data]
    2686          59 :                 if (dfScale == 1.0 && dfOffset == -32768.0 &&
    2687         118 :                     !osDataNull.empty() && CPLAtof(osDataNull) == 65535.0)
    2688             :                 {
    2689             :                     // Given that we will map the nodata value to -32768
    2690           9 :                     pszSQL = sqlite3_mprintf(
    2691             :                         "SELECT 1 FROM "
    2692             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2693             :                         "tpudt_name = '%q' "
    2694             :                         "AND NOT ((offset = 0.0 or offset = 1.0) "
    2695             :                         "AND scale = 1.0) "
    2696             :                         "LIMIT 1",
    2697             :                         pszTableName);
    2698             :                 }
    2699             :                 else
    2700             :                 {
    2701          50 :                     pszSQL = sqlite3_mprintf(
    2702             :                         "SELECT 1 FROM "
    2703             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2704             :                         "tpudt_name = '%q' "
    2705             :                         "AND NOT (offset = 0.0 AND scale = 1.0) LIMIT 1",
    2706             :                         pszTableName);
    2707             :                 }
    2708          59 :                 sqlite3_stmt *hSQLStmt = nullptr;
    2709             :                 int rc =
    2710          59 :                     SQLPrepareWithError(hDB, pszSQL, -1, &hSQLStmt, nullptr);
    2711             : 
    2712          59 :                 if (rc == SQLITE_OK)
    2713             :                 {
    2714          59 :                     if (sqlite3_step(hSQLStmt) == SQLITE_ROW)
    2715             :                     {
    2716           8 :                         SetDataType(GDT_Float32);
    2717             :                     }
    2718          59 :                     sqlite3_finalize(hSQLStmt);
    2719             :                 }
    2720          59 :                 sqlite3_free(pszSQL);
    2721             :             }
    2722             : 
    2723          59 :             SetGlobalOffsetScale(dfOffset, dfScale);
    2724             :         }
    2725          65 :         if (pszPrecision)
    2726          65 :             m_dfPrecision = CPLAtof(pszPrecision);
    2727             : 
    2728             :         // Request those columns in a separate query, so as to keep
    2729             :         // compatibility with pre OGC 17-066r1 databases
    2730             :         pszSQL =
    2731          65 :             sqlite3_mprintf("SELECT uom, field_name, grid_cell_encoding FROM "
    2732             :                             "gpkg_2d_gridded_coverage_ancillary "
    2733             :                             "WHERE tile_matrix_set_name = '%q'",
    2734             :                             pszTableName);
    2735          65 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    2736          65 :         oResult = SQLQuery(hDB, pszSQL);
    2737          65 :         CPLPopErrorHandler();
    2738          65 :         sqlite3_free(pszSQL);
    2739          65 :         if (oResult && oResult->RowCount() == 1)
    2740             :         {
    2741          64 :             const char *pszUom = oResult->GetValue(0, 0);
    2742          64 :             if (pszUom)
    2743           2 :                 osUom = pszUom;
    2744          64 :             const char *pszFieldName = oResult->GetValue(1, 0);
    2745          64 :             if (pszFieldName)
    2746          64 :                 osFieldName = pszFieldName;
    2747          64 :             const char *pszGridCellEncoding = oResult->GetValue(2, 0);
    2748          64 :             if (pszGridCellEncoding)
    2749          64 :                 osGridCellEncoding = pszGridCellEncoding;
    2750             :         }
    2751             :     }
    2752             : 
    2753         288 :     m_bRecordInsertedInGPKGContent = true;
    2754         288 :     m_nSRID = nSRSId;
    2755             : 
    2756         575 :     if (auto poSRS = GetSpatialRef(nSRSId))
    2757             :     {
    2758         287 :         m_oSRS = *(poSRS.get());
    2759             :     }
    2760             : 
    2761             :     /* Various sanity checks added in the SELECT */
    2762         288 :     char *pszQuotedTableName = sqlite3_mprintf("'%q'", pszTableName);
    2763         576 :     CPLString osQuotedTableName(pszQuotedTableName);
    2764         288 :     sqlite3_free(pszQuotedTableName);
    2765         288 :     char *pszSQL = sqlite3_mprintf(
    2766             :         "SELECT zoom_level, pixel_x_size, pixel_y_size, tile_width, "
    2767             :         "tile_height, matrix_width, matrix_height "
    2768             :         "FROM gpkg_tile_matrix tm "
    2769             :         "WHERE table_name = %s "
    2770             :         // INT_MAX would be the theoretical maximum value to avoid
    2771             :         // overflows, but that's already a insane value.
    2772             :         "AND zoom_level >= 0 AND zoom_level <= 65536 "
    2773             :         "AND pixel_x_size > 0 AND pixel_y_size > 0 "
    2774             :         "AND tile_width >= 1 AND tile_width <= 65536 "
    2775             :         "AND tile_height >= 1 AND tile_height <= 65536 "
    2776             :         "AND matrix_width >= 1 AND matrix_height >= 1",
    2777             :         osQuotedTableName.c_str());
    2778         576 :     CPLString osSQL(pszSQL);
    2779             :     const char *pszZoomLevel =
    2780         288 :         CSLFetchNameValue(papszOpenOptionsIn, "ZOOM_LEVEL");
    2781         288 :     if (pszZoomLevel)
    2782             :     {
    2783           5 :         if (GetUpdate())
    2784           1 :             osSQL += CPLSPrintf(" AND zoom_level <= %d", atoi(pszZoomLevel));
    2785             :         else
    2786             :         {
    2787             :             osSQL += CPLSPrintf(
    2788             :                 " AND (zoom_level = %d OR (zoom_level < %d AND EXISTS(SELECT 1 "
    2789             :                 "FROM %s WHERE zoom_level = tm.zoom_level LIMIT 1)))",
    2790             :                 atoi(pszZoomLevel), atoi(pszZoomLevel),
    2791           4 :                 osQuotedTableName.c_str());
    2792             :         }
    2793             :     }
    2794             :     // In read-only mode, only lists non empty zoom levels
    2795         283 :     else if (!GetUpdate())
    2796             :     {
    2797             :         osSQL += CPLSPrintf(" AND EXISTS(SELECT 1 FROM %s WHERE zoom_level = "
    2798             :                             "tm.zoom_level LIMIT 1)",
    2799         229 :                             osQuotedTableName.c_str());
    2800             :     }
    2801             :     else  // if( pszZoomLevel == nullptr )
    2802             :     {
    2803             :         osSQL +=
    2804             :             CPLSPrintf(" AND zoom_level <= (SELECT MAX(zoom_level) FROM %s)",
    2805          54 :                        osQuotedTableName.c_str());
    2806             :     }
    2807         288 :     osSQL += " ORDER BY zoom_level DESC";
    2808             :     // To avoid denial of service.
    2809         288 :     osSQL += " LIMIT 100";
    2810             : 
    2811         576 :     auto oResult = SQLQuery(hDB, osSQL.c_str());
    2812         288 :     if (!oResult || oResult->RowCount() == 0)
    2813             :     {
    2814         122 :         if (oResult && oResult->RowCount() == 0 && pszContentsMinX != nullptr &&
    2815         122 :             pszContentsMinY != nullptr && pszContentsMaxX != nullptr &&
    2816             :             pszContentsMaxY != nullptr)
    2817             :         {
    2818          60 :             osSQL = pszSQL;
    2819          60 :             osSQL += " ORDER BY zoom_level DESC";
    2820          60 :             if (!GetUpdate())
    2821          34 :                 osSQL += " LIMIT 1";
    2822          60 :             oResult = SQLQuery(hDB, osSQL.c_str());
    2823             :         }
    2824          61 :         if (!oResult || oResult->RowCount() == 0)
    2825             :         {
    2826           1 :             if (oResult && pszZoomLevel != nullptr)
    2827             :             {
    2828           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2829             :                          "ZOOM_LEVEL is probably not valid w.r.t tile "
    2830             :                          "table content");
    2831             :             }
    2832           1 :             sqlite3_free(pszSQL);
    2833           1 :             return false;
    2834             :         }
    2835             :     }
    2836         287 :     sqlite3_free(pszSQL);
    2837             : 
    2838             :     // If USE_TILE_EXTENT=YES, then query the tile table to find which tiles
    2839             :     // actually exist.
    2840             : 
    2841             :     // CAUTION: Do not move those variables inside inner scope !
    2842         574 :     CPLString osContentsMinX, osContentsMinY, osContentsMaxX, osContentsMaxY;
    2843             : 
    2844         287 :     if (CPLTestBool(
    2845             :             CSLFetchNameValueDef(papszOpenOptionsIn, "USE_TILE_EXTENT", "NO")))
    2846             :     {
    2847          13 :         pszSQL = sqlite3_mprintf(
    2848             :             "SELECT MIN(tile_column), MIN(tile_row), MAX(tile_column), "
    2849             :             "MAX(tile_row) FROM \"%w\" WHERE zoom_level = %d",
    2850             :             pszTableName, atoi(oResult->GetValue(0, 0)));
    2851          13 :         auto oResult2 = SQLQuery(hDB, pszSQL);
    2852          13 :         sqlite3_free(pszSQL);
    2853          26 :         if (!oResult2 || oResult2->RowCount() == 0 ||
    2854             :             // Can happen if table is empty
    2855          38 :             oResult2->GetValue(0, 0) == nullptr ||
    2856             :             // Can happen if table has no NOT NULL constraint on tile_row
    2857             :             // and that all tile_row are NULL
    2858          12 :             oResult2->GetValue(1, 0) == nullptr)
    2859             :         {
    2860           1 :             return false;
    2861             :         }
    2862          12 :         const double dfPixelXSize = CPLAtof(oResult->GetValue(1, 0));
    2863          12 :         const double dfPixelYSize = CPLAtof(oResult->GetValue(2, 0));
    2864          12 :         const int nTileWidth = atoi(oResult->GetValue(3, 0));
    2865          12 :         const int nTileHeight = atoi(oResult->GetValue(4, 0));
    2866             :         osContentsMinX =
    2867          24 :             CPLSPrintf("%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2868          12 :                                              atoi(oResult2->GetValue(0, 0)));
    2869             :         osContentsMaxY =
    2870          24 :             CPLSPrintf("%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2871          12 :                                              atoi(oResult2->GetValue(1, 0)));
    2872             :         osContentsMaxX = CPLSPrintf(
    2873          24 :             "%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2874          12 :                                   (1 + atoi(oResult2->GetValue(2, 0))));
    2875             :         osContentsMinY = CPLSPrintf(
    2876          24 :             "%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2877          12 :                                   (1 + atoi(oResult2->GetValue(3, 0))));
    2878          12 :         pszContentsMinX = osContentsMinX.c_str();
    2879          12 :         pszContentsMinY = osContentsMinY.c_str();
    2880          12 :         pszContentsMaxX = osContentsMaxX.c_str();
    2881          12 :         pszContentsMaxY = osContentsMaxY.c_str();
    2882             :     }
    2883             : 
    2884         286 :     if (!InitRaster(nullptr, pszTableName, dfMinX, dfMinY, dfMaxX, dfMaxY,
    2885             :                     pszContentsMinX, pszContentsMinY, pszContentsMaxX,
    2886         286 :                     pszContentsMaxY, papszOpenOptionsIn, *oResult, 0))
    2887             :     {
    2888           3 :         return false;
    2889             :     }
    2890             : 
    2891         283 :     auto poBand = cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(1));
    2892         283 :     if (!osDataNull.empty())
    2893             :     {
    2894          23 :         double dfGPKGNoDataValue = CPLAtof(osDataNull);
    2895          23 :         if (m_eTF == GPKG_TF_PNG_16BIT)
    2896             :         {
    2897          21 :             if (dfGPKGNoDataValue < 0 || dfGPKGNoDataValue > 65535 ||
    2898          21 :                 static_cast<int>(dfGPKGNoDataValue) != dfGPKGNoDataValue)
    2899             :             {
    2900           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2901             :                          "data_null = %.17g is invalid for integer data_type",
    2902             :                          dfGPKGNoDataValue);
    2903             :             }
    2904             :             else
    2905             :             {
    2906          21 :                 m_usGPKGNull = static_cast<GUInt16>(dfGPKGNoDataValue);
    2907          21 :                 if (m_eDT == GDT_Int16 && m_usGPKGNull > 32767)
    2908           9 :                     dfGPKGNoDataValue = -32768.0;
    2909          12 :                 else if (m_eDT == GDT_Float32)
    2910             :                 {
    2911             :                     // Pick a value that is unlikely to be hit with offset &
    2912             :                     // scale
    2913           4 :                     dfGPKGNoDataValue = -std::numeric_limits<float>::max();
    2914             :                 }
    2915          21 :                 poBand->SetNoDataValueInternal(dfGPKGNoDataValue);
    2916             :             }
    2917             :         }
    2918             :         else
    2919             :         {
    2920           2 :             poBand->SetNoDataValueInternal(
    2921           2 :                 static_cast<float>(dfGPKGNoDataValue));
    2922             :         }
    2923             :     }
    2924         283 :     if (!osUom.empty())
    2925             :     {
    2926           2 :         poBand->SetUnitTypeInternal(osUom);
    2927             :     }
    2928         283 :     if (!osFieldName.empty())
    2929             :     {
    2930          64 :         GetRasterBand(1)->GDALRasterBand::SetDescription(osFieldName);
    2931             :     }
    2932         283 :     if (!osGridCellEncoding.empty())
    2933             :     {
    2934          64 :         if (osGridCellEncoding == "grid-value-is-center")
    2935             :         {
    2936          15 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2937             :                                             GDALMD_AOP_POINT);
    2938             :         }
    2939          49 :         else if (osGridCellEncoding == "grid-value-is-area")
    2940             :         {
    2941          45 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2942             :                                             GDALMD_AOP_AREA);
    2943             :         }
    2944             :         else
    2945             :         {
    2946           4 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2947             :                                             GDALMD_AOP_POINT);
    2948           4 :             GetRasterBand(1)->GDALRasterBand::SetMetadataItem(
    2949             :                 "GRID_CELL_ENCODING", osGridCellEncoding);
    2950             :         }
    2951             :     }
    2952             : 
    2953         283 :     CheckUnknownExtensions(true);
    2954             : 
    2955             :     // Do this after CheckUnknownExtensions() so that m_eTF is set to
    2956             :     // GPKG_TF_WEBP if the table already registers the gpkg_webp extension
    2957         283 :     const char *pszTF = CSLFetchNameValue(papszOpenOptionsIn, "TILE_FORMAT");
    2958         283 :     if (pszTF)
    2959             :     {
    2960           4 :         if (!GetUpdate())
    2961             :         {
    2962           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2963             :                      "TILE_FORMAT open option ignored in read-only mode");
    2964             :         }
    2965           4 :         else if (m_eTF == GPKG_TF_PNG_16BIT ||
    2966           4 :                  m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    2967             :         {
    2968           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2969             :                      "TILE_FORMAT open option ignored on gridded coverages");
    2970             :         }
    2971             :         else
    2972             :         {
    2973           4 :             GPKGTileFormat eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    2974           4 :             if (eTF == GPKG_TF_WEBP && m_eTF != eTF)
    2975             :             {
    2976           1 :                 if (!RegisterWebPExtension())
    2977           0 :                     return false;
    2978             :             }
    2979           4 :             m_eTF = eTF;
    2980             :         }
    2981             :     }
    2982             : 
    2983         283 :     ParseCompressionOptions(papszOpenOptionsIn);
    2984             : 
    2985         283 :     m_osWHERE = CSLFetchNameValueDef(papszOpenOptionsIn, "WHERE", "");
    2986             : 
    2987             :     // Set metadata
    2988         283 :     if (pszIdentifier && pszIdentifier[0])
    2989         283 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", pszIdentifier);
    2990         283 :     if (pszDescription && pszDescription[0])
    2991          21 :         GDALPamDataset::SetMetadataItem("DESCRIPTION", pszDescription);
    2992             : 
    2993             :     // Add overviews
    2994         368 :     for (int i = 1; i < oResult->RowCount(); i++)
    2995             :     {
    2996          86 :         auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    2997          86 :         poOvrDS->ShareLockWithParentDataset(this);
    2998         172 :         if (!poOvrDS->InitRaster(this, pszTableName, dfMinX, dfMinY, dfMaxX,
    2999             :                                  dfMaxY, pszContentsMinX, pszContentsMinY,
    3000             :                                  pszContentsMaxX, pszContentsMaxY,
    3001          86 :                                  papszOpenOptionsIn, *oResult, i))
    3002             :         {
    3003           0 :             break;
    3004             :         }
    3005             : 
    3006             :         int nTileWidth, nTileHeight;
    3007          86 :         poOvrDS->GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3008             :         const bool bStop =
    3009          87 :             (eAccess == GA_ReadOnly && poOvrDS->GetRasterXSize() < nTileWidth &&
    3010           1 :              poOvrDS->GetRasterYSize() < nTileHeight);
    3011             : 
    3012          86 :         m_apoOverviewDS.push_back(std::move(poOvrDS));
    3013             : 
    3014          86 :         if (bStop)
    3015             :         {
    3016           1 :             break;
    3017             :         }
    3018             :     }
    3019             : 
    3020         283 :     return true;
    3021             : }
    3022             : 
    3023             : /************************************************************************/
    3024             : /*                           GetSpatialRef()                            */
    3025             : /************************************************************************/
    3026             : 
    3027          25 : const OGRSpatialReference *GDALGeoPackageDataset::GetSpatialRef() const
    3028             : {
    3029          25 :     if (GetLayerCount())
    3030           3 :         return GDALDataset::GetSpatialRef();
    3031          22 :     return GetSpatialRefRasterOnly();
    3032             : }
    3033             : 
    3034             : /************************************************************************/
    3035             : /*                      GetSpatialRefRasterOnly()                       */
    3036             : /************************************************************************/
    3037             : 
    3038             : const OGRSpatialReference *
    3039          23 : GDALGeoPackageDataset::GetSpatialRefRasterOnly() const
    3040             : 
    3041             : {
    3042          23 :     return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
    3043             : }
    3044             : 
    3045             : /************************************************************************/
    3046             : /*                           SetSpatialRef()                            */
    3047             : /************************************************************************/
    3048             : 
    3049         158 : CPLErr GDALGeoPackageDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    3050             : {
    3051         158 :     if (nBands == 0)
    3052             :     {
    3053           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3054             :                  "SetProjection() not supported on a dataset with 0 band");
    3055           1 :         return CE_Failure;
    3056             :     }
    3057         157 :     if (eAccess != GA_Update)
    3058             :     {
    3059           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3060             :                  "SetProjection() not supported on read-only dataset");
    3061           1 :         return CE_Failure;
    3062             :     }
    3063             : 
    3064         156 :     const int nSRID = GetSrsId(poSRS);
    3065         312 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3066         156 :     if (poTS && nSRID != poTS->nEPSGCode)
    3067             :     {
    3068           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3069             :                  "Projection should be EPSG:%d for %s tiling scheme",
    3070           1 :                  poTS->nEPSGCode, m_osTilingScheme.c_str());
    3071           1 :         return CE_Failure;
    3072             :     }
    3073             : 
    3074         155 :     m_nSRID = nSRID;
    3075         155 :     m_oSRS.Clear();
    3076         155 :     if (poSRS)
    3077         154 :         m_oSRS = *poSRS;
    3078             : 
    3079         155 :     if (m_bRecordInsertedInGPKGContent)
    3080             :     {
    3081         124 :         char *pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET srs_id = %d "
    3082             :                                        "WHERE lower(table_name) = lower('%q')",
    3083             :                                        m_nSRID, m_osRasterTable.c_str());
    3084         124 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3085         124 :         sqlite3_free(pszSQL);
    3086         124 :         if (eErr != OGRERR_NONE)
    3087           0 :             return CE_Failure;
    3088             : 
    3089         124 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_tile_matrix_set SET srs_id = %d "
    3090             :                                  "WHERE lower(table_name) = lower('%q')",
    3091             :                                  m_nSRID, m_osRasterTable.c_str());
    3092         124 :         eErr = SQLCommand(hDB, pszSQL);
    3093         124 :         sqlite3_free(pszSQL);
    3094         124 :         if (eErr != OGRERR_NONE)
    3095           0 :             return CE_Failure;
    3096             :     }
    3097             : 
    3098         155 :     return CE_None;
    3099             : }
    3100             : 
    3101             : /************************************************************************/
    3102             : /*                          GetGeoTransform()                           */
    3103             : /************************************************************************/
    3104             : 
    3105          35 : CPLErr GDALGeoPackageDataset::GetGeoTransform(GDALGeoTransform &gt) const
    3106             : {
    3107          35 :     gt = m_gt;
    3108          35 :     if (!m_bGeoTransformValid)
    3109           2 :         return CE_Failure;
    3110             :     else
    3111          33 :         return CE_None;
    3112             : }
    3113             : 
    3114             : /************************************************************************/
    3115             : /*                          SetGeoTransform()                           */
    3116             : /************************************************************************/
    3117             : 
    3118         201 : CPLErr GDALGeoPackageDataset::SetGeoTransform(const GDALGeoTransform &gt)
    3119             : {
    3120         201 :     if (nBands == 0)
    3121             :     {
    3122           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3123             :                  "SetGeoTransform() not supported on a dataset with 0 band");
    3124           2 :         return CE_Failure;
    3125             :     }
    3126         199 :     if (eAccess != GA_Update)
    3127             :     {
    3128           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3129             :                  "SetGeoTransform() not supported on read-only dataset");
    3130           1 :         return CE_Failure;
    3131             :     }
    3132         198 :     if (m_bGeoTransformValid)
    3133             :     {
    3134           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3135             :                  "Cannot modify geotransform once set");
    3136           1 :         return CE_Failure;
    3137             :     }
    3138         197 :     if (gt[2] != 0.0 || gt[4] != 0 || gt[5] > 0.0)
    3139             :     {
    3140           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3141             :                  "Only north-up non rotated geotransform supported");
    3142           0 :         return CE_Failure;
    3143             :     }
    3144             : 
    3145         197 :     if (m_nZoomLevel < 0)
    3146             :     {
    3147         196 :         const auto poTS = GetTilingScheme(m_osTilingScheme);
    3148         196 :         if (poTS)
    3149             :         {
    3150          20 :             double dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3151          20 :             double dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3152         199 :             for (m_nZoomLevel = 0; m_nZoomLevel < MAX_ZOOM_LEVEL;
    3153         179 :                  m_nZoomLevel++)
    3154             :             {
    3155         198 :                 double dfExpectedPixelXSize =
    3156         198 :                     dfPixelXSizeZoomLevel0 / (1 << m_nZoomLevel);
    3157         198 :                 double dfExpectedPixelYSize =
    3158         198 :                     dfPixelYSizeZoomLevel0 / (1 << m_nZoomLevel);
    3159         198 :                 if (fabs(gt[1] - dfExpectedPixelXSize) <
    3160         217 :                         1e-8 * dfExpectedPixelXSize &&
    3161          19 :                     fabs(fabs(gt[5]) - dfExpectedPixelYSize) <
    3162          19 :                         1e-8 * dfExpectedPixelYSize)
    3163             :                 {
    3164          19 :                     break;
    3165             :                 }
    3166             :             }
    3167          20 :             if (m_nZoomLevel == MAX_ZOOM_LEVEL)
    3168             :             {
    3169           1 :                 m_nZoomLevel = -1;
    3170           1 :                 CPLError(
    3171             :                     CE_Failure, CPLE_NotSupported,
    3172             :                     "Could not find an appropriate zoom level of %s tiling "
    3173             :                     "scheme that matches raster pixel size",
    3174             :                     m_osTilingScheme.c_str());
    3175           1 :                 return CE_Failure;
    3176             :             }
    3177             :         }
    3178             :     }
    3179             : 
    3180         196 :     m_gt = gt;
    3181         196 :     m_bGeoTransformValid = true;
    3182             : 
    3183         196 :     return FinalizeRasterRegistration();
    3184             : }
    3185             : 
    3186             : /************************************************************************/
    3187             : /*                     FinalizeRasterRegistration()                     */
    3188             : /************************************************************************/
    3189             : 
    3190         196 : CPLErr GDALGeoPackageDataset::FinalizeRasterRegistration()
    3191             : {
    3192         196 :     OGRErr eErr = OGRERR_NONE;
    3193             : 
    3194         196 :     m_dfTMSMinX = m_gt[0];
    3195         196 :     m_dfTMSMaxY = m_gt[3];
    3196             : 
    3197             :     int nTileWidth, nTileHeight;
    3198         196 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3199             : 
    3200         196 :     if (m_nZoomLevel < 0)
    3201             :     {
    3202         176 :         m_nZoomLevel = 0;
    3203         258 :         while ((nRasterXSize >> m_nZoomLevel) > nTileWidth ||
    3204         177 :                (nRasterYSize >> m_nZoomLevel) > nTileHeight)
    3205          82 :             m_nZoomLevel++;
    3206             :     }
    3207             : 
    3208         196 :     double dfPixelXSizeZoomLevel0 = m_gt[1] * (1 << m_nZoomLevel);
    3209         196 :     double dfPixelYSizeZoomLevel0 = fabs(m_gt[5]) * (1 << m_nZoomLevel);
    3210             : 
    3211             :     int nTileXCountZoomLevel0{std::max(
    3212         392 :         1, static_cast<int>(std::ceil(
    3213         196 :                (static_cast<double>(nRasterXSize) /
    3214         196 :                 (static_cast<double>(nTileWidth) * (1 << m_nZoomLevel))))))};
    3215             :     int nTileYCountZoomLevel0{std::max(
    3216         392 :         1, static_cast<int>(std::ceil(
    3217         196 :                (static_cast<double>(nRasterYSize) /
    3218         196 :                 (static_cast<double>(nTileHeight) * (1 << m_nZoomLevel))))))};
    3219             : 
    3220         392 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3221         196 :     if (poTS)
    3222             :     {
    3223          20 :         CPLAssert(m_nZoomLevel >= 0);
    3224          20 :         m_dfTMSMinX = poTS->dfMinX;
    3225          20 :         m_dfTMSMaxY = poTS->dfMaxY;
    3226          20 :         dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3227          20 :         dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3228          20 :         nTileXCountZoomLevel0 = poTS->nTileXCountZoomLevel0;
    3229          20 :         nTileYCountZoomLevel0 = poTS->nTileYCountZoomLevel0;
    3230             :     }
    3231         196 :     m_nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << m_nZoomLevel);
    3232         196 :     m_nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << m_nZoomLevel);
    3233             : 
    3234         196 :     if (!ComputeTileAndPixelShifts())
    3235             :     {
    3236           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    3237             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    3238           1 :         return CE_Failure;
    3239             :     }
    3240             : 
    3241         195 :     if (!AllocCachedTiles())
    3242             :     {
    3243           0 :         return CE_Failure;
    3244             :     }
    3245             : 
    3246         195 :     double dfGDALMinX = m_gt[0];
    3247         195 :     double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3248         195 :     double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3249         195 :     double dfGDALMaxY = m_gt[3];
    3250             : 
    3251         195 :     if (SoftStartTransaction() != OGRERR_NONE)
    3252           0 :         return CE_Failure;
    3253             : 
    3254             :     const char *pszCurrentDate =
    3255         195 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3256             :     CPLString osInsertGpkgContentsFormatting(
    3257             :         "INSERT INTO gpkg_contents "
    3258             :         "(table_name,data_type,identifier,description,min_x,min_y,max_x,max_y,"
    3259             :         "last_change,srs_id) VALUES "
    3260         390 :         "('%q','%q','%q','%q',%.17g,%.17g,%.17g,%.17g,");
    3261         195 :     osInsertGpkgContentsFormatting += (pszCurrentDate) ? "'%q'" : "%s";
    3262         195 :     osInsertGpkgContentsFormatting += ",%d)";
    3263         390 :     char *pszSQL = sqlite3_mprintf(
    3264             :         osInsertGpkgContentsFormatting.c_str(), m_osRasterTable.c_str(),
    3265         195 :         (m_eDT == GDT_UInt8) ? "tiles" : "2d-gridded-coverage",
    3266             :         m_osIdentifier.c_str(), m_osDescription.c_str(), dfGDALMinX, dfGDALMinY,
    3267             :         dfGDALMaxX, dfGDALMaxY,
    3268             :         pszCurrentDate ? pszCurrentDate
    3269             :                        : "strftime('%Y-%m-%dT%H:%M:%fZ','now')",
    3270             :         m_nSRID);
    3271             : 
    3272         195 :     eErr = SQLCommand(hDB, pszSQL);
    3273         195 :     sqlite3_free(pszSQL);
    3274         195 :     if (eErr != OGRERR_NONE)
    3275             :     {
    3276           8 :         SoftRollbackTransaction();
    3277           8 :         return CE_Failure;
    3278             :     }
    3279             : 
    3280         187 :     double dfTMSMaxX = m_dfTMSMinX + nTileXCountZoomLevel0 * nTileWidth *
    3281             :                                          dfPixelXSizeZoomLevel0;
    3282         187 :     double dfTMSMinY = m_dfTMSMaxY - nTileYCountZoomLevel0 * nTileHeight *
    3283             :                                          dfPixelYSizeZoomLevel0;
    3284             : 
    3285             :     pszSQL =
    3286         187 :         sqlite3_mprintf("INSERT INTO gpkg_tile_matrix_set "
    3287             :                         "(table_name,srs_id,min_x,min_y,max_x,max_y) VALUES "
    3288             :                         "('%q',%d,%.17g,%.17g,%.17g,%.17g)",
    3289             :                         m_osRasterTable.c_str(), m_nSRID, m_dfTMSMinX,
    3290             :                         dfTMSMinY, dfTMSMaxX, m_dfTMSMaxY);
    3291         187 :     eErr = SQLCommand(hDB, pszSQL);
    3292         187 :     sqlite3_free(pszSQL);
    3293         187 :     if (eErr != OGRERR_NONE)
    3294             :     {
    3295           0 :         SoftRollbackTransaction();
    3296           0 :         return CE_Failure;
    3297             :     }
    3298             : 
    3299         187 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3300             : 
    3301         617 :     for (int i = 0; i <= m_nZoomLevel; i++)
    3302             :     {
    3303         430 :         double dfPixelXSizeZoomLevel = 0.0;
    3304         430 :         double dfPixelYSizeZoomLevel = 0.0;
    3305         430 :         int nTileMatrixWidth = 0;
    3306         430 :         int nTileMatrixHeight = 0;
    3307         430 :         if (EQUAL(m_osTilingScheme, "CUSTOM"))
    3308             :         {
    3309         249 :             dfPixelXSizeZoomLevel = m_gt[1] * (1 << (m_nZoomLevel - i));
    3310         249 :             dfPixelYSizeZoomLevel = fabs(m_gt[5]) * (1 << (m_nZoomLevel - i));
    3311             :         }
    3312             :         else
    3313             :         {
    3314         181 :             dfPixelXSizeZoomLevel = dfPixelXSizeZoomLevel0 / (1 << i);
    3315         181 :             dfPixelYSizeZoomLevel = dfPixelYSizeZoomLevel0 / (1 << i);
    3316             :         }
    3317         430 :         nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << i);
    3318         430 :         nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << i);
    3319             : 
    3320         430 :         pszSQL = sqlite3_mprintf(
    3321             :             "INSERT INTO gpkg_tile_matrix "
    3322             :             "(table_name,zoom_level,matrix_width,matrix_height,tile_width,tile_"
    3323             :             "height,pixel_x_size,pixel_y_size) VALUES "
    3324             :             "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3325             :             m_osRasterTable.c_str(), i, nTileMatrixWidth, nTileMatrixHeight,
    3326             :             nTileWidth, nTileHeight, dfPixelXSizeZoomLevel,
    3327             :             dfPixelYSizeZoomLevel);
    3328         430 :         eErr = SQLCommand(hDB, pszSQL);
    3329         430 :         sqlite3_free(pszSQL);
    3330         430 :         if (eErr != OGRERR_NONE)
    3331             :         {
    3332           0 :             SoftRollbackTransaction();
    3333           0 :             return CE_Failure;
    3334             :         }
    3335             : 
    3336         430 :         if (i < m_nZoomLevel)
    3337             :         {
    3338         486 :             auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3339         243 :             poOvrDS->ShareLockWithParentDataset(this);
    3340         243 :             poOvrDS->InitRaster(this, m_osRasterTable, i, nBands, m_dfTMSMinX,
    3341             :                                 m_dfTMSMaxY, dfPixelXSizeZoomLevel,
    3342             :                                 dfPixelYSizeZoomLevel, nTileWidth, nTileHeight,
    3343             :                                 nTileMatrixWidth, nTileMatrixHeight, dfGDALMinX,
    3344             :                                 dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    3345             : 
    3346         243 :             m_apoOverviewDS[m_nZoomLevel - 1 - i] = std::move(poOvrDS);
    3347             :         }
    3348             :     }
    3349             : 
    3350         187 :     if (!m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.empty())
    3351             :     {
    3352          40 :         eErr = SQLCommand(
    3353             :             hDB, m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.c_str());
    3354          40 :         m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.clear();
    3355          40 :         if (eErr != OGRERR_NONE)
    3356             :         {
    3357           0 :             SoftRollbackTransaction();
    3358           0 :             return CE_Failure;
    3359             :         }
    3360             :     }
    3361             : 
    3362         187 :     SoftCommitTransaction();
    3363             : 
    3364         187 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3365         187 :     m_bRecordInsertedInGPKGContent = true;
    3366             : 
    3367         187 :     return CE_None;
    3368             : }
    3369             : 
    3370             : /************************************************************************/
    3371             : /*                             FlushCache()                             */
    3372             : /************************************************************************/
    3373             : 
    3374        3221 : CPLErr GDALGeoPackageDataset::FlushCache(bool bAtClosing)
    3375             : {
    3376        3221 :     if (m_bInFlushCache)
    3377           0 :         return CE_None;
    3378             : 
    3379        3221 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3380             :     {
    3381        3218 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3382             :     }
    3383             : 
    3384        3221 :     if (m_bRemoveOGREmptyTable)
    3385             :     {
    3386         924 :         m_bRemoveOGREmptyTable = false;
    3387         924 :         RemoveOGREmptyTable();
    3388             :     }
    3389             : 
    3390        3221 :     CPLErr eErr = IFlushCacheWithErrCode(bAtClosing);
    3391             : 
    3392        3221 :     FlushMetadata();
    3393             : 
    3394        3221 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3395             :     {
    3396             :         // Needed again as above IFlushCacheWithErrCode()
    3397             :         // may have call GDALGeoPackageRasterBand::InvalidateStatistics()
    3398             :         // which modifies metadata
    3399        3221 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3400             :     }
    3401             : 
    3402        3221 :     return eErr;
    3403             : }
    3404             : 
    3405        5505 : CPLErr GDALGeoPackageDataset::IFlushCacheWithErrCode(bool bAtClosing)
    3406             : 
    3407             : {
    3408        5505 :     if (m_bInFlushCache)
    3409        2217 :         return CE_None;
    3410        3288 :     m_bInFlushCache = true;
    3411        3288 :     if (hDB && eAccess == GA_ReadOnly && bAtClosing)
    3412             :     {
    3413             :         // Clean-up metadata that will go to PAM by removing items that
    3414             :         // are reconstructed.
    3415        2410 :         CPLStringList aosMD;
    3416        1864 :         for (CSLConstList papszIter = GetMetadata(); papszIter && *papszIter;
    3417             :              ++papszIter)
    3418             :         {
    3419         659 :             char *pszKey = nullptr;
    3420         659 :             CPLParseNameValue(*papszIter, &pszKey);
    3421        1318 :             if (pszKey &&
    3422         659 :                 (EQUAL(pszKey, "AREA_OR_POINT") ||
    3423         505 :                  EQUAL(pszKey, "IDENTIFIER") || EQUAL(pszKey, "DESCRIPTION") ||
    3424         270 :                  EQUAL(pszKey, "ZOOM_LEVEL") ||
    3425         689 :                  STARTS_WITH(pszKey, "GPKG_METADATA_ITEM_")))
    3426             :             {
    3427             :                 // remove it
    3428             :             }
    3429             :             else
    3430             :             {
    3431          30 :                 aosMD.AddString(*papszIter);
    3432             :             }
    3433         659 :             CPLFree(pszKey);
    3434             :         }
    3435        1205 :         oMDMD.SetMetadata(aosMD.List());
    3436        1205 :         oMDMD.SetMetadata(nullptr, GDAL_MDD_IMAGE_STRUCTURE);
    3437             : 
    3438        2410 :         GDALPamDataset::FlushCache(bAtClosing);
    3439             :     }
    3440             :     else
    3441             :     {
    3442             :         // Short circuit GDALPamDataset to avoid serialization to .aux.xml
    3443        2083 :         GDALDataset::FlushCache(bAtClosing);
    3444             :     }
    3445             : 
    3446        7859 :     for (auto &poLayer : m_apoLayers)
    3447             :     {
    3448        4571 :         poLayer->RunDeferredCreationIfNecessary();
    3449        4571 :         poLayer->CreateSpatialIndexIfNecessary();
    3450             :     }
    3451             : 
    3452             :     // Update raster table last_change column in gpkg_contents if needed
    3453        3288 :     if (m_bHasModifiedTiles)
    3454             :     {
    3455         554 :         for (int i = 1; i <= nBands; ++i)
    3456             :         {
    3457             :             auto poBand =
    3458         367 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    3459         367 :             if (!poBand->HaveStatsMetadataBeenSetInThisSession())
    3460             :             {
    3461         353 :                 poBand->InvalidateStatistics();
    3462         353 :                 if (psPam && psPam->pszPamFilename)
    3463         353 :                     VSIUnlink(psPam->pszPamFilename);
    3464             :             }
    3465             :         }
    3466             : 
    3467         187 :         UpdateGpkgContentsLastChange(m_osRasterTable);
    3468             : 
    3469         187 :         m_bHasModifiedTiles = false;
    3470             :     }
    3471             : 
    3472        3288 :     CPLErr eErr = FlushTiles();
    3473             : 
    3474        3288 :     m_bInFlushCache = false;
    3475        3288 :     return eErr;
    3476             : }
    3477             : 
    3478             : /************************************************************************/
    3479             : /*                      GetCurrentDateEscapedSQL()                      */
    3480             : /************************************************************************/
    3481             : 
    3482        2519 : std::string GDALGeoPackageDataset::GetCurrentDateEscapedSQL()
    3483             : {
    3484             :     const char *pszCurrentDate =
    3485        2519 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3486        2519 :     if (pszCurrentDate)
    3487          14 :         return '\'' + SQLEscapeLiteral(pszCurrentDate) + '\'';
    3488        2512 :     return "strftime('%Y-%m-%dT%H:%M:%fZ','now')";
    3489             : }
    3490             : 
    3491             : /************************************************************************/
    3492             : /*                    UpdateGpkgContentsLastChange()                    */
    3493             : /************************************************************************/
    3494             : 
    3495             : OGRErr
    3496        1068 : GDALGeoPackageDataset::UpdateGpkgContentsLastChange(const char *pszTableName)
    3497             : {
    3498             :     char *pszSQL =
    3499        1068 :         sqlite3_mprintf("UPDATE gpkg_contents SET "
    3500             :                         "last_change = %s "
    3501             :                         "WHERE lower(table_name) = lower('%q')",
    3502        2136 :                         GetCurrentDateEscapedSQL().c_str(), pszTableName);
    3503        1068 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    3504        1068 :     sqlite3_free(pszSQL);
    3505        1068 :     return eErr;
    3506             : }
    3507             : 
    3508             : /************************************************************************/
    3509             : /*                          IBuildOverviews()                           */
    3510             : /************************************************************************/
    3511             : 
    3512          20 : CPLErr GDALGeoPackageDataset::IBuildOverviews(
    3513             :     const char *pszResampling, int nOverviews, const int *panOverviewList,
    3514             :     int nBandsIn, const int * /*panBandList*/, GDALProgressFunc pfnProgress,
    3515             :     void *pProgressData, CSLConstList papszOptions)
    3516             : {
    3517          20 :     if (GetAccess() != GA_Update)
    3518             :     {
    3519           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3520             :                  "Overview building not supported on a database opened in "
    3521             :                  "read-only mode");
    3522           1 :         return CE_Failure;
    3523             :     }
    3524          19 :     if (m_poParentDS != nullptr)
    3525             :     {
    3526           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3527             :                  "Overview building not supported on overview dataset");
    3528           1 :         return CE_Failure;
    3529             :     }
    3530             : 
    3531          18 :     if (nOverviews == 0)
    3532             :     {
    3533           5 :         for (auto &poOvrDS : m_apoOverviewDS)
    3534           3 :             poOvrDS->FlushCache(false);
    3535             : 
    3536           2 :         SoftStartTransaction();
    3537             : 
    3538           2 :         if (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    3539             :         {
    3540           1 :             char *pszSQL = sqlite3_mprintf(
    3541             :                 "DELETE FROM gpkg_2d_gridded_tile_ancillary WHERE id IN "
    3542             :                 "(SELECT y.id FROM \"%w\" x "
    3543             :                 "JOIN gpkg_2d_gridded_tile_ancillary y "
    3544             :                 "ON x.id = y.tpudt_id AND y.tpudt_name = '%q' AND "
    3545             :                 "x.zoom_level < %d)",
    3546             :                 m_osRasterTable.c_str(), m_osRasterTable.c_str(), m_nZoomLevel);
    3547           1 :             OGRErr eErr = SQLCommand(hDB, pszSQL);
    3548           1 :             sqlite3_free(pszSQL);
    3549           1 :             if (eErr != OGRERR_NONE)
    3550             :             {
    3551           0 :                 SoftRollbackTransaction();
    3552           0 :                 return CE_Failure;
    3553             :             }
    3554             :         }
    3555             : 
    3556             :         char *pszSQL =
    3557           2 :             sqlite3_mprintf("DELETE FROM \"%w\" WHERE zoom_level < %d",
    3558             :                             m_osRasterTable.c_str(), m_nZoomLevel);
    3559           2 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3560           2 :         sqlite3_free(pszSQL);
    3561           2 :         if (eErr != OGRERR_NONE)
    3562             :         {
    3563           0 :             SoftRollbackTransaction();
    3564           0 :             return CE_Failure;
    3565             :         }
    3566             : 
    3567           2 :         SoftCommitTransaction();
    3568             : 
    3569           2 :         return CE_None;
    3570             :     }
    3571             : 
    3572          16 :     if (nBandsIn != nBands)
    3573             :     {
    3574           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3575             :                  "Generation of overviews in GPKG only"
    3576             :                  "supported when operating on all bands.");
    3577           0 :         return CE_Failure;
    3578             :     }
    3579             : 
    3580          16 :     if (m_apoOverviewDS.empty())
    3581             :     {
    3582           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3583             :                  "Image too small to support overviews");
    3584           0 :         return CE_Failure;
    3585             :     }
    3586             : 
    3587          16 :     FlushCache(false);
    3588          60 :     for (int i = 0; i < nOverviews; i++)
    3589             :     {
    3590          47 :         if (panOverviewList[i] < 2)
    3591             :         {
    3592           1 :             CPLError(CE_Failure, CPLE_IllegalArg,
    3593             :                      "Overview factor must be >= 2");
    3594           1 :             return CE_Failure;
    3595             :         }
    3596             : 
    3597          46 :         bool bFound = false;
    3598          46 :         int jCandidate = -1;
    3599          46 :         int nMaxOvFactor = 0;
    3600         196 :         for (int j = 0; j < static_cast<int>(m_apoOverviewDS.size()); j++)
    3601             :         {
    3602         190 :             const auto poODS = m_apoOverviewDS[j].get();
    3603             :             const int nOvFactor =
    3604         190 :                 static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3605             : 
    3606         190 :             nMaxOvFactor = nOvFactor;
    3607             : 
    3608         190 :             if (nOvFactor == panOverviewList[i])
    3609             :             {
    3610          40 :                 bFound = true;
    3611          40 :                 break;
    3612             :             }
    3613             : 
    3614         150 :             if (jCandidate < 0 && nOvFactor > panOverviewList[i])
    3615           1 :                 jCandidate = j;
    3616             :         }
    3617             : 
    3618          46 :         if (!bFound)
    3619             :         {
    3620             :             /* Mostly for debug */
    3621           6 :             if (!CPLTestBool(CPLGetConfigOption(
    3622             :                     "ALLOW_GPKG_ZOOM_OTHER_EXTENSION", "YES")))
    3623             :             {
    3624           2 :                 CPLString osOvrList;
    3625           4 :                 for (const auto &poODS : m_apoOverviewDS)
    3626             :                 {
    3627             :                     const int nOvFactor =
    3628           2 :                         static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3629             : 
    3630           2 :                     if (!osOvrList.empty())
    3631           0 :                         osOvrList += ' ';
    3632           2 :                     osOvrList += CPLSPrintf("%d", nOvFactor);
    3633             :                 }
    3634           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    3635             :                          "Only overviews %s can be computed",
    3636             :                          osOvrList.c_str());
    3637           2 :                 return CE_Failure;
    3638             :             }
    3639             :             else
    3640             :             {
    3641           4 :                 int nOvFactor = panOverviewList[i];
    3642           4 :                 if (jCandidate < 0)
    3643           3 :                     jCandidate = static_cast<int>(m_apoOverviewDS.size());
    3644             : 
    3645           4 :                 int nOvXSize = std::max(1, GetRasterXSize() / nOvFactor);
    3646           4 :                 int nOvYSize = std::max(1, GetRasterYSize() / nOvFactor);
    3647           4 :                 if (!(jCandidate == static_cast<int>(m_apoOverviewDS.size()) &&
    3648           5 :                       nOvFactor == 2 * nMaxOvFactor) &&
    3649           1 :                     !m_bZoomOther)
    3650             :                 {
    3651           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    3652             :                              "Use of overview factor %d causes gpkg_zoom_other "
    3653             :                              "extension to be needed",
    3654             :                              nOvFactor);
    3655           1 :                     RegisterZoomOtherExtension();
    3656           1 :                     m_bZoomOther = true;
    3657             :                 }
    3658             : 
    3659           4 :                 SoftStartTransaction();
    3660             : 
    3661           4 :                 CPLAssert(jCandidate > 0);
    3662             :                 const int nNewZoomLevel =
    3663           4 :                     m_apoOverviewDS[jCandidate - 1]->m_nZoomLevel;
    3664             : 
    3665             :                 char *pszSQL;
    3666             :                 OGRErr eErr;
    3667          24 :                 for (int k = 0; k <= jCandidate; k++)
    3668             :                 {
    3669          60 :                     pszSQL = sqlite3_mprintf(
    3670             :                         "UPDATE gpkg_tile_matrix SET zoom_level = %d "
    3671             :                         "WHERE lower(table_name) = lower('%q') AND zoom_level "
    3672             :                         "= %d",
    3673          20 :                         m_nZoomLevel - k + 1, m_osRasterTable.c_str(),
    3674          20 :                         m_nZoomLevel - k);
    3675          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3676          20 :                     sqlite3_free(pszSQL);
    3677          20 :                     if (eErr != OGRERR_NONE)
    3678             :                     {
    3679           0 :                         SoftRollbackTransaction();
    3680           0 :                         return CE_Failure;
    3681             :                     }
    3682             : 
    3683             :                     pszSQL =
    3684          20 :                         sqlite3_mprintf("UPDATE \"%w\" SET zoom_level = %d "
    3685             :                                         "WHERE zoom_level = %d",
    3686             :                                         m_osRasterTable.c_str(),
    3687          20 :                                         m_nZoomLevel - k + 1, m_nZoomLevel - k);
    3688          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3689          20 :                     sqlite3_free(pszSQL);
    3690          20 :                     if (eErr != OGRERR_NONE)
    3691             :                     {
    3692           0 :                         SoftRollbackTransaction();
    3693           0 :                         return CE_Failure;
    3694             :                     }
    3695             :                 }
    3696             : 
    3697           4 :                 double dfGDALMinX = m_gt[0];
    3698           4 :                 double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3699           4 :                 double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3700           4 :                 double dfGDALMaxY = m_gt[3];
    3701           4 :                 double dfPixelXSizeZoomLevel = m_gt[1] * nOvFactor;
    3702           4 :                 double dfPixelYSizeZoomLevel = fabs(m_gt[5]) * nOvFactor;
    3703             :                 int nTileWidth, nTileHeight;
    3704           4 :                 GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3705           4 :                 int nTileMatrixWidth = DIV_ROUND_UP(nOvXSize, nTileWidth);
    3706           4 :                 int nTileMatrixHeight = DIV_ROUND_UP(nOvYSize, nTileHeight);
    3707           4 :                 pszSQL = sqlite3_mprintf(
    3708             :                     "INSERT INTO gpkg_tile_matrix "
    3709             :                     "(table_name,zoom_level,matrix_width,matrix_height,tile_"
    3710             :                     "width,tile_height,pixel_x_size,pixel_y_size) VALUES "
    3711             :                     "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3712             :                     m_osRasterTable.c_str(), nNewZoomLevel, nTileMatrixWidth,
    3713             :                     nTileMatrixHeight, nTileWidth, nTileHeight,
    3714             :                     dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel);
    3715           4 :                 eErr = SQLCommand(hDB, pszSQL);
    3716           4 :                 sqlite3_free(pszSQL);
    3717           4 :                 if (eErr != OGRERR_NONE)
    3718             :                 {
    3719           0 :                     SoftRollbackTransaction();
    3720           0 :                     return CE_Failure;
    3721             :                 }
    3722             : 
    3723           4 :                 SoftCommitTransaction();
    3724             : 
    3725           4 :                 m_nZoomLevel++; /* this change our zoom level as well as
    3726             :                                    previous overviews */
    3727          20 :                 for (int k = 0; k < jCandidate; k++)
    3728          16 :                     m_apoOverviewDS[k]->m_nZoomLevel++;
    3729             : 
    3730           4 :                 auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3731           4 :                 poOvrDS->ShareLockWithParentDataset(this);
    3732           4 :                 poOvrDS->InitRaster(
    3733             :                     this, m_osRasterTable, nNewZoomLevel, nBands, m_dfTMSMinX,
    3734             :                     m_dfTMSMaxY, dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel,
    3735             :                     nTileWidth, nTileHeight, nTileMatrixWidth,
    3736             :                     nTileMatrixHeight, dfGDALMinX, dfGDALMinY, dfGDALMaxX,
    3737             :                     dfGDALMaxY);
    3738           4 :                 m_apoOverviewDS.insert(m_apoOverviewDS.begin() + jCandidate,
    3739           8 :                                        std::move(poOvrDS));
    3740             :             }
    3741             :         }
    3742             :     }
    3743             : 
    3744             :     GDALRasterBand ***papapoOverviewBands = static_cast<GDALRasterBand ***>(
    3745          13 :         CPLCalloc(sizeof(GDALRasterBand **), nBands));
    3746          13 :     CPLErr eErr = CE_None;
    3747          49 :     for (int iBand = 0; eErr == CE_None && iBand < nBands; iBand++)
    3748             :     {
    3749          72 :         papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
    3750          36 :             CPLCalloc(sizeof(GDALRasterBand *), nOverviews));
    3751          36 :         int iCurOverview = 0;
    3752         185 :         for (int i = 0; i < nOverviews; i++)
    3753             :         {
    3754         149 :             bool bFound = false;
    3755         724 :             for (const auto &poODS : m_apoOverviewDS)
    3756             :             {
    3757             :                 const int nOvFactor =
    3758         724 :                     static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3759             : 
    3760         724 :                 if (nOvFactor == panOverviewList[i])
    3761             :                 {
    3762         298 :                     papapoOverviewBands[iBand][iCurOverview] =
    3763         149 :                         poODS->GetRasterBand(iBand + 1);
    3764         149 :                     iCurOverview++;
    3765         149 :                     bFound = true;
    3766         149 :                     break;
    3767             :                 }
    3768             :             }
    3769         149 :             if (!bFound)
    3770             :             {
    3771           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3772             :                          "Could not find dataset corresponding to ov factor %d",
    3773           0 :                          panOverviewList[i]);
    3774           0 :                 eErr = CE_Failure;
    3775             :             }
    3776             :         }
    3777          36 :         if (eErr == CE_None)
    3778             :         {
    3779          36 :             CPLAssert(iCurOverview == nOverviews);
    3780             :         }
    3781             :     }
    3782             : 
    3783          13 :     if (eErr == CE_None)
    3784          13 :         eErr = GDALRegenerateOverviewsMultiBand(
    3785          13 :             nBands, papoBands, nOverviews, papapoOverviewBands, pszResampling,
    3786             :             pfnProgress, pProgressData, papszOptions);
    3787             : 
    3788          49 :     for (int iBand = 0; iBand < nBands; iBand++)
    3789             :     {
    3790          36 :         CPLFree(papapoOverviewBands[iBand]);
    3791             :     }
    3792          13 :     CPLFree(papapoOverviewBands);
    3793             : 
    3794          13 :     return eErr;
    3795             : }
    3796             : 
    3797             : /************************************************************************/
    3798             : /*                            GetFileList()                             */
    3799             : /************************************************************************/
    3800             : 
    3801          38 : char **GDALGeoPackageDataset::GetFileList()
    3802             : {
    3803          38 :     TryLoadXML();
    3804          38 :     return GDALPamDataset::GetFileList();
    3805             : }
    3806             : 
    3807             : /************************************************************************/
    3808             : /*                       GetMetadataDomainList()                        */
    3809             : /************************************************************************/
    3810             : 
    3811          53 : char **GDALGeoPackageDataset::GetMetadataDomainList()
    3812             : {
    3813          53 :     GetMetadata();
    3814          53 :     if (!m_osRasterTable.empty())
    3815           5 :         GetMetadata("GEOPACKAGE");
    3816          53 :     return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
    3817          53 :                                    TRUE, GDAL_MDD_SUBDATASETS, nullptr);
    3818             : }
    3819             : 
    3820             : /************************************************************************/
    3821             : /*                        CheckMetadataDomain()                         */
    3822             : /************************************************************************/
    3823             : 
    3824        6930 : const char *GDALGeoPackageDataset::CheckMetadataDomain(const char *pszDomain)
    3825             : {
    3826        7121 :     if (pszDomain != nullptr && EQUAL(pszDomain, "GEOPACKAGE") &&
    3827         191 :         m_osRasterTable.empty())
    3828             :     {
    3829           4 :         CPLError(
    3830             :             CE_Warning, CPLE_IllegalArg,
    3831             :             "Using GEOPACKAGE for a non-raster geopackage is not supported. "
    3832             :             "Using default domain instead");
    3833           4 :         return nullptr;
    3834             :     }
    3835        6926 :     return pszDomain;
    3836             : }
    3837             : 
    3838             : /************************************************************************/
    3839             : /*                         HasMetadataTables()                          */
    3840             : /************************************************************************/
    3841             : 
    3842        6601 : bool GDALGeoPackageDataset::HasMetadataTables() const
    3843             : {
    3844        6601 :     if (m_nHasMetadataTables < 0)
    3845             :     {
    3846             :         const int nCount =
    3847        2508 :             SQLGetInteger(hDB,
    3848             :                           "SELECT COUNT(*) FROM sqlite_master WHERE name IN "
    3849             :                           "('gpkg_metadata', 'gpkg_metadata_reference') "
    3850             :                           "AND type IN ('table', 'view')",
    3851             :                           nullptr);
    3852        2508 :         m_nHasMetadataTables = nCount == 2;
    3853             :     }
    3854        6601 :     return CPL_TO_BOOL(m_nHasMetadataTables);
    3855             : }
    3856             : 
    3857             : /************************************************************************/
    3858             : /*                        HasDataColumnsTable()                         */
    3859             : /************************************************************************/
    3860             : 
    3861        1440 : bool GDALGeoPackageDataset::HasDataColumnsTable() const
    3862             : {
    3863        2880 :     const int nCount = SQLGetInteger(
    3864        1440 :         hDB,
    3865             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_data_columns'"
    3866             :         "AND type IN ('table', 'view')",
    3867             :         nullptr);
    3868        1440 :     return nCount == 1;
    3869             : }
    3870             : 
    3871             : /************************************************************************/
    3872             : /*                   HasDataColumnConstraintsTable()                    */
    3873             : /************************************************************************/
    3874             : 
    3875         169 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTable() const
    3876             : {
    3877         169 :     const int nCount = SQLGetInteger(hDB,
    3878             :                                      "SELECT 1 FROM sqlite_master WHERE name = "
    3879             :                                      "'gpkg_data_column_constraints'"
    3880             :                                      "AND type IN ('table', 'view')",
    3881             :                                      nullptr);
    3882         169 :     return nCount == 1;
    3883             : }
    3884             : 
    3885             : /************************************************************************/
    3886             : /*               HasDataColumnConstraintsTableGPKG_1_0()                */
    3887             : /************************************************************************/
    3888             : 
    3889         111 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTableGPKG_1_0() const
    3890             : {
    3891         111 :     if (m_nApplicationId != GP10_APPLICATION_ID)
    3892         109 :         return false;
    3893             :     // In GPKG 1.0, the columns were named minIsInclusive, maxIsInclusive
    3894             :     // They were changed in 1.1 to min_is_inclusive, max_is_inclusive
    3895           2 :     bool bRet = false;
    3896           2 :     sqlite3_stmt *hSQLStmt = nullptr;
    3897           2 :     int rc = sqlite3_prepare_v2(hDB,
    3898             :                                 "SELECT minIsInclusive, maxIsInclusive FROM "
    3899             :                                 "gpkg_data_column_constraints",
    3900             :                                 -1, &hSQLStmt, nullptr);
    3901           2 :     if (rc == SQLITE_OK)
    3902             :     {
    3903           2 :         bRet = true;
    3904           2 :         sqlite3_finalize(hSQLStmt);
    3905             :     }
    3906           2 :     return bRet;
    3907             : }
    3908             : 
    3909             : /************************************************************************/
    3910             : /*      CreateColumnsTableAndColumnConstraintsTablesIfNecessary()       */
    3911             : /************************************************************************/
    3912             : 
    3913          54 : bool GDALGeoPackageDataset::
    3914             :     CreateColumnsTableAndColumnConstraintsTablesIfNecessary()
    3915             : {
    3916          54 :     if (!HasDataColumnsTable())
    3917             :     {
    3918             :         // Geopackage < 1.3 had
    3919             :         // CONSTRAINT fk_gdc_tn FOREIGN KEY (table_name) REFERENCES
    3920             :         // gpkg_contents(table_name) instead of the unique constraint.
    3921          14 :         if (OGRERR_NONE !=
    3922          14 :             SQLCommand(
    3923             :                 GetDB(),
    3924             :                 "CREATE TABLE gpkg_data_columns ("
    3925             :                 "table_name TEXT NOT NULL,"
    3926             :                 "column_name TEXT NOT NULL,"
    3927             :                 "name TEXT,"
    3928             :                 "title TEXT,"
    3929             :                 "description TEXT,"
    3930             :                 "mime_type TEXT,"
    3931             :                 "constraint_name TEXT,"
    3932             :                 "CONSTRAINT pk_gdc PRIMARY KEY (table_name, column_name),"
    3933             :                 "CONSTRAINT gdc_tn UNIQUE (table_name, name));"))
    3934             :         {
    3935           0 :             return false;
    3936             :         }
    3937             :     }
    3938          54 :     if (!HasDataColumnConstraintsTable())
    3939             :     {
    3940          30 :         const char *min_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3941          15 :                                            ? "min_is_inclusive"
    3942             :                                            : "minIsInclusive";
    3943          30 :         const char *max_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3944          15 :                                            ? "max_is_inclusive"
    3945             :                                            : "maxIsInclusive";
    3946             : 
    3947             :         const std::string osSQL(
    3948             :             CPLSPrintf("CREATE TABLE gpkg_data_column_constraints ("
    3949             :                        "constraint_name TEXT NOT NULL,"
    3950             :                        "constraint_type TEXT NOT NULL,"
    3951             :                        "value TEXT,"
    3952             :                        "min NUMERIC,"
    3953             :                        "%s BOOLEAN,"
    3954             :                        "max NUMERIC,"
    3955             :                        "%s BOOLEAN,"
    3956             :                        "description TEXT,"
    3957             :                        "CONSTRAINT gdcc_ntv UNIQUE (constraint_name, "
    3958             :                        "constraint_type, value));",
    3959          15 :                        min_is_inclusive, max_is_inclusive));
    3960          15 :         if (OGRERR_NONE != SQLCommand(GetDB(), osSQL.c_str()))
    3961             :         {
    3962           0 :             return false;
    3963             :         }
    3964             :     }
    3965          54 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    3966             :     {
    3967           0 :         return false;
    3968             :     }
    3969          54 :     if (SQLGetInteger(GetDB(),
    3970             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3971             :                       "table_name = 'gpkg_data_columns'",
    3972          54 :                       nullptr) != 1)
    3973             :     {
    3974          15 :         if (OGRERR_NONE !=
    3975          15 :             SQLCommand(
    3976             :                 GetDB(),
    3977             :                 "INSERT INTO gpkg_extensions "
    3978             :                 "(table_name,column_name,extension_name,definition,scope) "
    3979             :                 "VALUES ('gpkg_data_columns', NULL, 'gpkg_schema', "
    3980             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    3981             :                 "'read-write')"))
    3982             :         {
    3983           0 :             return false;
    3984             :         }
    3985             :     }
    3986          54 :     if (SQLGetInteger(GetDB(),
    3987             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3988             :                       "table_name = 'gpkg_data_column_constraints'",
    3989          54 :                       nullptr) != 1)
    3990             :     {
    3991          15 :         if (OGRERR_NONE !=
    3992          15 :             SQLCommand(
    3993             :                 GetDB(),
    3994             :                 "INSERT INTO gpkg_extensions "
    3995             :                 "(table_name,column_name,extension_name,definition,scope) "
    3996             :                 "VALUES ('gpkg_data_column_constraints', NULL, 'gpkg_schema', "
    3997             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    3998             :                 "'read-write')"))
    3999             :         {
    4000           0 :             return false;
    4001             :         }
    4002             :     }
    4003             : 
    4004          54 :     return true;
    4005             : }
    4006             : 
    4007             : /************************************************************************/
    4008             : /*                      HasGpkgextRelationsTable()                      */
    4009             : /************************************************************************/
    4010             : 
    4011        1620 : bool GDALGeoPackageDataset::HasGpkgextRelationsTable() const
    4012             : {
    4013        3240 :     const int nCount = SQLGetInteger(
    4014        1620 :         hDB,
    4015             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkgext_relations'"
    4016             :         "AND type IN ('table', 'view')",
    4017             :         nullptr);
    4018        1620 :     return nCount == 1;
    4019             : }
    4020             : 
    4021             : /************************************************************************/
    4022             : /*                  CreateRelationsTableIfNecessary()                   */
    4023             : /************************************************************************/
    4024             : 
    4025          11 : bool GDALGeoPackageDataset::CreateRelationsTableIfNecessary()
    4026             : {
    4027          11 :     if (HasGpkgextRelationsTable())
    4028             :     {
    4029           6 :         return true;
    4030             :     }
    4031             : 
    4032           5 :     if (OGRERR_NONE !=
    4033           5 :         SQLCommand(GetDB(), "CREATE TABLE gpkgext_relations ("
    4034             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    4035             :                             "base_table_name TEXT NOT NULL,"
    4036             :                             "base_primary_column TEXT NOT NULL DEFAULT 'id',"
    4037             :                             "related_table_name TEXT NOT NULL,"
    4038             :                             "related_primary_column TEXT NOT NULL DEFAULT 'id',"
    4039             :                             "relation_name TEXT NOT NULL,"
    4040             :                             "mapping_table_name TEXT NOT NULL UNIQUE);"))
    4041             :     {
    4042           0 :         return false;
    4043             :     }
    4044             : 
    4045           5 :     return true;
    4046             : }
    4047             : 
    4048             : /************************************************************************/
    4049             : /*                         HasQGISLayerStyles()                         */
    4050             : /************************************************************************/
    4051             : 
    4052          11 : bool GDALGeoPackageDataset::HasQGISLayerStyles() const
    4053             : {
    4054             :     // QGIS layer_styles extension:
    4055             :     // https://github.com/pka/qgpkg/blob/master/qgis_geopackage_extension.md
    4056          11 :     bool bRet = false;
    4057             :     const int nCount =
    4058          11 :         SQLGetInteger(hDB,
    4059             :                       "SELECT 1 FROM sqlite_master WHERE name = 'layer_styles'"
    4060             :                       "AND type = 'table'",
    4061             :                       nullptr);
    4062          11 :     if (nCount == 1)
    4063             :     {
    4064           1 :         sqlite3_stmt *hSQLStmt = nullptr;
    4065           2 :         int rc = sqlite3_prepare_v2(
    4066           1 :             hDB, "SELECT f_table_name, f_geometry_column FROM layer_styles", -1,
    4067             :             &hSQLStmt, nullptr);
    4068           1 :         if (rc == SQLITE_OK)
    4069             :         {
    4070           1 :             bRet = true;
    4071           1 :             sqlite3_finalize(hSQLStmt);
    4072             :         }
    4073             :     }
    4074          11 :     return bRet;
    4075             : }
    4076             : 
    4077             : /************************************************************************/
    4078             : /*                            GetMetadata()                             */
    4079             : /************************************************************************/
    4080             : 
    4081        4546 : CSLConstList GDALGeoPackageDataset::GetMetadata(const char *pszDomain)
    4082             : 
    4083             : {
    4084        4546 :     pszDomain = CheckMetadataDomain(pszDomain);
    4085        4546 :     if (pszDomain != nullptr && EQUAL(pszDomain, GDAL_MDD_SUBDATASETS))
    4086          83 :         return m_aosSubDatasets.List();
    4087             : 
    4088        4463 :     if (m_bHasReadMetadataFromStorage)
    4089        2031 :         return GDALPamDataset::GetMetadata(pszDomain);
    4090             : 
    4091        2432 :     m_bHasReadMetadataFromStorage = true;
    4092             : 
    4093        2432 :     TryLoadXML();
    4094             : 
    4095        2432 :     if (!HasMetadataTables())
    4096        1837 :         return GDALPamDataset::GetMetadata(pszDomain);
    4097             : 
    4098         595 :     char *pszSQL = nullptr;
    4099         595 :     if (!m_osRasterTable.empty())
    4100             :     {
    4101         181 :         pszSQL = sqlite3_mprintf(
    4102             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4103             :             "mdr.reference_scope FROM gpkg_metadata md "
    4104             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4105             :             "WHERE "
    4106             :             "(mdr.reference_scope = 'geopackage' OR "
    4107             :             "(mdr.reference_scope = 'table' AND lower(mdr.table_name) = "
    4108             :             "lower('%q'))) ORDER BY md.id "
    4109             :             "LIMIT 1000",  // to avoid denial of service
    4110             :             m_osRasterTable.c_str());
    4111             :     }
    4112             :     else
    4113             :     {
    4114         414 :         pszSQL = sqlite3_mprintf(
    4115             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4116             :             "mdr.reference_scope FROM gpkg_metadata md "
    4117             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4118             :             "WHERE "
    4119             :             "mdr.reference_scope = 'geopackage' ORDER BY md.id "
    4120             :             "LIMIT 1000"  // to avoid denial of service
    4121             :         );
    4122             :     }
    4123             : 
    4124        1190 :     auto oResult = SQLQuery(hDB, pszSQL);
    4125         595 :     sqlite3_free(pszSQL);
    4126         595 :     if (!oResult)
    4127             :     {
    4128           0 :         return GDALPamDataset::GetMetadata(pszDomain);
    4129             :     }
    4130             : 
    4131         595 :     char **papszMetadata = CSLDuplicate(GDALPamDataset::GetMetadata());
    4132             : 
    4133             :     /* GDAL metadata */
    4134         796 :     for (int i = 0; i < oResult->RowCount(); i++)
    4135             :     {
    4136         201 :         const char *pszMetadata = oResult->GetValue(0, i);
    4137         201 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4138         201 :         const char *pszMimeType = oResult->GetValue(2, i);
    4139         201 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4140         201 :         if (pszMetadata && pszMDStandardURI && pszMimeType &&
    4141         201 :             pszReferenceScope && EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4142         185 :             EQUAL(pszMimeType, "text/xml"))
    4143             :         {
    4144         185 :             CPLXMLNode *psXMLNode = CPLParseXMLString(pszMetadata);
    4145         185 :             if (psXMLNode)
    4146             :             {
    4147         370 :                 GDALMultiDomainMetadata oLocalMDMD;
    4148         185 :                 oLocalMDMD.XMLInit(psXMLNode, FALSE);
    4149         355 :                 if (!m_osRasterTable.empty() &&
    4150         170 :                     EQUAL(pszReferenceScope, "geopackage"))
    4151             :                 {
    4152           6 :                     oMDMD.SetMetadata(oLocalMDMD.GetMetadata(), "GEOPACKAGE");
    4153             :                 }
    4154             :                 else
    4155             :                 {
    4156             :                     papszMetadata =
    4157         179 :                         CSLMerge(papszMetadata, oLocalMDMD.GetMetadata());
    4158         179 :                     CSLConstList papszDomainList = oLocalMDMD.GetDomainList();
    4159         179 :                     CSLConstList papszIter = papszDomainList;
    4160         482 :                     while (papszIter && *papszIter)
    4161             :                     {
    4162         303 :                         if (EQUAL(*papszIter, GDAL_MDD_IMAGE_STRUCTURE))
    4163             :                         {
    4164             :                             CSLConstList papszMD =
    4165         137 :                                 oLocalMDMD.GetMetadata(*papszIter);
    4166             :                             const char *pszBAND_COUNT =
    4167         137 :                                 CSLFetchNameValue(papszMD, "BAND_COUNT");
    4168         137 :                             if (pszBAND_COUNT)
    4169         135 :                                 m_nBandCountFromMetadata = atoi(pszBAND_COUNT);
    4170             : 
    4171             :                             const char *pszCOLOR_TABLE =
    4172         137 :                                 CSLFetchNameValue(papszMD, "COLOR_TABLE");
    4173         137 :                             if (pszCOLOR_TABLE)
    4174             :                             {
    4175             :                                 const CPLStringList aosTokens(
    4176             :                                     CSLTokenizeString2(pszCOLOR_TABLE, "{,",
    4177          26 :                                                        0));
    4178          13 :                                 if ((aosTokens.size() % 4) == 0)
    4179             :                                 {
    4180          13 :                                     const int nColors = aosTokens.size() / 4;
    4181             :                                     m_poCTFromMetadata =
    4182          13 :                                         std::make_unique<GDALColorTable>();
    4183        3341 :                                     for (int iColor = 0; iColor < nColors;
    4184             :                                          ++iColor)
    4185             :                                     {
    4186             :                                         GDALColorEntry sEntry;
    4187        3328 :                                         sEntry.c1 = static_cast<short>(
    4188        3328 :                                             atoi(aosTokens[4 * iColor + 0]));
    4189        3328 :                                         sEntry.c2 = static_cast<short>(
    4190        3328 :                                             atoi(aosTokens[4 * iColor + 1]));
    4191        3328 :                                         sEntry.c3 = static_cast<short>(
    4192        3328 :                                             atoi(aosTokens[4 * iColor + 2]));
    4193        3328 :                                         sEntry.c4 = static_cast<short>(
    4194        3328 :                                             atoi(aosTokens[4 * iColor + 3]));
    4195        3328 :                                         m_poCTFromMetadata->SetColorEntry(
    4196             :                                             iColor, &sEntry);
    4197             :                                     }
    4198             :                                 }
    4199             :                             }
    4200             : 
    4201             :                             const char *pszTILE_FORMAT =
    4202         137 :                                 CSLFetchNameValue(papszMD, "TILE_FORMAT");
    4203         137 :                             if (pszTILE_FORMAT)
    4204             :                             {
    4205           8 :                                 m_osTFFromMetadata = pszTILE_FORMAT;
    4206           8 :                                 oMDMD.SetMetadataItem("TILE_FORMAT",
    4207             :                                                       pszTILE_FORMAT,
    4208             :                                                       GDAL_MDD_IMAGE_STRUCTURE);
    4209             :                             }
    4210             : 
    4211             :                             const char *pszNodataValue =
    4212         137 :                                 CSLFetchNameValue(papszMD, "NODATA_VALUE");
    4213         137 :                             if (pszNodataValue)
    4214             :                             {
    4215           2 :                                 m_osNodataValueFromMetadata = pszNodataValue;
    4216             :                             }
    4217             :                         }
    4218             : 
    4219         166 :                         else if (!EQUAL(*papszIter, "") &&
    4220          21 :                                  !STARTS_WITH(*papszIter, "BAND_"))
    4221             :                         {
    4222          12 :                             oMDMD.SetMetadata(
    4223           6 :                                 oLocalMDMD.GetMetadata(*papszIter), *papszIter);
    4224             :                         }
    4225         303 :                         papszIter++;
    4226             :                     }
    4227             :                 }
    4228         185 :                 CPLDestroyXMLNode(psXMLNode);
    4229             :             }
    4230             :         }
    4231             :     }
    4232             : 
    4233         595 :     GDALPamDataset::SetMetadata(papszMetadata);
    4234         595 :     CSLDestroy(papszMetadata);
    4235         595 :     papszMetadata = nullptr;
    4236             : 
    4237             :     /* Add non-GDAL metadata now */
    4238         595 :     int nNonGDALMDILocal = 1;
    4239         595 :     int nNonGDALMDIGeopackage = 1;
    4240         796 :     for (int i = 0; i < oResult->RowCount(); i++)
    4241             :     {
    4242         201 :         const char *pszMetadata = oResult->GetValue(0, i);
    4243         201 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4244         201 :         const char *pszMimeType = oResult->GetValue(2, i);
    4245         201 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4246         201 :         if (pszMetadata == nullptr || pszMDStandardURI == nullptr ||
    4247         201 :             pszMimeType == nullptr || pszReferenceScope == nullptr)
    4248             :         {
    4249             :             // should not happen as there are NOT NULL constraints
    4250             :             // But a database could lack such NOT NULL constraints or have
    4251             :             // large values that would cause a memory allocation failure.
    4252           0 :             continue;
    4253             :         }
    4254         201 :         int bIsGPKGScope = EQUAL(pszReferenceScope, "geopackage");
    4255         201 :         if (EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4256         185 :             EQUAL(pszMimeType, "text/xml"))
    4257         185 :             continue;
    4258             : 
    4259          16 :         if (!m_osRasterTable.empty() && bIsGPKGScope)
    4260             :         {
    4261           8 :             oMDMD.SetMetadataItem(
    4262             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDIGeopackage),
    4263             :                 pszMetadata, "GEOPACKAGE");
    4264           8 :             nNonGDALMDIGeopackage++;
    4265             :         }
    4266             :         /*else if( strcmp( pszMDStandardURI, "http://www.isotc211.org/2005/gmd"
    4267             :         ) == 0 && strcmp( pszMimeType, "text/xml" ) == 0 )
    4268             :         {
    4269             :             char* apszMD[2];
    4270             :             apszMD[0] = (char*)pszMetadata;
    4271             :             apszMD[1] = NULL;
    4272             :             oMDMD.SetMetadata(apszMD, "xml:MD_Metadata");
    4273             :         }*/
    4274             :         else
    4275             :         {
    4276           8 :             oMDMD.SetMetadataItem(
    4277             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDILocal),
    4278             :                 pszMetadata);
    4279           8 :             nNonGDALMDILocal++;
    4280             :         }
    4281             :     }
    4282             : 
    4283         595 :     return GDALPamDataset::GetMetadata(pszDomain);
    4284             : }
    4285             : 
    4286             : /************************************************************************/
    4287             : /*                           WriteMetadata()                            */
    4288             : /************************************************************************/
    4289             : 
    4290         890 : void GDALGeoPackageDataset::WriteMetadata(
    4291             :     CPLXMLNode *psXMLNode, /* will be destroyed by the method */
    4292             :     const char *pszTableName)
    4293             : {
    4294         890 :     const bool bIsEmpty = (psXMLNode == nullptr);
    4295         890 :     if (!HasMetadataTables())
    4296             :     {
    4297         680 :         if (bIsEmpty || !CreateMetadataTables())
    4298             :         {
    4299         314 :             CPLDestroyXMLNode(psXMLNode);
    4300         314 :             return;
    4301             :         }
    4302             :     }
    4303             : 
    4304         576 :     char *pszXML = nullptr;
    4305         576 :     if (!bIsEmpty)
    4306             :     {
    4307             :         CPLXMLNode *psMasterXMLNode =
    4308         416 :             CPLCreateXMLNode(nullptr, CXT_Element, "GDALMultiDomainMetadata");
    4309         416 :         psMasterXMLNode->psChild = psXMLNode;
    4310         416 :         pszXML = CPLSerializeXMLTree(psMasterXMLNode);
    4311         416 :         CPLDestroyXMLNode(psMasterXMLNode);
    4312             :     }
    4313             :     // cppcheck-suppress uselessAssignmentPtrArg
    4314         576 :     psXMLNode = nullptr;
    4315             : 
    4316         576 :     char *pszSQL = nullptr;
    4317         576 :     if (pszTableName && pszTableName[0] != '\0')
    4318             :     {
    4319         424 :         pszSQL = sqlite3_mprintf(
    4320             :             "SELECT md.id FROM gpkg_metadata md "
    4321             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4322             :             "WHERE md.md_scope = 'dataset' AND "
    4323             :             "md.md_standard_uri='http://gdal.org' "
    4324             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = 'table' AND "
    4325             :             "lower(mdr.table_name) = lower('%q')",
    4326             :             pszTableName);
    4327             :     }
    4328             :     else
    4329             :     {
    4330         152 :         pszSQL = sqlite3_mprintf(
    4331             :             "SELECT md.id FROM gpkg_metadata md "
    4332             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4333             :             "WHERE md.md_scope = 'dataset' AND "
    4334             :             "md.md_standard_uri='http://gdal.org' "
    4335             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = "
    4336             :             "'geopackage'");
    4337             :     }
    4338             :     OGRErr err;
    4339         576 :     int mdId = SQLGetInteger(hDB, pszSQL, &err);
    4340         576 :     if (err != OGRERR_NONE)
    4341         543 :         mdId = -1;
    4342         576 :     sqlite3_free(pszSQL);
    4343             : 
    4344         576 :     if (bIsEmpty)
    4345             :     {
    4346         160 :         if (mdId >= 0)
    4347             :         {
    4348           6 :             SQLCommand(
    4349             :                 hDB,
    4350             :                 CPLSPrintf(
    4351             :                     "DELETE FROM gpkg_metadata_reference WHERE md_file_id = %d",
    4352             :                     mdId));
    4353           6 :             SQLCommand(
    4354             :                 hDB,
    4355             :                 CPLSPrintf("DELETE FROM gpkg_metadata WHERE id = %d", mdId));
    4356             :         }
    4357             :     }
    4358             :     else
    4359             :     {
    4360         416 :         if (mdId >= 0)
    4361             :         {
    4362          27 :             pszSQL = sqlite3_mprintf(
    4363             :                 "UPDATE gpkg_metadata SET metadata = '%q' WHERE id = %d",
    4364             :                 pszXML, mdId);
    4365             :         }
    4366             :         else
    4367             :         {
    4368             :             pszSQL =
    4369         389 :                 sqlite3_mprintf("INSERT INTO gpkg_metadata (md_scope, "
    4370             :                                 "md_standard_uri, mime_type, metadata) VALUES "
    4371             :                                 "('dataset','http://gdal.org','text/xml','%q')",
    4372             :                                 pszXML);
    4373             :         }
    4374         416 :         SQLCommand(hDB, pszSQL);
    4375         416 :         sqlite3_free(pszSQL);
    4376             : 
    4377         416 :         CPLFree(pszXML);
    4378             : 
    4379         416 :         if (mdId < 0)
    4380             :         {
    4381         389 :             const sqlite_int64 nFID = sqlite3_last_insert_rowid(hDB);
    4382         389 :             if (pszTableName != nullptr && pszTableName[0] != '\0')
    4383             :             {
    4384         377 :                 pszSQL = sqlite3_mprintf(
    4385             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4386             :                     "table_name, timestamp, md_file_id) VALUES "
    4387             :                     "('table', '%q', %s, %d)",
    4388         754 :                     pszTableName, GetCurrentDateEscapedSQL().c_str(),
    4389             :                     static_cast<int>(nFID));
    4390             :             }
    4391             :             else
    4392             :             {
    4393          12 :                 pszSQL = sqlite3_mprintf(
    4394             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4395             :                     "timestamp, md_file_id) VALUES "
    4396             :                     "('geopackage', %s, %d)",
    4397          24 :                     GetCurrentDateEscapedSQL().c_str(), static_cast<int>(nFID));
    4398             :             }
    4399             :         }
    4400             :         else
    4401             :         {
    4402          27 :             pszSQL = sqlite3_mprintf("UPDATE gpkg_metadata_reference SET "
    4403             :                                      "timestamp = %s WHERE md_file_id = %d",
    4404          54 :                                      GetCurrentDateEscapedSQL().c_str(), mdId);
    4405             :         }
    4406         416 :         SQLCommand(hDB, pszSQL);
    4407         416 :         sqlite3_free(pszSQL);
    4408             :     }
    4409             : }
    4410             : 
    4411             : /************************************************************************/
    4412             : /*                        CreateMetadataTables()                        */
    4413             : /************************************************************************/
    4414             : 
    4415         385 : bool GDALGeoPackageDataset::CreateMetadataTables()
    4416             : {
    4417             :     const bool bCreateTriggers =
    4418         385 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "NO"));
    4419             : 
    4420             :     /* From C.10. gpkg_metadata Table 35. gpkg_metadata Table Definition SQL  */
    4421             :     CPLString osSQL = "CREATE TABLE gpkg_metadata ("
    4422             :                       "id INTEGER CONSTRAINT m_pk PRIMARY KEY ASC NOT NULL,"
    4423             :                       "md_scope TEXT NOT NULL DEFAULT 'dataset',"
    4424             :                       "md_standard_uri TEXT NOT NULL,"
    4425             :                       "mime_type TEXT NOT NULL DEFAULT 'text/xml',"
    4426             :                       "metadata TEXT NOT NULL DEFAULT ''"
    4427         770 :                       ")";
    4428             : 
    4429             :     /* From D.2. metadata Table 40. metadata Trigger Definition SQL  */
    4430         385 :     const char *pszMetadataTriggers =
    4431             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_insert' "
    4432             :         "BEFORE INSERT ON 'gpkg_metadata' "
    4433             :         "FOR EACH ROW BEGIN "
    4434             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata violates "
    4435             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4436             :         "collectionSession | series | dataset | featureType | feature | "
    4437             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4438             :         "taxonomy software | service | collectionHardware | "
    4439             :         "nonGeographicDataset | dimensionGroup') "
    4440             :         "WHERE NOT(NEW.md_scope IN "
    4441             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4442             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4443             :         "'catalogue','schema','taxonomy','software','service', "
    4444             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4445             :         "END; "
    4446             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_update' "
    4447             :         "BEFORE UPDATE OF 'md_scope' ON 'gpkg_metadata' "
    4448             :         "FOR EACH ROW BEGIN "
    4449             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata violates "
    4450             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4451             :         "collectionSession | series | dataset | featureType | feature | "
    4452             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4453             :         "taxonomy software | service | collectionHardware | "
    4454             :         "nonGeographicDataset | dimensionGroup') "
    4455             :         "WHERE NOT(NEW.md_scope IN "
    4456             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4457             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4458             :         "'catalogue','schema','taxonomy','software','service', "
    4459             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4460             :         "END";
    4461         385 :     if (bCreateTriggers)
    4462             :     {
    4463           0 :         osSQL += ";";
    4464           0 :         osSQL += pszMetadataTriggers;
    4465             :     }
    4466             : 
    4467             :     /* From C.11. gpkg_metadata_reference Table 36. gpkg_metadata_reference
    4468             :      * Table Definition SQL */
    4469             :     osSQL += ";"
    4470             :              "CREATE TABLE gpkg_metadata_reference ("
    4471             :              "reference_scope TEXT NOT NULL,"
    4472             :              "table_name TEXT,"
    4473             :              "column_name TEXT,"
    4474             :              "row_id_value INTEGER,"
    4475             :              "timestamp DATETIME NOT NULL DEFAULT "
    4476             :              "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    4477             :              "md_file_id INTEGER NOT NULL,"
    4478             :              "md_parent_id INTEGER,"
    4479             :              "CONSTRAINT crmr_mfi_fk FOREIGN KEY (md_file_id) REFERENCES "
    4480             :              "gpkg_metadata(id),"
    4481             :              "CONSTRAINT crmr_mpi_fk FOREIGN KEY (md_parent_id) REFERENCES "
    4482             :              "gpkg_metadata(id)"
    4483         385 :              ")";
    4484             : 
    4485             :     /* From D.3. metadata_reference Table 41. gpkg_metadata_reference Trigger
    4486             :      * Definition SQL   */
    4487         385 :     const char *pszMetadataReferenceTriggers =
    4488             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_insert' "
    4489             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4490             :         "FOR EACH ROW BEGIN "
    4491             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4492             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4493             :         "table\", \"column\", \"row\", \"row/col\"') "
    4494             :         "WHERE NOT NEW.reference_scope IN "
    4495             :         "('geopackage','table','column','row','row/col'); "
    4496             :         "END; "
    4497             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_update' "
    4498             :         "BEFORE UPDATE OF 'reference_scope' ON 'gpkg_metadata_reference' "
    4499             :         "FOR EACH ROW BEGIN "
    4500             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4501             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4502             :         "\"table\", \"column\", \"row\", \"row/col\"') "
    4503             :         "WHERE NOT NEW.reference_scope IN "
    4504             :         "('geopackage','table','column','row','row/col'); "
    4505             :         "END; "
    4506             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_insert' "
    4507             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4508             :         "FOR EACH ROW BEGIN "
    4509             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4510             :         "violates constraint: column name must be NULL when reference_scope "
    4511             :         "is \"geopackage\", \"table\" or \"row\"') "
    4512             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4513             :         "AND NEW.column_name IS NOT NULL); "
    4514             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4515             :         "violates constraint: column name must be defined for the specified "
    4516             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4517             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4518             :         "AND NOT NEW.table_name IN ( "
    4519             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4520             :         "AND name = NEW.table_name "
    4521             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4522             :         "END; "
    4523             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_update' "
    4524             :         "BEFORE UPDATE OF column_name ON 'gpkg_metadata_reference' "
    4525             :         "FOR EACH ROW BEGIN "
    4526             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4527             :         "violates constraint: column name must be NULL when reference_scope "
    4528             :         "is \"geopackage\", \"table\" or \"row\"') "
    4529             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4530             :         "AND NEW.column_name IS NOT NULL); "
    4531             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4532             :         "violates constraint: column name must be defined for the specified "
    4533             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4534             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4535             :         "AND NOT NEW.table_name IN ( "
    4536             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4537             :         "AND name = NEW.table_name "
    4538             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4539             :         "END; "
    4540             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_insert' "
    4541             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4542             :         "FOR EACH ROW BEGIN "
    4543             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4544             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4545             :         "is \"geopackage\", \"table\" or \"column\"') "
    4546             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4547             :         "AND NEW.row_id_value IS NOT NULL; "
    4548             :         "END; "
    4549             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_update' "
    4550             :         "BEFORE UPDATE OF 'row_id_value' ON 'gpkg_metadata_reference' "
    4551             :         "FOR EACH ROW BEGIN "
    4552             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4553             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4554             :         "is \"geopackage\", \"table\" or \"column\"') "
    4555             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4556             :         "AND NEW.row_id_value IS NOT NULL; "
    4557             :         "END; "
    4558             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_insert' "
    4559             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4560             :         "FOR EACH ROW BEGIN "
    4561             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4562             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4563             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4564             :         "WHERE NOT (NEW.timestamp GLOB "
    4565             :         "'[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-"
    4566             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4567             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4568             :         "END; "
    4569             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_update' "
    4570             :         "BEFORE UPDATE OF 'timestamp' ON 'gpkg_metadata_reference' "
    4571             :         "FOR EACH ROW BEGIN "
    4572             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4573             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4574             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4575             :         "WHERE NOT (NEW.timestamp GLOB "
    4576             :         "'[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-"
    4577             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4578             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4579             :         "END";
    4580         385 :     if (bCreateTriggers)
    4581             :     {
    4582           0 :         osSQL += ";";
    4583           0 :         osSQL += pszMetadataReferenceTriggers;
    4584             :     }
    4585             : 
    4586         385 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    4587           2 :         return false;
    4588             : 
    4589         383 :     osSQL += ";";
    4590             :     osSQL += "INSERT INTO gpkg_extensions "
    4591             :              "(table_name, column_name, extension_name, definition, scope) "
    4592             :              "VALUES "
    4593             :              "('gpkg_metadata', NULL, 'gpkg_metadata', "
    4594             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4595         383 :              "'read-write')";
    4596             : 
    4597         383 :     osSQL += ";";
    4598             :     osSQL += "INSERT INTO gpkg_extensions "
    4599             :              "(table_name, column_name, extension_name, definition, scope) "
    4600             :              "VALUES "
    4601             :              "('gpkg_metadata_reference', NULL, 'gpkg_metadata', "
    4602             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4603         383 :              "'read-write')";
    4604             : 
    4605         383 :     const bool bOK = SQLCommand(hDB, osSQL) == OGRERR_NONE;
    4606         383 :     m_nHasMetadataTables = bOK;
    4607         383 :     return bOK;
    4608             : }
    4609             : 
    4610             : /************************************************************************/
    4611             : /*                           FlushMetadata()                            */
    4612             : /************************************************************************/
    4613             : 
    4614        9400 : void GDALGeoPackageDataset::FlushMetadata()
    4615             : {
    4616        9400 :     if (!m_bMetadataDirty || m_poParentDS != nullptr ||
    4617         445 :         m_nCreateMetadataTables == FALSE)
    4618        8961 :         return;
    4619         439 :     m_bMetadataDirty = false;
    4620             : 
    4621         439 :     if (eAccess == GA_ReadOnly)
    4622             :     {
    4623           3 :         return;
    4624             :     }
    4625             : 
    4626         436 :     bool bCanWriteAreaOrPoint =
    4627         870 :         !m_bGridCellEncodingAsCO &&
    4628         434 :         (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT);
    4629         436 :     if (!m_osRasterTable.empty())
    4630             :     {
    4631             :         const char *pszIdentifier =
    4632         150 :             GDALGeoPackageDataset::GetMetadataItem("IDENTIFIER");
    4633             :         const char *pszDescription =
    4634         150 :             GDALGeoPackageDataset::GetMetadataItem("DESCRIPTION");
    4635         182 :         if (!m_bIdentifierAsCO && pszIdentifier != nullptr &&
    4636          32 :             pszIdentifier != m_osIdentifier)
    4637             :         {
    4638          14 :             m_osIdentifier = pszIdentifier;
    4639             :             char *pszSQL =
    4640          14 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4641             :                                 "WHERE lower(table_name) = lower('%q')",
    4642             :                                 pszIdentifier, m_osRasterTable.c_str());
    4643          14 :             SQLCommand(hDB, pszSQL);
    4644          14 :             sqlite3_free(pszSQL);
    4645             :         }
    4646         157 :         if (!m_bDescriptionAsCO && pszDescription != nullptr &&
    4647           7 :             pszDescription != m_osDescription)
    4648             :         {
    4649           7 :             m_osDescription = pszDescription;
    4650             :             char *pszSQL =
    4651           7 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4652             :                                 "WHERE lower(table_name) = lower('%q')",
    4653             :                                 pszDescription, m_osRasterTable.c_str());
    4654           7 :             SQLCommand(hDB, pszSQL);
    4655           7 :             sqlite3_free(pszSQL);
    4656             :         }
    4657         150 :         if (bCanWriteAreaOrPoint)
    4658             :         {
    4659             :             const char *pszAreaOrPoint =
    4660          28 :                 GDALGeoPackageDataset::GetMetadataItem(GDALMD_AREA_OR_POINT);
    4661          28 :             if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_AREA))
    4662             :             {
    4663          23 :                 bCanWriteAreaOrPoint = false;
    4664          23 :                 char *pszSQL = sqlite3_mprintf(
    4665             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4666             :                     "grid_cell_encoding = 'grid-value-is-area' WHERE "
    4667             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4668             :                     m_osRasterTable.c_str());
    4669          23 :                 SQLCommand(hDB, pszSQL);
    4670          23 :                 sqlite3_free(pszSQL);
    4671             :             }
    4672           5 :             else if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_POINT))
    4673             :             {
    4674           1 :                 bCanWriteAreaOrPoint = false;
    4675           1 :                 char *pszSQL = sqlite3_mprintf(
    4676             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4677             :                     "grid_cell_encoding = 'grid-value-is-center' WHERE "
    4678             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4679             :                     m_osRasterTable.c_str());
    4680           1 :                 SQLCommand(hDB, pszSQL);
    4681           1 :                 sqlite3_free(pszSQL);
    4682             :             }
    4683             :         }
    4684             :     }
    4685             : 
    4686         436 :     char **papszMDDup = nullptr;
    4687         211 :     for (const char *pszKeyValue :
    4688         858 :          cpl::Iterate(GDALGeoPackageDataset::GetMetadata()))
    4689             :     {
    4690         211 :         if (STARTS_WITH_CI(pszKeyValue, "IDENTIFIER="))
    4691          32 :             continue;
    4692         179 :         if (STARTS_WITH_CI(pszKeyValue, "DESCRIPTION="))
    4693           8 :             continue;
    4694         171 :         if (STARTS_WITH_CI(pszKeyValue, "ZOOM_LEVEL="))
    4695          14 :             continue;
    4696         157 :         if (STARTS_WITH_CI(pszKeyValue, "GPKG_METADATA_ITEM_"))
    4697           4 :             continue;
    4698         153 :         if ((m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT) &&
    4699          29 :             !bCanWriteAreaOrPoint &&
    4700          26 :             STARTS_WITH_CI(pszKeyValue, GDALMD_AREA_OR_POINT))
    4701             :         {
    4702          26 :             continue;
    4703             :         }
    4704         127 :         papszMDDup = CSLInsertString(papszMDDup, -1, pszKeyValue);
    4705             :     }
    4706             : 
    4707         436 :     CPLXMLNode *psXMLNode = nullptr;
    4708             :     {
    4709         436 :         GDALMultiDomainMetadata oLocalMDMD;
    4710         436 :         CSLConstList papszDomainList = oMDMD.GetDomainList();
    4711         436 :         CSLConstList papszIter = papszDomainList;
    4712         436 :         oLocalMDMD.SetMetadata(papszMDDup);
    4713         777 :         while (papszIter && *papszIter)
    4714             :         {
    4715         341 :             if (!EQUAL(*papszIter, "") &&
    4716         165 :                 !EQUAL(*papszIter, GDAL_MDD_IMAGE_STRUCTURE) &&
    4717          15 :                 !EQUAL(*papszIter, "GEOPACKAGE"))
    4718             :             {
    4719           8 :                 oLocalMDMD.SetMetadata(oMDMD.GetMetadata(*papszIter),
    4720             :                                        *papszIter);
    4721             :             }
    4722         341 :             papszIter++;
    4723             :         }
    4724         436 :         if (m_nBandCountFromMetadata > 0)
    4725             :         {
    4726          80 :             oLocalMDMD.SetMetadataItem(
    4727             :                 "BAND_COUNT", CPLSPrintf("%d", m_nBandCountFromMetadata),
    4728             :                 GDAL_MDD_IMAGE_STRUCTURE);
    4729          80 :             if (nBands == 1)
    4730             :             {
    4731          55 :                 const auto poCT = GetRasterBand(1)->GetColorTable();
    4732          55 :                 if (poCT)
    4733             :                 {
    4734          16 :                     std::string osVal("{");
    4735           8 :                     const int nColorCount = poCT->GetColorEntryCount();
    4736        2056 :                     for (int i = 0; i < nColorCount; ++i)
    4737             :                     {
    4738        2048 :                         if (i > 0)
    4739        2040 :                             osVal += ',';
    4740        2048 :                         const GDALColorEntry *psEntry = poCT->GetColorEntry(i);
    4741             :                         osVal +=
    4742        2048 :                             CPLSPrintf("{%d,%d,%d,%d}", psEntry->c1,
    4743        2048 :                                        psEntry->c2, psEntry->c3, psEntry->c4);
    4744             :                     }
    4745           8 :                     osVal += '}';
    4746           8 :                     oLocalMDMD.SetMetadataItem("COLOR_TABLE", osVal.c_str(),
    4747             :                                                GDAL_MDD_IMAGE_STRUCTURE);
    4748             :                 }
    4749             :             }
    4750          80 :             if (nBands == 1)
    4751             :             {
    4752          55 :                 const char *pszTILE_FORMAT = nullptr;
    4753          55 :                 switch (m_eTF)
    4754             :                 {
    4755           0 :                     case GPKG_TF_PNG_JPEG:
    4756           0 :                         pszTILE_FORMAT = "JPEG_PNG";
    4757           0 :                         break;
    4758          49 :                     case GPKG_TF_PNG:
    4759          49 :                         break;
    4760           0 :                     case GPKG_TF_PNG8:
    4761           0 :                         pszTILE_FORMAT = "PNG8";
    4762           0 :                         break;
    4763           3 :                     case GPKG_TF_JPEG:
    4764           3 :                         pszTILE_FORMAT = "JPEG";
    4765           3 :                         break;
    4766           3 :                     case GPKG_TF_WEBP:
    4767           3 :                         pszTILE_FORMAT = "WEBP";
    4768           3 :                         break;
    4769           0 :                     case GPKG_TF_PNG_16BIT:
    4770           0 :                         break;
    4771           0 :                     case GPKG_TF_TIFF_32BIT_FLOAT:
    4772           0 :                         break;
    4773             :                 }
    4774          55 :                 if (pszTILE_FORMAT)
    4775           6 :                     oLocalMDMD.SetMetadataItem("TILE_FORMAT", pszTILE_FORMAT,
    4776             :                                                GDAL_MDD_IMAGE_STRUCTURE);
    4777             :             }
    4778             :         }
    4779         586 :         if (GetRasterCount() > 0 &&
    4780         150 :             GetRasterBand(1)->GetRasterDataType() == GDT_UInt8)
    4781             :         {
    4782         120 :             int bHasNoData = FALSE;
    4783             :             const double dfNoDataValue =
    4784         120 :                 GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    4785         120 :             if (bHasNoData)
    4786             :             {
    4787           3 :                 oLocalMDMD.SetMetadataItem("NODATA_VALUE",
    4788             :                                            CPLSPrintf("%.17g", dfNoDataValue),
    4789             :                                            GDAL_MDD_IMAGE_STRUCTURE);
    4790             :             }
    4791             :         }
    4792         693 :         for (int i = 1; i <= GetRasterCount(); ++i)
    4793             :         {
    4794             :             auto poBand =
    4795         257 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    4796         257 :             poBand->AddImplicitStatistics(false);
    4797         257 :             CSLConstList papszMD = GetRasterBand(i)->GetMetadata();
    4798         257 :             poBand->AddImplicitStatistics(true);
    4799         257 :             if (papszMD)
    4800             :             {
    4801          18 :                 oLocalMDMD.SetMetadata(papszMD, CPLSPrintf("BAND_%d", i));
    4802             :             }
    4803             :         }
    4804         436 :         psXMLNode = oLocalMDMD.Serialize();
    4805             :     }
    4806             : 
    4807         436 :     CSLDestroy(papszMDDup);
    4808         436 :     papszMDDup = nullptr;
    4809             : 
    4810         436 :     WriteMetadata(psXMLNode, m_osRasterTable.c_str());
    4811             : 
    4812         436 :     if (!m_osRasterTable.empty())
    4813             :     {
    4814             :         CSLConstList papszGeopackageMD =
    4815         150 :             GDALGeoPackageDataset::GetMetadata("GEOPACKAGE");
    4816             : 
    4817         150 :         papszMDDup = nullptr;
    4818         150 :         for (CSLConstList papszIter = papszGeopackageMD;
    4819         159 :              papszIter && *papszIter; ++papszIter)
    4820             :         {
    4821           9 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4822             :         }
    4823             : 
    4824         300 :         GDALMultiDomainMetadata oLocalMDMD;
    4825         150 :         oLocalMDMD.SetMetadata(papszMDDup);
    4826         150 :         CSLDestroy(papszMDDup);
    4827         150 :         papszMDDup = nullptr;
    4828         150 :         psXMLNode = oLocalMDMD.Serialize();
    4829             : 
    4830         150 :         WriteMetadata(psXMLNode, nullptr);
    4831             :     }
    4832             : 
    4833         740 :     for (auto &poLayer : m_apoLayers)
    4834             :     {
    4835         304 :         const char *pszIdentifier = poLayer->GetMetadataItem("IDENTIFIER");
    4836         304 :         const char *pszDescription = poLayer->GetMetadataItem("DESCRIPTION");
    4837         304 :         if (pszIdentifier != nullptr)
    4838             :         {
    4839             :             char *pszSQL =
    4840           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4841             :                                 "WHERE lower(table_name) = lower('%q')",
    4842             :                                 pszIdentifier, poLayer->GetName());
    4843           3 :             SQLCommand(hDB, pszSQL);
    4844           3 :             sqlite3_free(pszSQL);
    4845             :         }
    4846         304 :         if (pszDescription != nullptr)
    4847             :         {
    4848             :             char *pszSQL =
    4849           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4850             :                                 "WHERE lower(table_name) = lower('%q')",
    4851             :                                 pszDescription, poLayer->GetName());
    4852           3 :             SQLCommand(hDB, pszSQL);
    4853           3 :             sqlite3_free(pszSQL);
    4854             :         }
    4855             : 
    4856         304 :         papszMDDup = nullptr;
    4857        1105 :         for (CSLConstList papszIter = poLayer->GetMetadata();
    4858        1105 :              papszIter && *papszIter; ++papszIter)
    4859             :         {
    4860         801 :             if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4861           3 :                 continue;
    4862         798 :             if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4863           3 :                 continue;
    4864         795 :             if (STARTS_WITH_CI(*papszIter, "OLMD_FID64="))
    4865           0 :                 continue;
    4866         795 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4867             :         }
    4868             : 
    4869             :         {
    4870         304 :             GDALMultiDomainMetadata oLocalMDMD;
    4871         304 :             char **papszDomainList = poLayer->GetMetadataDomainList();
    4872         304 :             char **papszIter = papszDomainList;
    4873         304 :             oLocalMDMD.SetMetadata(papszMDDup);
    4874         673 :             while (papszIter && *papszIter)
    4875             :             {
    4876         369 :                 if (!EQUAL(*papszIter, ""))
    4877          78 :                     oLocalMDMD.SetMetadata(poLayer->GetMetadata(*papszIter),
    4878             :                                            *papszIter);
    4879         369 :                 papszIter++;
    4880             :             }
    4881         304 :             CSLDestroy(papszDomainList);
    4882         304 :             psXMLNode = oLocalMDMD.Serialize();
    4883             :         }
    4884             : 
    4885         304 :         CSLDestroy(papszMDDup);
    4886         304 :         papszMDDup = nullptr;
    4887             : 
    4888         304 :         WriteMetadata(psXMLNode, poLayer->GetName());
    4889             :     }
    4890             : }
    4891             : 
    4892             : /************************************************************************/
    4893             : /*                          GetMetadataItem()                           */
    4894             : /************************************************************************/
    4895             : 
    4896        2227 : const char *GDALGeoPackageDataset::GetMetadataItem(const char *pszName,
    4897             :                                                    const char *pszDomain)
    4898             : {
    4899        2227 :     pszDomain = CheckMetadataDomain(pszDomain);
    4900        2227 :     return CSLFetchNameValue(GetMetadata(pszDomain), pszName);
    4901             : }
    4902             : 
    4903             : /************************************************************************/
    4904             : /*                            SetMetadata()                             */
    4905             : /************************************************************************/
    4906             : 
    4907         136 : CPLErr GDALGeoPackageDataset::SetMetadata(CSLConstList papszMetadata,
    4908             :                                           const char *pszDomain)
    4909             : {
    4910         136 :     pszDomain = CheckMetadataDomain(pszDomain);
    4911         136 :     m_bMetadataDirty = true;
    4912         136 :     GetMetadata(); /* force loading from storage if needed */
    4913         136 :     return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
    4914             : }
    4915             : 
    4916             : /************************************************************************/
    4917             : /*                          SetMetadataItem()                           */
    4918             : /************************************************************************/
    4919             : 
    4920          21 : CPLErr GDALGeoPackageDataset::SetMetadataItem(const char *pszName,
    4921             :                                               const char *pszValue,
    4922             :                                               const char *pszDomain)
    4923             : {
    4924          21 :     pszDomain = CheckMetadataDomain(pszDomain);
    4925          21 :     m_bMetadataDirty = true;
    4926          21 :     GetMetadata(); /* force loading from storage if needed */
    4927          21 :     return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    4928             : }
    4929             : 
    4930             : /************************************************************************/
    4931             : /*                               Create()                               */
    4932             : /************************************************************************/
    4933             : 
    4934        1161 : int GDALGeoPackageDataset::Create(const char *pszFilename, int nXSize,
    4935             :                                   int nYSize, int nBandsIn, GDALDataType eDT,
    4936             :                                   CSLConstList papszOptions)
    4937             : {
    4938        2322 :     CPLString osCommand;
    4939             : 
    4940             :     /* First, ensure there isn't any such file yet. */
    4941             :     VSIStatBufL sStatBuf;
    4942             : 
    4943        1161 :     if (nBandsIn != 0)
    4944             :     {
    4945         234 :         if (eDT == GDT_UInt8)
    4946             :         {
    4947         164 :             if (nBandsIn != 1 && nBandsIn != 2 && nBandsIn != 3 &&
    4948             :                 nBandsIn != 4)
    4949             :             {
    4950           1 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4951             :                          "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), "
    4952             :                          "3 (RGB) or 4 (RGBA) band dataset supported for "
    4953             :                          "Byte datatype");
    4954           1 :                 return FALSE;
    4955             :             }
    4956             :         }
    4957          70 :         else if (eDT == GDT_Int16 || eDT == GDT_UInt16 || eDT == GDT_Float32)
    4958             :         {
    4959          43 :             if (nBandsIn != 1)
    4960             :             {
    4961           3 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4962             :                          "Only single band dataset supported for non Byte "
    4963             :                          "datatype");
    4964           3 :                 return FALSE;
    4965             :             }
    4966             :         }
    4967             :         else
    4968             :         {
    4969          27 :             CPLError(CE_Failure, CPLE_NotSupported,
    4970             :                      "Only Byte, Int16, UInt16 or Float32 supported");
    4971          27 :             return FALSE;
    4972             :         }
    4973             :     }
    4974             : 
    4975        1130 :     const size_t nFilenameLen = strlen(pszFilename);
    4976        1130 :     const bool bGpkgZip =
    4977        1125 :         (nFilenameLen > strlen(".gpkg.zip") &&
    4978        2255 :          !STARTS_WITH(pszFilename, "/vsizip/") &&
    4979        1125 :          EQUAL(pszFilename + nFilenameLen - strlen(".gpkg.zip"), ".gpkg.zip"));
    4980             : 
    4981             :     const bool bUseTempFile =
    4982        1131 :         bGpkgZip || (CPLTestBool(CPLGetConfigOption(
    4983           1 :                          "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", "NO")) &&
    4984           1 :                      (VSIHasOptimizedReadMultiRange(pszFilename) != FALSE ||
    4985           1 :                       EQUAL(CPLGetConfigOption(
    4986             :                                 "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", ""),
    4987        1130 :                             "FORCED")));
    4988             : 
    4989        1130 :     bool bFileExists = false;
    4990        1130 :     if (VSIStatL(pszFilename, &sStatBuf) == 0)
    4991             :     {
    4992          10 :         bFileExists = true;
    4993          20 :         if (nBandsIn == 0 || bUseTempFile ||
    4994          10 :             !CPLTestBool(
    4995             :                 CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")))
    4996             :         {
    4997           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    4998             :                      "A file system object called '%s' already exists.",
    4999             :                      pszFilename);
    5000             : 
    5001           0 :             return FALSE;
    5002             :         }
    5003             :     }
    5004             : 
    5005        1130 :     if (bUseTempFile)
    5006             :     {
    5007           3 :         if (bGpkgZip)
    5008             :         {
    5009           2 :             std::string osFilenameInZip(CPLGetFilename(pszFilename));
    5010           2 :             osFilenameInZip.resize(osFilenameInZip.size() - strlen(".zip"));
    5011             :             m_osFinalFilename =
    5012           2 :                 std::string("/vsizip/{") + pszFilename + "}/" + osFilenameInZip;
    5013             :         }
    5014             :         else
    5015             :         {
    5016           1 :             m_osFinalFilename = pszFilename;
    5017             :         }
    5018           3 :         m_pszFilename = CPLStrdup(
    5019           6 :             CPLGenerateTempFilenameSafe(CPLGetFilename(pszFilename)).c_str());
    5020           3 :         CPLDebug("GPKG", "Creating temporary file %s", m_pszFilename);
    5021             :     }
    5022             :     else
    5023             :     {
    5024        1127 :         m_pszFilename = CPLStrdup(pszFilename);
    5025             :     }
    5026        1130 :     m_bNew = true;
    5027        1130 :     eAccess = GA_Update;
    5028        1130 :     m_bDateTimeWithTZ =
    5029        1130 :         EQUAL(CSLFetchNameValueDef(papszOptions, "DATETIME_FORMAT", "WITH_TZ"),
    5030             :               "WITH_TZ");
    5031             : 
    5032             :     // for test/debug purposes only. true is the nominal value
    5033        1130 :     m_bPNGSupports2Bands =
    5034        1130 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_2BANDS", "TRUE"));
    5035        1130 :     m_bPNGSupportsCT =
    5036        1130 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_CT", "TRUE"));
    5037             : 
    5038        1130 :     if (!OpenOrCreateDB(bFileExists
    5039             :                             ? SQLITE_OPEN_READWRITE
    5040             :                             : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE))
    5041           7 :         return FALSE;
    5042             : 
    5043             :     /* Default to synchronous=off for performance for new file */
    5044        2236 :     if (!bFileExists &&
    5045        1113 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5046             :     {
    5047         587 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5048             :     }
    5049             : 
    5050             :     /* OGR UTF-8 support. If we set the UTF-8 Pragma early on, it */
    5051             :     /* will be written into the main file and supported henceforth */
    5052        1123 :     SQLCommand(hDB, "PRAGMA encoding = \"UTF-8\"");
    5053             : 
    5054        1123 :     if (bFileExists)
    5055             :     {
    5056          10 :         VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
    5057          10 :         if (fp)
    5058             :         {
    5059             :             GByte abyHeader[100];
    5060          10 :             VSIFReadL(abyHeader, 1, sizeof(abyHeader), fp);
    5061          10 :             VSIFCloseL(fp);
    5062             : 
    5063          10 :             memcpy(&m_nApplicationId, abyHeader + knApplicationIdPos, 4);
    5064          10 :             m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    5065          10 :             memcpy(&m_nUserVersion, abyHeader + knUserVersionPos, 4);
    5066          10 :             m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    5067             : 
    5068          10 :             if (m_nApplicationId == GP10_APPLICATION_ID)
    5069             :             {
    5070           0 :                 CPLDebug("GPKG", "GeoPackage v1.0");
    5071             :             }
    5072          10 :             else if (m_nApplicationId == GP11_APPLICATION_ID)
    5073             :             {
    5074           0 :                 CPLDebug("GPKG", "GeoPackage v1.1");
    5075             :             }
    5076          10 :             else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    5077          10 :                      m_nUserVersion >= GPKG_1_2_VERSION)
    5078             :             {
    5079          10 :                 CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    5080          10 :                          (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    5081             :             }
    5082             :         }
    5083             : 
    5084          10 :         DetectSpatialRefSysColumns();
    5085             :     }
    5086             : 
    5087        1123 :     const char *pszVersion = CSLFetchNameValue(papszOptions, "VERSION");
    5088        1123 :     if (pszVersion && !EQUAL(pszVersion, "AUTO"))
    5089             :     {
    5090          42 :         if (EQUAL(pszVersion, "1.0"))
    5091             :         {
    5092           3 :             m_nApplicationId = GP10_APPLICATION_ID;
    5093           3 :             m_nUserVersion = 0;
    5094             :         }
    5095          39 :         else if (EQUAL(pszVersion, "1.1"))
    5096             :         {
    5097           1 :             m_nApplicationId = GP11_APPLICATION_ID;
    5098           1 :             m_nUserVersion = 0;
    5099             :         }
    5100          38 :         else if (EQUAL(pszVersion, "1.2"))
    5101             :         {
    5102          15 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5103          15 :             m_nUserVersion = GPKG_1_2_VERSION;
    5104             :         }
    5105          23 :         else if (EQUAL(pszVersion, "1.3"))
    5106             :         {
    5107           3 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5108           3 :             m_nUserVersion = GPKG_1_3_VERSION;
    5109             :         }
    5110          20 :         else if (EQUAL(pszVersion, "1.4"))
    5111             :         {
    5112          20 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5113          20 :             m_nUserVersion = GPKG_1_4_VERSION;
    5114             :         }
    5115             :     }
    5116             : 
    5117        1123 :     SoftStartTransaction();
    5118             : 
    5119        2246 :     CPLString osSQL;
    5120        1123 :     if (!bFileExists)
    5121             :     {
    5122             :         /* Requirement 10: A GeoPackage SHALL include a gpkg_spatial_ref_sys
    5123             :          * table */
    5124             :         /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5125             :         osSQL = "CREATE TABLE gpkg_spatial_ref_sys ("
    5126             :                 "srs_name TEXT NOT NULL,"
    5127             :                 "srs_id INTEGER NOT NULL PRIMARY KEY,"
    5128             :                 "organization TEXT NOT NULL,"
    5129             :                 "organization_coordsys_id INTEGER NOT NULL,"
    5130             :                 "definition  TEXT NOT NULL,"
    5131        1113 :                 "description TEXT";
    5132        1113 :         if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "CRS_WKT_EXTENSION",
    5133        1303 :                                              "NO")) ||
    5134         190 :             (nBandsIn != 0 && eDT != GDT_UInt8))
    5135             :         {
    5136          42 :             m_bHasDefinition12_063 = true;
    5137          42 :             osSQL += ", definition_12_063 TEXT NOT NULL";
    5138          42 :             if (m_nUserVersion >= GPKG_1_4_VERSION)
    5139             :             {
    5140          40 :                 osSQL += ", epoch DOUBLE";
    5141          40 :                 m_bHasEpochColumn = true;
    5142             :             }
    5143             :         }
    5144             :         osSQL += ")"
    5145             :                  ";"
    5146             :                  /* Requirement 11: The gpkg_spatial_ref_sys table in a
    5147             :                     GeoPackage SHALL */
    5148             :                  /* contain a record for EPSG:4326, the geodetic WGS84 SRS */
    5149             :                  /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5150             : 
    5151             :                  "INSERT INTO gpkg_spatial_ref_sys ("
    5152             :                  "srs_name, srs_id, organization, organization_coordsys_id, "
    5153        1113 :                  "definition, description";
    5154        1113 :         if (m_bHasDefinition12_063)
    5155          42 :             osSQL += ", definition_12_063";
    5156             :         osSQL +=
    5157             :             ") VALUES ("
    5158             :             "'WGS 84 geodetic', 4326, 'EPSG', 4326, '"
    5159             :             "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS "
    5160             :             "84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],"
    5161             :             "AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY["
    5162             :             "\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY["
    5163             :             "\"EPSG\",\"9122\"]],AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\","
    5164             :             "EAST],AUTHORITY[\"EPSG\",\"4326\"]]"
    5165             :             "', 'longitude/latitude coordinates in decimal degrees on the WGS "
    5166        1113 :             "84 spheroid'";
    5167        1113 :         if (m_bHasDefinition12_063)
    5168             :             osSQL +=
    5169             :                 ", 'GEODCRS[\"WGS 84\", DATUM[\"World Geodetic System 1984\", "
    5170             :                 "ELLIPSOID[\"WGS 84\",6378137, 298.257223563, "
    5171             :                 "LENGTHUNIT[\"metre\", 1.0]]], PRIMEM[\"Greenwich\", 0.0, "
    5172             :                 "ANGLEUNIT[\"degree\",0.0174532925199433]], CS[ellipsoidal, "
    5173             :                 "2], AXIS[\"latitude\", north, ORDER[1]], AXIS[\"longitude\", "
    5174             :                 "east, ORDER[2]], ANGLEUNIT[\"degree\", 0.0174532925199433], "
    5175          42 :                 "ID[\"EPSG\", 4326]]'";
    5176             :         osSQL +=
    5177             :             ")"
    5178             :             ";"
    5179             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5180             :                SHALL */
    5181             :             /* contain a record with an srs_id of -1, an organization of “NONE”,
    5182             :              */
    5183             :             /* an organization_coordsys_id of -1, and definition “undefined” */
    5184             :             /* for undefined Cartesian coordinate reference systems */
    5185             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5186             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5187             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5188        1113 :             "definition, description";
    5189        1113 :         if (m_bHasDefinition12_063)
    5190          42 :             osSQL += ", definition_12_063";
    5191             :         osSQL += ") VALUES ("
    5192             :                  "'Undefined Cartesian SRS', -1, 'NONE', -1, 'undefined', "
    5193        1113 :                  "'undefined Cartesian coordinate reference system'";
    5194        1113 :         if (m_bHasDefinition12_063)
    5195          42 :             osSQL += ", 'undefined'";
    5196             :         osSQL +=
    5197             :             ")"
    5198             :             ";"
    5199             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5200             :                SHALL */
    5201             :             /* contain a record with an srs_id of 0, an organization of “NONE”,
    5202             :              */
    5203             :             /* an organization_coordsys_id of 0, and definition “undefined” */
    5204             :             /* for undefined geographic coordinate reference systems */
    5205             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5206             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5207             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5208        1113 :             "definition, description";
    5209        1113 :         if (m_bHasDefinition12_063)
    5210          42 :             osSQL += ", definition_12_063";
    5211             :         osSQL += ") VALUES ("
    5212             :                  "'Undefined geographic SRS', 0, 'NONE', 0, 'undefined', "
    5213        1113 :                  "'undefined geographic coordinate reference system'";
    5214        1113 :         if (m_bHasDefinition12_063)
    5215          42 :             osSQL += ", 'undefined'";
    5216             :         osSQL += ")"
    5217             :                  ";"
    5218             :                  /* Requirement 13: A GeoPackage file SHALL include a
    5219             :                     gpkg_contents table */
    5220             :                  /* http://opengis.github.io/geopackage/#_contents */
    5221             :                  "CREATE TABLE gpkg_contents ("
    5222             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5223             :                  "data_type TEXT NOT NULL,"
    5224             :                  "identifier TEXT UNIQUE,"
    5225             :                  "description TEXT DEFAULT '',"
    5226             :                  "last_change DATETIME NOT NULL DEFAULT "
    5227             :                  "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    5228             :                  "min_x DOUBLE, min_y DOUBLE,"
    5229             :                  "max_x DOUBLE, max_y DOUBLE,"
    5230             :                  "srs_id INTEGER,"
    5231             :                  "CONSTRAINT fk_gc_r_srs_id FOREIGN KEY (srs_id) REFERENCES "
    5232             :                  "gpkg_spatial_ref_sys(srs_id)"
    5233        1113 :                  ")";
    5234             : 
    5235             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5236        1113 :         if (CPLFetchBool(papszOptions, "ADD_GPKG_OGR_CONTENTS", true))
    5237             :         {
    5238        1107 :             m_bHasGPKGOGRContents = true;
    5239             :             osSQL += ";"
    5240             :                      "CREATE TABLE gpkg_ogr_contents("
    5241             :                      "table_name TEXT NOT NULL PRIMARY KEY,"
    5242             :                      "feature_count INTEGER DEFAULT NULL"
    5243        1107 :                      ")";
    5244             :         }
    5245             : #endif
    5246             : 
    5247             :         /* Requirement 21: A GeoPackage with a gpkg_contents table row with a
    5248             :          * “features” */
    5249             :         /* data_type SHALL contain a gpkg_geometry_columns table or updateable
    5250             :          * view */
    5251             :         /* http://opengis.github.io/geopackage/#_geometry_columns */
    5252             :         const bool bCreateGeometryColumns =
    5253        1113 :             CPLTestBool(CPLGetConfigOption("CREATE_GEOMETRY_COLUMNS", "YES"));
    5254        1113 :         if (bCreateGeometryColumns)
    5255             :         {
    5256        1112 :             m_bHasGPKGGeometryColumns = true;
    5257        1112 :             osSQL += ";";
    5258        1112 :             osSQL += pszCREATE_GPKG_GEOMETRY_COLUMNS;
    5259             :         }
    5260             :     }
    5261             : 
    5262             :     const bool bCreateTriggers =
    5263        1123 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "YES"));
    5264          10 :     if ((bFileExists && nBandsIn != 0 &&
    5265          10 :          SQLGetInteger(
    5266             :              hDB,
    5267             :              "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_tile_matrix_set' "
    5268             :              "AND type in ('table', 'view')",
    5269        2246 :              nullptr) == 0) ||
    5270        1122 :         (!bFileExists &&
    5271        1113 :          CPLTestBool(CPLGetConfigOption("CREATE_RASTER_TABLES", "YES"))))
    5272             :     {
    5273        1113 :         if (!osSQL.empty())
    5274        1112 :             osSQL += ";";
    5275             : 
    5276             :         /* From C.5. gpkg_tile_matrix_set Table 28. gpkg_tile_matrix_set Table
    5277             :          * Creation SQL  */
    5278             :         osSQL += "CREATE TABLE gpkg_tile_matrix_set ("
    5279             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5280             :                  "srs_id INTEGER NOT NULL,"
    5281             :                  "min_x DOUBLE NOT NULL,"
    5282             :                  "min_y DOUBLE NOT NULL,"
    5283             :                  "max_x DOUBLE NOT NULL,"
    5284             :                  "max_y DOUBLE NOT NULL,"
    5285             :                  "CONSTRAINT fk_gtms_table_name FOREIGN KEY (table_name) "
    5286             :                  "REFERENCES gpkg_contents(table_name),"
    5287             :                  "CONSTRAINT fk_gtms_srs FOREIGN KEY (srs_id) REFERENCES "
    5288             :                  "gpkg_spatial_ref_sys (srs_id)"
    5289             :                  ")"
    5290             :                  ";"
    5291             : 
    5292             :                  /* From C.6. gpkg_tile_matrix Table 29. gpkg_tile_matrix Table
    5293             :                     Creation SQL */
    5294             :                  "CREATE TABLE gpkg_tile_matrix ("
    5295             :                  "table_name TEXT NOT NULL,"
    5296             :                  "zoom_level INTEGER NOT NULL,"
    5297             :                  "matrix_width INTEGER NOT NULL,"
    5298             :                  "matrix_height INTEGER NOT NULL,"
    5299             :                  "tile_width INTEGER NOT NULL,"
    5300             :                  "tile_height INTEGER NOT NULL,"
    5301             :                  "pixel_x_size DOUBLE NOT NULL,"
    5302             :                  "pixel_y_size DOUBLE NOT NULL,"
    5303             :                  "CONSTRAINT pk_ttm PRIMARY KEY (table_name, zoom_level),"
    5304             :                  "CONSTRAINT fk_tmm_table_name FOREIGN KEY (table_name) "
    5305             :                  "REFERENCES gpkg_contents(table_name)"
    5306        1113 :                  ")";
    5307             : 
    5308        1113 :         if (bCreateTriggers)
    5309             :         {
    5310             :             /* From D.1. gpkg_tile_matrix Table 39. gpkg_tile_matrix Trigger
    5311             :              * Definition SQL */
    5312        1113 :             const char *pszTileMatrixTrigger =
    5313             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_insert' "
    5314             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5315             :                 "FOR EACH ROW BEGIN "
    5316             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5317             :                 "violates constraint: zoom_level cannot be less than 0') "
    5318             :                 "WHERE (NEW.zoom_level < 0); "
    5319             :                 "END; "
    5320             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_update' "
    5321             :                 "BEFORE UPDATE of zoom_level ON 'gpkg_tile_matrix' "
    5322             :                 "FOR EACH ROW BEGIN "
    5323             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5324             :                 "violates constraint: zoom_level cannot be less than 0') "
    5325             :                 "WHERE (NEW.zoom_level < 0); "
    5326             :                 "END; "
    5327             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_insert' "
    5328             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5329             :                 "FOR EACH ROW BEGIN "
    5330             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5331             :                 "violates constraint: matrix_width cannot be less than 1') "
    5332             :                 "WHERE (NEW.matrix_width < 1); "
    5333             :                 "END; "
    5334             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_update' "
    5335             :                 "BEFORE UPDATE OF matrix_width ON 'gpkg_tile_matrix' "
    5336             :                 "FOR EACH ROW BEGIN "
    5337             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5338             :                 "violates constraint: matrix_width cannot be less than 1') "
    5339             :                 "WHERE (NEW.matrix_width < 1); "
    5340             :                 "END; "
    5341             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_insert' "
    5342             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5343             :                 "FOR EACH ROW BEGIN "
    5344             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5345             :                 "violates constraint: matrix_height cannot be less than 1') "
    5346             :                 "WHERE (NEW.matrix_height < 1); "
    5347             :                 "END; "
    5348             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_update' "
    5349             :                 "BEFORE UPDATE OF matrix_height ON 'gpkg_tile_matrix' "
    5350             :                 "FOR EACH ROW BEGIN "
    5351             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5352             :                 "violates constraint: matrix_height cannot be less than 1') "
    5353             :                 "WHERE (NEW.matrix_height < 1); "
    5354             :                 "END; "
    5355             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_insert' "
    5356             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5357             :                 "FOR EACH ROW BEGIN "
    5358             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5359             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5360             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5361             :                 "END; "
    5362             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_update' "
    5363             :                 "BEFORE UPDATE OF pixel_x_size ON 'gpkg_tile_matrix' "
    5364             :                 "FOR EACH ROW BEGIN "
    5365             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5366             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5367             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5368             :                 "END; "
    5369             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_insert' "
    5370             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5371             :                 "FOR EACH ROW BEGIN "
    5372             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5373             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5374             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5375             :                 "END; "
    5376             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_update' "
    5377             :                 "BEFORE UPDATE OF pixel_y_size ON 'gpkg_tile_matrix' "
    5378             :                 "FOR EACH ROW BEGIN "
    5379             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5380             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5381             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5382             :                 "END;";
    5383        1113 :             osSQL += ";";
    5384        1113 :             osSQL += pszTileMatrixTrigger;
    5385             :         }
    5386             :     }
    5387             : 
    5388        1123 :     if (!osSQL.empty() && OGRERR_NONE != SQLCommand(hDB, osSQL))
    5389           1 :         return FALSE;
    5390             : 
    5391        1122 :     if (!bFileExists)
    5392             :     {
    5393             :         const char *pszMetadataTables =
    5394        1112 :             CSLFetchNameValue(papszOptions, "METADATA_TABLES");
    5395        1112 :         if (pszMetadataTables)
    5396          10 :             m_nCreateMetadataTables = int(CPLTestBool(pszMetadataTables));
    5397             : 
    5398        1112 :         if (m_nCreateMetadataTables == TRUE && !CreateMetadataTables())
    5399           0 :             return FALSE;
    5400             : 
    5401        1112 :         if (m_bHasDefinition12_063)
    5402             :         {
    5403          84 :             if (OGRERR_NONE != CreateExtensionsTableIfNecessary() ||
    5404             :                 OGRERR_NONE !=
    5405          42 :                     SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5406             :                                     "(table_name, column_name, extension_name, "
    5407             :                                     "definition, scope) "
    5408             :                                     "VALUES "
    5409             :                                     "('gpkg_spatial_ref_sys', "
    5410             :                                     "'definition_12_063', 'gpkg_crs_wkt', "
    5411             :                                     "'http://www.geopackage.org/spec120/"
    5412             :                                     "#extension_crs_wkt', 'read-write')"))
    5413             :             {
    5414           0 :                 return FALSE;
    5415             :             }
    5416          42 :             if (m_bHasEpochColumn)
    5417             :             {
    5418          40 :                 if (OGRERR_NONE !=
    5419          40 :                         SQLCommand(
    5420             :                             hDB, "UPDATE gpkg_extensions SET extension_name = "
    5421             :                                  "'gpkg_crs_wkt_1_1' "
    5422          80 :                                  "WHERE extension_name = 'gpkg_crs_wkt'") ||
    5423             :                     OGRERR_NONE !=
    5424          40 :                         SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5425             :                                         "(table_name, column_name, "
    5426             :                                         "extension_name, definition, scope) "
    5427             :                                         "VALUES "
    5428             :                                         "('gpkg_spatial_ref_sys', 'epoch', "
    5429             :                                         "'gpkg_crs_wkt_1_1', "
    5430             :                                         "'http://www.geopackage.org/spec/"
    5431             :                                         "#extension_crs_wkt', "
    5432             :                                         "'read-write')"))
    5433             :                 {
    5434           0 :                     return FALSE;
    5435             :                 }
    5436             :             }
    5437             :         }
    5438             :     }
    5439             : 
    5440        1122 :     if (nBandsIn != 0)
    5441             :     {
    5442         199 :         const std::string osTableName = CPLGetBasenameSafe(m_pszFilename);
    5443             :         m_osRasterTable = CSLFetchNameValueDef(papszOptions, "RASTER_TABLE",
    5444         199 :                                                osTableName.c_str());
    5445         199 :         if (m_osRasterTable.empty())
    5446             :         {
    5447           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5448             :                      "RASTER_TABLE must be set to a non empty value");
    5449           0 :             return FALSE;
    5450             :         }
    5451         199 :         m_bIdentifierAsCO =
    5452         199 :             CSLFetchNameValue(papszOptions, "RASTER_IDENTIFIER") != nullptr;
    5453             :         m_osIdentifier = CSLFetchNameValueDef(papszOptions, "RASTER_IDENTIFIER",
    5454         199 :                                               m_osRasterTable);
    5455         199 :         m_bDescriptionAsCO =
    5456         199 :             CSLFetchNameValue(papszOptions, "RASTER_DESCRIPTION") != nullptr;
    5457             :         m_osDescription =
    5458         199 :             CSLFetchNameValueDef(papszOptions, "RASTER_DESCRIPTION", "");
    5459         199 :         SetDataType(eDT);
    5460         199 :         if (eDT == GDT_Int16)
    5461          16 :             SetGlobalOffsetScale(-32768.0, 1.0);
    5462             : 
    5463             :         /* From C.7. sample_tile_pyramid (Informative) Table 31. EXAMPLE: tiles
    5464             :          * table Create Table SQL (Informative) */
    5465             :         char *pszSQL =
    5466         199 :             sqlite3_mprintf("CREATE TABLE \"%w\" ("
    5467             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    5468             :                             "zoom_level INTEGER NOT NULL,"
    5469             :                             "tile_column INTEGER NOT NULL,"
    5470             :                             "tile_row INTEGER NOT NULL,"
    5471             :                             "tile_data BLOB NOT NULL,"
    5472             :                             "UNIQUE (zoom_level, tile_column, tile_row)"
    5473             :                             ")",
    5474             :                             m_osRasterTable.c_str());
    5475         199 :         osSQL = pszSQL;
    5476         199 :         sqlite3_free(pszSQL);
    5477             : 
    5478         199 :         if (bCreateTriggers)
    5479             :         {
    5480         199 :             osSQL += ";";
    5481         199 :             osSQL += CreateRasterTriggersSQL(m_osRasterTable);
    5482             :         }
    5483             : 
    5484         199 :         OGRErr eErr = SQLCommand(hDB, osSQL);
    5485         199 :         if (OGRERR_NONE != eErr)
    5486           0 :             return FALSE;
    5487             : 
    5488         199 :         const char *pszTF = CSLFetchNameValue(papszOptions, "TILE_FORMAT");
    5489         199 :         if (eDT == GDT_Int16 || eDT == GDT_UInt16)
    5490             :         {
    5491          27 :             m_eTF = GPKG_TF_PNG_16BIT;
    5492          27 :             if (pszTF)
    5493             :             {
    5494           1 :                 if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "PNG"))
    5495             :                 {
    5496           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5497             :                              "Only AUTO or PNG supported "
    5498             :                              "as tile format for Int16 / UInt16");
    5499             :                 }
    5500             :             }
    5501             :         }
    5502         172 :         else if (eDT == GDT_Float32)
    5503             :         {
    5504          13 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    5505          13 :             if (pszTF)
    5506             :             {
    5507           5 :                 if (EQUAL(pszTF, "PNG"))
    5508           5 :                     m_eTF = GPKG_TF_PNG_16BIT;
    5509           0 :                 else if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "TIFF"))
    5510             :                 {
    5511           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5512             :                              "Only AUTO, PNG or TIFF supported "
    5513             :                              "as tile format for Float32");
    5514             :                 }
    5515             :             }
    5516             :         }
    5517             :         else
    5518             :         {
    5519         159 :             if (pszTF)
    5520             :             {
    5521          72 :                 m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    5522          72 :                 if (nBandsIn == 1 && m_eTF != GPKG_TF_PNG)
    5523           7 :                     m_bMetadataDirty = true;
    5524             :             }
    5525          87 :             else if (nBandsIn == 1)
    5526          76 :                 m_eTF = GPKG_TF_PNG;
    5527             :         }
    5528             : 
    5529         199 :         if (eDT != GDT_UInt8)
    5530             :         {
    5531          40 :             if (!CreateTileGriddedTable(papszOptions))
    5532           0 :                 return FALSE;
    5533             :         }
    5534             : 
    5535         199 :         nRasterXSize = nXSize;
    5536         199 :         nRasterYSize = nYSize;
    5537             : 
    5538             :         const char *pszTileSize =
    5539         199 :             CSLFetchNameValueDef(papszOptions, "BLOCKSIZE", "256");
    5540             :         const char *pszTileWidth =
    5541         199 :             CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", pszTileSize);
    5542             :         const char *pszTileHeight =
    5543         199 :             CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", pszTileSize);
    5544         199 :         int nTileWidth = atoi(pszTileWidth);
    5545         199 :         int nTileHeight = atoi(pszTileHeight);
    5546         199 :         if ((nTileWidth < 8 || nTileWidth > 4096 || nTileHeight < 8 ||
    5547         398 :              nTileHeight > 4096) &&
    5548           1 :             !CPLTestBool(CPLGetConfigOption("GPKG_ALLOW_CRAZY_SETTINGS", "NO")))
    5549             :         {
    5550           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5551             :                      "Invalid block dimensions: %dx%d", nTileWidth,
    5552             :                      nTileHeight);
    5553           0 :             return FALSE;
    5554             :         }
    5555             : 
    5556         533 :         for (int i = 1; i <= nBandsIn; i++)
    5557             :         {
    5558         334 :             SetBand(i, std::make_unique<GDALGeoPackageRasterBand>(
    5559             :                            this, nTileWidth, nTileHeight));
    5560             :         }
    5561             : 
    5562         199 :         GDALPamDataset::SetMetadataItem(GDALMD_INTERLEAVE, "PIXEL",
    5563             :                                         GDAL_MDD_IMAGE_STRUCTURE);
    5564         199 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", m_osIdentifier);
    5565         199 :         if (!m_osDescription.empty())
    5566           1 :             GDALPamDataset::SetMetadataItem("DESCRIPTION", m_osDescription);
    5567             : 
    5568         199 :         ParseCompressionOptions(papszOptions);
    5569             : 
    5570         199 :         if (m_eTF == GPKG_TF_WEBP)
    5571             :         {
    5572          10 :             if (!RegisterWebPExtension())
    5573           0 :                 return FALSE;
    5574             :         }
    5575             : 
    5576             :         m_osTilingScheme =
    5577         199 :             CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5578         199 :         if (!EQUAL(m_osTilingScheme, "CUSTOM"))
    5579             :         {
    5580          22 :             const auto poTS = GetTilingScheme(m_osTilingScheme);
    5581          22 :             if (!poTS)
    5582           0 :                 return FALSE;
    5583             : 
    5584          43 :             if (nTileWidth != poTS->nTileWidth ||
    5585          21 :                 nTileHeight != poTS->nTileHeight)
    5586             :             {
    5587           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    5588             :                          "Tile dimension should be %dx%d for %s tiling scheme",
    5589           1 :                          poTS->nTileWidth, poTS->nTileHeight,
    5590             :                          m_osTilingScheme.c_str());
    5591           1 :                 return FALSE;
    5592             :             }
    5593             : 
    5594             :             const char *pszZoomLevel =
    5595          21 :                 CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    5596          21 :             if (pszZoomLevel)
    5597             :             {
    5598           1 :                 m_nZoomLevel = atoi(pszZoomLevel);
    5599           1 :                 int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    5600           1 :                 while ((1 << nMaxZoomLevelForThisTM) >
    5601           2 :                            INT_MAX / poTS->nTileXCountZoomLevel0 ||
    5602           1 :                        (1 << nMaxZoomLevelForThisTM) >
    5603           1 :                            INT_MAX / poTS->nTileYCountZoomLevel0)
    5604             :                 {
    5605           0 :                     --nMaxZoomLevelForThisTM;
    5606             :                 }
    5607             : 
    5608           1 :                 if (m_nZoomLevel < 0 || m_nZoomLevel > nMaxZoomLevelForThisTM)
    5609             :                 {
    5610           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    5611             :                              "ZOOM_LEVEL = %s is invalid. It should be in "
    5612             :                              "[0,%d] range",
    5613             :                              pszZoomLevel, nMaxZoomLevelForThisTM);
    5614           0 :                     return FALSE;
    5615             :                 }
    5616             :             }
    5617             : 
    5618             :             // Implicitly sets SRS.
    5619          21 :             OGRSpatialReference oSRS;
    5620          21 :             if (oSRS.importFromEPSG(poTS->nEPSGCode) != OGRERR_NONE)
    5621           0 :                 return FALSE;
    5622          21 :             char *pszWKT = nullptr;
    5623          21 :             oSRS.exportToWkt(&pszWKT);
    5624          21 :             SetProjection(pszWKT);
    5625          21 :             CPLFree(pszWKT);
    5626             :         }
    5627             :         else
    5628             :         {
    5629         177 :             if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5630             :             {
    5631           0 :                 CPLError(
    5632             :                     CE_Failure, CPLE_NotSupported,
    5633             :                     "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5634           0 :                 return false;
    5635             :             }
    5636             :         }
    5637             :     }
    5638             : 
    5639        1121 :     if (bFileExists && nBandsIn > 0 && eDT == GDT_UInt8)
    5640             :     {
    5641             :         // If there was an ogr_empty_table table, we can remove it
    5642           9 :         RemoveOGREmptyTable();
    5643             :     }
    5644             : 
    5645        1121 :     SoftCommitTransaction();
    5646             : 
    5647             :     /* Requirement 2 */
    5648             :     /* We have to do this after there's some content so the database file */
    5649             :     /* is not zero length */
    5650        1121 :     SetApplicationAndUserVersionId();
    5651             : 
    5652             :     /* Default to synchronous=off for performance for new file */
    5653        2232 :     if (!bFileExists &&
    5654        1111 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5655             :     {
    5656         587 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5657             :     }
    5658             : 
    5659             :     // Enable SpatiaLite 4.3 GPKG mode, i.e. that SpatiaLite functions
    5660             :     // that take geometries will accept and return GPKG encoded geometries without
    5661             :     // explicit conversion.
    5662             :     // Note: we need to do that after DB creation, since EnableGpkgMode()
    5663             :     // checks for the presence of GPKG system tables.
    5664        1121 :     sqlite3_exec(hDB, "SELECT EnableGpkgMode()", nullptr, nullptr, nullptr);
    5665             : 
    5666        1121 :     return TRUE;
    5667             : }
    5668             : 
    5669             : /************************************************************************/
    5670             : /*                        RemoveOGREmptyTable()                         */
    5671             : /************************************************************************/
    5672             : 
    5673         933 : void GDALGeoPackageDataset::RemoveOGREmptyTable()
    5674             : {
    5675             :     // Run with sqlite3_exec since we don't want errors to be emitted
    5676         933 :     sqlite3_exec(hDB, "DROP TABLE IF EXISTS ogr_empty_table", nullptr, nullptr,
    5677             :                  nullptr);
    5678         933 :     sqlite3_exec(
    5679             :         hDB, "DELETE FROM gpkg_contents WHERE table_name = 'ogr_empty_table'",
    5680             :         nullptr, nullptr, nullptr);
    5681             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5682         933 :     if (m_bHasGPKGOGRContents)
    5683             :     {
    5684         918 :         sqlite3_exec(hDB,
    5685             :                      "DELETE FROM gpkg_ogr_contents WHERE "
    5686             :                      "table_name = 'ogr_empty_table'",
    5687             :                      nullptr, nullptr, nullptr);
    5688             :     }
    5689             : #endif
    5690         933 :     sqlite3_exec(hDB,
    5691             :                  "DELETE FROM gpkg_geometry_columns WHERE "
    5692             :                  "table_name = 'ogr_empty_table'",
    5693             :                  nullptr, nullptr, nullptr);
    5694         933 : }
    5695             : 
    5696             : /************************************************************************/
    5697             : /*                       CreateTileGriddedTable()                       */
    5698             : /************************************************************************/
    5699             : 
    5700          40 : bool GDALGeoPackageDataset::CreateTileGriddedTable(CSLConstList papszOptions)
    5701             : {
    5702          80 :     CPLString osSQL;
    5703          40 :     if (!HasGriddedCoverageAncillaryTable())
    5704             :     {
    5705             :         // It doesn't exist. So create gpkg_extensions table if necessary, and
    5706             :         // gpkg_2d_gridded_coverage_ancillary & gpkg_2d_gridded_tile_ancillary,
    5707             :         // and register them as extensions.
    5708          40 :         if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    5709           0 :             return false;
    5710             : 
    5711             :         // Req 1 /table-defs/coverage-ancillary
    5712             :         osSQL = "CREATE TABLE gpkg_2d_gridded_coverage_ancillary ("
    5713             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5714             :                 "tile_matrix_set_name TEXT NOT NULL UNIQUE,"
    5715             :                 "datatype TEXT NOT NULL DEFAULT 'integer',"
    5716             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5717             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5718             :                 "precision REAL DEFAULT 1.0,"
    5719             :                 "data_null REAL,"
    5720             :                 "grid_cell_encoding TEXT DEFAULT 'grid-value-is-center',"
    5721             :                 "uom TEXT,"
    5722             :                 "field_name TEXT DEFAULT 'Height',"
    5723             :                 "quantity_definition TEXT DEFAULT 'Height',"
    5724             :                 "CONSTRAINT fk_g2dgtct_name FOREIGN KEY(tile_matrix_set_name) "
    5725             :                 "REFERENCES gpkg_tile_matrix_set ( table_name ) "
    5726             :                 "CHECK (datatype in ('integer','float')))"
    5727             :                 ";"
    5728             :                 // Requirement 2 /table-defs/tile-ancillary
    5729             :                 "CREATE TABLE gpkg_2d_gridded_tile_ancillary ("
    5730             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5731             :                 "tpudt_name TEXT NOT NULL,"
    5732             :                 "tpudt_id INTEGER NOT NULL,"
    5733             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5734             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5735             :                 "min REAL DEFAULT NULL,"
    5736             :                 "max REAL DEFAULT NULL,"
    5737             :                 "mean REAL DEFAULT NULL,"
    5738             :                 "std_dev REAL DEFAULT NULL,"
    5739             :                 "CONSTRAINT fk_g2dgtat_name FOREIGN KEY (tpudt_name) "
    5740             :                 "REFERENCES gpkg_contents(table_name),"
    5741             :                 "UNIQUE (tpudt_name, tpudt_id))"
    5742             :                 ";"
    5743             :                 // Requirement 6 /gpkg-extensions
    5744             :                 "INSERT INTO gpkg_extensions "
    5745             :                 "(table_name, column_name, extension_name, definition, scope) "
    5746             :                 "VALUES ('gpkg_2d_gridded_coverage_ancillary', NULL, "
    5747             :                 "'gpkg_2d_gridded_coverage', "
    5748             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5749             :                 "'read-write')"
    5750             :                 ";"
    5751             :                 // Requirement 6 /gpkg-extensions
    5752             :                 "INSERT INTO gpkg_extensions "
    5753             :                 "(table_name, column_name, extension_name, definition, scope) "
    5754             :                 "VALUES ('gpkg_2d_gridded_tile_ancillary', NULL, "
    5755             :                 "'gpkg_2d_gridded_coverage', "
    5756             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5757             :                 "'read-write')"
    5758          40 :                 ";";
    5759             :     }
    5760             : 
    5761             :     // Requirement 6 /gpkg-extensions
    5762          40 :     char *pszSQL = sqlite3_mprintf(
    5763             :         "INSERT INTO gpkg_extensions "
    5764             :         "(table_name, column_name, extension_name, definition, scope) "
    5765             :         "VALUES ('%q', 'tile_data', "
    5766             :         "'gpkg_2d_gridded_coverage', "
    5767             :         "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5768             :         "'read-write')",
    5769             :         m_osRasterTable.c_str());
    5770          40 :     osSQL += pszSQL;
    5771          40 :     osSQL += ";";
    5772          40 :     sqlite3_free(pszSQL);
    5773             : 
    5774             :     // Requirement 7 /gpkg-2d-gridded-coverage-ancillary
    5775             :     // Requirement 8 /gpkg-2d-gridded-coverage-ancillary-set-name
    5776             :     // Requirement 9 /gpkg-2d-gridded-coverage-ancillary-datatype
    5777          40 :     m_dfPrecision =
    5778          40 :         CPLAtof(CSLFetchNameValueDef(papszOptions, "PRECISION", "1"));
    5779             :     CPLString osGridCellEncoding(CSLFetchNameValueDef(
    5780          80 :         papszOptions, "GRID_CELL_ENCODING", "grid-value-is-center"));
    5781          40 :     m_bGridCellEncodingAsCO =
    5782          40 :         CSLFetchNameValue(papszOptions, "GRID_CELL_ENCODING") != nullptr;
    5783          80 :     CPLString osUom(CSLFetchNameValueDef(papszOptions, "UOM", ""));
    5784             :     CPLString osFieldName(
    5785          80 :         CSLFetchNameValueDef(papszOptions, "FIELD_NAME", "Height"));
    5786             :     CPLString osQuantityDefinition(
    5787          80 :         CSLFetchNameValueDef(papszOptions, "QUANTITY_DEFINITION", "Height"));
    5788             : 
    5789         121 :     pszSQL = sqlite3_mprintf(
    5790             :         "INSERT INTO gpkg_2d_gridded_coverage_ancillary "
    5791             :         "(tile_matrix_set_name, datatype, scale, offset, precision, "
    5792             :         "grid_cell_encoding, uom, field_name, quantity_definition) "
    5793             :         "VALUES (%Q, '%s', %.17g, %.17g, %.17g, %Q, %Q, %Q, %Q)",
    5794             :         m_osRasterTable.c_str(),
    5795          40 :         (m_eTF == GPKG_TF_PNG_16BIT) ? "integer" : "float", m_dfScale,
    5796             :         m_dfOffset, m_dfPrecision, osGridCellEncoding.c_str(),
    5797          41 :         osUom.empty() ? nullptr : osUom.c_str(), osFieldName.c_str(),
    5798             :         osQuantityDefinition.c_str());
    5799          40 :     m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary = pszSQL;
    5800          40 :     sqlite3_free(pszSQL);
    5801             : 
    5802             :     // Requirement 3 /gpkg-spatial-ref-sys-row
    5803             :     auto oResultTable = SQLQuery(
    5804          80 :         hDB, "SELECT * FROM gpkg_spatial_ref_sys WHERE srs_id = 4979 LIMIT 2");
    5805          40 :     bool bHasEPSG4979 = (oResultTable && oResultTable->RowCount() == 1);
    5806          40 :     if (!bHasEPSG4979)
    5807             :     {
    5808          41 :         if (!m_bHasDefinition12_063 &&
    5809           1 :             !ConvertGpkgSpatialRefSysToExtensionWkt2(/*bForceEpoch=*/false))
    5810             :         {
    5811           0 :             return false;
    5812             :         }
    5813             : 
    5814             :         // This is WKT 2...
    5815          40 :         const char *pszWKT =
    5816             :             "GEODCRS[\"WGS 84\","
    5817             :             "DATUM[\"World Geodetic System 1984\","
    5818             :             "  ELLIPSOID[\"WGS 84\",6378137,298.257223563,"
    5819             :             "LENGTHUNIT[\"metre\",1.0]]],"
    5820             :             "CS[ellipsoidal,3],"
    5821             :             "  AXIS[\"latitude\",north,ORDER[1],ANGLEUNIT[\"degree\","
    5822             :             "0.0174532925199433]],"
    5823             :             "  AXIS[\"longitude\",east,ORDER[2],ANGLEUNIT[\"degree\","
    5824             :             "0.0174532925199433]],"
    5825             :             "  AXIS[\"ellipsoidal height\",up,ORDER[3],"
    5826             :             "LENGTHUNIT[\"metre\",1.0]],"
    5827             :             "ID[\"EPSG\",4979]]";
    5828             : 
    5829          40 :         pszSQL = sqlite3_mprintf(
    5830             :             "INSERT INTO gpkg_spatial_ref_sys "
    5831             :             "(srs_name,srs_id,organization,organization_coordsys_id,"
    5832             :             "definition,definition_12_063) VALUES "
    5833             :             "('WGS 84 3D', 4979, 'EPSG', 4979, 'undefined', '%q')",
    5834             :             pszWKT);
    5835          40 :         osSQL += ";";
    5836          40 :         osSQL += pszSQL;
    5837          40 :         sqlite3_free(pszSQL);
    5838             :     }
    5839             : 
    5840          40 :     return SQLCommand(hDB, osSQL) == OGRERR_NONE;
    5841             : }
    5842             : 
    5843             : /************************************************************************/
    5844             : /*                  HasGriddedCoverageAncillaryTable()                  */
    5845             : /************************************************************************/
    5846             : 
    5847          44 : bool GDALGeoPackageDataset::HasGriddedCoverageAncillaryTable()
    5848             : {
    5849             :     auto oResultTable = SQLQuery(
    5850             :         hDB, "SELECT * FROM sqlite_master WHERE type IN ('table', 'view') AND "
    5851          44 :              "name = 'gpkg_2d_gridded_coverage_ancillary'");
    5852          44 :     bool bHasTable = (oResultTable && oResultTable->RowCount() == 1);
    5853          88 :     return bHasTable;
    5854             : }
    5855             : 
    5856             : /************************************************************************/
    5857             : /*                        GetUnderlyingDataset()                        */
    5858             : /************************************************************************/
    5859             : 
    5860           3 : static GDALDataset *GetUnderlyingDataset(GDALDataset *poSrcDS)
    5861             : {
    5862           3 :     if (auto poVRTDS = dynamic_cast<VRTDataset *>(poSrcDS))
    5863             :     {
    5864           0 :         auto poTmpDS = poVRTDS->GetSingleSimpleSource();
    5865           0 :         if (poTmpDS)
    5866           0 :             return poTmpDS;
    5867             :     }
    5868             : 
    5869           3 :     return poSrcDS;
    5870             : }
    5871             : 
    5872             : /************************************************************************/
    5873             : /*                             CreateCopy()                             */
    5874             : /************************************************************************/
    5875             : 
    5876             : typedef struct
    5877             : {
    5878             :     const char *pszName;
    5879             :     GDALResampleAlg eResampleAlg;
    5880             : } WarpResamplingAlg;
    5881             : 
    5882             : static const WarpResamplingAlg asResamplingAlg[] = {
    5883             :     {"NEAREST", GRA_NearestNeighbour},
    5884             :     {"BILINEAR", GRA_Bilinear},
    5885             :     {"CUBIC", GRA_Cubic},
    5886             :     {"CUBICSPLINE", GRA_CubicSpline},
    5887             :     {"LANCZOS", GRA_Lanczos},
    5888             :     {"MODE", GRA_Mode},
    5889             :     {"AVERAGE", GRA_Average},
    5890             :     {"RMS", GRA_RMS},
    5891             : };
    5892             : 
    5893         167 : GDALDataset *GDALGeoPackageDataset::CreateCopy(const char *pszFilename,
    5894             :                                                GDALDataset *poSrcDS,
    5895             :                                                int bStrict,
    5896             :                                                CSLConstList papszOptions,
    5897             :                                                GDALProgressFunc pfnProgress,
    5898             :                                                void *pProgressData)
    5899             : {
    5900         167 :     const int nBands = poSrcDS->GetRasterCount();
    5901         167 :     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         165 :         CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5917             : 
    5918         330 :     CPLStringList apszUpdatedOptions(CSLDuplicate(papszOptions));
    5919         165 :     if (CPLTestBool(
    5920         171 :             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         165 :     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         164 :     const char *pszUnitType = poSrcDS->GetRasterBand(1)->GetUnitType();
    5937         328 :     if (CSLFetchNameValue(papszOptions, "UOM") == nullptr && pszUnitType &&
    5938         164 :         !EQUAL(pszUnitType, ""))
    5939             :     {
    5940           1 :         apszUpdatedOptions.SetNameValue("UOM", pszUnitType);
    5941             :     }
    5942             : 
    5943         164 :     if (EQUAL(pszTilingScheme, "CUSTOM"))
    5944             :     {
    5945         140 :         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         140 :         GDALGeoPackageDataset *poDS = nullptr;
    5953             :         GDALDriver *poThisDriver =
    5954         140 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5955         140 :         if (poThisDriver != nullptr)
    5956             :         {
    5957         140 :             apszUpdatedOptions.SetNameValue("SKIP_HOLES", "YES");
    5958         140 :             poDS = cpl::down_cast<GDALGeoPackageDataset *>(
    5959             :                 poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS, bStrict,
    5960             :                                                 apszUpdatedOptions, pfnProgress,
    5961         140 :                                                 pProgressData));
    5962             : 
    5963         261 :             if (poDS != nullptr &&
    5964         140 :                 poSrcDS->GetRasterBand(1)->GetRasterDataType() == GDT_UInt8 &&
    5965             :                 nBands <= 3)
    5966             :             {
    5967          81 :                 poDS->m_nBandCountFromMetadata = nBands;
    5968          81 :                 poDS->m_bMetadataDirty = true;
    5969             :             }
    5970             :         }
    5971         140 :         if (poDS)
    5972         121 :             poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    5973         140 :         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_UInt8 &&
    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 ||
    6201          15 :             atoi(oSrcSRS.GetAuthorityCode()) != 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          40 :     if (!(poDS->Create(pszFilename, nXSize, nYSize, nTargetBands, eDT,
    6236          20 :                        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_UInt8 && 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         482 : void GDALGeoPackageDataset::ParseCompressionOptions(CSLConstList papszOptions)
    6382             : {
    6383         482 :     const char *pszZLevel = CSLFetchNameValue(papszOptions, "ZLEVEL");
    6384         482 :     if (pszZLevel)
    6385           0 :         m_nZLevel = atoi(pszZLevel);
    6386             : 
    6387         482 :     const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
    6388         482 :     if (pszQuality)
    6389           0 :         m_nQuality = atoi(pszQuality);
    6390             : 
    6391         482 :     const char *pszDither = CSLFetchNameValue(papszOptions, "DITHER");
    6392         482 :     if (pszDither)
    6393           0 :         m_bDither = CPLTestBool(pszDither);
    6394         482 : }
    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       17277 : const OGRLayer *GDALGeoPackageDataset::GetLayer(int iLayer) const
    6446             : 
    6447             : {
    6448       17277 :     if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
    6449           7 :         return nullptr;
    6450             :     else
    6451       17270 :         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        1038 : GDALGeoPackageDataset::ICreateLayer(const char *pszLayerName,
    6526             :                                     const OGRGeomFieldDefn *poSrcGeomFieldDefn,
    6527             :                                     CSLConstList papszOptions)
    6528             : {
    6529             :     /* -------------------------------------------------------------------- */
    6530             :     /*      Verify we are in update mode.                                   */
    6531             :     /* -------------------------------------------------------------------- */
    6532        1038 :     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        1038 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "LAUNDER", "NO"));
    6544             :     const std::string osTableName(bLaunder ? LaunderName(pszLayerName)
    6545        3114 :                                            : std::string(pszLayerName));
    6546             : 
    6547             :     const auto eGType =
    6548        1038 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
    6549             :     const auto poSpatialRef =
    6550        1038 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
    6551             : 
    6552        1038 :     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        1038 :     const char *pszIdentifier = CSLFetchNameValue(papszOptions, "IDENTIFIER");
    6563        1038 :     if (pszIdentifier != nullptr && pszIdentifier[0] == '\0')
    6564           0 :         pszIdentifier = nullptr;
    6565        1038 :     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        1035 :         CSLFetchNameValue(papszOptions, "GEOMETRY_NAME");
    6606        1035 :     if (pszGeomColumnName == nullptr) /* deprecated name */
    6607         941 :         pszGeomColumnName = CSLFetchNameValue(papszOptions, "GEOMETRY_COLUMN");
    6608        1035 :     if (pszGeomColumnName == nullptr && poSrcGeomFieldDefn)
    6609             :     {
    6610         859 :         pszGeomColumnName = poSrcGeomFieldDefn->GetNameRef();
    6611         859 :         if (pszGeomColumnName && pszGeomColumnName[0] == 0)
    6612         824 :             pszGeomColumnName = nullptr;
    6613             :     }
    6614        1035 :     if (pszGeomColumnName == nullptr)
    6615         906 :         pszGeomColumnName = "geom";
    6616             :     const bool bGeomNullable =
    6617        1035 :         CPLFetchBool(papszOptions, "GEOMETRY_NULLABLE", true);
    6618             : 
    6619             :     /* Read FID option */
    6620        1035 :     const char *pszFIDColumnName = CSLFetchNameValue(papszOptions, "FID");
    6621        1035 :     if (pszFIDColumnName == nullptr)
    6622         935 :         pszFIDColumnName = "fid";
    6623             : 
    6624        1035 :     if (CPLTestBool(CPLGetConfigOption("GPKG_NAME_CHECK", "YES")))
    6625             :     {
    6626        1035 :         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        1033 :         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        1033 :         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        1276 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6659             :          iLayer++)
    6660             :     {
    6661         244 :         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        1032 :     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          95 :         m_apoLayers[0]->FinishOrDisableThreadedRTree();
    6687             :     }
    6688             : 
    6689             :     /* Create a blank layer. */
    6690             :     auto poLayer =
    6691        2064 :         std::make_unique<OGRGeoPackageTableLayer>(this, osTableName.c_str());
    6692             : 
    6693        2064 :     OGRSpatialReferenceRefCountedPtr poSRS;
    6694        1032 :     if (poSpatialRef)
    6695             :     {
    6696         345 :         poSRS = OGRSpatialReferenceRefCountedPtr::makeClone(poSpatialRef);
    6697         345 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    6698             :     }
    6699        3097 :     poLayer->SetCreationParameters(
    6700             :         eGType,
    6701        1033 :         bLaunder ? LaunderName(pszGeomColumnName).c_str() : pszGeomColumnName,
    6702        1032 :         bGeomNullable, poSRS.get(), CSLFetchNameValue(papszOptions, "SRID"),
    6703        2064 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetCoordinatePrecision()
    6704             :                            : OGRGeomCoordinatePrecision(),
    6705        1032 :         CPLTestBool(
    6706             :             CSLFetchNameValueDef(papszOptions, "DISCARD_COORD_LSB", "NO")),
    6707        1032 :         CPLTestBool(CSLFetchNameValueDef(
    6708             :             papszOptions, "UNDO_DISCARD_COORD_LSB_ON_READING", "NO")),
    6709        1033 :         bLaunder ? LaunderName(pszFIDColumnName).c_str() : pszFIDColumnName,
    6710             :         pszIdentifier, CSLFetchNameValue(papszOptions, "DESCRIPTION"));
    6711             : 
    6712        1032 :     poLayer->SetLaunder(bLaunder);
    6713             : 
    6714             :     /* Should we create a spatial index ? */
    6715        1032 :     const char *pszSI = CSLFetchNameValue(papszOptions, "SPATIAL_INDEX");
    6716        1032 :     int bCreateSpatialIndex = (pszSI == nullptr || CPLTestBool(pszSI));
    6717        1032 :     if (eGType != wkbNone && bCreateSpatialIndex)
    6718             :     {
    6719         928 :         poLayer->SetDeferredSpatialIndexCreation(true);
    6720             :     }
    6721             : 
    6722        1032 :     poLayer->SetPrecisionFlag(CPLFetchBool(papszOptions, "PRECISION", true));
    6723        1032 :     poLayer->SetTruncateFieldsFlag(
    6724        1032 :         CPLFetchBool(papszOptions, "TRUNCATE_FIELDS", false));
    6725        1032 :     if (eGType == wkbNone)
    6726             :     {
    6727          82 :         const char *pszASpatialVariant = CSLFetchNameValueDef(
    6728             :             papszOptions, "ASPATIAL_VARIANT",
    6729          82 :             m_bNonSpatialTablesNonRegisteredInGpkgContentsFound
    6730             :                 ? "NOT_REGISTERED"
    6731             :                 : "GPKG_ATTRIBUTES");
    6732          82 :         GPKGASpatialVariant eASpatialVariant = GPKG_ATTRIBUTES;
    6733          82 :         if (EQUAL(pszASpatialVariant, "GPKG_ATTRIBUTES"))
    6734          70 :             eASpatialVariant = GPKG_ATTRIBUTES;
    6735          12 :         else if (EQUAL(pszASpatialVariant, "OGR_ASPATIAL"))
    6736             :         {
    6737           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6738             :                      "ASPATIAL_VARIANT=OGR_ASPATIAL is no longer supported");
    6739           0 :             return nullptr;
    6740             :         }
    6741          12 :         else if (EQUAL(pszASpatialVariant, "NOT_REGISTERED"))
    6742          12 :             eASpatialVariant = NOT_REGISTERED;
    6743             :         else
    6744             :         {
    6745           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6746             :                      "Unsupported value for ASPATIAL_VARIANT: %s",
    6747             :                      pszASpatialVariant);
    6748           0 :             return nullptr;
    6749             :         }
    6750          82 :         poLayer->SetASpatialVariant(eASpatialVariant);
    6751             :     }
    6752             : 
    6753             :     const char *pszDateTimePrecision =
    6754        1032 :         CSLFetchNameValueDef(papszOptions, "DATETIME_PRECISION", "AUTO");
    6755        1032 :     if (EQUAL(pszDateTimePrecision, "MILLISECOND"))
    6756             :     {
    6757           2 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6758             :     }
    6759        1030 :     else if (EQUAL(pszDateTimePrecision, "SECOND"))
    6760             :     {
    6761           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6762           0 :             CPLError(
    6763             :                 CE_Warning, CPLE_AppDefined,
    6764             :                 "DATETIME_PRECISION=SECOND is only valid since GeoPackage 1.4");
    6765           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::SECOND);
    6766             :     }
    6767        1029 :     else if (EQUAL(pszDateTimePrecision, "MINUTE"))
    6768             :     {
    6769           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6770           0 :             CPLError(
    6771             :                 CE_Warning, CPLE_AppDefined,
    6772             :                 "DATETIME_PRECISION=MINUTE is only valid since GeoPackage 1.4");
    6773           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MINUTE);
    6774             :     }
    6775        1028 :     else if (EQUAL(pszDateTimePrecision, "AUTO"))
    6776             :     {
    6777        1027 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6778          15 :             poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6779             :     }
    6780             :     else
    6781             :     {
    6782           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    6783             :                  "Unsupported value for DATETIME_PRECISION: %s",
    6784             :                  pszDateTimePrecision);
    6785           1 :         return nullptr;
    6786             :     }
    6787             : 
    6788             :     // If there was an ogr_empty_table table, we can remove it
    6789             :     // But do it at dataset closing, otherwise locking performance issues
    6790             :     // can arise (probably when transactions are used).
    6791        1031 :     m_bRemoveOGREmptyTable = true;
    6792             : 
    6793        1031 :     m_apoLayers.emplace_back(std::move(poLayer));
    6794        1031 :     return m_apoLayers.back().get();
    6795             : }
    6796             : 
    6797             : /************************************************************************/
    6798             : /*                           FindLayerIndex()                           */
    6799             : /************************************************************************/
    6800             : 
    6801          29 : int GDALGeoPackageDataset::FindLayerIndex(const char *pszLayerName)
    6802             : 
    6803             : {
    6804          51 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6805             :          iLayer++)
    6806             :     {
    6807          35 :         if (EQUAL(pszLayerName, m_apoLayers[iLayer]->GetName()))
    6808          13 :             return iLayer;
    6809             :     }
    6810          16 :     return -1;
    6811             : }
    6812             : 
    6813             : /************************************************************************/
    6814             : /*                         DeleteLayerCommon()                          */
    6815             : /************************************************************************/
    6816             : 
    6817          43 : OGRErr GDALGeoPackageDataset::DeleteLayerCommon(const char *pszLayerName)
    6818             : {
    6819             :     // Temporary remove foreign key checks
    6820             :     const GPKGTemporaryForeignKeyCheckDisabler
    6821          43 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6822             : 
    6823          43 :     char *pszSQL = sqlite3_mprintf(
    6824             :         "DELETE FROM gpkg_contents WHERE lower(table_name) = lower('%q')",
    6825             :         pszLayerName);
    6826          43 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    6827          43 :     sqlite3_free(pszSQL);
    6828             : 
    6829          43 :     if (eErr == OGRERR_NONE && HasExtensionsTable())
    6830             :     {
    6831          41 :         pszSQL = sqlite3_mprintf(
    6832             :             "DELETE FROM gpkg_extensions WHERE lower(table_name) = lower('%q')",
    6833             :             pszLayerName);
    6834          41 :         eErr = SQLCommand(hDB, pszSQL);
    6835          41 :         sqlite3_free(pszSQL);
    6836             :     }
    6837             : 
    6838          43 :     if (eErr == OGRERR_NONE && HasMetadataTables())
    6839             :     {
    6840             :         // Delete from gpkg_metadata metadata records that are only referenced
    6841             :         // by the table we are about to drop
    6842          12 :         pszSQL = sqlite3_mprintf(
    6843             :             "DELETE FROM gpkg_metadata WHERE id IN ("
    6844             :             "SELECT DISTINCT md_file_id FROM "
    6845             :             "gpkg_metadata_reference WHERE "
    6846             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6847             :             "AND id NOT IN ("
    6848             :             "SELECT DISTINCT md_file_id FROM gpkg_metadata_reference WHERE "
    6849             :             "md_file_id IN (SELECT DISTINCT md_file_id FROM "
    6850             :             "gpkg_metadata_reference WHERE "
    6851             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6852             :             "AND lower(table_name) <> lower('%q'))",
    6853             :             pszLayerName, pszLayerName, pszLayerName);
    6854          12 :         eErr = SQLCommand(hDB, pszSQL);
    6855          12 :         sqlite3_free(pszSQL);
    6856             : 
    6857          12 :         if (eErr == OGRERR_NONE)
    6858             :         {
    6859             :             pszSQL =
    6860          12 :                 sqlite3_mprintf("DELETE FROM gpkg_metadata_reference WHERE "
    6861             :                                 "lower(table_name) = lower('%q')",
    6862             :                                 pszLayerName);
    6863          12 :             eErr = SQLCommand(hDB, pszSQL);
    6864          12 :             sqlite3_free(pszSQL);
    6865             :         }
    6866             :     }
    6867             : 
    6868          43 :     if (eErr == OGRERR_NONE && HasGpkgextRelationsTable())
    6869             :     {
    6870             :         // Remove reference to potential corresponding mapping table in
    6871             :         // gpkg_extensions
    6872           4 :         pszSQL = sqlite3_mprintf(
    6873             :             "DELETE FROM gpkg_extensions WHERE "
    6874             :             "extension_name IN ('related_tables', "
    6875             :             "'gpkg_related_tables') AND lower(table_name) = "
    6876             :             "(SELECT lower(mapping_table_name) FROM gpkgext_relations WHERE "
    6877             :             "lower(base_table_name) = lower('%q') OR "
    6878             :             "lower(related_table_name) = lower('%q') OR "
    6879             :             "lower(mapping_table_name) = lower('%q'))",
    6880             :             pszLayerName, pszLayerName, pszLayerName);
    6881           4 :         eErr = SQLCommand(hDB, pszSQL);
    6882           4 :         sqlite3_free(pszSQL);
    6883             : 
    6884           4 :         if (eErr == OGRERR_NONE)
    6885             :         {
    6886             :             // Remove reference to potential corresponding mapping table in
    6887             :             // gpkgext_relations
    6888             :             pszSQL =
    6889           4 :                 sqlite3_mprintf("DELETE FROM gpkgext_relations WHERE "
    6890             :                                 "lower(base_table_name) = lower('%q') OR "
    6891             :                                 "lower(related_table_name) = lower('%q') OR "
    6892             :                                 "lower(mapping_table_name) = lower('%q')",
    6893             :                                 pszLayerName, pszLayerName, pszLayerName);
    6894           4 :             eErr = SQLCommand(hDB, pszSQL);
    6895           4 :             sqlite3_free(pszSQL);
    6896             :         }
    6897             : 
    6898           4 :         if (eErr == OGRERR_NONE && HasExtensionsTable())
    6899             :         {
    6900             :             // If there is no longer any mapping table, then completely
    6901             :             // remove any reference to the extension in gpkg_extensions
    6902             :             // as mandated per the related table specification.
    6903             :             OGRErr err;
    6904           4 :             if (SQLGetInteger(hDB,
    6905             :                               "SELECT COUNT(*) FROM gpkg_extensions WHERE "
    6906             :                               "extension_name IN ('related_tables', "
    6907             :                               "'gpkg_related_tables') AND "
    6908             :                               "lower(table_name) != 'gpkgext_relations'",
    6909           4 :                               &err) == 0)
    6910             :             {
    6911           2 :                 eErr = SQLCommand(hDB, "DELETE FROM gpkg_extensions WHERE "
    6912             :                                        "extension_name IN ('related_tables', "
    6913             :                                        "'gpkg_related_tables')");
    6914             :             }
    6915             : 
    6916           4 :             ClearCachedRelationships();
    6917             :         }
    6918             :     }
    6919             : 
    6920          43 :     if (eErr == OGRERR_NONE)
    6921             :     {
    6922          43 :         pszSQL = sqlite3_mprintf("DROP TABLE \"%w\"", pszLayerName);
    6923          43 :         eErr = SQLCommand(hDB, pszSQL);
    6924          43 :         sqlite3_free(pszSQL);
    6925             :     }
    6926             : 
    6927             :     // Check foreign key integrity
    6928          43 :     if (eErr == OGRERR_NONE)
    6929             :     {
    6930          43 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    6931             :     }
    6932             : 
    6933          86 :     return eErr;
    6934             : }
    6935             : 
    6936             : /************************************************************************/
    6937             : /*                            DeleteLayer()                             */
    6938             : /************************************************************************/
    6939             : 
    6940          40 : OGRErr GDALGeoPackageDataset::DeleteLayer(int iLayer)
    6941             : {
    6942          79 :     if (!GetUpdate() || iLayer < 0 ||
    6943          39 :         iLayer >= static_cast<int>(m_apoLayers.size()))
    6944           2 :         return OGRERR_FAILURE;
    6945             : 
    6946          38 :     m_apoLayers[iLayer]->ResetReading();
    6947          38 :     m_apoLayers[iLayer]->SyncToDisk();
    6948             : 
    6949          76 :     CPLString osLayerName = m_apoLayers[iLayer]->GetName();
    6950             : 
    6951          38 :     CPLDebug("GPKG", "DeleteLayer(%s)", osLayerName.c_str());
    6952             : 
    6953             :     // Temporary remove foreign key checks
    6954             :     const GPKGTemporaryForeignKeyCheckDisabler
    6955          38 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6956             : 
    6957          38 :     OGRErr eErr = SoftStartTransaction();
    6958             : 
    6959          38 :     if (eErr == OGRERR_NONE)
    6960             :     {
    6961          38 :         if (m_apoLayers[iLayer]->HasSpatialIndex())
    6962          35 :             m_apoLayers[iLayer]->DropSpatialIndex();
    6963             : 
    6964             :         char *pszSQL =
    6965          38 :             sqlite3_mprintf("DELETE FROM gpkg_geometry_columns WHERE "
    6966             :                             "lower(table_name) = lower('%q')",
    6967             :                             osLayerName.c_str());
    6968          38 :         eErr = SQLCommand(hDB, pszSQL);
    6969          38 :         sqlite3_free(pszSQL);
    6970             :     }
    6971             : 
    6972          38 :     if (eErr == OGRERR_NONE && HasDataColumnsTable())
    6973             :     {
    6974           1 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_data_columns WHERE "
    6975             :                                        "lower(table_name) = lower('%q')",
    6976             :                                        osLayerName.c_str());
    6977           1 :         eErr = SQLCommand(hDB, pszSQL);
    6978           1 :         sqlite3_free(pszSQL);
    6979             :     }
    6980             : 
    6981             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    6982          38 :     if (eErr == OGRERR_NONE && m_bHasGPKGOGRContents)
    6983             :     {
    6984          38 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_ogr_contents WHERE "
    6985             :                                        "lower(table_name) = lower('%q')",
    6986             :                                        osLayerName.c_str());
    6987          38 :         eErr = SQLCommand(hDB, pszSQL);
    6988          38 :         sqlite3_free(pszSQL);
    6989             :     }
    6990             : #endif
    6991             : 
    6992          38 :     if (eErr == OGRERR_NONE)
    6993             :     {
    6994          38 :         eErr = DeleteLayerCommon(osLayerName.c_str());
    6995             :     }
    6996             : 
    6997          38 :     if (eErr == OGRERR_NONE)
    6998             :     {
    6999          38 :         eErr = SoftCommitTransaction();
    7000          38 :         if (eErr == OGRERR_NONE)
    7001             :         {
    7002             :             /* Delete the layer object */
    7003          38 :             m_apoLayers.erase(m_apoLayers.begin() + iLayer);
    7004             :         }
    7005             :     }
    7006             :     else
    7007             :     {
    7008           0 :         SoftRollbackTransaction();
    7009             :     }
    7010             : 
    7011          38 :     return eErr;
    7012             : }
    7013             : 
    7014             : /************************************************************************/
    7015             : /*                         DeleteRasterLayer()                          */
    7016             : /************************************************************************/
    7017             : 
    7018           2 : OGRErr GDALGeoPackageDataset::DeleteRasterLayer(const char *pszLayerName)
    7019             : {
    7020             :     // Temporary remove foreign key checks
    7021             :     const GPKGTemporaryForeignKeyCheckDisabler
    7022           2 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7023             : 
    7024           2 :     OGRErr eErr = SoftStartTransaction();
    7025             : 
    7026           2 :     if (eErr == OGRERR_NONE)
    7027             :     {
    7028           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix WHERE "
    7029             :                                        "lower(table_name) = lower('%q')",
    7030             :                                        pszLayerName);
    7031           2 :         eErr = SQLCommand(hDB, pszSQL);
    7032           2 :         sqlite3_free(pszSQL);
    7033             :     }
    7034             : 
    7035           2 :     if (eErr == OGRERR_NONE)
    7036             :     {
    7037           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix_set WHERE "
    7038             :                                        "lower(table_name) = lower('%q')",
    7039             :                                        pszLayerName);
    7040           2 :         eErr = SQLCommand(hDB, pszSQL);
    7041           2 :         sqlite3_free(pszSQL);
    7042             :     }
    7043             : 
    7044           2 :     if (eErr == OGRERR_NONE && HasGriddedCoverageAncillaryTable())
    7045             :     {
    7046             :         char *pszSQL =
    7047           1 :             sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_coverage_ancillary "
    7048             :                             "WHERE lower(tile_matrix_set_name) = lower('%q')",
    7049             :                             pszLayerName);
    7050           1 :         eErr = SQLCommand(hDB, pszSQL);
    7051           1 :         sqlite3_free(pszSQL);
    7052             : 
    7053           1 :         if (eErr == OGRERR_NONE)
    7054             :         {
    7055             :             pszSQL =
    7056           1 :                 sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_tile_ancillary "
    7057             :                                 "WHERE lower(tpudt_name) = lower('%q')",
    7058             :                                 pszLayerName);
    7059           1 :             eErr = SQLCommand(hDB, pszSQL);
    7060           1 :             sqlite3_free(pszSQL);
    7061             :         }
    7062             :     }
    7063             : 
    7064           2 :     if (eErr == OGRERR_NONE)
    7065             :     {
    7066           2 :         eErr = DeleteLayerCommon(pszLayerName);
    7067             :     }
    7068             : 
    7069           2 :     if (eErr == OGRERR_NONE)
    7070             :     {
    7071           2 :         eErr = SoftCommitTransaction();
    7072             :     }
    7073             :     else
    7074             :     {
    7075           0 :         SoftRollbackTransaction();
    7076             :     }
    7077             : 
    7078           4 :     return eErr;
    7079             : }
    7080             : 
    7081             : /************************************************************************/
    7082             : /*                     DeleteVectorOrRasterLayer()                      */
    7083             : /************************************************************************/
    7084             : 
    7085          13 : bool GDALGeoPackageDataset::DeleteVectorOrRasterLayer(const char *pszLayerName)
    7086             : {
    7087             : 
    7088          13 :     int idx = FindLayerIndex(pszLayerName);
    7089          13 :     if (idx >= 0)
    7090             :     {
    7091           5 :         DeleteLayer(idx);
    7092           5 :         return true;
    7093             :     }
    7094             : 
    7095             :     char *pszSQL =
    7096           8 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7097             :                         "lower(table_name) = lower('%q') "
    7098             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7099             :                         pszLayerName);
    7100           8 :     bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7101           8 :     sqlite3_free(pszSQL);
    7102           8 :     if (bIsRasterTable)
    7103             :     {
    7104           2 :         DeleteRasterLayer(pszLayerName);
    7105           2 :         return true;
    7106             :     }
    7107           6 :     return false;
    7108             : }
    7109             : 
    7110           7 : bool GDALGeoPackageDataset::RenameVectorOrRasterLayer(
    7111             :     const char *pszLayerName, const char *pszNewLayerName)
    7112             : {
    7113           7 :     int idx = FindLayerIndex(pszLayerName);
    7114           7 :     if (idx >= 0)
    7115             :     {
    7116           4 :         m_apoLayers[idx]->Rename(pszNewLayerName);
    7117           4 :         return true;
    7118             :     }
    7119             : 
    7120             :     char *pszSQL =
    7121           3 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7122             :                         "lower(table_name) = lower('%q') "
    7123             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7124             :                         pszLayerName);
    7125           3 :     const bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7126           3 :     sqlite3_free(pszSQL);
    7127             : 
    7128           3 :     if (bIsRasterTable)
    7129             :     {
    7130           2 :         return RenameRasterLayer(pszLayerName, pszNewLayerName);
    7131             :     }
    7132             : 
    7133           1 :     return false;
    7134             : }
    7135             : 
    7136           2 : bool GDALGeoPackageDataset::RenameRasterLayer(const char *pszLayerName,
    7137             :                                               const char *pszNewLayerName)
    7138             : {
    7139           4 :     std::string osSQL;
    7140             : 
    7141           2 :     char *pszSQL = sqlite3_mprintf(
    7142             :         "SELECT 1 FROM sqlite_master WHERE lower(name) = lower('%q') "
    7143             :         "AND type IN ('table', 'view')",
    7144             :         pszNewLayerName);
    7145           2 :     const bool bAlreadyExists = SQLGetInteger(GetDB(), pszSQL, nullptr) == 1;
    7146           2 :     sqlite3_free(pszSQL);
    7147           2 :     if (bAlreadyExists)
    7148             :     {
    7149           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Table %s already exists",
    7150             :                  pszNewLayerName);
    7151           0 :         return false;
    7152             :     }
    7153             : 
    7154             :     // Temporary remove foreign key checks
    7155             :     const GPKGTemporaryForeignKeyCheckDisabler
    7156           4 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7157             : 
    7158           2 :     if (SoftStartTransaction() != OGRERR_NONE)
    7159             :     {
    7160           0 :         return false;
    7161             :     }
    7162             : 
    7163           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET table_name = '%q' WHERE "
    7164             :                              "lower(table_name) = lower('%q');",
    7165             :                              pszNewLayerName, pszLayerName);
    7166           2 :     osSQL = pszSQL;
    7167           2 :     sqlite3_free(pszSQL);
    7168             : 
    7169           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' WHERE "
    7170             :                              "lower(identifier) = lower('%q');",
    7171             :                              pszNewLayerName, pszLayerName);
    7172           2 :     osSQL += pszSQL;
    7173           2 :     sqlite3_free(pszSQL);
    7174             : 
    7175             :     pszSQL =
    7176           2 :         sqlite3_mprintf("UPDATE gpkg_tile_matrix SET table_name = '%q' WHERE "
    7177             :                         "lower(table_name) = lower('%q');",
    7178             :                         pszNewLayerName, pszLayerName);
    7179           2 :     osSQL += pszSQL;
    7180           2 :     sqlite3_free(pszSQL);
    7181             : 
    7182           2 :     pszSQL = sqlite3_mprintf(
    7183             :         "UPDATE gpkg_tile_matrix_set SET table_name = '%q' WHERE "
    7184             :         "lower(table_name) = lower('%q');",
    7185             :         pszNewLayerName, pszLayerName);
    7186           2 :     osSQL += pszSQL;
    7187           2 :     sqlite3_free(pszSQL);
    7188             : 
    7189           2 :     if (HasGriddedCoverageAncillaryTable())
    7190             :     {
    7191           1 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_2d_gridded_coverage_ancillary "
    7192             :                                  "SET tile_matrix_set_name = '%q' WHERE "
    7193             :                                  "lower(tile_matrix_set_name) = lower('%q');",
    7194             :                                  pszNewLayerName, pszLayerName);
    7195           1 :         osSQL += pszSQL;
    7196           1 :         sqlite3_free(pszSQL);
    7197             : 
    7198           1 :         pszSQL = sqlite3_mprintf(
    7199             :             "UPDATE gpkg_2d_gridded_tile_ancillary SET tpudt_name = '%q' WHERE "
    7200             :             "lower(tpudt_name) = lower('%q');",
    7201             :             pszNewLayerName, pszLayerName);
    7202           1 :         osSQL += pszSQL;
    7203           1 :         sqlite3_free(pszSQL);
    7204             :     }
    7205             : 
    7206           2 :     if (HasExtensionsTable())
    7207             :     {
    7208           2 :         pszSQL = sqlite3_mprintf(
    7209             :             "UPDATE gpkg_extensions SET table_name = '%q' WHERE "
    7210             :             "lower(table_name) = lower('%q');",
    7211             :             pszNewLayerName, pszLayerName);
    7212           2 :         osSQL += pszSQL;
    7213           2 :         sqlite3_free(pszSQL);
    7214             :     }
    7215             : 
    7216           2 :     if (HasMetadataTables())
    7217             :     {
    7218           1 :         pszSQL = sqlite3_mprintf(
    7219             :             "UPDATE gpkg_metadata_reference SET table_name = '%q' WHERE "
    7220             :             "lower(table_name) = lower('%q');",
    7221             :             pszNewLayerName, pszLayerName);
    7222           1 :         osSQL += pszSQL;
    7223           1 :         sqlite3_free(pszSQL);
    7224             :     }
    7225             : 
    7226           2 :     if (HasDataColumnsTable())
    7227             :     {
    7228           0 :         pszSQL = sqlite3_mprintf(
    7229             :             "UPDATE gpkg_data_columns SET table_name = '%q' WHERE "
    7230             :             "lower(table_name) = lower('%q');",
    7231             :             pszNewLayerName, pszLayerName);
    7232           0 :         osSQL += pszSQL;
    7233           0 :         sqlite3_free(pszSQL);
    7234             :     }
    7235             : 
    7236           2 :     if (HasQGISLayerStyles())
    7237             :     {
    7238             :         // Update QGIS styles
    7239             :         pszSQL =
    7240           0 :             sqlite3_mprintf("UPDATE layer_styles SET f_table_name = '%q' WHERE "
    7241             :                             "lower(f_table_name) = lower('%q');",
    7242             :                             pszNewLayerName, pszLayerName);
    7243           0 :         osSQL += pszSQL;
    7244           0 :         sqlite3_free(pszSQL);
    7245             :     }
    7246             : 
    7247             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7248           2 :     if (m_bHasGPKGOGRContents)
    7249             :     {
    7250           2 :         pszSQL = sqlite3_mprintf(
    7251             :             "UPDATE gpkg_ogr_contents SET table_name = '%q' WHERE "
    7252             :             "lower(table_name) = lower('%q');",
    7253             :             pszNewLayerName, pszLayerName);
    7254           2 :         osSQL += pszSQL;
    7255           2 :         sqlite3_free(pszSQL);
    7256             :     }
    7257             : #endif
    7258             : 
    7259           2 :     if (HasGpkgextRelationsTable())
    7260             :     {
    7261           0 :         pszSQL = sqlite3_mprintf(
    7262             :             "UPDATE gpkgext_relations SET base_table_name = '%q' WHERE "
    7263             :             "lower(base_table_name) = lower('%q');",
    7264             :             pszNewLayerName, pszLayerName);
    7265           0 :         osSQL += pszSQL;
    7266           0 :         sqlite3_free(pszSQL);
    7267             : 
    7268           0 :         pszSQL = sqlite3_mprintf(
    7269             :             "UPDATE gpkgext_relations SET related_table_name = '%q' WHERE "
    7270             :             "lower(related_table_name) = lower('%q');",
    7271             :             pszNewLayerName, pszLayerName);
    7272           0 :         osSQL += pszSQL;
    7273           0 :         sqlite3_free(pszSQL);
    7274             : 
    7275           0 :         pszSQL = sqlite3_mprintf(
    7276             :             "UPDATE gpkgext_relations SET mapping_table_name = '%q' WHERE "
    7277             :             "lower(mapping_table_name) = lower('%q');",
    7278             :             pszNewLayerName, pszLayerName);
    7279           0 :         osSQL += pszSQL;
    7280           0 :         sqlite3_free(pszSQL);
    7281             :     }
    7282             : 
    7283             :     // Drop all triggers for the layer
    7284           2 :     pszSQL = sqlite3_mprintf("SELECT name FROM sqlite_master WHERE type = "
    7285             :                              "'trigger' AND tbl_name = '%q'",
    7286             :                              pszLayerName);
    7287           2 :     auto oTriggerResult = SQLQuery(GetDB(), pszSQL);
    7288           2 :     sqlite3_free(pszSQL);
    7289           2 :     if (oTriggerResult)
    7290             :     {
    7291          14 :         for (int i = 0; i < oTriggerResult->RowCount(); i++)
    7292             :         {
    7293          12 :             const char *pszTriggerName = oTriggerResult->GetValue(0, i);
    7294          12 :             pszSQL = sqlite3_mprintf("DROP TRIGGER IF EXISTS \"%w\";",
    7295             :                                      pszTriggerName);
    7296          12 :             osSQL += pszSQL;
    7297          12 :             sqlite3_free(pszSQL);
    7298             :         }
    7299             :     }
    7300             : 
    7301           2 :     pszSQL = sqlite3_mprintf("ALTER TABLE \"%w\" RENAME TO \"%w\";",
    7302             :                              pszLayerName, pszNewLayerName);
    7303           2 :     osSQL += pszSQL;
    7304           2 :     sqlite3_free(pszSQL);
    7305             : 
    7306             :     // Recreate all zoom/tile triggers
    7307           2 :     if (oTriggerResult)
    7308             :     {
    7309           2 :         osSQL += CreateRasterTriggersSQL(pszNewLayerName);
    7310             :     }
    7311             : 
    7312           2 :     OGRErr eErr = SQLCommand(GetDB(), osSQL.c_str());
    7313             : 
    7314             :     // Check foreign key integrity
    7315           2 :     if (eErr == OGRERR_NONE)
    7316             :     {
    7317           2 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    7318             :     }
    7319             : 
    7320           2 :     if (eErr == OGRERR_NONE)
    7321             :     {
    7322           2 :         eErr = SoftCommitTransaction();
    7323             :     }
    7324             :     else
    7325             :     {
    7326           0 :         SoftRollbackTransaction();
    7327             :     }
    7328             : 
    7329           2 :     return eErr == OGRERR_NONE;
    7330             : }
    7331             : 
    7332             : /************************************************************************/
    7333             : /*                           TestCapability()                           */
    7334             : /************************************************************************/
    7335             : 
    7336         623 : bool GDALGeoPackageDataset::TestCapability(const char *pszCap) const
    7337             : {
    7338         623 :     if (EQUAL(pszCap, ODsCCreateLayer) || EQUAL(pszCap, ODsCDeleteLayer) ||
    7339         408 :         EQUAL(pszCap, "RenameLayer"))
    7340             :     {
    7341         215 :         return GetUpdate();
    7342             :     }
    7343         408 :     else if (EQUAL(pszCap, ODsCCurveGeometries))
    7344          12 :         return TRUE;
    7345         396 :     else if (EQUAL(pszCap, ODsCMeasuredGeometries))
    7346           8 :         return TRUE;
    7347         388 :     else if (EQUAL(pszCap, ODsCZGeometries))
    7348           8 :         return TRUE;
    7349         380 :     else if (EQUAL(pszCap, ODsCRandomLayerWrite) ||
    7350         380 :              EQUAL(pszCap, GDsCAddRelationship) ||
    7351         380 :              EQUAL(pszCap, GDsCDeleteRelationship) ||
    7352         380 :              EQUAL(pszCap, GDsCUpdateRelationship) ||
    7353         380 :              EQUAL(pszCap, ODsCAddFieldDomain) ||
    7354         378 :              EQUAL(pszCap, ODsCUpdateFieldDomain) ||
    7355         376 :              EQUAL(pszCap, ODsCDeleteFieldDomain))
    7356             :     {
    7357           6 :         return GetUpdate();
    7358             :     }
    7359             : 
    7360         374 :     return OGRSQLiteBaseDataSource::TestCapability(pszCap);
    7361             : }
    7362             : 
    7363             : /************************************************************************/
    7364             : /*                       ResetReadingAllLayers()                        */
    7365             : /************************************************************************/
    7366             : 
    7367         208 : void GDALGeoPackageDataset::ResetReadingAllLayers()
    7368             : {
    7369         421 :     for (auto &poLayer : m_apoLayers)
    7370             :     {
    7371         213 :         poLayer->ResetReading();
    7372             :     }
    7373         208 : }
    7374             : 
    7375             : /************************************************************************/
    7376             : /*                             ExecuteSQL()                             */
    7377             : /************************************************************************/
    7378             : 
    7379             : static const char *const apszFuncsWithSideEffects[] = {
    7380             :     "CreateSpatialIndex",
    7381             :     "DisableSpatialIndex",
    7382             :     "HasSpatialIndex",
    7383             :     "RegisterGeometryExtension",
    7384             : };
    7385             : 
    7386        5729 : OGRLayer *GDALGeoPackageDataset::ExecuteSQL(const char *pszSQLCommand,
    7387             :                                             OGRGeometry *poSpatialFilter,
    7388             :                                             const char *pszDialect)
    7389             : 
    7390             : {
    7391        5729 :     m_bHasReadMetadataFromStorage = false;
    7392             : 
    7393        5729 :     FlushMetadata();
    7394             : 
    7395        5747 :     while (*pszSQLCommand != '\0' &&
    7396        5747 :            isspace(static_cast<unsigned char>(*pszSQLCommand)))
    7397          18 :         pszSQLCommand++;
    7398             : 
    7399       11458 :     CPLString osSQLCommand(pszSQLCommand);
    7400        5729 :     if (!osSQLCommand.empty() && osSQLCommand.back() == ';')
    7401          48 :         osSQLCommand.pop_back();
    7402             : 
    7403       11457 :     if (osSQLCommand.ifind("AsGPB(ST_") != std::string::npos ||
    7404        5728 :         osSQLCommand.ifind("AsGPB( ST_") != std::string::npos)
    7405             :     {
    7406           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    7407             :                  "Use of AsGPB(ST_xxx(...)) found in \"%s\". Since GDAL 3.13, "
    7408             :                  "ST_xxx() functions return a GeoPackage geometry when used "
    7409             :                  "with a GeoPackage connection, and the use of AsGPB() is no "
    7410             :                  "longer needed. It is here automatically removed",
    7411             :                  osSQLCommand.c_str());
    7412           1 :         osSQLCommand.replaceAll("AsGPB(ST_", "(ST_");
    7413           1 :         osSQLCommand.replaceAll("AsGPB( ST_", "(ST_");
    7414             :     }
    7415             : 
    7416        5729 :     if (pszDialect == nullptr || !EQUAL(pszDialect, "DEBUG"))
    7417             :     {
    7418             :         // Some SQL commands will influence the feature count behind our
    7419             :         // back, so disable it in that case.
    7420             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7421             :         const bool bInsertOrDelete =
    7422        5660 :             osSQLCommand.ifind("insert into ") != std::string::npos ||
    7423        2539 :             osSQLCommand.ifind("insert or replace into ") !=
    7424        8199 :                 std::string::npos ||
    7425        2502 :             osSQLCommand.ifind("delete from ") != std::string::npos;
    7426             :         const bool bRollback =
    7427        5660 :             osSQLCommand.ifind("rollback ") != std::string::npos;
    7428             : #endif
    7429             : 
    7430        7581 :         for (auto &poLayer : m_apoLayers)
    7431             :         {
    7432        1921 :             if (poLayer->SyncToDisk() != OGRERR_NONE)
    7433           0 :                 return nullptr;
    7434             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7435        2126 :             if (bRollback ||
    7436         205 :                 (bInsertOrDelete &&
    7437         205 :                  osSQLCommand.ifind(poLayer->GetName()) != std::string::npos))
    7438             :             {
    7439         203 :                 poLayer->DisableFeatureCount();
    7440             :             }
    7441             : #endif
    7442             :         }
    7443             :     }
    7444             : 
    7445        5729 :     if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 0") ||
    7446        5728 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=0") ||
    7447        5728 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =0") ||
    7448        5728 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 0"))
    7449             :     {
    7450           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, false);
    7451             :     }
    7452        5728 :     else if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 1") ||
    7453        5727 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=1") ||
    7454        5727 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =1") ||
    7455        5727 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 1"))
    7456             :     {
    7457           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, true);
    7458             :     }
    7459             : 
    7460             :     /* -------------------------------------------------------------------- */
    7461             :     /*      DEBUG "SELECT nolock" command.                                  */
    7462             :     /* -------------------------------------------------------------------- */
    7463        5798 :     if (pszDialect != nullptr && EQUAL(pszDialect, "DEBUG") &&
    7464          69 :         EQUAL(osSQLCommand, "SELECT nolock"))
    7465             :     {
    7466           3 :         return new OGRSQLiteSingleFeatureLayer(osSQLCommand, m_bNoLock ? 1 : 0);
    7467             :     }
    7468             : 
    7469             :     /* -------------------------------------------------------------------- */
    7470             :     /*      Special case DELLAYER: command.                                 */
    7471             :     /* -------------------------------------------------------------------- */
    7472        5726 :     if (STARTS_WITH_CI(osSQLCommand, "DELLAYER:"))
    7473             :     {
    7474           4 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DELLAYER:");
    7475             : 
    7476           4 :         while (*pszLayerName == ' ')
    7477           0 :             pszLayerName++;
    7478             : 
    7479           4 :         if (!DeleteVectorOrRasterLayer(pszLayerName))
    7480             :         {
    7481           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7482             :                      pszLayerName);
    7483             :         }
    7484           4 :         return nullptr;
    7485             :     }
    7486             : 
    7487             :     /* -------------------------------------------------------------------- */
    7488             :     /*      Special case RECOMPUTE EXTENT ON command.                       */
    7489             :     /* -------------------------------------------------------------------- */
    7490        5722 :     if (STARTS_WITH_CI(osSQLCommand, "RECOMPUTE EXTENT ON "))
    7491             :     {
    7492             :         const char *pszLayerName =
    7493           4 :             osSQLCommand.c_str() + strlen("RECOMPUTE EXTENT ON ");
    7494             : 
    7495           4 :         while (*pszLayerName == ' ')
    7496           0 :             pszLayerName++;
    7497             : 
    7498           4 :         int idx = FindLayerIndex(pszLayerName);
    7499           4 :         if (idx >= 0)
    7500             :         {
    7501           4 :             m_apoLayers[idx]->RecomputeExtent();
    7502             :         }
    7503             :         else
    7504           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7505             :                      pszLayerName);
    7506           4 :         return nullptr;
    7507             :     }
    7508             : 
    7509             :     /* -------------------------------------------------------------------- */
    7510             :     /*      Intercept DROP TABLE                                            */
    7511             :     /* -------------------------------------------------------------------- */
    7512        5718 :     if (STARTS_WITH_CI(osSQLCommand, "DROP TABLE "))
    7513             :     {
    7514           9 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DROP TABLE ");
    7515             : 
    7516           9 :         while (*pszLayerName == ' ')
    7517           0 :             pszLayerName++;
    7518             : 
    7519           9 :         if (DeleteVectorOrRasterLayer(SQLUnescape(pszLayerName)))
    7520           4 :             return nullptr;
    7521             :     }
    7522             : 
    7523             :     /* -------------------------------------------------------------------- */
    7524             :     /*      Intercept ALTER TABLE src_table RENAME TO dst_table             */
    7525             :     /*      and       ALTER TABLE table RENAME COLUMN src_name TO dst_name  */
    7526             :     /*      and       ALTER TABLE table DROP COLUMN col_name                */
    7527             :     /*                                                                      */
    7528             :     /*      We do this because SQLite mechanisms can't deal with updating   */
    7529             :     /*      literal values in gpkg_ tables that refer to table and column   */
    7530             :     /*      names.                                                          */
    7531             :     /* -------------------------------------------------------------------- */
    7532        5714 :     if (STARTS_WITH_CI(osSQLCommand, "ALTER TABLE "))
    7533             :     {
    7534           9 :         char **papszTokens = SQLTokenize(osSQLCommand);
    7535             :         /* ALTER TABLE src_table RENAME TO dst_table */
    7536          16 :         if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "RENAME") &&
    7537           7 :             EQUAL(papszTokens[4], "TO"))
    7538             :         {
    7539           7 :             const char *pszSrcTableName = papszTokens[2];
    7540           7 :             const char *pszDstTableName = papszTokens[5];
    7541           7 :             if (RenameVectorOrRasterLayer(SQLUnescape(pszSrcTableName),
    7542          14 :                                           SQLUnescape(pszDstTableName)))
    7543             :             {
    7544           6 :                 CSLDestroy(papszTokens);
    7545           6 :                 return nullptr;
    7546             :             }
    7547             :         }
    7548             :         /* ALTER TABLE table RENAME COLUMN src_name TO dst_name */
    7549           2 :         else if (CSLCount(papszTokens) == 8 &&
    7550           1 :                  EQUAL(papszTokens[3], "RENAME") &&
    7551           3 :                  EQUAL(papszTokens[4], "COLUMN") && EQUAL(papszTokens[6], "TO"))
    7552             :         {
    7553           1 :             const char *pszTableName = papszTokens[2];
    7554           1 :             const char *pszSrcColumn = papszTokens[5];
    7555           1 :             const char *pszDstColumn = papszTokens[7];
    7556             :             OGRGeoPackageTableLayer *poLayer =
    7557           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7558           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7559           1 :             if (poLayer)
    7560             :             {
    7561           2 :                 int nSrcFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7562           2 :                     SQLUnescape(pszSrcColumn));
    7563           1 :                 if (nSrcFieldIdx >= 0)
    7564             :                 {
    7565             :                     // OFTString or any type will do as we just alter the name
    7566             :                     // so it will be ignored.
    7567           1 :                     OGRFieldDefn oFieldDefn(SQLUnescape(pszDstColumn),
    7568           1 :                                             OFTString);
    7569           1 :                     poLayer->AlterFieldDefn(nSrcFieldIdx, &oFieldDefn,
    7570             :                                             ALTER_NAME_FLAG);
    7571           1 :                     CSLDestroy(papszTokens);
    7572           1 :                     return nullptr;
    7573             :                 }
    7574             :             }
    7575             :         }
    7576             :         /* ALTER TABLE table DROP COLUMN col_name */
    7577           2 :         else if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "DROP") &&
    7578           1 :                  EQUAL(papszTokens[4], "COLUMN"))
    7579             :         {
    7580           1 :             const char *pszTableName = papszTokens[2];
    7581           1 :             const char *pszColumnName = papszTokens[5];
    7582             :             OGRGeoPackageTableLayer *poLayer =
    7583           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7584           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7585           1 :             if (poLayer)
    7586             :             {
    7587           2 :                 int nFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7588           2 :                     SQLUnescape(pszColumnName));
    7589           1 :                 if (nFieldIdx >= 0)
    7590             :                 {
    7591           1 :                     poLayer->DeleteField(nFieldIdx);
    7592           1 :                     CSLDestroy(papszTokens);
    7593           1 :                     return nullptr;
    7594             :                 }
    7595             :             }
    7596             :         }
    7597           1 :         CSLDestroy(papszTokens);
    7598             :     }
    7599             : 
    7600        5706 :     if (ProcessTransactionSQL(osSQLCommand))
    7601             :     {
    7602         260 :         return nullptr;
    7603             :     }
    7604             : 
    7605        5446 :     if (EQUAL(osSQLCommand, "VACUUM"))
    7606             :     {
    7607          13 :         ResetReadingAllLayers();
    7608             :     }
    7609        5433 :     else if (STARTS_WITH_CI(osSQLCommand, "DELETE FROM "))
    7610             :     {
    7611             :         // Optimize truncation of a table, especially if it has a spatial
    7612             :         // index.
    7613          23 :         const CPLStringList aosTokens(SQLTokenize(osSQLCommand));
    7614          23 :         if (aosTokens.size() == 3)
    7615             :         {
    7616          16 :             const char *pszTableName = aosTokens[2];
    7617             :             OGRGeoPackageTableLayer *poLayer =
    7618           8 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7619          24 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7620          16 :             if (poLayer)
    7621             :             {
    7622           8 :                 poLayer->Truncate();
    7623           8 :                 return nullptr;
    7624             :             }
    7625             :         }
    7626             :     }
    7627        5410 :     else if (pszDialect != nullptr && EQUAL(pszDialect, "INDIRECT_SQLITE"))
    7628           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter, "SQLITE");
    7629        5409 :     else if (pszDialect != nullptr && !EQUAL(pszDialect, "") &&
    7630          67 :              !EQUAL(pszDialect, "NATIVE") && !EQUAL(pszDialect, "SQLITE") &&
    7631          67 :              !EQUAL(pszDialect, "DEBUG"))
    7632           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter,
    7633           1 :                                        pszDialect);
    7634             : 
    7635             :     /* -------------------------------------------------------------------- */
    7636             :     /*      Prepare statement.                                              */
    7637             :     /* -------------------------------------------------------------------- */
    7638             :     /* This will speed-up layer creation */
    7639             :     /* ORDER BY are costly to evaluate and are not necessary to establish */
    7640             :     /* the layer definition. */
    7641        5436 :     bool bUseStatementForGetNextFeature = true;
    7642        5436 :     bool bEmptyLayer = false;
    7643       10872 :     CPLString osSQLCommandTruncated(osSQLCommand);
    7644             : 
    7645       18060 :     if (osSQLCommand.ifind("SELECT ") == 0 &&
    7646        6312 :         CPLString(osSQLCommand.substr(1)).ifind("SELECT ") ==
    7647         835 :             std::string::npos &&
    7648         835 :         osSQLCommand.ifind(" UNION ") == std::string::npos &&
    7649        7147 :         osSQLCommand.ifind(" INTERSECT ") == std::string::npos &&
    7650         835 :         osSQLCommand.ifind(" EXCEPT ") == std::string::npos)
    7651             :     {
    7652         835 :         size_t nOrderByPos = osSQLCommand.ifind(" ORDER BY ");
    7653         835 :         if (nOrderByPos != std::string::npos)
    7654             :         {
    7655           9 :             osSQLCommandTruncated.resize(nOrderByPos);
    7656           9 :             bUseStatementForGetNextFeature = false;
    7657             :         }
    7658             :     }
    7659             : 
    7660        5436 :     const auto nErrorCount = CPLGetErrorCounter();
    7661             :     sqlite3_stmt *hSQLStmt =
    7662        5436 :         prepareSql(hDB, osSQLCommandTruncated.c_str(),
    7663        5436 :                    static_cast<int>(osSQLCommandTruncated.size()));
    7664        5436 :     if (!hSQLStmt)
    7665             :     {
    7666           9 :         if (nErrorCount == CPLGetErrorCounter())
    7667             :         {
    7668           6 :             CPLError(CE_Failure, CPLE_AppDefined, "%s",
    7669          12 :                      SQLFormatErrorMsgFailedPrepare(
    7670             :                          GetDB(), "In ExecuteSQL(): sqlite3_prepare_v2(): ",
    7671             :                          osSQLCommand.c_str())
    7672             :                          .c_str());
    7673             :         }
    7674           9 :         return nullptr;
    7675             :     }
    7676             : 
    7677             :     /* -------------------------------------------------------------------- */
    7678             :     /*      Do we get a resultset?                                          */
    7679             :     /* -------------------------------------------------------------------- */
    7680        5427 :     int rc = sqlite3_step(hSQLStmt);
    7681             : 
    7682        7108 :     for (auto &poLayer : m_apoLayers)
    7683             :     {
    7684        1681 :         if (!poLayer->RunDeferredDropRTreeTableIfNecessary())
    7685           0 :             return nullptr;
    7686             :     }
    7687             : 
    7688        5427 :     if (rc != SQLITE_ROW)
    7689             :     {
    7690        4638 :         if (rc != SQLITE_DONE)
    7691             :         {
    7692           7 :             CPLError(CE_Failure, CPLE_AppDefined,
    7693             :                      "In ExecuteSQL(): sqlite3_step(%s):\n  %s",
    7694             :                      osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7695             : 
    7696           7 :             sqlite3_finalize(hSQLStmt);
    7697           7 :             return nullptr;
    7698             :         }
    7699             : 
    7700        4631 :         if (EQUAL(osSQLCommand, "VACUUM"))
    7701             :         {
    7702          13 :             sqlite3_finalize(hSQLStmt);
    7703             :             /* VACUUM rewrites the DB, so we need to reset the application id */
    7704          13 :             SetApplicationAndUserVersionId();
    7705          13 :             return nullptr;
    7706             :         }
    7707             : 
    7708        4618 :         if (!STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7709             :         {
    7710        4490 :             sqlite3_finalize(hSQLStmt);
    7711        4490 :             return nullptr;
    7712             :         }
    7713             : 
    7714         128 :         bUseStatementForGetNextFeature = false;
    7715         128 :         bEmptyLayer = true;
    7716             :     }
    7717             : 
    7718             :     /* -------------------------------------------------------------------- */
    7719             :     /*      Special case for some functions which must be run               */
    7720             :     /*      only once                                                       */
    7721             :     /* -------------------------------------------------------------------- */
    7722         917 :     if (STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7723             :     {
    7724        4209 :         for (unsigned int i = 0; i < sizeof(apszFuncsWithSideEffects) /
    7725             :                                          sizeof(apszFuncsWithSideEffects[0]);
    7726             :              i++)
    7727             :         {
    7728        3393 :             if (EQUALN(apszFuncsWithSideEffects[i], osSQLCommand.c_str() + 7,
    7729             :                        strlen(apszFuncsWithSideEffects[i])))
    7730             :             {
    7731         112 :                 if (sqlite3_column_count(hSQLStmt) == 1 &&
    7732          56 :                     sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7733             :                 {
    7734          56 :                     int ret = sqlite3_column_int(hSQLStmt, 0);
    7735             : 
    7736          56 :                     sqlite3_finalize(hSQLStmt);
    7737             : 
    7738             :                     return new OGRSQLiteSingleFeatureLayer(
    7739          56 :                         apszFuncsWithSideEffects[i], ret);
    7740             :                 }
    7741             :             }
    7742             :         }
    7743             :     }
    7744          45 :     else if (STARTS_WITH_CI(osSQLCommand, "PRAGMA "))
    7745             :     {
    7746          63 :         if (sqlite3_column_count(hSQLStmt) == 1 &&
    7747          18 :             sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7748             :         {
    7749          15 :             int ret = sqlite3_column_int(hSQLStmt, 0);
    7750             : 
    7751          15 :             sqlite3_finalize(hSQLStmt);
    7752             : 
    7753          15 :             return new OGRSQLiteSingleFeatureLayer(osSQLCommand.c_str() + 7,
    7754          15 :                                                    ret);
    7755             :         }
    7756          33 :         else if (sqlite3_column_count(hSQLStmt) == 1 &&
    7757           3 :                  sqlite3_column_type(hSQLStmt, 0) == SQLITE_TEXT)
    7758             :         {
    7759             :             const char *pszRet = reinterpret_cast<const char *>(
    7760           3 :                 sqlite3_column_text(hSQLStmt, 0));
    7761             : 
    7762             :             OGRLayer *poRet = new OGRSQLiteSingleFeatureLayer(
    7763           3 :                 osSQLCommand.c_str() + 7, pszRet);
    7764             : 
    7765           3 :             sqlite3_finalize(hSQLStmt);
    7766             : 
    7767           3 :             return poRet;
    7768             :         }
    7769             :     }
    7770             : 
    7771             :     /* -------------------------------------------------------------------- */
    7772             :     /*      Create layer.                                                   */
    7773             :     /* -------------------------------------------------------------------- */
    7774             : 
    7775             :     auto poLayer = std::make_unique<OGRGeoPackageSelectLayer>(
    7776             :         this, osSQLCommand, hSQLStmt, bUseStatementForGetNextFeature,
    7777        1686 :         bEmptyLayer);
    7778             : 
    7779         846 :     if (poSpatialFilter != nullptr &&
    7780           3 :         poLayer->GetLayerDefn()->GetGeomFieldCount() > 0)
    7781           3 :         poLayer->SetSpatialFilter(0, poSpatialFilter);
    7782             : 
    7783         843 :     return poLayer.release();
    7784             : }
    7785             : 
    7786             : /************************************************************************/
    7787             : /*                          ReleaseResultSet()                          */
    7788             : /************************************************************************/
    7789             : 
    7790         876 : void GDALGeoPackageDataset::ReleaseResultSet(OGRLayer *poLayer)
    7791             : 
    7792             : {
    7793         876 :     delete poLayer;
    7794         876 : }
    7795             : 
    7796             : /************************************************************************/
    7797             : /*                         HasExtensionsTable()                         */
    7798             : /************************************************************************/
    7799             : 
    7800        8338 : bool GDALGeoPackageDataset::HasExtensionsTable()
    7801             : {
    7802        8338 :     return SQLGetInteger(
    7803             :                hDB,
    7804             :                "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_extensions' "
    7805             :                "AND type IN ('table', 'view')",
    7806        8338 :                nullptr) == 1;
    7807             : }
    7808             : 
    7809             : /************************************************************************/
    7810             : /*                       CheckUnknownExtensions()                       */
    7811             : /************************************************************************/
    7812             : 
    7813        1771 : void GDALGeoPackageDataset::CheckUnknownExtensions(bool bCheckRasterTable)
    7814             : {
    7815        1771 :     if (!HasExtensionsTable())
    7816         217 :         return;
    7817             : 
    7818        1554 :     char *pszSQL = nullptr;
    7819        1554 :     if (!bCheckRasterTable)
    7820        1334 :         pszSQL = sqlite3_mprintf(
    7821             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7822             :             "WHERE (table_name IS NULL "
    7823             :             "AND extension_name IS NOT NULL "
    7824             :             "AND definition IS NOT NULL "
    7825             :             "AND scope IS NOT NULL "
    7826             :             "AND extension_name NOT IN ("
    7827             :             "'gdal_aspatial', "
    7828             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7829             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7830             :                                        // 17-066r1 finalization
    7831             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7832             :             "'gpkg_metadata', "
    7833             :             "'gpkg_schema', "
    7834             :             "'gpkg_crs_wkt', "
    7835             :             "'gpkg_crs_wkt_1_1', "
    7836             :             "'related_tables', 'gpkg_related_tables')) "
    7837             : #ifdef WORKAROUND_SQLITE3_BUGS
    7838             :             "OR 0 "
    7839             : #endif
    7840             :             "LIMIT 1000");
    7841             :     else
    7842         220 :         pszSQL = sqlite3_mprintf(
    7843             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7844             :             "WHERE (lower(table_name) = lower('%q') "
    7845             :             "AND extension_name IS NOT NULL "
    7846             :             "AND definition IS NOT NULL "
    7847             :             "AND scope IS NOT NULL "
    7848             :             "AND extension_name NOT IN ("
    7849             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7850             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7851             :                                        // 17-066r1 finalization
    7852             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7853             :             "'gpkg_metadata', "
    7854             :             "'gpkg_schema', "
    7855             :             "'gpkg_crs_wkt', "
    7856             :             "'gpkg_crs_wkt_1_1', "
    7857             :             "'related_tables', 'gpkg_related_tables')) "
    7858             : #ifdef WORKAROUND_SQLITE3_BUGS
    7859             :             "OR 0 "
    7860             : #endif
    7861             :             "LIMIT 1000",
    7862             :             m_osRasterTable.c_str());
    7863             : 
    7864        3108 :     auto oResultTable = SQLQuery(GetDB(), pszSQL);
    7865        1554 :     sqlite3_free(pszSQL);
    7866        1554 :     if (oResultTable && oResultTable->RowCount() > 0)
    7867             :     {
    7868          42 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    7869             :         {
    7870          21 :             const char *pszExtName = oResultTable->GetValue(0, i);
    7871          21 :             const char *pszDefinition = oResultTable->GetValue(1, i);
    7872          21 :             const char *pszScope = oResultTable->GetValue(2, i);
    7873          21 :             if (pszExtName == nullptr || pszDefinition == nullptr ||
    7874             :                 pszScope == nullptr)
    7875             :             {
    7876           0 :                 continue;
    7877             :             }
    7878             : 
    7879          21 :             if (EQUAL(pszExtName, "gpkg_webp"))
    7880             :             {
    7881          15 :                 if (GDALGetDriverByName("WEBP") == nullptr)
    7882             :                 {
    7883           1 :                     CPLError(
    7884             :                         CE_Warning, CPLE_AppDefined,
    7885             :                         "Table %s contains WEBP tiles, but GDAL configured "
    7886             :                         "without WEBP support. Data will be missing",
    7887             :                         m_osRasterTable.c_str());
    7888             :                 }
    7889          15 :                 m_eTF = GPKG_TF_WEBP;
    7890          15 :                 continue;
    7891             :             }
    7892           6 :             if (EQUAL(pszExtName, "gpkg_zoom_other"))
    7893             :             {
    7894           2 :                 m_bZoomOther = true;
    7895           2 :                 continue;
    7896             :             }
    7897             : 
    7898           4 :             if (GetUpdate() && EQUAL(pszScope, "write-only"))
    7899             :             {
    7900           1 :                 CPLError(
    7901             :                     CE_Warning, CPLE_AppDefined,
    7902             :                     "Database relies on the '%s' (%s) extension that should "
    7903             :                     "be implemented for safe write-support, but is not "
    7904             :                     "currently. "
    7905             :                     "Update of that database are strongly discouraged to avoid "
    7906             :                     "corruption.",
    7907             :                     pszExtName, pszDefinition);
    7908             :             }
    7909           3 :             else if (GetUpdate() && EQUAL(pszScope, "read-write"))
    7910             :             {
    7911           1 :                 CPLError(
    7912             :                     CE_Warning, CPLE_AppDefined,
    7913             :                     "Database relies on the '%s' (%s) extension that should "
    7914             :                     "be implemented in order to read/write it safely, but is "
    7915             :                     "not currently. "
    7916             :                     "Some data may be missing while reading that database, and "
    7917             :                     "updates are strongly discouraged.",
    7918             :                     pszExtName, pszDefinition);
    7919             :             }
    7920           2 :             else if (EQUAL(pszScope, "read-write") &&
    7921             :                      // None of the NGA extensions at
    7922             :                      // http://ngageoint.github.io/GeoPackage/docs/extensions/
    7923             :                      // affect read-only scenarios
    7924           1 :                      !STARTS_WITH(pszExtName, "nga_"))
    7925             :             {
    7926           1 :                 CPLError(
    7927             :                     CE_Warning, CPLE_AppDefined,
    7928             :                     "Database relies on the '%s' (%s) extension that should "
    7929             :                     "be implemented in order to read it safely, but is not "
    7930             :                     "currently. "
    7931             :                     "Some data may be missing while reading that database.",
    7932             :                     pszExtName, pszDefinition);
    7933             :             }
    7934             :         }
    7935             :     }
    7936             : }
    7937             : 
    7938             : /************************************************************************/
    7939             : /*                      HasGDALAspatialExtension()                      */
    7940             : /************************************************************************/
    7941             : 
    7942        1432 : bool GDALGeoPackageDataset::HasGDALAspatialExtension()
    7943             : {
    7944        1432 :     if (!HasExtensionsTable())
    7945         141 :         return false;
    7946             : 
    7947             :     auto oResultTable = SQLQuery(hDB, "SELECT * FROM gpkg_extensions "
    7948             :                                       "WHERE (extension_name = 'gdal_aspatial' "
    7949             :                                       "AND table_name IS NULL "
    7950             :                                       "AND column_name IS NULL)"
    7951             : #ifdef WORKAROUND_SQLITE3_BUGS
    7952             :                                       " OR 0"
    7953             : #endif
    7954        1291 :     );
    7955        1291 :     bool bHasExtension = (oResultTable && oResultTable->RowCount() == 1);
    7956        1291 :     return bHasExtension;
    7957             : }
    7958             : 
    7959             : std::string
    7960         201 : GDALGeoPackageDataset::CreateRasterTriggersSQL(const std::string &osTableName)
    7961             : {
    7962             :     char *pszSQL;
    7963         201 :     std::string osSQL;
    7964             :     /* From D.5. sample_tile_pyramid Table 43. tiles table Trigger
    7965             :      * Definition SQL  */
    7966         201 :     pszSQL = sqlite3_mprintf(
    7967             :         "CREATE TRIGGER \"%w_zoom_insert\" "
    7968             :         "BEFORE INSERT ON \"%w\" "
    7969             :         "FOR EACH ROW BEGIN "
    7970             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7971             :         "constraint: zoom_level not specified for table in "
    7972             :         "gpkg_tile_matrix') "
    7973             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7974             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7975             :         "END; "
    7976             :         "CREATE TRIGGER \"%w_zoom_update\" "
    7977             :         "BEFORE UPDATE OF zoom_level ON \"%w\" "
    7978             :         "FOR EACH ROW BEGIN "
    7979             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7980             :         "constraint: zoom_level not specified for table in "
    7981             :         "gpkg_tile_matrix') "
    7982             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7983             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7984             :         "END; "
    7985             :         "CREATE TRIGGER \"%w_tile_column_insert\" "
    7986             :         "BEFORE INSERT ON \"%w\" "
    7987             :         "FOR EACH ROW BEGIN "
    7988             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7989             :         "constraint: tile_column cannot be < 0') "
    7990             :         "WHERE (NEW.tile_column < 0) ; "
    7991             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7992             :         "constraint: tile_column must by < matrix_width specified for "
    7993             :         "table and zoom level in gpkg_tile_matrix') "
    7994             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    7995             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    7996             :         "zoom_level = NEW.zoom_level)); "
    7997             :         "END; "
    7998             :         "CREATE TRIGGER \"%w_tile_column_update\" "
    7999             :         "BEFORE UPDATE OF tile_column ON \"%w\" "
    8000             :         "FOR EACH ROW BEGIN "
    8001             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8002             :         "constraint: tile_column cannot be < 0') "
    8003             :         "WHERE (NEW.tile_column < 0) ; "
    8004             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8005             :         "constraint: tile_column must by < matrix_width specified for "
    8006             :         "table and zoom level in gpkg_tile_matrix') "
    8007             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    8008             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8009             :         "zoom_level = NEW.zoom_level)); "
    8010             :         "END; "
    8011             :         "CREATE TRIGGER \"%w_tile_row_insert\" "
    8012             :         "BEFORE INSERT ON \"%w\" "
    8013             :         "FOR EACH ROW BEGIN "
    8014             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8015             :         "constraint: tile_row cannot be < 0') "
    8016             :         "WHERE (NEW.tile_row < 0) ; "
    8017             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8018             :         "constraint: tile_row must by < matrix_height specified for "
    8019             :         "table and zoom level in gpkg_tile_matrix') "
    8020             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8021             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8022             :         "zoom_level = NEW.zoom_level)); "
    8023             :         "END; "
    8024             :         "CREATE TRIGGER \"%w_tile_row_update\" "
    8025             :         "BEFORE UPDATE OF tile_row ON \"%w\" "
    8026             :         "FOR EACH ROW BEGIN "
    8027             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8028             :         "constraint: tile_row cannot be < 0') "
    8029             :         "WHERE (NEW.tile_row < 0) ; "
    8030             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8031             :         "constraint: tile_row must by < matrix_height specified for "
    8032             :         "table and zoom level in gpkg_tile_matrix') "
    8033             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8034             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8035             :         "zoom_level = NEW.zoom_level)); "
    8036             :         "END; ",
    8037             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8038             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8039             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8040             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8041             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8042             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8043             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8044             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8045             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8046             :         osTableName.c_str());
    8047         201 :     osSQL = pszSQL;
    8048         201 :     sqlite3_free(pszSQL);
    8049         201 :     return osSQL;
    8050             : }
    8051             : 
    8052             : /************************************************************************/
    8053             : /*                  CreateExtensionsTableIfNecessary()                  */
    8054             : /************************************************************************/
    8055             : 
    8056        1502 : OGRErr GDALGeoPackageDataset::CreateExtensionsTableIfNecessary()
    8057             : {
    8058             :     /* Check if the table gpkg_extensions exists */
    8059        1502 :     if (HasExtensionsTable())
    8060         517 :         return OGRERR_NONE;
    8061             : 
    8062             :     /* Requirement 79 : Every extension of a GeoPackage SHALL be registered */
    8063             :     /* in a corresponding row in the gpkg_extensions table. The absence of a */
    8064             :     /* gpkg_extensions table or the absence of rows in gpkg_extensions table */
    8065             :     /* SHALL both indicate the absence of extensions to a GeoPackage. */
    8066         985 :     const char *pszCreateGpkgExtensions =
    8067             :         "CREATE TABLE gpkg_extensions ("
    8068             :         "table_name TEXT,"
    8069             :         "column_name TEXT,"
    8070             :         "extension_name TEXT NOT NULL,"
    8071             :         "definition TEXT NOT NULL,"
    8072             :         "scope TEXT NOT NULL,"
    8073             :         "CONSTRAINT ge_tce UNIQUE (table_name, column_name, extension_name)"
    8074             :         ")";
    8075             : 
    8076         985 :     return SQLCommand(hDB, pszCreateGpkgExtensions);
    8077             : }
    8078             : 
    8079             : /************************************************************************/
    8080             : /*                 OGR_GPKG_Intersects_Spatial_Filter()                 */
    8081             : /************************************************************************/
    8082             : 
    8083       23236 : void OGR_GPKG_Intersects_Spatial_Filter(sqlite3_context *pContext, int argc,
    8084             :                                         sqlite3_value **argv)
    8085             : {
    8086       23236 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8087             :     {
    8088           0 :         sqlite3_result_int(pContext, 0);
    8089       23226 :         return;
    8090             :     }
    8091             : 
    8092             :     auto poLayer =
    8093       23236 :         static_cast<OGRGeoPackageTableLayer *>(sqlite3_user_data(pContext));
    8094             : 
    8095       23236 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8096             :     const GByte *pabyBLOB =
    8097       23236 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8098             : 
    8099             :     GPkgHeader sHeader;
    8100       46472 :     if (poLayer->m_bFilterIsEnvelope &&
    8101       23236 :         OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false, 0))
    8102             :     {
    8103       23236 :         if (sHeader.bExtentHasXY)
    8104             :         {
    8105          95 :             OGREnvelope sEnvelope;
    8106          95 :             sEnvelope.MinX = sHeader.MinX;
    8107          95 :             sEnvelope.MinY = sHeader.MinY;
    8108          95 :             sEnvelope.MaxX = sHeader.MaxX;
    8109          95 :             sEnvelope.MaxY = sHeader.MaxY;
    8110          95 :             if (poLayer->m_sFilterEnvelope.Contains(sEnvelope))
    8111             :             {
    8112          31 :                 sqlite3_result_int(pContext, 1);
    8113          31 :                 return;
    8114             :             }
    8115             :         }
    8116             : 
    8117             :         // Check if at least one point falls into the layer filter envelope
    8118             :         // nHeaderLen is > 0 for GeoPackage geometries
    8119       46410 :         if (sHeader.nHeaderLen > 0 &&
    8120       23205 :             OGRWKBIntersectsPessimistic(pabyBLOB + sHeader.nHeaderLen,
    8121       23205 :                                         nBLOBLen - sHeader.nHeaderLen,
    8122       23205 :                                         poLayer->m_sFilterEnvelope))
    8123             :         {
    8124       23195 :             sqlite3_result_int(pContext, 1);
    8125       23195 :             return;
    8126             :         }
    8127             :     }
    8128             : 
    8129             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8130          10 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8131          10 :     if (poGeom == nullptr)
    8132             :     {
    8133             :         // Try also spatialite geometry blobs
    8134           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8135           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8136           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8137             :         {
    8138           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8139           0 :             sqlite3_result_int(pContext, 0);
    8140           0 :             return;
    8141             :         }
    8142           0 :         poGeom.reset(poGeomSpatialite);
    8143             :     }
    8144             : 
    8145          10 :     sqlite3_result_int(pContext, poLayer->FilterGeometry(poGeom.get()));
    8146             : }
    8147             : 
    8148             : /************************************************************************/
    8149             : /*                        OGRGeoPackageSTMinX()                         */
    8150             : /************************************************************************/
    8151             : 
    8152      253765 : static void OGRGeoPackageSTMinX(sqlite3_context *pContext, int argc,
    8153             :                                 sqlite3_value **argv)
    8154             : {
    8155             :     GPkgHeader sHeader;
    8156      253765 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8157             :     {
    8158          17 :         sqlite3_result_null(pContext);
    8159          17 :         return;
    8160             :     }
    8161      253748 :     sqlite3_result_double(pContext, sHeader.MinX);
    8162             : }
    8163             : 
    8164             : /************************************************************************/
    8165             : /*                        OGRGeoPackageSTMinY()                         */
    8166             : /************************************************************************/
    8167             : 
    8168      253749 : static void OGRGeoPackageSTMinY(sqlite3_context *pContext, int argc,
    8169             :                                 sqlite3_value **argv)
    8170             : {
    8171             :     GPkgHeader sHeader;
    8172      253749 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8173             :     {
    8174           1 :         sqlite3_result_null(pContext);
    8175           1 :         return;
    8176             :     }
    8177      253748 :     sqlite3_result_double(pContext, sHeader.MinY);
    8178             : }
    8179             : 
    8180             : /************************************************************************/
    8181             : /*                        OGRGeoPackageSTMaxX()                         */
    8182             : /************************************************************************/
    8183             : 
    8184      253749 : static void OGRGeoPackageSTMaxX(sqlite3_context *pContext, int argc,
    8185             :                                 sqlite3_value **argv)
    8186             : {
    8187             :     GPkgHeader sHeader;
    8188      253749 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8189             :     {
    8190           1 :         sqlite3_result_null(pContext);
    8191           1 :         return;
    8192             :     }
    8193      253748 :     sqlite3_result_double(pContext, sHeader.MaxX);
    8194             : }
    8195             : 
    8196             : /************************************************************************/
    8197             : /*                        OGRGeoPackageSTMaxY()                         */
    8198             : /************************************************************************/
    8199             : 
    8200      253749 : static void OGRGeoPackageSTMaxY(sqlite3_context *pContext, int argc,
    8201             :                                 sqlite3_value **argv)
    8202             : {
    8203             :     GPkgHeader sHeader;
    8204      253749 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8205             :     {
    8206           1 :         sqlite3_result_null(pContext);
    8207           1 :         return;
    8208             :     }
    8209      253748 :     sqlite3_result_double(pContext, sHeader.MaxY);
    8210             : }
    8211             : 
    8212             : /************************************************************************/
    8213             : /*                       OGRGeoPackageSTIsEmpty()                       */
    8214             : /************************************************************************/
    8215             : 
    8216      255241 : static void OGRGeoPackageSTIsEmpty(sqlite3_context *pContext, int argc,
    8217             :                                    sqlite3_value **argv)
    8218             : {
    8219             :     GPkgHeader sHeader;
    8220      255241 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8221             :     {
    8222           2 :         sqlite3_result_null(pContext);
    8223           2 :         return;
    8224             :     }
    8225      255239 :     sqlite3_result_int(pContext, sHeader.bEmpty);
    8226             : }
    8227             : 
    8228             : /************************************************************************/
    8229             : /*                    OGRGeoPackageSTGeometryType()                     */
    8230             : /************************************************************************/
    8231             : 
    8232           7 : static void OGRGeoPackageSTGeometryType(sqlite3_context *pContext, int /*argc*/,
    8233             :                                         sqlite3_value **argv)
    8234             : {
    8235             :     GPkgHeader sHeader;
    8236             : 
    8237           7 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8238             :     const GByte *pabyBLOB =
    8239           7 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8240             :     OGRwkbGeometryType eGeometryType;
    8241             : 
    8242          13 :     if (nBLOBLen < 8 ||
    8243           6 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8244             :     {
    8245           2 :         if (OGRSQLiteGetSpatialiteGeometryHeader(
    8246             :                 pabyBLOB, nBLOBLen, nullptr, &eGeometryType, nullptr, nullptr,
    8247           2 :                 nullptr, nullptr, nullptr) == OGRERR_NONE)
    8248             :         {
    8249           1 :             sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8250             :                                 SQLITE_TRANSIENT);
    8251           4 :             return;
    8252             :         }
    8253             :         else
    8254             :         {
    8255           1 :             sqlite3_result_null(pContext);
    8256           1 :             return;
    8257             :         }
    8258             :     }
    8259             : 
    8260           5 :     if (static_cast<size_t>(nBLOBLen) < sHeader.nHeaderLen + 5)
    8261             :     {
    8262           2 :         sqlite3_result_null(pContext);
    8263           2 :         return;
    8264             :     }
    8265             : 
    8266           3 :     OGRErr err = OGRReadWKBGeometryType(pabyBLOB + sHeader.nHeaderLen,
    8267             :                                         wkbVariantIso, &eGeometryType);
    8268           3 :     if (err != OGRERR_NONE)
    8269           1 :         sqlite3_result_null(pContext);
    8270             :     else
    8271           2 :         sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8272             :                             SQLITE_TRANSIENT);
    8273             : }
    8274             : 
    8275             : /************************************************************************/
    8276             : /*                 OGRGeoPackageSTEnvelopesIntersects()                 */
    8277             : /************************************************************************/
    8278             : 
    8279         118 : static void OGRGeoPackageSTEnvelopesIntersects(sqlite3_context *pContext,
    8280             :                                                int argc, sqlite3_value **argv)
    8281             : {
    8282             :     GPkgHeader sHeader;
    8283         118 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8284             :     {
    8285           2 :         sqlite3_result_int(pContext, FALSE);
    8286         107 :         return;
    8287             :     }
    8288         116 :     const double dfMinX = sqlite3_value_double(argv[1]);
    8289         116 :     if (sHeader.MaxX < dfMinX)
    8290             :     {
    8291          93 :         sqlite3_result_int(pContext, FALSE);
    8292          93 :         return;
    8293             :     }
    8294          23 :     const double dfMinY = sqlite3_value_double(argv[2]);
    8295          23 :     if (sHeader.MaxY < dfMinY)
    8296             :     {
    8297          11 :         sqlite3_result_int(pContext, FALSE);
    8298          11 :         return;
    8299             :     }
    8300          12 :     const double dfMaxX = sqlite3_value_double(argv[3]);
    8301          12 :     if (sHeader.MinX > dfMaxX)
    8302             :     {
    8303           1 :         sqlite3_result_int(pContext, FALSE);
    8304           1 :         return;
    8305             :     }
    8306          11 :     const double dfMaxY = sqlite3_value_double(argv[4]);
    8307          11 :     sqlite3_result_int(pContext, sHeader.MinY <= dfMaxY);
    8308             : }
    8309             : 
    8310             : /************************************************************************/
    8311             : /*            OGRGeoPackageSTEnvelopesIntersectsTwoParams()             */
    8312             : /************************************************************************/
    8313             : 
    8314             : static void
    8315           3 : OGRGeoPackageSTEnvelopesIntersectsTwoParams(sqlite3_context *pContext, int argc,
    8316             :                                             sqlite3_value **argv)
    8317             : {
    8318             :     GPkgHeader sHeader;
    8319           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false, 0))
    8320             :     {
    8321           0 :         sqlite3_result_int(pContext, FALSE);
    8322           2 :         return;
    8323             :     }
    8324             :     GPkgHeader sHeader2;
    8325           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader2, true, false,
    8326             :                                 1))
    8327             :     {
    8328           0 :         sqlite3_result_int(pContext, FALSE);
    8329           0 :         return;
    8330             :     }
    8331           3 :     if (sHeader.MaxX < sHeader2.MinX)
    8332             :     {
    8333           1 :         sqlite3_result_int(pContext, FALSE);
    8334           1 :         return;
    8335             :     }
    8336           2 :     if (sHeader.MaxY < sHeader2.MinY)
    8337             :     {
    8338           0 :         sqlite3_result_int(pContext, FALSE);
    8339           0 :         return;
    8340             :     }
    8341           2 :     if (sHeader.MinX > sHeader2.MaxX)
    8342             :     {
    8343           1 :         sqlite3_result_int(pContext, FALSE);
    8344           1 :         return;
    8345             :     }
    8346           1 :     sqlite3_result_int(pContext, sHeader.MinY <= sHeader2.MaxY);
    8347             : }
    8348             : 
    8349             : /************************************************************************/
    8350             : /*                   OGRGeoPackageGPKGIsAssignable()                    */
    8351             : /************************************************************************/
    8352             : 
    8353           8 : static void OGRGeoPackageGPKGIsAssignable(sqlite3_context *pContext,
    8354             :                                           int /*argc*/, sqlite3_value **argv)
    8355             : {
    8356          15 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8357           7 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8358             :     {
    8359           2 :         sqlite3_result_int(pContext, 0);
    8360           2 :         return;
    8361             :     }
    8362             : 
    8363             :     const char *pszExpected =
    8364           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8365             :     const char *pszActual =
    8366           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8367           6 :     int bIsAssignable = OGR_GT_IsSubClassOf(OGRFromOGCGeomType(pszActual),
    8368             :                                             OGRFromOGCGeomType(pszExpected));
    8369           6 :     sqlite3_result_int(pContext, bIsAssignable);
    8370             : }
    8371             : 
    8372             : /************************************************************************/
    8373             : /*                        OGRGeoPackageSTSRID()                         */
    8374             : /************************************************************************/
    8375             : 
    8376          12 : static void OGRGeoPackageSTSRID(sqlite3_context *pContext, int argc,
    8377             :                                 sqlite3_value **argv)
    8378             : {
    8379             :     GPkgHeader sHeader;
    8380          12 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8381             :     {
    8382           2 :         sqlite3_result_null(pContext);
    8383           2 :         return;
    8384             :     }
    8385          10 :     sqlite3_result_int(pContext, sHeader.iSrsId);
    8386             : }
    8387             : 
    8388             : /************************************************************************/
    8389             : /*                        OGRGeoPackageSetSRID()                        */
    8390             : /************************************************************************/
    8391             : 
    8392          28 : static void OGRGeoPackageSetSRID(sqlite3_context *pContext, int /* argc */,
    8393             :                                  sqlite3_value **argv)
    8394             : {
    8395          28 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8396             :     {
    8397           1 :         sqlite3_result_null(pContext);
    8398           1 :         return;
    8399             :     }
    8400          27 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8401             :     GPkgHeader sHeader;
    8402          27 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8403             :     const GByte *pabyBLOB =
    8404          27 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8405             : 
    8406          54 :     if (nBLOBLen < 8 ||
    8407          27 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8408             :     {
    8409             :         // Try also spatialite geometry blobs
    8410           0 :         OGRGeometry *poGeom = nullptr;
    8411           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeom) !=
    8412             :             OGRERR_NONE)
    8413             :         {
    8414           0 :             sqlite3_result_null(pContext);
    8415           0 :             return;
    8416             :         }
    8417           0 :         size_t nBLOBDestLen = 0;
    8418             :         GByte *pabyDestBLOB =
    8419           0 :             GPkgGeometryFromOGR(poGeom, nDestSRID, nullptr, &nBLOBDestLen);
    8420           0 :         if (!pabyDestBLOB)
    8421             :         {
    8422           0 :             sqlite3_result_null(pContext);
    8423           0 :             return;
    8424             :         }
    8425           0 :         sqlite3_result_blob(pContext, pabyDestBLOB,
    8426             :                             static_cast<int>(nBLOBDestLen), VSIFree);
    8427           0 :         return;
    8428             :     }
    8429             : 
    8430          27 :     GByte *pabyDestBLOB = static_cast<GByte *>(CPLMalloc(nBLOBLen));
    8431          27 :     memcpy(pabyDestBLOB, pabyBLOB, nBLOBLen);
    8432          27 :     int32_t nSRIDToSerialize = nDestSRID;
    8433          27 :     if (OGR_SWAP(sHeader.eByteOrder))
    8434           0 :         nSRIDToSerialize = CPL_SWAP32(nSRIDToSerialize);
    8435          27 :     memcpy(pabyDestBLOB + 4, &nSRIDToSerialize, 4);
    8436          27 :     sqlite3_result_blob(pContext, pabyDestBLOB, nBLOBLen, VSIFree);
    8437             : }
    8438             : 
    8439             : /************************************************************************/
    8440             : /*                      OGRGeoPackageSTMakeValid()                      */
    8441             : /************************************************************************/
    8442             : 
    8443           3 : static void OGRGeoPackageSTMakeValid(sqlite3_context *pContext, int argc,
    8444             :                                      sqlite3_value **argv)
    8445             : {
    8446           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8447             :     {
    8448           2 :         sqlite3_result_null(pContext);
    8449           2 :         return;
    8450             :     }
    8451           1 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8452             :     const GByte *pabyBLOB =
    8453           1 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8454             : 
    8455             :     GPkgHeader sHeader;
    8456           1 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8457             :     {
    8458           0 :         sqlite3_result_null(pContext);
    8459           0 :         return;
    8460             :     }
    8461             : 
    8462             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8463           1 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8464           1 :     if (poGeom == nullptr)
    8465             :     {
    8466             :         // Try also spatialite geometry blobs
    8467           0 :         OGRGeometry *poGeomPtr = nullptr;
    8468           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8469             :             OGRERR_NONE)
    8470             :         {
    8471           0 :             sqlite3_result_null(pContext);
    8472           0 :             return;
    8473             :         }
    8474           0 :         poGeom.reset(poGeomPtr);
    8475             :     }
    8476           1 :     auto poValid = std::unique_ptr<OGRGeometry>(poGeom->MakeValid());
    8477           1 :     if (poValid == nullptr)
    8478             :     {
    8479           0 :         sqlite3_result_null(pContext);
    8480           0 :         return;
    8481             :     }
    8482             : 
    8483           1 :     size_t nBLOBDestLen = 0;
    8484           1 :     GByte *pabyDestBLOB = GPkgGeometryFromOGR(poValid.get(), sHeader.iSrsId,
    8485             :                                               nullptr, &nBLOBDestLen);
    8486           1 :     if (!pabyDestBLOB)
    8487             :     {
    8488           0 :         sqlite3_result_null(pContext);
    8489           0 :         return;
    8490             :     }
    8491           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8492             :                         VSIFree);
    8493             : }
    8494             : 
    8495             : /************************************************************************/
    8496             : /*                        OGRGeoPackageSTArea()                         */
    8497             : /************************************************************************/
    8498             : 
    8499          19 : static void OGRGeoPackageSTArea(sqlite3_context *pContext, int /*argc*/,
    8500             :                                 sqlite3_value **argv)
    8501             : {
    8502          19 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8503             :     {
    8504           1 :         sqlite3_result_null(pContext);
    8505          15 :         return;
    8506             :     }
    8507          18 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8508             :     const GByte *pabyBLOB =
    8509          18 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8510             : 
    8511             :     GPkgHeader sHeader;
    8512           0 :     std::unique_ptr<OGRGeometry> poGeom;
    8513          18 :     if (GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) == OGRERR_NONE)
    8514             :     {
    8515          16 :         if (sHeader.bEmpty)
    8516             :         {
    8517           3 :             sqlite3_result_double(pContext, 0);
    8518          13 :             return;
    8519             :         }
    8520          13 :         const GByte *pabyWkb = pabyBLOB + sHeader.nHeaderLen;
    8521          13 :         size_t nWKBSize = nBLOBLen - sHeader.nHeaderLen;
    8522             :         bool bNeedSwap;
    8523             :         uint32_t nType;
    8524          13 :         if (OGRWKBGetGeomType(pabyWkb, nWKBSize, bNeedSwap, nType))
    8525             :         {
    8526          13 :             if (nType == wkbPolygon || nType == wkbPolygon25D ||
    8527          11 :                 nType == wkbPolygon + 1000 ||  // wkbPolygonZ
    8528          10 :                 nType == wkbPolygonM || nType == wkbPolygonZM)
    8529             :             {
    8530             :                 double dfArea;
    8531           5 :                 if (OGRWKBPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8532             :                 {
    8533           5 :                     sqlite3_result_double(pContext, dfArea);
    8534           5 :                     return;
    8535           0 :                 }
    8536             :             }
    8537           8 :             else if (nType == wkbMultiPolygon || nType == wkbMultiPolygon25D ||
    8538           6 :                      nType == wkbMultiPolygon + 1000 ||  // wkbMultiPolygonZ
    8539           5 :                      nType == wkbMultiPolygonM || nType == wkbMultiPolygonZM)
    8540             :             {
    8541             :                 double dfArea;
    8542           5 :                 if (OGRWKBMultiPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8543             :                 {
    8544           5 :                     sqlite3_result_double(pContext, dfArea);
    8545           5 :                     return;
    8546             :                 }
    8547             :             }
    8548             :         }
    8549             : 
    8550             :         // For curve geometries, fallback to OGRGeometry methods
    8551           3 :         poGeom.reset(GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8552             :     }
    8553             :     else
    8554             :     {
    8555             :         // Try also spatialite geometry blobs
    8556           2 :         OGRGeometry *poGeomPtr = nullptr;
    8557           2 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8558             :             OGRERR_NONE)
    8559             :         {
    8560           1 :             sqlite3_result_null(pContext);
    8561           1 :             return;
    8562             :         }
    8563           1 :         poGeom.reset(poGeomPtr);
    8564             :     }
    8565           4 :     auto poSurface = dynamic_cast<OGRSurface *>(poGeom.get());
    8566           4 :     if (poSurface == nullptr)
    8567             :     {
    8568           2 :         auto poMultiSurface = dynamic_cast<OGRMultiSurface *>(poGeom.get());
    8569           2 :         if (poMultiSurface == nullptr)
    8570             :         {
    8571           1 :             sqlite3_result_double(pContext, 0);
    8572             :         }
    8573             :         else
    8574             :         {
    8575           1 :             sqlite3_result_double(pContext, poMultiSurface->get_Area());
    8576             :         }
    8577             :     }
    8578             :     else
    8579             :     {
    8580           2 :         sqlite3_result_double(pContext, poSurface->get_Area());
    8581             :     }
    8582             : }
    8583             : 
    8584             : /************************************************************************/
    8585             : /*                     OGRGeoPackageGeodesicArea()                      */
    8586             : /************************************************************************/
    8587             : 
    8588           5 : static void OGRGeoPackageGeodesicArea(sqlite3_context *pContext, int argc,
    8589             :                                       sqlite3_value **argv)
    8590             : {
    8591           5 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8592             :     {
    8593           1 :         sqlite3_result_null(pContext);
    8594           3 :         return;
    8595             :     }
    8596           4 :     if (sqlite3_value_int(argv[1]) != 1)
    8597             :     {
    8598           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8599             :                  "ST_Area(geom, use_ellipsoid) is only supported for "
    8600             :                  "use_ellipsoid = 1");
    8601             :     }
    8602             : 
    8603           4 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8604             :     const GByte *pabyBLOB =
    8605           4 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8606             :     GPkgHeader sHeader;
    8607           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8608             :     {
    8609           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8610           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8611           1 :         return;
    8612             :     }
    8613             : 
    8614             :     GDALGeoPackageDataset *poDS =
    8615           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8616             : 
    8617           3 :     auto poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8618           3 :     if (poSrcSRS == nullptr)
    8619             :     {
    8620           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    8621             :                  "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8622           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8623           1 :         return;
    8624             :     }
    8625             : 
    8626             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8627           2 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8628           2 :     if (poGeom == nullptr)
    8629             :     {
    8630             :         // Try also spatialite geometry blobs
    8631           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8632           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8633           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8634             :         {
    8635           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8636           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8637           0 :             return;
    8638             :         }
    8639           0 :         poGeom.reset(poGeomSpatialite);
    8640             :     }
    8641             : 
    8642           2 :     poGeom->assignSpatialReference(poSrcSRS.get());
    8643           2 :     sqlite3_result_double(
    8644             :         pContext, OGR_G_GeodesicArea(OGRGeometry::ToHandle(poGeom.get())));
    8645             : }
    8646             : 
    8647             : /************************************************************************/
    8648             : /*                OGRGeoPackageLengthOrGeodesicLength()                 */
    8649             : /************************************************************************/
    8650             : 
    8651           8 : static void OGRGeoPackageLengthOrGeodesicLength(sqlite3_context *pContext,
    8652             :                                                 int argc, sqlite3_value **argv)
    8653             : {
    8654           8 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8655             :     {
    8656           2 :         sqlite3_result_null(pContext);
    8657           5 :         return;
    8658             :     }
    8659           6 :     if (argc == 2 && sqlite3_value_int(argv[1]) != 1)
    8660             :     {
    8661           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8662             :                  "ST_Length(geom, use_ellipsoid) is only supported for "
    8663             :                  "use_ellipsoid = 1");
    8664             :     }
    8665             : 
    8666           6 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8667             :     const GByte *pabyBLOB =
    8668           6 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8669             :     GPkgHeader sHeader;
    8670           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8671             :     {
    8672           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8673           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8674           2 :         return;
    8675             :     }
    8676             : 
    8677             :     GDALGeoPackageDataset *poDS =
    8678           4 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8679             : 
    8680           4 :     OGRSpatialReferenceRefCountedPtr poSrcSRS;
    8681           4 :     if (argc == 2)
    8682             :     {
    8683           3 :         poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8684           3 :         if (!poSrcSRS)
    8685             :         {
    8686           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    8687             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8688           1 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8689           1 :             return;
    8690             :         }
    8691             :     }
    8692             : 
    8693             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8694           3 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8695           3 :     if (poGeom == nullptr)
    8696             :     {
    8697             :         // Try also spatialite geometry blobs
    8698           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8699           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8700           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8701             :         {
    8702           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8703           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8704           0 :             return;
    8705             :         }
    8706           0 :         poGeom.reset(poGeomSpatialite);
    8707             :     }
    8708             : 
    8709           3 :     if (argc == 2)
    8710           2 :         poGeom->assignSpatialReference(poSrcSRS.get());
    8711             : 
    8712           6 :     sqlite3_result_double(
    8713             :         pContext,
    8714           1 :         argc == 1 ? OGR_G_Length(OGRGeometry::ToHandle(poGeom.get()))
    8715           2 :                   : OGR_G_GeodesicLength(OGRGeometry::ToHandle(poGeom.get())));
    8716             : }
    8717             : 
    8718             : /************************************************************************/
    8719             : /*                       OGRGeoPackageTransform()                       */
    8720             : /************************************************************************/
    8721             : 
    8722             : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8723             :                             sqlite3_value **argv);
    8724             : 
    8725          32 : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8726             :                             sqlite3_value **argv)
    8727             : {
    8728          63 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB ||
    8729          31 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8730             :     {
    8731           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8732          32 :         return;
    8733             :     }
    8734             : 
    8735          30 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8736             :     const GByte *pabyBLOB =
    8737          30 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8738             :     GPkgHeader sHeader;
    8739          30 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8740             :     {
    8741           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8742           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8743           1 :         return;
    8744             :     }
    8745             : 
    8746          29 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8747          29 :     if (sHeader.iSrsId == nDestSRID)
    8748             :     {
    8749             :         // Return blob unmodified
    8750           3 :         sqlite3_result_blob(pContext, pabyBLOB, nBLOBLen, SQLITE_TRANSIENT);
    8751           3 :         return;
    8752             :     }
    8753             : 
    8754             :     GDALGeoPackageDataset *poDS =
    8755          26 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8756             : 
    8757             :     // Try to get the cached coordinate transformation
    8758             :     OGRCoordinateTransformation *poCT;
    8759          26 :     if (poDS->m_nLastCachedCTSrcSRId == sHeader.iSrsId &&
    8760          20 :         poDS->m_nLastCachedCTDstSRId == nDestSRID)
    8761             :     {
    8762          20 :         poCT = poDS->m_poLastCachedCT.get();
    8763             :     }
    8764             :     else
    8765             :     {
    8766           6 :         auto poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8767           6 :         if (poSrcSRS == nullptr)
    8768             :         {
    8769           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    8770             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8771           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8772           0 :             return;
    8773             :         }
    8774             : 
    8775           6 :         auto poDstSRS = poDS->GetSpatialRef(nDestSRID, true);
    8776           6 :         if (poDstSRS == nullptr)
    8777             :         {
    8778           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Target SRID (%d) is invalid",
    8779             :                      nDestSRID);
    8780           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8781           0 :             return;
    8782             :         }
    8783             :         poCT =
    8784           6 :             OGRCreateCoordinateTransformation(poSrcSRS.get(), poDstSRS.get());
    8785           6 :         if (poCT == nullptr)
    8786             :         {
    8787           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8788           0 :             return;
    8789             :         }
    8790             : 
    8791             :         // Cache coordinate transformation for potential later reuse
    8792           6 :         poDS->m_nLastCachedCTSrcSRId = sHeader.iSrsId;
    8793           6 :         poDS->m_nLastCachedCTDstSRId = nDestSRID;
    8794           6 :         poDS->m_poLastCachedCT.reset(poCT);
    8795           6 :         poCT = poDS->m_poLastCachedCT.get();
    8796             :     }
    8797             : 
    8798          26 :     if (sHeader.nHeaderLen >= 8)
    8799             :     {
    8800          26 :         std::vector<GByte> &abyNewBLOB = poDS->m_abyWKBTransformCache;
    8801          26 :         abyNewBLOB.resize(nBLOBLen);
    8802          26 :         memcpy(abyNewBLOB.data(), pabyBLOB, nBLOBLen);
    8803             : 
    8804          26 :         OGREnvelope3D oEnv3d;
    8805          26 :         if (!OGRWKBTransform(abyNewBLOB.data() + sHeader.nHeaderLen,
    8806          26 :                              nBLOBLen - sHeader.nHeaderLen, poCT,
    8807          78 :                              poDS->m_oWKBTransformCache, oEnv3d) ||
    8808          26 :             !GPkgUpdateHeader(abyNewBLOB.data(), nBLOBLen, nDestSRID,
    8809             :                               oEnv3d.MinX, oEnv3d.MaxX, oEnv3d.MinY,
    8810             :                               oEnv3d.MaxY, oEnv3d.MinZ, oEnv3d.MaxZ))
    8811             :         {
    8812           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8813           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8814           0 :             return;
    8815             :         }
    8816             : 
    8817          26 :         sqlite3_result_blob(pContext, abyNewBLOB.data(), nBLOBLen,
    8818             :                             SQLITE_TRANSIENT);
    8819          26 :         return;
    8820             :     }
    8821             : 
    8822             :     // Try also spatialite geometry blobs
    8823           0 :     OGRGeometry *poGeomSpatialite = nullptr;
    8824           0 :     if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8825           0 :                                           &poGeomSpatialite) != OGRERR_NONE)
    8826             :     {
    8827           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8828           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8829           0 :         return;
    8830             :     }
    8831           0 :     auto poGeom = std::unique_ptr<OGRGeometry>(poGeomSpatialite);
    8832             : 
    8833           0 :     if (poGeom->transform(poCT) != OGRERR_NONE)
    8834             :     {
    8835           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8836           0 :         return;
    8837             :     }
    8838             : 
    8839           0 :     size_t nBLOBDestLen = 0;
    8840             :     GByte *pabyDestBLOB =
    8841           0 :         GPkgGeometryFromOGR(poGeom.get(), nDestSRID, nullptr, &nBLOBDestLen);
    8842           0 :     if (!pabyDestBLOB)
    8843             :     {
    8844           0 :         sqlite3_result_null(pContext);
    8845           0 :         return;
    8846             :     }
    8847           0 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8848             :                         VSIFree);
    8849             : }
    8850             : 
    8851             : /************************************************************************/
    8852             : /*                    OGRGeoPackageSridFromAuthCRS()                    */
    8853             : /************************************************************************/
    8854             : 
    8855           4 : static void OGRGeoPackageSridFromAuthCRS(sqlite3_context *pContext,
    8856             :                                          int /*argc*/, sqlite3_value **argv)
    8857             : {
    8858           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8859           3 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8860             :     {
    8861           2 :         sqlite3_result_int(pContext, -1);
    8862           2 :         return;
    8863             :     }
    8864             : 
    8865             :     GDALGeoPackageDataset *poDS =
    8866           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8867             : 
    8868           2 :     char *pszSQL = sqlite3_mprintf(
    8869             :         "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
    8870             :         "lower(organization) = lower('%q') AND organization_coordsys_id = %d",
    8871           2 :         sqlite3_value_text(argv[0]), sqlite3_value_int(argv[1]));
    8872           2 :     OGRErr err = OGRERR_NONE;
    8873           2 :     int nSRSId = SQLGetInteger(poDS->GetDB(), pszSQL, &err);
    8874           2 :     sqlite3_free(pszSQL);
    8875           2 :     if (err != OGRERR_NONE)
    8876           1 :         nSRSId = -1;
    8877           2 :     sqlite3_result_int(pContext, nSRSId);
    8878             : }
    8879             : 
    8880             : /************************************************************************/
    8881             : /*                    OGRGeoPackageImportFromEPSG()                     */
    8882             : /************************************************************************/
    8883             : 
    8884           4 : static void OGRGeoPackageImportFromEPSG(sqlite3_context *pContext, int /*argc*/,
    8885             :                                         sqlite3_value **argv)
    8886             : {
    8887           4 :     if (sqlite3_value_type(argv[0]) != SQLITE_INTEGER)
    8888             :     {
    8889           1 :         sqlite3_result_int(pContext, -1);
    8890           2 :         return;
    8891             :     }
    8892             : 
    8893             :     GDALGeoPackageDataset *poDS =
    8894           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8895           3 :     OGRSpatialReference oSRS;
    8896           3 :     if (oSRS.importFromEPSG(sqlite3_value_int(argv[0])) != OGRERR_NONE)
    8897             :     {
    8898           1 :         sqlite3_result_int(pContext, -1);
    8899           1 :         return;
    8900             :     }
    8901             : 
    8902           2 :     sqlite3_result_int(pContext, poDS->GetSrsId(&oSRS));
    8903             : }
    8904             : 
    8905             : /************************************************************************/
    8906             : /*               OGRGeoPackageRegisterGeometryExtension()               */
    8907             : /************************************************************************/
    8908             : 
    8909           1 : static void OGRGeoPackageRegisterGeometryExtension(sqlite3_context *pContext,
    8910             :                                                    int /*argc*/,
    8911             :                                                    sqlite3_value **argv)
    8912             : {
    8913           1 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8914           2 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT ||
    8915           1 :         sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    8916             :     {
    8917           0 :         sqlite3_result_int(pContext, 0);
    8918           0 :         return;
    8919             :     }
    8920             : 
    8921             :     const char *pszTableName =
    8922           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8923             :     const char *pszGeomName =
    8924           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8925             :     const char *pszGeomType =
    8926           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    8927             : 
    8928             :     GDALGeoPackageDataset *poDS =
    8929           1 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8930             : 
    8931           1 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8932           1 :         poDS->GetLayerByName(pszTableName));
    8933           1 :     if (poLyr == nullptr)
    8934             :     {
    8935           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8936           0 :         sqlite3_result_int(pContext, 0);
    8937           0 :         return;
    8938             :     }
    8939           1 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8940             :     {
    8941           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8942           0 :         sqlite3_result_int(pContext, 0);
    8943           0 :         return;
    8944             :     }
    8945           1 :     const OGRwkbGeometryType eGeomType = OGRFromOGCGeomType(pszGeomType);
    8946           1 :     if (eGeomType == wkbUnknown)
    8947             :     {
    8948           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry type name");
    8949           0 :         sqlite3_result_int(pContext, 0);
    8950           0 :         return;
    8951             :     }
    8952             : 
    8953           1 :     sqlite3_result_int(
    8954             :         pContext,
    8955           1 :         static_cast<int>(poLyr->CreateGeometryExtensionIfNecessary(eGeomType)));
    8956             : }
    8957             : 
    8958             : /************************************************************************/
    8959             : /*                  OGRGeoPackageCreateSpatialIndex()                   */
    8960             : /************************************************************************/
    8961             : 
    8962          14 : static void OGRGeoPackageCreateSpatialIndex(sqlite3_context *pContext,
    8963             :                                             int /*argc*/, sqlite3_value **argv)
    8964             : {
    8965          27 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8966          13 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8967             :     {
    8968           2 :         sqlite3_result_int(pContext, 0);
    8969           2 :         return;
    8970             :     }
    8971             : 
    8972             :     const char *pszTableName =
    8973          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8974             :     const char *pszGeomName =
    8975          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8976             :     GDALGeoPackageDataset *poDS =
    8977          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8978             : 
    8979          12 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8980          12 :         poDS->GetLayerByName(pszTableName));
    8981          12 :     if (poLyr == nullptr)
    8982             :     {
    8983           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8984           1 :         sqlite3_result_int(pContext, 0);
    8985           1 :         return;
    8986             :     }
    8987          11 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8988             :     {
    8989           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8990           1 :         sqlite3_result_int(pContext, 0);
    8991           1 :         return;
    8992             :     }
    8993             : 
    8994          10 :     sqlite3_result_int(pContext, poLyr->CreateSpatialIndex());
    8995             : }
    8996             : 
    8997             : /************************************************************************/
    8998             : /*                  OGRGeoPackageDisableSpatialIndex()                  */
    8999             : /************************************************************************/
    9000             : 
    9001          12 : static void OGRGeoPackageDisableSpatialIndex(sqlite3_context *pContext,
    9002             :                                              int /*argc*/, sqlite3_value **argv)
    9003             : {
    9004          23 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9005          11 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9006             :     {
    9007           2 :         sqlite3_result_int(pContext, 0);
    9008           2 :         return;
    9009             :     }
    9010             : 
    9011             :     const char *pszTableName =
    9012          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9013             :     const char *pszGeomName =
    9014          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9015             :     GDALGeoPackageDataset *poDS =
    9016          10 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9017             : 
    9018          10 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9019          10 :         poDS->GetLayerByName(pszTableName));
    9020          10 :     if (poLyr == nullptr)
    9021             :     {
    9022           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9023           1 :         sqlite3_result_int(pContext, 0);
    9024           1 :         return;
    9025             :     }
    9026           9 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9027             :     {
    9028           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9029           1 :         sqlite3_result_int(pContext, 0);
    9030           1 :         return;
    9031             :     }
    9032             : 
    9033           8 :     sqlite3_result_int(pContext, poLyr->DropSpatialIndex(true));
    9034             : }
    9035             : 
    9036             : /************************************************************************/
    9037             : /*                    OGRGeoPackageHasSpatialIndex()                    */
    9038             : /************************************************************************/
    9039             : 
    9040          29 : static void OGRGeoPackageHasSpatialIndex(sqlite3_context *pContext,
    9041             :                                          int /*argc*/, sqlite3_value **argv)
    9042             : {
    9043          57 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9044          28 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9045             :     {
    9046           2 :         sqlite3_result_int(pContext, 0);
    9047           2 :         return;
    9048             :     }
    9049             : 
    9050             :     const char *pszTableName =
    9051          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9052             :     const char *pszGeomName =
    9053          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9054             :     GDALGeoPackageDataset *poDS =
    9055          27 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9056             : 
    9057          27 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9058          27 :         poDS->GetLayerByName(pszTableName));
    9059          27 :     if (poLyr == nullptr)
    9060             :     {
    9061           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9062           1 :         sqlite3_result_int(pContext, 0);
    9063           1 :         return;
    9064             :     }
    9065          26 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9066             :     {
    9067           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9068           1 :         sqlite3_result_int(pContext, 0);
    9069           1 :         return;
    9070             :     }
    9071             : 
    9072          25 :     poLyr->RunDeferredCreationIfNecessary();
    9073          25 :     poLyr->CreateSpatialIndexIfNecessary();
    9074             : 
    9075          25 :     sqlite3_result_int(pContext, poLyr->HasSpatialIndex());
    9076             : }
    9077             : 
    9078             : /************************************************************************/
    9079             : /*                       GPKG_hstore_get_value()                        */
    9080             : /************************************************************************/
    9081             : 
    9082           4 : static void GPKG_hstore_get_value(sqlite3_context *pContext, int /*argc*/,
    9083             :                                   sqlite3_value **argv)
    9084             : {
    9085           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9086           3 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9087             :     {
    9088           2 :         sqlite3_result_null(pContext);
    9089           2 :         return;
    9090             :     }
    9091             : 
    9092             :     const char *pszHStore =
    9093           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9094             :     const char *pszSearchedKey =
    9095           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9096           2 :     char *pszValue = OGRHStoreGetValue(pszHStore, pszSearchedKey);
    9097           2 :     if (pszValue != nullptr)
    9098           1 :         sqlite3_result_text(pContext, pszValue, -1, CPLFree);
    9099             :     else
    9100           1 :         sqlite3_result_null(pContext);
    9101             : }
    9102             : 
    9103             : /************************************************************************/
    9104             : /*                    GPKG_GDAL_GetMemFileFromBlob()                    */
    9105             : /************************************************************************/
    9106             : 
    9107         105 : static CPLString GPKG_GDAL_GetMemFileFromBlob(sqlite3_value **argv)
    9108             : {
    9109         105 :     int nBytes = sqlite3_value_bytes(argv[0]);
    9110             :     const GByte *pabyBLOB =
    9111         105 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    9112             :     CPLString osMemFileName(
    9113         105 :         VSIMemGenerateHiddenFilename("GPKG_GDAL_GetMemFileFromBlob"));
    9114         105 :     VSILFILE *fp = VSIFileFromMemBuffer(
    9115             :         osMemFileName.c_str(), const_cast<GByte *>(pabyBLOB), nBytes, FALSE);
    9116         105 :     VSIFCloseL(fp);
    9117         105 :     return osMemFileName;
    9118             : }
    9119             : 
    9120             : /************************************************************************/
    9121             : /*                       GPKG_GDAL_GetMimeType()                        */
    9122             : /************************************************************************/
    9123             : 
    9124          35 : static void GPKG_GDAL_GetMimeType(sqlite3_context *pContext, int /*argc*/,
    9125             :                                   sqlite3_value **argv)
    9126             : {
    9127          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9128             :     {
    9129           0 :         sqlite3_result_null(pContext);
    9130           0 :         return;
    9131             :     }
    9132             : 
    9133          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9134             :     GDALDriver *poDriver =
    9135          35 :         GDALDriver::FromHandle(GDALIdentifyDriver(osMemFileName, nullptr));
    9136          35 :     if (poDriver != nullptr)
    9137             :     {
    9138          35 :         const char *pszRes = nullptr;
    9139          35 :         if (EQUAL(poDriver->GetDescription(), "PNG"))
    9140          23 :             pszRes = "image/png";
    9141          12 :         else if (EQUAL(poDriver->GetDescription(), "JPEG"))
    9142           6 :             pszRes = "image/jpeg";
    9143           6 :         else if (EQUAL(poDriver->GetDescription(), "WEBP"))
    9144           6 :             pszRes = "image/x-webp";
    9145           0 :         else if (EQUAL(poDriver->GetDescription(), "GTIFF"))
    9146           0 :             pszRes = "image/tiff";
    9147             :         else
    9148           0 :             pszRes = CPLSPrintf("gdal/%s", poDriver->GetDescription());
    9149          35 :         sqlite3_result_text(pContext, pszRes, -1, SQLITE_TRANSIENT);
    9150             :     }
    9151             :     else
    9152           0 :         sqlite3_result_null(pContext);
    9153          35 :     VSIUnlink(osMemFileName);
    9154             : }
    9155             : 
    9156             : /************************************************************************/
    9157             : /*                       GPKG_GDAL_GetBandCount()                       */
    9158             : /************************************************************************/
    9159             : 
    9160          35 : static void GPKG_GDAL_GetBandCount(sqlite3_context *pContext, int /*argc*/,
    9161             :                                    sqlite3_value **argv)
    9162             : {
    9163          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9164             :     {
    9165           0 :         sqlite3_result_null(pContext);
    9166           0 :         return;
    9167             :     }
    9168             : 
    9169          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9170             :     auto poDS = std::unique_ptr<GDALDataset>(
    9171             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9172          70 :                           nullptr, nullptr, nullptr));
    9173          35 :     if (poDS != nullptr)
    9174             :     {
    9175          35 :         sqlite3_result_int(pContext, poDS->GetRasterCount());
    9176             :     }
    9177             :     else
    9178           0 :         sqlite3_result_null(pContext);
    9179          35 :     VSIUnlink(osMemFileName);
    9180             : }
    9181             : 
    9182             : /************************************************************************/
    9183             : /*                      GPKG_GDAL_HasColorTable()                       */
    9184             : /************************************************************************/
    9185             : 
    9186          35 : static void GPKG_GDAL_HasColorTable(sqlite3_context *pContext, int /*argc*/,
    9187             :                                     sqlite3_value **argv)
    9188             : {
    9189          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9190             :     {
    9191           0 :         sqlite3_result_null(pContext);
    9192           0 :         return;
    9193             :     }
    9194             : 
    9195          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9196             :     auto poDS = std::unique_ptr<GDALDataset>(
    9197             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9198          70 :                           nullptr, nullptr, nullptr));
    9199          35 :     if (poDS != nullptr)
    9200             :     {
    9201          35 :         sqlite3_result_int(
    9202          46 :             pContext, poDS->GetRasterCount() == 1 &&
    9203          11 :                           poDS->GetRasterBand(1)->GetColorTable() != nullptr);
    9204             :     }
    9205             :     else
    9206           0 :         sqlite3_result_null(pContext);
    9207          35 :     VSIUnlink(osMemFileName);
    9208             : }
    9209             : 
    9210             : /************************************************************************/
    9211             : /*                       GetRasterLayerDataset()                        */
    9212             : /************************************************************************/
    9213             : 
    9214             : GDALDataset *
    9215          12 : GDALGeoPackageDataset::GetRasterLayerDataset(const char *pszLayerName)
    9216             : {
    9217          12 :     const auto oIter = m_oCachedRasterDS.find(pszLayerName);
    9218          12 :     if (oIter != m_oCachedRasterDS.end())
    9219          10 :         return oIter->second.get();
    9220             : 
    9221             :     auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
    9222           4 :         (std::string("GPKG:\"") + m_pszFilename + "\":" + pszLayerName).c_str(),
    9223           4 :         GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR));
    9224           2 :     if (!poDS)
    9225             :     {
    9226           0 :         return nullptr;
    9227             :     }
    9228           2 :     m_oCachedRasterDS[pszLayerName] = std::move(poDS);
    9229           2 :     return m_oCachedRasterDS[pszLayerName].get();
    9230             : }
    9231             : 
    9232             : /************************************************************************/
    9233             : /*                  GPKG_gdal_get_layer_pixel_value()                   */
    9234             : /************************************************************************/
    9235             : 
    9236             : // NOTE: keep in sync implementations in ogrsqlitesqlfunctionscommon.cpp
    9237             : // and ogrgeopackagedatasource.cpp
    9238          13 : static void GPKG_gdal_get_layer_pixel_value(sqlite3_context *pContext, int argc,
    9239             :                                             sqlite3_value **argv)
    9240             : {
    9241          13 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9242             :     {
    9243           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9244             :                  "Invalid arguments to gdal_get_layer_pixel_value()");
    9245           1 :         sqlite3_result_null(pContext);
    9246           1 :         return;
    9247             :     }
    9248             : 
    9249             :     const char *pszLayerName =
    9250          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9251             : 
    9252             :     GDALGeoPackageDataset *poGlobalDS =
    9253          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9254          12 :     auto poDS = poGlobalDS->GetRasterLayerDataset(pszLayerName);
    9255          12 :     if (!poDS)
    9256             :     {
    9257           0 :         sqlite3_result_null(pContext);
    9258           0 :         return;
    9259             :     }
    9260             : 
    9261          12 :     OGRSQLite_gdal_get_pixel_value_common("gdal_get_layer_pixel_value",
    9262             :                                           pContext, argc, argv, poDS);
    9263             : }
    9264             : 
    9265             : /************************************************************************/
    9266             : /*                       GPKG_ogr_layer_Extent()                        */
    9267             : /************************************************************************/
    9268             : 
    9269           3 : static void GPKG_ogr_layer_Extent(sqlite3_context *pContext, int /*argc*/,
    9270             :                                   sqlite3_value **argv)
    9271             : {
    9272           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9273             :     {
    9274           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Invalid argument type",
    9275             :                  "ogr_layer_Extent");
    9276           1 :         sqlite3_result_null(pContext);
    9277           2 :         return;
    9278             :     }
    9279             : 
    9280             :     const char *pszLayerName =
    9281           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9282             :     GDALGeoPackageDataset *poDS =
    9283           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9284           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9285           2 :     if (!poLayer)
    9286             :     {
    9287           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer",
    9288             :                  "ogr_layer_Extent");
    9289           1 :         sqlite3_result_null(pContext);
    9290           1 :         return;
    9291             :     }
    9292             : 
    9293           1 :     if (poLayer->GetGeomType() == wkbNone)
    9294             :     {
    9295           0 :         sqlite3_result_null(pContext);
    9296           0 :         return;
    9297             :     }
    9298             : 
    9299           1 :     OGREnvelope sExtent;
    9300           1 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9301             :     {
    9302           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9303             :                  "ogr_layer_Extent");
    9304           0 :         sqlite3_result_null(pContext);
    9305           0 :         return;
    9306             :     }
    9307             : 
    9308           1 :     OGRPolygon oPoly;
    9309           1 :     auto poRing = std::make_unique<OGRLinearRing>();
    9310           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9311           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MinY);
    9312           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MaxY);
    9313           1 :     poRing->addPoint(sExtent.MinX, sExtent.MaxY);
    9314           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9315           1 :     oPoly.addRing(std::move(poRing));
    9316             : 
    9317           1 :     const auto poSRS = poLayer->GetSpatialRef();
    9318           1 :     const int nSRID = poDS->GetSrsId(poSRS);
    9319           1 :     size_t nBLOBDestLen = 0;
    9320             :     GByte *pabyDestBLOB =
    9321           1 :         GPkgGeometryFromOGR(&oPoly, nSRID, nullptr, &nBLOBDestLen);
    9322           1 :     if (!pabyDestBLOB)
    9323             :     {
    9324           0 :         sqlite3_result_null(pContext);
    9325           0 :         return;
    9326             :     }
    9327           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    9328             :                         VSIFree);
    9329             : }
    9330             : 
    9331             : /************************************************************************/
    9332             : /*                   GPKG_ST_Hilbert_X_Y_TableName()                    */
    9333             : /************************************************************************/
    9334             : 
    9335           8 : static void GPKG_ST_Hilbert_X_Y_TableName(sqlite3_context *pContext,
    9336             :                                           [[maybe_unused]] int argc,
    9337             :                                           sqlite3_value **argv)
    9338             : {
    9339           8 :     CPLAssert(argc == 3);
    9340           8 :     const double dfX = sqlite3_value_double(argv[0]);
    9341           8 :     const double dfY = sqlite3_value_double(argv[1]);
    9342             : 
    9343           8 :     if (sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    9344             :     {
    9345           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9346             :                  "%s: Invalid argument type for 3rd argument. Text expected",
    9347             :                  "ST_Hilbert()");
    9348           1 :         sqlite3_result_null(pContext);
    9349           6 :         return;
    9350             :     }
    9351             : 
    9352             :     const char *pszLayerName =
    9353           7 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    9354             :     GDALGeoPackageDataset *poDS =
    9355           7 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9356           7 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9357           7 :     if (!poLayer)
    9358             :     {
    9359           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer '%s'",
    9360             :                  "ST_Hilbert()", pszLayerName);
    9361           1 :         sqlite3_result_null(pContext);
    9362           1 :         return;
    9363             :     }
    9364             : 
    9365           6 :     OGREnvelope sExtent;
    9366           6 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9367             :     {
    9368           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9369             :                  "ST_Hilbert()");
    9370           0 :         sqlite3_result_null(pContext);
    9371           0 :         return;
    9372             :     }
    9373           6 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9374           3 :           dfY <= sExtent.MaxY))
    9375             :     {
    9376           4 :         CPLError(CE_Warning, CPLE_AppDefined,
    9377             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9378             :                  dfX, dfY);
    9379           4 :         sqlite3_result_null(pContext);
    9380           4 :         return;
    9381             :     }
    9382           2 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9383             : }
    9384             : 
    9385             : /************************************************************************/
    9386             : /*                     GPKG_ST_Hilbert_Geom_BBOX()                      */
    9387             : /************************************************************************/
    9388             : 
    9389           6 : static void GPKG_ST_Hilbert_Geom_BBOX(sqlite3_context *pContext, int argc,
    9390             :                                       sqlite3_value **argv)
    9391             : {
    9392           6 :     CPLAssert(argc == 5);
    9393             :     GPkgHeader sHeader;
    9394           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    9395             :     {
    9396           1 :         sqlite3_result_null(pContext);
    9397           5 :         return;
    9398             :     }
    9399           5 :     const double dfX = (sHeader.MinX + sHeader.MaxX) / 2;
    9400           5 :     const double dfY = (sHeader.MinY + sHeader.MaxY) / 2;
    9401             : 
    9402           5 :     OGREnvelope sExtent;
    9403           5 :     sExtent.MinX = sqlite3_value_double(argv[1]);
    9404           5 :     sExtent.MinY = sqlite3_value_double(argv[2]);
    9405           5 :     sExtent.MaxX = sqlite3_value_double(argv[3]);
    9406           5 :     sExtent.MaxY = sqlite3_value_double(argv[4]);
    9407           5 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9408           2 :           dfY <= sExtent.MaxY))
    9409             :     {
    9410           4 :         CPLError(CE_Warning, CPLE_AppDefined,
    9411             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9412             :                  dfX, dfY);
    9413           4 :         sqlite3_result_null(pContext);
    9414           4 :         return;
    9415             :     }
    9416           1 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9417             : }
    9418             : 
    9419             : /************************************************************************/
    9420             : /*                   GPKG_ST_Hilbert_Geom_TableName()                   */
    9421             : /************************************************************************/
    9422             : 
    9423           4 : static void GPKG_ST_Hilbert_Geom_TableName(sqlite3_context *pContext, int argc,
    9424             :                                            sqlite3_value **argv)
    9425             : {
    9426           4 :     CPLAssert(argc == 2);
    9427             :     GPkgHeader sHeader;
    9428           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    9429             :     {
    9430           1 :         sqlite3_result_null(pContext);
    9431           3 :         return;
    9432             :     }
    9433           3 :     const double dfX = (sHeader.MinX + sHeader.MaxX) / 2;
    9434           3 :     const double dfY = (sHeader.MinY + sHeader.MaxY) / 2;
    9435             : 
    9436           3 :     if (sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9437             :     {
    9438           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9439             :                  "%s: Invalid argument type for 2nd argument. Text expected",
    9440             :                  "ST_Hilbert()");
    9441           1 :         sqlite3_result_null(pContext);
    9442           1 :         return;
    9443             :     }
    9444             : 
    9445             :     const char *pszLayerName =
    9446           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9447             :     GDALGeoPackageDataset *poDS =
    9448           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9449           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9450           2 :     if (!poLayer)
    9451             :     {
    9452           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer '%s'",
    9453             :                  "ST_Hilbert()", pszLayerName);
    9454           1 :         sqlite3_result_null(pContext);
    9455           1 :         return;
    9456             :     }
    9457             : 
    9458           1 :     OGREnvelope sExtent;
    9459           1 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9460             :     {
    9461           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9462             :                  "ST_Hilbert()");
    9463           0 :         sqlite3_result_null(pContext);
    9464           0 :         return;
    9465             :     }
    9466           1 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9467           1 :           dfY <= sExtent.MaxY))
    9468             :     {
    9469           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9470             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9471             :                  dfX, dfY);
    9472           0 :         sqlite3_result_null(pContext);
    9473           0 :         return;
    9474             :     }
    9475           1 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9476             : }
    9477             : 
    9478             : /************************************************************************/
    9479             : /*                        InstallSQLFunctions()                         */
    9480             : /************************************************************************/
    9481             : 
    9482             : #ifndef SQLITE_DETERMINISTIC
    9483             : #define SQLITE_DETERMINISTIC 0
    9484             : #endif
    9485             : 
    9486             : #ifndef SQLITE_INNOCUOUS
    9487             : #define SQLITE_INNOCUOUS 0
    9488             : #endif
    9489             : 
    9490             : #ifndef UTF8_INNOCUOUS
    9491             : #define UTF8_INNOCUOUS (SQLITE_UTF8 | SQLITE_DETERMINISTIC | SQLITE_INNOCUOUS)
    9492             : #endif
    9493             : 
    9494        2623 : void GDALGeoPackageDataset::InstallSQLFunctions()
    9495             : {
    9496        2623 :     InitSpatialite();
    9497             : 
    9498             :     // Enable SpatiaLite 4.3 GPKG mode, i.e. that SpatiaLite functions
    9499             :     // that take geometries will accept and return GPKG encoded geometries without
    9500             :     // explicit conversion.
    9501             :     // Use sqlite3_exec() instead of SQLCommand() since we don't want verbose
    9502             :     // error.
    9503        2623 :     sqlite3_exec(hDB, "SELECT EnableGpkgMode()", nullptr, nullptr, nullptr);
    9504             : 
    9505             :     /* Used by RTree Spatial Index Extension */
    9506        2623 :     sqlite3_create_function(hDB, "ST_MinX", 1, UTF8_INNOCUOUS, nullptr,
    9507             :                             OGRGeoPackageSTMinX, nullptr, nullptr);
    9508        2623 :     sqlite3_create_function(hDB, "ST_MinY", 1, UTF8_INNOCUOUS, nullptr,
    9509             :                             OGRGeoPackageSTMinY, nullptr, nullptr);
    9510        2623 :     sqlite3_create_function(hDB, "ST_MaxX", 1, UTF8_INNOCUOUS, nullptr,
    9511             :                             OGRGeoPackageSTMaxX, nullptr, nullptr);
    9512        2623 :     sqlite3_create_function(hDB, "ST_MaxY", 1, UTF8_INNOCUOUS, nullptr,
    9513             :                             OGRGeoPackageSTMaxY, nullptr, nullptr);
    9514        2623 :     sqlite3_create_function(hDB, "ST_IsEmpty", 1, UTF8_INNOCUOUS, nullptr,
    9515             :                             OGRGeoPackageSTIsEmpty, nullptr, nullptr);
    9516             : 
    9517             :     /* Used by Geometry Type Triggers Extension */
    9518        2623 :     sqlite3_create_function(hDB, "ST_GeometryType", 1, UTF8_INNOCUOUS, nullptr,
    9519             :                             OGRGeoPackageSTGeometryType, nullptr, nullptr);
    9520        2623 :     sqlite3_create_function(hDB, "GPKG_IsAssignable", 2, UTF8_INNOCUOUS,
    9521             :                             nullptr, OGRGeoPackageGPKGIsAssignable, nullptr,
    9522             :                             nullptr);
    9523             : 
    9524             :     /* Used by Geometry SRS ID Triggers Extension */
    9525        2623 :     sqlite3_create_function(hDB, "ST_SRID", 1, UTF8_INNOCUOUS, nullptr,
    9526             :                             OGRGeoPackageSTSRID, nullptr, nullptr);
    9527             : 
    9528             :     /* Spatialite-like functions */
    9529        2623 :     sqlite3_create_function(hDB, "CreateSpatialIndex", 2, SQLITE_UTF8, this,
    9530             :                             OGRGeoPackageCreateSpatialIndex, nullptr, nullptr);
    9531        2623 :     sqlite3_create_function(hDB, "DisableSpatialIndex", 2, SQLITE_UTF8, this,
    9532             :                             OGRGeoPackageDisableSpatialIndex, nullptr, nullptr);
    9533        2623 :     sqlite3_create_function(hDB, "HasSpatialIndex", 2, SQLITE_UTF8, this,
    9534             :                             OGRGeoPackageHasSpatialIndex, nullptr, nullptr);
    9535             : 
    9536             :     // HSTORE functions
    9537        2623 :     sqlite3_create_function(hDB, "hstore_get_value", 2, UTF8_INNOCUOUS, nullptr,
    9538             :                             GPKG_hstore_get_value, nullptr, nullptr);
    9539             : 
    9540             :     // Override a few Spatialite functions to work with gpkg_spatial_ref_sys
    9541        2623 :     sqlite3_create_function(hDB, "ST_Transform", 2, UTF8_INNOCUOUS, this,
    9542             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9543        2623 :     sqlite3_create_function(hDB, "Transform", 2, UTF8_INNOCUOUS, this,
    9544             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9545        2623 :     sqlite3_create_function(hDB, "SridFromAuthCRS", 2, SQLITE_UTF8, this,
    9546             :                             OGRGeoPackageSridFromAuthCRS, nullptr, nullptr);
    9547             : 
    9548        2623 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9549             :                             OGRGeoPackageSTEnvelopesIntersectsTwoParams,
    9550             :                             nullptr, nullptr);
    9551        2623 :     sqlite3_create_function(
    9552             :         hDB, "ST_EnvelopesIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9553             :         OGRGeoPackageSTEnvelopesIntersectsTwoParams, nullptr, nullptr);
    9554             : 
    9555        2623 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 5, UTF8_INNOCUOUS, nullptr,
    9556             :                             OGRGeoPackageSTEnvelopesIntersects, nullptr,
    9557             :                             nullptr);
    9558        2623 :     sqlite3_create_function(hDB, "ST_EnvelopesIntersects", 5, UTF8_INNOCUOUS,
    9559             :                             nullptr, OGRGeoPackageSTEnvelopesIntersects,
    9560             :                             nullptr, nullptr);
    9561             : 
    9562             :     // Implementation that directly hacks the GeoPackage geometry blob header
    9563        2623 :     sqlite3_create_function(hDB, "SetSRID", 2, UTF8_INNOCUOUS, nullptr,
    9564             :                             OGRGeoPackageSetSRID, nullptr, nullptr);
    9565             : 
    9566             :     // GDAL specific function
    9567        2623 :     sqlite3_create_function(hDB, "ImportFromEPSG", 1, SQLITE_UTF8, this,
    9568             :                             OGRGeoPackageImportFromEPSG, nullptr, nullptr);
    9569             : 
    9570             :     // May be used by ogrmerge.py
    9571        2623 :     sqlite3_create_function(hDB, "RegisterGeometryExtension", 3, SQLITE_UTF8,
    9572             :                             this, OGRGeoPackageRegisterGeometryExtension,
    9573             :                             nullptr, nullptr);
    9574             : 
    9575        2623 :     if (OGRGeometryFactory::haveGEOS())
    9576             :     {
    9577        2623 :         sqlite3_create_function(hDB, "ST_MakeValid", 1, UTF8_INNOCUOUS, nullptr,
    9578             :                                 OGRGeoPackageSTMakeValid, nullptr, nullptr);
    9579             :     }
    9580             : 
    9581        2623 :     sqlite3_create_function(hDB, "ST_Length", 1, UTF8_INNOCUOUS, nullptr,
    9582             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9583             :                             nullptr);
    9584        2623 :     sqlite3_create_function(hDB, "ST_Length", 2, UTF8_INNOCUOUS, this,
    9585             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9586             :                             nullptr);
    9587             : 
    9588        2623 :     sqlite3_create_function(hDB, "ST_Area", 1, UTF8_INNOCUOUS, nullptr,
    9589             :                             OGRGeoPackageSTArea, nullptr, nullptr);
    9590        2623 :     sqlite3_create_function(hDB, "ST_Area", 2, UTF8_INNOCUOUS, this,
    9591             :                             OGRGeoPackageGeodesicArea, nullptr, nullptr);
    9592             : 
    9593             :     // Debug functions
    9594        2623 :     if (CPLTestBool(CPLGetConfigOption("GPKG_DEBUG", "FALSE")))
    9595             :     {
    9596         428 :         sqlite3_create_function(hDB, "GDAL_GetMimeType", 1,
    9597             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9598             :                                 GPKG_GDAL_GetMimeType, nullptr, nullptr);
    9599         428 :         sqlite3_create_function(hDB, "GDAL_GetBandCount", 1,
    9600             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9601             :                                 GPKG_GDAL_GetBandCount, nullptr, nullptr);
    9602         428 :         sqlite3_create_function(hDB, "GDAL_HasColorTable", 1,
    9603             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9604             :                                 GPKG_GDAL_HasColorTable, nullptr, nullptr);
    9605             :     }
    9606             : 
    9607        2623 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 5, SQLITE_UTF8,
    9608             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9609             :                             nullptr);
    9610        2623 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 6, SQLITE_UTF8,
    9611             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9612             :                             nullptr);
    9613             : 
    9614             :     // Function from VirtualOGR
    9615        2623 :     sqlite3_create_function(hDB, "ogr_layer_Extent", 1, SQLITE_UTF8, this,
    9616             :                             GPKG_ogr_layer_Extent, nullptr, nullptr);
    9617             : 
    9618        2623 :     m_pSQLFunctionData = OGRSQLiteRegisterSQLFunctionsCommon(hDB);
    9619             : 
    9620             :     // ST_Hilbert() inspired from https://duckdb.org/docs/stable/core_extensions/spatial/functions#st_hilbert
    9621             :     // Override the generic version of OGRSQLiteRegisterSQLFunctionsCommon()
    9622             : 
    9623             :     // X,Y,table_name
    9624        2623 :     sqlite3_create_function(hDB, "ST_Hilbert", 2 + 1, UTF8_INNOCUOUS, this,
    9625             :                             GPKG_ST_Hilbert_X_Y_TableName, nullptr, nullptr);
    9626             : 
    9627             :     // geometry,minX,minY,maxX,maxY
    9628        2623 :     sqlite3_create_function(hDB, "ST_Hilbert", 1 + 4, UTF8_INNOCUOUS, nullptr,
    9629             :                             GPKG_ST_Hilbert_Geom_BBOX, nullptr, nullptr);
    9630             : 
    9631             :     // geometry,table_name
    9632        2623 :     sqlite3_create_function(hDB, "ST_Hilbert", 1 + 1, UTF8_INNOCUOUS, this,
    9633             :                             GPKG_ST_Hilbert_Geom_TableName, nullptr, nullptr);
    9634        2623 : }
    9635             : 
    9636             : /************************************************************************/
    9637             : /*                           OpenOrCreateDB()                           */
    9638             : /************************************************************************/
    9639             : 
    9640        2628 : bool GDALGeoPackageDataset::OpenOrCreateDB(int flags)
    9641             : {
    9642        2628 :     const bool bSuccess = OGRSQLiteBaseDataSource::OpenOrCreateDB(
    9643             :         flags, /*bRegisterOGR2SQLiteExtensions=*/false,
    9644             :         /*bLoadExtensions=*/true);
    9645        2628 :     if (!bSuccess)
    9646          10 :         return false;
    9647             : 
    9648             :     // Turning on recursive_triggers is needed so that DELETE triggers fire
    9649             :     // in a INSERT OR REPLACE statement. In particular this is needed to
    9650             :     // make sure gpkg_ogr_contents.feature_count is properly updated.
    9651        2618 :     SQLCommand(hDB, "PRAGMA recursive_triggers = 1");
    9652             : 
    9653        2618 :     InstallSQLFunctions();
    9654             : 
    9655             :     const char *pszSqlitePragma =
    9656        2618 :         CPLGetConfigOption("OGR_SQLITE_PRAGMA", nullptr);
    9657        2618 :     OGRErr eErr = OGRERR_NONE;
    9658           6 :     if ((!pszSqlitePragma || !strstr(pszSqlitePragma, "trusted_schema")) &&
    9659             :         // Older sqlite versions don't have this pragma
    9660        5242 :         SQLGetInteger(hDB, "PRAGMA trusted_schema", &eErr) == 0 &&
    9661        2618 :         eErr == OGRERR_NONE)
    9662             :     {
    9663        2618 :         bool bNeedsTrustedSchema = false;
    9664             : 
    9665             :         // Current SQLite versions require PRAGMA trusted_schema = 1 to be
    9666             :         // able to use the RTree from triggers, which is only needed when
    9667             :         // modifying the RTree.
    9668        6429 :         if (((flags & SQLITE_OPEN_READWRITE) != 0 ||
    9669        4043 :              (flags & SQLITE_OPEN_CREATE) != 0) &&
    9670        1425 :             OGRSQLiteRTreeRequiresTrustedSchemaOn())
    9671             :         {
    9672        1425 :             bNeedsTrustedSchema = true;
    9673             :         }
    9674             : 
    9675             : #ifdef HAVE_SPATIALITE
    9676             :         // Spatialite <= 5.1.0 doesn't declare its functions as SQLITE_INNOCUOUS
    9677        1193 :         if (!bNeedsTrustedSchema && HasExtensionsTable() &&
    9678        1098 :             SQLGetInteger(
    9679             :                 hDB,
    9680             :                 "SELECT 1 FROM gpkg_extensions WHERE "
    9681             :                 "extension_name ='gdal_spatialite_computed_geom_column'",
    9682           1 :                 nullptr) == 1 &&
    9683        3811 :             SpatialiteRequiresTrustedSchemaOn() && AreSpatialiteTriggersSafe())
    9684             :         {
    9685           1 :             bNeedsTrustedSchema = true;
    9686             :         }
    9687             : #endif
    9688             : 
    9689        2618 :         if (bNeedsTrustedSchema)
    9690             :         {
    9691        1426 :             CPLDebug("GPKG", "Setting PRAGMA trusted_schema = 1");
    9692        1426 :             SQLCommand(hDB, "PRAGMA trusted_schema = 1");
    9693             :         }
    9694             :     }
    9695             : 
    9696             :     const char *pszPreludeStatements =
    9697        2618 :         CSLFetchNameValue(papszOpenOptions, "PRELUDE_STATEMENTS");
    9698        2618 :     if (pszPreludeStatements)
    9699             :     {
    9700           2 :         if (SQLCommand(hDB, pszPreludeStatements) != OGRERR_NONE)
    9701           0 :             return false;
    9702             :     }
    9703             : 
    9704        2618 :     return true;
    9705             : }
    9706             : 
    9707             : /************************************************************************/
    9708             : /*                 GetLayerWithGetSpatialWhereByName()                  */
    9709             : /************************************************************************/
    9710             : 
    9711             : std::pair<OGRLayer *, IOGRSQLiteGetSpatialWhere *>
    9712          98 : GDALGeoPackageDataset::GetLayerWithGetSpatialWhereByName(const char *pszName)
    9713             : {
    9714             :     OGRGeoPackageLayer *poRet =
    9715          98 :         cpl::down_cast<OGRGeoPackageLayer *>(GetLayerByName(pszName));
    9716          98 :     return std::pair(poRet, poRet);
    9717             : }
    9718             : 
    9719             : /************************************************************************/
    9720             : /*                         CommitTransaction()                          */
    9721             : /************************************************************************/
    9722             : 
    9723         420 : OGRErr GDALGeoPackageDataset::CommitTransaction()
    9724             : 
    9725             : {
    9726         420 :     if (m_nSoftTransactionLevel == 1)
    9727             :     {
    9728         414 :         FlushMetadata();
    9729         883 :         for (auto &poLayer : m_apoLayers)
    9730             :         {
    9731         469 :             poLayer->DoJobAtTransactionCommit();
    9732             :         }
    9733             :     }
    9734             : 
    9735         420 :     return OGRSQLiteBaseDataSource::CommitTransaction();
    9736             : }
    9737             : 
    9738             : /************************************************************************/
    9739             : /*                        RollbackTransaction()                         */
    9740             : /************************************************************************/
    9741             : 
    9742          37 : OGRErr GDALGeoPackageDataset::RollbackTransaction()
    9743             : 
    9744             : {
    9745             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9746          74 :     std::vector<bool> abAddTriggers;
    9747          37 :     std::vector<bool> abTriggersDeletedInTransaction;
    9748             : #endif
    9749          37 :     if (m_nSoftTransactionLevel == 1)
    9750             :     {
    9751          36 :         FlushMetadata();
    9752          74 :         for (auto &poLayer : m_apoLayers)
    9753             :         {
    9754             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9755          38 :             abAddTriggers.push_back(poLayer->GetAddOGRFeatureCountTriggers());
    9756          38 :             abTriggersDeletedInTransaction.push_back(
    9757          38 :                 poLayer->GetOGRFeatureCountTriggersDeletedInTransaction());
    9758          38 :             poLayer->SetAddOGRFeatureCountTriggers(false);
    9759             : #endif
    9760          38 :             poLayer->DoJobAtTransactionRollback();
    9761             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9762          38 :             poLayer->DisableFeatureCount();
    9763             : #endif
    9764             :         }
    9765             :     }
    9766             : 
    9767          37 :     const OGRErr eErr = OGRSQLiteBaseDataSource::RollbackTransaction();
    9768             : 
    9769             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9770          37 :     if (!abAddTriggers.empty())
    9771             :     {
    9772          72 :         for (size_t i = 0; i < m_apoLayers.size(); ++i)
    9773             :         {
    9774          38 :             auto &poLayer = m_apoLayers[i];
    9775          38 :             if (abTriggersDeletedInTransaction[i])
    9776             :             {
    9777           7 :                 poLayer->SetOGRFeatureCountTriggersEnabled(true);
    9778             :             }
    9779             :             else
    9780             :             {
    9781          31 :                 poLayer->SetAddOGRFeatureCountTriggers(abAddTriggers[i]);
    9782             :             }
    9783             :         }
    9784             :     }
    9785             : #endif
    9786          74 :     return eErr;
    9787             : }
    9788             : 
    9789             : /************************************************************************/
    9790             : /*                       GetGeometryTypeString()                        */
    9791             : /************************************************************************/
    9792             : 
    9793             : const char *
    9794        1950 : GDALGeoPackageDataset::GetGeometryTypeString(OGRwkbGeometryType eType)
    9795             : {
    9796        1950 :     const char *pszGPKGGeomType = OGRToOGCGeomType(eType);
    9797        1962 :     if (EQUAL(pszGPKGGeomType, "GEOMETRYCOLLECTION") &&
    9798          12 :         CPLTestBool(CPLGetConfigOption("OGR_GPKG_GEOMCOLLECTION", "NO")))
    9799             :     {
    9800           0 :         pszGPKGGeomType = "GEOMCOLLECTION";
    9801             :     }
    9802        1950 :     return pszGPKGGeomType;
    9803             : }
    9804             : 
    9805             : /************************************************************************/
    9806             : /*                        GetFieldDomainNames()                         */
    9807             : /************************************************************************/
    9808             : 
    9809             : std::vector<std::string>
    9810          18 : GDALGeoPackageDataset::GetFieldDomainNames(CSLConstList) const
    9811             : {
    9812          18 :     if (!HasDataColumnConstraintsTable())
    9813           3 :         return std::vector<std::string>();
    9814             : 
    9815          30 :     std::vector<std::string> oDomainNamesList;
    9816             : 
    9817          15 :     std::unique_ptr<SQLResult> oResultTable;
    9818             :     {
    9819             :         std::string osSQL =
    9820             :             "SELECT DISTINCT constraint_name "
    9821             :             "FROM gpkg_data_column_constraints "
    9822             :             "WHERE constraint_name NOT LIKE '_%_domain_description' "
    9823             :             "ORDER BY constraint_name "
    9824          15 :             "LIMIT 10000"  // to avoid denial of service
    9825             :             ;
    9826          15 :         oResultTable = SQLQuery(hDB, osSQL.c_str());
    9827          15 :         if (!oResultTable)
    9828           0 :             return oDomainNamesList;
    9829             :     }
    9830             : 
    9831          15 :     if (oResultTable->RowCount() == 10000)
    9832             :     {
    9833           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9834             :                  "Number of rows returned for field domain names has been "
    9835             :                  "truncated.");
    9836             :     }
    9837          15 :     else if (oResultTable->RowCount() > 0)
    9838             :     {
    9839          14 :         oDomainNamesList.reserve(oResultTable->RowCount());
    9840         147 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    9841             :         {
    9842         133 :             const char *pszConstraintName = oResultTable->GetValue(0, i);
    9843         133 :             if (!pszConstraintName)
    9844           0 :                 continue;
    9845             : 
    9846         133 :             oDomainNamesList.emplace_back(pszConstraintName);
    9847             :         }
    9848             :     }
    9849             : 
    9850          15 :     return oDomainNamesList;
    9851             : }
    9852             : 
    9853             : /************************************************************************/
    9854             : /*                           GetFieldDomain()                           */
    9855             : /************************************************************************/
    9856             : 
    9857             : const OGRFieldDomain *
    9858         140 : GDALGeoPackageDataset::GetFieldDomain(const std::string &name) const
    9859             : {
    9860         140 :     const auto baseRet = GDALDataset::GetFieldDomain(name);
    9861         140 :     if (baseRet)
    9862          43 :         return baseRet;
    9863             : 
    9864          97 :     if (!HasDataColumnConstraintsTable())
    9865           4 :         return nullptr;
    9866             : 
    9867          93 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
    9868          93 :     const char *min_is_inclusive =
    9869          93 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
    9870          93 :     const char *max_is_inclusive =
    9871          93 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
    9872             : 
    9873          93 :     std::unique_ptr<SQLResult> oResultTable;
    9874             :     // Note: for coded domains, we use a little trick by using a dummy
    9875             :     // _{domainname}_domain_description enum that has a single entry whose
    9876             :     // description is the description of the main domain.
    9877             :     {
    9878          93 :         char *pszSQL = sqlite3_mprintf(
    9879             :             "SELECT constraint_type, value, min, %s, "
    9880             :             "max, %s, description, constraint_name "
    9881             :             "FROM gpkg_data_column_constraints "
    9882             :             "WHERE constraint_name IN ('%q', "
    9883             :             "'_%q_domain_description') "
    9884             :             "AND length(constraint_type) < 100 "  // to
    9885             :                                                   // avoid
    9886             :                                                   // denial
    9887             :                                                   // of
    9888             :                                                   // service
    9889             :             "AND (value IS NULL OR length(value) < "
    9890             :             "10000) "  // to avoid denial
    9891             :                        // of service
    9892             :             "AND (description IS NULL OR "
    9893             :             "length(description) < 10000) "  // to
    9894             :                                              // avoid
    9895             :                                              // denial
    9896             :                                              // of
    9897             :                                              // service
    9898             :             "ORDER BY value "
    9899             :             "LIMIT 10000",  // to avoid denial of
    9900             :                             // service
    9901             :             min_is_inclusive, max_is_inclusive, name.c_str(), name.c_str());
    9902          93 :         oResultTable = SQLQuery(hDB, pszSQL);
    9903          93 :         sqlite3_free(pszSQL);
    9904          93 :         if (!oResultTable)
    9905           0 :             return nullptr;
    9906             :     }
    9907          93 :     if (oResultTable->RowCount() == 0)
    9908             :     {
    9909          33 :         return nullptr;
    9910             :     }
    9911          60 :     if (oResultTable->RowCount() == 10000)
    9912             :     {
    9913           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9914             :                  "Number of rows returned for field domain %s has been "
    9915             :                  "truncated.",
    9916             :                  name.c_str());
    9917             :     }
    9918             : 
    9919             :     // Try to find the field domain data type from fields that implement it
    9920          60 :     int nFieldType = -1;
    9921          60 :     OGRFieldSubType eSubType = OFSTNone;
    9922          60 :     if (HasDataColumnsTable())
    9923             :     {
    9924          55 :         char *pszSQL = sqlite3_mprintf(
    9925             :             "SELECT table_name, column_name FROM gpkg_data_columns WHERE "
    9926             :             "constraint_name = '%q' LIMIT 10",
    9927             :             name.c_str());
    9928         110 :         auto oResultTable2 = SQLQuery(hDB, pszSQL);
    9929          55 :         sqlite3_free(pszSQL);
    9930          55 :         if (oResultTable2 && oResultTable2->RowCount() >= 1)
    9931             :         {
    9932          62 :             for (int iRecord = 0; iRecord < oResultTable2->RowCount();
    9933             :                  iRecord++)
    9934             :             {
    9935          31 :                 const char *pszTableName = oResultTable2->GetValue(0, iRecord);
    9936          31 :                 const char *pszColumnName = oResultTable2->GetValue(1, iRecord);
    9937          31 :                 if (pszTableName == nullptr || pszColumnName == nullptr)
    9938           0 :                     continue;
    9939             :                 OGRLayer *poLayer =
    9940          62 :                     const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    9941          31 :                         pszTableName);
    9942          31 :                 if (poLayer)
    9943             :                 {
    9944          31 :                     const auto poFDefn = poLayer->GetLayerDefn();
    9945          31 :                     int nIdx = poFDefn->GetFieldIndex(pszColumnName);
    9946          31 :                     if (nIdx >= 0)
    9947             :                     {
    9948          31 :                         const auto poFieldDefn = poFDefn->GetFieldDefn(nIdx);
    9949          31 :                         const auto eType = poFieldDefn->GetType();
    9950          31 :                         if (nFieldType < 0)
    9951             :                         {
    9952          31 :                             nFieldType = eType;
    9953          31 :                             eSubType = poFieldDefn->GetSubType();
    9954             :                         }
    9955           0 :                         else if ((eType == OFTInteger64 || eType == OFTReal) &&
    9956             :                                  nFieldType == OFTInteger)
    9957             :                         {
    9958             :                             // ok
    9959             :                         }
    9960           0 :                         else if (eType == OFTInteger &&
    9961           0 :                                  (nFieldType == OFTInteger64 ||
    9962             :                                   nFieldType == OFTReal))
    9963             :                         {
    9964           0 :                             nFieldType = OFTInteger;
    9965           0 :                             eSubType = OFSTNone;
    9966             :                         }
    9967           0 :                         else if (nFieldType != eType)
    9968             :                         {
    9969           0 :                             nFieldType = -1;
    9970           0 :                             eSubType = OFSTNone;
    9971           0 :                             break;
    9972             :                         }
    9973             :                     }
    9974             :                 }
    9975             :             }
    9976             :         }
    9977             :     }
    9978             : 
    9979          60 :     std::unique_ptr<OGRFieldDomain> poDomain;
    9980         120 :     std::vector<OGRCodedValue> asValues;
    9981          60 :     bool error = false;
    9982         120 :     CPLString osLastConstraintType;
    9983          60 :     int nFieldTypeFromEnumCode = -1;
    9984         120 :     std::string osConstraintDescription;
    9985         120 :     std::string osDescrConstraintName("_");
    9986          60 :     osDescrConstraintName += name;
    9987          60 :     osDescrConstraintName += "_domain_description";
    9988         151 :     for (int iRecord = 0; iRecord < oResultTable->RowCount(); iRecord++)
    9989             :     {
    9990          95 :         const char *pszConstraintType = oResultTable->GetValue(0, iRecord);
    9991          95 :         if (pszConstraintType == nullptr)
    9992           2 :             continue;
    9993          95 :         const char *pszValue = oResultTable->GetValue(1, iRecord);
    9994          95 :         const char *pszMin = oResultTable->GetValue(2, iRecord);
    9995             :         const bool bIsMinIncluded =
    9996          95 :             oResultTable->GetValueAsInteger(3, iRecord) == 1;
    9997          95 :         const char *pszMax = oResultTable->GetValue(4, iRecord);
    9998             :         const bool bIsMaxIncluded =
    9999          95 :             oResultTable->GetValueAsInteger(5, iRecord) == 1;
   10000          95 :         const char *pszDescription = oResultTable->GetValue(6, iRecord);
   10001          95 :         const char *pszConstraintName = oResultTable->GetValue(7, iRecord);
   10002             : 
   10003          95 :         if (!osLastConstraintType.empty() && osLastConstraintType != "enum")
   10004             :         {
   10005           1 :             CPLError(CE_Failure, CPLE_AppDefined,
   10006             :                      "Only constraint of type 'enum' can have multiple rows");
   10007           1 :             error = true;
   10008           4 :             break;
   10009             :         }
   10010             : 
   10011          94 :         if (strcmp(pszConstraintType, "enum") == 0)
   10012             :         {
   10013          67 :             if (pszValue == nullptr)
   10014             :             {
   10015           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10016             :                          "NULL in 'value' column of enumeration");
   10017           1 :                 error = true;
   10018           1 :                 break;
   10019             :             }
   10020          66 :             if (osDescrConstraintName == pszConstraintName)
   10021             :             {
   10022           2 :                 if (pszDescription)
   10023             :                 {
   10024           2 :                     osConstraintDescription = pszDescription;
   10025             :                 }
   10026           2 :                 continue;
   10027             :             }
   10028          64 :             if (asValues.empty())
   10029             :             {
   10030          32 :                 asValues.reserve(oResultTable->RowCount() + 1);
   10031             :             }
   10032             :             OGRCodedValue cv;
   10033             :             // intended: the 'value' column in GPKG is actually the code
   10034          64 :             cv.pszCode = VSI_STRDUP_VERBOSE(pszValue);
   10035          64 :             if (cv.pszCode == nullptr)
   10036             :             {
   10037           0 :                 error = true;
   10038           0 :                 break;
   10039             :             }
   10040          64 :             if (pszDescription)
   10041             :             {
   10042          50 :                 cv.pszValue = VSI_STRDUP_VERBOSE(pszDescription);
   10043          50 :                 if (cv.pszValue == nullptr)
   10044             :                 {
   10045           0 :                     VSIFree(cv.pszCode);
   10046           0 :                     error = true;
   10047           0 :                     break;
   10048             :                 }
   10049             :             }
   10050             :             else
   10051             :             {
   10052          14 :                 cv.pszValue = nullptr;
   10053             :             }
   10054             : 
   10055             :             // If we can't get the data type from field definition, guess it
   10056             :             // from code.
   10057          64 :             if (nFieldType < 0 && nFieldTypeFromEnumCode != OFTString)
   10058             :             {
   10059          36 :                 switch (CPLGetValueType(cv.pszCode))
   10060             :                 {
   10061          26 :                     case CPL_VALUE_INTEGER:
   10062             :                     {
   10063          26 :                         if (nFieldTypeFromEnumCode != OFTReal &&
   10064             :                             nFieldTypeFromEnumCode != OFTInteger64)
   10065             :                         {
   10066          18 :                             const auto nVal = CPLAtoGIntBig(cv.pszCode);
   10067          34 :                             if (nVal < std::numeric_limits<int>::min() ||
   10068          16 :                                 nVal > std::numeric_limits<int>::max())
   10069             :                             {
   10070           6 :                                 nFieldTypeFromEnumCode = OFTInteger64;
   10071             :                             }
   10072             :                             else
   10073             :                             {
   10074          12 :                                 nFieldTypeFromEnumCode = OFTInteger;
   10075             :                             }
   10076             :                         }
   10077          26 :                         break;
   10078             :                     }
   10079             : 
   10080           6 :                     case CPL_VALUE_REAL:
   10081           6 :                         nFieldTypeFromEnumCode = OFTReal;
   10082           6 :                         break;
   10083             : 
   10084           4 :                     case CPL_VALUE_STRING:
   10085           4 :                         nFieldTypeFromEnumCode = OFTString;
   10086           4 :                         break;
   10087             :                 }
   10088             :             }
   10089             : 
   10090          64 :             asValues.emplace_back(cv);
   10091             :         }
   10092          27 :         else if (strcmp(pszConstraintType, "range") == 0)
   10093             :         {
   10094             :             OGRField sMin;
   10095             :             OGRField sMax;
   10096          20 :             OGR_RawField_SetUnset(&sMin);
   10097          20 :             OGR_RawField_SetUnset(&sMax);
   10098          20 :             if (nFieldType != OFTInteger && nFieldType != OFTInteger64)
   10099          11 :                 nFieldType = OFTReal;
   10100          39 :             if (pszMin != nullptr &&
   10101          19 :                 CPLAtof(pszMin) != -std::numeric_limits<double>::infinity())
   10102             :             {
   10103          15 :                 if (nFieldType == OFTInteger)
   10104           6 :                     sMin.Integer = atoi(pszMin);
   10105           9 :                 else if (nFieldType == OFTInteger64)
   10106           3 :                     sMin.Integer64 = CPLAtoGIntBig(pszMin);
   10107             :                 else /* if( nFieldType == OFTReal ) */
   10108           6 :                     sMin.Real = CPLAtof(pszMin);
   10109             :             }
   10110          39 :             if (pszMax != nullptr &&
   10111          19 :                 CPLAtof(pszMax) != std::numeric_limits<double>::infinity())
   10112             :             {
   10113          15 :                 if (nFieldType == OFTInteger)
   10114           6 :                     sMax.Integer = atoi(pszMax);
   10115           9 :                 else if (nFieldType == OFTInteger64)
   10116           3 :                     sMax.Integer64 = CPLAtoGIntBig(pszMax);
   10117             :                 else /* if( nFieldType == OFTReal ) */
   10118           6 :                     sMax.Real = CPLAtof(pszMax);
   10119             :             }
   10120          20 :             poDomain = std::make_unique<OGRRangeFieldDomain>(
   10121          20 :                 name, pszDescription ? pszDescription : "",
   10122          40 :                 static_cast<OGRFieldType>(nFieldType), eSubType, sMin,
   10123          20 :                 bIsMinIncluded, sMax, bIsMaxIncluded);
   10124             :         }
   10125           7 :         else if (strcmp(pszConstraintType, "glob") == 0)
   10126             :         {
   10127           6 :             if (pszValue == nullptr)
   10128             :             {
   10129           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10130             :                          "NULL in 'value' column of glob");
   10131           1 :                 error = true;
   10132           1 :                 break;
   10133             :             }
   10134           5 :             if (nFieldType < 0)
   10135           1 :                 nFieldType = OFTString;
   10136           5 :             poDomain = std::make_unique<OGRGlobFieldDomain>(
   10137           5 :                 name, pszDescription ? pszDescription : "",
   10138          15 :                 static_cast<OGRFieldType>(nFieldType), eSubType, pszValue);
   10139             :         }
   10140             :         else
   10141             :         {
   10142           1 :             CPLError(CE_Failure, CPLE_AppDefined,
   10143             :                      "Unhandled constraint_type: %s", pszConstraintType);
   10144           1 :             error = true;
   10145           1 :             break;
   10146             :         }
   10147             : 
   10148          89 :         osLastConstraintType = pszConstraintType;
   10149             :     }
   10150             : 
   10151          60 :     if (!asValues.empty())
   10152             :     {
   10153          32 :         if (nFieldType < 0)
   10154          18 :             nFieldType = nFieldTypeFromEnumCode;
   10155          32 :         poDomain = std::make_unique<OGRCodedFieldDomain>(
   10156             :             name, osConstraintDescription,
   10157          64 :             static_cast<OGRFieldType>(nFieldType), eSubType,
   10158          64 :             std::move(asValues));
   10159             :     }
   10160             : 
   10161          60 :     if (error)
   10162             :     {
   10163           4 :         return nullptr;
   10164             :     }
   10165             : 
   10166          56 :     m_oMapFieldDomains[name] = std::move(poDomain);
   10167          56 :     return GDALDataset::GetFieldDomain(name);
   10168             : }
   10169             : 
   10170             : /************************************************************************/
   10171             : /*                           AddFieldDomain()                           */
   10172             : /************************************************************************/
   10173             : 
   10174          19 : bool GDALGeoPackageDataset::AddFieldDomain(
   10175             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10176             : {
   10177          38 :     const std::string domainName(domain->GetName());
   10178          19 :     if (!GetUpdate())
   10179             :     {
   10180           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10181             :                  "AddFieldDomain() not supported on read-only dataset");
   10182           0 :         return false;
   10183             :     }
   10184          19 :     if (GetFieldDomain(domainName) != nullptr)
   10185             :     {
   10186           1 :         failureReason = "A domain of identical name already exists";
   10187           1 :         return false;
   10188             :     }
   10189          18 :     if (!CreateColumnsTableAndColumnConstraintsTablesIfNecessary())
   10190           0 :         return false;
   10191             : 
   10192          18 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
   10193          18 :     const char *min_is_inclusive =
   10194          18 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
   10195          18 :     const char *max_is_inclusive =
   10196          18 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
   10197             : 
   10198          18 :     const auto &osDescription = domain->GetDescription();
   10199          18 :     switch (domain->GetDomainType())
   10200             :     {
   10201          11 :         case OFDT_CODED:
   10202             :         {
   10203             :             const auto poCodedDomain =
   10204          11 :                 cpl::down_cast<const OGRCodedFieldDomain *>(domain.get());
   10205          11 :             if (!osDescription.empty())
   10206             :             {
   10207             :                 // We use a little trick by using a dummy
   10208             :                 // _{domainname}_domain_description enum that has a single
   10209             :                 // entry whose description is the description of the main
   10210             :                 // domain.
   10211           1 :                 char *pszSQL = sqlite3_mprintf(
   10212             :                     "INSERT INTO gpkg_data_column_constraints ("
   10213             :                     "constraint_name, constraint_type, value, "
   10214             :                     "min, %s, max, %s, "
   10215             :                     "description) VALUES ("
   10216             :                     "'_%q_domain_description', 'enum', '', NULL, NULL, NULL, "
   10217             :                     "NULL, %Q)",
   10218             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10219             :                     osDescription.c_str());
   10220           1 :                 CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
   10221           1 :                 sqlite3_free(pszSQL);
   10222             :             }
   10223          11 :             const auto &enumeration = poCodedDomain->GetEnumeration();
   10224          33 :             for (int i = 0; enumeration[i].pszCode != nullptr; ++i)
   10225             :             {
   10226          22 :                 char *pszSQL = sqlite3_mprintf(
   10227             :                     "INSERT INTO gpkg_data_column_constraints ("
   10228             :                     "constraint_name, constraint_type, value, "
   10229             :                     "min, %s, max, %s, "
   10230             :                     "description) VALUES ("
   10231             :                     "'%q', 'enum', '%q', NULL, NULL, NULL, NULL, %Q)",
   10232             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10233          22 :                     enumeration[i].pszCode, enumeration[i].pszValue);
   10234          22 :                 bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10235          22 :                 sqlite3_free(pszSQL);
   10236          22 :                 if (!ok)
   10237           0 :                     return false;
   10238             :             }
   10239          11 :             break;
   10240             :         }
   10241             : 
   10242           6 :         case OFDT_RANGE:
   10243             :         {
   10244             :             const auto poRangeDomain =
   10245           6 :                 cpl::down_cast<const OGRRangeFieldDomain *>(domain.get());
   10246           6 :             const auto eFieldType = poRangeDomain->GetFieldType();
   10247           6 :             if (eFieldType != OFTInteger && eFieldType != OFTInteger64 &&
   10248             :                 eFieldType != OFTReal)
   10249             :             {
   10250             :                 failureReason = "Only range domains of numeric type are "
   10251           0 :                                 "supported in GeoPackage";
   10252           0 :                 return false;
   10253             :             }
   10254             : 
   10255           6 :             double dfMin = -std::numeric_limits<double>::infinity();
   10256           6 :             double dfMax = std::numeric_limits<double>::infinity();
   10257           6 :             bool bMinIsInclusive = true;
   10258           6 :             const auto &sMin = poRangeDomain->GetMin(bMinIsInclusive);
   10259           6 :             bool bMaxIsInclusive = true;
   10260           6 :             const auto &sMax = poRangeDomain->GetMax(bMaxIsInclusive);
   10261           6 :             if (eFieldType == OFTInteger)
   10262             :             {
   10263           2 :                 if (!OGR_RawField_IsUnset(&sMin))
   10264           2 :                     dfMin = sMin.Integer;
   10265           2 :                 if (!OGR_RawField_IsUnset(&sMax))
   10266           2 :                     dfMax = sMax.Integer;
   10267             :             }
   10268           4 :             else if (eFieldType == OFTInteger64)
   10269             :             {
   10270           1 :                 if (!OGR_RawField_IsUnset(&sMin))
   10271           1 :                     dfMin = static_cast<double>(sMin.Integer64);
   10272           1 :                 if (!OGR_RawField_IsUnset(&sMax))
   10273           1 :                     dfMax = static_cast<double>(sMax.Integer64);
   10274             :             }
   10275             :             else /* if( eFieldType == OFTReal ) */
   10276             :             {
   10277           3 :                 if (!OGR_RawField_IsUnset(&sMin))
   10278           3 :                     dfMin = sMin.Real;
   10279           3 :                 if (!OGR_RawField_IsUnset(&sMax))
   10280           3 :                     dfMax = sMax.Real;
   10281             :             }
   10282             : 
   10283           6 :             sqlite3_stmt *hInsertStmt = nullptr;
   10284             :             const char *pszSQL =
   10285           6 :                 CPLSPrintf("INSERT INTO gpkg_data_column_constraints ("
   10286             :                            "constraint_name, constraint_type, value, "
   10287             :                            "min, %s, max, %s, "
   10288             :                            "description) VALUES ("
   10289             :                            "?, 'range', NULL, ?, ?, ?, ?, ?)",
   10290             :                            min_is_inclusive, max_is_inclusive);
   10291           6 :             if (SQLPrepareWithError(hDB, pszSQL, -1, &hInsertStmt, nullptr) !=
   10292             :                 SQLITE_OK)
   10293             :             {
   10294           0 :                 return false;
   10295             :             }
   10296           6 :             sqlite3_bind_text(hInsertStmt, 1, domainName.c_str(),
   10297           6 :                               static_cast<int>(domainName.size()),
   10298             :                               SQLITE_TRANSIENT);
   10299           6 :             sqlite3_bind_double(hInsertStmt, 2, dfMin);
   10300           6 :             sqlite3_bind_int(hInsertStmt, 3, bMinIsInclusive ? 1 : 0);
   10301           6 :             sqlite3_bind_double(hInsertStmt, 4, dfMax);
   10302           6 :             sqlite3_bind_int(hInsertStmt, 5, bMaxIsInclusive ? 1 : 0);
   10303           6 :             if (osDescription.empty())
   10304             :             {
   10305           3 :                 sqlite3_bind_null(hInsertStmt, 6);
   10306             :             }
   10307             :             else
   10308             :             {
   10309           3 :                 sqlite3_bind_text(hInsertStmt, 6, osDescription.c_str(),
   10310           3 :                                   static_cast<int>(osDescription.size()),
   10311             :                                   SQLITE_TRANSIENT);
   10312             :             }
   10313           6 :             const int sqlite_err = sqlite3_step(hInsertStmt);
   10314           6 :             sqlite3_finalize(hInsertStmt);
   10315           6 :             if (sqlite_err != SQLITE_OK && sqlite_err != SQLITE_DONE)
   10316             :             {
   10317           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10318             :                          "failed to execute insertion '%s': %s", pszSQL,
   10319             :                          sqlite3_errmsg(hDB));
   10320           0 :                 return false;
   10321             :             }
   10322             : 
   10323           6 :             break;
   10324             :         }
   10325             : 
   10326           1 :         case OFDT_GLOB:
   10327             :         {
   10328             :             const auto poGlobDomain =
   10329           1 :                 cpl::down_cast<const OGRGlobFieldDomain *>(domain.get());
   10330           2 :             char *pszSQL = sqlite3_mprintf(
   10331             :                 "INSERT INTO gpkg_data_column_constraints ("
   10332             :                 "constraint_name, constraint_type, value, "
   10333             :                 "min, %s, max, %s, "
   10334             :                 "description) VALUES ("
   10335             :                 "'%q', 'glob', '%q', NULL, NULL, NULL, NULL, %Q)",
   10336             :                 min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10337           1 :                 poGlobDomain->GetGlob().c_str(),
   10338           2 :                 osDescription.empty() ? nullptr : osDescription.c_str());
   10339           1 :             bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10340           1 :             sqlite3_free(pszSQL);
   10341           1 :             if (!ok)
   10342           0 :                 return false;
   10343             : 
   10344           1 :             break;
   10345             :         }
   10346             :     }
   10347             : 
   10348          18 :     m_oMapFieldDomains[domainName] = std::move(domain);
   10349          18 :     return true;
   10350             : }
   10351             : 
   10352             : /************************************************************************/
   10353             : /*                         UpdateFieldDomain()                          */
   10354             : /************************************************************************/
   10355             : 
   10356           3 : bool GDALGeoPackageDataset::UpdateFieldDomain(
   10357             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10358             : {
   10359           6 :     const std::string domainName(domain->GetName());
   10360           3 :     if (eAccess != GA_Update)
   10361             :     {
   10362           1 :         CPLError(CE_Failure, CPLE_NotSupported,
   10363             :                  "UpdateFieldDomain() not supported on read-only dataset");
   10364           1 :         return false;
   10365             :     }
   10366             : 
   10367           2 :     if (GetFieldDomain(domainName) == nullptr)
   10368             :     {
   10369           1 :         failureReason = "The domain should already exist to be updated";
   10370           1 :         return false;
   10371             :     }
   10372             : 
   10373           1 :     bool bRet = SoftStartTransaction() == OGRERR_NONE;
   10374           1 :     if (bRet)
   10375             :     {
   10376           2 :         bRet = DeleteFieldDomain(domainName, failureReason) &&
   10377           1 :                AddFieldDomain(std::move(domain), failureReason);
   10378           1 :         if (bRet)
   10379           1 :             bRet = SoftCommitTransaction() == OGRERR_NONE;
   10380             :         else
   10381           0 :             SoftRollbackTransaction();
   10382             :     }
   10383           1 :     return bRet;
   10384             : }
   10385             : 
   10386             : /************************************************************************/
   10387             : /*                         DeleteFieldDomain()                          */
   10388             : /************************************************************************/
   10389             : 
   10390          18 : bool GDALGeoPackageDataset::DeleteFieldDomain(const std::string &name,
   10391             :                                               std::string &failureReason)
   10392             : {
   10393          18 :     if (eAccess != GA_Update)
   10394             :     {
   10395           1 :         CPLError(CE_Failure, CPLE_NotSupported,
   10396             :                  "DeleteFieldDomain() not supported on read-only dataset");
   10397           1 :         return false;
   10398             :     }
   10399          17 :     if (GetFieldDomain(name) == nullptr)
   10400             :     {
   10401           1 :         failureReason = "Domain does not exist";
   10402           1 :         return false;
   10403             :     }
   10404             : 
   10405             :     char *pszSQL =
   10406          16 :         sqlite3_mprintf("DELETE FROM gpkg_data_column_constraints WHERE "
   10407             :                         "constraint_name IN ('%q', '_%q_domain_description')",
   10408             :                         name.c_str(), name.c_str());
   10409          16 :     const bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10410          16 :     sqlite3_free(pszSQL);
   10411          16 :     if (ok)
   10412          16 :         m_oMapFieldDomains.erase(name);
   10413          16 :     return ok;
   10414             : }
   10415             : 
   10416             : /************************************************************************/
   10417             : /*                          AddRelationship()                           */
   10418             : /************************************************************************/
   10419             : 
   10420          26 : bool GDALGeoPackageDataset::AddRelationship(
   10421             :     std::unique_ptr<GDALRelationship> &&relationship,
   10422             :     std::string &failureReason)
   10423             : {
   10424          26 :     if (!GetUpdate())
   10425             :     {
   10426           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10427             :                  "AddRelationship() not supported on read-only dataset");
   10428           0 :         return false;
   10429             :     }
   10430             : 
   10431             :     const std::string osRelationshipName = GenerateNameForRelationship(
   10432          26 :         relationship->GetLeftTableName().c_str(),
   10433          26 :         relationship->GetRightTableName().c_str(),
   10434         104 :         relationship->GetRelatedTableType().c_str());
   10435             :     // sanity checks
   10436          26 :     if (GetRelationship(osRelationshipName) != nullptr)
   10437             :     {
   10438           1 :         failureReason = "A relationship of identical name already exists";
   10439           1 :         return false;
   10440             :     }
   10441             : 
   10442          25 :     if (!ValidateRelationship(relationship.get(), failureReason))
   10443             :     {
   10444          14 :         return false;
   10445             :     }
   10446             : 
   10447          75 :     for (auto &poLayer : m_apoLayers)
   10448             :     {
   10449          64 :         if (poLayer->SyncToDisk() != OGRERR_NONE)
   10450           0 :             return false;
   10451             :     }
   10452             : 
   10453          11 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
   10454             :     {
   10455           0 :         return false;
   10456             :     }
   10457          11 :     if (!CreateRelationsTableIfNecessary())
   10458             :     {
   10459           0 :         failureReason = "Could not create gpkgext_relations table";
   10460           0 :         return false;
   10461             :     }
   10462          11 :     if (SQLGetInteger(GetDB(),
   10463             :                       "SELECT 1 FROM gpkg_extensions WHERE "
   10464             :                       "table_name = 'gpkgext_relations'",
   10465          11 :                       nullptr) != 1)
   10466             :     {
   10467           5 :         if (OGRERR_NONE !=
   10468           5 :             SQLCommand(
   10469             :                 GetDB(),
   10470             :                 "INSERT INTO gpkg_extensions "
   10471             :                 "(table_name,column_name,extension_name,definition,scope) "
   10472             :                 "VALUES ('gpkgext_relations', NULL, 'gpkg_related_tables', "
   10473             :                 "'http://www.geopackage.org/18-000.html', "
   10474             :                 "'read-write')"))
   10475             :         {
   10476             :             failureReason =
   10477           0 :                 "Could not create gpkg_extensions entry for gpkgext_relations";
   10478           0 :             return false;
   10479             :         }
   10480             :     }
   10481             : 
   10482          11 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10483          11 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10484          11 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10485          11 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10486             : 
   10487          22 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10488          11 :     if (osRelatedTableType.empty())
   10489             :     {
   10490           5 :         osRelatedTableType = "features";
   10491             :     }
   10492             : 
   10493             :     // generate mapping table if not set
   10494          22 :     CPLString osMappingTableName = relationship->GetMappingTableName();
   10495          11 :     if (osMappingTableName.empty())
   10496             :     {
   10497           5 :         int nIndex = 1;
   10498           5 :         osMappingTableName = osLeftTableName + "_" + osRightTableName;
   10499           5 :         while (FindLayerIndex(osMappingTableName.c_str()) >= 0)
   10500             :         {
   10501           0 :             nIndex += 1;
   10502             :             osMappingTableName.Printf("%s_%s_%d", osLeftTableName.c_str(),
   10503           0 :                                       osRightTableName.c_str(), nIndex);
   10504             :         }
   10505             : 
   10506             :         // determine whether base/related keys are unique
   10507           5 :         bool bBaseKeyIsUnique = false;
   10508             :         {
   10509             :             const std::set<std::string> uniqueBaseFieldsUC =
   10510             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10511          10 :                                                osLeftTableName.c_str());
   10512          10 :             if (uniqueBaseFieldsUC.find(
   10513           5 :                     CPLString(aosLeftTableFields[0]).toupper()) !=
   10514          10 :                 uniqueBaseFieldsUC.end())
   10515             :             {
   10516           2 :                 bBaseKeyIsUnique = true;
   10517             :             }
   10518             :         }
   10519           5 :         bool bRelatedKeyIsUnique = false;
   10520             :         {
   10521             :             const std::set<std::string> uniqueRelatedFieldsUC =
   10522             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10523          10 :                                                osRightTableName.c_str());
   10524          10 :             if (uniqueRelatedFieldsUC.find(
   10525           5 :                     CPLString(aosRightTableFields[0]).toupper()) !=
   10526          10 :                 uniqueRelatedFieldsUC.end())
   10527             :             {
   10528           2 :                 bRelatedKeyIsUnique = true;
   10529             :             }
   10530             :         }
   10531             : 
   10532             :         // create mapping table
   10533             : 
   10534           5 :         std::string osBaseIdDefinition = "base_id INTEGER";
   10535           5 :         if (bBaseKeyIsUnique)
   10536             :         {
   10537           2 :             char *pszSQL = sqlite3_mprintf(
   10538             :                 " CONSTRAINT 'fk_base_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10539             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10540             :                 "DEFERRED",
   10541             :                 osMappingTableName.c_str(), osLeftTableName.c_str(),
   10542           2 :                 aosLeftTableFields[0].c_str());
   10543           2 :             osBaseIdDefinition += pszSQL;
   10544           2 :             sqlite3_free(pszSQL);
   10545             :         }
   10546             : 
   10547           5 :         std::string osRelatedIdDefinition = "related_id INTEGER";
   10548           5 :         if (bRelatedKeyIsUnique)
   10549             :         {
   10550           2 :             char *pszSQL = sqlite3_mprintf(
   10551             :                 " CONSTRAINT 'fk_related_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10552             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10553             :                 "DEFERRED",
   10554             :                 osMappingTableName.c_str(), osRightTableName.c_str(),
   10555           2 :                 aosRightTableFields[0].c_str());
   10556           2 :             osRelatedIdDefinition += pszSQL;
   10557           2 :             sqlite3_free(pszSQL);
   10558             :         }
   10559             : 
   10560           5 :         char *pszSQL = sqlite3_mprintf("CREATE TABLE \"%w\" ("
   10561             :                                        "id INTEGER PRIMARY KEY AUTOINCREMENT, "
   10562             :                                        "%s, %s);",
   10563             :                                        osMappingTableName.c_str(),
   10564             :                                        osBaseIdDefinition.c_str(),
   10565             :                                        osRelatedIdDefinition.c_str());
   10566           5 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
   10567           5 :         sqlite3_free(pszSQL);
   10568           5 :         if (eErr != OGRERR_NONE)
   10569             :         {
   10570             :             failureReason =
   10571           0 :                 ("Could not create mapping table " + osMappingTableName)
   10572           0 :                     .c_str();
   10573           0 :             return false;
   10574             :         }
   10575             : 
   10576             :         /*
   10577             :          * Strictly speaking we should NOT be inserting the mapping table into gpkg_contents.
   10578             :          * The related tables extension explicitly states that the mapping table should only be
   10579             :          * in the gpkgext_relations table and not in gpkg_contents. (See also discussion at
   10580             :          * https://github.com/opengeospatial/geopackage/issues/679).
   10581             :          *
   10582             :          * However, if we don't insert the mapping table into gpkg_contents then it is no longer
   10583             :          * visible to some clients (eg ESRI software only allows opening tables that are present
   10584             :          * in gpkg_contents). So we'll do this anyway, for maximum compatibility and flexibility.
   10585             :          *
   10586             :          * More related discussion is at https://github.com/OSGeo/gdal/pull/9258
   10587             :          */
   10588           5 :         pszSQL = sqlite3_mprintf(
   10589             :             "INSERT INTO gpkg_contents "
   10590             :             "(table_name,data_type,identifier,description,last_change,srs_id) "
   10591             :             "VALUES "
   10592             :             "('%q','attributes','%q','Mapping table for relationship between "
   10593             :             "%q and %q',%s,0)",
   10594             :             osMappingTableName.c_str(), /*table_name*/
   10595             :             osMappingTableName.c_str(), /*identifier*/
   10596             :             osLeftTableName.c_str(),    /*description left table name*/
   10597             :             osRightTableName.c_str(),   /*description right table name*/
   10598          10 :             GDALGeoPackageDataset::GetCurrentDateEscapedSQL().c_str());
   10599             : 
   10600             :         // Note -- we explicitly ignore failures here, because hey, we aren't really
   10601             :         // supposed to be adding this table to gpkg_contents anyway!
   10602           5 :         (void)SQLCommand(hDB, pszSQL);
   10603           5 :         sqlite3_free(pszSQL);
   10604             : 
   10605           5 :         pszSQL = sqlite3_mprintf(
   10606             :             "CREATE INDEX \"idx_%w_base_id\" ON \"%w\" (base_id);",
   10607             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10608           5 :         eErr = SQLCommand(hDB, pszSQL);
   10609           5 :         sqlite3_free(pszSQL);
   10610           5 :         if (eErr != OGRERR_NONE)
   10611             :         {
   10612           0 :             failureReason = ("Could not create index for " +
   10613           0 :                              osMappingTableName + " (base_id)")
   10614           0 :                                 .c_str();
   10615           0 :             return false;
   10616             :         }
   10617             : 
   10618           5 :         pszSQL = sqlite3_mprintf(
   10619             :             "CREATE INDEX \"idx_%qw_related_id\" ON \"%w\" (related_id);",
   10620             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10621           5 :         eErr = SQLCommand(hDB, pszSQL);
   10622           5 :         sqlite3_free(pszSQL);
   10623           5 :         if (eErr != OGRERR_NONE)
   10624             :         {
   10625           0 :             failureReason = ("Could not create index for " +
   10626           0 :                              osMappingTableName + " (related_id)")
   10627           0 :                                 .c_str();
   10628           0 :             return false;
   10629             :         }
   10630             : 
   10631             :         auto poLayer = std::make_unique<OGRGeoPackageTableLayer>(
   10632          10 :             this, osMappingTableName.c_str());
   10633           5 :         poLayer->SetOpeningParameters(osMappingTableName.c_str(), "table",
   10634             :                                       /* bIsInGpkgContents = */ true,
   10635             :                                       /* bIsSpatial = */ false,
   10636             :                                       /* pszGeomColName =*/nullptr,
   10637             :                                       /* pszGeomType =*/nullptr,
   10638             :                                       /* bHasZ = */ false, /* bHasM = */ false);
   10639           5 :         m_apoLayers.push_back(std::move(poLayer));
   10640             :     }
   10641             :     else
   10642             :     {
   10643             :         // validate mapping table structure
   10644           6 :         if (OGRGeoPackageTableLayer *poLayer =
   10645           6 :                 cpl::down_cast<OGRGeoPackageTableLayer *>(
   10646           6 :                     GetLayerByName(osMappingTableName)))
   10647             :         {
   10648           4 :             if (poLayer->GetLayerDefn()->GetFieldIndex("base_id") < 0)
   10649             :             {
   10650             :                 failureReason =
   10651           2 :                     ("Field base_id must exist in " + osMappingTableName)
   10652           1 :                         .c_str();
   10653           1 :                 return false;
   10654             :             }
   10655           3 :             if (poLayer->GetLayerDefn()->GetFieldIndex("related_id") < 0)
   10656             :             {
   10657             :                 failureReason =
   10658           2 :                     ("Field related_id must exist in " + osMappingTableName)
   10659           1 :                         .c_str();
   10660           1 :                 return false;
   10661             :             }
   10662             :         }
   10663             :         else
   10664             :         {
   10665             :             failureReason =
   10666           2 :                 ("Could not retrieve table " + osMappingTableName).c_str();
   10667           2 :             return false;
   10668             :         }
   10669             :     }
   10670             : 
   10671           7 :     char *pszSQL = sqlite3_mprintf(
   10672             :         "INSERT INTO gpkg_extensions "
   10673             :         "(table_name,column_name,extension_name,definition,scope) "
   10674             :         "VALUES ('%q', NULL, 'gpkg_related_tables', "
   10675             :         "'http://www.geopackage.org/18-000.html', "
   10676             :         "'read-write')",
   10677             :         osMappingTableName.c_str());
   10678           7 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10679           7 :     sqlite3_free(pszSQL);
   10680           7 :     if (eErr != OGRERR_NONE)
   10681             :     {
   10682           0 :         failureReason = ("Could not insert mapping table " +
   10683           0 :                          osMappingTableName + " into gpkg_extensions")
   10684           0 :                             .c_str();
   10685           0 :         return false;
   10686             :     }
   10687             : 
   10688          21 :     pszSQL = sqlite3_mprintf(
   10689             :         "INSERT INTO gpkgext_relations "
   10690             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10691             :         "primary_column,relation_name,mapping_table_name) "
   10692             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10693           7 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10694           7 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10695             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10696           7 :     eErr = SQLCommand(hDB, pszSQL);
   10697           7 :     sqlite3_free(pszSQL);
   10698           7 :     if (eErr != OGRERR_NONE)
   10699             :     {
   10700           0 :         failureReason = "Could not insert relationship into gpkgext_relations";
   10701           0 :         return false;
   10702             :     }
   10703             : 
   10704           7 :     ClearCachedRelationships();
   10705           7 :     LoadRelationships();
   10706           7 :     return true;
   10707             : }
   10708             : 
   10709             : /************************************************************************/
   10710             : /*                         DeleteRelationship()                         */
   10711             : /************************************************************************/
   10712             : 
   10713           4 : bool GDALGeoPackageDataset::DeleteRelationship(const std::string &name,
   10714             :                                                std::string &failureReason)
   10715             : {
   10716           4 :     if (eAccess != GA_Update)
   10717             :     {
   10718           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10719             :                  "DeleteRelationship() not supported on read-only dataset");
   10720           0 :         return false;
   10721             :     }
   10722             : 
   10723             :     // ensure relationships are up to date before we try to remove one
   10724           4 :     ClearCachedRelationships();
   10725           4 :     LoadRelationships();
   10726             : 
   10727           8 :     std::string osMappingTableName;
   10728             :     {
   10729           4 :         const GDALRelationship *poRelationship = GetRelationship(name);
   10730           4 :         if (poRelationship == nullptr)
   10731             :         {
   10732           1 :             failureReason = "Could not find relationship with name " + name;
   10733           1 :             return false;
   10734             :         }
   10735             : 
   10736           3 :         osMappingTableName = poRelationship->GetMappingTableName();
   10737             :     }
   10738             : 
   10739             :     // DeleteLayerCommon will delete existing relationship objects, so we can't
   10740             :     // refer to poRelationship or any of its members previously obtained here
   10741           3 :     if (DeleteLayerCommon(osMappingTableName.c_str()) != OGRERR_NONE)
   10742             :     {
   10743             :         failureReason =
   10744           0 :             "Could not remove mapping layer name " + osMappingTableName;
   10745             : 
   10746             :         // relationships may have been left in an inconsistent state -- reload
   10747             :         // them now
   10748           0 :         ClearCachedRelationships();
   10749           0 :         LoadRelationships();
   10750           0 :         return false;
   10751             :     }
   10752             : 
   10753           3 :     ClearCachedRelationships();
   10754           3 :     LoadRelationships();
   10755           3 :     return true;
   10756             : }
   10757             : 
   10758             : /************************************************************************/
   10759             : /*                         UpdateRelationship()                         */
   10760             : /************************************************************************/
   10761             : 
   10762           6 : bool GDALGeoPackageDataset::UpdateRelationship(
   10763             :     std::unique_ptr<GDALRelationship> &&relationship,
   10764             :     std::string &failureReason)
   10765             : {
   10766           6 :     if (eAccess != GA_Update)
   10767             :     {
   10768           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10769             :                  "UpdateRelationship() not supported on read-only dataset");
   10770           0 :         return false;
   10771             :     }
   10772             : 
   10773             :     // ensure relationships are up to date before we try to update one
   10774           6 :     ClearCachedRelationships();
   10775           6 :     LoadRelationships();
   10776             : 
   10777           6 :     const std::string &osRelationshipName = relationship->GetName();
   10778           6 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10779           6 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10780           6 :     const std::string &osMappingTableName = relationship->GetMappingTableName();
   10781           6 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10782           6 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10783             : 
   10784             :     // sanity checks
   10785             :     {
   10786             :         const GDALRelationship *poExistingRelationship =
   10787           6 :             GetRelationship(osRelationshipName);
   10788           6 :         if (poExistingRelationship == nullptr)
   10789             :         {
   10790             :             failureReason =
   10791           1 :                 "The relationship should already exist to be updated";
   10792           1 :             return false;
   10793             :         }
   10794             : 
   10795           5 :         if (!ValidateRelationship(relationship.get(), failureReason))
   10796             :         {
   10797           2 :             return false;
   10798             :         }
   10799             : 
   10800             :         // we don't permit changes to the participating tables
   10801           3 :         if (osLeftTableName != poExistingRelationship->GetLeftTableName())
   10802             :         {
   10803           0 :             failureReason = ("Cannot change base table from " +
   10804           0 :                              poExistingRelationship->GetLeftTableName() +
   10805           0 :                              " to " + osLeftTableName)
   10806           0 :                                 .c_str();
   10807           0 :             return false;
   10808             :         }
   10809           3 :         if (osRightTableName != poExistingRelationship->GetRightTableName())
   10810             :         {
   10811           0 :             failureReason = ("Cannot change related table from " +
   10812           0 :                              poExistingRelationship->GetRightTableName() +
   10813           0 :                              " to " + osRightTableName)
   10814           0 :                                 .c_str();
   10815           0 :             return false;
   10816             :         }
   10817           3 :         if (osMappingTableName != poExistingRelationship->GetMappingTableName())
   10818             :         {
   10819           0 :             failureReason = ("Cannot change mapping table from " +
   10820           0 :                              poExistingRelationship->GetMappingTableName() +
   10821           0 :                              " to " + osMappingTableName)
   10822           0 :                                 .c_str();
   10823           0 :             return false;
   10824             :         }
   10825             :     }
   10826             : 
   10827           6 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10828           3 :     if (osRelatedTableType.empty())
   10829             :     {
   10830           0 :         osRelatedTableType = "features";
   10831             :     }
   10832             : 
   10833           3 :     char *pszSQL = sqlite3_mprintf(
   10834             :         "DELETE FROM gpkgext_relations WHERE mapping_table_name='%q'",
   10835             :         osMappingTableName.c_str());
   10836           3 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10837           3 :     sqlite3_free(pszSQL);
   10838           3 :     if (eErr != OGRERR_NONE)
   10839             :     {
   10840             :         failureReason =
   10841           0 :             "Could not delete old relationship from gpkgext_relations";
   10842           0 :         return false;
   10843             :     }
   10844             : 
   10845           9 :     pszSQL = sqlite3_mprintf(
   10846             :         "INSERT INTO gpkgext_relations "
   10847             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10848             :         "primary_column,relation_name,mapping_table_name) "
   10849             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10850           3 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10851           3 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10852             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10853           3 :     eErr = SQLCommand(hDB, pszSQL);
   10854           3 :     sqlite3_free(pszSQL);
   10855           3 :     if (eErr != OGRERR_NONE)
   10856             :     {
   10857             :         failureReason =
   10858           0 :             "Could not insert updated relationship into gpkgext_relations";
   10859           0 :         return false;
   10860             :     }
   10861             : 
   10862           3 :     ClearCachedRelationships();
   10863           3 :     LoadRelationships();
   10864           3 :     return true;
   10865             : }
   10866             : 
   10867             : /************************************************************************/
   10868             : /*                       GetSqliteMasterContent()                       */
   10869             : /************************************************************************/
   10870             : 
   10871             : const std::vector<SQLSqliteMasterContent> &
   10872           2 : GDALGeoPackageDataset::GetSqliteMasterContent()
   10873             : {
   10874           2 :     if (m_aoSqliteMasterContent.empty())
   10875             :     {
   10876             :         auto oResultTable =
   10877           2 :             SQLQuery(hDB, "SELECT sql, type, tbl_name FROM sqlite_master");
   10878           1 :         if (oResultTable)
   10879             :         {
   10880          58 :             for (int rowCnt = 0; rowCnt < oResultTable->RowCount(); ++rowCnt)
   10881             :             {
   10882         114 :                 SQLSqliteMasterContent row;
   10883          57 :                 const char *pszSQL = oResultTable->GetValue(0, rowCnt);
   10884          57 :                 row.osSQL = pszSQL ? pszSQL : "";
   10885          57 :                 const char *pszType = oResultTable->GetValue(1, rowCnt);
   10886          57 :                 row.osType = pszType ? pszType : "";
   10887          57 :                 const char *pszTableName = oResultTable->GetValue(2, rowCnt);
   10888          57 :                 row.osTableName = pszTableName ? pszTableName : "";
   10889          57 :                 m_aoSqliteMasterContent.emplace_back(std::move(row));
   10890             :             }
   10891             :         }
   10892             :     }
   10893           2 :     return m_aoSqliteMasterContent;
   10894             : }

Generated by: LCOV version 1.14