LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/gpkg - ogrgeopackagedatasource.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 4122 4596 89.7 %
Date: 2026-05-07 20:04:54 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         582 : GetTilingScheme(const char *pszName)
      83             : {
      84         582 :     if (EQUAL(pszName, "CUSTOM"))
      85         454 :         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        1057 : OGRErr GDALGeoPackageDataset::SetApplicationAndUserVersionId()
     192             : {
     193        1057 :     CPLAssert(hDB != nullptr);
     194             : 
     195        1057 :     const CPLString osPragma(CPLString().Printf("PRAGMA application_id = %u;"
     196             :                                                 "PRAGMA user_version = %u",
     197             :                                                 m_nApplicationId,
     198        2114 :                                                 m_nUserVersion));
     199        2114 :     return SQLCommand(hDB, osPragma.c_str());
     200             : }
     201             : 
     202        2840 : bool GDALGeoPackageDataset::CloseDB()
     203             : {
     204        2840 :     OGRSQLiteUnregisterSQLFunctions(m_pSQLFunctionData);
     205        2840 :     m_pSQLFunctionData = nullptr;
     206        2840 :     return OGRSQLiteBaseDataSource::CloseDB();
     207             : }
     208             : 
     209          11 : bool GDALGeoPackageDataset::ReOpenDB()
     210             : {
     211          11 :     CPLAssert(hDB != nullptr);
     212          11 :     CPLAssert(m_pszFilename != nullptr);
     213             : 
     214          11 :     FinishSpatialite();
     215             : 
     216          11 :     CloseDB();
     217             : 
     218             :     /* And re-open the file */
     219          11 :     return OpenOrCreateDB(SQLITE_OPEN_READWRITE);
     220             : }
     221             : 
     222         971 : static OGRErr GDALGPKGImportFromEPSG(OGRSpatialReference *poSpatialRef,
     223             :                                      int nEPSGCode)
     224             : {
     225         971 :     CPLPushErrorHandler(CPLQuietErrorHandler);
     226         971 :     const OGRErr eErr = poSpatialRef->importFromEPSG(nEPSGCode);
     227         971 :     CPLPopErrorHandler();
     228         971 :     CPLErrorReset();
     229         971 :     return eErr;
     230             : }
     231             : 
     232             : OGRSpatialReferenceRefCountedPtr
     233        1389 : GDALGeoPackageDataset::GetSpatialRef(int iSrsId, bool bFallbackToEPSG,
     234             :                                      bool bEmitErrorIfNotFound)
     235             : {
     236        1389 :     const auto oIter = m_oMapSrsIdToSrs.find(iSrsId);
     237        1389 :     if (oIter != m_oMapSrsIdToSrs.end())
     238             :     {
     239         103 :         return oIter->second;
     240             :     }
     241             : 
     242        1286 :     if (iSrsId == 0 || iSrsId == -1)
     243             :     {
     244         121 :         auto poSpatialRef = OGRSpatialReferenceRefCountedPtr::makeInstance();
     245         121 :         poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     246             : 
     247             :         // See corresponding tests in GDALGeoPackageDataset::GetSrsId
     248         121 :         if (iSrsId == 0)
     249             :         {
     250          31 :             poSpatialRef->SetGeogCS("Undefined geographic SRS", "unknown",
     251             :                                     "unknown", SRS_WGS84_SEMIMAJOR,
     252             :                                     SRS_WGS84_INVFLATTENING);
     253             :         }
     254          90 :         else if (iSrsId == -1)
     255             :         {
     256          90 :             poSpatialRef->SetLocalCS("Undefined Cartesian SRS");
     257          90 :             poSpatialRef->SetLinearUnits(SRS_UL_METER, 1.0);
     258             :         }
     259             : 
     260         242 :         return m_oMapSrsIdToSrs.insert({iSrsId, std::move(poSpatialRef)})
     261         121 :             .first->second;
     262             :     }
     263             : 
     264        2330 :     CPLString oSQL;
     265        1165 :     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        1165 :                 m_bHasDefinition12_063 ? ", definition_12_063" : "",
     270        1165 :                 m_bHasEpochColumn ? ", epoch" : "", iSrsId);
     271             : 
     272        2330 :     auto oResult = SQLQuery(hDB, oSQL.c_str());
     273             : 
     274        1165 :     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        1153 :     const char *pszName = oResult->GetValue(0, 0);
     299        1153 :     if (pszName && EQUAL(pszName, "Undefined SRS"))
     300             :     {
     301         461 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     302         461 :         return nullptr;
     303             :     }
     304         692 :     const char *pszWkt = oResult->GetValue(1, 0);
     305         692 :     if (pszWkt == nullptr)
     306           0 :         return nullptr;
     307         692 :     const char *pszOrganization = oResult->GetValue(2, 0);
     308         692 :     const char *pszOrganizationCoordsysID = oResult->GetValue(3, 0);
     309             :     const char *pszWkt2 =
     310         692 :         m_bHasDefinition12_063 ? oResult->GetValue(4, 0) : nullptr;
     311         692 :     if (pszWkt2 && !EQUAL(pszWkt2, "undefined"))
     312          76 :         pszWkt = pszWkt2;
     313             :     const char *pszCoordinateEpoch =
     314         692 :         m_bHasEpochColumn ? oResult->GetValue(5, 0) : nullptr;
     315             :     const double dfCoordinateEpoch =
     316         692 :         pszCoordinateEpoch ? CPLAtof(pszCoordinateEpoch) : 0.0;
     317             : 
     318        1384 :     auto poSpatialRef = OGRSpatialReferenceRefCountedPtr::makeInstance();
     319         692 :     poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     320             :     // Try to import first from EPSG code, and then from WKT
     321         692 :     if (!(pszOrganization && pszOrganizationCoordsysID &&
     322         692 :           EQUAL(pszOrganization, "EPSG") &&
     323         668 :           (atoi(pszOrganizationCoordsysID) == iSrsId ||
     324           4 :            (dfCoordinateEpoch > 0 && strstr(pszWkt, "DYNAMIC[") == nullptr)) &&
     325         668 :           GDALGPKGImportFromEPSG(poSpatialRef.get(),
     326             :                                  atoi(pszOrganizationCoordsysID)) ==
     327        1384 :               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         692 :     poSpatialRef->StripTOWGS84IfKnownDatumAndAllowed();
     338         692 :     poSpatialRef->SetCoordinateEpoch(dfCoordinateEpoch);
     339        1384 :     return m_oMapSrsIdToSrs.insert({iSrsId, std::move(poSpatialRef)})
     340         692 :         .first->second;
     341             : }
     342             : 
     343         334 : const char *GDALGeoPackageDataset::GetSrsName(const OGRSpatialReference &oSRS)
     344             : {
     345         334 :     const char *pszName = oSRS.GetName();
     346         334 :     if (pszName)
     347         334 :         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        1034 : int GDALGeoPackageDataset::GetSrsId(const OGRSpatialReference *poSRSIn)
     520             : {
     521        1034 :     const char *pszName = poSRSIn ? poSRSIn->GetName() : nullptr;
     522        1521 :     if (!poSRSIn || poSRSIn->IsEmpty() ||
     523         487 :         (pszName && EQUAL(pszName, "Undefined SRS")))
     524             :     {
     525         549 :         OGRErr err = OGRERR_NONE;
     526         549 :         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         549 :         if (err == OGRERR_NONE)
     532          60 :             return nSRSId;
     533             : 
     534             :         // The below WKT definitions are somehow questionable (using a 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         489 :         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         488 :             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         489 :         if (SQLCommand(hDB, pszSQL) == OGRERR_NONE)
     576         489 :             return UNDEFINED_CRS_SRS_ID;
     577             : #undef UNDEFINED_CRS_SRS_ID
     578             : #undef XSTRINGIFY
     579             : #undef STRINGIFY
     580           0 :         return -1;
     581             :     }
     582             : 
     583         970 :     auto poSRS = OGRSpatialReferenceRefCountedPtr::makeClone(poSRSIn);
     584         485 :     if (poSRS->IsGeographic() || poSRS->IsLocal())
     585             :     {
     586             :         // See corresponding tests in GDALGeoPackageDataset::GetSpatialRef
     587         169 :         if (pszName != nullptr && strlen(pszName) > 0)
     588             :         {
     589         169 :             if (EQUAL(pszName, "Undefined geographic SRS"))
     590           2 :                 return 0;
     591             : 
     592         167 :             if (EQUAL(pszName, "Undefined Cartesian SRS"))
     593           1 :                 return -1;
     594             :         }
     595             :     }
     596             : 
     597         482 :     const char *pszAuthorityName = poSRS->GetAuthorityName();
     598             : 
     599         482 :     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         482 :     char *pszSQL = nullptr;
     623         482 :     int nSRSId = DEFAULT_SRID;
     624         482 :     int nAuthorityCode = 0;
     625         482 :     OGRErr err = OGRERR_NONE;
     626         482 :     bool bCanUseAuthorityCode = false;
     627         482 :     const char *const apszIsSameOptions[] = {
     628             :         "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES",
     629             :         "IGNORE_COORDINATE_EPOCH=YES", nullptr};
     630         482 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0)
     631             :     {
     632         454 :         const char *pszAuthorityCode = poSRS->GetAuthorityCode();
     633         454 :         if (pszAuthorityCode)
     634             :         {
     635         454 :             if (CPLGetValueType(pszAuthorityCode) == CPL_VALUE_INTEGER)
     636             :             {
     637         454 :                 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         936 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     652         454 :         poSRSIn->GetCoordinateEpoch() == 0)
     653             :     {
     654             :         pszSQL =
     655         449 :             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         449 :         nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     661         449 :         sqlite3_free(pszSQL);
     662             : 
     663             :         // Got a match? Return it!
     664         449 :         if (OGRERR_NONE == err)
     665             :         {
     666         144 :             auto poRefSRS = GetSpatialRef(nSRSId);
     667             :             bool bOK =
     668         144 :                 (poRefSRS == nullptr ||
     669         145 :                  poSRS->IsSame(poRefSRS.get(), apszIsSameOptions) ||
     670           1 :                  !CPLTestBool(CPLGetConfigOption("OGR_GPKG_CHECK_SRS", "YES")));
     671         144 :             if (bOK)
     672             :             {
     673         143 :                 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         339 :     CPLCharUniquePtr pszWKT1;
     691         339 :     CPLCharUniquePtr pszWKT2_2015;
     692         339 :     CPLCharUniquePtr pszWKT2_2019;
     693         339 :     const char *const apszOptionsWkt1[] = {"FORMAT=WKT1_GDAL", nullptr};
     694         339 :     const char *const apszOptionsWkt2_2015[] = {"FORMAT=WKT2_2015", nullptr};
     695         339 :     const char *const apszOptionsWkt2_2019[] = {"FORMAT=WKT2_2019", nullptr};
     696             : 
     697         678 :     std::string osEpochTest;
     698         339 :     if (poSRSIn->GetCoordinateEpoch() > 0 && m_bHasEpochColumn)
     699             :     {
     700             :         osEpochTest =
     701           3 :             CPLSPrintf(" AND epoch = %.17g", poSRSIn->GetCoordinateEpoch());
     702             :     }
     703             : 
     704         669 :     if (!(poSRS->IsGeographic() && poSRS->GetAxesCount() == 3) &&
     705         330 :         !poSRS->IsDerivedGeographic())
     706             :     {
     707         660 :         CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
     708         330 :         char *pszTmp = nullptr;
     709         330 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt1);
     710         330 :         pszWKT1.reset(pszTmp);
     711         330 :         if (pszWKT1 && pszWKT1.get()[0] == '\0')
     712             :         {
     713           0 :             pszWKT1.reset();
     714             :         }
     715             :     }
     716             :     {
     717         678 :         CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
     718         339 :         char *pszTmp = nullptr;
     719         339 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2015);
     720         339 :         pszWKT2_2015.reset(pszTmp);
     721         339 :         if (pszWKT2_2015 && pszWKT2_2015.get()[0] == '\0')
     722             :         {
     723           0 :             pszWKT2_2015.reset();
     724             :         }
     725             :     }
     726             :     {
     727         339 :         char *pszTmp = nullptr;
     728         339 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2019);
     729         339 :         pszWKT2_2019.reset(pszTmp);
     730         339 :         if (pszWKT2_2019 && pszWKT2_2019.get()[0] == '\0')
     731             :         {
     732           0 :             pszWKT2_2019.reset();
     733             :         }
     734             :     }
     735             : 
     736         339 :     if (!pszWKT1 && !pszWKT2_2015 && !pszWKT2_2019)
     737             :     {
     738           0 :         return DEFAULT_SRID;
     739             :     }
     740             : 
     741         339 :     if (poSRSIn->GetCoordinateEpoch() == 0 || m_bHasEpochColumn)
     742             :     {
     743             :         // Search if there is already an existing entry with this WKT
     744         336 :         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         294 :         else if (pszWKT1)
     767             :         {
     768             :             pszSQL =
     769         291 :                 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         336 :         if (pszSQL)
     778             :         {
     779         333 :             nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     780         333 :             sqlite3_free(pszSQL);
     781         333 :             if (OGRERR_NONE == err)
     782             :             {
     783           5 :                 return nSRSId;
     784             :             }
     785             :         }
     786             :     }
     787             : 
     788         642 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     789         308 :         poSRSIn->GetCoordinateEpoch() == 0)
     790             :     {
     791         304 :         bool bTryToReuseSRSId = true;
     792         304 :         if (EQUAL(pszAuthorityName, "EPSG"))
     793             :         {
     794         606 :             OGRSpatialReference oSRS_EPSG;
     795         303 :             if (GDALGPKGImportFromEPSG(&oSRS_EPSG, nAuthorityCode) ==
     796             :                 OGRERR_NONE)
     797             :             {
     798         304 :                 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         304 :         if (bTryToReuseSRSId)
     816             :         {
     817             :             // No match, but maybe we can use the nAuthorityCode as the nSRSId?
     818         303 :             pszSQL = sqlite3_mprintf(
     819             :                 "SELECT Count(*) FROM gpkg_spatial_ref_sys WHERE "
     820             :                 "srs_id = %d",
     821             :                 nAuthorityCode);
     822             : 
     823             :             // Yep, we can!
     824         303 :             if (SQLGetInteger(hDB, pszSQL, nullptr) == 0)
     825         302 :                 bCanUseAuthorityCode = true;
     826         303 :             sqlite3_free(pszSQL);
     827             :         }
     828             :     }
     829             : 
     830         334 :     bool bConvertGpkgSpatialRefSysToExtensionWkt2 = false;
     831         334 :     bool bForceEpoch = false;
     832         337 :     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         334 :     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         340 :     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         334 :     if (bCanUseAuthorityCode)
     885             :     {
     886         302 :         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         668 :     std::string osEpochColumn;
     898         334 :     std::string osEpochVal;
     899         334 :     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         334 :     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         289 :         if (pszAuthorityName != nullptr && nAuthorityCode > 0)
     943             :         {
     944         548 :             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         274 :                 GetSrsName(*poSRS), nSRSId, pszAuthorityName, nAuthorityCode,
     949         548 :                 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         334 :     CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
     964             : 
     965             :     // Free everything that was allocated.
     966         334 :     sqlite3_free(pszSQL);
     967             : 
     968         334 :     return nSRSId;
     969             : }
     970             : 
     971             : /************************************************************************/
     972             : /*                       ~GDALGeoPackageDataset()                       */
     973             : /************************************************************************/
     974             : 
     975        5658 : GDALGeoPackageDataset::~GDALGeoPackageDataset()
     976             : {
     977        2829 :     GDALGeoPackageDataset::Close();
     978        5658 : }
     979             : 
     980             : /************************************************************************/
     981             : /*                               Close()                                */
     982             : /************************************************************************/
     983             : 
     984        4765 : CPLErr GDALGeoPackageDataset::Close(GDALProgressFunc, void *)
     985             : {
     986        4765 :     CPLErr eErr = CE_None;
     987        4765 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     988             :     {
     989        1659 :         if (eAccess == GA_Update && m_poParentDS == nullptr &&
     990        4488 :             !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        5647 :         if (!IsMarkedSuppressOnClose() &&
     999        2818 :             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        4674 :         for (int i = 0; i < nBands; i++)
    1008        1845 :             delete papoBands[i];
    1009        2829 :         nBands = 0;
    1010        2829 :         CPLFree(papoBands);
    1011        2829 :         papoBands = nullptr;
    1012             : 
    1013             :         // Destroy overviews before cleaning m_hTempDB as they could still
    1014             :         // need it
    1015        2829 :         m_apoOverviewDS.clear();
    1016             : 
    1017        2829 :         if (m_poParentDS)
    1018             :         {
    1019         330 :             hDB = nullptr;
    1020             :         }
    1021             : 
    1022        2829 :         m_apoLayers.clear();
    1023             : 
    1024        2829 :         m_oMapSrsIdToSrs.clear();
    1025             : 
    1026        2829 :         if (!CloseDB())
    1027           0 :             eErr = CE_Failure;
    1028             : 
    1029        2829 :         if (OGRSQLiteBaseDataSource::Close() != CE_None)
    1030           0 :             eErr = CE_Failure;
    1031             :     }
    1032        4765 :     return eErr;
    1033             : }
    1034             : 
    1035             : /************************************************************************/
    1036             : /*                          ICanIWriteBlock()                           */
    1037             : /************************************************************************/
    1038             : 
    1039        5697 : bool GDALGeoPackageDataset::ICanIWriteBlock()
    1040             : {
    1041        5697 :     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        5697 :     if (m_pabyCachedTiles == nullptr)
    1050             :     {
    1051           0 :         return false;
    1052             :     }
    1053             : 
    1054        5697 :     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        5697 :     return true;
    1061             : }
    1062             : 
    1063             : /************************************************************************/
    1064             : /*                             IRasterIO()                              */
    1065             : /************************************************************************/
    1066             : 
    1067         135 : 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         135 :     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         135 :     if (eErr == CE_None && eRWFlag == GF_Write && nXSize == nBufXSize &&
    1083         124 :         nYSize == nBufYSize && nBandCount == nBands &&
    1084         121 :         m_nShiftXPixelsMod == 0 && m_nShiftYPixelsMod == 0)
    1085             :     {
    1086             :         auto poBand =
    1087         117 :             cpl::down_cast<GDALGPKGMBTilesLikeRasterBand *>(GetRasterBand(1));
    1088             :         int nBlockXSize, nBlockYSize;
    1089         117 :         poBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
    1090         117 :         const int nBlockXStart = DIV_ROUND_UP(nXOff, nBlockXSize);
    1091         117 :         const int nBlockYStart = DIV_ROUND_UP(nYOff, nBlockYSize);
    1092         117 :         const int nBlockXEnd = (nXOff + nXSize) / nBlockXSize;
    1093         117 :         const int nBlockYEnd = (nYOff + nYSize) / nBlockYSize;
    1094         271 :         for (int nBlockY = nBlockXStart; nBlockY < nBlockYEnd; nBlockY++)
    1095             :         {
    1096        4371 :             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         135 :     return eErr;
    1120             : }
    1121             : 
    1122             : /************************************************************************/
    1123             : /*                          GetOGRTableLimit()                          */
    1124             : /************************************************************************/
    1125             : 
    1126        4625 : static int GetOGRTableLimit()
    1127             : {
    1128        4625 :     return atoi(CPLGetConfigOption("OGR_TABLE_LIMIT", "10000"));
    1129             : }
    1130             : 
    1131             : /************************************************************************/
    1132             : /*                   GetNameTypeMapFromSQliteMaster()                   */
    1133             : /************************************************************************/
    1134             : 
    1135             : const std::map<CPLString, CPLString> &
    1136        1446 : GDALGeoPackageDataset::GetNameTypeMapFromSQliteMaster()
    1137             : {
    1138        1446 :     if (!m_oMapNameToType.empty())
    1139         391 :         return m_oMapNameToType;
    1140             : 
    1141             :     CPLString osSQL(
    1142             :         "SELECT name, type FROM sqlite_master WHERE "
    1143             :         "type IN ('view', 'table') OR "
    1144        2110 :         "(name LIKE 'trigger_%_feature_count_%' AND type = 'trigger')");
    1145        1055 :     const int nTableLimit = GetOGRTableLimit();
    1146        1055 :     if (nTableLimit > 0)
    1147             :     {
    1148        1055 :         osSQL += " LIMIT ";
    1149        1055 :         osSQL += CPLSPrintf("%d", 1 + 3 * nTableLimit);
    1150             :     }
    1151             : 
    1152        1055 :     auto oResult = SQLQuery(hDB, osSQL);
    1153        1055 :     if (oResult)
    1154             :     {
    1155       17633 :         for (int i = 0; i < oResult->RowCount(); i++)
    1156             :         {
    1157       16578 :             const char *pszName = oResult->GetValue(0, i);
    1158       16578 :             const char *pszType = oResult->GetValue(1, i);
    1159       16578 :             m_oMapNameToType[CPLString(pszName).toupper()] = pszType;
    1160             :         }
    1161             :     }
    1162             : 
    1163        1055 :     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        1003 : GDALGeoPackageDataset::GetUnknownExtensionsTableSpecific()
    1182             : {
    1183        1003 :     if (m_bMapTableToExtensionsBuilt)
    1184         107 :         return m_oMapTableToExtensions;
    1185         896 :     m_bMapTableToExtensionsBuilt = true;
    1186             : 
    1187         896 :     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        1688 :         ")");
    1210         844 :     const int nTableLimit = GetOGRTableLimit();
    1211         844 :     if (nTableLimit > 0)
    1212             :     {
    1213         844 :         osSQL += " LIMIT ";
    1214         844 :         osSQL += CPLSPrintf("%d", 1 + 10 * nTableLimit);
    1215             :     }
    1216             : 
    1217         844 :     auto oResult = SQLQuery(hDB, osSQL);
    1218         844 :     if (oResult)
    1219             :     {
    1220        1561 :         for (int i = 0; i < oResult->RowCount(); i++)
    1221             :         {
    1222         717 :             const char *pszTableName = oResult->GetValue(0, i);
    1223         717 :             const char *pszExtensionName = oResult->GetValue(1, i);
    1224         717 :             const char *pszDefinition = oResult->GetValue(2, i);
    1225         717 :             const char *pszScope = oResult->GetValue(3, i);
    1226         717 :             if (pszTableName && pszExtensionName && pszDefinition && pszScope)
    1227             :             {
    1228         717 :                 GPKGExtensionDesc oDesc;
    1229         717 :                 oDesc.osExtensionName = pszExtensionName;
    1230         717 :                 oDesc.osDefinition = pszDefinition;
    1231         717 :                 oDesc.osScope = pszScope;
    1232        1434 :                 m_oMapTableToExtensions[CPLString(pszTableName).toupper()]
    1233         717 :                     .push_back(std::move(oDesc));
    1234             :             }
    1235             :         }
    1236             :     }
    1237             : 
    1238         844 :     return m_oMapTableToExtensions;
    1239             : }
    1240             : 
    1241             : /************************************************************************/
    1242             : /*                            GetContents()                             */
    1243             : /************************************************************************/
    1244             : 
    1245             : const std::map<CPLString, GPKGContentsDesc> &
    1246         984 : GDALGeoPackageDataset::GetContents()
    1247             : {
    1248         984 :     if (m_bMapTableToContentsBuilt)
    1249          90 :         return m_oMapTableToContents;
    1250         894 :     m_bMapTableToContentsBuilt = true;
    1251             : 
    1252             :     CPLString osSQL("SELECT table_name, data_type, identifier, "
    1253             :                     "description, min_x, min_y, max_x, max_y "
    1254        1788 :                     "FROM gpkg_contents");
    1255         894 :     const int nTableLimit = GetOGRTableLimit();
    1256         894 :     if (nTableLimit > 0)
    1257             :     {
    1258         894 :         osSQL += " LIMIT ";
    1259         894 :         osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1260             :     }
    1261             : 
    1262         894 :     auto oResult = SQLQuery(hDB, osSQL);
    1263         894 :     if (oResult)
    1264             :     {
    1265        1935 :         for (int i = 0; i < oResult->RowCount(); i++)
    1266             :         {
    1267        1041 :             const char *pszTableName = oResult->GetValue(0, i);
    1268        1041 :             if (pszTableName == nullptr)
    1269           0 :                 continue;
    1270        1041 :             const char *pszDataType = oResult->GetValue(1, i);
    1271        1041 :             const char *pszIdentifier = oResult->GetValue(2, i);
    1272        1041 :             const char *pszDescription = oResult->GetValue(3, i);
    1273        1041 :             const char *pszMinX = oResult->GetValue(4, i);
    1274        1041 :             const char *pszMinY = oResult->GetValue(5, i);
    1275        1041 :             const char *pszMaxX = oResult->GetValue(6, i);
    1276        1041 :             const char *pszMaxY = oResult->GetValue(7, i);
    1277        1041 :             GPKGContentsDesc oDesc;
    1278        1041 :             if (pszDataType)
    1279        1041 :                 oDesc.osDataType = pszDataType;
    1280        1041 :             if (pszIdentifier)
    1281        1041 :                 oDesc.osIdentifier = pszIdentifier;
    1282        1041 :             if (pszDescription)
    1283        1040 :                 oDesc.osDescription = pszDescription;
    1284        1041 :             if (pszMinX)
    1285         699 :                 oDesc.osMinX = pszMinX;
    1286        1041 :             if (pszMinY)
    1287         699 :                 oDesc.osMinY = pszMinY;
    1288        1041 :             if (pszMaxX)
    1289         699 :                 oDesc.osMaxX = pszMaxX;
    1290        1041 :             if (pszMaxY)
    1291         699 :                 oDesc.osMaxY = pszMaxY;
    1292        2082 :             m_oMapTableToContents[CPLString(pszTableName).toupper()] =
    1293        2082 :                 std::move(oDesc);
    1294             :         }
    1295             :     }
    1296             : 
    1297         894 :     return m_oMapTableToContents;
    1298             : }
    1299             : 
    1300             : /************************************************************************/
    1301             : /*                                Open()                                */
    1302             : /************************************************************************/
    1303             : 
    1304        1414 : int GDALGeoPackageDataset::Open(GDALOpenInfo *poOpenInfo,
    1305             :                                 const std::string &osFilenameInZip)
    1306             : {
    1307        1414 :     m_osFilenameInZip = osFilenameInZip;
    1308        1414 :     CPLAssert(m_apoLayers.empty());
    1309        1414 :     CPLAssert(hDB == nullptr);
    1310             : 
    1311        1414 :     SetDescription(poOpenInfo->pszFilename);
    1312        2828 :     CPLString osFilename(poOpenInfo->pszFilename);
    1313        2828 :     CPLString osSubdatasetTableName;
    1314             :     GByte abyHeaderLetMeHerePlease[100];
    1315        1414 :     const GByte *pabyHeader = poOpenInfo->pabyHeader;
    1316        1414 :     if (STARTS_WITH_CI(poOpenInfo->pszFilename, "GPKG:"))
    1317             :     {
    1318         270 :         char **papszTokens = CSLTokenizeString2(poOpenInfo->pszFilename, ":",
    1319             :                                                 CSLT_HONOURSTRINGS);
    1320         270 :         int nCount = CSLCount(papszTokens);
    1321         270 :         if (nCount < 2)
    1322             :         {
    1323           0 :             CSLDestroy(papszTokens);
    1324           0 :             return FALSE;
    1325             :         }
    1326             : 
    1327         270 :         if (nCount <= 3)
    1328             :         {
    1329         268 :             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         270 :         if (nCount >= 3)
    1350          14 :             osSubdatasetTableName = papszTokens[nCount - 1];
    1351             : 
    1352         270 :         CSLDestroy(papszTokens);
    1353         270 :         VSILFILE *fp = VSIFOpenL(osFilename, "rb");
    1354         270 :         if (fp != nullptr)
    1355             :         {
    1356         270 :             VSIFReadL(abyHeaderLetMeHerePlease, 1, 100, fp);
    1357         270 :             VSIFCloseL(fp);
    1358             :         }
    1359         270 :         pabyHeader = abyHeaderLetMeHerePlease;
    1360             :     }
    1361        1144 :     else if (poOpenInfo->pabyHeader &&
    1362        1144 :              STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1363             :                          "SQLite format 3"))
    1364             :     {
    1365        1137 :         m_bCallUndeclareFileNotToOpen = true;
    1366        1137 :         GDALOpenInfoDeclareFileNotToOpen(osFilename, poOpenInfo->pabyHeader,
    1367             :                                          poOpenInfo->nHeaderBytes);
    1368             :     }
    1369             : 
    1370        1414 :     eAccess = poOpenInfo->eAccess;
    1371        1414 :     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        1412 :         m_pszFilename = CPLStrdup(osFilename);
    1379             :     }
    1380             : 
    1381        1414 :     if (poOpenInfo->papszOpenOptions)
    1382             :     {
    1383         100 :         CSLDestroy(papszOpenOptions);
    1384         100 :         papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
    1385             :     }
    1386             : 
    1387             : #ifdef ENABLE_SQL_GPKG_FORMAT
    1388        1414 :     if (poOpenInfo->pabyHeader &&
    1389        1144 :         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        1409 :     else if (pabyHeader != nullptr)
    1424             : #endif
    1425             :     {
    1426        1409 :         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        1020 :             VSIFCloseL(poOpenInfo->fpL);
    1431        1020 :             poOpenInfo->fpL = nullptr;
    1432             :         }
    1433             : 
    1434             :         /* See if we can open the SQLite database */
    1435        1409 :         if (!OpenOrCreateDB(GetUpdate() ? SQLITE_OPEN_READWRITE
    1436             :                                         : SQLITE_OPEN_READONLY))
    1437           3 :             return FALSE;
    1438             : 
    1439        1406 :         memcpy(&m_nApplicationId, pabyHeader + knApplicationIdPos, 4);
    1440        1406 :         m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    1441        1406 :         memcpy(&m_nUserVersion, pabyHeader + knUserVersionPos, 4);
    1442        1406 :         m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    1443        1406 :         if (m_nApplicationId == GP10_APPLICATION_ID)
    1444             :         {
    1445           9 :             CPLDebug("GPKG", "GeoPackage v1.0");
    1446             :         }
    1447        1397 :         else if (m_nApplicationId == GP11_APPLICATION_ID)
    1448             :         {
    1449           2 :             CPLDebug("GPKG", "GeoPackage v1.1");
    1450             :         }
    1451        1395 :         else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    1452        1391 :                  m_nUserVersion >= GPKG_1_2_VERSION)
    1453             :         {
    1454        1389 :             CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    1455        1389 :                      (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        1411 :     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        1411 :     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        1411 :     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        1411 :                       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        1411 :     DetectSpatialRefSysColumns();
    1500             : 
    1501             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    1502        1411 :     if (SQLGetInteger(hDB,
    1503             :                       "SELECT 1 FROM sqlite_master WHERE "
    1504             :                       "name = 'gpkg_ogr_contents' AND type = 'table'",
    1505        1411 :                       nullptr) == 1)
    1506             :     {
    1507        1400 :         m_bHasGPKGOGRContents = true;
    1508             :     }
    1509             : #endif
    1510             : 
    1511        1411 :     CheckUnknownExtensions();
    1512             : 
    1513        1411 :     int bRet = FALSE;
    1514        1411 :     bool bHasGPKGExtRelations = false;
    1515        1411 :     if (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR)
    1516             :     {
    1517        1219 :         m_bHasGPKGGeometryColumns =
    1518        1219 :             SQLGetInteger(hDB,
    1519             :                           "SELECT 1 FROM sqlite_master WHERE "
    1520             :                           "name = 'gpkg_geometry_columns' AND "
    1521             :                           "type IN ('table', 'view')",
    1522        1219 :                           nullptr) == 1;
    1523        1219 :         bHasGPKGExtRelations = HasGpkgextRelationsTable();
    1524             :     }
    1525        1411 :     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        1217 :             "  WHERE data_type IN ('aspatial', 'attributes') ";
    1551             : 
    1552        2434 :         const char *pszListAllTables = CSLFetchNameValueDef(
    1553        1217 :             poOpenInfo->papszOpenOptions, "LIST_ALL_TABLES", "AUTO");
    1554        1217 :         bool bHasASpatialOrAttributes = HasGDALAspatialExtension();
    1555        1217 :         if (!bHasASpatialOrAttributes)
    1556             :         {
    1557             :             auto oResultTable =
    1558             :                 SQLQuery(hDB, "SELECT * FROM gpkg_contents WHERE "
    1559        1216 :                               "data_type = 'attributes' LIMIT 1");
    1560        1216 :             bHasASpatialOrAttributes =
    1561        1216 :                 (oResultTable && oResultTable->RowCount() == 1);
    1562             :         }
    1563        1217 :         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        1217 :         if (EQUAL(pszListAllTables, "YES") ||
    1578        1216 :             (!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        1147 :                 "gpkg_contents)";
    1595        1147 :             if (bHasGPKGExtRelations)
    1596             :             {
    1597             :                 osSQL += " AND lower(name) NOT IN (SELECT "
    1598             :                          "lower(mapping_table_name) FROM "
    1599          15 :                          "gpkgext_relations)";
    1600             :             }
    1601             :         }
    1602        1217 :         const int nTableLimit = GetOGRTableLimit();
    1603        1217 :         if (nTableLimit > 0)
    1604             :         {
    1605        1217 :             osSQL += " LIMIT ";
    1606        1217 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1607             :         }
    1608             : 
    1609        1217 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1610        1217 :         if (!oResult)
    1611             :         {
    1612           0 :             return FALSE;
    1613             :         }
    1614             : 
    1615        1217 :         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        1217 :         if (oResult->RowCount() > 0)
    1626             :         {
    1627        1100 :             bRet = TRUE;
    1628             : 
    1629        1100 :             m_apoLayers.reserve(oResult->RowCount());
    1630             : 
    1631        2200 :             std::map<std::string, int> oMapTableRefCount;
    1632        4428 :             for (int i = 0; i < oResult->RowCount(); i++)
    1633             :             {
    1634        3328 :                 const char *pszTableName = oResult->GetValue(0, i);
    1635        3328 :                 if (pszTableName == nullptr)
    1636           0 :                     continue;
    1637        3328 :                 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        2200 :             std::set<std::string> oExistingLayers;
    1649        4428 :             for (int i = 0; i < oResult->RowCount(); i++)
    1650             :             {
    1651        3328 :                 const char *pszTableName = oResult->GetValue(0, i);
    1652        3328 :                 if (pszTableName == nullptr)
    1653           2 :                     continue;
    1654             :                 const bool bTableHasSeveralGeomColumns =
    1655        3328 :                     oMapTableRefCount[pszTableName] > 1;
    1656        3328 :                 bool bIsSpatial = CPL_TO_BOOL(oResult->GetValueAsInteger(2, i));
    1657        3328 :                 const char *pszGeomColName = oResult->GetValue(3, i);
    1658        3328 :                 const char *pszGeomType = oResult->GetValue(4, i);
    1659        3328 :                 const char *pszZ = oResult->GetValue(5, i);
    1660        3328 :                 const char *pszM = oResult->GetValue(6, i);
    1661             :                 bool bIsInGpkgContents =
    1662        3328 :                     CPL_TO_BOOL(oResult->GetValueAsInteger(11, i));
    1663        3328 :                 if (!bIsInGpkgContents)
    1664          46 :                     m_bNonSpatialTablesNonRegisteredInGpkgContentsFound = true;
    1665        3328 :                 const char *pszObjectType = oResult->GetValue(12, i);
    1666        3328 :                 if (pszObjectType == nullptr ||
    1667        3327 :                     !(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        6948 :                     pszGeomColName ? std::string(pszTableName) + " (" +
    1684             :                                          pszGeomColName + ')'
    1685        6654 :                                    : std::string(pszTableName);
    1686        3327 :                 if (cpl::contains(oExistingLayers, osLayerNameWithGeomColName))
    1687           1 :                     continue;
    1688        3326 :                 oExistingLayers.insert(osLayerNameWithGeomColName);
    1689             :                 const std::string osLayerName =
    1690             :                     bTableHasSeveralGeomColumns
    1691           3 :                         ? std::move(osLayerNameWithGeomColName)
    1692        6655 :                         : std::string(pszTableName);
    1693             :                 auto poLayer = std::make_unique<OGRGeoPackageTableLayer>(
    1694        6652 :                     this, osLayerName.c_str());
    1695        3326 :                 bool bHasZ = pszZ && atoi(pszZ) > 0;
    1696        3326 :                 bool bHasM = pszM && atoi(pszM) > 0;
    1697        3326 :                 if (pszGeomType && EQUAL(pszGeomType, "GEOMETRY"))
    1698             :                 {
    1699         676 :                     if (pszZ && atoi(pszZ) == 2)
    1700          14 :                         bHasZ = false;
    1701         676 :                     if (pszM && atoi(pszM) == 2)
    1702           6 :                         bHasM = false;
    1703             :                 }
    1704        3326 :                 poLayer->SetOpeningParameters(
    1705             :                     pszTableName, pszObjectType, bIsInGpkgContents, bIsSpatial,
    1706             :                     pszGeomColName, pszGeomType, bHasZ, bHasM);
    1707        3326 :                 m_apoLayers.push_back(std::move(poLayer));
    1708             :             }
    1709             :         }
    1710             :     }
    1711             : 
    1712        1411 :     bool bHasTileMatrixSet = false;
    1713        1411 :     if (poOpenInfo->nOpenFlags & GDAL_OF_RASTER)
    1714             :     {
    1715         618 :         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        1411 :     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         615 :             "data_type IN ('tiles', '2d-gridded-coverage')";
    1730         615 :         if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE"))
    1731             :             osSubdatasetTableName =
    1732           2 :                 CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE");
    1733         615 :         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         615 :         const int nTableLimit = GetOGRTableLimit();
    1742         615 :         if (nTableLimit > 0)
    1743             :         {
    1744         615 :             osSQL += " LIMIT ";
    1745         615 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1746             :         }
    1747             : 
    1748         615 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1749         615 :         if (!oResult)
    1750             :         {
    1751           0 :             return FALSE;
    1752             :         }
    1753             : 
    1754         615 :         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         614 :         else if (oResult->RowCount() == 1)
    1761             :         {
    1762         284 :             const char *pszTableName = oResult->GetValue(0, 0);
    1763         284 :             const char *pszIdentifier = oResult->GetValue(1, 0);
    1764         284 :             const char *pszDescription = oResult->GetValue(2, 0);
    1765         284 :             const char *pszSRSId = oResult->GetValue(3, 0);
    1766         284 :             const char *pszMinX = oResult->GetValue(4, 0);
    1767         284 :             const char *pszMinY = oResult->GetValue(5, 0);
    1768         284 :             const char *pszMaxX = oResult->GetValue(6, 0);
    1769         284 :             const char *pszMaxY = oResult->GetValue(7, 0);
    1770         284 :             const char *pszTMSMinX = oResult->GetValue(8, 0);
    1771         284 :             const char *pszTMSMinY = oResult->GetValue(9, 0);
    1772         284 :             const char *pszTMSMaxX = oResult->GetValue(10, 0);
    1773         284 :             const char *pszTMSMaxY = oResult->GetValue(11, 0);
    1774         284 :             const char *pszDataType = oResult->GetValue(12, 0);
    1775         284 :             if (pszTableName && pszTMSMinX && pszTMSMinY && pszTMSMaxX &&
    1776             :                 pszTMSMaxY)
    1777             :             {
    1778         568 :                 bRet = OpenRaster(
    1779             :                     pszTableName, pszIdentifier, pszDescription,
    1780         284 :                     pszSRSId ? atoi(pszSRSId) : 0, CPLAtof(pszTMSMinX),
    1781             :                     CPLAtof(pszTMSMinY), CPLAtof(pszTMSMaxX),
    1782             :                     CPLAtof(pszTMSMaxY), pszMinX, pszMinY, pszMaxX, pszMaxY,
    1783         284 :                     EQUAL(pszDataType, "tiles"), poOpenInfo->papszOpenOptions);
    1784             :             }
    1785             :         }
    1786         330 :         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        1411 :     if (!bRet && (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR))
    1821             :     {
    1822          34 :         if ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE))
    1823             :         {
    1824          23 :             bRet = TRUE;
    1825             :         }
    1826             :         else
    1827             :         {
    1828          11 :             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        1411 :     if (eAccess == GA_Update)
    1836             :     {
    1837         285 :         FixupWrongRTreeTrigger();
    1838         285 :         FixupWrongMedataReferenceColumnNameUpdate();
    1839             :     }
    1840             : 
    1841        1411 :     SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    1842             : 
    1843        1411 :     return bRet;
    1844             : }
    1845             : 
    1846             : /************************************************************************/
    1847             : /*                     DetectSpatialRefSysColumns()                     */
    1848             : /************************************************************************/
    1849             : 
    1850        1421 : void GDALGeoPackageDataset::DetectSpatialRefSysColumns()
    1851             : {
    1852             :     // Detect definition_12_063 column
    1853             :     {
    1854        1421 :         sqlite3_stmt *hSQLStmt = nullptr;
    1855        1421 :         int rc = sqlite3_prepare_v2(
    1856             :             hDB, "SELECT definition_12_063 FROM gpkg_spatial_ref_sys ", -1,
    1857             :             &hSQLStmt, nullptr);
    1858        1421 :         if (rc == SQLITE_OK)
    1859             :         {
    1860          85 :             m_bHasDefinition12_063 = true;
    1861          85 :             sqlite3_finalize(hSQLStmt);
    1862             :         }
    1863             :     }
    1864             : 
    1865             :     // Detect epoch column
    1866        1421 :     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        1421 : }
    1879             : 
    1880             : /************************************************************************/
    1881             : /*                       FixupWrongRTreeTrigger()                       */
    1882             : /************************************************************************/
    1883             : 
    1884         285 : void GDALGeoPackageDataset::FixupWrongRTreeTrigger()
    1885             : {
    1886             :     auto oResult = SQLQuery(
    1887             :         hDB,
    1888             :         "SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND "
    1889         285 :         "NAME LIKE 'rtree_%_update3' AND sql LIKE '% AFTER UPDATE OF % ON %'");
    1890         285 :     if (oResult == nullptr)
    1891           0 :         return;
    1892         285 :     if (oResult->RowCount() > 0)
    1893             :     {
    1894           1 :         CPLDebug("GPKG", "Fixing incorrect trigger(s) related to RTree");
    1895             :     }
    1896         287 :     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           9 :                 while (*pszPtr != '\0' && *pszPtr != chStringDelim)
    1912             :                 {
    1913           8 :                     if (*pszPtr == '\\' && pszPtr[1] == chStringDelim)
    1914           0 :                         pszPtr += 2;
    1915             :                     else
    1916           8 :                         pszPtr += 1;
    1917             :                 }
    1918           1 :                 if (*pszPtr == chStringDelim)
    1919           1 :                     pszPtr++;
    1920             :             }
    1921             :             else
    1922             :             {
    1923           1 :                 pszPtr++;
    1924           8 :                 while (*pszPtr != ' ')
    1925           7 :                     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         285 : 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         285 :              "sql LIKE '%column_nameIS%'");
    1954         285 :     if (oResult == nullptr)
    1955           0 :         return;
    1956         285 :     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          99 : void GDALGeoPackageDataset::LoadRelationships() const
    1985             : {
    1986          99 :     m_osMapRelationships.clear();
    1987             : 
    1988          99 :     std::vector<std::string> oExcludedTables;
    1989          99 :     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          99 :     LoadRelationshipsFromForeignKeys(oExcludedTables);
    2004          99 :     m_bHasPopulatedRelationships = true;
    2005          99 : }
    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         368 : 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         368 :     m_osRasterTable = pszTableName;
    2274         368 :     m_dfTMSMinX = dfMinX;
    2275         368 :     m_dfTMSMaxY = dfMaxY;
    2276             : 
    2277             :     // Despite prior checking, the type might be Binary and
    2278             :     // SQLResultGetValue() not working properly on it
    2279         368 :     int nZoomLevel = atoi(oResult.GetValue(0, nIdxInResult));
    2280         368 :     if (nZoomLevel < 0 || nZoomLevel > 65536)
    2281             :     {
    2282           0 :         return false;
    2283             :     }
    2284         368 :     double dfPixelXSize = CPLAtof(oResult.GetValue(1, nIdxInResult));
    2285         368 :     double dfPixelYSize = CPLAtof(oResult.GetValue(2, nIdxInResult));
    2286         368 :     if (dfPixelXSize <= 0 || dfPixelYSize <= 0)
    2287             :     {
    2288           0 :         return false;
    2289             :     }
    2290         368 :     int nTileWidth = atoi(oResult.GetValue(3, nIdxInResult));
    2291         368 :     int nTileHeight = atoi(oResult.GetValue(4, nIdxInResult));
    2292         368 :     if (nTileWidth <= 0 || nTileWidth > 65536 || nTileHeight <= 0 ||
    2293             :         nTileHeight > 65536)
    2294             :     {
    2295           0 :         return false;
    2296             :     }
    2297             :     int nTileMatrixWidth = static_cast<int>(
    2298         736 :         std::min(static_cast<GIntBig>(INT_MAX),
    2299         368 :                  CPLAtoGIntBig(oResult.GetValue(5, nIdxInResult))));
    2300             :     int nTileMatrixHeight = static_cast<int>(
    2301         736 :         std::min(static_cast<GIntBig>(INT_MAX),
    2302         368 :                  CPLAtoGIntBig(oResult.GetValue(6, nIdxInResult))));
    2303         368 :     if (nTileMatrixWidth <= 0 || nTileMatrixHeight <= 0)
    2304             :     {
    2305           0 :         return false;
    2306             :     }
    2307             : 
    2308             :     /* Use content bounds in priority over tile_matrix_set bounds */
    2309         368 :     double dfGDALMinX = dfMinX;
    2310         368 :     double dfGDALMinY = dfMinY;
    2311         368 :     double dfGDALMaxX = dfMaxX;
    2312         368 :     double dfGDALMaxY = dfMaxY;
    2313             :     pszContentsMinX =
    2314         368 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINX", pszContentsMinX);
    2315             :     pszContentsMinY =
    2316         368 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINY", pszContentsMinY);
    2317             :     pszContentsMaxX =
    2318         368 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXX", pszContentsMaxX);
    2319             :     pszContentsMaxY =
    2320         368 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXY", pszContentsMaxY);
    2321         368 :     if (pszContentsMinX != nullptr && pszContentsMinY != nullptr &&
    2322         368 :         pszContentsMaxX != nullptr && pszContentsMaxY != nullptr)
    2323             :     {
    2324         735 :         if (CPLAtof(pszContentsMinX) < CPLAtof(pszContentsMaxX) &&
    2325         367 :             CPLAtof(pszContentsMinY) < CPLAtof(pszContentsMaxY))
    2326             :         {
    2327         367 :             dfGDALMinX = CPLAtof(pszContentsMinX);
    2328         367 :             dfGDALMinY = CPLAtof(pszContentsMinY);
    2329         367 :             dfGDALMaxX = CPLAtof(pszContentsMaxX);
    2330         367 :             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         368 :     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         368 :     int nBandCount = 0;
    2349             :     const char *pszBAND_COUNT =
    2350         368 :         CSLFetchNameValue(papszOpenOptionsIn, "BAND_COUNT");
    2351         368 :     if (poParentDS)
    2352             :     {
    2353          86 :         nBandCount = poParentDS->GetRasterCount();
    2354             :     }
    2355         282 :     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         217 :         if (pszBAND_COUNT != nullptr && !EQUAL(pszBAND_COUNT, "AUTO"))
    2368             :         {
    2369          69 :             nBandCount = atoi(pszBAND_COUNT);
    2370          69 :             if (nBandCount == 1)
    2371           5 :                 GetMetadata("IMAGE_STRUCTURE");
    2372             :         }
    2373             :         else
    2374             :         {
    2375         148 :             GetMetadata("IMAGE_STRUCTURE");
    2376         148 :             nBandCount = m_nBandCountFromMetadata;
    2377         148 :             if (nBandCount == 1)
    2378          46 :                 m_eTF = GPKG_TF_PNG;
    2379             :         }
    2380         217 :         if (nBandCount == 1 && !m_osTFFromMetadata.empty())
    2381             :         {
    2382           2 :             m_eTF = GDALGPKGMBTilesGetTileFormat(m_osTFFromMetadata.c_str());
    2383             :         }
    2384         217 :         if (nBandCount <= 0 || nBandCount > 4)
    2385          88 :             nBandCount = 4;
    2386             :     }
    2387             : 
    2388         368 :     return InitRaster(poParentDS, pszTableName, nZoomLevel, nBandCount, dfMinX,
    2389             :                       dfMaxY, dfPixelXSize, dfPixelYSize, nTileWidth,
    2390             :                       nTileHeight, nTileMatrixWidth, nTileMatrixHeight,
    2391         368 :                       dfGDALMinX, dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    2392             : }
    2393             : 
    2394             : /************************************************************************/
    2395             : /*                     ComputeTileAndPixelShifts()                      */
    2396             : /************************************************************************/
    2397             : 
    2398         803 : bool GDALGeoPackageDataset::ComputeTileAndPixelShifts()
    2399             : {
    2400             :     int nTileWidth, nTileHeight;
    2401         803 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2402             : 
    2403             :     // Compute shift between GDAL origin and TileMatrixSet origin
    2404         803 :     const double dfShiftXPixels = (m_gt[0] - m_dfTMSMinX) / m_gt[1];
    2405         803 :     if (!(dfShiftXPixels / nTileWidth >= INT_MIN &&
    2406         800 :           dfShiftXPixels / nTileWidth < INT_MAX))
    2407             :     {
    2408           3 :         return false;
    2409             :     }
    2410         800 :     const int64_t nShiftXPixels =
    2411         800 :         static_cast<int64_t>(floor(0.5 + dfShiftXPixels));
    2412         800 :     m_nShiftXTiles = static_cast<int>(nShiftXPixels / nTileWidth);
    2413         800 :     if (nShiftXPixels < 0 && (nShiftXPixels % nTileWidth) != 0)
    2414          11 :         m_nShiftXTiles--;
    2415         800 :     m_nShiftXPixelsMod =
    2416         800 :         (static_cast<int>(nShiftXPixels % nTileWidth) + nTileWidth) %
    2417             :         nTileWidth;
    2418             : 
    2419         800 :     const double dfShiftYPixels = (m_gt[3] - m_dfTMSMaxY) / m_gt[5];
    2420         800 :     if (!(dfShiftYPixels / nTileHeight >= INT_MIN &&
    2421         800 :           dfShiftYPixels / nTileHeight < INT_MAX))
    2422             :     {
    2423           1 :         return false;
    2424             :     }
    2425         799 :     const int64_t nShiftYPixels =
    2426         799 :         static_cast<int64_t>(floor(0.5 + dfShiftYPixels));
    2427         799 :     m_nShiftYTiles = static_cast<int>(nShiftYPixels / nTileHeight);
    2428         799 :     if (nShiftYPixels < 0 && (nShiftYPixels % nTileHeight) != 0)
    2429          11 :         m_nShiftYTiles--;
    2430         799 :     m_nShiftYPixelsMod =
    2431         799 :         (static_cast<int>(nShiftYPixels % nTileHeight) + nTileHeight) %
    2432             :         nTileHeight;
    2433         799 :     return true;
    2434             : }
    2435             : 
    2436             : /************************************************************************/
    2437             : /*                          AllocCachedTiles()                          */
    2438             : /************************************************************************/
    2439             : 
    2440         799 : bool GDALGeoPackageDataset::AllocCachedTiles()
    2441             : {
    2442             :     int nTileWidth, nTileHeight;
    2443         799 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2444             : 
    2445             :     // We currently need 4 caches because of
    2446             :     // GDALGPKGMBTilesLikePseudoDataset::ReadTile(int nRow, int nCol)
    2447         799 :     const int nCacheCount = 4;
    2448             :     /*
    2449             :             (m_nShiftXPixelsMod != 0 || m_nShiftYPixelsMod != 0) ? 4 :
    2450             :             (GetUpdate() && m_eDT == GDT_UInt8) ? 2 : 1;
    2451             :     */
    2452         799 :     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         799 :     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         799 :     return true;
    2464             : }
    2465             : 
    2466             : /************************************************************************/
    2467             : /*                             InitRaster()                             */
    2468             : /************************************************************************/
    2469             : 
    2470         612 : 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         612 :     m_osRasterTable = pszTableName;
    2478         612 :     m_dfTMSMinX = dfTMSMinX;
    2479         612 :     m_dfTMSMaxY = dfTMSMaxY;
    2480         612 :     m_nZoomLevel = nZoomLevel;
    2481         612 :     m_nTileMatrixWidth = nTileMatrixWidth;
    2482         612 :     m_nTileMatrixHeight = nTileMatrixHeight;
    2483             : 
    2484         612 :     m_bGeoTransformValid = true;
    2485         612 :     m_gt[0] = dfGDALMinX;
    2486         612 :     m_gt[1] = dfPixelXSize;
    2487         612 :     m_gt[3] = dfGDALMaxY;
    2488         612 :     m_gt[5] = -dfPixelYSize;
    2489         612 :     double dfRasterXSize = 0.5 + (dfGDALMaxX - dfGDALMinX) / dfPixelXSize;
    2490         612 :     double dfRasterYSize = 0.5 + (dfGDALMaxY - dfGDALMinY) / dfPixelYSize;
    2491         612 :     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         612 :     nRasterXSize = std::max(1, static_cast<int>(dfRasterXSize));
    2498         612 :     nRasterYSize = std::max(1, static_cast<int>(dfRasterYSize));
    2499             : 
    2500         612 :     if (poParentDS)
    2501             :     {
    2502         330 :         m_poParentDS = poParentDS;
    2503         330 :         eAccess = poParentDS->eAccess;
    2504         330 :         hDB = poParentDS->hDB;
    2505         330 :         m_eTF = poParentDS->m_eTF;
    2506         330 :         m_eDT = poParentDS->m_eDT;
    2507         330 :         m_nDTSize = poParentDS->m_nDTSize;
    2508         330 :         m_dfScale = poParentDS->m_dfScale;
    2509         330 :         m_dfOffset = poParentDS->m_dfOffset;
    2510         330 :         m_dfPrecision = poParentDS->m_dfPrecision;
    2511         330 :         m_usGPKGNull = poParentDS->m_usGPKGNull;
    2512         330 :         m_nQuality = poParentDS->m_nQuality;
    2513         330 :         m_nZLevel = poParentDS->m_nZLevel;
    2514         330 :         m_bDither = poParentDS->m_bDither;
    2515             :         /*m_nSRID = poParentDS->m_nSRID;*/
    2516         330 :         m_osWHERE = poParentDS->m_osWHERE;
    2517         330 :         SetDescription(CPLSPrintf("%s - zoom_level=%d",
    2518         330 :                                   poParentDS->GetDescription(), m_nZoomLevel));
    2519             :     }
    2520             : 
    2521        2130 :     for (int i = 1; i <= nBandCount; i++)
    2522             :     {
    2523             :         auto poNewBand = std::make_unique<GDALGeoPackageRasterBand>(
    2524        1518 :             this, nTileWidth, nTileHeight);
    2525        1518 :         if (poParentDS)
    2526             :         {
    2527         766 :             int bHasNoData = FALSE;
    2528             :             double dfNoDataValue =
    2529         766 :                 poParentDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    2530         766 :             if (bHasNoData)
    2531          24 :                 poNewBand->SetNoDataValueInternal(dfNoDataValue);
    2532             :         }
    2533             : 
    2534        1518 :         if (nBandCount == 1 && m_poCTFromMetadata)
    2535             :         {
    2536           3 :             poNewBand->AssignColorTable(m_poCTFromMetadata.get());
    2537             :         }
    2538        1518 :         if (!m_osNodataValueFromMetadata.empty())
    2539             :         {
    2540           8 :             poNewBand->SetNoDataValueInternal(
    2541             :                 CPLAtof(m_osNodataValueFromMetadata.c_str()));
    2542             :         }
    2543             : 
    2544        1518 :         SetBand(i, std::move(poNewBand));
    2545             :     }
    2546             : 
    2547         612 :     if (!ComputeTileAndPixelShifts())
    2548             :     {
    2549           3 :         CPLError(CE_Failure, CPLE_AppDefined,
    2550             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    2551           3 :         return false;
    2552             :     }
    2553             : 
    2554         609 :     GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    2555         609 :     GDALPamDataset::SetMetadataItem("ZOOM_LEVEL",
    2556             :                                     CPLSPrintf("%d", m_nZoomLevel));
    2557             : 
    2558         609 :     return AllocCachedTiles();
    2559             : }
    2560             : 
    2561             : /************************************************************************/
    2562             : /*                    GDALGPKGMBTilesGetTileFormat()                    */
    2563             : /************************************************************************/
    2564             : 
    2565          80 : GPKGTileFormat GDALGPKGMBTilesGetTileFormat(const char *pszTF)
    2566             : {
    2567          80 :     GPKGTileFormat eTF = GPKG_TF_PNG_JPEG;
    2568          80 :     if (pszTF)
    2569             :     {
    2570          80 :         if (EQUAL(pszTF, "PNG_JPEG") || EQUAL(pszTF, "AUTO"))
    2571           1 :             eTF = GPKG_TF_PNG_JPEG;
    2572          79 :         else if (EQUAL(pszTF, "PNG"))
    2573          46 :             eTF = GPKG_TF_PNG;
    2574          33 :         else if (EQUAL(pszTF, "PNG8"))
    2575           6 :             eTF = GPKG_TF_PNG8;
    2576          27 :         else if (EQUAL(pszTF, "JPEG"))
    2577          14 :             eTF = GPKG_TF_JPEG;
    2578          13 :         else if (EQUAL(pszTF, "WEBP"))
    2579          13 :             eTF = GPKG_TF_WEBP;
    2580             :         else
    2581             :         {
    2582           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2583             :                      "Unsuppoted value for TILE_FORMAT: %s", pszTF);
    2584             :         }
    2585             :     }
    2586          80 :     return eTF;
    2587             : }
    2588             : 
    2589          28 : const char *GDALMBTilesGetTileFormatName(GPKGTileFormat eTF)
    2590             : {
    2591          28 :     switch (eTF)
    2592             :     {
    2593          26 :         case GPKG_TF_PNG:
    2594             :         case GPKG_TF_PNG8:
    2595          26 :             return "png";
    2596           1 :         case GPKG_TF_JPEG:
    2597           1 :             return "jpg";
    2598           1 :         case GPKG_TF_WEBP:
    2599           1 :             return "webp";
    2600           0 :         default:
    2601           0 :             break;
    2602             :     }
    2603           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2604             :              "Unsuppoted value for TILE_FORMAT: %d", static_cast<int>(eTF));
    2605           0 :     return nullptr;
    2606             : }
    2607             : 
    2608             : /************************************************************************/
    2609             : /*                             OpenRaster()                             */
    2610             : /************************************************************************/
    2611             : 
    2612         284 : bool GDALGeoPackageDataset::OpenRaster(
    2613             :     const char *pszTableName, const char *pszIdentifier,
    2614             :     const char *pszDescription, int nSRSId, double dfMinX, double dfMinY,
    2615             :     double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2616             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2617             :     const char *pszContentsMaxY, bool bIsTiles, CSLConstList papszOpenOptionsIn)
    2618             : {
    2619         284 :     if (dfMinX >= dfMaxX || dfMinY >= dfMaxY)
    2620           0 :         return false;
    2621             : 
    2622             :     // Config option just for debug, and for example force set to NaN
    2623             :     // which is not supported
    2624         568 :     CPLString osDataNull = CPLGetConfigOption("GPKG_NODATA", "");
    2625         568 :     CPLString osUom;
    2626         568 :     CPLString osFieldName;
    2627         568 :     CPLString osGridCellEncoding;
    2628         284 :     if (!bIsTiles)
    2629             :     {
    2630          65 :         char *pszSQL = sqlite3_mprintf(
    2631             :             "SELECT datatype, scale, offset, data_null, precision FROM "
    2632             :             "gpkg_2d_gridded_coverage_ancillary "
    2633             :             "WHERE tile_matrix_set_name = '%q' "
    2634             :             "AND datatype IN ('integer', 'float')"
    2635             :             "AND (scale > 0 OR scale IS NULL)",
    2636             :             pszTableName);
    2637          65 :         auto oResult = SQLQuery(hDB, pszSQL);
    2638          65 :         sqlite3_free(pszSQL);
    2639          65 :         if (!oResult || oResult->RowCount() == 0)
    2640             :         {
    2641           0 :             return false;
    2642             :         }
    2643          65 :         const char *pszDataType = oResult->GetValue(0, 0);
    2644          65 :         const char *pszScale = oResult->GetValue(1, 0);
    2645          65 :         const char *pszOffset = oResult->GetValue(2, 0);
    2646          65 :         const char *pszDataNull = oResult->GetValue(3, 0);
    2647          65 :         const char *pszPrecision = oResult->GetValue(4, 0);
    2648          65 :         if (pszDataNull)
    2649          23 :             osDataNull = pszDataNull;
    2650          65 :         if (EQUAL(pszDataType, "float"))
    2651             :         {
    2652           6 :             SetDataType(GDT_Float32);
    2653           6 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    2654             :         }
    2655             :         else
    2656             :         {
    2657          59 :             SetDataType(GDT_Float32);
    2658          59 :             m_eTF = GPKG_TF_PNG_16BIT;
    2659          59 :             const double dfScale = pszScale ? CPLAtof(pszScale) : 1.0;
    2660          59 :             const double dfOffset = pszOffset ? CPLAtof(pszOffset) : 0.0;
    2661          59 :             if (dfScale == 1.0)
    2662             :             {
    2663          59 :                 if (dfOffset == 0.0)
    2664             :                 {
    2665          24 :                     SetDataType(GDT_UInt16);
    2666             :                 }
    2667          35 :                 else if (dfOffset == -32768.0)
    2668             :                 {
    2669          35 :                     SetDataType(GDT_Int16);
    2670             :                 }
    2671             :                 // coverity[tainted_data]
    2672           0 :                 else if (dfOffset == -32767.0 && !osDataNull.empty() &&
    2673           0 :                          CPLAtof(osDataNull) == 65535.0)
    2674             :                 // Given that we will map the nodata value to -32768
    2675             :                 {
    2676           0 :                     SetDataType(GDT_Int16);
    2677             :                 }
    2678             :             }
    2679             : 
    2680             :             // Check that the tile offset and scales are compatible of a
    2681             :             // final integer result.
    2682          59 :             if (m_eDT != GDT_Float32)
    2683             :             {
    2684             :                 // coverity[tainted_data]
    2685          59 :                 if (dfScale == 1.0 && dfOffset == -32768.0 &&
    2686         118 :                     !osDataNull.empty() && CPLAtof(osDataNull) == 65535.0)
    2687             :                 {
    2688             :                     // Given that we will map the nodata value to -32768
    2689           9 :                     pszSQL = sqlite3_mprintf(
    2690             :                         "SELECT 1 FROM "
    2691             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2692             :                         "tpudt_name = '%q' "
    2693             :                         "AND NOT ((offset = 0.0 or offset = 1.0) "
    2694             :                         "AND scale = 1.0) "
    2695             :                         "LIMIT 1",
    2696             :                         pszTableName);
    2697             :                 }
    2698             :                 else
    2699             :                 {
    2700          50 :                     pszSQL = sqlite3_mprintf(
    2701             :                         "SELECT 1 FROM "
    2702             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2703             :                         "tpudt_name = '%q' "
    2704             :                         "AND NOT (offset = 0.0 AND scale = 1.0) LIMIT 1",
    2705             :                         pszTableName);
    2706             :                 }
    2707          59 :                 sqlite3_stmt *hSQLStmt = nullptr;
    2708             :                 int rc =
    2709          59 :                     SQLPrepareWithError(hDB, pszSQL, -1, &hSQLStmt, nullptr);
    2710             : 
    2711          59 :                 if (rc == SQLITE_OK)
    2712             :                 {
    2713          59 :                     if (sqlite3_step(hSQLStmt) == SQLITE_ROW)
    2714             :                     {
    2715           8 :                         SetDataType(GDT_Float32);
    2716             :                     }
    2717          59 :                     sqlite3_finalize(hSQLStmt);
    2718             :                 }
    2719          59 :                 sqlite3_free(pszSQL);
    2720             :             }
    2721             : 
    2722          59 :             SetGlobalOffsetScale(dfOffset, dfScale);
    2723             :         }
    2724          65 :         if (pszPrecision)
    2725          65 :             m_dfPrecision = CPLAtof(pszPrecision);
    2726             : 
    2727             :         // Request those columns in a separate query, so as to keep
    2728             :         // compatibility with pre OGC 17-066r1 databases
    2729             :         pszSQL =
    2730          65 :             sqlite3_mprintf("SELECT uom, field_name, grid_cell_encoding FROM "
    2731             :                             "gpkg_2d_gridded_coverage_ancillary "
    2732             :                             "WHERE tile_matrix_set_name = '%q'",
    2733             :                             pszTableName);
    2734          65 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    2735          65 :         oResult = SQLQuery(hDB, pszSQL);
    2736          65 :         CPLPopErrorHandler();
    2737          65 :         sqlite3_free(pszSQL);
    2738          65 :         if (oResult && oResult->RowCount() == 1)
    2739             :         {
    2740          64 :             const char *pszUom = oResult->GetValue(0, 0);
    2741          64 :             if (pszUom)
    2742           2 :                 osUom = pszUom;
    2743          64 :             const char *pszFieldName = oResult->GetValue(1, 0);
    2744          64 :             if (pszFieldName)
    2745          64 :                 osFieldName = pszFieldName;
    2746          64 :             const char *pszGridCellEncoding = oResult->GetValue(2, 0);
    2747          64 :             if (pszGridCellEncoding)
    2748          64 :                 osGridCellEncoding = pszGridCellEncoding;
    2749             :         }
    2750             :     }
    2751             : 
    2752         284 :     m_bRecordInsertedInGPKGContent = true;
    2753         284 :     m_nSRID = nSRSId;
    2754             : 
    2755         567 :     if (auto poSRS = GetSpatialRef(nSRSId))
    2756             :     {
    2757         283 :         m_oSRS = *(poSRS.get());
    2758             :     }
    2759             : 
    2760             :     /* Various sanity checks added in the SELECT */
    2761         284 :     char *pszQuotedTableName = sqlite3_mprintf("'%q'", pszTableName);
    2762         568 :     CPLString osQuotedTableName(pszQuotedTableName);
    2763         284 :     sqlite3_free(pszQuotedTableName);
    2764         284 :     char *pszSQL = sqlite3_mprintf(
    2765             :         "SELECT zoom_level, pixel_x_size, pixel_y_size, tile_width, "
    2766             :         "tile_height, matrix_width, matrix_height "
    2767             :         "FROM gpkg_tile_matrix tm "
    2768             :         "WHERE table_name = %s "
    2769             :         // INT_MAX would be the theoretical maximum value to avoid
    2770             :         // overflows, but that's already a insane value.
    2771             :         "AND zoom_level >= 0 AND zoom_level <= 65536 "
    2772             :         "AND pixel_x_size > 0 AND pixel_y_size > 0 "
    2773             :         "AND tile_width >= 1 AND tile_width <= 65536 "
    2774             :         "AND tile_height >= 1 AND tile_height <= 65536 "
    2775             :         "AND matrix_width >= 1 AND matrix_height >= 1",
    2776             :         osQuotedTableName.c_str());
    2777         568 :     CPLString osSQL(pszSQL);
    2778             :     const char *pszZoomLevel =
    2779         284 :         CSLFetchNameValue(papszOpenOptionsIn, "ZOOM_LEVEL");
    2780         284 :     if (pszZoomLevel)
    2781             :     {
    2782           5 :         if (GetUpdate())
    2783           1 :             osSQL += CPLSPrintf(" AND zoom_level <= %d", atoi(pszZoomLevel));
    2784             :         else
    2785             :         {
    2786             :             osSQL += CPLSPrintf(
    2787             :                 " AND (zoom_level = %d OR (zoom_level < %d AND EXISTS(SELECT 1 "
    2788             :                 "FROM %s WHERE zoom_level = tm.zoom_level LIMIT 1)))",
    2789             :                 atoi(pszZoomLevel), atoi(pszZoomLevel),
    2790           4 :                 osQuotedTableName.c_str());
    2791             :         }
    2792             :     }
    2793             :     // In read-only mode, only lists non empty zoom levels
    2794         279 :     else if (!GetUpdate())
    2795             :     {
    2796             :         osSQL += CPLSPrintf(" AND EXISTS(SELECT 1 FROM %s WHERE zoom_level = "
    2797             :                             "tm.zoom_level LIMIT 1)",
    2798         225 :                             osQuotedTableName.c_str());
    2799             :     }
    2800             :     else  // if( pszZoomLevel == nullptr )
    2801             :     {
    2802             :         osSQL +=
    2803             :             CPLSPrintf(" AND zoom_level <= (SELECT MAX(zoom_level) FROM %s)",
    2804          54 :                        osQuotedTableName.c_str());
    2805             :     }
    2806         284 :     osSQL += " ORDER BY zoom_level DESC";
    2807             :     // To avoid denial of service.
    2808         284 :     osSQL += " LIMIT 100";
    2809             : 
    2810         568 :     auto oResult = SQLQuery(hDB, osSQL.c_str());
    2811         284 :     if (!oResult || oResult->RowCount() == 0)
    2812             :     {
    2813         120 :         if (oResult && oResult->RowCount() == 0 && pszContentsMinX != nullptr &&
    2814         120 :             pszContentsMinY != nullptr && pszContentsMaxX != nullptr &&
    2815             :             pszContentsMaxY != nullptr)
    2816             :         {
    2817          59 :             osSQL = pszSQL;
    2818          59 :             osSQL += " ORDER BY zoom_level DESC";
    2819          59 :             if (!GetUpdate())
    2820          33 :                 osSQL += " LIMIT 1";
    2821          59 :             oResult = SQLQuery(hDB, osSQL.c_str());
    2822             :         }
    2823          60 :         if (!oResult || oResult->RowCount() == 0)
    2824             :         {
    2825           1 :             if (oResult && pszZoomLevel != nullptr)
    2826             :             {
    2827           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2828             :                          "ZOOM_LEVEL is probably not valid w.r.t tile "
    2829             :                          "table content");
    2830             :             }
    2831           1 :             sqlite3_free(pszSQL);
    2832           1 :             return false;
    2833             :         }
    2834             :     }
    2835         283 :     sqlite3_free(pszSQL);
    2836             : 
    2837             :     // If USE_TILE_EXTENT=YES, then query the tile table to find which tiles
    2838             :     // actually exist.
    2839             : 
    2840             :     // CAUTION: Do not move those variables inside inner scope !
    2841         566 :     CPLString osContentsMinX, osContentsMinY, osContentsMaxX, osContentsMaxY;
    2842             : 
    2843         283 :     if (CPLTestBool(
    2844             :             CSLFetchNameValueDef(papszOpenOptionsIn, "USE_TILE_EXTENT", "NO")))
    2845             :     {
    2846          13 :         pszSQL = sqlite3_mprintf(
    2847             :             "SELECT MIN(tile_column), MIN(tile_row), MAX(tile_column), "
    2848             :             "MAX(tile_row) FROM \"%w\" WHERE zoom_level = %d",
    2849             :             pszTableName, atoi(oResult->GetValue(0, 0)));
    2850          13 :         auto oResult2 = SQLQuery(hDB, pszSQL);
    2851          13 :         sqlite3_free(pszSQL);
    2852          26 :         if (!oResult2 || oResult2->RowCount() == 0 ||
    2853             :             // Can happen if table is empty
    2854          38 :             oResult2->GetValue(0, 0) == nullptr ||
    2855             :             // Can happen if table has no NOT NULL constraint on tile_row
    2856             :             // and that all tile_row are NULL
    2857          12 :             oResult2->GetValue(1, 0) == nullptr)
    2858             :         {
    2859           1 :             return false;
    2860             :         }
    2861          12 :         const double dfPixelXSize = CPLAtof(oResult->GetValue(1, 0));
    2862          12 :         const double dfPixelYSize = CPLAtof(oResult->GetValue(2, 0));
    2863          12 :         const int nTileWidth = atoi(oResult->GetValue(3, 0));
    2864          12 :         const int nTileHeight = atoi(oResult->GetValue(4, 0));
    2865             :         osContentsMinX =
    2866          24 :             CPLSPrintf("%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2867          12 :                                              atoi(oResult2->GetValue(0, 0)));
    2868             :         osContentsMaxY =
    2869          24 :             CPLSPrintf("%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2870          12 :                                              atoi(oResult2->GetValue(1, 0)));
    2871             :         osContentsMaxX = CPLSPrintf(
    2872          24 :             "%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2873          12 :                                   (1 + atoi(oResult2->GetValue(2, 0))));
    2874             :         osContentsMinY = CPLSPrintf(
    2875          24 :             "%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2876          12 :                                   (1 + atoi(oResult2->GetValue(3, 0))));
    2877          12 :         pszContentsMinX = osContentsMinX.c_str();
    2878          12 :         pszContentsMinY = osContentsMinY.c_str();
    2879          12 :         pszContentsMaxX = osContentsMaxX.c_str();
    2880          12 :         pszContentsMaxY = osContentsMaxY.c_str();
    2881             :     }
    2882             : 
    2883         282 :     if (!InitRaster(nullptr, pszTableName, dfMinX, dfMinY, dfMaxX, dfMaxY,
    2884             :                     pszContentsMinX, pszContentsMinY, pszContentsMaxX,
    2885         282 :                     pszContentsMaxY, papszOpenOptionsIn, *oResult, 0))
    2886             :     {
    2887           3 :         return false;
    2888             :     }
    2889             : 
    2890         279 :     auto poBand = cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(1));
    2891         279 :     if (!osDataNull.empty())
    2892             :     {
    2893          23 :         double dfGPKGNoDataValue = CPLAtof(osDataNull);
    2894          23 :         if (m_eTF == GPKG_TF_PNG_16BIT)
    2895             :         {
    2896          21 :             if (dfGPKGNoDataValue < 0 || dfGPKGNoDataValue > 65535 ||
    2897          21 :                 static_cast<int>(dfGPKGNoDataValue) != dfGPKGNoDataValue)
    2898             :             {
    2899           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2900             :                          "data_null = %.17g is invalid for integer data_type",
    2901             :                          dfGPKGNoDataValue);
    2902             :             }
    2903             :             else
    2904             :             {
    2905          21 :                 m_usGPKGNull = static_cast<GUInt16>(dfGPKGNoDataValue);
    2906          21 :                 if (m_eDT == GDT_Int16 && m_usGPKGNull > 32767)
    2907           9 :                     dfGPKGNoDataValue = -32768.0;
    2908          12 :                 else if (m_eDT == GDT_Float32)
    2909             :                 {
    2910             :                     // Pick a value that is unlikely to be hit with offset &
    2911             :                     // scale
    2912           4 :                     dfGPKGNoDataValue = -std::numeric_limits<float>::max();
    2913             :                 }
    2914          21 :                 poBand->SetNoDataValueInternal(dfGPKGNoDataValue);
    2915             :             }
    2916             :         }
    2917             :         else
    2918             :         {
    2919           2 :             poBand->SetNoDataValueInternal(
    2920           2 :                 static_cast<float>(dfGPKGNoDataValue));
    2921             :         }
    2922             :     }
    2923         279 :     if (!osUom.empty())
    2924             :     {
    2925           2 :         poBand->SetUnitTypeInternal(osUom);
    2926             :     }
    2927         279 :     if (!osFieldName.empty())
    2928             :     {
    2929          64 :         GetRasterBand(1)->GDALRasterBand::SetDescription(osFieldName);
    2930             :     }
    2931         279 :     if (!osGridCellEncoding.empty())
    2932             :     {
    2933          64 :         if (osGridCellEncoding == "grid-value-is-center")
    2934             :         {
    2935          15 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2936             :                                             GDALMD_AOP_POINT);
    2937             :         }
    2938          49 :         else if (osGridCellEncoding == "grid-value-is-area")
    2939             :         {
    2940          45 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2941             :                                             GDALMD_AOP_AREA);
    2942             :         }
    2943             :         else
    2944             :         {
    2945           4 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2946             :                                             GDALMD_AOP_POINT);
    2947           4 :             GetRasterBand(1)->GDALRasterBand::SetMetadataItem(
    2948             :                 "GRID_CELL_ENCODING", osGridCellEncoding);
    2949             :         }
    2950             :     }
    2951             : 
    2952         279 :     CheckUnknownExtensions(true);
    2953             : 
    2954             :     // Do this after CheckUnknownExtensions() so that m_eTF is set to
    2955             :     // GPKG_TF_WEBP if the table already registers the gpkg_webp extension
    2956         279 :     const char *pszTF = CSLFetchNameValue(papszOpenOptionsIn, "TILE_FORMAT");
    2957         279 :     if (pszTF)
    2958             :     {
    2959           4 :         if (!GetUpdate())
    2960             :         {
    2961           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2962             :                      "TILE_FORMAT open option ignored in read-only mode");
    2963             :         }
    2964           4 :         else if (m_eTF == GPKG_TF_PNG_16BIT ||
    2965           4 :                  m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    2966             :         {
    2967           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2968             :                      "TILE_FORMAT open option ignored on gridded coverages");
    2969             :         }
    2970             :         else
    2971             :         {
    2972           4 :             GPKGTileFormat eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    2973           4 :             if (eTF == GPKG_TF_WEBP && m_eTF != eTF)
    2974             :             {
    2975           1 :                 if (!RegisterWebPExtension())
    2976           0 :                     return false;
    2977             :             }
    2978           4 :             m_eTF = eTF;
    2979             :         }
    2980             :     }
    2981             : 
    2982         279 :     ParseCompressionOptions(papszOpenOptionsIn);
    2983             : 
    2984         279 :     m_osWHERE = CSLFetchNameValueDef(papszOpenOptionsIn, "WHERE", "");
    2985             : 
    2986             :     // Set metadata
    2987         279 :     if (pszIdentifier && pszIdentifier[0])
    2988         279 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", pszIdentifier);
    2989         279 :     if (pszDescription && pszDescription[0])
    2990          21 :         GDALPamDataset::SetMetadataItem("DESCRIPTION", pszDescription);
    2991             : 
    2992             :     // Add overviews
    2993         364 :     for (int i = 1; i < oResult->RowCount(); i++)
    2994             :     {
    2995          86 :         auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    2996          86 :         poOvrDS->ShareLockWithParentDataset(this);
    2997         172 :         if (!poOvrDS->InitRaster(this, pszTableName, dfMinX, dfMinY, dfMaxX,
    2998             :                                  dfMaxY, pszContentsMinX, pszContentsMinY,
    2999             :                                  pszContentsMaxX, pszContentsMaxY,
    3000          86 :                                  papszOpenOptionsIn, *oResult, i))
    3001             :         {
    3002           0 :             break;
    3003             :         }
    3004             : 
    3005             :         int nTileWidth, nTileHeight;
    3006          86 :         poOvrDS->GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3007             :         const bool bStop =
    3008          87 :             (eAccess == GA_ReadOnly && poOvrDS->GetRasterXSize() < nTileWidth &&
    3009           1 :              poOvrDS->GetRasterYSize() < nTileHeight);
    3010             : 
    3011          86 :         m_apoOverviewDS.push_back(std::move(poOvrDS));
    3012             : 
    3013          86 :         if (bStop)
    3014             :         {
    3015           1 :             break;
    3016             :         }
    3017             :     }
    3018             : 
    3019         279 :     return true;
    3020             : }
    3021             : 
    3022             : /************************************************************************/
    3023             : /*                           GetSpatialRef()                            */
    3024             : /************************************************************************/
    3025             : 
    3026          17 : const OGRSpatialReference *GDALGeoPackageDataset::GetSpatialRef() const
    3027             : {
    3028          17 :     if (GetLayerCount())
    3029           1 :         return GDALDataset::GetSpatialRef();
    3030          16 :     return GetSpatialRefRasterOnly();
    3031             : }
    3032             : 
    3033             : /************************************************************************/
    3034             : /*                      GetSpatialRefRasterOnly()                       */
    3035             : /************************************************************************/
    3036             : 
    3037             : const OGRSpatialReference *
    3038          17 : GDALGeoPackageDataset::GetSpatialRefRasterOnly() const
    3039             : 
    3040             : {
    3041          17 :     return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
    3042             : }
    3043             : 
    3044             : /************************************************************************/
    3045             : /*                           SetSpatialRef()                            */
    3046             : /************************************************************************/
    3047             : 
    3048         156 : CPLErr GDALGeoPackageDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    3049             : {
    3050         156 :     if (nBands == 0)
    3051             :     {
    3052           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3053             :                  "SetProjection() not supported on a dataset with 0 band");
    3054           1 :         return CE_Failure;
    3055             :     }
    3056         155 :     if (eAccess != GA_Update)
    3057             :     {
    3058           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3059             :                  "SetProjection() not supported on read-only dataset");
    3060           1 :         return CE_Failure;
    3061             :     }
    3062             : 
    3063         154 :     const int nSRID = GetSrsId(poSRS);
    3064         308 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3065         154 :     if (poTS && nSRID != poTS->nEPSGCode)
    3066             :     {
    3067           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3068             :                  "Projection should be EPSG:%d for %s tiling scheme",
    3069           1 :                  poTS->nEPSGCode, m_osTilingScheme.c_str());
    3070           1 :         return CE_Failure;
    3071             :     }
    3072             : 
    3073         153 :     m_nSRID = nSRID;
    3074         153 :     m_oSRS.Clear();
    3075         153 :     if (poSRS)
    3076         152 :         m_oSRS = *poSRS;
    3077             : 
    3078         153 :     if (m_bRecordInsertedInGPKGContent)
    3079             :     {
    3080         122 :         char *pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET srs_id = %d "
    3081             :                                        "WHERE lower(table_name) = lower('%q')",
    3082             :                                        m_nSRID, m_osRasterTable.c_str());
    3083         122 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3084         122 :         sqlite3_free(pszSQL);
    3085         122 :         if (eErr != OGRERR_NONE)
    3086           0 :             return CE_Failure;
    3087             : 
    3088         122 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_tile_matrix_set SET srs_id = %d "
    3089             :                                  "WHERE lower(table_name) = lower('%q')",
    3090             :                                  m_nSRID, m_osRasterTable.c_str());
    3091         122 :         eErr = SQLCommand(hDB, pszSQL);
    3092         122 :         sqlite3_free(pszSQL);
    3093         122 :         if (eErr != OGRERR_NONE)
    3094           0 :             return CE_Failure;
    3095             :     }
    3096             : 
    3097         153 :     return CE_None;
    3098             : }
    3099             : 
    3100             : /************************************************************************/
    3101             : /*                          GetGeoTransform()                           */
    3102             : /************************************************************************/
    3103             : 
    3104          33 : CPLErr GDALGeoPackageDataset::GetGeoTransform(GDALGeoTransform &gt) const
    3105             : {
    3106          33 :     gt = m_gt;
    3107          33 :     if (!m_bGeoTransformValid)
    3108           2 :         return CE_Failure;
    3109             :     else
    3110          31 :         return CE_None;
    3111             : }
    3112             : 
    3113             : /************************************************************************/
    3114             : /*                          SetGeoTransform()                           */
    3115             : /************************************************************************/
    3116             : 
    3117         196 : CPLErr GDALGeoPackageDataset::SetGeoTransform(const GDALGeoTransform &gt)
    3118             : {
    3119         196 :     if (nBands == 0)
    3120             :     {
    3121           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3122             :                  "SetGeoTransform() not supported on a dataset with 0 band");
    3123           2 :         return CE_Failure;
    3124             :     }
    3125         194 :     if (eAccess != GA_Update)
    3126             :     {
    3127           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3128             :                  "SetGeoTransform() not supported on read-only dataset");
    3129           1 :         return CE_Failure;
    3130             :     }
    3131         193 :     if (m_bGeoTransformValid)
    3132             :     {
    3133           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3134             :                  "Cannot modify geotransform once set");
    3135           1 :         return CE_Failure;
    3136             :     }
    3137         192 :     if (gt[2] != 0.0 || gt[4] != 0 || gt[5] > 0.0)
    3138             :     {
    3139           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3140             :                  "Only north-up non rotated geotransform supported");
    3141           0 :         return CE_Failure;
    3142             :     }
    3143             : 
    3144         192 :     if (m_nZoomLevel < 0)
    3145             :     {
    3146         191 :         const auto poTS = GetTilingScheme(m_osTilingScheme);
    3147         191 :         if (poTS)
    3148             :         {
    3149          20 :             double dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3150          20 :             double dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3151         199 :             for (m_nZoomLevel = 0; m_nZoomLevel < MAX_ZOOM_LEVEL;
    3152         179 :                  m_nZoomLevel++)
    3153             :             {
    3154         198 :                 double dfExpectedPixelXSize =
    3155         198 :                     dfPixelXSizeZoomLevel0 / (1 << m_nZoomLevel);
    3156         198 :                 double dfExpectedPixelYSize =
    3157         198 :                     dfPixelYSizeZoomLevel0 / (1 << m_nZoomLevel);
    3158         198 :                 if (fabs(gt[1] - dfExpectedPixelXSize) <
    3159         217 :                         1e-8 * dfExpectedPixelXSize &&
    3160          19 :                     fabs(fabs(gt[5]) - dfExpectedPixelYSize) <
    3161          19 :                         1e-8 * dfExpectedPixelYSize)
    3162             :                 {
    3163          19 :                     break;
    3164             :                 }
    3165             :             }
    3166          20 :             if (m_nZoomLevel == MAX_ZOOM_LEVEL)
    3167             :             {
    3168           1 :                 m_nZoomLevel = -1;
    3169           1 :                 CPLError(
    3170             :                     CE_Failure, CPLE_NotSupported,
    3171             :                     "Could not find an appropriate zoom level of %s tiling "
    3172             :                     "scheme that matches raster pixel size",
    3173             :                     m_osTilingScheme.c_str());
    3174           1 :                 return CE_Failure;
    3175             :             }
    3176             :         }
    3177             :     }
    3178             : 
    3179         191 :     m_gt = gt;
    3180         191 :     m_bGeoTransformValid = true;
    3181             : 
    3182         191 :     return FinalizeRasterRegistration();
    3183             : }
    3184             : 
    3185             : /************************************************************************/
    3186             : /*                     FinalizeRasterRegistration()                     */
    3187             : /************************************************************************/
    3188             : 
    3189         191 : CPLErr GDALGeoPackageDataset::FinalizeRasterRegistration()
    3190             : {
    3191             :     OGRErr eErr;
    3192             : 
    3193         191 :     m_dfTMSMinX = m_gt[0];
    3194         191 :     m_dfTMSMaxY = m_gt[3];
    3195             : 
    3196             :     int nTileWidth, nTileHeight;
    3197         191 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3198             : 
    3199         191 :     if (m_nZoomLevel < 0)
    3200             :     {
    3201         171 :         m_nZoomLevel = 0;
    3202         250 :         while ((nRasterXSize >> m_nZoomLevel) > nTileWidth ||
    3203         171 :                (nRasterYSize >> m_nZoomLevel) > nTileHeight)
    3204          79 :             m_nZoomLevel++;
    3205             :     }
    3206             : 
    3207         191 :     double dfPixelXSizeZoomLevel0 = m_gt[1] * (1 << m_nZoomLevel);
    3208         191 :     double dfPixelYSizeZoomLevel0 = fabs(m_gt[5]) * (1 << m_nZoomLevel);
    3209             :     int nTileXCountZoomLevel0 =
    3210         191 :         std::max(1, DIV_ROUND_UP((nRasterXSize >> m_nZoomLevel), nTileWidth));
    3211             :     int nTileYCountZoomLevel0 =
    3212         191 :         std::max(1, DIV_ROUND_UP((nRasterYSize >> m_nZoomLevel), nTileHeight));
    3213             : 
    3214         382 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3215         191 :     if (poTS)
    3216             :     {
    3217          20 :         CPLAssert(m_nZoomLevel >= 0);
    3218          20 :         m_dfTMSMinX = poTS->dfMinX;
    3219          20 :         m_dfTMSMaxY = poTS->dfMaxY;
    3220          20 :         dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3221          20 :         dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3222          20 :         nTileXCountZoomLevel0 = poTS->nTileXCountZoomLevel0;
    3223          20 :         nTileYCountZoomLevel0 = poTS->nTileYCountZoomLevel0;
    3224             :     }
    3225         191 :     m_nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << m_nZoomLevel);
    3226         191 :     m_nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << m_nZoomLevel);
    3227             : 
    3228         191 :     if (!ComputeTileAndPixelShifts())
    3229             :     {
    3230           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    3231             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    3232           1 :         return CE_Failure;
    3233             :     }
    3234             : 
    3235         190 :     if (!AllocCachedTiles())
    3236             :     {
    3237           0 :         return CE_Failure;
    3238             :     }
    3239             : 
    3240         190 :     double dfGDALMinX = m_gt[0];
    3241         190 :     double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3242         190 :     double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3243         190 :     double dfGDALMaxY = m_gt[3];
    3244             : 
    3245         190 :     if (SoftStartTransaction() != OGRERR_NONE)
    3246           0 :         return CE_Failure;
    3247             : 
    3248             :     const char *pszCurrentDate =
    3249         190 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3250             :     CPLString osInsertGpkgContentsFormatting(
    3251             :         "INSERT INTO gpkg_contents "
    3252             :         "(table_name,data_type,identifier,description,min_x,min_y,max_x,max_y,"
    3253             :         "last_change,srs_id) VALUES "
    3254         380 :         "('%q','%q','%q','%q',%.17g,%.17g,%.17g,%.17g,");
    3255         190 :     osInsertGpkgContentsFormatting += (pszCurrentDate) ? "'%q'" : "%s";
    3256         190 :     osInsertGpkgContentsFormatting += ",%d)";
    3257         380 :     char *pszSQL = sqlite3_mprintf(
    3258             :         osInsertGpkgContentsFormatting.c_str(), m_osRasterTable.c_str(),
    3259         190 :         (m_eDT == GDT_UInt8) ? "tiles" : "2d-gridded-coverage",
    3260             :         m_osIdentifier.c_str(), m_osDescription.c_str(), dfGDALMinX, dfGDALMinY,
    3261             :         dfGDALMaxX, dfGDALMaxY,
    3262             :         pszCurrentDate ? pszCurrentDate
    3263             :                        : "strftime('%Y-%m-%dT%H:%M:%fZ','now')",
    3264             :         m_nSRID);
    3265             : 
    3266         190 :     eErr = SQLCommand(hDB, pszSQL);
    3267         190 :     sqlite3_free(pszSQL);
    3268         190 :     if (eErr != OGRERR_NONE)
    3269             :     {
    3270           8 :         SoftRollbackTransaction();
    3271           8 :         return CE_Failure;
    3272             :     }
    3273             : 
    3274         182 :     double dfTMSMaxX = m_dfTMSMinX + nTileXCountZoomLevel0 * nTileWidth *
    3275             :                                          dfPixelXSizeZoomLevel0;
    3276         182 :     double dfTMSMinY = m_dfTMSMaxY - nTileYCountZoomLevel0 * nTileHeight *
    3277             :                                          dfPixelYSizeZoomLevel0;
    3278             : 
    3279             :     pszSQL =
    3280         182 :         sqlite3_mprintf("INSERT INTO gpkg_tile_matrix_set "
    3281             :                         "(table_name,srs_id,min_x,min_y,max_x,max_y) VALUES "
    3282             :                         "('%q',%d,%.17g,%.17g,%.17g,%.17g)",
    3283             :                         m_osRasterTable.c_str(), m_nSRID, m_dfTMSMinX,
    3284             :                         dfTMSMinY, dfTMSMaxX, m_dfTMSMaxY);
    3285         182 :     eErr = SQLCommand(hDB, pszSQL);
    3286         182 :     sqlite3_free(pszSQL);
    3287         182 :     if (eErr != OGRERR_NONE)
    3288             :     {
    3289           0 :         SoftRollbackTransaction();
    3290           0 :         return CE_Failure;
    3291             :     }
    3292             : 
    3293         182 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3294             : 
    3295         604 :     for (int i = 0; i <= m_nZoomLevel; i++)
    3296             :     {
    3297         422 :         double dfPixelXSizeZoomLevel = 0.0;
    3298         422 :         double dfPixelYSizeZoomLevel = 0.0;
    3299         422 :         int nTileMatrixWidth = 0;
    3300         422 :         int nTileMatrixHeight = 0;
    3301         422 :         if (EQUAL(m_osTilingScheme, "CUSTOM"))
    3302             :         {
    3303         241 :             dfPixelXSizeZoomLevel = m_gt[1] * (1 << (m_nZoomLevel - i));
    3304         241 :             dfPixelYSizeZoomLevel = fabs(m_gt[5]) * (1 << (m_nZoomLevel - i));
    3305             :         }
    3306             :         else
    3307             :         {
    3308         181 :             dfPixelXSizeZoomLevel = dfPixelXSizeZoomLevel0 / (1 << i);
    3309         181 :             dfPixelYSizeZoomLevel = dfPixelYSizeZoomLevel0 / (1 << i);
    3310             :         }
    3311         422 :         nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << i);
    3312         422 :         nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << i);
    3313             : 
    3314         422 :         pszSQL = sqlite3_mprintf(
    3315             :             "INSERT INTO gpkg_tile_matrix "
    3316             :             "(table_name,zoom_level,matrix_width,matrix_height,tile_width,tile_"
    3317             :             "height,pixel_x_size,pixel_y_size) VALUES "
    3318             :             "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3319             :             m_osRasterTable.c_str(), i, nTileMatrixWidth, nTileMatrixHeight,
    3320             :             nTileWidth, nTileHeight, dfPixelXSizeZoomLevel,
    3321             :             dfPixelYSizeZoomLevel);
    3322         422 :         eErr = SQLCommand(hDB, pszSQL);
    3323         422 :         sqlite3_free(pszSQL);
    3324         422 :         if (eErr != OGRERR_NONE)
    3325             :         {
    3326           0 :             SoftRollbackTransaction();
    3327           0 :             return CE_Failure;
    3328             :         }
    3329             : 
    3330         422 :         if (i < m_nZoomLevel)
    3331             :         {
    3332         480 :             auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3333         240 :             poOvrDS->ShareLockWithParentDataset(this);
    3334         240 :             poOvrDS->InitRaster(this, m_osRasterTable, i, nBands, m_dfTMSMinX,
    3335             :                                 m_dfTMSMaxY, dfPixelXSizeZoomLevel,
    3336             :                                 dfPixelYSizeZoomLevel, nTileWidth, nTileHeight,
    3337             :                                 nTileMatrixWidth, nTileMatrixHeight, dfGDALMinX,
    3338             :                                 dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    3339             : 
    3340         240 :             m_apoOverviewDS[m_nZoomLevel - 1 - i] = std::move(poOvrDS);
    3341             :         }
    3342             :     }
    3343             : 
    3344         182 :     if (!m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.empty())
    3345             :     {
    3346          40 :         eErr = SQLCommand(
    3347             :             hDB, m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.c_str());
    3348          40 :         m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.clear();
    3349          40 :         if (eErr != OGRERR_NONE)
    3350             :         {
    3351           0 :             SoftRollbackTransaction();
    3352           0 :             return CE_Failure;
    3353             :         }
    3354             :     }
    3355             : 
    3356         182 :     SoftCommitTransaction();
    3357             : 
    3358         182 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3359         182 :     m_bRecordInsertedInGPKGContent = true;
    3360             : 
    3361         182 :     return CE_None;
    3362             : }
    3363             : 
    3364             : /************************************************************************/
    3365             : /*                             FlushCache()                             */
    3366             : /************************************************************************/
    3367             : 
    3368        3041 : CPLErr GDALGeoPackageDataset::FlushCache(bool bAtClosing)
    3369             : {
    3370        3041 :     if (m_bInFlushCache)
    3371           0 :         return CE_None;
    3372             : 
    3373        3041 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3374             :     {
    3375        3038 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3376             :     }
    3377             : 
    3378        3041 :     if (m_bRemoveOGREmptyTable)
    3379             :     {
    3380         852 :         m_bRemoveOGREmptyTable = false;
    3381         852 :         RemoveOGREmptyTable();
    3382             :     }
    3383             : 
    3384        3041 :     CPLErr eErr = IFlushCacheWithErrCode(bAtClosing);
    3385             : 
    3386        3041 :     FlushMetadata();
    3387             : 
    3388        3041 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3389             :     {
    3390             :         // Needed again as above IFlushCacheWithErrCode()
    3391             :         // may have call GDALGeoPackageRasterBand::InvalidateStatistics()
    3392             :         // which modifies metadata
    3393        3041 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3394             :     }
    3395             : 
    3396        3041 :     return eErr;
    3397             : }
    3398             : 
    3399        5305 : CPLErr GDALGeoPackageDataset::IFlushCacheWithErrCode(bool bAtClosing)
    3400             : 
    3401             : {
    3402        5305 :     if (m_bInFlushCache)
    3403        2197 :         return CE_None;
    3404        3108 :     m_bInFlushCache = true;
    3405        3108 :     if (hDB && eAccess == GA_ReadOnly && bAtClosing)
    3406             :     {
    3407             :         // Clean-up metadata that will go to PAM by removing items that
    3408             :         // are reconstructed.
    3409        2278 :         CPLStringList aosMD;
    3410        1789 :         for (CSLConstList papszIter = GetMetadata(); papszIter && *papszIter;
    3411             :              ++papszIter)
    3412             :         {
    3413         650 :             char *pszKey = nullptr;
    3414         650 :             CPLParseNameValue(*papszIter, &pszKey);
    3415        1300 :             if (pszKey &&
    3416         650 :                 (EQUAL(pszKey, "AREA_OR_POINT") ||
    3417         497 :                  EQUAL(pszKey, "IDENTIFIER") || EQUAL(pszKey, "DESCRIPTION") ||
    3418         266 :                  EQUAL(pszKey, "ZOOM_LEVEL") ||
    3419         680 :                  STARTS_WITH(pszKey, "GPKG_METADATA_ITEM_")))
    3420             :             {
    3421             :                 // remove it
    3422             :             }
    3423             :             else
    3424             :             {
    3425          30 :                 aosMD.AddString(*papszIter);
    3426             :             }
    3427         650 :             CPLFree(pszKey);
    3428             :         }
    3429        1139 :         oMDMD.SetMetadata(aosMD.List());
    3430        1139 :         oMDMD.SetMetadata(nullptr, "IMAGE_STRUCTURE");
    3431             : 
    3432        2278 :         GDALPamDataset::FlushCache(bAtClosing);
    3433             :     }
    3434             :     else
    3435             :     {
    3436             :         // Short circuit GDALPamDataset to avoid serialization to .aux.xml
    3437        1969 :         GDALDataset::FlushCache(bAtClosing);
    3438             :     }
    3439             : 
    3440        7514 :     for (auto &poLayer : m_apoLayers)
    3441             :     {
    3442        4406 :         poLayer->RunDeferredCreationIfNecessary();
    3443        4406 :         poLayer->CreateSpatialIndexIfNecessary();
    3444             :     }
    3445             : 
    3446             :     // Update raster table last_change column in gpkg_contents if needed
    3447        3108 :     if (m_bHasModifiedTiles)
    3448             :     {
    3449         542 :         for (int i = 1; i <= nBands; ++i)
    3450             :         {
    3451             :             auto poBand =
    3452         360 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    3453         360 :             if (!poBand->HaveStatsMetadataBeenSetInThisSession())
    3454             :             {
    3455         346 :                 poBand->InvalidateStatistics();
    3456         346 :                 if (psPam && psPam->pszPamFilename)
    3457         346 :                     VSIUnlink(psPam->pszPamFilename);
    3458             :             }
    3459             :         }
    3460             : 
    3461         182 :         UpdateGpkgContentsLastChange(m_osRasterTable);
    3462             : 
    3463         182 :         m_bHasModifiedTiles = false;
    3464             :     }
    3465             : 
    3466        3108 :     CPLErr eErr = FlushTiles();
    3467             : 
    3468        3108 :     m_bInFlushCache = false;
    3469        3108 :     return eErr;
    3470             : }
    3471             : 
    3472             : /************************************************************************/
    3473             : /*                      GetCurrentDateEscapedSQL()                      */
    3474             : /************************************************************************/
    3475             : 
    3476        2310 : std::string GDALGeoPackageDataset::GetCurrentDateEscapedSQL()
    3477             : {
    3478             :     const char *pszCurrentDate =
    3479        2310 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3480        2310 :     if (pszCurrentDate)
    3481          10 :         return '\'' + SQLEscapeLiteral(pszCurrentDate) + '\'';
    3482        2305 :     return "strftime('%Y-%m-%dT%H:%M:%fZ','now')";
    3483             : }
    3484             : 
    3485             : /************************************************************************/
    3486             : /*                    UpdateGpkgContentsLastChange()                    */
    3487             : /************************************************************************/
    3488             : 
    3489             : OGRErr
    3490         991 : GDALGeoPackageDataset::UpdateGpkgContentsLastChange(const char *pszTableName)
    3491             : {
    3492             :     char *pszSQL =
    3493         991 :         sqlite3_mprintf("UPDATE gpkg_contents SET "
    3494             :                         "last_change = %s "
    3495             :                         "WHERE lower(table_name) = lower('%q')",
    3496        1982 :                         GetCurrentDateEscapedSQL().c_str(), pszTableName);
    3497         991 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    3498         991 :     sqlite3_free(pszSQL);
    3499         991 :     return eErr;
    3500             : }
    3501             : 
    3502             : /************************************************************************/
    3503             : /*                          IBuildOverviews()                           */
    3504             : /************************************************************************/
    3505             : 
    3506          20 : CPLErr GDALGeoPackageDataset::IBuildOverviews(
    3507             :     const char *pszResampling, int nOverviews, const int *panOverviewList,
    3508             :     int nBandsIn, const int * /*panBandList*/, GDALProgressFunc pfnProgress,
    3509             :     void *pProgressData, CSLConstList papszOptions)
    3510             : {
    3511          20 :     if (GetAccess() != GA_Update)
    3512             :     {
    3513           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3514             :                  "Overview building not supported on a database opened in "
    3515             :                  "read-only mode");
    3516           1 :         return CE_Failure;
    3517             :     }
    3518          19 :     if (m_poParentDS != nullptr)
    3519             :     {
    3520           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3521             :                  "Overview building not supported on overview dataset");
    3522           1 :         return CE_Failure;
    3523             :     }
    3524             : 
    3525          18 :     if (nOverviews == 0)
    3526             :     {
    3527           5 :         for (auto &poOvrDS : m_apoOverviewDS)
    3528           3 :             poOvrDS->FlushCache(false);
    3529             : 
    3530           2 :         SoftStartTransaction();
    3531             : 
    3532           2 :         if (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    3533             :         {
    3534           1 :             char *pszSQL = sqlite3_mprintf(
    3535             :                 "DELETE FROM gpkg_2d_gridded_tile_ancillary WHERE id IN "
    3536             :                 "(SELECT y.id FROM \"%w\" x "
    3537             :                 "JOIN gpkg_2d_gridded_tile_ancillary y "
    3538             :                 "ON x.id = y.tpudt_id AND y.tpudt_name = '%q' AND "
    3539             :                 "x.zoom_level < %d)",
    3540             :                 m_osRasterTable.c_str(), m_osRasterTable.c_str(), m_nZoomLevel);
    3541           1 :             OGRErr eErr = SQLCommand(hDB, pszSQL);
    3542           1 :             sqlite3_free(pszSQL);
    3543           1 :             if (eErr != OGRERR_NONE)
    3544             :             {
    3545           0 :                 SoftRollbackTransaction();
    3546           0 :                 return CE_Failure;
    3547             :             }
    3548             :         }
    3549             : 
    3550             :         char *pszSQL =
    3551           2 :             sqlite3_mprintf("DELETE FROM \"%w\" WHERE zoom_level < %d",
    3552             :                             m_osRasterTable.c_str(), m_nZoomLevel);
    3553           2 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3554           2 :         sqlite3_free(pszSQL);
    3555           2 :         if (eErr != OGRERR_NONE)
    3556             :         {
    3557           0 :             SoftRollbackTransaction();
    3558           0 :             return CE_Failure;
    3559             :         }
    3560             : 
    3561           2 :         SoftCommitTransaction();
    3562             : 
    3563           2 :         return CE_None;
    3564             :     }
    3565             : 
    3566          16 :     if (nBandsIn != nBands)
    3567             :     {
    3568           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3569             :                  "Generation of overviews in GPKG only"
    3570             :                  "supported when operating on all bands.");
    3571           0 :         return CE_Failure;
    3572             :     }
    3573             : 
    3574          16 :     if (m_apoOverviewDS.empty())
    3575             :     {
    3576           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3577             :                  "Image too small to support overviews");
    3578           0 :         return CE_Failure;
    3579             :     }
    3580             : 
    3581          16 :     FlushCache(false);
    3582          60 :     for (int i = 0; i < nOverviews; i++)
    3583             :     {
    3584          47 :         if (panOverviewList[i] < 2)
    3585             :         {
    3586           1 :             CPLError(CE_Failure, CPLE_IllegalArg,
    3587             :                      "Overview factor must be >= 2");
    3588           1 :             return CE_Failure;
    3589             :         }
    3590             : 
    3591          46 :         bool bFound = false;
    3592          46 :         int jCandidate = -1;
    3593          46 :         int nMaxOvFactor = 0;
    3594         196 :         for (int j = 0; j < static_cast<int>(m_apoOverviewDS.size()); j++)
    3595             :         {
    3596         190 :             const auto poODS = m_apoOverviewDS[j].get();
    3597             :             const int nOvFactor =
    3598         190 :                 static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3599             : 
    3600         190 :             nMaxOvFactor = nOvFactor;
    3601             : 
    3602         190 :             if (nOvFactor == panOverviewList[i])
    3603             :             {
    3604          40 :                 bFound = true;
    3605          40 :                 break;
    3606             :             }
    3607             : 
    3608         150 :             if (jCandidate < 0 && nOvFactor > panOverviewList[i])
    3609           1 :                 jCandidate = j;
    3610             :         }
    3611             : 
    3612          46 :         if (!bFound)
    3613             :         {
    3614             :             /* Mostly for debug */
    3615           6 :             if (!CPLTestBool(CPLGetConfigOption(
    3616             :                     "ALLOW_GPKG_ZOOM_OTHER_EXTENSION", "YES")))
    3617             :             {
    3618           2 :                 CPLString osOvrList;
    3619           4 :                 for (const auto &poODS : m_apoOverviewDS)
    3620             :                 {
    3621             :                     const int nOvFactor =
    3622           2 :                         static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3623             : 
    3624           2 :                     if (!osOvrList.empty())
    3625           0 :                         osOvrList += ' ';
    3626           2 :                     osOvrList += CPLSPrintf("%d", nOvFactor);
    3627             :                 }
    3628           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    3629             :                          "Only overviews %s can be computed",
    3630             :                          osOvrList.c_str());
    3631           2 :                 return CE_Failure;
    3632             :             }
    3633             :             else
    3634             :             {
    3635           4 :                 int nOvFactor = panOverviewList[i];
    3636           4 :                 if (jCandidate < 0)
    3637           3 :                     jCandidate = static_cast<int>(m_apoOverviewDS.size());
    3638             : 
    3639           4 :                 int nOvXSize = std::max(1, GetRasterXSize() / nOvFactor);
    3640           4 :                 int nOvYSize = std::max(1, GetRasterYSize() / nOvFactor);
    3641           4 :                 if (!(jCandidate == static_cast<int>(m_apoOverviewDS.size()) &&
    3642           5 :                       nOvFactor == 2 * nMaxOvFactor) &&
    3643           1 :                     !m_bZoomOther)
    3644             :                 {
    3645           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    3646             :                              "Use of overview factor %d causes gpkg_zoom_other "
    3647             :                              "extension to be needed",
    3648             :                              nOvFactor);
    3649           1 :                     RegisterZoomOtherExtension();
    3650           1 :                     m_bZoomOther = true;
    3651             :                 }
    3652             : 
    3653           4 :                 SoftStartTransaction();
    3654             : 
    3655           4 :                 CPLAssert(jCandidate > 0);
    3656             :                 const int nNewZoomLevel =
    3657           4 :                     m_apoOverviewDS[jCandidate - 1]->m_nZoomLevel;
    3658             : 
    3659             :                 char *pszSQL;
    3660             :                 OGRErr eErr;
    3661          24 :                 for (int k = 0; k <= jCandidate; k++)
    3662             :                 {
    3663          60 :                     pszSQL = sqlite3_mprintf(
    3664             :                         "UPDATE gpkg_tile_matrix SET zoom_level = %d "
    3665             :                         "WHERE lower(table_name) = lower('%q') AND zoom_level "
    3666             :                         "= %d",
    3667          20 :                         m_nZoomLevel - k + 1, m_osRasterTable.c_str(),
    3668          20 :                         m_nZoomLevel - k);
    3669          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3670          20 :                     sqlite3_free(pszSQL);
    3671          20 :                     if (eErr != OGRERR_NONE)
    3672             :                     {
    3673           0 :                         SoftRollbackTransaction();
    3674           0 :                         return CE_Failure;
    3675             :                     }
    3676             : 
    3677             :                     pszSQL =
    3678          20 :                         sqlite3_mprintf("UPDATE \"%w\" SET zoom_level = %d "
    3679             :                                         "WHERE zoom_level = %d",
    3680             :                                         m_osRasterTable.c_str(),
    3681          20 :                                         m_nZoomLevel - k + 1, m_nZoomLevel - k);
    3682          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3683          20 :                     sqlite3_free(pszSQL);
    3684          20 :                     if (eErr != OGRERR_NONE)
    3685             :                     {
    3686           0 :                         SoftRollbackTransaction();
    3687           0 :                         return CE_Failure;
    3688             :                     }
    3689             :                 }
    3690             : 
    3691           4 :                 double dfGDALMinX = m_gt[0];
    3692           4 :                 double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3693           4 :                 double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3694           4 :                 double dfGDALMaxY = m_gt[3];
    3695           4 :                 double dfPixelXSizeZoomLevel = m_gt[1] * nOvFactor;
    3696           4 :                 double dfPixelYSizeZoomLevel = fabs(m_gt[5]) * nOvFactor;
    3697             :                 int nTileWidth, nTileHeight;
    3698           4 :                 GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3699           4 :                 int nTileMatrixWidth = DIV_ROUND_UP(nOvXSize, nTileWidth);
    3700           4 :                 int nTileMatrixHeight = DIV_ROUND_UP(nOvYSize, nTileHeight);
    3701           4 :                 pszSQL = sqlite3_mprintf(
    3702             :                     "INSERT INTO gpkg_tile_matrix "
    3703             :                     "(table_name,zoom_level,matrix_width,matrix_height,tile_"
    3704             :                     "width,tile_height,pixel_x_size,pixel_y_size) VALUES "
    3705             :                     "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3706             :                     m_osRasterTable.c_str(), nNewZoomLevel, nTileMatrixWidth,
    3707             :                     nTileMatrixHeight, nTileWidth, nTileHeight,
    3708             :                     dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel);
    3709           4 :                 eErr = SQLCommand(hDB, pszSQL);
    3710           4 :                 sqlite3_free(pszSQL);
    3711           4 :                 if (eErr != OGRERR_NONE)
    3712             :                 {
    3713           0 :                     SoftRollbackTransaction();
    3714           0 :                     return CE_Failure;
    3715             :                 }
    3716             : 
    3717           4 :                 SoftCommitTransaction();
    3718             : 
    3719           4 :                 m_nZoomLevel++; /* this change our zoom level as well as
    3720             :                                    previous overviews */
    3721          20 :                 for (int k = 0; k < jCandidate; k++)
    3722          16 :                     m_apoOverviewDS[k]->m_nZoomLevel++;
    3723             : 
    3724           4 :                 auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3725           4 :                 poOvrDS->ShareLockWithParentDataset(this);
    3726           4 :                 poOvrDS->InitRaster(
    3727             :                     this, m_osRasterTable, nNewZoomLevel, nBands, m_dfTMSMinX,
    3728             :                     m_dfTMSMaxY, dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel,
    3729             :                     nTileWidth, nTileHeight, nTileMatrixWidth,
    3730             :                     nTileMatrixHeight, dfGDALMinX, dfGDALMinY, dfGDALMaxX,
    3731             :                     dfGDALMaxY);
    3732           4 :                 m_apoOverviewDS.insert(m_apoOverviewDS.begin() + jCandidate,
    3733           8 :                                        std::move(poOvrDS));
    3734             :             }
    3735             :         }
    3736             :     }
    3737             : 
    3738             :     GDALRasterBand ***papapoOverviewBands = static_cast<GDALRasterBand ***>(
    3739          13 :         CPLCalloc(sizeof(GDALRasterBand **), nBands));
    3740          13 :     CPLErr eErr = CE_None;
    3741          49 :     for (int iBand = 0; eErr == CE_None && iBand < nBands; iBand++)
    3742             :     {
    3743          72 :         papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
    3744          36 :             CPLCalloc(sizeof(GDALRasterBand *), nOverviews));
    3745          36 :         int iCurOverview = 0;
    3746         185 :         for (int i = 0; i < nOverviews; i++)
    3747             :         {
    3748         149 :             bool bFound = false;
    3749         724 :             for (const auto &poODS : m_apoOverviewDS)
    3750             :             {
    3751             :                 const int nOvFactor =
    3752         724 :                     static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3753             : 
    3754         724 :                 if (nOvFactor == panOverviewList[i])
    3755             :                 {
    3756         298 :                     papapoOverviewBands[iBand][iCurOverview] =
    3757         149 :                         poODS->GetRasterBand(iBand + 1);
    3758         149 :                     iCurOverview++;
    3759         149 :                     bFound = true;
    3760         149 :                     break;
    3761             :                 }
    3762             :             }
    3763         149 :             if (!bFound)
    3764             :             {
    3765           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3766             :                          "Could not find dataset corresponding to ov factor %d",
    3767           0 :                          panOverviewList[i]);
    3768           0 :                 eErr = CE_Failure;
    3769             :             }
    3770             :         }
    3771          36 :         if (eErr == CE_None)
    3772             :         {
    3773          36 :             CPLAssert(iCurOverview == nOverviews);
    3774             :         }
    3775             :     }
    3776             : 
    3777          13 :     if (eErr == CE_None)
    3778          13 :         eErr = GDALRegenerateOverviewsMultiBand(
    3779          13 :             nBands, papoBands, nOverviews, papapoOverviewBands, pszResampling,
    3780             :             pfnProgress, pProgressData, papszOptions);
    3781             : 
    3782          49 :     for (int iBand = 0; iBand < nBands; iBand++)
    3783             :     {
    3784          36 :         CPLFree(papapoOverviewBands[iBand]);
    3785             :     }
    3786          13 :     CPLFree(papapoOverviewBands);
    3787             : 
    3788          13 :     return eErr;
    3789             : }
    3790             : 
    3791             : /************************************************************************/
    3792             : /*                            GetFileList()                             */
    3793             : /************************************************************************/
    3794             : 
    3795          38 : char **GDALGeoPackageDataset::GetFileList()
    3796             : {
    3797          38 :     TryLoadXML();
    3798          38 :     return GDALPamDataset::GetFileList();
    3799             : }
    3800             : 
    3801             : /************************************************************************/
    3802             : /*                       GetMetadataDomainList()                        */
    3803             : /************************************************************************/
    3804             : 
    3805          47 : char **GDALGeoPackageDataset::GetMetadataDomainList()
    3806             : {
    3807          47 :     GetMetadata();
    3808          47 :     if (!m_osRasterTable.empty())
    3809           5 :         GetMetadata("GEOPACKAGE");
    3810          47 :     return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
    3811          47 :                                    TRUE, "SUBDATASETS", nullptr);
    3812             : }
    3813             : 
    3814             : /************************************************************************/
    3815             : /*                        CheckMetadataDomain()                         */
    3816             : /************************************************************************/
    3817             : 
    3818        6417 : const char *GDALGeoPackageDataset::CheckMetadataDomain(const char *pszDomain)
    3819             : {
    3820        6603 :     if (pszDomain != nullptr && EQUAL(pszDomain, "GEOPACKAGE") &&
    3821         186 :         m_osRasterTable.empty())
    3822             :     {
    3823           4 :         CPLError(
    3824             :             CE_Warning, CPLE_IllegalArg,
    3825             :             "Using GEOPACKAGE for a non-raster geopackage is not supported. "
    3826             :             "Using default domain instead");
    3827           4 :         return nullptr;
    3828             :     }
    3829        6413 :     return pszDomain;
    3830             : }
    3831             : 
    3832             : /************************************************************************/
    3833             : /*                         HasMetadataTables()                          */
    3834             : /************************************************************************/
    3835             : 
    3836        6125 : bool GDALGeoPackageDataset::HasMetadataTables() const
    3837             : {
    3838        6125 :     if (m_nHasMetadataTables < 0)
    3839             :     {
    3840             :         const int nCount =
    3841        2354 :             SQLGetInteger(hDB,
    3842             :                           "SELECT COUNT(*) FROM sqlite_master WHERE name IN "
    3843             :                           "('gpkg_metadata', 'gpkg_metadata_reference') "
    3844             :                           "AND type IN ('table', 'view')",
    3845             :                           nullptr);
    3846        2354 :         m_nHasMetadataTables = nCount == 2;
    3847             :     }
    3848        6125 :     return CPL_TO_BOOL(m_nHasMetadataTables);
    3849             : }
    3850             : 
    3851             : /************************************************************************/
    3852             : /*                        HasDataColumnsTable()                         */
    3853             : /************************************************************************/
    3854             : 
    3855        1362 : bool GDALGeoPackageDataset::HasDataColumnsTable() const
    3856             : {
    3857        2724 :     const int nCount = SQLGetInteger(
    3858        1362 :         hDB,
    3859             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_data_columns'"
    3860             :         "AND type IN ('table', 'view')",
    3861             :         nullptr);
    3862        1362 :     return nCount == 1;
    3863             : }
    3864             : 
    3865             : /************************************************************************/
    3866             : /*                   HasDataColumnConstraintsTable()                    */
    3867             : /************************************************************************/
    3868             : 
    3869         168 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTable() const
    3870             : {
    3871         168 :     const int nCount = SQLGetInteger(hDB,
    3872             :                                      "SELECT 1 FROM sqlite_master WHERE name = "
    3873             :                                      "'gpkg_data_column_constraints'"
    3874             :                                      "AND type IN ('table', 'view')",
    3875             :                                      nullptr);
    3876         168 :     return nCount == 1;
    3877             : }
    3878             : 
    3879             : /************************************************************************/
    3880             : /*               HasDataColumnConstraintsTableGPKG_1_0()                */
    3881             : /************************************************************************/
    3882             : 
    3883         111 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTableGPKG_1_0() const
    3884             : {
    3885         111 :     if (m_nApplicationId != GP10_APPLICATION_ID)
    3886         109 :         return false;
    3887             :     // In GPKG 1.0, the columns were named minIsInclusive, maxIsInclusive
    3888             :     // They were changed in 1.1 to min_is_inclusive, max_is_inclusive
    3889           2 :     bool bRet = false;
    3890           2 :     sqlite3_stmt *hSQLStmt = nullptr;
    3891           2 :     int rc = sqlite3_prepare_v2(hDB,
    3892             :                                 "SELECT minIsInclusive, maxIsInclusive FROM "
    3893             :                                 "gpkg_data_column_constraints",
    3894             :                                 -1, &hSQLStmt, nullptr);
    3895           2 :     if (rc == SQLITE_OK)
    3896             :     {
    3897           2 :         bRet = true;
    3898           2 :         sqlite3_finalize(hSQLStmt);
    3899             :     }
    3900           2 :     return bRet;
    3901             : }
    3902             : 
    3903             : /************************************************************************/
    3904             : /*      CreateColumnsTableAndColumnConstraintsTablesIfNecessary()       */
    3905             : /************************************************************************/
    3906             : 
    3907          53 : bool GDALGeoPackageDataset::
    3908             :     CreateColumnsTableAndColumnConstraintsTablesIfNecessary()
    3909             : {
    3910          53 :     if (!HasDataColumnsTable())
    3911             :     {
    3912             :         // Geopackage < 1.3 had
    3913             :         // CONSTRAINT fk_gdc_tn FOREIGN KEY (table_name) REFERENCES
    3914             :         // gpkg_contents(table_name) instead of the unique constraint.
    3915          13 :         if (OGRERR_NONE !=
    3916          13 :             SQLCommand(
    3917             :                 GetDB(),
    3918             :                 "CREATE TABLE gpkg_data_columns ("
    3919             :                 "table_name TEXT NOT NULL,"
    3920             :                 "column_name TEXT NOT NULL,"
    3921             :                 "name TEXT,"
    3922             :                 "title TEXT,"
    3923             :                 "description TEXT,"
    3924             :                 "mime_type TEXT,"
    3925             :                 "constraint_name TEXT,"
    3926             :                 "CONSTRAINT pk_gdc PRIMARY KEY (table_name, column_name),"
    3927             :                 "CONSTRAINT gdc_tn UNIQUE (table_name, name));"))
    3928             :         {
    3929           0 :             return false;
    3930             :         }
    3931             :     }
    3932          53 :     if (!HasDataColumnConstraintsTable())
    3933             :     {
    3934          28 :         const char *min_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3935          14 :                                            ? "min_is_inclusive"
    3936             :                                            : "minIsInclusive";
    3937          28 :         const char *max_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3938          14 :                                            ? "max_is_inclusive"
    3939             :                                            : "maxIsInclusive";
    3940             : 
    3941             :         const std::string osSQL(
    3942             :             CPLSPrintf("CREATE TABLE gpkg_data_column_constraints ("
    3943             :                        "constraint_name TEXT NOT NULL,"
    3944             :                        "constraint_type TEXT NOT NULL,"
    3945             :                        "value TEXT,"
    3946             :                        "min NUMERIC,"
    3947             :                        "%s BOOLEAN,"
    3948             :                        "max NUMERIC,"
    3949             :                        "%s BOOLEAN,"
    3950             :                        "description TEXT,"
    3951             :                        "CONSTRAINT gdcc_ntv UNIQUE (constraint_name, "
    3952             :                        "constraint_type, value));",
    3953          14 :                        min_is_inclusive, max_is_inclusive));
    3954          14 :         if (OGRERR_NONE != SQLCommand(GetDB(), osSQL.c_str()))
    3955             :         {
    3956           0 :             return false;
    3957             :         }
    3958             :     }
    3959          53 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    3960             :     {
    3961           0 :         return false;
    3962             :     }
    3963          53 :     if (SQLGetInteger(GetDB(),
    3964             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3965             :                       "table_name = 'gpkg_data_columns'",
    3966          53 :                       nullptr) != 1)
    3967             :     {
    3968          14 :         if (OGRERR_NONE !=
    3969          14 :             SQLCommand(
    3970             :                 GetDB(),
    3971             :                 "INSERT INTO gpkg_extensions "
    3972             :                 "(table_name,column_name,extension_name,definition,scope) "
    3973             :                 "VALUES ('gpkg_data_columns', NULL, 'gpkg_schema', "
    3974             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    3975             :                 "'read-write')"))
    3976             :         {
    3977           0 :             return false;
    3978             :         }
    3979             :     }
    3980          53 :     if (SQLGetInteger(GetDB(),
    3981             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3982             :                       "table_name = 'gpkg_data_column_constraints'",
    3983          53 :                       nullptr) != 1)
    3984             :     {
    3985          14 :         if (OGRERR_NONE !=
    3986          14 :             SQLCommand(
    3987             :                 GetDB(),
    3988             :                 "INSERT INTO gpkg_extensions "
    3989             :                 "(table_name,column_name,extension_name,definition,scope) "
    3990             :                 "VALUES ('gpkg_data_column_constraints', NULL, 'gpkg_schema', "
    3991             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    3992             :                 "'read-write')"))
    3993             :         {
    3994           0 :             return false;
    3995             :         }
    3996             :     }
    3997             : 
    3998          53 :     return true;
    3999             : }
    4000             : 
    4001             : /************************************************************************/
    4002             : /*                      HasGpkgextRelationsTable()                      */
    4003             : /************************************************************************/
    4004             : 
    4005        1395 : bool GDALGeoPackageDataset::HasGpkgextRelationsTable() const
    4006             : {
    4007        2790 :     const int nCount = SQLGetInteger(
    4008        1395 :         hDB,
    4009             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkgext_relations'"
    4010             :         "AND type IN ('table', 'view')",
    4011             :         nullptr);
    4012        1395 :     return nCount == 1;
    4013             : }
    4014             : 
    4015             : /************************************************************************/
    4016             : /*                  CreateRelationsTableIfNecessary()                   */
    4017             : /************************************************************************/
    4018             : 
    4019          11 : bool GDALGeoPackageDataset::CreateRelationsTableIfNecessary()
    4020             : {
    4021          11 :     if (HasGpkgextRelationsTable())
    4022             :     {
    4023           6 :         return true;
    4024             :     }
    4025             : 
    4026           5 :     if (OGRERR_NONE !=
    4027           5 :         SQLCommand(GetDB(), "CREATE TABLE gpkgext_relations ("
    4028             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    4029             :                             "base_table_name TEXT NOT NULL,"
    4030             :                             "base_primary_column TEXT NOT NULL DEFAULT 'id',"
    4031             :                             "related_table_name TEXT NOT NULL,"
    4032             :                             "related_primary_column TEXT NOT NULL DEFAULT 'id',"
    4033             :                             "relation_name TEXT NOT NULL,"
    4034             :                             "mapping_table_name TEXT NOT NULL UNIQUE);"))
    4035             :     {
    4036           0 :         return false;
    4037             :     }
    4038             : 
    4039           5 :     return true;
    4040             : }
    4041             : 
    4042             : /************************************************************************/
    4043             : /*                         HasQGISLayerStyles()                         */
    4044             : /************************************************************************/
    4045             : 
    4046          11 : bool GDALGeoPackageDataset::HasQGISLayerStyles() const
    4047             : {
    4048             :     // QGIS layer_styles extension:
    4049             :     // https://github.com/pka/qgpkg/blob/master/qgis_geopackage_extension.md
    4050          11 :     bool bRet = false;
    4051             :     const int nCount =
    4052          11 :         SQLGetInteger(hDB,
    4053             :                       "SELECT 1 FROM sqlite_master WHERE name = 'layer_styles'"
    4054             :                       "AND type = 'table'",
    4055             :                       nullptr);
    4056          11 :     if (nCount == 1)
    4057             :     {
    4058           1 :         sqlite3_stmt *hSQLStmt = nullptr;
    4059           2 :         int rc = sqlite3_prepare_v2(
    4060           1 :             hDB, "SELECT f_table_name, f_geometry_column FROM layer_styles", -1,
    4061             :             &hSQLStmt, nullptr);
    4062           1 :         if (rc == SQLITE_OK)
    4063             :         {
    4064           1 :             bRet = true;
    4065           1 :             sqlite3_finalize(hSQLStmt);
    4066             :         }
    4067             :     }
    4068          11 :     return bRet;
    4069             : }
    4070             : 
    4071             : /************************************************************************/
    4072             : /*                            GetMetadata()                             */
    4073             : /************************************************************************/
    4074             : 
    4075        4210 : CSLConstList GDALGeoPackageDataset::GetMetadata(const char *pszDomain)
    4076             : 
    4077             : {
    4078        4210 :     pszDomain = CheckMetadataDomain(pszDomain);
    4079        4210 :     if (pszDomain != nullptr && EQUAL(pszDomain, "SUBDATASETS"))
    4080          74 :         return m_aosSubDatasets.List();
    4081             : 
    4082        4136 :     if (m_bHasReadMetadataFromStorage)
    4083        1850 :         return GDALPamDataset::GetMetadata(pszDomain);
    4084             : 
    4085        2286 :     m_bHasReadMetadataFromStorage = true;
    4086             : 
    4087        2286 :     TryLoadXML();
    4088             : 
    4089        2286 :     if (!HasMetadataTables())
    4090        1746 :         return GDALPamDataset::GetMetadata(pszDomain);
    4091             : 
    4092         540 :     char *pszSQL = nullptr;
    4093         540 :     if (!m_osRasterTable.empty())
    4094             :     {
    4095         177 :         pszSQL = sqlite3_mprintf(
    4096             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4097             :             "mdr.reference_scope FROM gpkg_metadata md "
    4098             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4099             :             "WHERE "
    4100             :             "(mdr.reference_scope = 'geopackage' OR "
    4101             :             "(mdr.reference_scope = 'table' AND lower(mdr.table_name) = "
    4102             :             "lower('%q'))) ORDER BY md.id "
    4103             :             "LIMIT 1000",  // to avoid denial of service
    4104             :             m_osRasterTable.c_str());
    4105             :     }
    4106             :     else
    4107             :     {
    4108         363 :         pszSQL = sqlite3_mprintf(
    4109             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4110             :             "mdr.reference_scope FROM gpkg_metadata md "
    4111             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4112             :             "WHERE "
    4113             :             "mdr.reference_scope = 'geopackage' ORDER BY md.id "
    4114             :             "LIMIT 1000"  // to avoid denial of service
    4115             :         );
    4116             :     }
    4117             : 
    4118        1080 :     auto oResult = SQLQuery(hDB, pszSQL);
    4119         540 :     sqlite3_free(pszSQL);
    4120         540 :     if (!oResult)
    4121             :     {
    4122           0 :         return GDALPamDataset::GetMetadata(pszDomain);
    4123             :     }
    4124             : 
    4125         540 :     char **papszMetadata = CSLDuplicate(GDALPamDataset::GetMetadata());
    4126             : 
    4127             :     /* GDAL metadata */
    4128         737 :     for (int i = 0; i < oResult->RowCount(); i++)
    4129             :     {
    4130         197 :         const char *pszMetadata = oResult->GetValue(0, i);
    4131         197 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4132         197 :         const char *pszMimeType = oResult->GetValue(2, i);
    4133         197 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4134         197 :         if (pszMetadata && pszMDStandardURI && pszMimeType &&
    4135         197 :             pszReferenceScope && EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4136         181 :             EQUAL(pszMimeType, "text/xml"))
    4137             :         {
    4138         181 :             CPLXMLNode *psXMLNode = CPLParseXMLString(pszMetadata);
    4139         181 :             if (psXMLNode)
    4140             :             {
    4141         362 :                 GDALMultiDomainMetadata oLocalMDMD;
    4142         181 :                 oLocalMDMD.XMLInit(psXMLNode, FALSE);
    4143         347 :                 if (!m_osRasterTable.empty() &&
    4144         166 :                     EQUAL(pszReferenceScope, "geopackage"))
    4145             :                 {
    4146           6 :                     oMDMD.SetMetadata(oLocalMDMD.GetMetadata(), "GEOPACKAGE");
    4147             :                 }
    4148             :                 else
    4149             :                 {
    4150             :                     papszMetadata =
    4151         175 :                         CSLMerge(papszMetadata, oLocalMDMD.GetMetadata());
    4152         175 :                     CSLConstList papszDomainList = oLocalMDMD.GetDomainList();
    4153         175 :                     CSLConstList papszIter = papszDomainList;
    4154         470 :                     while (papszIter && *papszIter)
    4155             :                     {
    4156         295 :                         if (EQUAL(*papszIter, "IMAGE_STRUCTURE"))
    4157             :                         {
    4158             :                             CSLConstList papszMD =
    4159         133 :                                 oLocalMDMD.GetMetadata(*papszIter);
    4160             :                             const char *pszBAND_COUNT =
    4161         133 :                                 CSLFetchNameValue(papszMD, "BAND_COUNT");
    4162         133 :                             if (pszBAND_COUNT)
    4163         131 :                                 m_nBandCountFromMetadata = atoi(pszBAND_COUNT);
    4164             : 
    4165             :                             const char *pszCOLOR_TABLE =
    4166         133 :                                 CSLFetchNameValue(papszMD, "COLOR_TABLE");
    4167         133 :                             if (pszCOLOR_TABLE)
    4168             :                             {
    4169             :                                 const CPLStringList aosTokens(
    4170             :                                     CSLTokenizeString2(pszCOLOR_TABLE, "{,",
    4171          26 :                                                        0));
    4172          13 :                                 if ((aosTokens.size() % 4) == 0)
    4173             :                                 {
    4174          13 :                                     const int nColors = aosTokens.size() / 4;
    4175             :                                     m_poCTFromMetadata =
    4176          13 :                                         std::make_unique<GDALColorTable>();
    4177        3341 :                                     for (int iColor = 0; iColor < nColors;
    4178             :                                          ++iColor)
    4179             :                                     {
    4180             :                                         GDALColorEntry sEntry;
    4181        3328 :                                         sEntry.c1 = static_cast<short>(
    4182        3328 :                                             atoi(aosTokens[4 * iColor + 0]));
    4183        3328 :                                         sEntry.c2 = static_cast<short>(
    4184        3328 :                                             atoi(aosTokens[4 * iColor + 1]));
    4185        3328 :                                         sEntry.c3 = static_cast<short>(
    4186        3328 :                                             atoi(aosTokens[4 * iColor + 2]));
    4187        3328 :                                         sEntry.c4 = static_cast<short>(
    4188        3328 :                                             atoi(aosTokens[4 * iColor + 3]));
    4189        3328 :                                         m_poCTFromMetadata->SetColorEntry(
    4190             :                                             iColor, &sEntry);
    4191             :                                     }
    4192             :                                 }
    4193             :                             }
    4194             : 
    4195             :                             const char *pszTILE_FORMAT =
    4196         133 :                                 CSLFetchNameValue(papszMD, "TILE_FORMAT");
    4197         133 :                             if (pszTILE_FORMAT)
    4198             :                             {
    4199           8 :                                 m_osTFFromMetadata = pszTILE_FORMAT;
    4200           8 :                                 oMDMD.SetMetadataItem("TILE_FORMAT",
    4201             :                                                       pszTILE_FORMAT,
    4202             :                                                       "IMAGE_STRUCTURE");
    4203             :                             }
    4204             : 
    4205             :                             const char *pszNodataValue =
    4206         133 :                                 CSLFetchNameValue(papszMD, "NODATA_VALUE");
    4207         133 :                             if (pszNodataValue)
    4208             :                             {
    4209           2 :                                 m_osNodataValueFromMetadata = pszNodataValue;
    4210             :                             }
    4211             :                         }
    4212             : 
    4213         162 :                         else if (!EQUAL(*papszIter, "") &&
    4214          18 :                                  !STARTS_WITH(*papszIter, "BAND_"))
    4215             :                         {
    4216          12 :                             oMDMD.SetMetadata(
    4217           6 :                                 oLocalMDMD.GetMetadata(*papszIter), *papszIter);
    4218             :                         }
    4219         295 :                         papszIter++;
    4220             :                     }
    4221             :                 }
    4222         181 :                 CPLDestroyXMLNode(psXMLNode);
    4223             :             }
    4224             :         }
    4225             :     }
    4226             : 
    4227         540 :     GDALPamDataset::SetMetadata(papszMetadata);
    4228         540 :     CSLDestroy(papszMetadata);
    4229         540 :     papszMetadata = nullptr;
    4230             : 
    4231             :     /* Add non-GDAL metadata now */
    4232         540 :     int nNonGDALMDILocal = 1;
    4233         540 :     int nNonGDALMDIGeopackage = 1;
    4234         737 :     for (int i = 0; i < oResult->RowCount(); i++)
    4235             :     {
    4236         197 :         const char *pszMetadata = oResult->GetValue(0, i);
    4237         197 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4238         197 :         const char *pszMimeType = oResult->GetValue(2, i);
    4239         197 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4240         197 :         if (pszMetadata == nullptr || pszMDStandardURI == nullptr ||
    4241         197 :             pszMimeType == nullptr || pszReferenceScope == nullptr)
    4242             :         {
    4243             :             // should not happen as there are NOT NULL constraints
    4244             :             // But a database could lack such NOT NULL constraints or have
    4245             :             // large values that would cause a memory allocation failure.
    4246           0 :             continue;
    4247             :         }
    4248         197 :         int bIsGPKGScope = EQUAL(pszReferenceScope, "geopackage");
    4249         197 :         if (EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4250         181 :             EQUAL(pszMimeType, "text/xml"))
    4251         181 :             continue;
    4252             : 
    4253          16 :         if (!m_osRasterTable.empty() && bIsGPKGScope)
    4254             :         {
    4255           8 :             oMDMD.SetMetadataItem(
    4256             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDIGeopackage),
    4257             :                 pszMetadata, "GEOPACKAGE");
    4258           8 :             nNonGDALMDIGeopackage++;
    4259             :         }
    4260             :         /*else if( strcmp( pszMDStandardURI, "http://www.isotc211.org/2005/gmd"
    4261             :         ) == 0 && strcmp( pszMimeType, "text/xml" ) == 0 )
    4262             :         {
    4263             :             char* apszMD[2];
    4264             :             apszMD[0] = (char*)pszMetadata;
    4265             :             apszMD[1] = NULL;
    4266             :             oMDMD.SetMetadata(apszMD, "xml:MD_Metadata");
    4267             :         }*/
    4268             :         else
    4269             :         {
    4270           8 :             oMDMD.SetMetadataItem(
    4271             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDILocal),
    4272             :                 pszMetadata);
    4273           8 :             nNonGDALMDILocal++;
    4274             :         }
    4275             :     }
    4276             : 
    4277         540 :     return GDALPamDataset::GetMetadata(pszDomain);
    4278             : }
    4279             : 
    4280             : /************************************************************************/
    4281             : /*                           WriteMetadata()                            */
    4282             : /************************************************************************/
    4283             : 
    4284         770 : void GDALGeoPackageDataset::WriteMetadata(
    4285             :     CPLXMLNode *psXMLNode, /* will be destroyed by the method */
    4286             :     const char *pszTableName)
    4287             : {
    4288         770 :     const bool bIsEmpty = (psXMLNode == nullptr);
    4289         770 :     if (!HasMetadataTables())
    4290             :     {
    4291         565 :         if (bIsEmpty || !CreateMetadataTables())
    4292             :         {
    4293         259 :             CPLDestroyXMLNode(psXMLNode);
    4294         259 :             return;
    4295             :         }
    4296             :     }
    4297             : 
    4298         511 :     char *pszXML = nullptr;
    4299         511 :     if (!bIsEmpty)
    4300             :     {
    4301             :         CPLXMLNode *psMasterXMLNode =
    4302         356 :             CPLCreateXMLNode(nullptr, CXT_Element, "GDALMultiDomainMetadata");
    4303         356 :         psMasterXMLNode->psChild = psXMLNode;
    4304         356 :         pszXML = CPLSerializeXMLTree(psMasterXMLNode);
    4305         356 :         CPLDestroyXMLNode(psMasterXMLNode);
    4306             :     }
    4307             :     // cppcheck-suppress uselessAssignmentPtrArg
    4308         511 :     psXMLNode = nullptr;
    4309             : 
    4310         511 :     char *pszSQL = nullptr;
    4311         511 :     if (pszTableName && pszTableName[0] != '\0')
    4312             :     {
    4313         364 :         pszSQL = sqlite3_mprintf(
    4314             :             "SELECT md.id FROM gpkg_metadata md "
    4315             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4316             :             "WHERE md.md_scope = 'dataset' AND "
    4317             :             "md.md_standard_uri='http://gdal.org' "
    4318             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = 'table' AND "
    4319             :             "lower(mdr.table_name) = lower('%q')",
    4320             :             pszTableName);
    4321             :     }
    4322             :     else
    4323             :     {
    4324         147 :         pszSQL = sqlite3_mprintf(
    4325             :             "SELECT md.id FROM gpkg_metadata md "
    4326             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4327             :             "WHERE md.md_scope = 'dataset' AND "
    4328             :             "md.md_standard_uri='http://gdal.org' "
    4329             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = "
    4330             :             "'geopackage'");
    4331             :     }
    4332             :     OGRErr err;
    4333         511 :     int mdId = SQLGetInteger(hDB, pszSQL, &err);
    4334         511 :     if (err != OGRERR_NONE)
    4335         478 :         mdId = -1;
    4336         511 :     sqlite3_free(pszSQL);
    4337             : 
    4338         511 :     if (bIsEmpty)
    4339             :     {
    4340         155 :         if (mdId >= 0)
    4341             :         {
    4342           6 :             SQLCommand(
    4343             :                 hDB,
    4344             :                 CPLSPrintf(
    4345             :                     "DELETE FROM gpkg_metadata_reference WHERE md_file_id = %d",
    4346             :                     mdId));
    4347           6 :             SQLCommand(
    4348             :                 hDB,
    4349             :                 CPLSPrintf("DELETE FROM gpkg_metadata WHERE id = %d", mdId));
    4350             :         }
    4351             :     }
    4352             :     else
    4353             :     {
    4354         356 :         if (mdId >= 0)
    4355             :         {
    4356          27 :             pszSQL = sqlite3_mprintf(
    4357             :                 "UPDATE gpkg_metadata SET metadata = '%q' WHERE id = %d",
    4358             :                 pszXML, mdId);
    4359             :         }
    4360             :         else
    4361             :         {
    4362             :             pszSQL =
    4363         329 :                 sqlite3_mprintf("INSERT INTO gpkg_metadata (md_scope, "
    4364             :                                 "md_standard_uri, mime_type, metadata) VALUES "
    4365             :                                 "('dataset','http://gdal.org','text/xml','%q')",
    4366             :                                 pszXML);
    4367             :         }
    4368         356 :         SQLCommand(hDB, pszSQL);
    4369         356 :         sqlite3_free(pszSQL);
    4370             : 
    4371         356 :         CPLFree(pszXML);
    4372             : 
    4373         356 :         if (mdId < 0)
    4374             :         {
    4375         329 :             const sqlite_int64 nFID = sqlite3_last_insert_rowid(hDB);
    4376         329 :             if (pszTableName != nullptr && pszTableName[0] != '\0')
    4377             :             {
    4378         317 :                 pszSQL = sqlite3_mprintf(
    4379             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4380             :                     "table_name, timestamp, md_file_id) VALUES "
    4381             :                     "('table', '%q', %s, %d)",
    4382         634 :                     pszTableName, GetCurrentDateEscapedSQL().c_str(),
    4383             :                     static_cast<int>(nFID));
    4384             :             }
    4385             :             else
    4386             :             {
    4387          12 :                 pszSQL = sqlite3_mprintf(
    4388             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4389             :                     "timestamp, md_file_id) VALUES "
    4390             :                     "('geopackage', %s, %d)",
    4391          24 :                     GetCurrentDateEscapedSQL().c_str(), static_cast<int>(nFID));
    4392             :             }
    4393             :         }
    4394             :         else
    4395             :         {
    4396          27 :             pszSQL = sqlite3_mprintf("UPDATE gpkg_metadata_reference SET "
    4397             :                                      "timestamp = %s WHERE md_file_id = %d",
    4398          54 :                                      GetCurrentDateEscapedSQL().c_str(), mdId);
    4399             :         }
    4400         356 :         SQLCommand(hDB, pszSQL);
    4401         356 :         sqlite3_free(pszSQL);
    4402             :     }
    4403             : }
    4404             : 
    4405             : /************************************************************************/
    4406             : /*                        CreateMetadataTables()                        */
    4407             : /************************************************************************/
    4408             : 
    4409         325 : bool GDALGeoPackageDataset::CreateMetadataTables()
    4410             : {
    4411             :     const bool bCreateTriggers =
    4412         325 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "NO"));
    4413             : 
    4414             :     /* From C.10. gpkg_metadata Table 35. gpkg_metadata Table Definition SQL  */
    4415             :     CPLString osSQL = "CREATE TABLE gpkg_metadata ("
    4416             :                       "id INTEGER CONSTRAINT m_pk PRIMARY KEY ASC NOT NULL,"
    4417             :                       "md_scope TEXT NOT NULL DEFAULT 'dataset',"
    4418             :                       "md_standard_uri TEXT NOT NULL,"
    4419             :                       "mime_type TEXT NOT NULL DEFAULT 'text/xml',"
    4420             :                       "metadata TEXT NOT NULL DEFAULT ''"
    4421         650 :                       ")";
    4422             : 
    4423             :     /* From D.2. metadata Table 40. metadata Trigger Definition SQL  */
    4424         325 :     const char *pszMetadataTriggers =
    4425             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_insert' "
    4426             :         "BEFORE INSERT ON 'gpkg_metadata' "
    4427             :         "FOR EACH ROW BEGIN "
    4428             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata violates "
    4429             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4430             :         "collectionSession | series | dataset | featureType | feature | "
    4431             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4432             :         "taxonomy software | service | collectionHardware | "
    4433             :         "nonGeographicDataset | dimensionGroup') "
    4434             :         "WHERE NOT(NEW.md_scope IN "
    4435             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4436             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4437             :         "'catalogue','schema','taxonomy','software','service', "
    4438             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4439             :         "END; "
    4440             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_update' "
    4441             :         "BEFORE UPDATE OF 'md_scope' ON 'gpkg_metadata' "
    4442             :         "FOR EACH ROW BEGIN "
    4443             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata violates "
    4444             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4445             :         "collectionSession | series | dataset | featureType | feature | "
    4446             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4447             :         "taxonomy software | service | collectionHardware | "
    4448             :         "nonGeographicDataset | dimensionGroup') "
    4449             :         "WHERE NOT(NEW.md_scope IN "
    4450             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4451             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4452             :         "'catalogue','schema','taxonomy','software','service', "
    4453             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4454             :         "END";
    4455         325 :     if (bCreateTriggers)
    4456             :     {
    4457           0 :         osSQL += ";";
    4458           0 :         osSQL += pszMetadataTriggers;
    4459             :     }
    4460             : 
    4461             :     /* From C.11. gpkg_metadata_reference Table 36. gpkg_metadata_reference
    4462             :      * Table Definition SQL */
    4463             :     osSQL += ";"
    4464             :              "CREATE TABLE gpkg_metadata_reference ("
    4465             :              "reference_scope TEXT NOT NULL,"
    4466             :              "table_name TEXT,"
    4467             :              "column_name TEXT,"
    4468             :              "row_id_value INTEGER,"
    4469             :              "timestamp DATETIME NOT NULL DEFAULT "
    4470             :              "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    4471             :              "md_file_id INTEGER NOT NULL,"
    4472             :              "md_parent_id INTEGER,"
    4473             :              "CONSTRAINT crmr_mfi_fk FOREIGN KEY (md_file_id) REFERENCES "
    4474             :              "gpkg_metadata(id),"
    4475             :              "CONSTRAINT crmr_mpi_fk FOREIGN KEY (md_parent_id) REFERENCES "
    4476             :              "gpkg_metadata(id)"
    4477         325 :              ")";
    4478             : 
    4479             :     /* From D.3. metadata_reference Table 41. gpkg_metadata_reference Trigger
    4480             :      * Definition SQL   */
    4481         325 :     const char *pszMetadataReferenceTriggers =
    4482             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_insert' "
    4483             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4484             :         "FOR EACH ROW BEGIN "
    4485             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4486             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4487             :         "table\", \"column\", \"row\", \"row/col\"') "
    4488             :         "WHERE NOT NEW.reference_scope IN "
    4489             :         "('geopackage','table','column','row','row/col'); "
    4490             :         "END; "
    4491             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_update' "
    4492             :         "BEFORE UPDATE OF 'reference_scope' ON 'gpkg_metadata_reference' "
    4493             :         "FOR EACH ROW BEGIN "
    4494             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4495             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4496             :         "\"table\", \"column\", \"row\", \"row/col\"') "
    4497             :         "WHERE NOT NEW.reference_scope IN "
    4498             :         "('geopackage','table','column','row','row/col'); "
    4499             :         "END; "
    4500             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_insert' "
    4501             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4502             :         "FOR EACH ROW BEGIN "
    4503             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4504             :         "violates constraint: column name must be NULL when reference_scope "
    4505             :         "is \"geopackage\", \"table\" or \"row\"') "
    4506             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4507             :         "AND NEW.column_name IS NOT NULL); "
    4508             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4509             :         "violates constraint: column name must be defined for the specified "
    4510             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4511             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4512             :         "AND NOT NEW.table_name IN ( "
    4513             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4514             :         "AND name = NEW.table_name "
    4515             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4516             :         "END; "
    4517             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_update' "
    4518             :         "BEFORE UPDATE OF column_name ON 'gpkg_metadata_reference' "
    4519             :         "FOR EACH ROW BEGIN "
    4520             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4521             :         "violates constraint: column name must be NULL when reference_scope "
    4522             :         "is \"geopackage\", \"table\" or \"row\"') "
    4523             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4524             :         "AND NEW.column_name IS NOT NULL); "
    4525             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4526             :         "violates constraint: column name must be defined for the specified "
    4527             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4528             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4529             :         "AND NOT NEW.table_name IN ( "
    4530             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4531             :         "AND name = NEW.table_name "
    4532             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4533             :         "END; "
    4534             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_insert' "
    4535             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4536             :         "FOR EACH ROW BEGIN "
    4537             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4538             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4539             :         "is \"geopackage\", \"table\" or \"column\"') "
    4540             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4541             :         "AND NEW.row_id_value IS NOT NULL; "
    4542             :         "END; "
    4543             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_update' "
    4544             :         "BEFORE UPDATE OF 'row_id_value' ON 'gpkg_metadata_reference' "
    4545             :         "FOR EACH ROW BEGIN "
    4546             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4547             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4548             :         "is \"geopackage\", \"table\" or \"column\"') "
    4549             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4550             :         "AND NEW.row_id_value IS NOT NULL; "
    4551             :         "END; "
    4552             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_insert' "
    4553             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4554             :         "FOR EACH ROW BEGIN "
    4555             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4556             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4557             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4558             :         "WHERE NOT (NEW.timestamp GLOB "
    4559             :         "'[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-"
    4560             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4561             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4562             :         "END; "
    4563             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_update' "
    4564             :         "BEFORE UPDATE OF 'timestamp' ON 'gpkg_metadata_reference' "
    4565             :         "FOR EACH ROW BEGIN "
    4566             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4567             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4568             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4569             :         "WHERE NOT (NEW.timestamp GLOB "
    4570             :         "'[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-"
    4571             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4572             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4573             :         "END";
    4574         325 :     if (bCreateTriggers)
    4575             :     {
    4576           0 :         osSQL += ";";
    4577           0 :         osSQL += pszMetadataReferenceTriggers;
    4578             :     }
    4579             : 
    4580         325 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    4581           2 :         return false;
    4582             : 
    4583         323 :     osSQL += ";";
    4584             :     osSQL += "INSERT INTO gpkg_extensions "
    4585             :              "(table_name, column_name, extension_name, definition, scope) "
    4586             :              "VALUES "
    4587             :              "('gpkg_metadata', NULL, 'gpkg_metadata', "
    4588             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4589         323 :              "'read-write')";
    4590             : 
    4591         323 :     osSQL += ";";
    4592             :     osSQL += "INSERT INTO gpkg_extensions "
    4593             :              "(table_name, column_name, extension_name, definition, scope) "
    4594             :              "VALUES "
    4595             :              "('gpkg_metadata_reference', NULL, 'gpkg_metadata', "
    4596             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4597         323 :              "'read-write')";
    4598             : 
    4599         323 :     const bool bOK = SQLCommand(hDB, osSQL) == OGRERR_NONE;
    4600         323 :     m_nHasMetadataTables = bOK;
    4601         323 :     return bOK;
    4602             : }
    4603             : 
    4604             : /************************************************************************/
    4605             : /*                           FlushMetadata()                            */
    4606             : /************************************************************************/
    4607             : 
    4608        9165 : void GDALGeoPackageDataset::FlushMetadata()
    4609             : {
    4610        9165 :     if (!m_bMetadataDirty || m_poParentDS != nullptr ||
    4611         385 :         m_nCreateMetadataTables == FALSE)
    4612        8786 :         return;
    4613         379 :     m_bMetadataDirty = false;
    4614             : 
    4615         379 :     if (eAccess == GA_ReadOnly)
    4616             :     {
    4617           3 :         return;
    4618             :     }
    4619             : 
    4620         376 :     bool bCanWriteAreaOrPoint =
    4621         750 :         !m_bGridCellEncodingAsCO &&
    4622         374 :         (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT);
    4623         376 :     if (!m_osRasterTable.empty())
    4624             :     {
    4625             :         const char *pszIdentifier =
    4626         145 :             GDALGeoPackageDataset::GetMetadataItem("IDENTIFIER");
    4627             :         const char *pszDescription =
    4628         145 :             GDALGeoPackageDataset::GetMetadataItem("DESCRIPTION");
    4629         174 :         if (!m_bIdentifierAsCO && pszIdentifier != nullptr &&
    4630          29 :             pszIdentifier != m_osIdentifier)
    4631             :         {
    4632          14 :             m_osIdentifier = pszIdentifier;
    4633             :             char *pszSQL =
    4634          14 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4635             :                                 "WHERE lower(table_name) = lower('%q')",
    4636             :                                 pszIdentifier, m_osRasterTable.c_str());
    4637          14 :             SQLCommand(hDB, pszSQL);
    4638          14 :             sqlite3_free(pszSQL);
    4639             :         }
    4640         152 :         if (!m_bDescriptionAsCO && pszDescription != nullptr &&
    4641           7 :             pszDescription != m_osDescription)
    4642             :         {
    4643           7 :             m_osDescription = pszDescription;
    4644             :             char *pszSQL =
    4645           7 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4646             :                                 "WHERE lower(table_name) = lower('%q')",
    4647             :                                 pszDescription, m_osRasterTable.c_str());
    4648           7 :             SQLCommand(hDB, pszSQL);
    4649           7 :             sqlite3_free(pszSQL);
    4650             :         }
    4651         145 :         if (bCanWriteAreaOrPoint)
    4652             :         {
    4653             :             const char *pszAreaOrPoint =
    4654          28 :                 GDALGeoPackageDataset::GetMetadataItem(GDALMD_AREA_OR_POINT);
    4655          28 :             if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_AREA))
    4656             :             {
    4657          23 :                 bCanWriteAreaOrPoint = false;
    4658          23 :                 char *pszSQL = sqlite3_mprintf(
    4659             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4660             :                     "grid_cell_encoding = 'grid-value-is-area' WHERE "
    4661             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4662             :                     m_osRasterTable.c_str());
    4663          23 :                 SQLCommand(hDB, pszSQL);
    4664          23 :                 sqlite3_free(pszSQL);
    4665             :             }
    4666           5 :             else if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_POINT))
    4667             :             {
    4668           1 :                 bCanWriteAreaOrPoint = false;
    4669           1 :                 char *pszSQL = sqlite3_mprintf(
    4670             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4671             :                     "grid_cell_encoding = 'grid-value-is-center' WHERE "
    4672             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4673             :                     m_osRasterTable.c_str());
    4674           1 :                 SQLCommand(hDB, pszSQL);
    4675           1 :                 sqlite3_free(pszSQL);
    4676             :             }
    4677             :         }
    4678             :     }
    4679             : 
    4680         376 :     char **papszMDDup = nullptr;
    4681         206 :     for (const char *pszKeyValue :
    4682         788 :          cpl::Iterate(GDALGeoPackageDataset::GetMetadata()))
    4683             :     {
    4684         206 :         if (STARTS_WITH_CI(pszKeyValue, "IDENTIFIER="))
    4685          29 :             continue;
    4686         177 :         if (STARTS_WITH_CI(pszKeyValue, "DESCRIPTION="))
    4687           8 :             continue;
    4688         169 :         if (STARTS_WITH_CI(pszKeyValue, "ZOOM_LEVEL="))
    4689          14 :             continue;
    4690         155 :         if (STARTS_WITH_CI(pszKeyValue, "GPKG_METADATA_ITEM_"))
    4691           4 :             continue;
    4692         151 :         if ((m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT) &&
    4693          29 :             !bCanWriteAreaOrPoint &&
    4694          26 :             STARTS_WITH_CI(pszKeyValue, GDALMD_AREA_OR_POINT))
    4695             :         {
    4696          26 :             continue;
    4697             :         }
    4698         125 :         papszMDDup = CSLInsertString(papszMDDup, -1, pszKeyValue);
    4699             :     }
    4700             : 
    4701         376 :     CPLXMLNode *psXMLNode = nullptr;
    4702             :     {
    4703         376 :         GDALMultiDomainMetadata oLocalMDMD;
    4704         376 :         CSLConstList papszDomainList = oMDMD.GetDomainList();
    4705         376 :         CSLConstList papszIter = papszDomainList;
    4706         376 :         oLocalMDMD.SetMetadata(papszMDDup);
    4707         707 :         while (papszIter && *papszIter)
    4708             :         {
    4709         331 :             if (!EQUAL(*papszIter, "") &&
    4710         160 :                 !EQUAL(*papszIter, "IMAGE_STRUCTURE") &&
    4711          15 :                 !EQUAL(*papszIter, "GEOPACKAGE"))
    4712             :             {
    4713           8 :                 oLocalMDMD.SetMetadata(oMDMD.GetMetadata(*papszIter),
    4714             :                                        *papszIter);
    4715             :             }
    4716         331 :             papszIter++;
    4717             :         }
    4718         376 :         if (m_nBandCountFromMetadata > 0)
    4719             :         {
    4720          75 :             oLocalMDMD.SetMetadataItem(
    4721             :                 "BAND_COUNT", CPLSPrintf("%d", m_nBandCountFromMetadata),
    4722             :                 "IMAGE_STRUCTURE");
    4723          75 :             if (nBands == 1)
    4724             :             {
    4725          51 :                 const auto poCT = GetRasterBand(1)->GetColorTable();
    4726          51 :                 if (poCT)
    4727             :                 {
    4728          16 :                     std::string osVal("{");
    4729           8 :                     const int nColorCount = poCT->GetColorEntryCount();
    4730        2056 :                     for (int i = 0; i < nColorCount; ++i)
    4731             :                     {
    4732        2048 :                         if (i > 0)
    4733        2040 :                             osVal += ',';
    4734        2048 :                         const GDALColorEntry *psEntry = poCT->GetColorEntry(i);
    4735             :                         osVal +=
    4736        2048 :                             CPLSPrintf("{%d,%d,%d,%d}", psEntry->c1,
    4737        2048 :                                        psEntry->c2, psEntry->c3, psEntry->c4);
    4738             :                     }
    4739           8 :                     osVal += '}';
    4740           8 :                     oLocalMDMD.SetMetadataItem("COLOR_TABLE", osVal.c_str(),
    4741             :                                                "IMAGE_STRUCTURE");
    4742             :                 }
    4743             :             }
    4744          75 :             if (nBands == 1)
    4745             :             {
    4746          51 :                 const char *pszTILE_FORMAT = nullptr;
    4747          51 :                 switch (m_eTF)
    4748             :                 {
    4749           0 :                     case GPKG_TF_PNG_JPEG:
    4750           0 :                         pszTILE_FORMAT = "JPEG_PNG";
    4751           0 :                         break;
    4752          45 :                     case GPKG_TF_PNG:
    4753          45 :                         break;
    4754           0 :                     case GPKG_TF_PNG8:
    4755           0 :                         pszTILE_FORMAT = "PNG8";
    4756           0 :                         break;
    4757           3 :                     case GPKG_TF_JPEG:
    4758           3 :                         pszTILE_FORMAT = "JPEG";
    4759           3 :                         break;
    4760           3 :                     case GPKG_TF_WEBP:
    4761           3 :                         pszTILE_FORMAT = "WEBP";
    4762           3 :                         break;
    4763           0 :                     case GPKG_TF_PNG_16BIT:
    4764           0 :                         break;
    4765           0 :                     case GPKG_TF_TIFF_32BIT_FLOAT:
    4766           0 :                         break;
    4767             :                 }
    4768          51 :                 if (pszTILE_FORMAT)
    4769           6 :                     oLocalMDMD.SetMetadataItem("TILE_FORMAT", pszTILE_FORMAT,
    4770             :                                                "IMAGE_STRUCTURE");
    4771             :             }
    4772             :         }
    4773         521 :         if (GetRasterCount() > 0 &&
    4774         145 :             GetRasterBand(1)->GetRasterDataType() == GDT_UInt8)
    4775             :         {
    4776         115 :             int bHasNoData = FALSE;
    4777             :             const double dfNoDataValue =
    4778         115 :                 GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    4779         115 :             if (bHasNoData)
    4780             :             {
    4781           3 :                 oLocalMDMD.SetMetadataItem("NODATA_VALUE",
    4782             :                                            CPLSPrintf("%.17g", dfNoDataValue),
    4783             :                                            "IMAGE_STRUCTURE");
    4784             :             }
    4785             :         }
    4786         626 :         for (int i = 1; i <= GetRasterCount(); ++i)
    4787             :         {
    4788             :             auto poBand =
    4789         250 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    4790         250 :             poBand->AddImplicitStatistics(false);
    4791         250 :             CSLConstList papszMD = GetRasterBand(i)->GetMetadata();
    4792         250 :             poBand->AddImplicitStatistics(true);
    4793         250 :             if (papszMD)
    4794             :             {
    4795          15 :                 oLocalMDMD.SetMetadata(papszMD, CPLSPrintf("BAND_%d", i));
    4796             :             }
    4797             :         }
    4798         376 :         psXMLNode = oLocalMDMD.Serialize();
    4799             :     }
    4800             : 
    4801         376 :     CSLDestroy(papszMDDup);
    4802         376 :     papszMDDup = nullptr;
    4803             : 
    4804         376 :     WriteMetadata(psXMLNode, m_osRasterTable.c_str());
    4805             : 
    4806         376 :     if (!m_osRasterTable.empty())
    4807             :     {
    4808             :         CSLConstList papszGeopackageMD =
    4809         145 :             GDALGeoPackageDataset::GetMetadata("GEOPACKAGE");
    4810             : 
    4811         145 :         papszMDDup = nullptr;
    4812         145 :         for (CSLConstList papszIter = papszGeopackageMD;
    4813         154 :              papszIter && *papszIter; ++papszIter)
    4814             :         {
    4815           9 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4816             :         }
    4817             : 
    4818         290 :         GDALMultiDomainMetadata oLocalMDMD;
    4819         145 :         oLocalMDMD.SetMetadata(papszMDDup);
    4820         145 :         CSLDestroy(papszMDDup);
    4821         145 :         papszMDDup = nullptr;
    4822         145 :         psXMLNode = oLocalMDMD.Serialize();
    4823             : 
    4824         145 :         WriteMetadata(psXMLNode, nullptr);
    4825             :     }
    4826             : 
    4827         625 :     for (auto &poLayer : m_apoLayers)
    4828             :     {
    4829         249 :         const char *pszIdentifier = poLayer->GetMetadataItem("IDENTIFIER");
    4830         249 :         const char *pszDescription = poLayer->GetMetadataItem("DESCRIPTION");
    4831         249 :         if (pszIdentifier != nullptr)
    4832             :         {
    4833             :             char *pszSQL =
    4834           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4835             :                                 "WHERE lower(table_name) = lower('%q')",
    4836             :                                 pszIdentifier, poLayer->GetName());
    4837           3 :             SQLCommand(hDB, pszSQL);
    4838           3 :             sqlite3_free(pszSQL);
    4839             :         }
    4840         249 :         if (pszDescription != nullptr)
    4841             :         {
    4842             :             char *pszSQL =
    4843           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4844             :                                 "WHERE lower(table_name) = lower('%q')",
    4845             :                                 pszDescription, poLayer->GetName());
    4846           3 :             SQLCommand(hDB, pszSQL);
    4847           3 :             sqlite3_free(pszSQL);
    4848             :         }
    4849             : 
    4850         249 :         papszMDDup = nullptr;
    4851         667 :         for (CSLConstList papszIter = poLayer->GetMetadata();
    4852         667 :              papszIter && *papszIter; ++papszIter)
    4853             :         {
    4854         418 :             if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4855           3 :                 continue;
    4856         415 :             if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4857           3 :                 continue;
    4858         412 :             if (STARTS_WITH_CI(*papszIter, "OLMD_FID64="))
    4859           0 :                 continue;
    4860         412 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4861             :         }
    4862             : 
    4863             :         {
    4864         249 :             GDALMultiDomainMetadata oLocalMDMD;
    4865         249 :             char **papszDomainList = poLayer->GetMetadataDomainList();
    4866         249 :             char **papszIter = papszDomainList;
    4867         249 :             oLocalMDMD.SetMetadata(papszMDDup);
    4868         554 :             while (papszIter && *papszIter)
    4869             :             {
    4870         305 :                 if (!EQUAL(*papszIter, ""))
    4871          69 :                     oLocalMDMD.SetMetadata(poLayer->GetMetadata(*papszIter),
    4872             :                                            *papszIter);
    4873         305 :                 papszIter++;
    4874             :             }
    4875         249 :             CSLDestroy(papszDomainList);
    4876         249 :             psXMLNode = oLocalMDMD.Serialize();
    4877             :         }
    4878             : 
    4879         249 :         CSLDestroy(papszMDDup);
    4880         249 :         papszMDDup = nullptr;
    4881             : 
    4882         249 :         WriteMetadata(psXMLNode, poLayer->GetName());
    4883             :     }
    4884             : }
    4885             : 
    4886             : /************************************************************************/
    4887             : /*                          GetMetadataItem()                           */
    4888             : /************************************************************************/
    4889             : 
    4890        2052 : const char *GDALGeoPackageDataset::GetMetadataItem(const char *pszName,
    4891             :                                                    const char *pszDomain)
    4892             : {
    4893        2052 :     pszDomain = CheckMetadataDomain(pszDomain);
    4894        2052 :     return CSLFetchNameValue(GetMetadata(pszDomain), pszName);
    4895             : }
    4896             : 
    4897             : /************************************************************************/
    4898             : /*                            SetMetadata()                             */
    4899             : /************************************************************************/
    4900             : 
    4901         134 : CPLErr GDALGeoPackageDataset::SetMetadata(CSLConstList papszMetadata,
    4902             :                                           const char *pszDomain)
    4903             : {
    4904         134 :     pszDomain = CheckMetadataDomain(pszDomain);
    4905         134 :     m_bMetadataDirty = true;
    4906         134 :     GetMetadata(); /* force loading from storage if needed */
    4907         134 :     return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
    4908             : }
    4909             : 
    4910             : /************************************************************************/
    4911             : /*                          SetMetadataItem()                           */
    4912             : /************************************************************************/
    4913             : 
    4914          21 : CPLErr GDALGeoPackageDataset::SetMetadataItem(const char *pszName,
    4915             :                                               const char *pszValue,
    4916             :                                               const char *pszDomain)
    4917             : {
    4918          21 :     pszDomain = CheckMetadataDomain(pszDomain);
    4919          21 :     m_bMetadataDirty = true;
    4920          21 :     GetMetadata(); /* force loading from storage if needed */
    4921          21 :     return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    4922             : }
    4923             : 
    4924             : /************************************************************************/
    4925             : /*                               Create()                               */
    4926             : /************************************************************************/
    4927             : 
    4928        1085 : int GDALGeoPackageDataset::Create(const char *pszFilename, int nXSize,
    4929             :                                   int nYSize, int nBandsIn, GDALDataType eDT,
    4930             :                                   CSLConstList papszOptions)
    4931             : {
    4932        2170 :     CPLString osCommand;
    4933             : 
    4934             :     /* First, ensure there isn't any such file yet. */
    4935             :     VSIStatBufL sStatBuf;
    4936             : 
    4937        1085 :     if (nBandsIn != 0)
    4938             :     {
    4939         230 :         if (eDT == GDT_UInt8)
    4940             :         {
    4941         160 :             if (nBandsIn != 1 && nBandsIn != 2 && nBandsIn != 3 &&
    4942             :                 nBandsIn != 4)
    4943             :             {
    4944           1 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4945             :                          "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), "
    4946             :                          "3 (RGB) or 4 (RGBA) band dataset supported for "
    4947             :                          "Byte datatype");
    4948           1 :                 return FALSE;
    4949             :             }
    4950             :         }
    4951          70 :         else if (eDT == GDT_Int16 || eDT == GDT_UInt16 || eDT == GDT_Float32)
    4952             :         {
    4953          43 :             if (nBandsIn != 1)
    4954             :             {
    4955           3 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4956             :                          "Only single band dataset supported for non Byte "
    4957             :                          "datatype");
    4958           3 :                 return FALSE;
    4959             :             }
    4960             :         }
    4961             :         else
    4962             :         {
    4963          27 :             CPLError(CE_Failure, CPLE_NotSupported,
    4964             :                      "Only Byte, Int16, UInt16 or Float32 supported");
    4965          27 :             return FALSE;
    4966             :         }
    4967             :     }
    4968             : 
    4969        1054 :     const size_t nFilenameLen = strlen(pszFilename);
    4970        1054 :     const bool bGpkgZip =
    4971        1049 :         (nFilenameLen > strlen(".gpkg.zip") &&
    4972        2103 :          !STARTS_WITH(pszFilename, "/vsizip/") &&
    4973        1049 :          EQUAL(pszFilename + nFilenameLen - strlen(".gpkg.zip"), ".gpkg.zip"));
    4974             : 
    4975             :     const bool bUseTempFile =
    4976        1055 :         bGpkgZip || (CPLTestBool(CPLGetConfigOption(
    4977           1 :                          "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", "NO")) &&
    4978           1 :                      (VSIHasOptimizedReadMultiRange(pszFilename) != FALSE ||
    4979           1 :                       EQUAL(CPLGetConfigOption(
    4980             :                                 "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", ""),
    4981        1054 :                             "FORCED")));
    4982             : 
    4983        1054 :     bool bFileExists = false;
    4984        1054 :     if (VSIStatL(pszFilename, &sStatBuf) == 0)
    4985             :     {
    4986          10 :         bFileExists = true;
    4987          20 :         if (nBandsIn == 0 || bUseTempFile ||
    4988          10 :             !CPLTestBool(
    4989             :                 CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")))
    4990             :         {
    4991           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    4992             :                      "A file system object called '%s' already exists.",
    4993             :                      pszFilename);
    4994             : 
    4995           0 :             return FALSE;
    4996             :         }
    4997             :     }
    4998             : 
    4999        1054 :     if (bUseTempFile)
    5000             :     {
    5001           3 :         if (bGpkgZip)
    5002             :         {
    5003           2 :             std::string osFilenameInZip(CPLGetFilename(pszFilename));
    5004           2 :             osFilenameInZip.resize(osFilenameInZip.size() - strlen(".zip"));
    5005             :             m_osFinalFilename =
    5006           2 :                 std::string("/vsizip/{") + pszFilename + "}/" + osFilenameInZip;
    5007             :         }
    5008             :         else
    5009             :         {
    5010           1 :             m_osFinalFilename = pszFilename;
    5011             :         }
    5012           3 :         m_pszFilename = CPLStrdup(
    5013           6 :             CPLGenerateTempFilenameSafe(CPLGetFilename(pszFilename)).c_str());
    5014           3 :         CPLDebug("GPKG", "Creating temporary file %s", m_pszFilename);
    5015             :     }
    5016             :     else
    5017             :     {
    5018        1051 :         m_pszFilename = CPLStrdup(pszFilename);
    5019             :     }
    5020        1054 :     m_bNew = true;
    5021        1054 :     eAccess = GA_Update;
    5022        1054 :     m_bDateTimeWithTZ =
    5023        1054 :         EQUAL(CSLFetchNameValueDef(papszOptions, "DATETIME_FORMAT", "WITH_TZ"),
    5024             :               "WITH_TZ");
    5025             : 
    5026             :     // for test/debug purposes only. true is the nominal value
    5027        1054 :     m_bPNGSupports2Bands =
    5028        1054 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_2BANDS", "TRUE"));
    5029        1054 :     m_bPNGSupportsCT =
    5030        1054 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_CT", "TRUE"));
    5031             : 
    5032        1054 :     if (!OpenOrCreateDB(bFileExists
    5033             :                             ? SQLITE_OPEN_READWRITE
    5034             :                             : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE))
    5035           8 :         return FALSE;
    5036             : 
    5037             :     /* Default to synchronous=off for performance for new file */
    5038        2082 :     if (!bFileExists &&
    5039        1036 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5040             :     {
    5041         520 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5042             :     }
    5043             : 
    5044             :     /* OGR UTF-8 support. If we set the UTF-8 Pragma early on, it */
    5045             :     /* will be written into the main file and supported henceforth */
    5046        1046 :     SQLCommand(hDB, "PRAGMA encoding = \"UTF-8\"");
    5047             : 
    5048        1046 :     if (bFileExists)
    5049             :     {
    5050          10 :         VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
    5051          10 :         if (fp)
    5052             :         {
    5053             :             GByte abyHeader[100];
    5054          10 :             VSIFReadL(abyHeader, 1, sizeof(abyHeader), fp);
    5055          10 :             VSIFCloseL(fp);
    5056             : 
    5057          10 :             memcpy(&m_nApplicationId, abyHeader + knApplicationIdPos, 4);
    5058          10 :             m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    5059          10 :             memcpy(&m_nUserVersion, abyHeader + knUserVersionPos, 4);
    5060          10 :             m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    5061             : 
    5062          10 :             if (m_nApplicationId == GP10_APPLICATION_ID)
    5063             :             {
    5064           0 :                 CPLDebug("GPKG", "GeoPackage v1.0");
    5065             :             }
    5066          10 :             else if (m_nApplicationId == GP11_APPLICATION_ID)
    5067             :             {
    5068           0 :                 CPLDebug("GPKG", "GeoPackage v1.1");
    5069             :             }
    5070          10 :             else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    5071          10 :                      m_nUserVersion >= GPKG_1_2_VERSION)
    5072             :             {
    5073          10 :                 CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    5074          10 :                          (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    5075             :             }
    5076             :         }
    5077             : 
    5078          10 :         DetectSpatialRefSysColumns();
    5079             :     }
    5080             : 
    5081        1046 :     const char *pszVersion = CSLFetchNameValue(papszOptions, "VERSION");
    5082        1046 :     if (pszVersion && !EQUAL(pszVersion, "AUTO"))
    5083             :     {
    5084          40 :         if (EQUAL(pszVersion, "1.0"))
    5085             :         {
    5086           2 :             m_nApplicationId = GP10_APPLICATION_ID;
    5087           2 :             m_nUserVersion = 0;
    5088             :         }
    5089          38 :         else if (EQUAL(pszVersion, "1.1"))
    5090             :         {
    5091           1 :             m_nApplicationId = GP11_APPLICATION_ID;
    5092           1 :             m_nUserVersion = 0;
    5093             :         }
    5094          37 :         else if (EQUAL(pszVersion, "1.2"))
    5095             :         {
    5096          15 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5097          15 :             m_nUserVersion = GPKG_1_2_VERSION;
    5098             :         }
    5099          22 :         else if (EQUAL(pszVersion, "1.3"))
    5100             :         {
    5101           3 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5102           3 :             m_nUserVersion = GPKG_1_3_VERSION;
    5103             :         }
    5104          19 :         else if (EQUAL(pszVersion, "1.4"))
    5105             :         {
    5106          19 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5107          19 :             m_nUserVersion = GPKG_1_4_VERSION;
    5108             :         }
    5109             :     }
    5110             : 
    5111        1046 :     SoftStartTransaction();
    5112             : 
    5113        2092 :     CPLString osSQL;
    5114        1046 :     if (!bFileExists)
    5115             :     {
    5116             :         /* Requirement 10: A GeoPackage SHALL include a gpkg_spatial_ref_sys
    5117             :          * table */
    5118             :         /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5119             :         osSQL = "CREATE TABLE gpkg_spatial_ref_sys ("
    5120             :                 "srs_name TEXT NOT NULL,"
    5121             :                 "srs_id INTEGER NOT NULL PRIMARY KEY,"
    5122             :                 "organization TEXT NOT NULL,"
    5123             :                 "organization_coordsys_id INTEGER NOT NULL,"
    5124             :                 "definition  TEXT NOT NULL,"
    5125        1036 :                 "description TEXT";
    5126        1036 :         if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "CRS_WKT_EXTENSION",
    5127        1221 :                                              "NO")) ||
    5128         185 :             (nBandsIn != 0 && eDT != GDT_UInt8))
    5129             :         {
    5130          42 :             m_bHasDefinition12_063 = true;
    5131          42 :             osSQL += ", definition_12_063 TEXT NOT NULL";
    5132          42 :             if (m_nUserVersion >= GPKG_1_4_VERSION)
    5133             :             {
    5134          40 :                 osSQL += ", epoch DOUBLE";
    5135          40 :                 m_bHasEpochColumn = true;
    5136             :             }
    5137             :         }
    5138             :         osSQL += ")"
    5139             :                  ";"
    5140             :                  /* Requirement 11: The gpkg_spatial_ref_sys table in a
    5141             :                     GeoPackage SHALL */
    5142             :                  /* contain a record for EPSG:4326, the geodetic WGS84 SRS */
    5143             :                  /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5144             : 
    5145             :                  "INSERT INTO gpkg_spatial_ref_sys ("
    5146             :                  "srs_name, srs_id, organization, organization_coordsys_id, "
    5147        1036 :                  "definition, description";
    5148        1036 :         if (m_bHasDefinition12_063)
    5149          42 :             osSQL += ", definition_12_063";
    5150             :         osSQL +=
    5151             :             ") VALUES ("
    5152             :             "'WGS 84 geodetic', 4326, 'EPSG', 4326, '"
    5153             :             "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS "
    5154             :             "84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],"
    5155             :             "AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY["
    5156             :             "\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY["
    5157             :             "\"EPSG\",\"9122\"]],AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\","
    5158             :             "EAST],AUTHORITY[\"EPSG\",\"4326\"]]"
    5159             :             "', 'longitude/latitude coordinates in decimal degrees on the WGS "
    5160        1036 :             "84 spheroid'";
    5161        1036 :         if (m_bHasDefinition12_063)
    5162             :             osSQL +=
    5163             :                 ", 'GEODCRS[\"WGS 84\", DATUM[\"World Geodetic System 1984\", "
    5164             :                 "ELLIPSOID[\"WGS 84\",6378137, 298.257223563, "
    5165             :                 "LENGTHUNIT[\"metre\", 1.0]]], PRIMEM[\"Greenwich\", 0.0, "
    5166             :                 "ANGLEUNIT[\"degree\",0.0174532925199433]], CS[ellipsoidal, "
    5167             :                 "2], AXIS[\"latitude\", north, ORDER[1]], AXIS[\"longitude\", "
    5168             :                 "east, ORDER[2]], ANGLEUNIT[\"degree\", 0.0174532925199433], "
    5169          42 :                 "ID[\"EPSG\", 4326]]'";
    5170             :         osSQL +=
    5171             :             ")"
    5172             :             ";"
    5173             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5174             :                SHALL */
    5175             :             /* contain a record with an srs_id of -1, an organization of “NONE”,
    5176             :              */
    5177             :             /* an organization_coordsys_id of -1, and definition “undefined” */
    5178             :             /* for undefined Cartesian coordinate reference systems */
    5179             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5180             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5181             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5182        1036 :             "definition, description";
    5183        1036 :         if (m_bHasDefinition12_063)
    5184          42 :             osSQL += ", definition_12_063";
    5185             :         osSQL += ") VALUES ("
    5186             :                  "'Undefined Cartesian SRS', -1, 'NONE', -1, 'undefined', "
    5187        1036 :                  "'undefined Cartesian coordinate reference system'";
    5188        1036 :         if (m_bHasDefinition12_063)
    5189          42 :             osSQL += ", 'undefined'";
    5190             :         osSQL +=
    5191             :             ")"
    5192             :             ";"
    5193             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5194             :                SHALL */
    5195             :             /* contain a record with an srs_id of 0, an organization of “NONE”,
    5196             :              */
    5197             :             /* an organization_coordsys_id of 0, and definition “undefined” */
    5198             :             /* for undefined geographic coordinate reference systems */
    5199             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5200             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5201             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5202        1036 :             "definition, description";
    5203        1036 :         if (m_bHasDefinition12_063)
    5204          42 :             osSQL += ", definition_12_063";
    5205             :         osSQL += ") VALUES ("
    5206             :                  "'Undefined geographic SRS', 0, 'NONE', 0, 'undefined', "
    5207        1036 :                  "'undefined geographic coordinate reference system'";
    5208        1036 :         if (m_bHasDefinition12_063)
    5209          42 :             osSQL += ", 'undefined'";
    5210             :         osSQL += ")"
    5211             :                  ";"
    5212             :                  /* Requirement 13: A GeoPackage file SHALL include a
    5213             :                     gpkg_contents table */
    5214             :                  /* http://opengis.github.io/geopackage/#_contents */
    5215             :                  "CREATE TABLE gpkg_contents ("
    5216             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5217             :                  "data_type TEXT NOT NULL,"
    5218             :                  "identifier TEXT UNIQUE,"
    5219             :                  "description TEXT DEFAULT '',"
    5220             :                  "last_change DATETIME NOT NULL DEFAULT "
    5221             :                  "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    5222             :                  "min_x DOUBLE, min_y DOUBLE,"
    5223             :                  "max_x DOUBLE, max_y DOUBLE,"
    5224             :                  "srs_id INTEGER,"
    5225             :                  "CONSTRAINT fk_gc_r_srs_id FOREIGN KEY (srs_id) REFERENCES "
    5226             :                  "gpkg_spatial_ref_sys(srs_id)"
    5227        1036 :                  ")";
    5228             : 
    5229             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5230        1036 :         if (CPLFetchBool(papszOptions, "ADD_GPKG_OGR_CONTENTS", true))
    5231             :         {
    5232        1030 :             m_bHasGPKGOGRContents = true;
    5233             :             osSQL += ";"
    5234             :                      "CREATE TABLE gpkg_ogr_contents("
    5235             :                      "table_name TEXT NOT NULL PRIMARY KEY,"
    5236             :                      "feature_count INTEGER DEFAULT NULL"
    5237        1030 :                      ")";
    5238             :         }
    5239             : #endif
    5240             : 
    5241             :         /* Requirement 21: A GeoPackage with a gpkg_contents table row with a
    5242             :          * “features” */
    5243             :         /* data_type SHALL contain a gpkg_geometry_columns table or updateable
    5244             :          * view */
    5245             :         /* http://opengis.github.io/geopackage/#_geometry_columns */
    5246             :         const bool bCreateGeometryColumns =
    5247        1036 :             CPLTestBool(CPLGetConfigOption("CREATE_GEOMETRY_COLUMNS", "YES"));
    5248        1036 :         if (bCreateGeometryColumns)
    5249             :         {
    5250        1035 :             m_bHasGPKGGeometryColumns = true;
    5251        1035 :             osSQL += ";";
    5252        1035 :             osSQL += pszCREATE_GPKG_GEOMETRY_COLUMNS;
    5253             :         }
    5254             :     }
    5255             : 
    5256             :     const bool bCreateTriggers =
    5257        1046 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "YES"));
    5258          10 :     if ((bFileExists && nBandsIn != 0 &&
    5259          10 :          SQLGetInteger(
    5260             :              hDB,
    5261             :              "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_tile_matrix_set' "
    5262             :              "AND type in ('table', 'view')",
    5263        2092 :              nullptr) == 0) ||
    5264        1045 :         (!bFileExists &&
    5265        1036 :          CPLTestBool(CPLGetConfigOption("CREATE_RASTER_TABLES", "YES"))))
    5266             :     {
    5267        1036 :         if (!osSQL.empty())
    5268        1035 :             osSQL += ";";
    5269             : 
    5270             :         /* From C.5. gpkg_tile_matrix_set Table 28. gpkg_tile_matrix_set Table
    5271             :          * Creation SQL  */
    5272             :         osSQL += "CREATE TABLE gpkg_tile_matrix_set ("
    5273             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5274             :                  "srs_id INTEGER NOT NULL,"
    5275             :                  "min_x DOUBLE NOT NULL,"
    5276             :                  "min_y DOUBLE NOT NULL,"
    5277             :                  "max_x DOUBLE NOT NULL,"
    5278             :                  "max_y DOUBLE NOT NULL,"
    5279             :                  "CONSTRAINT fk_gtms_table_name FOREIGN KEY (table_name) "
    5280             :                  "REFERENCES gpkg_contents(table_name),"
    5281             :                  "CONSTRAINT fk_gtms_srs FOREIGN KEY (srs_id) REFERENCES "
    5282             :                  "gpkg_spatial_ref_sys (srs_id)"
    5283             :                  ")"
    5284             :                  ";"
    5285             : 
    5286             :                  /* From C.6. gpkg_tile_matrix Table 29. gpkg_tile_matrix Table
    5287             :                     Creation SQL */
    5288             :                  "CREATE TABLE gpkg_tile_matrix ("
    5289             :                  "table_name TEXT NOT NULL,"
    5290             :                  "zoom_level INTEGER NOT NULL,"
    5291             :                  "matrix_width INTEGER NOT NULL,"
    5292             :                  "matrix_height INTEGER NOT NULL,"
    5293             :                  "tile_width INTEGER NOT NULL,"
    5294             :                  "tile_height INTEGER NOT NULL,"
    5295             :                  "pixel_x_size DOUBLE NOT NULL,"
    5296             :                  "pixel_y_size DOUBLE NOT NULL,"
    5297             :                  "CONSTRAINT pk_ttm PRIMARY KEY (table_name, zoom_level),"
    5298             :                  "CONSTRAINT fk_tmm_table_name FOREIGN KEY (table_name) "
    5299             :                  "REFERENCES gpkg_contents(table_name)"
    5300        1036 :                  ")";
    5301             : 
    5302        1036 :         if (bCreateTriggers)
    5303             :         {
    5304             :             /* From D.1. gpkg_tile_matrix Table 39. gpkg_tile_matrix Trigger
    5305             :              * Definition SQL */
    5306        1036 :             const char *pszTileMatrixTrigger =
    5307             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_insert' "
    5308             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5309             :                 "FOR EACH ROW BEGIN "
    5310             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5311             :                 "violates constraint: zoom_level cannot be less than 0') "
    5312             :                 "WHERE (NEW.zoom_level < 0); "
    5313             :                 "END; "
    5314             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_update' "
    5315             :                 "BEFORE UPDATE of zoom_level ON 'gpkg_tile_matrix' "
    5316             :                 "FOR EACH ROW BEGIN "
    5317             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5318             :                 "violates constraint: zoom_level cannot be less than 0') "
    5319             :                 "WHERE (NEW.zoom_level < 0); "
    5320             :                 "END; "
    5321             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_insert' "
    5322             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5323             :                 "FOR EACH ROW BEGIN "
    5324             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5325             :                 "violates constraint: matrix_width cannot be less than 1') "
    5326             :                 "WHERE (NEW.matrix_width < 1); "
    5327             :                 "END; "
    5328             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_update' "
    5329             :                 "BEFORE UPDATE OF matrix_width ON 'gpkg_tile_matrix' "
    5330             :                 "FOR EACH ROW BEGIN "
    5331             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5332             :                 "violates constraint: matrix_width cannot be less than 1') "
    5333             :                 "WHERE (NEW.matrix_width < 1); "
    5334             :                 "END; "
    5335             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_insert' "
    5336             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5337             :                 "FOR EACH ROW BEGIN "
    5338             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5339             :                 "violates constraint: matrix_height cannot be less than 1') "
    5340             :                 "WHERE (NEW.matrix_height < 1); "
    5341             :                 "END; "
    5342             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_update' "
    5343             :                 "BEFORE UPDATE OF matrix_height ON 'gpkg_tile_matrix' "
    5344             :                 "FOR EACH ROW BEGIN "
    5345             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5346             :                 "violates constraint: matrix_height cannot be less than 1') "
    5347             :                 "WHERE (NEW.matrix_height < 1); "
    5348             :                 "END; "
    5349             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_insert' "
    5350             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5351             :                 "FOR EACH ROW BEGIN "
    5352             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5353             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5354             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5355             :                 "END; "
    5356             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_update' "
    5357             :                 "BEFORE UPDATE OF pixel_x_size ON 'gpkg_tile_matrix' "
    5358             :                 "FOR EACH ROW BEGIN "
    5359             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5360             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5361             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5362             :                 "END; "
    5363             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_insert' "
    5364             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5365             :                 "FOR EACH ROW BEGIN "
    5366             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5367             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5368             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5369             :                 "END; "
    5370             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_update' "
    5371             :                 "BEFORE UPDATE OF pixel_y_size ON 'gpkg_tile_matrix' "
    5372             :                 "FOR EACH ROW BEGIN "
    5373             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5374             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5375             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5376             :                 "END;";
    5377        1036 :             osSQL += ";";
    5378        1036 :             osSQL += pszTileMatrixTrigger;
    5379             :         }
    5380             :     }
    5381             : 
    5382        1046 :     if (!osSQL.empty() && OGRERR_NONE != SQLCommand(hDB, osSQL))
    5383           1 :         return FALSE;
    5384             : 
    5385        1045 :     if (!bFileExists)
    5386             :     {
    5387             :         const char *pszMetadataTables =
    5388        1035 :             CSLFetchNameValue(papszOptions, "METADATA_TABLES");
    5389        1035 :         if (pszMetadataTables)
    5390          10 :             m_nCreateMetadataTables = int(CPLTestBool(pszMetadataTables));
    5391             : 
    5392        1035 :         if (m_nCreateMetadataTables == TRUE && !CreateMetadataTables())
    5393           0 :             return FALSE;
    5394             : 
    5395        1035 :         if (m_bHasDefinition12_063)
    5396             :         {
    5397          84 :             if (OGRERR_NONE != CreateExtensionsTableIfNecessary() ||
    5398             :                 OGRERR_NONE !=
    5399          42 :                     SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5400             :                                     "(table_name, column_name, extension_name, "
    5401             :                                     "definition, scope) "
    5402             :                                     "VALUES "
    5403             :                                     "('gpkg_spatial_ref_sys', "
    5404             :                                     "'definition_12_063', 'gpkg_crs_wkt', "
    5405             :                                     "'http://www.geopackage.org/spec120/"
    5406             :                                     "#extension_crs_wkt', 'read-write')"))
    5407             :             {
    5408           0 :                 return FALSE;
    5409             :             }
    5410          42 :             if (m_bHasEpochColumn)
    5411             :             {
    5412          40 :                 if (OGRERR_NONE !=
    5413          40 :                         SQLCommand(
    5414             :                             hDB, "UPDATE gpkg_extensions SET extension_name = "
    5415             :                                  "'gpkg_crs_wkt_1_1' "
    5416          80 :                                  "WHERE extension_name = 'gpkg_crs_wkt'") ||
    5417             :                     OGRERR_NONE !=
    5418          40 :                         SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5419             :                                         "(table_name, column_name, "
    5420             :                                         "extension_name, definition, scope) "
    5421             :                                         "VALUES "
    5422             :                                         "('gpkg_spatial_ref_sys', 'epoch', "
    5423             :                                         "'gpkg_crs_wkt_1_1', "
    5424             :                                         "'http://www.geopackage.org/spec/"
    5425             :                                         "#extension_crs_wkt', "
    5426             :                                         "'read-write')"))
    5427             :                 {
    5428           0 :                     return FALSE;
    5429             :                 }
    5430             :             }
    5431             :         }
    5432             :     }
    5433             : 
    5434        1045 :     if (nBandsIn != 0)
    5435             :     {
    5436         194 :         const std::string osTableName = CPLGetBasenameSafe(m_pszFilename);
    5437             :         m_osRasterTable = CSLFetchNameValueDef(papszOptions, "RASTER_TABLE",
    5438         194 :                                                osTableName.c_str());
    5439         194 :         if (m_osRasterTable.empty())
    5440             :         {
    5441           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5442             :                      "RASTER_TABLE must be set to a non empty value");
    5443           0 :             return FALSE;
    5444             :         }
    5445         194 :         m_bIdentifierAsCO =
    5446         194 :             CSLFetchNameValue(papszOptions, "RASTER_IDENTIFIER") != nullptr;
    5447             :         m_osIdentifier = CSLFetchNameValueDef(papszOptions, "RASTER_IDENTIFIER",
    5448         194 :                                               m_osRasterTable);
    5449         194 :         m_bDescriptionAsCO =
    5450         194 :             CSLFetchNameValue(papszOptions, "RASTER_DESCRIPTION") != nullptr;
    5451             :         m_osDescription =
    5452         194 :             CSLFetchNameValueDef(papszOptions, "RASTER_DESCRIPTION", "");
    5453         194 :         SetDataType(eDT);
    5454         194 :         if (eDT == GDT_Int16)
    5455          16 :             SetGlobalOffsetScale(-32768.0, 1.0);
    5456             : 
    5457             :         /* From C.7. sample_tile_pyramid (Informative) Table 31. EXAMPLE: tiles
    5458             :          * table Create Table SQL (Informative) */
    5459             :         char *pszSQL =
    5460         194 :             sqlite3_mprintf("CREATE TABLE \"%w\" ("
    5461             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    5462             :                             "zoom_level INTEGER NOT NULL,"
    5463             :                             "tile_column INTEGER NOT NULL,"
    5464             :                             "tile_row INTEGER NOT NULL,"
    5465             :                             "tile_data BLOB NOT NULL,"
    5466             :                             "UNIQUE (zoom_level, tile_column, tile_row)"
    5467             :                             ")",
    5468             :                             m_osRasterTable.c_str());
    5469         194 :         osSQL = pszSQL;
    5470         194 :         sqlite3_free(pszSQL);
    5471             : 
    5472         194 :         if (bCreateTriggers)
    5473             :         {
    5474         194 :             osSQL += ";";
    5475         194 :             osSQL += CreateRasterTriggersSQL(m_osRasterTable);
    5476             :         }
    5477             : 
    5478         194 :         OGRErr eErr = SQLCommand(hDB, osSQL);
    5479         194 :         if (OGRERR_NONE != eErr)
    5480           0 :             return FALSE;
    5481             : 
    5482         194 :         const char *pszTF = CSLFetchNameValue(papszOptions, "TILE_FORMAT");
    5483         194 :         if (eDT == GDT_Int16 || eDT == GDT_UInt16)
    5484             :         {
    5485          27 :             m_eTF = GPKG_TF_PNG_16BIT;
    5486          27 :             if (pszTF)
    5487             :             {
    5488           1 :                 if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "PNG"))
    5489             :                 {
    5490           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5491             :                              "Only AUTO or PNG supported "
    5492             :                              "as tile format for Int16 / UInt16");
    5493             :                 }
    5494             :             }
    5495             :         }
    5496         167 :         else if (eDT == GDT_Float32)
    5497             :         {
    5498          13 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    5499          13 :             if (pszTF)
    5500             :             {
    5501           5 :                 if (EQUAL(pszTF, "PNG"))
    5502           5 :                     m_eTF = GPKG_TF_PNG_16BIT;
    5503           0 :                 else if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "TIFF"))
    5504             :                 {
    5505           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5506             :                              "Only AUTO, PNG or TIFF supported "
    5507             :                              "as tile format for Float32");
    5508             :                 }
    5509             :             }
    5510             :         }
    5511             :         else
    5512             :         {
    5513         154 :             if (pszTF)
    5514             :             {
    5515          71 :                 m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    5516          71 :                 if (nBandsIn == 1 && m_eTF != GPKG_TF_PNG)
    5517           7 :                     m_bMetadataDirty = true;
    5518             :             }
    5519          83 :             else if (nBandsIn == 1)
    5520          72 :                 m_eTF = GPKG_TF_PNG;
    5521             :         }
    5522             : 
    5523         194 :         if (eDT != GDT_UInt8)
    5524             :         {
    5525          40 :             if (!CreateTileGriddedTable(papszOptions))
    5526           0 :                 return FALSE;
    5527             :         }
    5528             : 
    5529         194 :         nRasterXSize = nXSize;
    5530         194 :         nRasterYSize = nYSize;
    5531             : 
    5532             :         const char *pszTileSize =
    5533         194 :             CSLFetchNameValueDef(papszOptions, "BLOCKSIZE", "256");
    5534             :         const char *pszTileWidth =
    5535         194 :             CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", pszTileSize);
    5536             :         const char *pszTileHeight =
    5537         194 :             CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", pszTileSize);
    5538         194 :         int nTileWidth = atoi(pszTileWidth);
    5539         194 :         int nTileHeight = atoi(pszTileHeight);
    5540         194 :         if ((nTileWidth < 8 || nTileWidth > 4096 || nTileHeight < 8 ||
    5541         388 :              nTileHeight > 4096) &&
    5542           1 :             !CPLTestBool(CPLGetConfigOption("GPKG_ALLOW_CRAZY_SETTINGS", "NO")))
    5543             :         {
    5544           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5545             :                      "Invalid block dimensions: %dx%d", nTileWidth,
    5546             :                      nTileHeight);
    5547           0 :             return FALSE;
    5548             :         }
    5549             : 
    5550         521 :         for (int i = 1; i <= nBandsIn; i++)
    5551             :         {
    5552         327 :             SetBand(i, std::make_unique<GDALGeoPackageRasterBand>(
    5553             :                            this, nTileWidth, nTileHeight));
    5554             :         }
    5555             : 
    5556         194 :         GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL",
    5557             :                                         "IMAGE_STRUCTURE");
    5558         194 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", m_osIdentifier);
    5559         194 :         if (!m_osDescription.empty())
    5560           1 :             GDALPamDataset::SetMetadataItem("DESCRIPTION", m_osDescription);
    5561             : 
    5562         194 :         ParseCompressionOptions(papszOptions);
    5563             : 
    5564         194 :         if (m_eTF == GPKG_TF_WEBP)
    5565             :         {
    5566          10 :             if (!RegisterWebPExtension())
    5567           0 :                 return FALSE;
    5568             :         }
    5569             : 
    5570             :         m_osTilingScheme =
    5571         194 :             CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5572         194 :         if (!EQUAL(m_osTilingScheme, "CUSTOM"))
    5573             :         {
    5574          22 :             const auto poTS = GetTilingScheme(m_osTilingScheme);
    5575          22 :             if (!poTS)
    5576           0 :                 return FALSE;
    5577             : 
    5578          43 :             if (nTileWidth != poTS->nTileWidth ||
    5579          21 :                 nTileHeight != poTS->nTileHeight)
    5580             :             {
    5581           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    5582             :                          "Tile dimension should be %dx%d for %s tiling scheme",
    5583           1 :                          poTS->nTileWidth, poTS->nTileHeight,
    5584             :                          m_osTilingScheme.c_str());
    5585           1 :                 return FALSE;
    5586             :             }
    5587             : 
    5588             :             const char *pszZoomLevel =
    5589          21 :                 CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    5590          21 :             if (pszZoomLevel)
    5591             :             {
    5592           1 :                 m_nZoomLevel = atoi(pszZoomLevel);
    5593           1 :                 int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    5594           1 :                 while ((1 << nMaxZoomLevelForThisTM) >
    5595           2 :                            INT_MAX / poTS->nTileXCountZoomLevel0 ||
    5596           1 :                        (1 << nMaxZoomLevelForThisTM) >
    5597           1 :                            INT_MAX / poTS->nTileYCountZoomLevel0)
    5598             :                 {
    5599           0 :                     --nMaxZoomLevelForThisTM;
    5600             :                 }
    5601             : 
    5602           1 :                 if (m_nZoomLevel < 0 || m_nZoomLevel > nMaxZoomLevelForThisTM)
    5603             :                 {
    5604           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    5605             :                              "ZOOM_LEVEL = %s is invalid. It should be in "
    5606             :                              "[0,%d] range",
    5607             :                              pszZoomLevel, nMaxZoomLevelForThisTM);
    5608           0 :                     return FALSE;
    5609             :                 }
    5610             :             }
    5611             : 
    5612             :             // Implicitly sets SRS.
    5613          21 :             OGRSpatialReference oSRS;
    5614          21 :             if (oSRS.importFromEPSG(poTS->nEPSGCode) != OGRERR_NONE)
    5615           0 :                 return FALSE;
    5616          21 :             char *pszWKT = nullptr;
    5617          21 :             oSRS.exportToWkt(&pszWKT);
    5618          21 :             SetProjection(pszWKT);
    5619          21 :             CPLFree(pszWKT);
    5620             :         }
    5621             :         else
    5622             :         {
    5623         172 :             if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5624             :             {
    5625           0 :                 CPLError(
    5626             :                     CE_Failure, CPLE_NotSupported,
    5627             :                     "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5628           0 :                 return false;
    5629             :             }
    5630             :         }
    5631             :     }
    5632             : 
    5633        1044 :     if (bFileExists && nBandsIn > 0 && eDT == GDT_UInt8)
    5634             :     {
    5635             :         // If there was an ogr_empty_table table, we can remove it
    5636           9 :         RemoveOGREmptyTable();
    5637             :     }
    5638             : 
    5639        1044 :     SoftCommitTransaction();
    5640             : 
    5641             :     /* Requirement 2 */
    5642             :     /* We have to do this after there's some content so the database file */
    5643             :     /* is not zero length */
    5644        1044 :     SetApplicationAndUserVersionId();
    5645             : 
    5646             :     /* Default to synchronous=off for performance for new file */
    5647        2078 :     if (!bFileExists &&
    5648        1034 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5649             :     {
    5650         520 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5651             :     }
    5652             : 
    5653             :     // Enable SpatiaLite 4.3 GPKG mode, i.e. that SpatiaLite functions
    5654             :     // that take geometries will accept and return GPKG encoded geometries without
    5655             :     // explicit conversion.
    5656             :     // Note: we need to do that after DB creation, since EnableGpkgMode()
    5657             :     // checks for the presence of GPKG system tables.
    5658        1044 :     sqlite3_exec(hDB, "SELECT EnableGpkgMode()", nullptr, nullptr, nullptr);
    5659             : 
    5660        1044 :     return TRUE;
    5661             : }
    5662             : 
    5663             : /************************************************************************/
    5664             : /*                        RemoveOGREmptyTable()                         */
    5665             : /************************************************************************/
    5666             : 
    5667         861 : void GDALGeoPackageDataset::RemoveOGREmptyTable()
    5668             : {
    5669             :     // Run with sqlite3_exec since we don't want errors to be emitted
    5670         861 :     sqlite3_exec(hDB, "DROP TABLE IF EXISTS ogr_empty_table", nullptr, nullptr,
    5671             :                  nullptr);
    5672         861 :     sqlite3_exec(
    5673             :         hDB, "DELETE FROM gpkg_contents WHERE table_name = 'ogr_empty_table'",
    5674             :         nullptr, nullptr, nullptr);
    5675             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5676         861 :     if (m_bHasGPKGOGRContents)
    5677             :     {
    5678         846 :         sqlite3_exec(hDB,
    5679             :                      "DELETE FROM gpkg_ogr_contents WHERE "
    5680             :                      "table_name = 'ogr_empty_table'",
    5681             :                      nullptr, nullptr, nullptr);
    5682             :     }
    5683             : #endif
    5684         861 :     sqlite3_exec(hDB,
    5685             :                  "DELETE FROM gpkg_geometry_columns WHERE "
    5686             :                  "table_name = 'ogr_empty_table'",
    5687             :                  nullptr, nullptr, nullptr);
    5688         861 : }
    5689             : 
    5690             : /************************************************************************/
    5691             : /*                       CreateTileGriddedTable()                       */
    5692             : /************************************************************************/
    5693             : 
    5694          40 : bool GDALGeoPackageDataset::CreateTileGriddedTable(CSLConstList papszOptions)
    5695             : {
    5696          80 :     CPLString osSQL;
    5697          40 :     if (!HasGriddedCoverageAncillaryTable())
    5698             :     {
    5699             :         // It doesn't exist. So create gpkg_extensions table if necessary, and
    5700             :         // gpkg_2d_gridded_coverage_ancillary & gpkg_2d_gridded_tile_ancillary,
    5701             :         // and register them as extensions.
    5702          40 :         if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    5703           0 :             return false;
    5704             : 
    5705             :         // Req 1 /table-defs/coverage-ancillary
    5706             :         osSQL = "CREATE TABLE gpkg_2d_gridded_coverage_ancillary ("
    5707             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5708             :                 "tile_matrix_set_name TEXT NOT NULL UNIQUE,"
    5709             :                 "datatype TEXT NOT NULL DEFAULT 'integer',"
    5710             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5711             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5712             :                 "precision REAL DEFAULT 1.0,"
    5713             :                 "data_null REAL,"
    5714             :                 "grid_cell_encoding TEXT DEFAULT 'grid-value-is-center',"
    5715             :                 "uom TEXT,"
    5716             :                 "field_name TEXT DEFAULT 'Height',"
    5717             :                 "quantity_definition TEXT DEFAULT 'Height',"
    5718             :                 "CONSTRAINT fk_g2dgtct_name FOREIGN KEY(tile_matrix_set_name) "
    5719             :                 "REFERENCES gpkg_tile_matrix_set ( table_name ) "
    5720             :                 "CHECK (datatype in ('integer','float')))"
    5721             :                 ";"
    5722             :                 // Requirement 2 /table-defs/tile-ancillary
    5723             :                 "CREATE TABLE gpkg_2d_gridded_tile_ancillary ("
    5724             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5725             :                 "tpudt_name TEXT NOT NULL,"
    5726             :                 "tpudt_id INTEGER NOT NULL,"
    5727             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5728             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5729             :                 "min REAL DEFAULT NULL,"
    5730             :                 "max REAL DEFAULT NULL,"
    5731             :                 "mean REAL DEFAULT NULL,"
    5732             :                 "std_dev REAL DEFAULT NULL,"
    5733             :                 "CONSTRAINT fk_g2dgtat_name FOREIGN KEY (tpudt_name) "
    5734             :                 "REFERENCES gpkg_contents(table_name),"
    5735             :                 "UNIQUE (tpudt_name, tpudt_id))"
    5736             :                 ";"
    5737             :                 // Requirement 6 /gpkg-extensions
    5738             :                 "INSERT INTO gpkg_extensions "
    5739             :                 "(table_name, column_name, extension_name, definition, scope) "
    5740             :                 "VALUES ('gpkg_2d_gridded_coverage_ancillary', NULL, "
    5741             :                 "'gpkg_2d_gridded_coverage', "
    5742             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5743             :                 "'read-write')"
    5744             :                 ";"
    5745             :                 // Requirement 6 /gpkg-extensions
    5746             :                 "INSERT INTO gpkg_extensions "
    5747             :                 "(table_name, column_name, extension_name, definition, scope) "
    5748             :                 "VALUES ('gpkg_2d_gridded_tile_ancillary', NULL, "
    5749             :                 "'gpkg_2d_gridded_coverage', "
    5750             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5751             :                 "'read-write')"
    5752          40 :                 ";";
    5753             :     }
    5754             : 
    5755             :     // Requirement 6 /gpkg-extensions
    5756          40 :     char *pszSQL = sqlite3_mprintf(
    5757             :         "INSERT INTO gpkg_extensions "
    5758             :         "(table_name, column_name, extension_name, definition, scope) "
    5759             :         "VALUES ('%q', 'tile_data', "
    5760             :         "'gpkg_2d_gridded_coverage', "
    5761             :         "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5762             :         "'read-write')",
    5763             :         m_osRasterTable.c_str());
    5764          40 :     osSQL += pszSQL;
    5765          40 :     osSQL += ";";
    5766          40 :     sqlite3_free(pszSQL);
    5767             : 
    5768             :     // Requirement 7 /gpkg-2d-gridded-coverage-ancillary
    5769             :     // Requirement 8 /gpkg-2d-gridded-coverage-ancillary-set-name
    5770             :     // Requirement 9 /gpkg-2d-gridded-coverage-ancillary-datatype
    5771          40 :     m_dfPrecision =
    5772          40 :         CPLAtof(CSLFetchNameValueDef(papszOptions, "PRECISION", "1"));
    5773             :     CPLString osGridCellEncoding(CSLFetchNameValueDef(
    5774          80 :         papszOptions, "GRID_CELL_ENCODING", "grid-value-is-center"));
    5775          40 :     m_bGridCellEncodingAsCO =
    5776          40 :         CSLFetchNameValue(papszOptions, "GRID_CELL_ENCODING") != nullptr;
    5777          80 :     CPLString osUom(CSLFetchNameValueDef(papszOptions, "UOM", ""));
    5778             :     CPLString osFieldName(
    5779          80 :         CSLFetchNameValueDef(papszOptions, "FIELD_NAME", "Height"));
    5780             :     CPLString osQuantityDefinition(
    5781          80 :         CSLFetchNameValueDef(papszOptions, "QUANTITY_DEFINITION", "Height"));
    5782             : 
    5783         121 :     pszSQL = sqlite3_mprintf(
    5784             :         "INSERT INTO gpkg_2d_gridded_coverage_ancillary "
    5785             :         "(tile_matrix_set_name, datatype, scale, offset, precision, "
    5786             :         "grid_cell_encoding, uom, field_name, quantity_definition) "
    5787             :         "VALUES (%Q, '%s', %.17g, %.17g, %.17g, %Q, %Q, %Q, %Q)",
    5788             :         m_osRasterTable.c_str(),
    5789          40 :         (m_eTF == GPKG_TF_PNG_16BIT) ? "integer" : "float", m_dfScale,
    5790             :         m_dfOffset, m_dfPrecision, osGridCellEncoding.c_str(),
    5791          41 :         osUom.empty() ? nullptr : osUom.c_str(), osFieldName.c_str(),
    5792             :         osQuantityDefinition.c_str());
    5793          40 :     m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary = pszSQL;
    5794          40 :     sqlite3_free(pszSQL);
    5795             : 
    5796             :     // Requirement 3 /gpkg-spatial-ref-sys-row
    5797             :     auto oResultTable = SQLQuery(
    5798          80 :         hDB, "SELECT * FROM gpkg_spatial_ref_sys WHERE srs_id = 4979 LIMIT 2");
    5799          40 :     bool bHasEPSG4979 = (oResultTable && oResultTable->RowCount() == 1);
    5800          40 :     if (!bHasEPSG4979)
    5801             :     {
    5802          41 :         if (!m_bHasDefinition12_063 &&
    5803           1 :             !ConvertGpkgSpatialRefSysToExtensionWkt2(/*bForceEpoch=*/false))
    5804             :         {
    5805           0 :             return false;
    5806             :         }
    5807             : 
    5808             :         // This is WKT 2...
    5809          40 :         const char *pszWKT =
    5810             :             "GEODCRS[\"WGS 84\","
    5811             :             "DATUM[\"World Geodetic System 1984\","
    5812             :             "  ELLIPSOID[\"WGS 84\",6378137,298.257223563,"
    5813             :             "LENGTHUNIT[\"metre\",1.0]]],"
    5814             :             "CS[ellipsoidal,3],"
    5815             :             "  AXIS[\"latitude\",north,ORDER[1],ANGLEUNIT[\"degree\","
    5816             :             "0.0174532925199433]],"
    5817             :             "  AXIS[\"longitude\",east,ORDER[2],ANGLEUNIT[\"degree\","
    5818             :             "0.0174532925199433]],"
    5819             :             "  AXIS[\"ellipsoidal height\",up,ORDER[3],"
    5820             :             "LENGTHUNIT[\"metre\",1.0]],"
    5821             :             "ID[\"EPSG\",4979]]";
    5822             : 
    5823          40 :         pszSQL = sqlite3_mprintf(
    5824             :             "INSERT INTO gpkg_spatial_ref_sys "
    5825             :             "(srs_name,srs_id,organization,organization_coordsys_id,"
    5826             :             "definition,definition_12_063) VALUES "
    5827             :             "('WGS 84 3D', 4979, 'EPSG', 4979, 'undefined', '%q')",
    5828             :             pszWKT);
    5829          40 :         osSQL += ";";
    5830          40 :         osSQL += pszSQL;
    5831          40 :         sqlite3_free(pszSQL);
    5832             :     }
    5833             : 
    5834          40 :     return SQLCommand(hDB, osSQL) == OGRERR_NONE;
    5835             : }
    5836             : 
    5837             : /************************************************************************/
    5838             : /*                  HasGriddedCoverageAncillaryTable()                  */
    5839             : /************************************************************************/
    5840             : 
    5841          44 : bool GDALGeoPackageDataset::HasGriddedCoverageAncillaryTable()
    5842             : {
    5843             :     auto oResultTable = SQLQuery(
    5844             :         hDB, "SELECT * FROM sqlite_master WHERE type IN ('table', 'view') AND "
    5845          44 :              "name = 'gpkg_2d_gridded_coverage_ancillary'");
    5846          44 :     bool bHasTable = (oResultTable && oResultTable->RowCount() == 1);
    5847          88 :     return bHasTable;
    5848             : }
    5849             : 
    5850             : /************************************************************************/
    5851             : /*                        GetUnderlyingDataset()                        */
    5852             : /************************************************************************/
    5853             : 
    5854           3 : static GDALDataset *GetUnderlyingDataset(GDALDataset *poSrcDS)
    5855             : {
    5856           3 :     if (auto poVRTDS = dynamic_cast<VRTDataset *>(poSrcDS))
    5857             :     {
    5858           0 :         auto poTmpDS = poVRTDS->GetSingleSimpleSource();
    5859           0 :         if (poTmpDS)
    5860           0 :             return poTmpDS;
    5861             :     }
    5862             : 
    5863           3 :     return poSrcDS;
    5864             : }
    5865             : 
    5866             : /************************************************************************/
    5867             : /*                             CreateCopy()                             */
    5868             : /************************************************************************/
    5869             : 
    5870             : typedef struct
    5871             : {
    5872             :     const char *pszName;
    5873             :     GDALResampleAlg eResampleAlg;
    5874             : } WarpResamplingAlg;
    5875             : 
    5876             : static const WarpResamplingAlg asResamplingAlg[] = {
    5877             :     {"NEAREST", GRA_NearestNeighbour},
    5878             :     {"BILINEAR", GRA_Bilinear},
    5879             :     {"CUBIC", GRA_Cubic},
    5880             :     {"CUBICSPLINE", GRA_CubicSpline},
    5881             :     {"LANCZOS", GRA_Lanczos},
    5882             :     {"MODE", GRA_Mode},
    5883             :     {"AVERAGE", GRA_Average},
    5884             :     {"RMS", GRA_RMS},
    5885             : };
    5886             : 
    5887         163 : GDALDataset *GDALGeoPackageDataset::CreateCopy(const char *pszFilename,
    5888             :                                                GDALDataset *poSrcDS,
    5889             :                                                int bStrict,
    5890             :                                                CSLConstList papszOptions,
    5891             :                                                GDALProgressFunc pfnProgress,
    5892             :                                                void *pProgressData)
    5893             : {
    5894         163 :     const int nBands = poSrcDS->GetRasterCount();
    5895         163 :     if (nBands == 0)
    5896             :     {
    5897           2 :         GDALDataset *poDS = nullptr;
    5898             :         GDALDriver *poThisDriver =
    5899           2 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5900           2 :         if (poThisDriver != nullptr)
    5901             :         {
    5902           2 :             poDS = poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS,
    5903             :                                                    bStrict, papszOptions,
    5904             :                                                    pfnProgress, pProgressData);
    5905             :         }
    5906           2 :         return poDS;
    5907             :     }
    5908             : 
    5909             :     const char *pszTilingScheme =
    5910         161 :         CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5911             : 
    5912         322 :     CPLStringList apszUpdatedOptions(CSLDuplicate(papszOptions));
    5913         161 :     if (CPLTestBool(
    5914         167 :             CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")) &&
    5915           6 :         CSLFetchNameValue(papszOptions, "RASTER_TABLE") == nullptr)
    5916             :     {
    5917             :         const std::string osBasename(CPLGetBasenameSafe(
    5918           6 :             GetUnderlyingDataset(poSrcDS)->GetDescription()));
    5919           3 :         apszUpdatedOptions.SetNameValue("RASTER_TABLE", osBasename.c_str());
    5920             :     }
    5921             : 
    5922         161 :     if (nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4)
    5923             :     {
    5924           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    5925             :                  "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or "
    5926             :                  "4 (RGBA) band dataset supported");
    5927           1 :         return nullptr;
    5928             :     }
    5929             : 
    5930         160 :     const char *pszUnitType = poSrcDS->GetRasterBand(1)->GetUnitType();
    5931         320 :     if (CSLFetchNameValue(papszOptions, "UOM") == nullptr && pszUnitType &&
    5932         160 :         !EQUAL(pszUnitType, ""))
    5933             :     {
    5934           1 :         apszUpdatedOptions.SetNameValue("UOM", pszUnitType);
    5935             :     }
    5936             : 
    5937         160 :     if (EQUAL(pszTilingScheme, "CUSTOM"))
    5938             :     {
    5939         136 :         if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5940             :         {
    5941           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    5942             :                      "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5943           0 :             return nullptr;
    5944             :         }
    5945             : 
    5946         136 :         GDALGeoPackageDataset *poDS = nullptr;
    5947             :         GDALDriver *poThisDriver =
    5948         136 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5949         136 :         if (poThisDriver != nullptr)
    5950             :         {
    5951         136 :             apszUpdatedOptions.SetNameValue("SKIP_HOLES", "YES");
    5952         136 :             poDS = cpl::down_cast<GDALGeoPackageDataset *>(
    5953             :                 poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS, bStrict,
    5954             :                                                 apszUpdatedOptions, pfnProgress,
    5955         136 :                                                 pProgressData));
    5956             : 
    5957         252 :             if (poDS != nullptr &&
    5958         136 :                 poSrcDS->GetRasterBand(1)->GetRasterDataType() == GDT_UInt8 &&
    5959             :                 nBands <= 3)
    5960             :             {
    5961          76 :                 poDS->m_nBandCountFromMetadata = nBands;
    5962          76 :                 poDS->m_bMetadataDirty = true;
    5963             :             }
    5964             :         }
    5965         136 :         if (poDS)
    5966         116 :             poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    5967         136 :         return poDS;
    5968             :     }
    5969             : 
    5970          48 :     const auto poTS = GetTilingScheme(pszTilingScheme);
    5971          24 :     if (!poTS)
    5972             :     {
    5973           2 :         return nullptr;
    5974             :     }
    5975          22 :     const int nEPSGCode = poTS->nEPSGCode;
    5976             : 
    5977          44 :     OGRSpatialReference oSRS;
    5978          22 :     if (oSRS.importFromEPSG(nEPSGCode) != OGRERR_NONE)
    5979             :     {
    5980           0 :         return nullptr;
    5981             :     }
    5982          22 :     char *pszWKT = nullptr;
    5983          22 :     oSRS.exportToWkt(&pszWKT);
    5984          22 :     char **papszTO = CSLSetNameValue(nullptr, "DST_SRS", pszWKT);
    5985             : 
    5986          22 :     void *hTransformArg = nullptr;
    5987             : 
    5988             :     // Hack to compensate for GDALSuggestedWarpOutput2() failure (or not
    5989             :     // ideal suggestion with PROJ 8) when reprojecting latitude = +/- 90 to
    5990             :     // EPSG:3857.
    5991          22 :     GDALGeoTransform srcGT;
    5992          22 :     std::unique_ptr<GDALDataset> poTmpDS;
    5993          22 :     bool bEPSG3857Adjust = false;
    5994           8 :     if (nEPSGCode == 3857 && poSrcDS->GetGeoTransform(srcGT) == CE_None &&
    5995          30 :         srcGT[2] == 0 && srcGT[4] == 0 && srcGT[5] < 0)
    5996             :     {
    5997           8 :         const auto poSrcSRS = poSrcDS->GetSpatialRef();
    5998           8 :         if (poSrcSRS && poSrcSRS->IsGeographic())
    5999             :         {
    6000           2 :             double maxLat = srcGT[3];
    6001           2 :             double minLat = srcGT[3] + poSrcDS->GetRasterYSize() * srcGT[5];
    6002             :             // Corresponds to the latitude of below MAX_GM
    6003           2 :             constexpr double MAX_LAT = 85.0511287798066;
    6004           2 :             bool bModified = false;
    6005           2 :             if (maxLat > MAX_LAT)
    6006             :             {
    6007           2 :                 maxLat = MAX_LAT;
    6008           2 :                 bModified = true;
    6009             :             }
    6010           2 :             if (minLat < -MAX_LAT)
    6011             :             {
    6012           2 :                 minLat = -MAX_LAT;
    6013           2 :                 bModified = true;
    6014             :             }
    6015           2 :             if (bModified)
    6016             :             {
    6017           4 :                 CPLStringList aosOptions;
    6018           2 :                 aosOptions.AddString("-of");
    6019           2 :                 aosOptions.AddString("VRT");
    6020           2 :                 aosOptions.AddString("-projwin");
    6021           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", srcGT[0]));
    6022           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", maxLat));
    6023             :                 aosOptions.AddString(CPLSPrintf(
    6024           2 :                     "%.17g", srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1]));
    6025           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", minLat));
    6026             :                 auto psOptions =
    6027           2 :                     GDALTranslateOptionsNew(aosOptions.List(), nullptr);
    6028           2 :                 poTmpDS.reset(GDALDataset::FromHandle(GDALTranslate(
    6029             :                     "", GDALDataset::ToHandle(poSrcDS), psOptions, nullptr)));
    6030           2 :                 GDALTranslateOptionsFree(psOptions);
    6031           2 :                 if (poTmpDS)
    6032             :                 {
    6033           2 :                     bEPSG3857Adjust = true;
    6034           2 :                     hTransformArg = GDALCreateGenImgProjTransformer2(
    6035           2 :                         GDALDataset::FromHandle(poTmpDS.get()), nullptr,
    6036             :                         papszTO);
    6037             :                 }
    6038             :             }
    6039             :         }
    6040             :     }
    6041          22 :     if (hTransformArg == nullptr)
    6042             :     {
    6043             :         hTransformArg =
    6044          20 :             GDALCreateGenImgProjTransformer2(poSrcDS, nullptr, papszTO);
    6045             :     }
    6046             : 
    6047          22 :     if (hTransformArg == nullptr)
    6048             :     {
    6049           1 :         CPLFree(pszWKT);
    6050           1 :         CSLDestroy(papszTO);
    6051           1 :         return nullptr;
    6052             :     }
    6053             : 
    6054          21 :     GDALTransformerInfo *psInfo =
    6055             :         static_cast<GDALTransformerInfo *>(hTransformArg);
    6056          21 :     GDALGeoTransform gt;
    6057             :     double adfExtent[4];
    6058             :     int nXSize, nYSize;
    6059             : 
    6060          21 :     if (GDALSuggestedWarpOutput2(poSrcDS, psInfo->pfnTransform, hTransformArg,
    6061             :                                  gt.data(), &nXSize, &nYSize, adfExtent,
    6062          21 :                                  0) != CE_None)
    6063             :     {
    6064           0 :         CPLFree(pszWKT);
    6065           0 :         CSLDestroy(papszTO);
    6066           0 :         GDALDestroyGenImgProjTransformer(hTransformArg);
    6067           0 :         return nullptr;
    6068             :     }
    6069             : 
    6070          21 :     GDALDestroyGenImgProjTransformer(hTransformArg);
    6071          21 :     hTransformArg = nullptr;
    6072          21 :     poTmpDS.reset();
    6073             : 
    6074          21 :     if (bEPSG3857Adjust)
    6075             :     {
    6076           2 :         constexpr double SPHERICAL_RADIUS = 6378137.0;
    6077           2 :         constexpr double MAX_GM =
    6078             :             SPHERICAL_RADIUS * M_PI;  // 20037508.342789244
    6079           2 :         double maxNorthing = gt[3];
    6080           2 :         double minNorthing = gt[3] + gt[5] * nYSize;
    6081           2 :         bool bChanged = false;
    6082           2 :         if (maxNorthing > MAX_GM)
    6083             :         {
    6084           2 :             bChanged = true;
    6085           2 :             maxNorthing = MAX_GM;
    6086             :         }
    6087           2 :         if (minNorthing < -MAX_GM)
    6088             :         {
    6089           2 :             bChanged = true;
    6090           2 :             minNorthing = -MAX_GM;
    6091             :         }
    6092           2 :         if (bChanged)
    6093             :         {
    6094           2 :             gt[3] = maxNorthing;
    6095           2 :             nYSize = int((maxNorthing - minNorthing) / (-gt[5]) + 0.5);
    6096           2 :             adfExtent[1] = maxNorthing + nYSize * gt[5];
    6097           2 :             adfExtent[3] = maxNorthing;
    6098             :         }
    6099             :     }
    6100             : 
    6101          21 :     double dfComputedRes = gt[1];
    6102          21 :     double dfPrevRes = 0.0;
    6103          21 :     double dfRes = 0.0;
    6104          21 :     int nZoomLevel = 0;  // Used after for.
    6105          21 :     const char *pszZoomLevel = CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    6106          21 :     if (pszZoomLevel)
    6107             :     {
    6108           2 :         nZoomLevel = atoi(pszZoomLevel);
    6109             : 
    6110           2 :         int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    6111           2 :         while ((1 << nMaxZoomLevelForThisTM) >
    6112           4 :                    INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6113           2 :                (1 << nMaxZoomLevelForThisTM) >
    6114           2 :                    INT_MAX / poTS->nTileYCountZoomLevel0)
    6115             :         {
    6116           0 :             --nMaxZoomLevelForThisTM;
    6117             :         }
    6118             : 
    6119           2 :         if (nZoomLevel < 0 || nZoomLevel > nMaxZoomLevelForThisTM)
    6120             :         {
    6121           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6122             :                      "ZOOM_LEVEL = %s is invalid. It should be in [0,%d] range",
    6123             :                      pszZoomLevel, nMaxZoomLevelForThisTM);
    6124           1 :             CPLFree(pszWKT);
    6125           1 :             CSLDestroy(papszTO);
    6126           1 :             return nullptr;
    6127             :         }
    6128             :     }
    6129             :     else
    6130             :     {
    6131         171 :         for (; nZoomLevel < MAX_ZOOM_LEVEL; nZoomLevel++)
    6132             :         {
    6133         171 :             dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6134         171 :             if (dfComputedRes > dfRes ||
    6135         152 :                 fabs(dfComputedRes - dfRes) / dfRes <= 1e-8)
    6136             :                 break;
    6137         152 :             dfPrevRes = dfRes;
    6138             :         }
    6139          38 :         if (nZoomLevel == MAX_ZOOM_LEVEL ||
    6140          38 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6141          19 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileYCountZoomLevel0)
    6142             :         {
    6143           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6144             :                      "Could not find an appropriate zoom level");
    6145           0 :             CPLFree(pszWKT);
    6146           0 :             CSLDestroy(papszTO);
    6147           0 :             return nullptr;
    6148             :         }
    6149             : 
    6150          19 :         if (nZoomLevel > 0 && fabs(dfComputedRes - dfRes) / dfRes > 1e-8)
    6151             :         {
    6152          17 :             const char *pszZoomLevelStrategy = CSLFetchNameValueDef(
    6153             :                 papszOptions, "ZOOM_LEVEL_STRATEGY", "AUTO");
    6154          17 :             if (EQUAL(pszZoomLevelStrategy, "LOWER"))
    6155             :             {
    6156           1 :                 nZoomLevel--;
    6157             :             }
    6158          16 :             else if (EQUAL(pszZoomLevelStrategy, "UPPER"))
    6159             :             {
    6160             :                 /* do nothing */
    6161             :             }
    6162             :             else
    6163             :             {
    6164          15 :                 if (dfPrevRes / dfComputedRes < dfComputedRes / dfRes)
    6165          13 :                     nZoomLevel--;
    6166             :             }
    6167             :         }
    6168             :     }
    6169             : 
    6170          20 :     dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6171             : 
    6172          20 :     double dfMinX = adfExtent[0];
    6173          20 :     double dfMinY = adfExtent[1];
    6174          20 :     double dfMaxX = adfExtent[2];
    6175          20 :     double dfMaxY = adfExtent[3];
    6176             : 
    6177          20 :     nXSize = static_cast<int>(0.5 + (dfMaxX - dfMinX) / dfRes);
    6178          20 :     nYSize = static_cast<int>(0.5 + (dfMaxY - dfMinY) / dfRes);
    6179          20 :     gt[1] = dfRes;
    6180          20 :     gt[5] = -dfRes;
    6181             : 
    6182          20 :     const GDALDataType eDT = poSrcDS->GetRasterBand(1)->GetRasterDataType();
    6183          20 :     int nTargetBands = nBands;
    6184             :     /* For grey level or RGB, if there's reprojection involved, add an alpha */
    6185             :     /* channel */
    6186          37 :     if (eDT == GDT_UInt8 &&
    6187          13 :         ((nBands == 1 &&
    6188          17 :           poSrcDS->GetRasterBand(1)->GetColorTable() == nullptr) ||
    6189             :          nBands == 3))
    6190             :     {
    6191          30 :         OGRSpatialReference oSrcSRS;
    6192          15 :         oSrcSRS.SetFromUserInput(poSrcDS->GetProjectionRef());
    6193          15 :         oSrcSRS.AutoIdentifyEPSG();
    6194          30 :         if (oSrcSRS.GetAuthorityCode() == nullptr ||
    6195          15 :             atoi(oSrcSRS.GetAuthorityCode()) != nEPSGCode)
    6196             :         {
    6197          13 :             nTargetBands++;
    6198             :         }
    6199             :     }
    6200             : 
    6201          20 :     GDALResampleAlg eResampleAlg = GRA_Bilinear;
    6202          20 :     const char *pszResampling = CSLFetchNameValue(papszOptions, "RESAMPLING");
    6203          20 :     if (pszResampling)
    6204             :     {
    6205           6 :         for (size_t iAlg = 0;
    6206           6 :              iAlg < sizeof(asResamplingAlg) / sizeof(asResamplingAlg[0]);
    6207             :              iAlg++)
    6208             :         {
    6209           6 :             if (EQUAL(pszResampling, asResamplingAlg[iAlg].pszName))
    6210             :             {
    6211           3 :                 eResampleAlg = asResamplingAlg[iAlg].eResampleAlg;
    6212           3 :                 break;
    6213             :             }
    6214             :         }
    6215             :     }
    6216             : 
    6217          16 :     if (nBands == 1 && poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    6218          36 :         eResampleAlg != GRA_NearestNeighbour && eResampleAlg != GRA_Mode)
    6219             :     {
    6220           0 :         CPLError(
    6221             :             CE_Warning, CPLE_AppDefined,
    6222             :             "Input dataset has a color table, which will likely lead to "
    6223             :             "bad results when using a resampling method other than "
    6224             :             "nearest neighbour or mode. Converting the dataset to 24/32 bit "
    6225             :             "(e.g. with gdal_translate -expand rgb/rgba) is advised.");
    6226             :     }
    6227             : 
    6228          40 :     auto poDS = std::make_unique<GDALGeoPackageDataset>();
    6229          40 :     if (!(poDS->Create(pszFilename, nXSize, nYSize, nTargetBands, eDT,
    6230          20 :                        apszUpdatedOptions)))
    6231             :     {
    6232           1 :         CPLFree(pszWKT);
    6233           1 :         CSLDestroy(papszTO);
    6234           1 :         return nullptr;
    6235             :     }
    6236             : 
    6237             :     // Assign nodata values before the SetGeoTransform call.
    6238             :     // SetGeoTransform will trigger creation of the overview datasets for each
    6239             :     // zoom level and at that point the nodata value needs to be known.
    6240          19 :     int bHasNoData = FALSE;
    6241             :     double dfNoDataValue =
    6242          19 :         poSrcDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    6243          19 :     if (eDT != GDT_UInt8 && bHasNoData)
    6244             :     {
    6245           3 :         poDS->GetRasterBand(1)->SetNoDataValue(dfNoDataValue);
    6246             :     }
    6247             : 
    6248          19 :     poDS->SetGeoTransform(gt);
    6249          19 :     poDS->SetProjection(pszWKT);
    6250          19 :     CPLFree(pszWKT);
    6251          19 :     pszWKT = nullptr;
    6252          24 :     if (nTargetBands == 1 && nBands == 1 &&
    6253           5 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
    6254             :     {
    6255           2 :         poDS->GetRasterBand(1)->SetColorTable(
    6256           1 :             poSrcDS->GetRasterBand(1)->GetColorTable());
    6257             :     }
    6258             : 
    6259             :     hTransformArg =
    6260          19 :         GDALCreateGenImgProjTransformer2(poSrcDS, poDS.get(), papszTO);
    6261          19 :     CSLDestroy(papszTO);
    6262          19 :     if (hTransformArg == nullptr)
    6263             :     {
    6264           0 :         return nullptr;
    6265             :     }
    6266             : 
    6267          19 :     poDS->SetMetadata(poSrcDS->GetMetadata());
    6268             : 
    6269             :     /* -------------------------------------------------------------------- */
    6270             :     /*      Warp the transformer with a linear approximator                 */
    6271             :     /* -------------------------------------------------------------------- */
    6272          19 :     hTransformArg = GDALCreateApproxTransformer(GDALGenImgProjTransform,
    6273             :                                                 hTransformArg, 0.125);
    6274          19 :     GDALApproxTransformerOwnsSubtransformer(hTransformArg, TRUE);
    6275             : 
    6276             :     /* -------------------------------------------------------------------- */
    6277             :     /*      Setup warp options.                                             */
    6278             :     /* -------------------------------------------------------------------- */
    6279          19 :     GDALWarpOptions *psWO = GDALCreateWarpOptions();
    6280             : 
    6281          19 :     psWO->papszWarpOptions = CSLSetNameValue(nullptr, "OPTIMIZE_SIZE", "YES");
    6282          19 :     psWO->papszWarpOptions =
    6283          19 :         CSLSetNameValue(psWO->papszWarpOptions, "SAMPLE_GRID", "YES");
    6284          19 :     if (bHasNoData)
    6285             :     {
    6286           3 :         if (dfNoDataValue == 0.0)
    6287             :         {
    6288             :             // Do not initialize in the case where nodata != 0, since we
    6289             :             // want the GeoPackage driver to return empty tiles at the nodata
    6290             :             // value instead of 0 as GDAL core would
    6291           0 :             psWO->papszWarpOptions =
    6292           0 :                 CSLSetNameValue(psWO->papszWarpOptions, "INIT_DEST", "0");
    6293             :         }
    6294             : 
    6295           3 :         psWO->padfSrcNoDataReal =
    6296           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6297           3 :         psWO->padfSrcNoDataReal[0] = dfNoDataValue;
    6298             : 
    6299           3 :         psWO->padfDstNoDataReal =
    6300           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6301           3 :         psWO->padfDstNoDataReal[0] = dfNoDataValue;
    6302             :     }
    6303          19 :     psWO->eWorkingDataType = eDT;
    6304          19 :     psWO->eResampleAlg = eResampleAlg;
    6305             : 
    6306          19 :     psWO->hSrcDS = poSrcDS;
    6307          19 :     psWO->hDstDS = poDS.get();
    6308             : 
    6309          19 :     psWO->pfnTransformer = GDALApproxTransform;
    6310          19 :     psWO->pTransformerArg = hTransformArg;
    6311             : 
    6312          19 :     psWO->pfnProgress = pfnProgress;
    6313          19 :     psWO->pProgressArg = pProgressData;
    6314             : 
    6315             :     /* -------------------------------------------------------------------- */
    6316             :     /*      Setup band mapping.                                             */
    6317             :     /* -------------------------------------------------------------------- */
    6318             : 
    6319          19 :     if (nBands == 2 || nBands == 4)
    6320           1 :         psWO->nBandCount = nBands - 1;
    6321             :     else
    6322          18 :         psWO->nBandCount = nBands;
    6323             : 
    6324          19 :     psWO->panSrcBands =
    6325          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6326          19 :     psWO->panDstBands =
    6327          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6328             : 
    6329          46 :     for (int i = 0; i < psWO->nBandCount; i++)
    6330             :     {
    6331          27 :         psWO->panSrcBands[i] = i + 1;
    6332          27 :         psWO->panDstBands[i] = i + 1;
    6333             :     }
    6334             : 
    6335          19 :     if (nBands == 2 || nBands == 4)
    6336             :     {
    6337           1 :         psWO->nSrcAlphaBand = nBands;
    6338             :     }
    6339          19 :     if (nTargetBands == 2 || nTargetBands == 4)
    6340             :     {
    6341          13 :         psWO->nDstAlphaBand = nTargetBands;
    6342             :     }
    6343             : 
    6344             :     /* -------------------------------------------------------------------- */
    6345             :     /*      Initialize and execute the warp.                                */
    6346             :     /* -------------------------------------------------------------------- */
    6347          38 :     GDALWarpOperation oWO;
    6348             : 
    6349          19 :     CPLErr eErr = oWO.Initialize(psWO);
    6350          19 :     if (eErr == CE_None)
    6351             :     {
    6352             :         /*if( bMulti )
    6353             :             eErr = oWO.ChunkAndWarpMulti( 0, 0, nXSize, nYSize );
    6354             :         else*/
    6355          19 :         eErr = oWO.ChunkAndWarpImage(0, 0, nXSize, nYSize);
    6356             :     }
    6357          19 :     if (eErr != CE_None)
    6358             :     {
    6359           0 :         poDS.reset();
    6360             :     }
    6361             : 
    6362          19 :     GDALDestroyTransformer(hTransformArg);
    6363          19 :     GDALDestroyWarpOptions(psWO);
    6364             : 
    6365          19 :     if (poDS)
    6366          19 :         poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    6367             : 
    6368          19 :     return poDS.release();
    6369             : }
    6370             : 
    6371             : /************************************************************************/
    6372             : /*                      ParseCompressionOptions()                       */
    6373             : /************************************************************************/
    6374             : 
    6375         473 : void GDALGeoPackageDataset::ParseCompressionOptions(CSLConstList papszOptions)
    6376             : {
    6377         473 :     const char *pszZLevel = CSLFetchNameValue(papszOptions, "ZLEVEL");
    6378         473 :     if (pszZLevel)
    6379           0 :         m_nZLevel = atoi(pszZLevel);
    6380             : 
    6381         473 :     const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
    6382         473 :     if (pszQuality)
    6383           0 :         m_nQuality = atoi(pszQuality);
    6384             : 
    6385         473 :     const char *pszDither = CSLFetchNameValue(papszOptions, "DITHER");
    6386         473 :     if (pszDither)
    6387           0 :         m_bDither = CPLTestBool(pszDither);
    6388         473 : }
    6389             : 
    6390             : /************************************************************************/
    6391             : /*                       RegisterWebPExtension()                        */
    6392             : /************************************************************************/
    6393             : 
    6394          11 : bool GDALGeoPackageDataset::RegisterWebPExtension()
    6395             : {
    6396          11 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6397           0 :         return false;
    6398             : 
    6399          11 :     char *pszSQL = sqlite3_mprintf(
    6400             :         "INSERT INTO gpkg_extensions "
    6401             :         "(table_name, column_name, extension_name, definition, scope) "
    6402             :         "VALUES "
    6403             :         "('%q', 'tile_data', 'gpkg_webp', "
    6404             :         "'http://www.geopackage.org/spec120/#extension_tiles_webp', "
    6405             :         "'read-write')",
    6406             :         m_osRasterTable.c_str());
    6407          11 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6408          11 :     sqlite3_free(pszSQL);
    6409             : 
    6410          11 :     return OGRERR_NONE == eErr;
    6411             : }
    6412             : 
    6413             : /************************************************************************/
    6414             : /*                     RegisterZoomOtherExtension()                     */
    6415             : /************************************************************************/
    6416             : 
    6417           1 : bool GDALGeoPackageDataset::RegisterZoomOtherExtension()
    6418             : {
    6419           1 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6420           0 :         return false;
    6421             : 
    6422           1 :     char *pszSQL = sqlite3_mprintf(
    6423             :         "INSERT INTO gpkg_extensions "
    6424             :         "(table_name, column_name, extension_name, definition, scope) "
    6425             :         "VALUES "
    6426             :         "('%q', 'tile_data', 'gpkg_zoom_other', "
    6427             :         "'http://www.geopackage.org/spec120/#extension_zoom_other_intervals', "
    6428             :         "'read-write')",
    6429             :         m_osRasterTable.c_str());
    6430           1 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6431           1 :     sqlite3_free(pszSQL);
    6432           1 :     return OGRERR_NONE == eErr;
    6433             : }
    6434             : 
    6435             : /************************************************************************/
    6436             : /*                              GetLayer()                              */
    6437             : /************************************************************************/
    6438             : 
    6439       16900 : const OGRLayer *GDALGeoPackageDataset::GetLayer(int iLayer) const
    6440             : 
    6441             : {
    6442       16900 :     if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
    6443           7 :         return nullptr;
    6444             :     else
    6445       16893 :         return m_apoLayers[iLayer].get();
    6446             : }
    6447             : 
    6448             : /************************************************************************/
    6449             : /*                            LaunderName()                             */
    6450             : /************************************************************************/
    6451             : 
    6452             : /** Launder identifiers (table, column names) according to guidance at
    6453             :  * https://www.geopackage.org/guidance/getting-started.html:
    6454             :  * "For maximum interoperability, start your database identifiers (table names,
    6455             :  * column names, etc.) with a lowercase character and only use lowercase
    6456             :  * characters, numbers 0-9, and underscores (_)."
    6457             :  */
    6458             : 
    6459             : /* static */
    6460           5 : std::string GDALGeoPackageDataset::LaunderName(const std::string &osStr)
    6461             : {
    6462           5 :     char *pszASCII = CPLUTF8ForceToASCII(osStr.c_str(), '_');
    6463          10 :     const std::string osStrASCII(pszASCII);
    6464           5 :     CPLFree(pszASCII);
    6465             : 
    6466          10 :     std::string osRet;
    6467           5 :     osRet.reserve(osStrASCII.size());
    6468             : 
    6469          29 :     for (size_t i = 0; i < osStrASCII.size(); ++i)
    6470             :     {
    6471          24 :         if (osRet.empty())
    6472             :         {
    6473           5 :             if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6474             :             {
    6475           2 :                 osRet += (osStrASCII[i] - 'A' + 'a');
    6476             :             }
    6477           3 :             else if (osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z')
    6478             :             {
    6479           2 :                 osRet += osStrASCII[i];
    6480             :             }
    6481             :             else
    6482             :             {
    6483           1 :                 continue;
    6484             :             }
    6485             :         }
    6486          19 :         else if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6487             :         {
    6488          11 :             osRet += (osStrASCII[i] - 'A' + 'a');
    6489             :         }
    6490           9 :         else if ((osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z') ||
    6491          14 :                  (osStrASCII[i] >= '0' && osStrASCII[i] <= '9') ||
    6492           5 :                  osStrASCII[i] == '_')
    6493             :         {
    6494           7 :             osRet += osStrASCII[i];
    6495             :         }
    6496             :         else
    6497             :         {
    6498           1 :             osRet += '_';
    6499             :         }
    6500             :     }
    6501             : 
    6502           5 :     if (osRet.empty() && !osStrASCII.empty())
    6503           2 :         return LaunderName(std::string("x").append(osStrASCII));
    6504             : 
    6505           4 :     if (osRet != osStr)
    6506             :     {
    6507           3 :         CPLDebug("PG", "LaunderName('%s') -> '%s'", osStr.c_str(),
    6508             :                  osRet.c_str());
    6509             :     }
    6510             : 
    6511           4 :     return osRet;
    6512             : }
    6513             : 
    6514             : /************************************************************************/
    6515             : /*                            ICreateLayer()                            */
    6516             : /************************************************************************/
    6517             : 
    6518             : OGRLayer *
    6519         966 : GDALGeoPackageDataset::ICreateLayer(const char *pszLayerName,
    6520             :                                     const OGRGeomFieldDefn *poSrcGeomFieldDefn,
    6521             :                                     CSLConstList papszOptions)
    6522             : {
    6523             :     /* -------------------------------------------------------------------- */
    6524             :     /*      Verify we are in update mode.                                   */
    6525             :     /* -------------------------------------------------------------------- */
    6526         966 :     if (!GetUpdate())
    6527             :     {
    6528           0 :         CPLError(CE_Failure, CPLE_NoWriteAccess,
    6529             :                  "Data source %s opened read-only.\n"
    6530             :                  "New layer %s cannot be created.\n",
    6531             :                  m_pszFilename, pszLayerName);
    6532             : 
    6533           0 :         return nullptr;
    6534             :     }
    6535             : 
    6536             :     const bool bLaunder =
    6537         966 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "LAUNDER", "NO"));
    6538             :     const std::string osTableName(bLaunder ? LaunderName(pszLayerName)
    6539        2898 :                                            : std::string(pszLayerName));
    6540             : 
    6541             :     const auto eGType =
    6542         966 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
    6543             :     const auto poSpatialRef =
    6544         966 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
    6545             : 
    6546         966 :     if (!m_bHasGPKGGeometryColumns)
    6547             :     {
    6548           1 :         if (SQLCommand(hDB, pszCREATE_GPKG_GEOMETRY_COLUMNS) != OGRERR_NONE)
    6549             :         {
    6550           0 :             return nullptr;
    6551             :         }
    6552           1 :         m_bHasGPKGGeometryColumns = true;
    6553             :     }
    6554             : 
    6555             :     // Check identifier unicity
    6556         966 :     const char *pszIdentifier = CSLFetchNameValue(papszOptions, "IDENTIFIER");
    6557         966 :     if (pszIdentifier != nullptr && pszIdentifier[0] == '\0')
    6558           0 :         pszIdentifier = nullptr;
    6559         966 :     if (pszIdentifier != nullptr)
    6560             :     {
    6561          13 :         for (auto &poLayer : m_apoLayers)
    6562             :         {
    6563             :             const char *pszOtherIdentifier =
    6564           9 :                 poLayer->GetMetadataItem("IDENTIFIER");
    6565           9 :             if (pszOtherIdentifier == nullptr)
    6566           6 :                 pszOtherIdentifier = poLayer->GetName();
    6567          18 :             if (pszOtherIdentifier != nullptr &&
    6568          12 :                 EQUAL(pszOtherIdentifier, pszIdentifier) &&
    6569           3 :                 !EQUAL(poLayer->GetName(), osTableName.c_str()))
    6570             :             {
    6571           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6572             :                          "Identifier %s is already used by table %s",
    6573             :                          pszIdentifier, poLayer->GetName());
    6574           2 :                 return nullptr;
    6575             :             }
    6576             :         }
    6577             : 
    6578             :         // In case there would be table in gpkg_contents not listed as a
    6579             :         // vector layer
    6580           4 :         char *pszSQL = sqlite3_mprintf(
    6581             :             "SELECT table_name FROM gpkg_contents WHERE identifier = '%q' "
    6582             :             "LIMIT 2",
    6583             :             pszIdentifier);
    6584           4 :         auto oResult = SQLQuery(hDB, pszSQL);
    6585           4 :         sqlite3_free(pszSQL);
    6586           8 :         if (oResult && oResult->RowCount() > 0 &&
    6587           9 :             oResult->GetValue(0, 0) != nullptr &&
    6588           1 :             !EQUAL(oResult->GetValue(0, 0), osTableName.c_str()))
    6589             :         {
    6590           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6591             :                      "Identifier %s is already used by table %s", pszIdentifier,
    6592             :                      oResult->GetValue(0, 0));
    6593           1 :             return nullptr;
    6594             :         }
    6595             :     }
    6596             : 
    6597             :     /* Read GEOMETRY_NAME option */
    6598             :     const char *pszGeomColumnName =
    6599         963 :         CSLFetchNameValue(papszOptions, "GEOMETRY_NAME");
    6600         963 :     if (pszGeomColumnName == nullptr) /* deprecated name */
    6601         876 :         pszGeomColumnName = CSLFetchNameValue(papszOptions, "GEOMETRY_COLUMN");
    6602         963 :     if (pszGeomColumnName == nullptr && poSrcGeomFieldDefn)
    6603             :     {
    6604         794 :         pszGeomColumnName = poSrcGeomFieldDefn->GetNameRef();
    6605         794 :         if (pszGeomColumnName && pszGeomColumnName[0] == 0)
    6606         759 :             pszGeomColumnName = nullptr;
    6607             :     }
    6608         963 :     if (pszGeomColumnName == nullptr)
    6609         841 :         pszGeomColumnName = "geom";
    6610             :     const bool bGeomNullable =
    6611         963 :         CPLFetchBool(papszOptions, "GEOMETRY_NULLABLE", true);
    6612             : 
    6613             :     /* Read FID option */
    6614         963 :     const char *pszFIDColumnName = CSLFetchNameValue(papszOptions, "FID");
    6615         963 :     if (pszFIDColumnName == nullptr)
    6616         872 :         pszFIDColumnName = "fid";
    6617             : 
    6618         963 :     if (CPLTestBool(CPLGetConfigOption("GPKG_NAME_CHECK", "YES")))
    6619             :     {
    6620         963 :         if (strspn(pszFIDColumnName, "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") > 0)
    6621             :         {
    6622           2 :             CPLError(CE_Failure, CPLE_AppDefined,
    6623             :                      "The primary key (%s) name may not contain special "
    6624             :                      "characters or spaces",
    6625             :                      pszFIDColumnName);
    6626           2 :             return nullptr;
    6627             :         }
    6628             : 
    6629             :         /* Avoiding gpkg prefixes is not an official requirement, but seems wise
    6630             :          */
    6631         961 :         if (STARTS_WITH(osTableName.c_str(), "gpkg"))
    6632             :         {
    6633           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6634             :                      "The layer name may not begin with 'gpkg' as it is a "
    6635             :                      "reserved geopackage prefix");
    6636           0 :             return nullptr;
    6637             :         }
    6638             : 
    6639             :         /* Preemptively try and avoid sqlite3 syntax errors due to  */
    6640             :         /* illegal characters. */
    6641         961 :         if (strspn(osTableName.c_str(), "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") >
    6642             :             0)
    6643             :         {
    6644           0 :             CPLError(
    6645             :                 CE_Failure, CPLE_AppDefined,
    6646             :                 "The layer name may not contain special characters or spaces");
    6647           0 :             return nullptr;
    6648             :         }
    6649             :     }
    6650             : 
    6651             :     /* Check for any existing layers that already use this name */
    6652        1204 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6653             :          iLayer++)
    6654             :     {
    6655         244 :         if (EQUAL(osTableName.c_str(), m_apoLayers[iLayer]->GetName()))
    6656             :         {
    6657             :             const char *pszOverwrite =
    6658           2 :                 CSLFetchNameValue(papszOptions, "OVERWRITE");
    6659           2 :             if (pszOverwrite != nullptr && CPLTestBool(pszOverwrite))
    6660             :             {
    6661           1 :                 DeleteLayer(iLayer);
    6662             :             }
    6663             :             else
    6664             :             {
    6665           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6666             :                          "Layer %s already exists, CreateLayer failed.\n"
    6667             :                          "Use the layer creation option OVERWRITE=YES to "
    6668             :                          "replace it.",
    6669             :                          osTableName.c_str());
    6670           1 :                 return nullptr;
    6671             :             }
    6672             :         }
    6673             :     }
    6674             : 
    6675         960 :     if (m_apoLayers.size() == 1)
    6676             :     {
    6677             :         // Async RTree building doesn't play well with multiple layer:
    6678             :         // SQLite3 locks being hold for a long time, random failed commits,
    6679             :         // etc.
    6680          95 :         m_apoLayers[0]->FinishOrDisableThreadedRTree();
    6681             :     }
    6682             : 
    6683             :     /* Create a blank layer. */
    6684             :     auto poLayer =
    6685        1920 :         std::make_unique<OGRGeoPackageTableLayer>(this, osTableName.c_str());
    6686             : 
    6687        1920 :     OGRSpatialReferenceRefCountedPtr poSRS;
    6688         960 :     if (poSpatialRef)
    6689             :     {
    6690         328 :         poSRS = OGRSpatialReferenceRefCountedPtr::makeClone(poSpatialRef);
    6691         328 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    6692             :     }
    6693        2881 :     poLayer->SetCreationParameters(
    6694             :         eGType,
    6695         961 :         bLaunder ? LaunderName(pszGeomColumnName).c_str() : pszGeomColumnName,
    6696         960 :         bGeomNullable, poSRS.get(), CSLFetchNameValue(papszOptions, "SRID"),
    6697        1920 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetCoordinatePrecision()
    6698             :                            : OGRGeomCoordinatePrecision(),
    6699         960 :         CPLTestBool(
    6700             :             CSLFetchNameValueDef(papszOptions, "DISCARD_COORD_LSB", "NO")),
    6701         960 :         CPLTestBool(CSLFetchNameValueDef(
    6702             :             papszOptions, "UNDO_DISCARD_COORD_LSB_ON_READING", "NO")),
    6703         961 :         bLaunder ? LaunderName(pszFIDColumnName).c_str() : pszFIDColumnName,
    6704             :         pszIdentifier, CSLFetchNameValue(papszOptions, "DESCRIPTION"));
    6705             : 
    6706         960 :     poLayer->SetLaunder(bLaunder);
    6707             : 
    6708             :     /* Should we create a spatial index ? */
    6709         960 :     const char *pszSI = CSLFetchNameValue(papszOptions, "SPATIAL_INDEX");
    6710         960 :     int bCreateSpatialIndex = (pszSI == nullptr || CPLTestBool(pszSI));
    6711         960 :     if (eGType != wkbNone && bCreateSpatialIndex)
    6712             :     {
    6713         856 :         poLayer->SetDeferredSpatialIndexCreation(true);
    6714             :     }
    6715             : 
    6716         960 :     poLayer->SetPrecisionFlag(CPLFetchBool(papszOptions, "PRECISION", true));
    6717         960 :     poLayer->SetTruncateFieldsFlag(
    6718         960 :         CPLFetchBool(papszOptions, "TRUNCATE_FIELDS", false));
    6719         960 :     if (eGType == wkbNone)
    6720             :     {
    6721          82 :         const char *pszASpatialVariant = CSLFetchNameValueDef(
    6722             :             papszOptions, "ASPATIAL_VARIANT",
    6723          82 :             m_bNonSpatialTablesNonRegisteredInGpkgContentsFound
    6724             :                 ? "NOT_REGISTERED"
    6725             :                 : "GPKG_ATTRIBUTES");
    6726          82 :         GPKGASpatialVariant eASpatialVariant = GPKG_ATTRIBUTES;
    6727          82 :         if (EQUAL(pszASpatialVariant, "GPKG_ATTRIBUTES"))
    6728          70 :             eASpatialVariant = GPKG_ATTRIBUTES;
    6729          12 :         else if (EQUAL(pszASpatialVariant, "OGR_ASPATIAL"))
    6730             :         {
    6731           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6732             :                      "ASPATIAL_VARIANT=OGR_ASPATIAL is no longer supported");
    6733           0 :             return nullptr;
    6734             :         }
    6735          12 :         else if (EQUAL(pszASpatialVariant, "NOT_REGISTERED"))
    6736          12 :             eASpatialVariant = NOT_REGISTERED;
    6737             :         else
    6738             :         {
    6739           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6740             :                      "Unsupported value for ASPATIAL_VARIANT: %s",
    6741             :                      pszASpatialVariant);
    6742           0 :             return nullptr;
    6743             :         }
    6744          82 :         poLayer->SetASpatialVariant(eASpatialVariant);
    6745             :     }
    6746             : 
    6747             :     const char *pszDateTimePrecision =
    6748         960 :         CSLFetchNameValueDef(papszOptions, "DATETIME_PRECISION", "AUTO");
    6749         960 :     if (EQUAL(pszDateTimePrecision, "MILLISECOND"))
    6750             :     {
    6751           2 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6752             :     }
    6753         958 :     else if (EQUAL(pszDateTimePrecision, "SECOND"))
    6754             :     {
    6755           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6756           0 :             CPLError(
    6757             :                 CE_Warning, CPLE_AppDefined,
    6758             :                 "DATETIME_PRECISION=SECOND is only valid since GeoPackage 1.4");
    6759           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::SECOND);
    6760             :     }
    6761         957 :     else if (EQUAL(pszDateTimePrecision, "MINUTE"))
    6762             :     {
    6763           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6764           0 :             CPLError(
    6765             :                 CE_Warning, CPLE_AppDefined,
    6766             :                 "DATETIME_PRECISION=MINUTE is only valid since GeoPackage 1.4");
    6767           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MINUTE);
    6768             :     }
    6769         956 :     else if (EQUAL(pszDateTimePrecision, "AUTO"))
    6770             :     {
    6771         955 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6772          13 :             poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6773             :     }
    6774             :     else
    6775             :     {
    6776           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    6777             :                  "Unsupported value for DATETIME_PRECISION: %s",
    6778             :                  pszDateTimePrecision);
    6779           1 :         return nullptr;
    6780             :     }
    6781             : 
    6782             :     // If there was an ogr_empty_table table, we can remove it
    6783             :     // But do it at dataset closing, otherwise locking performance issues
    6784             :     // can arise (probably when transactions are used).
    6785         959 :     m_bRemoveOGREmptyTable = true;
    6786             : 
    6787         959 :     m_apoLayers.emplace_back(std::move(poLayer));
    6788         959 :     return m_apoLayers.back().get();
    6789             : }
    6790             : 
    6791             : /************************************************************************/
    6792             : /*                           FindLayerIndex()                           */
    6793             : /************************************************************************/
    6794             : 
    6795          29 : int GDALGeoPackageDataset::FindLayerIndex(const char *pszLayerName)
    6796             : 
    6797             : {
    6798          51 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6799             :          iLayer++)
    6800             :     {
    6801          35 :         if (EQUAL(pszLayerName, m_apoLayers[iLayer]->GetName()))
    6802          13 :             return iLayer;
    6803             :     }
    6804          16 :     return -1;
    6805             : }
    6806             : 
    6807             : /************************************************************************/
    6808             : /*                         DeleteLayerCommon()                          */
    6809             : /************************************************************************/
    6810             : 
    6811          43 : OGRErr GDALGeoPackageDataset::DeleteLayerCommon(const char *pszLayerName)
    6812             : {
    6813             :     // Temporary remove foreign key checks
    6814             :     const GPKGTemporaryForeignKeyCheckDisabler
    6815          43 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6816             : 
    6817          43 :     char *pszSQL = sqlite3_mprintf(
    6818             :         "DELETE FROM gpkg_contents WHERE lower(table_name) = lower('%q')",
    6819             :         pszLayerName);
    6820          43 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    6821          43 :     sqlite3_free(pszSQL);
    6822             : 
    6823          43 :     if (eErr == OGRERR_NONE && HasExtensionsTable())
    6824             :     {
    6825          41 :         pszSQL = sqlite3_mprintf(
    6826             :             "DELETE FROM gpkg_extensions WHERE lower(table_name) = lower('%q')",
    6827             :             pszLayerName);
    6828          41 :         eErr = SQLCommand(hDB, pszSQL);
    6829          41 :         sqlite3_free(pszSQL);
    6830             :     }
    6831             : 
    6832          43 :     if (eErr == OGRERR_NONE && HasMetadataTables())
    6833             :     {
    6834             :         // Delete from gpkg_metadata metadata records that are only referenced
    6835             :         // by the table we are about to drop
    6836          12 :         pszSQL = sqlite3_mprintf(
    6837             :             "DELETE FROM gpkg_metadata WHERE id IN ("
    6838             :             "SELECT DISTINCT md_file_id FROM "
    6839             :             "gpkg_metadata_reference WHERE "
    6840             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6841             :             "AND id NOT IN ("
    6842             :             "SELECT DISTINCT md_file_id FROM gpkg_metadata_reference WHERE "
    6843             :             "md_file_id IN (SELECT DISTINCT md_file_id FROM "
    6844             :             "gpkg_metadata_reference WHERE "
    6845             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6846             :             "AND lower(table_name) <> lower('%q'))",
    6847             :             pszLayerName, pszLayerName, pszLayerName);
    6848          12 :         eErr = SQLCommand(hDB, pszSQL);
    6849          12 :         sqlite3_free(pszSQL);
    6850             : 
    6851          12 :         if (eErr == OGRERR_NONE)
    6852             :         {
    6853             :             pszSQL =
    6854          12 :                 sqlite3_mprintf("DELETE FROM gpkg_metadata_reference WHERE "
    6855             :                                 "lower(table_name) = lower('%q')",
    6856             :                                 pszLayerName);
    6857          12 :             eErr = SQLCommand(hDB, pszSQL);
    6858          12 :             sqlite3_free(pszSQL);
    6859             :         }
    6860             :     }
    6861             : 
    6862          43 :     if (eErr == OGRERR_NONE && HasGpkgextRelationsTable())
    6863             :     {
    6864             :         // Remove reference to potential corresponding mapping table in
    6865             :         // gpkg_extensions
    6866           4 :         pszSQL = sqlite3_mprintf(
    6867             :             "DELETE FROM gpkg_extensions WHERE "
    6868             :             "extension_name IN ('related_tables', "
    6869             :             "'gpkg_related_tables') AND lower(table_name) = "
    6870             :             "(SELECT lower(mapping_table_name) FROM gpkgext_relations WHERE "
    6871             :             "lower(base_table_name) = lower('%q') OR "
    6872             :             "lower(related_table_name) = lower('%q') OR "
    6873             :             "lower(mapping_table_name) = lower('%q'))",
    6874             :             pszLayerName, pszLayerName, pszLayerName);
    6875           4 :         eErr = SQLCommand(hDB, pszSQL);
    6876           4 :         sqlite3_free(pszSQL);
    6877             : 
    6878           4 :         if (eErr == OGRERR_NONE)
    6879             :         {
    6880             :             // Remove reference to potential corresponding mapping table in
    6881             :             // gpkgext_relations
    6882             :             pszSQL =
    6883           4 :                 sqlite3_mprintf("DELETE FROM gpkgext_relations WHERE "
    6884             :                                 "lower(base_table_name) = lower('%q') OR "
    6885             :                                 "lower(related_table_name) = lower('%q') OR "
    6886             :                                 "lower(mapping_table_name) = lower('%q')",
    6887             :                                 pszLayerName, pszLayerName, pszLayerName);
    6888           4 :             eErr = SQLCommand(hDB, pszSQL);
    6889           4 :             sqlite3_free(pszSQL);
    6890             :         }
    6891             : 
    6892           4 :         if (eErr == OGRERR_NONE && HasExtensionsTable())
    6893             :         {
    6894             :             // If there is no longer any mapping table, then completely
    6895             :             // remove any reference to the extension in gpkg_extensions
    6896             :             // as mandated per the related table specification.
    6897             :             OGRErr err;
    6898           4 :             if (SQLGetInteger(hDB,
    6899             :                               "SELECT COUNT(*) FROM gpkg_extensions WHERE "
    6900             :                               "extension_name IN ('related_tables', "
    6901             :                               "'gpkg_related_tables') AND "
    6902             :                               "lower(table_name) != 'gpkgext_relations'",
    6903           4 :                               &err) == 0)
    6904             :             {
    6905           2 :                 eErr = SQLCommand(hDB, "DELETE FROM gpkg_extensions WHERE "
    6906             :                                        "extension_name IN ('related_tables', "
    6907             :                                        "'gpkg_related_tables')");
    6908             :             }
    6909             : 
    6910           4 :             ClearCachedRelationships();
    6911             :         }
    6912             :     }
    6913             : 
    6914          43 :     if (eErr == OGRERR_NONE)
    6915             :     {
    6916          43 :         pszSQL = sqlite3_mprintf("DROP TABLE \"%w\"", pszLayerName);
    6917          43 :         eErr = SQLCommand(hDB, pszSQL);
    6918          43 :         sqlite3_free(pszSQL);
    6919             :     }
    6920             : 
    6921             :     // Check foreign key integrity
    6922          43 :     if (eErr == OGRERR_NONE)
    6923             :     {
    6924          43 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    6925             :     }
    6926             : 
    6927          86 :     return eErr;
    6928             : }
    6929             : 
    6930             : /************************************************************************/
    6931             : /*                            DeleteLayer()                             */
    6932             : /************************************************************************/
    6933             : 
    6934          40 : OGRErr GDALGeoPackageDataset::DeleteLayer(int iLayer)
    6935             : {
    6936          79 :     if (!GetUpdate() || iLayer < 0 ||
    6937          39 :         iLayer >= static_cast<int>(m_apoLayers.size()))
    6938           2 :         return OGRERR_FAILURE;
    6939             : 
    6940          38 :     m_apoLayers[iLayer]->ResetReading();
    6941          38 :     m_apoLayers[iLayer]->SyncToDisk();
    6942             : 
    6943          76 :     CPLString osLayerName = m_apoLayers[iLayer]->GetName();
    6944             : 
    6945          38 :     CPLDebug("GPKG", "DeleteLayer(%s)", osLayerName.c_str());
    6946             : 
    6947             :     // Temporary remove foreign key checks
    6948             :     const GPKGTemporaryForeignKeyCheckDisabler
    6949          38 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6950             : 
    6951          38 :     OGRErr eErr = SoftStartTransaction();
    6952             : 
    6953          38 :     if (eErr == OGRERR_NONE)
    6954             :     {
    6955          38 :         if (m_apoLayers[iLayer]->HasSpatialIndex())
    6956          35 :             m_apoLayers[iLayer]->DropSpatialIndex();
    6957             : 
    6958             :         char *pszSQL =
    6959          38 :             sqlite3_mprintf("DELETE FROM gpkg_geometry_columns WHERE "
    6960             :                             "lower(table_name) = lower('%q')",
    6961             :                             osLayerName.c_str());
    6962          38 :         eErr = SQLCommand(hDB, pszSQL);
    6963          38 :         sqlite3_free(pszSQL);
    6964             :     }
    6965             : 
    6966          38 :     if (eErr == OGRERR_NONE && HasDataColumnsTable())
    6967             :     {
    6968           1 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_data_columns WHERE "
    6969             :                                        "lower(table_name) = lower('%q')",
    6970             :                                        osLayerName.c_str());
    6971           1 :         eErr = SQLCommand(hDB, pszSQL);
    6972           1 :         sqlite3_free(pszSQL);
    6973             :     }
    6974             : 
    6975             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    6976          38 :     if (eErr == OGRERR_NONE && m_bHasGPKGOGRContents)
    6977             :     {
    6978          38 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_ogr_contents WHERE "
    6979             :                                        "lower(table_name) = lower('%q')",
    6980             :                                        osLayerName.c_str());
    6981          38 :         eErr = SQLCommand(hDB, pszSQL);
    6982          38 :         sqlite3_free(pszSQL);
    6983             :     }
    6984             : #endif
    6985             : 
    6986          38 :     if (eErr == OGRERR_NONE)
    6987             :     {
    6988          38 :         eErr = DeleteLayerCommon(osLayerName.c_str());
    6989             :     }
    6990             : 
    6991          38 :     if (eErr == OGRERR_NONE)
    6992             :     {
    6993          38 :         eErr = SoftCommitTransaction();
    6994          38 :         if (eErr == OGRERR_NONE)
    6995             :         {
    6996             :             /* Delete the layer object */
    6997          38 :             m_apoLayers.erase(m_apoLayers.begin() + iLayer);
    6998             :         }
    6999             :     }
    7000             :     else
    7001             :     {
    7002           0 :         SoftRollbackTransaction();
    7003             :     }
    7004             : 
    7005          38 :     return eErr;
    7006             : }
    7007             : 
    7008             : /************************************************************************/
    7009             : /*                         DeleteRasterLayer()                          */
    7010             : /************************************************************************/
    7011             : 
    7012           2 : OGRErr GDALGeoPackageDataset::DeleteRasterLayer(const char *pszLayerName)
    7013             : {
    7014             :     // Temporary remove foreign key checks
    7015             :     const GPKGTemporaryForeignKeyCheckDisabler
    7016           2 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7017             : 
    7018           2 :     OGRErr eErr = SoftStartTransaction();
    7019             : 
    7020           2 :     if (eErr == OGRERR_NONE)
    7021             :     {
    7022           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix WHERE "
    7023             :                                        "lower(table_name) = lower('%q')",
    7024             :                                        pszLayerName);
    7025           2 :         eErr = SQLCommand(hDB, pszSQL);
    7026           2 :         sqlite3_free(pszSQL);
    7027             :     }
    7028             : 
    7029           2 :     if (eErr == OGRERR_NONE)
    7030             :     {
    7031           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix_set WHERE "
    7032             :                                        "lower(table_name) = lower('%q')",
    7033             :                                        pszLayerName);
    7034           2 :         eErr = SQLCommand(hDB, pszSQL);
    7035           2 :         sqlite3_free(pszSQL);
    7036             :     }
    7037             : 
    7038           2 :     if (eErr == OGRERR_NONE && HasGriddedCoverageAncillaryTable())
    7039             :     {
    7040             :         char *pszSQL =
    7041           1 :             sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_coverage_ancillary "
    7042             :                             "WHERE lower(tile_matrix_set_name) = lower('%q')",
    7043             :                             pszLayerName);
    7044           1 :         eErr = SQLCommand(hDB, pszSQL);
    7045           1 :         sqlite3_free(pszSQL);
    7046             : 
    7047           1 :         if (eErr == OGRERR_NONE)
    7048             :         {
    7049             :             pszSQL =
    7050           1 :                 sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_tile_ancillary "
    7051             :                                 "WHERE lower(tpudt_name) = lower('%q')",
    7052             :                                 pszLayerName);
    7053           1 :             eErr = SQLCommand(hDB, pszSQL);
    7054           1 :             sqlite3_free(pszSQL);
    7055             :         }
    7056             :     }
    7057             : 
    7058           2 :     if (eErr == OGRERR_NONE)
    7059             :     {
    7060           2 :         eErr = DeleteLayerCommon(pszLayerName);
    7061             :     }
    7062             : 
    7063           2 :     if (eErr == OGRERR_NONE)
    7064             :     {
    7065           2 :         eErr = SoftCommitTransaction();
    7066             :     }
    7067             :     else
    7068             :     {
    7069           0 :         SoftRollbackTransaction();
    7070             :     }
    7071             : 
    7072           4 :     return eErr;
    7073             : }
    7074             : 
    7075             : /************************************************************************/
    7076             : /*                     DeleteVectorOrRasterLayer()                      */
    7077             : /************************************************************************/
    7078             : 
    7079          13 : bool GDALGeoPackageDataset::DeleteVectorOrRasterLayer(const char *pszLayerName)
    7080             : {
    7081             : 
    7082          13 :     int idx = FindLayerIndex(pszLayerName);
    7083          13 :     if (idx >= 0)
    7084             :     {
    7085           5 :         DeleteLayer(idx);
    7086           5 :         return true;
    7087             :     }
    7088             : 
    7089             :     char *pszSQL =
    7090           8 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7091             :                         "lower(table_name) = lower('%q') "
    7092             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7093             :                         pszLayerName);
    7094           8 :     bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7095           8 :     sqlite3_free(pszSQL);
    7096           8 :     if (bIsRasterTable)
    7097             :     {
    7098           2 :         DeleteRasterLayer(pszLayerName);
    7099           2 :         return true;
    7100             :     }
    7101           6 :     return false;
    7102             : }
    7103             : 
    7104           7 : bool GDALGeoPackageDataset::RenameVectorOrRasterLayer(
    7105             :     const char *pszLayerName, const char *pszNewLayerName)
    7106             : {
    7107           7 :     int idx = FindLayerIndex(pszLayerName);
    7108           7 :     if (idx >= 0)
    7109             :     {
    7110           4 :         m_apoLayers[idx]->Rename(pszNewLayerName);
    7111           4 :         return true;
    7112             :     }
    7113             : 
    7114             :     char *pszSQL =
    7115           3 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7116             :                         "lower(table_name) = lower('%q') "
    7117             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7118             :                         pszLayerName);
    7119           3 :     const bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7120           3 :     sqlite3_free(pszSQL);
    7121             : 
    7122           3 :     if (bIsRasterTable)
    7123             :     {
    7124           2 :         return RenameRasterLayer(pszLayerName, pszNewLayerName);
    7125             :     }
    7126             : 
    7127           1 :     return false;
    7128             : }
    7129             : 
    7130           2 : bool GDALGeoPackageDataset::RenameRasterLayer(const char *pszLayerName,
    7131             :                                               const char *pszNewLayerName)
    7132             : {
    7133           4 :     std::string osSQL;
    7134             : 
    7135           2 :     char *pszSQL = sqlite3_mprintf(
    7136             :         "SELECT 1 FROM sqlite_master WHERE lower(name) = lower('%q') "
    7137             :         "AND type IN ('table', 'view')",
    7138             :         pszNewLayerName);
    7139           2 :     const bool bAlreadyExists = SQLGetInteger(GetDB(), pszSQL, nullptr) == 1;
    7140           2 :     sqlite3_free(pszSQL);
    7141           2 :     if (bAlreadyExists)
    7142             :     {
    7143           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Table %s already exists",
    7144             :                  pszNewLayerName);
    7145           0 :         return false;
    7146             :     }
    7147             : 
    7148             :     // Temporary remove foreign key checks
    7149             :     const GPKGTemporaryForeignKeyCheckDisabler
    7150           4 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7151             : 
    7152           2 :     if (SoftStartTransaction() != OGRERR_NONE)
    7153             :     {
    7154           0 :         return false;
    7155             :     }
    7156             : 
    7157           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET table_name = '%q' WHERE "
    7158             :                              "lower(table_name) = lower('%q');",
    7159             :                              pszNewLayerName, pszLayerName);
    7160           2 :     osSQL = pszSQL;
    7161           2 :     sqlite3_free(pszSQL);
    7162             : 
    7163           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' WHERE "
    7164             :                              "lower(identifier) = lower('%q');",
    7165             :                              pszNewLayerName, pszLayerName);
    7166           2 :     osSQL += pszSQL;
    7167           2 :     sqlite3_free(pszSQL);
    7168             : 
    7169             :     pszSQL =
    7170           2 :         sqlite3_mprintf("UPDATE gpkg_tile_matrix SET table_name = '%q' WHERE "
    7171             :                         "lower(table_name) = lower('%q');",
    7172             :                         pszNewLayerName, pszLayerName);
    7173           2 :     osSQL += pszSQL;
    7174           2 :     sqlite3_free(pszSQL);
    7175             : 
    7176           2 :     pszSQL = sqlite3_mprintf(
    7177             :         "UPDATE gpkg_tile_matrix_set SET table_name = '%q' WHERE "
    7178             :         "lower(table_name) = lower('%q');",
    7179             :         pszNewLayerName, pszLayerName);
    7180           2 :     osSQL += pszSQL;
    7181           2 :     sqlite3_free(pszSQL);
    7182             : 
    7183           2 :     if (HasGriddedCoverageAncillaryTable())
    7184             :     {
    7185           1 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_2d_gridded_coverage_ancillary "
    7186             :                                  "SET tile_matrix_set_name = '%q' WHERE "
    7187             :                                  "lower(tile_matrix_set_name) = lower('%q');",
    7188             :                                  pszNewLayerName, pszLayerName);
    7189           1 :         osSQL += pszSQL;
    7190           1 :         sqlite3_free(pszSQL);
    7191             : 
    7192           1 :         pszSQL = sqlite3_mprintf(
    7193             :             "UPDATE gpkg_2d_gridded_tile_ancillary SET tpudt_name = '%q' WHERE "
    7194             :             "lower(tpudt_name) = lower('%q');",
    7195             :             pszNewLayerName, pszLayerName);
    7196           1 :         osSQL += pszSQL;
    7197           1 :         sqlite3_free(pszSQL);
    7198             :     }
    7199             : 
    7200           2 :     if (HasExtensionsTable())
    7201             :     {
    7202           2 :         pszSQL = sqlite3_mprintf(
    7203             :             "UPDATE gpkg_extensions SET table_name = '%q' WHERE "
    7204             :             "lower(table_name) = lower('%q');",
    7205             :             pszNewLayerName, pszLayerName);
    7206           2 :         osSQL += pszSQL;
    7207           2 :         sqlite3_free(pszSQL);
    7208             :     }
    7209             : 
    7210           2 :     if (HasMetadataTables())
    7211             :     {
    7212           1 :         pszSQL = sqlite3_mprintf(
    7213             :             "UPDATE gpkg_metadata_reference SET table_name = '%q' WHERE "
    7214             :             "lower(table_name) = lower('%q');",
    7215             :             pszNewLayerName, pszLayerName);
    7216           1 :         osSQL += pszSQL;
    7217           1 :         sqlite3_free(pszSQL);
    7218             :     }
    7219             : 
    7220           2 :     if (HasDataColumnsTable())
    7221             :     {
    7222           0 :         pszSQL = sqlite3_mprintf(
    7223             :             "UPDATE gpkg_data_columns SET table_name = '%q' WHERE "
    7224             :             "lower(table_name) = lower('%q');",
    7225             :             pszNewLayerName, pszLayerName);
    7226           0 :         osSQL += pszSQL;
    7227           0 :         sqlite3_free(pszSQL);
    7228             :     }
    7229             : 
    7230           2 :     if (HasQGISLayerStyles())
    7231             :     {
    7232             :         // Update QGIS styles
    7233             :         pszSQL =
    7234           0 :             sqlite3_mprintf("UPDATE layer_styles SET f_table_name = '%q' WHERE "
    7235             :                             "lower(f_table_name) = lower('%q');",
    7236             :                             pszNewLayerName, pszLayerName);
    7237           0 :         osSQL += pszSQL;
    7238           0 :         sqlite3_free(pszSQL);
    7239             :     }
    7240             : 
    7241             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7242           2 :     if (m_bHasGPKGOGRContents)
    7243             :     {
    7244           2 :         pszSQL = sqlite3_mprintf(
    7245             :             "UPDATE gpkg_ogr_contents SET table_name = '%q' WHERE "
    7246             :             "lower(table_name) = lower('%q');",
    7247             :             pszNewLayerName, pszLayerName);
    7248           2 :         osSQL += pszSQL;
    7249           2 :         sqlite3_free(pszSQL);
    7250             :     }
    7251             : #endif
    7252             : 
    7253           2 :     if (HasGpkgextRelationsTable())
    7254             :     {
    7255           0 :         pszSQL = sqlite3_mprintf(
    7256             :             "UPDATE gpkgext_relations SET base_table_name = '%q' WHERE "
    7257             :             "lower(base_table_name) = lower('%q');",
    7258             :             pszNewLayerName, pszLayerName);
    7259           0 :         osSQL += pszSQL;
    7260           0 :         sqlite3_free(pszSQL);
    7261             : 
    7262           0 :         pszSQL = sqlite3_mprintf(
    7263             :             "UPDATE gpkgext_relations SET related_table_name = '%q' WHERE "
    7264             :             "lower(related_table_name) = lower('%q');",
    7265             :             pszNewLayerName, pszLayerName);
    7266           0 :         osSQL += pszSQL;
    7267           0 :         sqlite3_free(pszSQL);
    7268             : 
    7269           0 :         pszSQL = sqlite3_mprintf(
    7270             :             "UPDATE gpkgext_relations SET mapping_table_name = '%q' WHERE "
    7271             :             "lower(mapping_table_name) = lower('%q');",
    7272             :             pszNewLayerName, pszLayerName);
    7273           0 :         osSQL += pszSQL;
    7274           0 :         sqlite3_free(pszSQL);
    7275             :     }
    7276             : 
    7277             :     // Drop all triggers for the layer
    7278           2 :     pszSQL = sqlite3_mprintf("SELECT name FROM sqlite_master WHERE type = "
    7279             :                              "'trigger' AND tbl_name = '%q'",
    7280             :                              pszLayerName);
    7281           2 :     auto oTriggerResult = SQLQuery(GetDB(), pszSQL);
    7282           2 :     sqlite3_free(pszSQL);
    7283           2 :     if (oTriggerResult)
    7284             :     {
    7285          14 :         for (int i = 0; i < oTriggerResult->RowCount(); i++)
    7286             :         {
    7287          12 :             const char *pszTriggerName = oTriggerResult->GetValue(0, i);
    7288          12 :             pszSQL = sqlite3_mprintf("DROP TRIGGER IF EXISTS \"%w\";",
    7289             :                                      pszTriggerName);
    7290          12 :             osSQL += pszSQL;
    7291          12 :             sqlite3_free(pszSQL);
    7292             :         }
    7293             :     }
    7294             : 
    7295           2 :     pszSQL = sqlite3_mprintf("ALTER TABLE \"%w\" RENAME TO \"%w\";",
    7296             :                              pszLayerName, pszNewLayerName);
    7297           2 :     osSQL += pszSQL;
    7298           2 :     sqlite3_free(pszSQL);
    7299             : 
    7300             :     // Recreate all zoom/tile triggers
    7301           2 :     if (oTriggerResult)
    7302             :     {
    7303           2 :         osSQL += CreateRasterTriggersSQL(pszNewLayerName);
    7304             :     }
    7305             : 
    7306           2 :     OGRErr eErr = SQLCommand(GetDB(), osSQL.c_str());
    7307             : 
    7308             :     // Check foreign key integrity
    7309           2 :     if (eErr == OGRERR_NONE)
    7310             :     {
    7311           2 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    7312             :     }
    7313             : 
    7314           2 :     if (eErr == OGRERR_NONE)
    7315             :     {
    7316           2 :         eErr = SoftCommitTransaction();
    7317             :     }
    7318             :     else
    7319             :     {
    7320           0 :         SoftRollbackTransaction();
    7321             :     }
    7322             : 
    7323           2 :     return eErr == OGRERR_NONE;
    7324             : }
    7325             : 
    7326             : /************************************************************************/
    7327             : /*                           TestCapability()                           */
    7328             : /************************************************************************/
    7329             : 
    7330         558 : int GDALGeoPackageDataset::TestCapability(const char *pszCap) const
    7331             : {
    7332         558 :     if (EQUAL(pszCap, ODsCCreateLayer) || EQUAL(pszCap, ODsCDeleteLayer) ||
    7333         361 :         EQUAL(pszCap, "RenameLayer"))
    7334             :     {
    7335         197 :         return GetUpdate();
    7336             :     }
    7337         361 :     else if (EQUAL(pszCap, ODsCCurveGeometries))
    7338          12 :         return TRUE;
    7339         349 :     else if (EQUAL(pszCap, ODsCMeasuredGeometries))
    7340           8 :         return TRUE;
    7341         341 :     else if (EQUAL(pszCap, ODsCZGeometries))
    7342           8 :         return TRUE;
    7343         333 :     else if (EQUAL(pszCap, ODsCRandomLayerWrite) ||
    7344         333 :              EQUAL(pszCap, GDsCAddRelationship) ||
    7345         333 :              EQUAL(pszCap, GDsCDeleteRelationship) ||
    7346         333 :              EQUAL(pszCap, GDsCUpdateRelationship) ||
    7347         333 :              EQUAL(pszCap, ODsCAddFieldDomain) ||
    7348         331 :              EQUAL(pszCap, ODsCUpdateFieldDomain) ||
    7349         329 :              EQUAL(pszCap, ODsCDeleteFieldDomain))
    7350             :     {
    7351           6 :         return GetUpdate();
    7352             :     }
    7353             : 
    7354         327 :     return OGRSQLiteBaseDataSource::TestCapability(pszCap);
    7355             : }
    7356             : 
    7357             : /************************************************************************/
    7358             : /*                       ResetReadingAllLayers()                        */
    7359             : /************************************************************************/
    7360             : 
    7361         205 : void GDALGeoPackageDataset::ResetReadingAllLayers()
    7362             : {
    7363         415 :     for (auto &poLayer : m_apoLayers)
    7364             :     {
    7365         210 :         poLayer->ResetReading();
    7366             :     }
    7367         205 : }
    7368             : 
    7369             : /************************************************************************/
    7370             : /*                             ExecuteSQL()                             */
    7371             : /************************************************************************/
    7372             : 
    7373             : static const char *const apszFuncsWithSideEffects[] = {
    7374             :     "CreateSpatialIndex",
    7375             :     "DisableSpatialIndex",
    7376             :     "HasSpatialIndex",
    7377             :     "RegisterGeometryExtension",
    7378             : };
    7379             : 
    7380        5720 : OGRLayer *GDALGeoPackageDataset::ExecuteSQL(const char *pszSQLCommand,
    7381             :                                             OGRGeometry *poSpatialFilter,
    7382             :                                             const char *pszDialect)
    7383             : 
    7384             : {
    7385        5720 :     m_bHasReadMetadataFromStorage = false;
    7386             : 
    7387        5720 :     FlushMetadata();
    7388             : 
    7389        5738 :     while (*pszSQLCommand != '\0' &&
    7390        5738 :            isspace(static_cast<unsigned char>(*pszSQLCommand)))
    7391          18 :         pszSQLCommand++;
    7392             : 
    7393       11440 :     CPLString osSQLCommand(pszSQLCommand);
    7394        5720 :     if (!osSQLCommand.empty() && osSQLCommand.back() == ';')
    7395          48 :         osSQLCommand.pop_back();
    7396             : 
    7397       11439 :     if (osSQLCommand.ifind("AsGPB(ST_") != std::string::npos ||
    7398        5719 :         osSQLCommand.ifind("AsGPB( ST_") != std::string::npos)
    7399             :     {
    7400           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    7401             :                  "Use of AsGPB(ST_xxx(...)) found in \"%s\". Since GDAL 3.13, "
    7402             :                  "ST_xxx() functions return a GeoPackage geometry when used "
    7403             :                  "with a GeoPackage connection, and the use of AsGPB() is no "
    7404             :                  "longer needed. It is here automatically removed",
    7405             :                  osSQLCommand.c_str());
    7406           1 :         osSQLCommand.replaceAll("AsGPB(ST_", "(ST_");
    7407           1 :         osSQLCommand.replaceAll("AsGPB( ST_", "(ST_");
    7408             :     }
    7409             : 
    7410        5720 :     if (pszDialect == nullptr || !EQUAL(pszDialect, "DEBUG"))
    7411             :     {
    7412             :         // Some SQL commands will influence the feature count behind our
    7413             :         // back, so disable it in that case.
    7414             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7415             :         const bool bInsertOrDelete =
    7416        5651 :             osSQLCommand.ifind("insert into ") != std::string::npos ||
    7417        2530 :             osSQLCommand.ifind("insert or replace into ") !=
    7418        8181 :                 std::string::npos ||
    7419        2493 :             osSQLCommand.ifind("delete from ") != std::string::npos;
    7420             :         const bool bRollback =
    7421        5651 :             osSQLCommand.ifind("rollback ") != std::string::npos;
    7422             : #endif
    7423             : 
    7424        7563 :         for (auto &poLayer : m_apoLayers)
    7425             :         {
    7426        1912 :             if (poLayer->SyncToDisk() != OGRERR_NONE)
    7427           0 :                 return nullptr;
    7428             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7429        2117 :             if (bRollback ||
    7430         205 :                 (bInsertOrDelete &&
    7431         205 :                  osSQLCommand.ifind(poLayer->GetName()) != std::string::npos))
    7432             :             {
    7433         203 :                 poLayer->DisableFeatureCount();
    7434             :             }
    7435             : #endif
    7436             :         }
    7437             :     }
    7438             : 
    7439        5720 :     if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 0") ||
    7440        5719 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=0") ||
    7441        5719 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =0") ||
    7442        5719 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 0"))
    7443             :     {
    7444           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, false);
    7445             :     }
    7446        5719 :     else if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 1") ||
    7447        5718 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=1") ||
    7448        5718 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =1") ||
    7449        5718 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 1"))
    7450             :     {
    7451           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, true);
    7452             :     }
    7453             : 
    7454             :     /* -------------------------------------------------------------------- */
    7455             :     /*      DEBUG "SELECT nolock" command.                                  */
    7456             :     /* -------------------------------------------------------------------- */
    7457        5789 :     if (pszDialect != nullptr && EQUAL(pszDialect, "DEBUG") &&
    7458          69 :         EQUAL(osSQLCommand, "SELECT nolock"))
    7459             :     {
    7460           3 :         return new OGRSQLiteSingleFeatureLayer(osSQLCommand, m_bNoLock ? 1 : 0);
    7461             :     }
    7462             : 
    7463             :     /* -------------------------------------------------------------------- */
    7464             :     /*      Special case DELLAYER: command.                                 */
    7465             :     /* -------------------------------------------------------------------- */
    7466        5717 :     if (STARTS_WITH_CI(osSQLCommand, "DELLAYER:"))
    7467             :     {
    7468           4 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DELLAYER:");
    7469             : 
    7470           4 :         while (*pszLayerName == ' ')
    7471           0 :             pszLayerName++;
    7472             : 
    7473           4 :         if (!DeleteVectorOrRasterLayer(pszLayerName))
    7474             :         {
    7475           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7476             :                      pszLayerName);
    7477             :         }
    7478           4 :         return nullptr;
    7479             :     }
    7480             : 
    7481             :     /* -------------------------------------------------------------------- */
    7482             :     /*      Special case RECOMPUTE EXTENT ON command.                       */
    7483             :     /* -------------------------------------------------------------------- */
    7484        5713 :     if (STARTS_WITH_CI(osSQLCommand, "RECOMPUTE EXTENT ON "))
    7485             :     {
    7486             :         const char *pszLayerName =
    7487           4 :             osSQLCommand.c_str() + strlen("RECOMPUTE EXTENT ON ");
    7488             : 
    7489           4 :         while (*pszLayerName == ' ')
    7490           0 :             pszLayerName++;
    7491             : 
    7492           4 :         int idx = FindLayerIndex(pszLayerName);
    7493           4 :         if (idx >= 0)
    7494             :         {
    7495           4 :             m_apoLayers[idx]->RecomputeExtent();
    7496             :         }
    7497             :         else
    7498           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7499             :                      pszLayerName);
    7500           4 :         return nullptr;
    7501             :     }
    7502             : 
    7503             :     /* -------------------------------------------------------------------- */
    7504             :     /*      Intercept DROP TABLE                                            */
    7505             :     /* -------------------------------------------------------------------- */
    7506        5709 :     if (STARTS_WITH_CI(osSQLCommand, "DROP TABLE "))
    7507             :     {
    7508           9 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DROP TABLE ");
    7509             : 
    7510           9 :         while (*pszLayerName == ' ')
    7511           0 :             pszLayerName++;
    7512             : 
    7513           9 :         if (DeleteVectorOrRasterLayer(SQLUnescape(pszLayerName)))
    7514           4 :             return nullptr;
    7515             :     }
    7516             : 
    7517             :     /* -------------------------------------------------------------------- */
    7518             :     /*      Intercept ALTER TABLE src_table RENAME TO dst_table             */
    7519             :     /*      and       ALTER TABLE table RENAME COLUMN src_name TO dst_name  */
    7520             :     /*      and       ALTER TABLE table DROP COLUMN col_name                */
    7521             :     /*                                                                      */
    7522             :     /*      We do this because SQLite mechanisms can't deal with updating   */
    7523             :     /*      literal values in gpkg_ tables that refer to table and column   */
    7524             :     /*      names.                                                          */
    7525             :     /* -------------------------------------------------------------------- */
    7526        5705 :     if (STARTS_WITH_CI(osSQLCommand, "ALTER TABLE "))
    7527             :     {
    7528           9 :         char **papszTokens = SQLTokenize(osSQLCommand);
    7529             :         /* ALTER TABLE src_table RENAME TO dst_table */
    7530          16 :         if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "RENAME") &&
    7531           7 :             EQUAL(papszTokens[4], "TO"))
    7532             :         {
    7533           7 :             const char *pszSrcTableName = papszTokens[2];
    7534           7 :             const char *pszDstTableName = papszTokens[5];
    7535           7 :             if (RenameVectorOrRasterLayer(SQLUnescape(pszSrcTableName),
    7536          14 :                                           SQLUnescape(pszDstTableName)))
    7537             :             {
    7538           6 :                 CSLDestroy(papszTokens);
    7539           6 :                 return nullptr;
    7540             :             }
    7541             :         }
    7542             :         /* ALTER TABLE table RENAME COLUMN src_name TO dst_name */
    7543           2 :         else if (CSLCount(papszTokens) == 8 &&
    7544           1 :                  EQUAL(papszTokens[3], "RENAME") &&
    7545           3 :                  EQUAL(papszTokens[4], "COLUMN") && EQUAL(papszTokens[6], "TO"))
    7546             :         {
    7547           1 :             const char *pszTableName = papszTokens[2];
    7548           1 :             const char *pszSrcColumn = papszTokens[5];
    7549           1 :             const char *pszDstColumn = papszTokens[7];
    7550             :             OGRGeoPackageTableLayer *poLayer =
    7551           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7552           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7553           1 :             if (poLayer)
    7554             :             {
    7555           2 :                 int nSrcFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7556           2 :                     SQLUnescape(pszSrcColumn));
    7557           1 :                 if (nSrcFieldIdx >= 0)
    7558             :                 {
    7559             :                     // OFTString or any type will do as we just alter the name
    7560             :                     // so it will be ignored.
    7561           1 :                     OGRFieldDefn oFieldDefn(SQLUnescape(pszDstColumn),
    7562           1 :                                             OFTString);
    7563           1 :                     poLayer->AlterFieldDefn(nSrcFieldIdx, &oFieldDefn,
    7564             :                                             ALTER_NAME_FLAG);
    7565           1 :                     CSLDestroy(papszTokens);
    7566           1 :                     return nullptr;
    7567             :                 }
    7568             :             }
    7569             :         }
    7570             :         /* ALTER TABLE table DROP COLUMN col_name */
    7571           2 :         else if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "DROP") &&
    7572           1 :                  EQUAL(papszTokens[4], "COLUMN"))
    7573             :         {
    7574           1 :             const char *pszTableName = papszTokens[2];
    7575           1 :             const char *pszColumnName = papszTokens[5];
    7576             :             OGRGeoPackageTableLayer *poLayer =
    7577           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7578           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7579           1 :             if (poLayer)
    7580             :             {
    7581           2 :                 int nFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7582           2 :                     SQLUnescape(pszColumnName));
    7583           1 :                 if (nFieldIdx >= 0)
    7584             :                 {
    7585           1 :                     poLayer->DeleteField(nFieldIdx);
    7586           1 :                     CSLDestroy(papszTokens);
    7587           1 :                     return nullptr;
    7588             :                 }
    7589             :             }
    7590             :         }
    7591           1 :         CSLDestroy(papszTokens);
    7592             :     }
    7593             : 
    7594        5697 :     if (ProcessTransactionSQL(osSQLCommand))
    7595             :     {
    7596         253 :         return nullptr;
    7597             :     }
    7598             : 
    7599        5444 :     if (EQUAL(osSQLCommand, "VACUUM"))
    7600             :     {
    7601          13 :         ResetReadingAllLayers();
    7602             :     }
    7603        5431 :     else if (STARTS_WITH_CI(osSQLCommand, "DELETE FROM "))
    7604             :     {
    7605             :         // Optimize truncation of a table, especially if it has a spatial
    7606             :         // index.
    7607          23 :         const CPLStringList aosTokens(SQLTokenize(osSQLCommand));
    7608          23 :         if (aosTokens.size() == 3)
    7609             :         {
    7610          16 :             const char *pszTableName = aosTokens[2];
    7611             :             OGRGeoPackageTableLayer *poLayer =
    7612           8 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7613          24 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7614          16 :             if (poLayer)
    7615             :             {
    7616           8 :                 poLayer->Truncate();
    7617           8 :                 return nullptr;
    7618             :             }
    7619             :         }
    7620             :     }
    7621        5408 :     else if (pszDialect != nullptr && EQUAL(pszDialect, "INDIRECT_SQLITE"))
    7622           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter, "SQLITE");
    7623        5407 :     else if (pszDialect != nullptr && !EQUAL(pszDialect, "") &&
    7624          67 :              !EQUAL(pszDialect, "NATIVE") && !EQUAL(pszDialect, "SQLITE") &&
    7625          67 :              !EQUAL(pszDialect, "DEBUG"))
    7626           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter,
    7627           1 :                                        pszDialect);
    7628             : 
    7629             :     /* -------------------------------------------------------------------- */
    7630             :     /*      Prepare statement.                                              */
    7631             :     /* -------------------------------------------------------------------- */
    7632             :     /* This will speed-up layer creation */
    7633             :     /* ORDER BY are costly to evaluate and are not necessary to establish */
    7634             :     /* the layer definition. */
    7635        5434 :     bool bUseStatementForGetNextFeature = true;
    7636        5434 :     bool bEmptyLayer = false;
    7637       10868 :     CPLString osSQLCommandTruncated(osSQLCommand);
    7638             : 
    7639       18050 :     if (osSQLCommand.ifind("SELECT ") == 0 &&
    7640        6308 :         CPLString(osSQLCommand.substr(1)).ifind("SELECT ") ==
    7641         833 :             std::string::npos &&
    7642         833 :         osSQLCommand.ifind(" UNION ") == std::string::npos &&
    7643        7141 :         osSQLCommand.ifind(" INTERSECT ") == std::string::npos &&
    7644         833 :         osSQLCommand.ifind(" EXCEPT ") == std::string::npos)
    7645             :     {
    7646         833 :         size_t nOrderByPos = osSQLCommand.ifind(" ORDER BY ");
    7647         833 :         if (nOrderByPos != std::string::npos)
    7648             :         {
    7649           9 :             osSQLCommandTruncated.resize(nOrderByPos);
    7650           9 :             bUseStatementForGetNextFeature = false;
    7651             :         }
    7652             :     }
    7653             : 
    7654        5434 :     const auto nErrorCount = CPLGetErrorCounter();
    7655             :     sqlite3_stmt *hSQLStmt =
    7656        5434 :         prepareSql(hDB, osSQLCommandTruncated.c_str(),
    7657        5434 :                    static_cast<int>(osSQLCommandTruncated.size()));
    7658        5434 :     if (!hSQLStmt)
    7659             :     {
    7660          12 :         if (nErrorCount == CPLGetErrorCounter())
    7661             :         {
    7662           9 :             CPLError(CE_Failure, CPLE_AppDefined, "%s",
    7663          18 :                      SQLFormatErrorMsgFailedPrepare(
    7664             :                          GetDB(), "In ExecuteSQL(): sqlite3_prepare_v2(): ",
    7665             :                          osSQLCommand.c_str())
    7666             :                          .c_str());
    7667             :         }
    7668          12 :         return nullptr;
    7669             :     }
    7670             : 
    7671             :     /* -------------------------------------------------------------------- */
    7672             :     /*      Do we get a resultset?                                          */
    7673             :     /* -------------------------------------------------------------------- */
    7674        5422 :     int rc = sqlite3_step(hSQLStmt);
    7675             : 
    7676        7096 :     for (auto &poLayer : m_apoLayers)
    7677             :     {
    7678        1674 :         if (!poLayer->RunDeferredDropRTreeTableIfNecessary())
    7679           0 :             return nullptr;
    7680             :     }
    7681             : 
    7682        5422 :     if (rc != SQLITE_ROW)
    7683             :     {
    7684        4635 :         if (rc != SQLITE_DONE)
    7685             :         {
    7686           7 :             CPLError(CE_Failure, CPLE_AppDefined,
    7687             :                      "In ExecuteSQL(): sqlite3_step(%s):\n  %s",
    7688             :                      osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7689             : 
    7690           7 :             sqlite3_finalize(hSQLStmt);
    7691           7 :             return nullptr;
    7692             :         }
    7693             : 
    7694        4628 :         if (EQUAL(osSQLCommand, "VACUUM"))
    7695             :         {
    7696          13 :             sqlite3_finalize(hSQLStmt);
    7697             :             /* VACUUM rewrites the DB, so we need to reset the application id */
    7698          13 :             SetApplicationAndUserVersionId();
    7699          13 :             return nullptr;
    7700             :         }
    7701             : 
    7702        4615 :         if (!STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7703             :         {
    7704        4487 :             sqlite3_finalize(hSQLStmt);
    7705        4487 :             return nullptr;
    7706             :         }
    7707             : 
    7708         128 :         bUseStatementForGetNextFeature = false;
    7709         128 :         bEmptyLayer = true;
    7710             :     }
    7711             : 
    7712             :     /* -------------------------------------------------------------------- */
    7713             :     /*      Special case for some functions which must be run               */
    7714             :     /*      only once                                                       */
    7715             :     /* -------------------------------------------------------------------- */
    7716         915 :     if (STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7717             :     {
    7718        4199 :         for (unsigned int i = 0; i < sizeof(apszFuncsWithSideEffects) /
    7719             :                                          sizeof(apszFuncsWithSideEffects[0]);
    7720             :              i++)
    7721             :         {
    7722        3385 :             if (EQUALN(apszFuncsWithSideEffects[i], osSQLCommand.c_str() + 7,
    7723             :                        strlen(apszFuncsWithSideEffects[i])))
    7724             :             {
    7725         112 :                 if (sqlite3_column_count(hSQLStmt) == 1 &&
    7726          56 :                     sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7727             :                 {
    7728          56 :                     int ret = sqlite3_column_int(hSQLStmt, 0);
    7729             : 
    7730          56 :                     sqlite3_finalize(hSQLStmt);
    7731             : 
    7732             :                     return new OGRSQLiteSingleFeatureLayer(
    7733          56 :                         apszFuncsWithSideEffects[i], ret);
    7734             :                 }
    7735             :             }
    7736             :         }
    7737             :     }
    7738          45 :     else if (STARTS_WITH_CI(osSQLCommand, "PRAGMA "))
    7739             :     {
    7740          63 :         if (sqlite3_column_count(hSQLStmt) == 1 &&
    7741          18 :             sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7742             :         {
    7743          15 :             int ret = sqlite3_column_int(hSQLStmt, 0);
    7744             : 
    7745          15 :             sqlite3_finalize(hSQLStmt);
    7746             : 
    7747          15 :             return new OGRSQLiteSingleFeatureLayer(osSQLCommand.c_str() + 7,
    7748          15 :                                                    ret);
    7749             :         }
    7750          33 :         else if (sqlite3_column_count(hSQLStmt) == 1 &&
    7751           3 :                  sqlite3_column_type(hSQLStmt, 0) == SQLITE_TEXT)
    7752             :         {
    7753             :             const char *pszRet = reinterpret_cast<const char *>(
    7754           3 :                 sqlite3_column_text(hSQLStmt, 0));
    7755             : 
    7756             :             OGRLayer *poRet = new OGRSQLiteSingleFeatureLayer(
    7757           3 :                 osSQLCommand.c_str() + 7, pszRet);
    7758             : 
    7759           3 :             sqlite3_finalize(hSQLStmt);
    7760             : 
    7761           3 :             return poRet;
    7762             :         }
    7763             :     }
    7764             : 
    7765             :     /* -------------------------------------------------------------------- */
    7766             :     /*      Create layer.                                                   */
    7767             :     /* -------------------------------------------------------------------- */
    7768             : 
    7769             :     auto poLayer = std::make_unique<OGRGeoPackageSelectLayer>(
    7770             :         this, osSQLCommand, hSQLStmt, bUseStatementForGetNextFeature,
    7771        1682 :         bEmptyLayer);
    7772             : 
    7773         844 :     if (poSpatialFilter != nullptr &&
    7774           3 :         poLayer->GetLayerDefn()->GetGeomFieldCount() > 0)
    7775           3 :         poLayer->SetSpatialFilter(0, poSpatialFilter);
    7776             : 
    7777         841 :     return poLayer.release();
    7778             : }
    7779             : 
    7780             : /************************************************************************/
    7781             : /*                          ReleaseResultSet()                          */
    7782             : /************************************************************************/
    7783             : 
    7784         874 : void GDALGeoPackageDataset::ReleaseResultSet(OGRLayer *poLayer)
    7785             : 
    7786             : {
    7787         874 :     delete poLayer;
    7788         874 : }
    7789             : 
    7790             : /************************************************************************/
    7791             : /*                         HasExtensionsTable()                         */
    7792             : /************************************************************************/
    7793             : 
    7794        7644 : bool GDALGeoPackageDataset::HasExtensionsTable()
    7795             : {
    7796        7644 :     return SQLGetInteger(
    7797             :                hDB,
    7798             :                "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_extensions' "
    7799             :                "AND type IN ('table', 'view')",
    7800        7644 :                nullptr) == 1;
    7801             : }
    7802             : 
    7803             : /************************************************************************/
    7804             : /*                       CheckUnknownExtensions()                       */
    7805             : /************************************************************************/
    7806             : 
    7807        1690 : void GDALGeoPackageDataset::CheckUnknownExtensions(bool bCheckRasterTable)
    7808             : {
    7809        1690 :     if (!HasExtensionsTable())
    7810         217 :         return;
    7811             : 
    7812        1473 :     char *pszSQL = nullptr;
    7813        1473 :     if (!bCheckRasterTable)
    7814        1257 :         pszSQL = sqlite3_mprintf(
    7815             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7816             :             "WHERE (table_name IS NULL "
    7817             :             "AND extension_name IS NOT NULL "
    7818             :             "AND definition IS NOT NULL "
    7819             :             "AND scope IS NOT NULL "
    7820             :             "AND extension_name NOT IN ("
    7821             :             "'gdal_aspatial', "
    7822             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7823             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7824             :                                        // 17-066r1 finalization
    7825             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7826             :             "'gpkg_metadata', "
    7827             :             "'gpkg_schema', "
    7828             :             "'gpkg_crs_wkt', "
    7829             :             "'gpkg_crs_wkt_1_1', "
    7830             :             "'related_tables', 'gpkg_related_tables')) "
    7831             : #ifdef WORKAROUND_SQLITE3_BUGS
    7832             :             "OR 0 "
    7833             : #endif
    7834             :             "LIMIT 1000");
    7835             :     else
    7836         216 :         pszSQL = sqlite3_mprintf(
    7837             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7838             :             "WHERE (lower(table_name) = lower('%q') "
    7839             :             "AND extension_name IS NOT NULL "
    7840             :             "AND definition IS NOT NULL "
    7841             :             "AND scope IS NOT NULL "
    7842             :             "AND extension_name NOT IN ("
    7843             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7844             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7845             :                                        // 17-066r1 finalization
    7846             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7847             :             "'gpkg_metadata', "
    7848             :             "'gpkg_schema', "
    7849             :             "'gpkg_crs_wkt', "
    7850             :             "'gpkg_crs_wkt_1_1', "
    7851             :             "'related_tables', 'gpkg_related_tables')) "
    7852             : #ifdef WORKAROUND_SQLITE3_BUGS
    7853             :             "OR 0 "
    7854             : #endif
    7855             :             "LIMIT 1000",
    7856             :             m_osRasterTable.c_str());
    7857             : 
    7858        2946 :     auto oResultTable = SQLQuery(GetDB(), pszSQL);
    7859        1473 :     sqlite3_free(pszSQL);
    7860        1473 :     if (oResultTable && oResultTable->RowCount() > 0)
    7861             :     {
    7862          42 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    7863             :         {
    7864          21 :             const char *pszExtName = oResultTable->GetValue(0, i);
    7865          21 :             const char *pszDefinition = oResultTable->GetValue(1, i);
    7866          21 :             const char *pszScope = oResultTable->GetValue(2, i);
    7867          21 :             if (pszExtName == nullptr || pszDefinition == nullptr ||
    7868             :                 pszScope == nullptr)
    7869             :             {
    7870           0 :                 continue;
    7871             :             }
    7872             : 
    7873          21 :             if (EQUAL(pszExtName, "gpkg_webp"))
    7874             :             {
    7875          15 :                 if (GDALGetDriverByName("WEBP") == nullptr)
    7876             :                 {
    7877           1 :                     CPLError(
    7878             :                         CE_Warning, CPLE_AppDefined,
    7879             :                         "Table %s contains WEBP tiles, but GDAL configured "
    7880             :                         "without WEBP support. Data will be missing",
    7881             :                         m_osRasterTable.c_str());
    7882             :                 }
    7883          15 :                 m_eTF = GPKG_TF_WEBP;
    7884          15 :                 continue;
    7885             :             }
    7886           6 :             if (EQUAL(pszExtName, "gpkg_zoom_other"))
    7887             :             {
    7888           2 :                 m_bZoomOther = true;
    7889           2 :                 continue;
    7890             :             }
    7891             : 
    7892           4 :             if (GetUpdate() && EQUAL(pszScope, "write-only"))
    7893             :             {
    7894           1 :                 CPLError(
    7895             :                     CE_Warning, CPLE_AppDefined,
    7896             :                     "Database relies on the '%s' (%s) extension that should "
    7897             :                     "be implemented for safe write-support, but is not "
    7898             :                     "currently. "
    7899             :                     "Update of that database are strongly discouraged to avoid "
    7900             :                     "corruption.",
    7901             :                     pszExtName, pszDefinition);
    7902             :             }
    7903           3 :             else if (GetUpdate() && EQUAL(pszScope, "read-write"))
    7904             :             {
    7905           1 :                 CPLError(
    7906             :                     CE_Warning, CPLE_AppDefined,
    7907             :                     "Database relies on the '%s' (%s) extension that should "
    7908             :                     "be implemented in order to read/write it safely, but is "
    7909             :                     "not currently. "
    7910             :                     "Some data may be missing while reading that database, and "
    7911             :                     "updates are strongly discouraged.",
    7912             :                     pszExtName, pszDefinition);
    7913             :             }
    7914           2 :             else if (EQUAL(pszScope, "read-write") &&
    7915             :                      // None of the NGA extensions at
    7916             :                      // http://ngageoint.github.io/GeoPackage/docs/extensions/
    7917             :                      // affect read-only scenarios
    7918           1 :                      !STARTS_WITH(pszExtName, "nga_"))
    7919             :             {
    7920           1 :                 CPLError(
    7921             :                     CE_Warning, CPLE_AppDefined,
    7922             :                     "Database relies on the '%s' (%s) extension that should "
    7923             :                     "be implemented in order to read it safely, but is not "
    7924             :                     "currently. "
    7925             :                     "Some data may be missing while reading that database.",
    7926             :                     pszExtName, pszDefinition);
    7927             :             }
    7928             :         }
    7929             :     }
    7930             : }
    7931             : 
    7932             : /************************************************************************/
    7933             : /*                      HasGDALAspatialExtension()                      */
    7934             : /************************************************************************/
    7935             : 
    7936        1217 : bool GDALGeoPackageDataset::HasGDALAspatialExtension()
    7937             : {
    7938        1217 :     if (!HasExtensionsTable())
    7939         103 :         return false;
    7940             : 
    7941             :     auto oResultTable = SQLQuery(hDB, "SELECT * FROM gpkg_extensions "
    7942             :                                       "WHERE (extension_name = 'gdal_aspatial' "
    7943             :                                       "AND table_name IS NULL "
    7944             :                                       "AND column_name IS NULL)"
    7945             : #ifdef WORKAROUND_SQLITE3_BUGS
    7946             :                                       " OR 0"
    7947             : #endif
    7948        1114 :     );
    7949        1114 :     bool bHasExtension = (oResultTable && oResultTable->RowCount() == 1);
    7950        1114 :     return bHasExtension;
    7951             : }
    7952             : 
    7953             : std::string
    7954         196 : GDALGeoPackageDataset::CreateRasterTriggersSQL(const std::string &osTableName)
    7955             : {
    7956             :     char *pszSQL;
    7957         196 :     std::string osSQL;
    7958             :     /* From D.5. sample_tile_pyramid Table 43. tiles table Trigger
    7959             :      * Definition SQL  */
    7960         196 :     pszSQL = sqlite3_mprintf(
    7961             :         "CREATE TRIGGER \"%w_zoom_insert\" "
    7962             :         "BEFORE INSERT ON \"%w\" "
    7963             :         "FOR EACH ROW BEGIN "
    7964             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7965             :         "constraint: zoom_level not specified for table in "
    7966             :         "gpkg_tile_matrix') "
    7967             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7968             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7969             :         "END; "
    7970             :         "CREATE TRIGGER \"%w_zoom_update\" "
    7971             :         "BEFORE UPDATE OF zoom_level ON \"%w\" "
    7972             :         "FOR EACH ROW BEGIN "
    7973             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7974             :         "constraint: zoom_level not specified for table in "
    7975             :         "gpkg_tile_matrix') "
    7976             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7977             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7978             :         "END; "
    7979             :         "CREATE TRIGGER \"%w_tile_column_insert\" "
    7980             :         "BEFORE INSERT ON \"%w\" "
    7981             :         "FOR EACH ROW BEGIN "
    7982             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7983             :         "constraint: tile_column cannot be < 0') "
    7984             :         "WHERE (NEW.tile_column < 0) ; "
    7985             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7986             :         "constraint: tile_column must by < matrix_width specified for "
    7987             :         "table and zoom level in gpkg_tile_matrix') "
    7988             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    7989             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    7990             :         "zoom_level = NEW.zoom_level)); "
    7991             :         "END; "
    7992             :         "CREATE TRIGGER \"%w_tile_column_update\" "
    7993             :         "BEFORE UPDATE OF tile_column ON \"%w\" "
    7994             :         "FOR EACH ROW BEGIN "
    7995             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7996             :         "constraint: tile_column cannot be < 0') "
    7997             :         "WHERE (NEW.tile_column < 0) ; "
    7998             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7999             :         "constraint: tile_column must by < matrix_width specified for "
    8000             :         "table and zoom level in gpkg_tile_matrix') "
    8001             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    8002             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8003             :         "zoom_level = NEW.zoom_level)); "
    8004             :         "END; "
    8005             :         "CREATE TRIGGER \"%w_tile_row_insert\" "
    8006             :         "BEFORE INSERT ON \"%w\" "
    8007             :         "FOR EACH ROW BEGIN "
    8008             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8009             :         "constraint: tile_row cannot be < 0') "
    8010             :         "WHERE (NEW.tile_row < 0) ; "
    8011             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8012             :         "constraint: tile_row must by < matrix_height specified for "
    8013             :         "table and zoom level in gpkg_tile_matrix') "
    8014             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8015             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8016             :         "zoom_level = NEW.zoom_level)); "
    8017             :         "END; "
    8018             :         "CREATE TRIGGER \"%w_tile_row_update\" "
    8019             :         "BEFORE UPDATE OF tile_row ON \"%w\" "
    8020             :         "FOR EACH ROW BEGIN "
    8021             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8022             :         "constraint: tile_row cannot be < 0') "
    8023             :         "WHERE (NEW.tile_row < 0) ; "
    8024             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8025             :         "constraint: tile_row must by < matrix_height specified for "
    8026             :         "table and zoom level in gpkg_tile_matrix') "
    8027             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8028             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8029             :         "zoom_level = NEW.zoom_level)); "
    8030             :         "END; ",
    8031             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8032             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8033             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8034             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8035             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8036             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8037             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8038             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8039             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8040             :         osTableName.c_str());
    8041         196 :     osSQL = pszSQL;
    8042         196 :     sqlite3_free(pszSQL);
    8043         196 :     return osSQL;
    8044             : }
    8045             : 
    8046             : /************************************************************************/
    8047             : /*                  CreateExtensionsTableIfNecessary()                  */
    8048             : /************************************************************************/
    8049             : 
    8050        1369 : OGRErr GDALGeoPackageDataset::CreateExtensionsTableIfNecessary()
    8051             : {
    8052             :     /* Check if the table gpkg_extensions exists */
    8053        1369 :     if (HasExtensionsTable())
    8054         461 :         return OGRERR_NONE;
    8055             : 
    8056             :     /* Requirement 79 : Every extension of a GeoPackage SHALL be registered */
    8057             :     /* in a corresponding row in the gpkg_extensions table. The absence of a */
    8058             :     /* gpkg_extensions table or the absence of rows in gpkg_extensions table */
    8059             :     /* SHALL both indicate the absence of extensions to a GeoPackage. */
    8060         908 :     const char *pszCreateGpkgExtensions =
    8061             :         "CREATE TABLE gpkg_extensions ("
    8062             :         "table_name TEXT,"
    8063             :         "column_name TEXT,"
    8064             :         "extension_name TEXT NOT NULL,"
    8065             :         "definition TEXT NOT NULL,"
    8066             :         "scope TEXT NOT NULL,"
    8067             :         "CONSTRAINT ge_tce UNIQUE (table_name, column_name, extension_name)"
    8068             :         ")";
    8069             : 
    8070         908 :     return SQLCommand(hDB, pszCreateGpkgExtensions);
    8071             : }
    8072             : 
    8073             : /************************************************************************/
    8074             : /*                 OGR_GPKG_Intersects_Spatial_Filter()                 */
    8075             : /************************************************************************/
    8076             : 
    8077       23236 : void OGR_GPKG_Intersects_Spatial_Filter(sqlite3_context *pContext, int argc,
    8078             :                                         sqlite3_value **argv)
    8079             : {
    8080       23236 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8081             :     {
    8082           0 :         sqlite3_result_int(pContext, 0);
    8083       23226 :         return;
    8084             :     }
    8085             : 
    8086             :     auto poLayer =
    8087       23236 :         static_cast<OGRGeoPackageTableLayer *>(sqlite3_user_data(pContext));
    8088             : 
    8089       23236 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8090             :     const GByte *pabyBLOB =
    8091       23236 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8092             : 
    8093             :     GPkgHeader sHeader;
    8094       46472 :     if (poLayer->m_bFilterIsEnvelope &&
    8095       23236 :         OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false, 0))
    8096             :     {
    8097       23236 :         if (sHeader.bExtentHasXY)
    8098             :         {
    8099          95 :             OGREnvelope sEnvelope;
    8100          95 :             sEnvelope.MinX = sHeader.MinX;
    8101          95 :             sEnvelope.MinY = sHeader.MinY;
    8102          95 :             sEnvelope.MaxX = sHeader.MaxX;
    8103          95 :             sEnvelope.MaxY = sHeader.MaxY;
    8104          95 :             if (poLayer->m_sFilterEnvelope.Contains(sEnvelope))
    8105             :             {
    8106          31 :                 sqlite3_result_int(pContext, 1);
    8107          31 :                 return;
    8108             :             }
    8109             :         }
    8110             : 
    8111             :         // Check if at least one point falls into the layer filter envelope
    8112             :         // nHeaderLen is > 0 for GeoPackage geometries
    8113       46410 :         if (sHeader.nHeaderLen > 0 &&
    8114       23205 :             OGRWKBIntersectsPessimistic(pabyBLOB + sHeader.nHeaderLen,
    8115       23205 :                                         nBLOBLen - sHeader.nHeaderLen,
    8116       23205 :                                         poLayer->m_sFilterEnvelope))
    8117             :         {
    8118       23195 :             sqlite3_result_int(pContext, 1);
    8119       23195 :             return;
    8120             :         }
    8121             :     }
    8122             : 
    8123             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8124          10 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8125          10 :     if (poGeom == nullptr)
    8126             :     {
    8127             :         // Try also spatialite geometry blobs
    8128           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8129           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8130           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8131             :         {
    8132           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8133           0 :             sqlite3_result_int(pContext, 0);
    8134           0 :             return;
    8135             :         }
    8136           0 :         poGeom.reset(poGeomSpatialite);
    8137             :     }
    8138             : 
    8139          10 :     sqlite3_result_int(pContext, poLayer->FilterGeometry(poGeom.get()));
    8140             : }
    8141             : 
    8142             : /************************************************************************/
    8143             : /*                        OGRGeoPackageSTMinX()                         */
    8144             : /************************************************************************/
    8145             : 
    8146      253065 : static void OGRGeoPackageSTMinX(sqlite3_context *pContext, int argc,
    8147             :                                 sqlite3_value **argv)
    8148             : {
    8149             :     GPkgHeader sHeader;
    8150      253065 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8151             :     {
    8152          17 :         sqlite3_result_null(pContext);
    8153          17 :         return;
    8154             :     }
    8155      253048 :     sqlite3_result_double(pContext, sHeader.MinX);
    8156             : }
    8157             : 
    8158             : /************************************************************************/
    8159             : /*                        OGRGeoPackageSTMinY()                         */
    8160             : /************************************************************************/
    8161             : 
    8162      253049 : static void OGRGeoPackageSTMinY(sqlite3_context *pContext, int argc,
    8163             :                                 sqlite3_value **argv)
    8164             : {
    8165             :     GPkgHeader sHeader;
    8166      253049 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8167             :     {
    8168           1 :         sqlite3_result_null(pContext);
    8169           1 :         return;
    8170             :     }
    8171      253048 :     sqlite3_result_double(pContext, sHeader.MinY);
    8172             : }
    8173             : 
    8174             : /************************************************************************/
    8175             : /*                        OGRGeoPackageSTMaxX()                         */
    8176             : /************************************************************************/
    8177             : 
    8178      253049 : static void OGRGeoPackageSTMaxX(sqlite3_context *pContext, int argc,
    8179             :                                 sqlite3_value **argv)
    8180             : {
    8181             :     GPkgHeader sHeader;
    8182      253049 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8183             :     {
    8184           1 :         sqlite3_result_null(pContext);
    8185           1 :         return;
    8186             :     }
    8187      253048 :     sqlite3_result_double(pContext, sHeader.MaxX);
    8188             : }
    8189             : 
    8190             : /************************************************************************/
    8191             : /*                        OGRGeoPackageSTMaxY()                         */
    8192             : /************************************************************************/
    8193             : 
    8194      253049 : static void OGRGeoPackageSTMaxY(sqlite3_context *pContext, int argc,
    8195             :                                 sqlite3_value **argv)
    8196             : {
    8197             :     GPkgHeader sHeader;
    8198      253049 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8199             :     {
    8200           1 :         sqlite3_result_null(pContext);
    8201           1 :         return;
    8202             :     }
    8203      253048 :     sqlite3_result_double(pContext, sHeader.MaxY);
    8204             : }
    8205             : 
    8206             : /************************************************************************/
    8207             : /*                       OGRGeoPackageSTIsEmpty()                       */
    8208             : /************************************************************************/
    8209             : 
    8210      254499 : static void OGRGeoPackageSTIsEmpty(sqlite3_context *pContext, int argc,
    8211             :                                    sqlite3_value **argv)
    8212             : {
    8213             :     GPkgHeader sHeader;
    8214      254499 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8215             :     {
    8216           2 :         sqlite3_result_null(pContext);
    8217           2 :         return;
    8218             :     }
    8219      254497 :     sqlite3_result_int(pContext, sHeader.bEmpty);
    8220             : }
    8221             : 
    8222             : /************************************************************************/
    8223             : /*                    OGRGeoPackageSTGeometryType()                     */
    8224             : /************************************************************************/
    8225             : 
    8226           7 : static void OGRGeoPackageSTGeometryType(sqlite3_context *pContext, int /*argc*/,
    8227             :                                         sqlite3_value **argv)
    8228             : {
    8229             :     GPkgHeader sHeader;
    8230             : 
    8231           7 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8232             :     const GByte *pabyBLOB =
    8233           7 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8234             :     OGRwkbGeometryType eGeometryType;
    8235             : 
    8236          13 :     if (nBLOBLen < 8 ||
    8237           6 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8238             :     {
    8239           2 :         if (OGRSQLiteGetSpatialiteGeometryHeader(
    8240             :                 pabyBLOB, nBLOBLen, nullptr, &eGeometryType, nullptr, nullptr,
    8241           2 :                 nullptr, nullptr, nullptr) == OGRERR_NONE)
    8242             :         {
    8243           1 :             sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8244             :                                 SQLITE_TRANSIENT);
    8245           4 :             return;
    8246             :         }
    8247             :         else
    8248             :         {
    8249           1 :             sqlite3_result_null(pContext);
    8250           1 :             return;
    8251             :         }
    8252             :     }
    8253             : 
    8254           5 :     if (static_cast<size_t>(nBLOBLen) < sHeader.nHeaderLen + 5)
    8255             :     {
    8256           2 :         sqlite3_result_null(pContext);
    8257           2 :         return;
    8258             :     }
    8259             : 
    8260           3 :     OGRErr err = OGRReadWKBGeometryType(pabyBLOB + sHeader.nHeaderLen,
    8261             :                                         wkbVariantIso, &eGeometryType);
    8262           3 :     if (err != OGRERR_NONE)
    8263           1 :         sqlite3_result_null(pContext);
    8264             :     else
    8265           2 :         sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8266             :                             SQLITE_TRANSIENT);
    8267             : }
    8268             : 
    8269             : /************************************************************************/
    8270             : /*                 OGRGeoPackageSTEnvelopesIntersects()                 */
    8271             : /************************************************************************/
    8272             : 
    8273         118 : static void OGRGeoPackageSTEnvelopesIntersects(sqlite3_context *pContext,
    8274             :                                                int argc, sqlite3_value **argv)
    8275             : {
    8276             :     GPkgHeader sHeader;
    8277         118 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8278             :     {
    8279           2 :         sqlite3_result_int(pContext, FALSE);
    8280         107 :         return;
    8281             :     }
    8282         116 :     const double dfMinX = sqlite3_value_double(argv[1]);
    8283         116 :     if (sHeader.MaxX < dfMinX)
    8284             :     {
    8285          93 :         sqlite3_result_int(pContext, FALSE);
    8286          93 :         return;
    8287             :     }
    8288          23 :     const double dfMinY = sqlite3_value_double(argv[2]);
    8289          23 :     if (sHeader.MaxY < dfMinY)
    8290             :     {
    8291          11 :         sqlite3_result_int(pContext, FALSE);
    8292          11 :         return;
    8293             :     }
    8294          12 :     const double dfMaxX = sqlite3_value_double(argv[3]);
    8295          12 :     if (sHeader.MinX > dfMaxX)
    8296             :     {
    8297           1 :         sqlite3_result_int(pContext, FALSE);
    8298           1 :         return;
    8299             :     }
    8300          11 :     const double dfMaxY = sqlite3_value_double(argv[4]);
    8301          11 :     sqlite3_result_int(pContext, sHeader.MinY <= dfMaxY);
    8302             : }
    8303             : 
    8304             : /************************************************************************/
    8305             : /*            OGRGeoPackageSTEnvelopesIntersectsTwoParams()             */
    8306             : /************************************************************************/
    8307             : 
    8308             : static void
    8309           3 : OGRGeoPackageSTEnvelopesIntersectsTwoParams(sqlite3_context *pContext, int argc,
    8310             :                                             sqlite3_value **argv)
    8311             : {
    8312             :     GPkgHeader sHeader;
    8313           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false, 0))
    8314             :     {
    8315           0 :         sqlite3_result_int(pContext, FALSE);
    8316           2 :         return;
    8317             :     }
    8318             :     GPkgHeader sHeader2;
    8319           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader2, true, false,
    8320             :                                 1))
    8321             :     {
    8322           0 :         sqlite3_result_int(pContext, FALSE);
    8323           0 :         return;
    8324             :     }
    8325           3 :     if (sHeader.MaxX < sHeader2.MinX)
    8326             :     {
    8327           1 :         sqlite3_result_int(pContext, FALSE);
    8328           1 :         return;
    8329             :     }
    8330           2 :     if (sHeader.MaxY < sHeader2.MinY)
    8331             :     {
    8332           0 :         sqlite3_result_int(pContext, FALSE);
    8333           0 :         return;
    8334             :     }
    8335           2 :     if (sHeader.MinX > sHeader2.MaxX)
    8336             :     {
    8337           1 :         sqlite3_result_int(pContext, FALSE);
    8338           1 :         return;
    8339             :     }
    8340           1 :     sqlite3_result_int(pContext, sHeader.MinY <= sHeader2.MaxY);
    8341             : }
    8342             : 
    8343             : /************************************************************************/
    8344             : /*                   OGRGeoPackageGPKGIsAssignable()                    */
    8345             : /************************************************************************/
    8346             : 
    8347           8 : static void OGRGeoPackageGPKGIsAssignable(sqlite3_context *pContext,
    8348             :                                           int /*argc*/, sqlite3_value **argv)
    8349             : {
    8350          15 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8351           7 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8352             :     {
    8353           2 :         sqlite3_result_int(pContext, 0);
    8354           2 :         return;
    8355             :     }
    8356             : 
    8357             :     const char *pszExpected =
    8358           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8359             :     const char *pszActual =
    8360           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8361           6 :     int bIsAssignable = OGR_GT_IsSubClassOf(OGRFromOGCGeomType(pszActual),
    8362             :                                             OGRFromOGCGeomType(pszExpected));
    8363           6 :     sqlite3_result_int(pContext, bIsAssignable);
    8364             : }
    8365             : 
    8366             : /************************************************************************/
    8367             : /*                        OGRGeoPackageSTSRID()                         */
    8368             : /************************************************************************/
    8369             : 
    8370          12 : static void OGRGeoPackageSTSRID(sqlite3_context *pContext, int argc,
    8371             :                                 sqlite3_value **argv)
    8372             : {
    8373             :     GPkgHeader sHeader;
    8374          12 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8375             :     {
    8376           2 :         sqlite3_result_null(pContext);
    8377           2 :         return;
    8378             :     }
    8379          10 :     sqlite3_result_int(pContext, sHeader.iSrsId);
    8380             : }
    8381             : 
    8382             : /************************************************************************/
    8383             : /*                        OGRGeoPackageSetSRID()                        */
    8384             : /************************************************************************/
    8385             : 
    8386          28 : static void OGRGeoPackageSetSRID(sqlite3_context *pContext, int /* argc */,
    8387             :                                  sqlite3_value **argv)
    8388             : {
    8389          28 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8390             :     {
    8391           1 :         sqlite3_result_null(pContext);
    8392           1 :         return;
    8393             :     }
    8394          27 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8395             :     GPkgHeader sHeader;
    8396          27 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8397             :     const GByte *pabyBLOB =
    8398          27 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8399             : 
    8400          54 :     if (nBLOBLen < 8 ||
    8401          27 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8402             :     {
    8403             :         // Try also spatialite geometry blobs
    8404           0 :         OGRGeometry *poGeom = nullptr;
    8405           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeom) !=
    8406             :             OGRERR_NONE)
    8407             :         {
    8408           0 :             sqlite3_result_null(pContext);
    8409           0 :             return;
    8410             :         }
    8411           0 :         size_t nBLOBDestLen = 0;
    8412             :         GByte *pabyDestBLOB =
    8413           0 :             GPkgGeometryFromOGR(poGeom, nDestSRID, nullptr, &nBLOBDestLen);
    8414           0 :         if (!pabyDestBLOB)
    8415             :         {
    8416           0 :             sqlite3_result_null(pContext);
    8417           0 :             return;
    8418             :         }
    8419           0 :         sqlite3_result_blob(pContext, pabyDestBLOB,
    8420             :                             static_cast<int>(nBLOBDestLen), VSIFree);
    8421           0 :         return;
    8422             :     }
    8423             : 
    8424          27 :     GByte *pabyDestBLOB = static_cast<GByte *>(CPLMalloc(nBLOBLen));
    8425          27 :     memcpy(pabyDestBLOB, pabyBLOB, nBLOBLen);
    8426          27 :     int32_t nSRIDToSerialize = nDestSRID;
    8427          27 :     if (OGR_SWAP(sHeader.eByteOrder))
    8428           0 :         nSRIDToSerialize = CPL_SWAP32(nSRIDToSerialize);
    8429          27 :     memcpy(pabyDestBLOB + 4, &nSRIDToSerialize, 4);
    8430          27 :     sqlite3_result_blob(pContext, pabyDestBLOB, nBLOBLen, VSIFree);
    8431             : }
    8432             : 
    8433             : /************************************************************************/
    8434             : /*                      OGRGeoPackageSTMakeValid()                      */
    8435             : /************************************************************************/
    8436             : 
    8437           3 : static void OGRGeoPackageSTMakeValid(sqlite3_context *pContext, int argc,
    8438             :                                      sqlite3_value **argv)
    8439             : {
    8440           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8441             :     {
    8442           2 :         sqlite3_result_null(pContext);
    8443           2 :         return;
    8444             :     }
    8445           1 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8446             :     const GByte *pabyBLOB =
    8447           1 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8448             : 
    8449             :     GPkgHeader sHeader;
    8450           1 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8451             :     {
    8452           0 :         sqlite3_result_null(pContext);
    8453           0 :         return;
    8454             :     }
    8455             : 
    8456             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8457           1 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8458           1 :     if (poGeom == nullptr)
    8459             :     {
    8460             :         // Try also spatialite geometry blobs
    8461           0 :         OGRGeometry *poGeomPtr = nullptr;
    8462           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8463             :             OGRERR_NONE)
    8464             :         {
    8465           0 :             sqlite3_result_null(pContext);
    8466           0 :             return;
    8467             :         }
    8468           0 :         poGeom.reset(poGeomPtr);
    8469             :     }
    8470           1 :     auto poValid = std::unique_ptr<OGRGeometry>(poGeom->MakeValid());
    8471           1 :     if (poValid == nullptr)
    8472             :     {
    8473           0 :         sqlite3_result_null(pContext);
    8474           0 :         return;
    8475             :     }
    8476             : 
    8477           1 :     size_t nBLOBDestLen = 0;
    8478           1 :     GByte *pabyDestBLOB = GPkgGeometryFromOGR(poValid.get(), sHeader.iSrsId,
    8479             :                                               nullptr, &nBLOBDestLen);
    8480           1 :     if (!pabyDestBLOB)
    8481             :     {
    8482           0 :         sqlite3_result_null(pContext);
    8483           0 :         return;
    8484             :     }
    8485           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8486             :                         VSIFree);
    8487             : }
    8488             : 
    8489             : /************************************************************************/
    8490             : /*                        OGRGeoPackageSTArea()                         */
    8491             : /************************************************************************/
    8492             : 
    8493          19 : static void OGRGeoPackageSTArea(sqlite3_context *pContext, int /*argc*/,
    8494             :                                 sqlite3_value **argv)
    8495             : {
    8496          19 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8497             :     {
    8498           1 :         sqlite3_result_null(pContext);
    8499          15 :         return;
    8500             :     }
    8501          18 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8502             :     const GByte *pabyBLOB =
    8503          18 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8504             : 
    8505             :     GPkgHeader sHeader;
    8506           0 :     std::unique_ptr<OGRGeometry> poGeom;
    8507          18 :     if (GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) == OGRERR_NONE)
    8508             :     {
    8509          16 :         if (sHeader.bEmpty)
    8510             :         {
    8511           3 :             sqlite3_result_double(pContext, 0);
    8512          13 :             return;
    8513             :         }
    8514          13 :         const GByte *pabyWkb = pabyBLOB + sHeader.nHeaderLen;
    8515          13 :         size_t nWKBSize = nBLOBLen - sHeader.nHeaderLen;
    8516             :         bool bNeedSwap;
    8517             :         uint32_t nType;
    8518          13 :         if (OGRWKBGetGeomType(pabyWkb, nWKBSize, bNeedSwap, nType))
    8519             :         {
    8520          13 :             if (nType == wkbPolygon || nType == wkbPolygon25D ||
    8521          11 :                 nType == wkbPolygon + 1000 ||  // wkbPolygonZ
    8522          10 :                 nType == wkbPolygonM || nType == wkbPolygonZM)
    8523             :             {
    8524             :                 double dfArea;
    8525           5 :                 if (OGRWKBPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8526             :                 {
    8527           5 :                     sqlite3_result_double(pContext, dfArea);
    8528           5 :                     return;
    8529           0 :                 }
    8530             :             }
    8531           8 :             else if (nType == wkbMultiPolygon || nType == wkbMultiPolygon25D ||
    8532           6 :                      nType == wkbMultiPolygon + 1000 ||  // wkbMultiPolygonZ
    8533           5 :                      nType == wkbMultiPolygonM || nType == wkbMultiPolygonZM)
    8534             :             {
    8535             :                 double dfArea;
    8536           5 :                 if (OGRWKBMultiPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8537             :                 {
    8538           5 :                     sqlite3_result_double(pContext, dfArea);
    8539           5 :                     return;
    8540             :                 }
    8541             :             }
    8542             :         }
    8543             : 
    8544             :         // For curve geometries, fallback to OGRGeometry methods
    8545           3 :         poGeom.reset(GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8546             :     }
    8547             :     else
    8548             :     {
    8549             :         // Try also spatialite geometry blobs
    8550           2 :         OGRGeometry *poGeomPtr = nullptr;
    8551           2 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8552             :             OGRERR_NONE)
    8553             :         {
    8554           1 :             sqlite3_result_null(pContext);
    8555           1 :             return;
    8556             :         }
    8557           1 :         poGeom.reset(poGeomPtr);
    8558             :     }
    8559           4 :     auto poSurface = dynamic_cast<OGRSurface *>(poGeom.get());
    8560           4 :     if (poSurface == nullptr)
    8561             :     {
    8562           2 :         auto poMultiSurface = dynamic_cast<OGRMultiSurface *>(poGeom.get());
    8563           2 :         if (poMultiSurface == nullptr)
    8564             :         {
    8565           1 :             sqlite3_result_double(pContext, 0);
    8566             :         }
    8567             :         else
    8568             :         {
    8569           1 :             sqlite3_result_double(pContext, poMultiSurface->get_Area());
    8570             :         }
    8571             :     }
    8572             :     else
    8573             :     {
    8574           2 :         sqlite3_result_double(pContext, poSurface->get_Area());
    8575             :     }
    8576             : }
    8577             : 
    8578             : /************************************************************************/
    8579             : /*                     OGRGeoPackageGeodesicArea()                      */
    8580             : /************************************************************************/
    8581             : 
    8582           5 : static void OGRGeoPackageGeodesicArea(sqlite3_context *pContext, int argc,
    8583             :                                       sqlite3_value **argv)
    8584             : {
    8585           5 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8586             :     {
    8587           1 :         sqlite3_result_null(pContext);
    8588           3 :         return;
    8589             :     }
    8590           4 :     if (sqlite3_value_int(argv[1]) != 1)
    8591             :     {
    8592           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8593             :                  "ST_Area(geom, use_ellipsoid) is only supported for "
    8594             :                  "use_ellipsoid = 1");
    8595             :     }
    8596             : 
    8597           4 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8598             :     const GByte *pabyBLOB =
    8599           4 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8600             :     GPkgHeader sHeader;
    8601           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8602             :     {
    8603           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8604           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8605           1 :         return;
    8606             :     }
    8607             : 
    8608             :     GDALGeoPackageDataset *poDS =
    8609           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8610             : 
    8611           3 :     auto poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8612           3 :     if (poSrcSRS == nullptr)
    8613             :     {
    8614           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    8615             :                  "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8616           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8617           1 :         return;
    8618             :     }
    8619             : 
    8620             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8621           2 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8622           2 :     if (poGeom == nullptr)
    8623             :     {
    8624             :         // Try also spatialite geometry blobs
    8625           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8626           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8627           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8628             :         {
    8629           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8630           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8631           0 :             return;
    8632             :         }
    8633           0 :         poGeom.reset(poGeomSpatialite);
    8634             :     }
    8635             : 
    8636           2 :     poGeom->assignSpatialReference(poSrcSRS.get());
    8637           2 :     sqlite3_result_double(
    8638             :         pContext, OGR_G_GeodesicArea(OGRGeometry::ToHandle(poGeom.get())));
    8639             : }
    8640             : 
    8641             : /************************************************************************/
    8642             : /*                OGRGeoPackageLengthOrGeodesicLength()                 */
    8643             : /************************************************************************/
    8644             : 
    8645           8 : static void OGRGeoPackageLengthOrGeodesicLength(sqlite3_context *pContext,
    8646             :                                                 int argc, sqlite3_value **argv)
    8647             : {
    8648           8 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8649             :     {
    8650           2 :         sqlite3_result_null(pContext);
    8651           5 :         return;
    8652             :     }
    8653           6 :     if (argc == 2 && sqlite3_value_int(argv[1]) != 1)
    8654             :     {
    8655           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8656             :                  "ST_Length(geom, use_ellipsoid) is only supported for "
    8657             :                  "use_ellipsoid = 1");
    8658             :     }
    8659             : 
    8660           6 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8661             :     const GByte *pabyBLOB =
    8662           6 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8663             :     GPkgHeader sHeader;
    8664           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8665             :     {
    8666           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8667           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8668           2 :         return;
    8669             :     }
    8670             : 
    8671             :     GDALGeoPackageDataset *poDS =
    8672           4 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8673             : 
    8674           4 :     OGRSpatialReferenceRefCountedPtr poSrcSRS;
    8675           4 :     if (argc == 2)
    8676             :     {
    8677           3 :         poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8678           3 :         if (!poSrcSRS)
    8679             :         {
    8680           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    8681             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8682           1 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8683           1 :             return;
    8684             :         }
    8685             :     }
    8686             : 
    8687             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8688           3 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8689           3 :     if (poGeom == nullptr)
    8690             :     {
    8691             :         // Try also spatialite geometry blobs
    8692           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8693           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8694           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8695             :         {
    8696           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8697           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8698           0 :             return;
    8699             :         }
    8700           0 :         poGeom.reset(poGeomSpatialite);
    8701             :     }
    8702             : 
    8703           3 :     if (argc == 2)
    8704           2 :         poGeom->assignSpatialReference(poSrcSRS.get());
    8705             : 
    8706           6 :     sqlite3_result_double(
    8707             :         pContext,
    8708           1 :         argc == 1 ? OGR_G_Length(OGRGeometry::ToHandle(poGeom.get()))
    8709           2 :                   : OGR_G_GeodesicLength(OGRGeometry::ToHandle(poGeom.get())));
    8710             : }
    8711             : 
    8712             : /************************************************************************/
    8713             : /*                       OGRGeoPackageTransform()                       */
    8714             : /************************************************************************/
    8715             : 
    8716             : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8717             :                             sqlite3_value **argv);
    8718             : 
    8719          32 : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8720             :                             sqlite3_value **argv)
    8721             : {
    8722          63 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB ||
    8723          31 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8724             :     {
    8725           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8726          32 :         return;
    8727             :     }
    8728             : 
    8729          30 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8730             :     const GByte *pabyBLOB =
    8731          30 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8732             :     GPkgHeader sHeader;
    8733          30 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8734             :     {
    8735           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8736           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8737           1 :         return;
    8738             :     }
    8739             : 
    8740          29 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8741          29 :     if (sHeader.iSrsId == nDestSRID)
    8742             :     {
    8743             :         // Return blob unmodified
    8744           3 :         sqlite3_result_blob(pContext, pabyBLOB, nBLOBLen, SQLITE_TRANSIENT);
    8745           3 :         return;
    8746             :     }
    8747             : 
    8748             :     GDALGeoPackageDataset *poDS =
    8749          26 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8750             : 
    8751             :     // Try to get the cached coordinate transformation
    8752             :     OGRCoordinateTransformation *poCT;
    8753          26 :     if (poDS->m_nLastCachedCTSrcSRId == sHeader.iSrsId &&
    8754          20 :         poDS->m_nLastCachedCTDstSRId == nDestSRID)
    8755             :     {
    8756          20 :         poCT = poDS->m_poLastCachedCT.get();
    8757             :     }
    8758             :     else
    8759             :     {
    8760           6 :         auto poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8761           6 :         if (poSrcSRS == nullptr)
    8762             :         {
    8763           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    8764             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8765           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8766           0 :             return;
    8767             :         }
    8768             : 
    8769           6 :         auto poDstSRS = poDS->GetSpatialRef(nDestSRID, true);
    8770           6 :         if (poDstSRS == nullptr)
    8771             :         {
    8772           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Target SRID (%d) is invalid",
    8773             :                      nDestSRID);
    8774           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8775           0 :             return;
    8776             :         }
    8777             :         poCT =
    8778           6 :             OGRCreateCoordinateTransformation(poSrcSRS.get(), poDstSRS.get());
    8779           6 :         if (poCT == nullptr)
    8780             :         {
    8781           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8782           0 :             return;
    8783             :         }
    8784             : 
    8785             :         // Cache coordinate transformation for potential later reuse
    8786           6 :         poDS->m_nLastCachedCTSrcSRId = sHeader.iSrsId;
    8787           6 :         poDS->m_nLastCachedCTDstSRId = nDestSRID;
    8788           6 :         poDS->m_poLastCachedCT.reset(poCT);
    8789           6 :         poCT = poDS->m_poLastCachedCT.get();
    8790             :     }
    8791             : 
    8792          26 :     if (sHeader.nHeaderLen >= 8)
    8793             :     {
    8794          26 :         std::vector<GByte> &abyNewBLOB = poDS->m_abyWKBTransformCache;
    8795          26 :         abyNewBLOB.resize(nBLOBLen);
    8796          26 :         memcpy(abyNewBLOB.data(), pabyBLOB, nBLOBLen);
    8797             : 
    8798          26 :         OGREnvelope3D oEnv3d;
    8799          26 :         if (!OGRWKBTransform(abyNewBLOB.data() + sHeader.nHeaderLen,
    8800          26 :                              nBLOBLen - sHeader.nHeaderLen, poCT,
    8801          78 :                              poDS->m_oWKBTransformCache, oEnv3d) ||
    8802          26 :             !GPkgUpdateHeader(abyNewBLOB.data(), nBLOBLen, nDestSRID,
    8803             :                               oEnv3d.MinX, oEnv3d.MaxX, oEnv3d.MinY,
    8804             :                               oEnv3d.MaxY, oEnv3d.MinZ, oEnv3d.MaxZ))
    8805             :         {
    8806           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8807           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8808           0 :             return;
    8809             :         }
    8810             : 
    8811          26 :         sqlite3_result_blob(pContext, abyNewBLOB.data(), nBLOBLen,
    8812             :                             SQLITE_TRANSIENT);
    8813          26 :         return;
    8814             :     }
    8815             : 
    8816             :     // Try also spatialite geometry blobs
    8817           0 :     OGRGeometry *poGeomSpatialite = nullptr;
    8818           0 :     if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8819           0 :                                           &poGeomSpatialite) != OGRERR_NONE)
    8820             :     {
    8821           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8822           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8823           0 :         return;
    8824             :     }
    8825           0 :     auto poGeom = std::unique_ptr<OGRGeometry>(poGeomSpatialite);
    8826             : 
    8827           0 :     if (poGeom->transform(poCT) != OGRERR_NONE)
    8828             :     {
    8829           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8830           0 :         return;
    8831             :     }
    8832             : 
    8833           0 :     size_t nBLOBDestLen = 0;
    8834             :     GByte *pabyDestBLOB =
    8835           0 :         GPkgGeometryFromOGR(poGeom.get(), nDestSRID, nullptr, &nBLOBDestLen);
    8836           0 :     if (!pabyDestBLOB)
    8837             :     {
    8838           0 :         sqlite3_result_null(pContext);
    8839           0 :         return;
    8840             :     }
    8841           0 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8842             :                         VSIFree);
    8843             : }
    8844             : 
    8845             : /************************************************************************/
    8846             : /*                    OGRGeoPackageSridFromAuthCRS()                    */
    8847             : /************************************************************************/
    8848             : 
    8849           4 : static void OGRGeoPackageSridFromAuthCRS(sqlite3_context *pContext,
    8850             :                                          int /*argc*/, sqlite3_value **argv)
    8851             : {
    8852           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8853           3 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8854             :     {
    8855           2 :         sqlite3_result_int(pContext, -1);
    8856           2 :         return;
    8857             :     }
    8858             : 
    8859             :     GDALGeoPackageDataset *poDS =
    8860           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8861             : 
    8862           2 :     char *pszSQL = sqlite3_mprintf(
    8863             :         "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
    8864             :         "lower(organization) = lower('%q') AND organization_coordsys_id = %d",
    8865           2 :         sqlite3_value_text(argv[0]), sqlite3_value_int(argv[1]));
    8866           2 :     OGRErr err = OGRERR_NONE;
    8867           2 :     int nSRSId = SQLGetInteger(poDS->GetDB(), pszSQL, &err);
    8868           2 :     sqlite3_free(pszSQL);
    8869           2 :     if (err != OGRERR_NONE)
    8870           1 :         nSRSId = -1;
    8871           2 :     sqlite3_result_int(pContext, nSRSId);
    8872             : }
    8873             : 
    8874             : /************************************************************************/
    8875             : /*                    OGRGeoPackageImportFromEPSG()                     */
    8876             : /************************************************************************/
    8877             : 
    8878           4 : static void OGRGeoPackageImportFromEPSG(sqlite3_context *pContext, int /*argc*/,
    8879             :                                         sqlite3_value **argv)
    8880             : {
    8881           4 :     if (sqlite3_value_type(argv[0]) != SQLITE_INTEGER)
    8882             :     {
    8883           1 :         sqlite3_result_int(pContext, -1);
    8884           2 :         return;
    8885             :     }
    8886             : 
    8887             :     GDALGeoPackageDataset *poDS =
    8888           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8889           3 :     OGRSpatialReference oSRS;
    8890           3 :     if (oSRS.importFromEPSG(sqlite3_value_int(argv[0])) != OGRERR_NONE)
    8891             :     {
    8892           1 :         sqlite3_result_int(pContext, -1);
    8893           1 :         return;
    8894             :     }
    8895             : 
    8896           2 :     sqlite3_result_int(pContext, poDS->GetSrsId(&oSRS));
    8897             : }
    8898             : 
    8899             : /************************************************************************/
    8900             : /*               OGRGeoPackageRegisterGeometryExtension()               */
    8901             : /************************************************************************/
    8902             : 
    8903           1 : static void OGRGeoPackageRegisterGeometryExtension(sqlite3_context *pContext,
    8904             :                                                    int /*argc*/,
    8905             :                                                    sqlite3_value **argv)
    8906             : {
    8907           1 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8908           2 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT ||
    8909           1 :         sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    8910             :     {
    8911           0 :         sqlite3_result_int(pContext, 0);
    8912           0 :         return;
    8913             :     }
    8914             : 
    8915             :     const char *pszTableName =
    8916           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8917             :     const char *pszGeomName =
    8918           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8919             :     const char *pszGeomType =
    8920           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    8921             : 
    8922             :     GDALGeoPackageDataset *poDS =
    8923           1 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8924             : 
    8925           1 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8926           1 :         poDS->GetLayerByName(pszTableName));
    8927           1 :     if (poLyr == nullptr)
    8928             :     {
    8929           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8930           0 :         sqlite3_result_int(pContext, 0);
    8931           0 :         return;
    8932             :     }
    8933           1 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8934             :     {
    8935           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8936           0 :         sqlite3_result_int(pContext, 0);
    8937           0 :         return;
    8938             :     }
    8939           1 :     const OGRwkbGeometryType eGeomType = OGRFromOGCGeomType(pszGeomType);
    8940           1 :     if (eGeomType == wkbUnknown)
    8941             :     {
    8942           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry type name");
    8943           0 :         sqlite3_result_int(pContext, 0);
    8944           0 :         return;
    8945             :     }
    8946             : 
    8947           1 :     sqlite3_result_int(
    8948             :         pContext,
    8949           1 :         static_cast<int>(poLyr->CreateGeometryExtensionIfNecessary(eGeomType)));
    8950             : }
    8951             : 
    8952             : /************************************************************************/
    8953             : /*                  OGRGeoPackageCreateSpatialIndex()                   */
    8954             : /************************************************************************/
    8955             : 
    8956          14 : static void OGRGeoPackageCreateSpatialIndex(sqlite3_context *pContext,
    8957             :                                             int /*argc*/, sqlite3_value **argv)
    8958             : {
    8959          27 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8960          13 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8961             :     {
    8962           2 :         sqlite3_result_int(pContext, 0);
    8963           2 :         return;
    8964             :     }
    8965             : 
    8966             :     const char *pszTableName =
    8967          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8968             :     const char *pszGeomName =
    8969          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8970             :     GDALGeoPackageDataset *poDS =
    8971          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8972             : 
    8973          12 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8974          12 :         poDS->GetLayerByName(pszTableName));
    8975          12 :     if (poLyr == nullptr)
    8976             :     {
    8977           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8978           1 :         sqlite3_result_int(pContext, 0);
    8979           1 :         return;
    8980             :     }
    8981          11 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8982             :     {
    8983           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8984           1 :         sqlite3_result_int(pContext, 0);
    8985           1 :         return;
    8986             :     }
    8987             : 
    8988          10 :     sqlite3_result_int(pContext, poLyr->CreateSpatialIndex());
    8989             : }
    8990             : 
    8991             : /************************************************************************/
    8992             : /*                  OGRGeoPackageDisableSpatialIndex()                  */
    8993             : /************************************************************************/
    8994             : 
    8995          12 : static void OGRGeoPackageDisableSpatialIndex(sqlite3_context *pContext,
    8996             :                                              int /*argc*/, sqlite3_value **argv)
    8997             : {
    8998          23 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8999          11 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9000             :     {
    9001           2 :         sqlite3_result_int(pContext, 0);
    9002           2 :         return;
    9003             :     }
    9004             : 
    9005             :     const char *pszTableName =
    9006          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9007             :     const char *pszGeomName =
    9008          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9009             :     GDALGeoPackageDataset *poDS =
    9010          10 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9011             : 
    9012          10 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9013          10 :         poDS->GetLayerByName(pszTableName));
    9014          10 :     if (poLyr == nullptr)
    9015             :     {
    9016           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9017           1 :         sqlite3_result_int(pContext, 0);
    9018           1 :         return;
    9019             :     }
    9020           9 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9021             :     {
    9022           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9023           1 :         sqlite3_result_int(pContext, 0);
    9024           1 :         return;
    9025             :     }
    9026             : 
    9027           8 :     sqlite3_result_int(pContext, poLyr->DropSpatialIndex(true));
    9028             : }
    9029             : 
    9030             : /************************************************************************/
    9031             : /*                    OGRGeoPackageHasSpatialIndex()                    */
    9032             : /************************************************************************/
    9033             : 
    9034          29 : static void OGRGeoPackageHasSpatialIndex(sqlite3_context *pContext,
    9035             :                                          int /*argc*/, sqlite3_value **argv)
    9036             : {
    9037          57 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9038          28 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9039             :     {
    9040           2 :         sqlite3_result_int(pContext, 0);
    9041           2 :         return;
    9042             :     }
    9043             : 
    9044             :     const char *pszTableName =
    9045          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9046             :     const char *pszGeomName =
    9047          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9048             :     GDALGeoPackageDataset *poDS =
    9049          27 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9050             : 
    9051          27 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9052          27 :         poDS->GetLayerByName(pszTableName));
    9053          27 :     if (poLyr == nullptr)
    9054             :     {
    9055           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9056           1 :         sqlite3_result_int(pContext, 0);
    9057           1 :         return;
    9058             :     }
    9059          26 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9060             :     {
    9061           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9062           1 :         sqlite3_result_int(pContext, 0);
    9063           1 :         return;
    9064             :     }
    9065             : 
    9066          25 :     poLyr->RunDeferredCreationIfNecessary();
    9067          25 :     poLyr->CreateSpatialIndexIfNecessary();
    9068             : 
    9069          25 :     sqlite3_result_int(pContext, poLyr->HasSpatialIndex());
    9070             : }
    9071             : 
    9072             : /************************************************************************/
    9073             : /*                       GPKG_hstore_get_value()                        */
    9074             : /************************************************************************/
    9075             : 
    9076           4 : static void GPKG_hstore_get_value(sqlite3_context *pContext, int /*argc*/,
    9077             :                                   sqlite3_value **argv)
    9078             : {
    9079           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9080           3 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9081             :     {
    9082           2 :         sqlite3_result_null(pContext);
    9083           2 :         return;
    9084             :     }
    9085             : 
    9086             :     const char *pszHStore =
    9087           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9088             :     const char *pszSearchedKey =
    9089           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9090           2 :     char *pszValue = OGRHStoreGetValue(pszHStore, pszSearchedKey);
    9091           2 :     if (pszValue != nullptr)
    9092           1 :         sqlite3_result_text(pContext, pszValue, -1, CPLFree);
    9093             :     else
    9094           1 :         sqlite3_result_null(pContext);
    9095             : }
    9096             : 
    9097             : /************************************************************************/
    9098             : /*                    GPKG_GDAL_GetMemFileFromBlob()                    */
    9099             : /************************************************************************/
    9100             : 
    9101         105 : static CPLString GPKG_GDAL_GetMemFileFromBlob(sqlite3_value **argv)
    9102             : {
    9103         105 :     int nBytes = sqlite3_value_bytes(argv[0]);
    9104             :     const GByte *pabyBLOB =
    9105         105 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    9106             :     CPLString osMemFileName(
    9107         105 :         VSIMemGenerateHiddenFilename("GPKG_GDAL_GetMemFileFromBlob"));
    9108         105 :     VSILFILE *fp = VSIFileFromMemBuffer(
    9109             :         osMemFileName.c_str(), const_cast<GByte *>(pabyBLOB), nBytes, FALSE);
    9110         105 :     VSIFCloseL(fp);
    9111         105 :     return osMemFileName;
    9112             : }
    9113             : 
    9114             : /************************************************************************/
    9115             : /*                       GPKG_GDAL_GetMimeType()                        */
    9116             : /************************************************************************/
    9117             : 
    9118          35 : static void GPKG_GDAL_GetMimeType(sqlite3_context *pContext, int /*argc*/,
    9119             :                                   sqlite3_value **argv)
    9120             : {
    9121          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9122             :     {
    9123           0 :         sqlite3_result_null(pContext);
    9124           0 :         return;
    9125             :     }
    9126             : 
    9127          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9128             :     GDALDriver *poDriver =
    9129          35 :         GDALDriver::FromHandle(GDALIdentifyDriver(osMemFileName, nullptr));
    9130          35 :     if (poDriver != nullptr)
    9131             :     {
    9132          35 :         const char *pszRes = nullptr;
    9133          35 :         if (EQUAL(poDriver->GetDescription(), "PNG"))
    9134          23 :             pszRes = "image/png";
    9135          12 :         else if (EQUAL(poDriver->GetDescription(), "JPEG"))
    9136           6 :             pszRes = "image/jpeg";
    9137           6 :         else if (EQUAL(poDriver->GetDescription(), "WEBP"))
    9138           6 :             pszRes = "image/x-webp";
    9139           0 :         else if (EQUAL(poDriver->GetDescription(), "GTIFF"))
    9140           0 :             pszRes = "image/tiff";
    9141             :         else
    9142           0 :             pszRes = CPLSPrintf("gdal/%s", poDriver->GetDescription());
    9143          35 :         sqlite3_result_text(pContext, pszRes, -1, SQLITE_TRANSIENT);
    9144             :     }
    9145             :     else
    9146           0 :         sqlite3_result_null(pContext);
    9147          35 :     VSIUnlink(osMemFileName);
    9148             : }
    9149             : 
    9150             : /************************************************************************/
    9151             : /*                       GPKG_GDAL_GetBandCount()                       */
    9152             : /************************************************************************/
    9153             : 
    9154          35 : static void GPKG_GDAL_GetBandCount(sqlite3_context *pContext, int /*argc*/,
    9155             :                                    sqlite3_value **argv)
    9156             : {
    9157          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9158             :     {
    9159           0 :         sqlite3_result_null(pContext);
    9160           0 :         return;
    9161             :     }
    9162             : 
    9163          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9164             :     auto poDS = std::unique_ptr<GDALDataset>(
    9165             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9166          70 :                           nullptr, nullptr, nullptr));
    9167          35 :     if (poDS != nullptr)
    9168             :     {
    9169          35 :         sqlite3_result_int(pContext, poDS->GetRasterCount());
    9170             :     }
    9171             :     else
    9172           0 :         sqlite3_result_null(pContext);
    9173          35 :     VSIUnlink(osMemFileName);
    9174             : }
    9175             : 
    9176             : /************************************************************************/
    9177             : /*                      GPKG_GDAL_HasColorTable()                       */
    9178             : /************************************************************************/
    9179             : 
    9180          35 : static void GPKG_GDAL_HasColorTable(sqlite3_context *pContext, int /*argc*/,
    9181             :                                     sqlite3_value **argv)
    9182             : {
    9183          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9184             :     {
    9185           0 :         sqlite3_result_null(pContext);
    9186           0 :         return;
    9187             :     }
    9188             : 
    9189          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9190             :     auto poDS = std::unique_ptr<GDALDataset>(
    9191             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9192          70 :                           nullptr, nullptr, nullptr));
    9193          35 :     if (poDS != nullptr)
    9194             :     {
    9195          35 :         sqlite3_result_int(
    9196          46 :             pContext, poDS->GetRasterCount() == 1 &&
    9197          11 :                           poDS->GetRasterBand(1)->GetColorTable() != nullptr);
    9198             :     }
    9199             :     else
    9200           0 :         sqlite3_result_null(pContext);
    9201          35 :     VSIUnlink(osMemFileName);
    9202             : }
    9203             : 
    9204             : /************************************************************************/
    9205             : /*                       GetRasterLayerDataset()                        */
    9206             : /************************************************************************/
    9207             : 
    9208             : GDALDataset *
    9209          12 : GDALGeoPackageDataset::GetRasterLayerDataset(const char *pszLayerName)
    9210             : {
    9211          12 :     const auto oIter = m_oCachedRasterDS.find(pszLayerName);
    9212          12 :     if (oIter != m_oCachedRasterDS.end())
    9213          10 :         return oIter->second.get();
    9214             : 
    9215             :     auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
    9216           4 :         (std::string("GPKG:\"") + m_pszFilename + "\":" + pszLayerName).c_str(),
    9217           4 :         GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR));
    9218           2 :     if (!poDS)
    9219             :     {
    9220           0 :         return nullptr;
    9221             :     }
    9222           2 :     m_oCachedRasterDS[pszLayerName] = std::move(poDS);
    9223           2 :     return m_oCachedRasterDS[pszLayerName].get();
    9224             : }
    9225             : 
    9226             : /************************************************************************/
    9227             : /*                  GPKG_gdal_get_layer_pixel_value()                   */
    9228             : /************************************************************************/
    9229             : 
    9230             : // NOTE: keep in sync implementations in ogrsqlitesqlfunctionscommon.cpp
    9231             : // and ogrgeopackagedatasource.cpp
    9232          13 : static void GPKG_gdal_get_layer_pixel_value(sqlite3_context *pContext, int argc,
    9233             :                                             sqlite3_value **argv)
    9234             : {
    9235          13 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9236             :     {
    9237           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9238             :                  "Invalid arguments to gdal_get_layer_pixel_value()");
    9239           1 :         sqlite3_result_null(pContext);
    9240           1 :         return;
    9241             :     }
    9242             : 
    9243             :     const char *pszLayerName =
    9244          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9245             : 
    9246             :     GDALGeoPackageDataset *poGlobalDS =
    9247          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9248          12 :     auto poDS = poGlobalDS->GetRasterLayerDataset(pszLayerName);
    9249          12 :     if (!poDS)
    9250             :     {
    9251           0 :         sqlite3_result_null(pContext);
    9252           0 :         return;
    9253             :     }
    9254             : 
    9255          12 :     OGRSQLite_gdal_get_pixel_value_common("gdal_get_layer_pixel_value",
    9256             :                                           pContext, argc, argv, poDS);
    9257             : }
    9258             : 
    9259             : /************************************************************************/
    9260             : /*                       GPKG_ogr_layer_Extent()                        */
    9261             : /************************************************************************/
    9262             : 
    9263           3 : static void GPKG_ogr_layer_Extent(sqlite3_context *pContext, int /*argc*/,
    9264             :                                   sqlite3_value **argv)
    9265             : {
    9266           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9267             :     {
    9268           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Invalid argument type",
    9269             :                  "ogr_layer_Extent");
    9270           1 :         sqlite3_result_null(pContext);
    9271           2 :         return;
    9272             :     }
    9273             : 
    9274             :     const char *pszLayerName =
    9275           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9276             :     GDALGeoPackageDataset *poDS =
    9277           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9278           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9279           2 :     if (!poLayer)
    9280             :     {
    9281           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer",
    9282             :                  "ogr_layer_Extent");
    9283           1 :         sqlite3_result_null(pContext);
    9284           1 :         return;
    9285             :     }
    9286             : 
    9287           1 :     if (poLayer->GetGeomType() == wkbNone)
    9288             :     {
    9289           0 :         sqlite3_result_null(pContext);
    9290           0 :         return;
    9291             :     }
    9292             : 
    9293           1 :     OGREnvelope sExtent;
    9294           1 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9295             :     {
    9296           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9297             :                  "ogr_layer_Extent");
    9298           0 :         sqlite3_result_null(pContext);
    9299           0 :         return;
    9300             :     }
    9301             : 
    9302           1 :     OGRPolygon oPoly;
    9303           1 :     auto poRing = std::make_unique<OGRLinearRing>();
    9304           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9305           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MinY);
    9306           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MaxY);
    9307           1 :     poRing->addPoint(sExtent.MinX, sExtent.MaxY);
    9308           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9309           1 :     oPoly.addRing(std::move(poRing));
    9310             : 
    9311           1 :     const auto poSRS = poLayer->GetSpatialRef();
    9312           1 :     const int nSRID = poDS->GetSrsId(poSRS);
    9313           1 :     size_t nBLOBDestLen = 0;
    9314             :     GByte *pabyDestBLOB =
    9315           1 :         GPkgGeometryFromOGR(&oPoly, nSRID, nullptr, &nBLOBDestLen);
    9316           1 :     if (!pabyDestBLOB)
    9317             :     {
    9318           0 :         sqlite3_result_null(pContext);
    9319           0 :         return;
    9320             :     }
    9321           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    9322             :                         VSIFree);
    9323             : }
    9324             : 
    9325             : /************************************************************************/
    9326             : /*                   GPKG_ST_Hilbert_X_Y_TableName()                    */
    9327             : /************************************************************************/
    9328             : 
    9329           8 : static void GPKG_ST_Hilbert_X_Y_TableName(sqlite3_context *pContext,
    9330             :                                           [[maybe_unused]] int argc,
    9331             :                                           sqlite3_value **argv)
    9332             : {
    9333           8 :     CPLAssert(argc == 3);
    9334           8 :     const double dfX = sqlite3_value_double(argv[0]);
    9335           8 :     const double dfY = sqlite3_value_double(argv[1]);
    9336             : 
    9337           8 :     if (sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    9338             :     {
    9339           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9340             :                  "%s: Invalid argument type for 3rd argument. Text expected",
    9341             :                  "ST_Hilbert()");
    9342           1 :         sqlite3_result_null(pContext);
    9343           6 :         return;
    9344             :     }
    9345             : 
    9346             :     const char *pszLayerName =
    9347           7 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    9348             :     GDALGeoPackageDataset *poDS =
    9349           7 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9350           7 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9351           7 :     if (!poLayer)
    9352             :     {
    9353           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer '%s'",
    9354             :                  "ST_Hilbert()", pszLayerName);
    9355           1 :         sqlite3_result_null(pContext);
    9356           1 :         return;
    9357             :     }
    9358             : 
    9359           6 :     OGREnvelope sExtent;
    9360           6 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9361             :     {
    9362           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9363             :                  "ST_Hilbert()");
    9364           0 :         sqlite3_result_null(pContext);
    9365           0 :         return;
    9366             :     }
    9367           6 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9368           3 :           dfY <= sExtent.MaxY))
    9369             :     {
    9370           4 :         CPLError(CE_Warning, CPLE_AppDefined,
    9371             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9372             :                  dfX, dfY);
    9373           4 :         sqlite3_result_null(pContext);
    9374           4 :         return;
    9375             :     }
    9376           2 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9377             : }
    9378             : 
    9379             : /************************************************************************/
    9380             : /*                     GPKG_ST_Hilbert_Geom_BBOX()                      */
    9381             : /************************************************************************/
    9382             : 
    9383           6 : static void GPKG_ST_Hilbert_Geom_BBOX(sqlite3_context *pContext, int argc,
    9384             :                                       sqlite3_value **argv)
    9385             : {
    9386           6 :     CPLAssert(argc == 5);
    9387             :     GPkgHeader sHeader;
    9388           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    9389             :     {
    9390           1 :         sqlite3_result_null(pContext);
    9391           5 :         return;
    9392             :     }
    9393           5 :     const double dfX = (sHeader.MinX + sHeader.MaxX) / 2;
    9394           5 :     const double dfY = (sHeader.MinY + sHeader.MaxY) / 2;
    9395             : 
    9396           5 :     OGREnvelope sExtent;
    9397           5 :     sExtent.MinX = sqlite3_value_double(argv[1]);
    9398           5 :     sExtent.MinY = sqlite3_value_double(argv[2]);
    9399           5 :     sExtent.MaxX = sqlite3_value_double(argv[3]);
    9400           5 :     sExtent.MaxY = sqlite3_value_double(argv[4]);
    9401           5 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9402           2 :           dfY <= sExtent.MaxY))
    9403             :     {
    9404           4 :         CPLError(CE_Warning, CPLE_AppDefined,
    9405             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9406             :                  dfX, dfY);
    9407           4 :         sqlite3_result_null(pContext);
    9408           4 :         return;
    9409             :     }
    9410           1 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9411             : }
    9412             : 
    9413             : /************************************************************************/
    9414             : /*                   GPKG_ST_Hilbert_Geom_TableName()                   */
    9415             : /************************************************************************/
    9416             : 
    9417           4 : static void GPKG_ST_Hilbert_Geom_TableName(sqlite3_context *pContext, int argc,
    9418             :                                            sqlite3_value **argv)
    9419             : {
    9420           4 :     CPLAssert(argc == 2);
    9421             :     GPkgHeader sHeader;
    9422           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    9423             :     {
    9424           1 :         sqlite3_result_null(pContext);
    9425           3 :         return;
    9426             :     }
    9427           3 :     const double dfX = (sHeader.MinX + sHeader.MaxX) / 2;
    9428           3 :     const double dfY = (sHeader.MinY + sHeader.MaxY) / 2;
    9429             : 
    9430           3 :     if (sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9431             :     {
    9432           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9433             :                  "%s: Invalid argument type for 2nd argument. Text expected",
    9434             :                  "ST_Hilbert()");
    9435           1 :         sqlite3_result_null(pContext);
    9436           1 :         return;
    9437             :     }
    9438             : 
    9439             :     const char *pszLayerName =
    9440           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9441             :     GDALGeoPackageDataset *poDS =
    9442           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9443           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9444           2 :     if (!poLayer)
    9445             :     {
    9446           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer '%s'",
    9447             :                  "ST_Hilbert()", pszLayerName);
    9448           1 :         sqlite3_result_null(pContext);
    9449           1 :         return;
    9450             :     }
    9451             : 
    9452           1 :     OGREnvelope sExtent;
    9453           1 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9454             :     {
    9455           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9456             :                  "ST_Hilbert()");
    9457           0 :         sqlite3_result_null(pContext);
    9458           0 :         return;
    9459             :     }
    9460           1 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9461           1 :           dfY <= sExtent.MaxY))
    9462             :     {
    9463           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9464             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9465             :                  dfX, dfY);
    9466           0 :         sqlite3_result_null(pContext);
    9467           0 :         return;
    9468             :     }
    9469           1 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9470             : }
    9471             : 
    9472             : /************************************************************************/
    9473             : /*                        InstallSQLFunctions()                         */
    9474             : /************************************************************************/
    9475             : 
    9476             : #ifndef SQLITE_DETERMINISTIC
    9477             : #define SQLITE_DETERMINISTIC 0
    9478             : #endif
    9479             : 
    9480             : #ifndef SQLITE_INNOCUOUS
    9481             : #define SQLITE_INNOCUOUS 0
    9482             : #endif
    9483             : 
    9484             : #ifndef UTF8_INNOCUOUS
    9485             : #define UTF8_INNOCUOUS (SQLITE_UTF8 | SQLITE_DETERMINISTIC | SQLITE_INNOCUOUS)
    9486             : #endif
    9487             : 
    9488        2468 : void GDALGeoPackageDataset::InstallSQLFunctions()
    9489             : {
    9490        2468 :     InitSpatialite();
    9491             : 
    9492             :     // Enable SpatiaLite 4.3 GPKG mode, i.e. that SpatiaLite functions
    9493             :     // that take geometries will accept and return GPKG encoded geometries without
    9494             :     // explicit conversion.
    9495             :     // Use sqlite3_exec() instead of SQLCommand() since we don't want verbose
    9496             :     // error.
    9497        2468 :     sqlite3_exec(hDB, "SELECT EnableGpkgMode()", nullptr, nullptr, nullptr);
    9498             : 
    9499             :     /* Used by RTree Spatial Index Extension */
    9500        2468 :     sqlite3_create_function(hDB, "ST_MinX", 1, UTF8_INNOCUOUS, nullptr,
    9501             :                             OGRGeoPackageSTMinX, nullptr, nullptr);
    9502        2468 :     sqlite3_create_function(hDB, "ST_MinY", 1, UTF8_INNOCUOUS, nullptr,
    9503             :                             OGRGeoPackageSTMinY, nullptr, nullptr);
    9504        2468 :     sqlite3_create_function(hDB, "ST_MaxX", 1, UTF8_INNOCUOUS, nullptr,
    9505             :                             OGRGeoPackageSTMaxX, nullptr, nullptr);
    9506        2468 :     sqlite3_create_function(hDB, "ST_MaxY", 1, UTF8_INNOCUOUS, nullptr,
    9507             :                             OGRGeoPackageSTMaxY, nullptr, nullptr);
    9508        2468 :     sqlite3_create_function(hDB, "ST_IsEmpty", 1, UTF8_INNOCUOUS, nullptr,
    9509             :                             OGRGeoPackageSTIsEmpty, nullptr, nullptr);
    9510             : 
    9511             :     /* Used by Geometry Type Triggers Extension */
    9512        2468 :     sqlite3_create_function(hDB, "ST_GeometryType", 1, UTF8_INNOCUOUS, nullptr,
    9513             :                             OGRGeoPackageSTGeometryType, nullptr, nullptr);
    9514        2468 :     sqlite3_create_function(hDB, "GPKG_IsAssignable", 2, UTF8_INNOCUOUS,
    9515             :                             nullptr, OGRGeoPackageGPKGIsAssignable, nullptr,
    9516             :                             nullptr);
    9517             : 
    9518             :     /* Used by Geometry SRS ID Triggers Extension */
    9519        2468 :     sqlite3_create_function(hDB, "ST_SRID", 1, UTF8_INNOCUOUS, nullptr,
    9520             :                             OGRGeoPackageSTSRID, nullptr, nullptr);
    9521             : 
    9522             :     /* Spatialite-like functions */
    9523        2468 :     sqlite3_create_function(hDB, "CreateSpatialIndex", 2, SQLITE_UTF8, this,
    9524             :                             OGRGeoPackageCreateSpatialIndex, nullptr, nullptr);
    9525        2468 :     sqlite3_create_function(hDB, "DisableSpatialIndex", 2, SQLITE_UTF8, this,
    9526             :                             OGRGeoPackageDisableSpatialIndex, nullptr, nullptr);
    9527        2468 :     sqlite3_create_function(hDB, "HasSpatialIndex", 2, SQLITE_UTF8, this,
    9528             :                             OGRGeoPackageHasSpatialIndex, nullptr, nullptr);
    9529             : 
    9530             :     // HSTORE functions
    9531        2468 :     sqlite3_create_function(hDB, "hstore_get_value", 2, UTF8_INNOCUOUS, nullptr,
    9532             :                             GPKG_hstore_get_value, nullptr, nullptr);
    9533             : 
    9534             :     // Override a few Spatialite functions to work with gpkg_spatial_ref_sys
    9535        2468 :     sqlite3_create_function(hDB, "ST_Transform", 2, UTF8_INNOCUOUS, this,
    9536             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9537        2468 :     sqlite3_create_function(hDB, "Transform", 2, UTF8_INNOCUOUS, this,
    9538             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9539        2468 :     sqlite3_create_function(hDB, "SridFromAuthCRS", 2, SQLITE_UTF8, this,
    9540             :                             OGRGeoPackageSridFromAuthCRS, nullptr, nullptr);
    9541             : 
    9542        2468 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9543             :                             OGRGeoPackageSTEnvelopesIntersectsTwoParams,
    9544             :                             nullptr, nullptr);
    9545        2468 :     sqlite3_create_function(
    9546             :         hDB, "ST_EnvelopesIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9547             :         OGRGeoPackageSTEnvelopesIntersectsTwoParams, nullptr, nullptr);
    9548             : 
    9549        2468 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 5, UTF8_INNOCUOUS, nullptr,
    9550             :                             OGRGeoPackageSTEnvelopesIntersects, nullptr,
    9551             :                             nullptr);
    9552        2468 :     sqlite3_create_function(hDB, "ST_EnvelopesIntersects", 5, UTF8_INNOCUOUS,
    9553             :                             nullptr, OGRGeoPackageSTEnvelopesIntersects,
    9554             :                             nullptr, nullptr);
    9555             : 
    9556             :     // Implementation that directly hacks the GeoPackage geometry blob header
    9557        2468 :     sqlite3_create_function(hDB, "SetSRID", 2, UTF8_INNOCUOUS, nullptr,
    9558             :                             OGRGeoPackageSetSRID, nullptr, nullptr);
    9559             : 
    9560             :     // GDAL specific function
    9561        2468 :     sqlite3_create_function(hDB, "ImportFromEPSG", 1, SQLITE_UTF8, this,
    9562             :                             OGRGeoPackageImportFromEPSG, nullptr, nullptr);
    9563             : 
    9564             :     // May be used by ogrmerge.py
    9565        2468 :     sqlite3_create_function(hDB, "RegisterGeometryExtension", 3, SQLITE_UTF8,
    9566             :                             this, OGRGeoPackageRegisterGeometryExtension,
    9567             :                             nullptr, nullptr);
    9568             : 
    9569        2468 :     if (OGRGeometryFactory::haveGEOS())
    9570             :     {
    9571        2468 :         sqlite3_create_function(hDB, "ST_MakeValid", 1, UTF8_INNOCUOUS, nullptr,
    9572             :                                 OGRGeoPackageSTMakeValid, nullptr, nullptr);
    9573             :     }
    9574             : 
    9575        2468 :     sqlite3_create_function(hDB, "ST_Length", 1, UTF8_INNOCUOUS, nullptr,
    9576             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9577             :                             nullptr);
    9578        2468 :     sqlite3_create_function(hDB, "ST_Length", 2, UTF8_INNOCUOUS, this,
    9579             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9580             :                             nullptr);
    9581             : 
    9582        2468 :     sqlite3_create_function(hDB, "ST_Area", 1, UTF8_INNOCUOUS, nullptr,
    9583             :                             OGRGeoPackageSTArea, nullptr, nullptr);
    9584        2468 :     sqlite3_create_function(hDB, "ST_Area", 2, UTF8_INNOCUOUS, this,
    9585             :                             OGRGeoPackageGeodesicArea, nullptr, nullptr);
    9586             : 
    9587             :     // Debug functions
    9588        2468 :     if (CPLTestBool(CPLGetConfigOption("GPKG_DEBUG", "FALSE")))
    9589             :     {
    9590         422 :         sqlite3_create_function(hDB, "GDAL_GetMimeType", 1,
    9591             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9592             :                                 GPKG_GDAL_GetMimeType, nullptr, nullptr);
    9593         422 :         sqlite3_create_function(hDB, "GDAL_GetBandCount", 1,
    9594             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9595             :                                 GPKG_GDAL_GetBandCount, nullptr, nullptr);
    9596         422 :         sqlite3_create_function(hDB, "GDAL_HasColorTable", 1,
    9597             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9598             :                                 GPKG_GDAL_HasColorTable, nullptr, nullptr);
    9599             :     }
    9600             : 
    9601        2468 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 5, SQLITE_UTF8,
    9602             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9603             :                             nullptr);
    9604        2468 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 6, SQLITE_UTF8,
    9605             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9606             :                             nullptr);
    9607             : 
    9608             :     // Function from VirtualOGR
    9609        2468 :     sqlite3_create_function(hDB, "ogr_layer_Extent", 1, SQLITE_UTF8, this,
    9610             :                             GPKG_ogr_layer_Extent, nullptr, nullptr);
    9611             : 
    9612        2468 :     m_pSQLFunctionData = OGRSQLiteRegisterSQLFunctionsCommon(hDB);
    9613             : 
    9614             :     // ST_Hilbert() inspired from https://duckdb.org/docs/stable/core_extensions/spatial/functions#st_hilbert
    9615             :     // Override the generic version of OGRSQLiteRegisterSQLFunctionsCommon()
    9616             : 
    9617             :     // X,Y,table_name
    9618        2468 :     sqlite3_create_function(hDB, "ST_Hilbert", 2 + 1, UTF8_INNOCUOUS, this,
    9619             :                             GPKG_ST_Hilbert_X_Y_TableName, nullptr, nullptr);
    9620             : 
    9621             :     // geometry,minX,minY,maxX,maxY
    9622        2468 :     sqlite3_create_function(hDB, "ST_Hilbert", 1 + 4, UTF8_INNOCUOUS, nullptr,
    9623             :                             GPKG_ST_Hilbert_Geom_BBOX, nullptr, nullptr);
    9624             : 
    9625             :     // geometry,table_name
    9626        2468 :     sqlite3_create_function(hDB, "ST_Hilbert", 1 + 1, UTF8_INNOCUOUS, this,
    9627             :                             GPKG_ST_Hilbert_Geom_TableName, nullptr, nullptr);
    9628        2468 : }
    9629             : 
    9630             : /************************************************************************/
    9631             : /*                           OpenOrCreateDB()                           */
    9632             : /************************************************************************/
    9633             : 
    9634        2474 : bool GDALGeoPackageDataset::OpenOrCreateDB(int flags)
    9635             : {
    9636        2474 :     const bool bSuccess = OGRSQLiteBaseDataSource::OpenOrCreateDB(
    9637             :         flags, /*bRegisterOGR2SQLiteExtensions=*/false,
    9638             :         /*bLoadExtensions=*/true);
    9639        2474 :     if (!bSuccess)
    9640          11 :         return false;
    9641             : 
    9642             :     // Turning on recursive_triggers is needed so that DELETE triggers fire
    9643             :     // in a INSERT OR REPLACE statement. In particular this is needed to
    9644             :     // make sure gpkg_ogr_contents.feature_count is properly updated.
    9645        2463 :     SQLCommand(hDB, "PRAGMA recursive_triggers = 1");
    9646             : 
    9647        2463 :     InstallSQLFunctions();
    9648             : 
    9649             :     const char *pszSqlitePragma =
    9650        2463 :         CPLGetConfigOption("OGR_SQLITE_PRAGMA", nullptr);
    9651        2463 :     OGRErr eErr = OGRERR_NONE;
    9652           6 :     if ((!pszSqlitePragma || !strstr(pszSqlitePragma, "trusted_schema")) &&
    9653             :         // Older sqlite versions don't have this pragma
    9654        4932 :         SQLGetInteger(hDB, "PRAGMA trusted_schema", &eErr) == 0 &&
    9655        2463 :         eErr == OGRERR_NONE)
    9656             :     {
    9657        2463 :         bool bNeedsTrustedSchema = false;
    9658             : 
    9659             :         // Current SQLite versions require PRAGMA trusted_schema = 1 to be
    9660             :         // able to use the RTree from triggers, which is only needed when
    9661             :         // modifying the RTree.
    9662        6048 :         if (((flags & SQLITE_OPEN_READWRITE) != 0 ||
    9663        3804 :              (flags & SQLITE_OPEN_CREATE) != 0) &&
    9664        1341 :             OGRSQLiteRTreeRequiresTrustedSchemaOn())
    9665             :         {
    9666        1341 :             bNeedsTrustedSchema = true;
    9667             :         }
    9668             : 
    9669             : #ifdef HAVE_SPATIALITE
    9670             :         // Spatialite <= 5.1.0 doesn't declare its functions as SQLITE_INNOCUOUS
    9671        1122 :         if (!bNeedsTrustedSchema && HasExtensionsTable() &&
    9672        1027 :             SQLGetInteger(
    9673             :                 hDB,
    9674             :                 "SELECT 1 FROM gpkg_extensions WHERE "
    9675             :                 "extension_name ='gdal_spatialite_computed_geom_column'",
    9676           1 :                 nullptr) == 1 &&
    9677        3585 :             SpatialiteRequiresTrustedSchemaOn() && AreSpatialiteTriggersSafe())
    9678             :         {
    9679           1 :             bNeedsTrustedSchema = true;
    9680             :         }
    9681             : #endif
    9682             : 
    9683        2463 :         if (bNeedsTrustedSchema)
    9684             :         {
    9685        1342 :             CPLDebug("GPKG", "Setting PRAGMA trusted_schema = 1");
    9686        1342 :             SQLCommand(hDB, "PRAGMA trusted_schema = 1");
    9687             :         }
    9688             :     }
    9689             : 
    9690             :     const char *pszPreludeStatements =
    9691        2463 :         CSLFetchNameValue(papszOpenOptions, "PRELUDE_STATEMENTS");
    9692        2463 :     if (pszPreludeStatements)
    9693             :     {
    9694           2 :         if (SQLCommand(hDB, pszPreludeStatements) != OGRERR_NONE)
    9695           0 :             return false;
    9696             :     }
    9697             : 
    9698        2463 :     return true;
    9699             : }
    9700             : 
    9701             : /************************************************************************/
    9702             : /*                 GetLayerWithGetSpatialWhereByName()                  */
    9703             : /************************************************************************/
    9704             : 
    9705             : std::pair<OGRLayer *, IOGRSQLiteGetSpatialWhere *>
    9706          90 : GDALGeoPackageDataset::GetLayerWithGetSpatialWhereByName(const char *pszName)
    9707             : {
    9708             :     OGRGeoPackageLayer *poRet =
    9709          90 :         cpl::down_cast<OGRGeoPackageLayer *>(GetLayerByName(pszName));
    9710          90 :     return std::pair(poRet, poRet);
    9711             : }
    9712             : 
    9713             : /************************************************************************/
    9714             : /*                         CommitTransaction()                          */
    9715             : /************************************************************************/
    9716             : 
    9717         374 : OGRErr GDALGeoPackageDataset::CommitTransaction()
    9718             : 
    9719             : {
    9720         374 :     if (m_nSoftTransactionLevel == 1)
    9721             :     {
    9722         368 :         FlushMetadata();
    9723         791 :         for (auto &poLayer : m_apoLayers)
    9724             :         {
    9725         423 :             poLayer->DoJobAtTransactionCommit();
    9726             :         }
    9727             :     }
    9728             : 
    9729         374 :     return OGRSQLiteBaseDataSource::CommitTransaction();
    9730             : }
    9731             : 
    9732             : /************************************************************************/
    9733             : /*                        RollbackTransaction()                         */
    9734             : /************************************************************************/
    9735             : 
    9736          37 : OGRErr GDALGeoPackageDataset::RollbackTransaction()
    9737             : 
    9738             : {
    9739             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9740          74 :     std::vector<bool> abAddTriggers;
    9741          37 :     std::vector<bool> abTriggersDeletedInTransaction;
    9742             : #endif
    9743          37 :     if (m_nSoftTransactionLevel == 1)
    9744             :     {
    9745          36 :         FlushMetadata();
    9746          74 :         for (auto &poLayer : m_apoLayers)
    9747             :         {
    9748             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9749          38 :             abAddTriggers.push_back(poLayer->GetAddOGRFeatureCountTriggers());
    9750          38 :             abTriggersDeletedInTransaction.push_back(
    9751          38 :                 poLayer->GetOGRFeatureCountTriggersDeletedInTransaction());
    9752          38 :             poLayer->SetAddOGRFeatureCountTriggers(false);
    9753             : #endif
    9754          38 :             poLayer->DoJobAtTransactionRollback();
    9755             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9756          38 :             poLayer->DisableFeatureCount();
    9757             : #endif
    9758             :         }
    9759             :     }
    9760             : 
    9761          37 :     const OGRErr eErr = OGRSQLiteBaseDataSource::RollbackTransaction();
    9762             : 
    9763             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9764          37 :     if (!abAddTriggers.empty())
    9765             :     {
    9766          72 :         for (size_t i = 0; i < m_apoLayers.size(); ++i)
    9767             :         {
    9768          38 :             auto &poLayer = m_apoLayers[i];
    9769          38 :             if (abTriggersDeletedInTransaction[i])
    9770             :             {
    9771           7 :                 poLayer->SetOGRFeatureCountTriggersEnabled(true);
    9772             :             }
    9773             :             else
    9774             :             {
    9775          31 :                 poLayer->SetAddOGRFeatureCountTriggers(abAddTriggers[i]);
    9776             :             }
    9777             :         }
    9778             :     }
    9779             : #endif
    9780          74 :     return eErr;
    9781             : }
    9782             : 
    9783             : /************************************************************************/
    9784             : /*                       GetGeometryTypeString()                        */
    9785             : /************************************************************************/
    9786             : 
    9787             : const char *
    9788        1803 : GDALGeoPackageDataset::GetGeometryTypeString(OGRwkbGeometryType eType)
    9789             : {
    9790        1803 :     const char *pszGPKGGeomType = OGRToOGCGeomType(eType);
    9791        1815 :     if (EQUAL(pszGPKGGeomType, "GEOMETRYCOLLECTION") &&
    9792          12 :         CPLTestBool(CPLGetConfigOption("OGR_GPKG_GEOMCOLLECTION", "NO")))
    9793             :     {
    9794           0 :         pszGPKGGeomType = "GEOMCOLLECTION";
    9795             :     }
    9796        1803 :     return pszGPKGGeomType;
    9797             : }
    9798             : 
    9799             : /************************************************************************/
    9800             : /*                        GetFieldDomainNames()                         */
    9801             : /************************************************************************/
    9802             : 
    9803             : std::vector<std::string>
    9804          18 : GDALGeoPackageDataset::GetFieldDomainNames(CSLConstList) const
    9805             : {
    9806          18 :     if (!HasDataColumnConstraintsTable())
    9807           3 :         return std::vector<std::string>();
    9808             : 
    9809          30 :     std::vector<std::string> oDomainNamesList;
    9810             : 
    9811          15 :     std::unique_ptr<SQLResult> oResultTable;
    9812             :     {
    9813             :         std::string osSQL =
    9814             :             "SELECT DISTINCT constraint_name "
    9815             :             "FROM gpkg_data_column_constraints "
    9816             :             "WHERE constraint_name NOT LIKE '_%_domain_description' "
    9817             :             "ORDER BY constraint_name "
    9818          15 :             "LIMIT 10000"  // to avoid denial of service
    9819             :             ;
    9820          15 :         oResultTable = SQLQuery(hDB, osSQL.c_str());
    9821          15 :         if (!oResultTable)
    9822           0 :             return oDomainNamesList;
    9823             :     }
    9824             : 
    9825          15 :     if (oResultTable->RowCount() == 10000)
    9826             :     {
    9827           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9828             :                  "Number of rows returned for field domain names has been "
    9829             :                  "truncated.");
    9830             :     }
    9831          15 :     else if (oResultTable->RowCount() > 0)
    9832             :     {
    9833          14 :         oDomainNamesList.reserve(oResultTable->RowCount());
    9834         147 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    9835             :         {
    9836         133 :             const char *pszConstraintName = oResultTable->GetValue(0, i);
    9837         133 :             if (!pszConstraintName)
    9838           0 :                 continue;
    9839             : 
    9840         133 :             oDomainNamesList.emplace_back(pszConstraintName);
    9841             :         }
    9842             :     }
    9843             : 
    9844          15 :     return oDomainNamesList;
    9845             : }
    9846             : 
    9847             : /************************************************************************/
    9848             : /*                           GetFieldDomain()                           */
    9849             : /************************************************************************/
    9850             : 
    9851             : const OGRFieldDomain *
    9852         140 : GDALGeoPackageDataset::GetFieldDomain(const std::string &name) const
    9853             : {
    9854         140 :     const auto baseRet = GDALDataset::GetFieldDomain(name);
    9855         140 :     if (baseRet)
    9856          43 :         return baseRet;
    9857             : 
    9858          97 :     if (!HasDataColumnConstraintsTable())
    9859           4 :         return nullptr;
    9860             : 
    9861          93 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
    9862          93 :     const char *min_is_inclusive =
    9863          93 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
    9864          93 :     const char *max_is_inclusive =
    9865          93 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
    9866             : 
    9867          93 :     std::unique_ptr<SQLResult> oResultTable;
    9868             :     // Note: for coded domains, we use a little trick by using a dummy
    9869             :     // _{domainname}_domain_description enum that has a single entry whose
    9870             :     // description is the description of the main domain.
    9871             :     {
    9872          93 :         char *pszSQL = sqlite3_mprintf(
    9873             :             "SELECT constraint_type, value, min, %s, "
    9874             :             "max, %s, description, constraint_name "
    9875             :             "FROM gpkg_data_column_constraints "
    9876             :             "WHERE constraint_name IN ('%q', "
    9877             :             "'_%q_domain_description') "
    9878             :             "AND length(constraint_type) < 100 "  // to
    9879             :                                                   // avoid
    9880             :                                                   // denial
    9881             :                                                   // of
    9882             :                                                   // service
    9883             :             "AND (value IS NULL OR length(value) < "
    9884             :             "10000) "  // to avoid denial
    9885             :                        // of service
    9886             :             "AND (description IS NULL OR "
    9887             :             "length(description) < 10000) "  // to
    9888             :                                              // avoid
    9889             :                                              // denial
    9890             :                                              // of
    9891             :                                              // service
    9892             :             "ORDER BY value "
    9893             :             "LIMIT 10000",  // to avoid denial of
    9894             :                             // service
    9895             :             min_is_inclusive, max_is_inclusive, name.c_str(), name.c_str());
    9896          93 :         oResultTable = SQLQuery(hDB, pszSQL);
    9897          93 :         sqlite3_free(pszSQL);
    9898          93 :         if (!oResultTable)
    9899           0 :             return nullptr;
    9900             :     }
    9901          93 :     if (oResultTable->RowCount() == 0)
    9902             :     {
    9903          33 :         return nullptr;
    9904             :     }
    9905          60 :     if (oResultTable->RowCount() == 10000)
    9906             :     {
    9907           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9908             :                  "Number of rows returned for field domain %s has been "
    9909             :                  "truncated.",
    9910             :                  name.c_str());
    9911             :     }
    9912             : 
    9913             :     // Try to find the field domain data type from fields that implement it
    9914          60 :     int nFieldType = -1;
    9915          60 :     OGRFieldSubType eSubType = OFSTNone;
    9916          60 :     if (HasDataColumnsTable())
    9917             :     {
    9918          55 :         char *pszSQL = sqlite3_mprintf(
    9919             :             "SELECT table_name, column_name FROM gpkg_data_columns WHERE "
    9920             :             "constraint_name = '%q' LIMIT 10",
    9921             :             name.c_str());
    9922         110 :         auto oResultTable2 = SQLQuery(hDB, pszSQL);
    9923          55 :         sqlite3_free(pszSQL);
    9924          55 :         if (oResultTable2 && oResultTable2->RowCount() >= 1)
    9925             :         {
    9926          62 :             for (int iRecord = 0; iRecord < oResultTable2->RowCount();
    9927             :                  iRecord++)
    9928             :             {
    9929          31 :                 const char *pszTableName = oResultTable2->GetValue(0, iRecord);
    9930          31 :                 const char *pszColumnName = oResultTable2->GetValue(1, iRecord);
    9931          31 :                 if (pszTableName == nullptr || pszColumnName == nullptr)
    9932           0 :                     continue;
    9933             :                 OGRLayer *poLayer =
    9934          62 :                     const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    9935          31 :                         pszTableName);
    9936          31 :                 if (poLayer)
    9937             :                 {
    9938          31 :                     const auto poFDefn = poLayer->GetLayerDefn();
    9939          31 :                     int nIdx = poFDefn->GetFieldIndex(pszColumnName);
    9940          31 :                     if (nIdx >= 0)
    9941             :                     {
    9942          31 :                         const auto poFieldDefn = poFDefn->GetFieldDefn(nIdx);
    9943          31 :                         const auto eType = poFieldDefn->GetType();
    9944          31 :                         if (nFieldType < 0)
    9945             :                         {
    9946          31 :                             nFieldType = eType;
    9947          31 :                             eSubType = poFieldDefn->GetSubType();
    9948             :                         }
    9949           0 :                         else if ((eType == OFTInteger64 || eType == OFTReal) &&
    9950             :                                  nFieldType == OFTInteger)
    9951             :                         {
    9952             :                             // ok
    9953             :                         }
    9954           0 :                         else if (eType == OFTInteger &&
    9955           0 :                                  (nFieldType == OFTInteger64 ||
    9956             :                                   nFieldType == OFTReal))
    9957             :                         {
    9958           0 :                             nFieldType = OFTInteger;
    9959           0 :                             eSubType = OFSTNone;
    9960             :                         }
    9961           0 :                         else if (nFieldType != eType)
    9962             :                         {
    9963           0 :                             nFieldType = -1;
    9964           0 :                             eSubType = OFSTNone;
    9965           0 :                             break;
    9966             :                         }
    9967             :                     }
    9968             :                 }
    9969             :             }
    9970             :         }
    9971             :     }
    9972             : 
    9973          60 :     std::unique_ptr<OGRFieldDomain> poDomain;
    9974         120 :     std::vector<OGRCodedValue> asValues;
    9975          60 :     bool error = false;
    9976         120 :     CPLString osLastConstraintType;
    9977          60 :     int nFieldTypeFromEnumCode = -1;
    9978         120 :     std::string osConstraintDescription;
    9979         120 :     std::string osDescrConstraintName("_");
    9980          60 :     osDescrConstraintName += name;
    9981          60 :     osDescrConstraintName += "_domain_description";
    9982         151 :     for (int iRecord = 0; iRecord < oResultTable->RowCount(); iRecord++)
    9983             :     {
    9984          95 :         const char *pszConstraintType = oResultTable->GetValue(0, iRecord);
    9985          95 :         if (pszConstraintType == nullptr)
    9986           2 :             continue;
    9987          95 :         const char *pszValue = oResultTable->GetValue(1, iRecord);
    9988          95 :         const char *pszMin = oResultTable->GetValue(2, iRecord);
    9989             :         const bool bIsMinIncluded =
    9990          95 :             oResultTable->GetValueAsInteger(3, iRecord) == 1;
    9991          95 :         const char *pszMax = oResultTable->GetValue(4, iRecord);
    9992             :         const bool bIsMaxIncluded =
    9993          95 :             oResultTable->GetValueAsInteger(5, iRecord) == 1;
    9994          95 :         const char *pszDescription = oResultTable->GetValue(6, iRecord);
    9995          95 :         const char *pszConstraintName = oResultTable->GetValue(7, iRecord);
    9996             : 
    9997          95 :         if (!osLastConstraintType.empty() && osLastConstraintType != "enum")
    9998             :         {
    9999           1 :             CPLError(CE_Failure, CPLE_AppDefined,
   10000             :                      "Only constraint of type 'enum' can have multiple rows");
   10001           1 :             error = true;
   10002           4 :             break;
   10003             :         }
   10004             : 
   10005          94 :         if (strcmp(pszConstraintType, "enum") == 0)
   10006             :         {
   10007          67 :             if (pszValue == nullptr)
   10008             :             {
   10009           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10010             :                          "NULL in 'value' column of enumeration");
   10011           1 :                 error = true;
   10012           1 :                 break;
   10013             :             }
   10014          66 :             if (osDescrConstraintName == pszConstraintName)
   10015             :             {
   10016           2 :                 if (pszDescription)
   10017             :                 {
   10018           2 :                     osConstraintDescription = pszDescription;
   10019             :                 }
   10020           2 :                 continue;
   10021             :             }
   10022          64 :             if (asValues.empty())
   10023             :             {
   10024          32 :                 asValues.reserve(oResultTable->RowCount() + 1);
   10025             :             }
   10026             :             OGRCodedValue cv;
   10027             :             // intended: the 'value' column in GPKG is actually the code
   10028          64 :             cv.pszCode = VSI_STRDUP_VERBOSE(pszValue);
   10029          64 :             if (cv.pszCode == nullptr)
   10030             :             {
   10031           0 :                 error = true;
   10032           0 :                 break;
   10033             :             }
   10034          64 :             if (pszDescription)
   10035             :             {
   10036          50 :                 cv.pszValue = VSI_STRDUP_VERBOSE(pszDescription);
   10037          50 :                 if (cv.pszValue == nullptr)
   10038             :                 {
   10039           0 :                     VSIFree(cv.pszCode);
   10040           0 :                     error = true;
   10041           0 :                     break;
   10042             :                 }
   10043             :             }
   10044             :             else
   10045             :             {
   10046          14 :                 cv.pszValue = nullptr;
   10047             :             }
   10048             : 
   10049             :             // If we can't get the data type from field definition, guess it
   10050             :             // from code.
   10051          64 :             if (nFieldType < 0 && nFieldTypeFromEnumCode != OFTString)
   10052             :             {
   10053          36 :                 switch (CPLGetValueType(cv.pszCode))
   10054             :                 {
   10055          26 :                     case CPL_VALUE_INTEGER:
   10056             :                     {
   10057          26 :                         if (nFieldTypeFromEnumCode != OFTReal &&
   10058             :                             nFieldTypeFromEnumCode != OFTInteger64)
   10059             :                         {
   10060          18 :                             const auto nVal = CPLAtoGIntBig(cv.pszCode);
   10061          34 :                             if (nVal < std::numeric_limits<int>::min() ||
   10062          16 :                                 nVal > std::numeric_limits<int>::max())
   10063             :                             {
   10064           6 :                                 nFieldTypeFromEnumCode = OFTInteger64;
   10065             :                             }
   10066             :                             else
   10067             :                             {
   10068          12 :                                 nFieldTypeFromEnumCode = OFTInteger;
   10069             :                             }
   10070             :                         }
   10071          26 :                         break;
   10072             :                     }
   10073             : 
   10074           6 :                     case CPL_VALUE_REAL:
   10075           6 :                         nFieldTypeFromEnumCode = OFTReal;
   10076           6 :                         break;
   10077             : 
   10078           4 :                     case CPL_VALUE_STRING:
   10079           4 :                         nFieldTypeFromEnumCode = OFTString;
   10080           4 :                         break;
   10081             :                 }
   10082             :             }
   10083             : 
   10084          64 :             asValues.emplace_back(cv);
   10085             :         }
   10086          27 :         else if (strcmp(pszConstraintType, "range") == 0)
   10087             :         {
   10088             :             OGRField sMin;
   10089             :             OGRField sMax;
   10090          20 :             OGR_RawField_SetUnset(&sMin);
   10091          20 :             OGR_RawField_SetUnset(&sMax);
   10092          20 :             if (nFieldType != OFTInteger && nFieldType != OFTInteger64)
   10093          11 :                 nFieldType = OFTReal;
   10094          39 :             if (pszMin != nullptr &&
   10095          19 :                 CPLAtof(pszMin) != -std::numeric_limits<double>::infinity())
   10096             :             {
   10097          15 :                 if (nFieldType == OFTInteger)
   10098           6 :                     sMin.Integer = atoi(pszMin);
   10099           9 :                 else if (nFieldType == OFTInteger64)
   10100           3 :                     sMin.Integer64 = CPLAtoGIntBig(pszMin);
   10101             :                 else /* if( nFieldType == OFTReal ) */
   10102           6 :                     sMin.Real = CPLAtof(pszMin);
   10103             :             }
   10104          39 :             if (pszMax != nullptr &&
   10105          19 :                 CPLAtof(pszMax) != std::numeric_limits<double>::infinity())
   10106             :             {
   10107          15 :                 if (nFieldType == OFTInteger)
   10108           6 :                     sMax.Integer = atoi(pszMax);
   10109           9 :                 else if (nFieldType == OFTInteger64)
   10110           3 :                     sMax.Integer64 = CPLAtoGIntBig(pszMax);
   10111             :                 else /* if( nFieldType == OFTReal ) */
   10112           6 :                     sMax.Real = CPLAtof(pszMax);
   10113             :             }
   10114          20 :             poDomain = std::make_unique<OGRRangeFieldDomain>(
   10115          20 :                 name, pszDescription ? pszDescription : "",
   10116          40 :                 static_cast<OGRFieldType>(nFieldType), eSubType, sMin,
   10117          20 :                 bIsMinIncluded, sMax, bIsMaxIncluded);
   10118             :         }
   10119           7 :         else if (strcmp(pszConstraintType, "glob") == 0)
   10120             :         {
   10121           6 :             if (pszValue == nullptr)
   10122             :             {
   10123           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10124             :                          "NULL in 'value' column of glob");
   10125           1 :                 error = true;
   10126           1 :                 break;
   10127             :             }
   10128           5 :             if (nFieldType < 0)
   10129           1 :                 nFieldType = OFTString;
   10130           5 :             poDomain = std::make_unique<OGRGlobFieldDomain>(
   10131           5 :                 name, pszDescription ? pszDescription : "",
   10132          15 :                 static_cast<OGRFieldType>(nFieldType), eSubType, pszValue);
   10133             :         }
   10134             :         else
   10135             :         {
   10136           1 :             CPLError(CE_Failure, CPLE_AppDefined,
   10137             :                      "Unhandled constraint_type: %s", pszConstraintType);
   10138           1 :             error = true;
   10139           1 :             break;
   10140             :         }
   10141             : 
   10142          89 :         osLastConstraintType = pszConstraintType;
   10143             :     }
   10144             : 
   10145          60 :     if (!asValues.empty())
   10146             :     {
   10147          32 :         if (nFieldType < 0)
   10148          18 :             nFieldType = nFieldTypeFromEnumCode;
   10149          32 :         poDomain = std::make_unique<OGRCodedFieldDomain>(
   10150             :             name, osConstraintDescription,
   10151          64 :             static_cast<OGRFieldType>(nFieldType), eSubType,
   10152          64 :             std::move(asValues));
   10153             :     }
   10154             : 
   10155          60 :     if (error)
   10156             :     {
   10157           4 :         return nullptr;
   10158             :     }
   10159             : 
   10160          56 :     m_oMapFieldDomains[name] = std::move(poDomain);
   10161          56 :     return GDALDataset::GetFieldDomain(name);
   10162             : }
   10163             : 
   10164             : /************************************************************************/
   10165             : /*                           AddFieldDomain()                           */
   10166             : /************************************************************************/
   10167             : 
   10168          19 : bool GDALGeoPackageDataset::AddFieldDomain(
   10169             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10170             : {
   10171          38 :     const std::string domainName(domain->GetName());
   10172          19 :     if (!GetUpdate())
   10173             :     {
   10174           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10175             :                  "AddFieldDomain() not supported on read-only dataset");
   10176           0 :         return false;
   10177             :     }
   10178          19 :     if (GetFieldDomain(domainName) != nullptr)
   10179             :     {
   10180           1 :         failureReason = "A domain of identical name already exists";
   10181           1 :         return false;
   10182             :     }
   10183          18 :     if (!CreateColumnsTableAndColumnConstraintsTablesIfNecessary())
   10184           0 :         return false;
   10185             : 
   10186          18 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
   10187          18 :     const char *min_is_inclusive =
   10188          18 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
   10189          18 :     const char *max_is_inclusive =
   10190          18 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
   10191             : 
   10192          18 :     const auto &osDescription = domain->GetDescription();
   10193          18 :     switch (domain->GetDomainType())
   10194             :     {
   10195          11 :         case OFDT_CODED:
   10196             :         {
   10197             :             const auto poCodedDomain =
   10198          11 :                 cpl::down_cast<const OGRCodedFieldDomain *>(domain.get());
   10199          11 :             if (!osDescription.empty())
   10200             :             {
   10201             :                 // We use a little trick by using a dummy
   10202             :                 // _{domainname}_domain_description enum that has a single
   10203             :                 // entry whose description is the description of the main
   10204             :                 // domain.
   10205           1 :                 char *pszSQL = sqlite3_mprintf(
   10206             :                     "INSERT INTO gpkg_data_column_constraints ("
   10207             :                     "constraint_name, constraint_type, value, "
   10208             :                     "min, %s, max, %s, "
   10209             :                     "description) VALUES ("
   10210             :                     "'_%q_domain_description', 'enum', '', NULL, NULL, NULL, "
   10211             :                     "NULL, %Q)",
   10212             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10213             :                     osDescription.c_str());
   10214           1 :                 CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
   10215           1 :                 sqlite3_free(pszSQL);
   10216             :             }
   10217          11 :             const auto &enumeration = poCodedDomain->GetEnumeration();
   10218          33 :             for (int i = 0; enumeration[i].pszCode != nullptr; ++i)
   10219             :             {
   10220          22 :                 char *pszSQL = sqlite3_mprintf(
   10221             :                     "INSERT INTO gpkg_data_column_constraints ("
   10222             :                     "constraint_name, constraint_type, value, "
   10223             :                     "min, %s, max, %s, "
   10224             :                     "description) VALUES ("
   10225             :                     "'%q', 'enum', '%q', NULL, NULL, NULL, NULL, %Q)",
   10226             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10227          22 :                     enumeration[i].pszCode, enumeration[i].pszValue);
   10228          22 :                 bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10229          22 :                 sqlite3_free(pszSQL);
   10230          22 :                 if (!ok)
   10231           0 :                     return false;
   10232             :             }
   10233          11 :             break;
   10234             :         }
   10235             : 
   10236           6 :         case OFDT_RANGE:
   10237             :         {
   10238             :             const auto poRangeDomain =
   10239           6 :                 cpl::down_cast<const OGRRangeFieldDomain *>(domain.get());
   10240           6 :             const auto eFieldType = poRangeDomain->GetFieldType();
   10241           6 :             if (eFieldType != OFTInteger && eFieldType != OFTInteger64 &&
   10242             :                 eFieldType != OFTReal)
   10243             :             {
   10244             :                 failureReason = "Only range domains of numeric type are "
   10245           0 :                                 "supported in GeoPackage";
   10246           0 :                 return false;
   10247             :             }
   10248             : 
   10249           6 :             double dfMin = -std::numeric_limits<double>::infinity();
   10250           6 :             double dfMax = std::numeric_limits<double>::infinity();
   10251           6 :             bool bMinIsInclusive = true;
   10252           6 :             const auto &sMin = poRangeDomain->GetMin(bMinIsInclusive);
   10253           6 :             bool bMaxIsInclusive = true;
   10254           6 :             const auto &sMax = poRangeDomain->GetMax(bMaxIsInclusive);
   10255           6 :             if (eFieldType == OFTInteger)
   10256             :             {
   10257           2 :                 if (!OGR_RawField_IsUnset(&sMin))
   10258           2 :                     dfMin = sMin.Integer;
   10259           2 :                 if (!OGR_RawField_IsUnset(&sMax))
   10260           2 :                     dfMax = sMax.Integer;
   10261             :             }
   10262           4 :             else if (eFieldType == OFTInteger64)
   10263             :             {
   10264           1 :                 if (!OGR_RawField_IsUnset(&sMin))
   10265           1 :                     dfMin = static_cast<double>(sMin.Integer64);
   10266           1 :                 if (!OGR_RawField_IsUnset(&sMax))
   10267           1 :                     dfMax = static_cast<double>(sMax.Integer64);
   10268             :             }
   10269             :             else /* if( eFieldType == OFTReal ) */
   10270             :             {
   10271           3 :                 if (!OGR_RawField_IsUnset(&sMin))
   10272           3 :                     dfMin = sMin.Real;
   10273           3 :                 if (!OGR_RawField_IsUnset(&sMax))
   10274           3 :                     dfMax = sMax.Real;
   10275             :             }
   10276             : 
   10277           6 :             sqlite3_stmt *hInsertStmt = nullptr;
   10278             :             const char *pszSQL =
   10279           6 :                 CPLSPrintf("INSERT INTO gpkg_data_column_constraints ("
   10280             :                            "constraint_name, constraint_type, value, "
   10281             :                            "min, %s, max, %s, "
   10282             :                            "description) VALUES ("
   10283             :                            "?, 'range', NULL, ?, ?, ?, ?, ?)",
   10284             :                            min_is_inclusive, max_is_inclusive);
   10285           6 :             if (SQLPrepareWithError(hDB, pszSQL, -1, &hInsertStmt, nullptr) !=
   10286             :                 SQLITE_OK)
   10287             :             {
   10288           0 :                 return false;
   10289             :             }
   10290           6 :             sqlite3_bind_text(hInsertStmt, 1, domainName.c_str(),
   10291           6 :                               static_cast<int>(domainName.size()),
   10292             :                               SQLITE_TRANSIENT);
   10293           6 :             sqlite3_bind_double(hInsertStmt, 2, dfMin);
   10294           6 :             sqlite3_bind_int(hInsertStmt, 3, bMinIsInclusive ? 1 : 0);
   10295           6 :             sqlite3_bind_double(hInsertStmt, 4, dfMax);
   10296           6 :             sqlite3_bind_int(hInsertStmt, 5, bMaxIsInclusive ? 1 : 0);
   10297           6 :             if (osDescription.empty())
   10298             :             {
   10299           3 :                 sqlite3_bind_null(hInsertStmt, 6);
   10300             :             }
   10301             :             else
   10302             :             {
   10303           3 :                 sqlite3_bind_text(hInsertStmt, 6, osDescription.c_str(),
   10304           3 :                                   static_cast<int>(osDescription.size()),
   10305             :                                   SQLITE_TRANSIENT);
   10306             :             }
   10307           6 :             const int sqlite_err = sqlite3_step(hInsertStmt);
   10308           6 :             sqlite3_finalize(hInsertStmt);
   10309           6 :             if (sqlite_err != SQLITE_OK && sqlite_err != SQLITE_DONE)
   10310             :             {
   10311           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10312             :                          "failed to execute insertion '%s': %s", pszSQL,
   10313             :                          sqlite3_errmsg(hDB));
   10314           0 :                 return false;
   10315             :             }
   10316             : 
   10317           6 :             break;
   10318             :         }
   10319             : 
   10320           1 :         case OFDT_GLOB:
   10321             :         {
   10322             :             const auto poGlobDomain =
   10323           1 :                 cpl::down_cast<const OGRGlobFieldDomain *>(domain.get());
   10324           2 :             char *pszSQL = sqlite3_mprintf(
   10325             :                 "INSERT INTO gpkg_data_column_constraints ("
   10326             :                 "constraint_name, constraint_type, value, "
   10327             :                 "min, %s, max, %s, "
   10328             :                 "description) VALUES ("
   10329             :                 "'%q', 'glob', '%q', NULL, NULL, NULL, NULL, %Q)",
   10330             :                 min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10331           1 :                 poGlobDomain->GetGlob().c_str(),
   10332           2 :                 osDescription.empty() ? nullptr : osDescription.c_str());
   10333           1 :             bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10334           1 :             sqlite3_free(pszSQL);
   10335           1 :             if (!ok)
   10336           0 :                 return false;
   10337             : 
   10338           1 :             break;
   10339             :         }
   10340             :     }
   10341             : 
   10342          18 :     m_oMapFieldDomains[domainName] = std::move(domain);
   10343          18 :     return true;
   10344             : }
   10345             : 
   10346             : /************************************************************************/
   10347             : /*                         UpdateFieldDomain()                          */
   10348             : /************************************************************************/
   10349             : 
   10350           3 : bool GDALGeoPackageDataset::UpdateFieldDomain(
   10351             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10352             : {
   10353           6 :     const std::string domainName(domain->GetName());
   10354           3 :     if (eAccess != GA_Update)
   10355             :     {
   10356           1 :         CPLError(CE_Failure, CPLE_NotSupported,
   10357             :                  "UpdateFieldDomain() not supported on read-only dataset");
   10358           1 :         return false;
   10359             :     }
   10360             : 
   10361           2 :     if (GetFieldDomain(domainName) == nullptr)
   10362             :     {
   10363           1 :         failureReason = "The domain should already exist to be updated";
   10364           1 :         return false;
   10365             :     }
   10366             : 
   10367           1 :     bool bRet = SoftStartTransaction() == OGRERR_NONE;
   10368           1 :     if (bRet)
   10369             :     {
   10370           2 :         bRet = DeleteFieldDomain(domainName, failureReason) &&
   10371           1 :                AddFieldDomain(std::move(domain), failureReason);
   10372           1 :         if (bRet)
   10373           1 :             bRet = SoftCommitTransaction() == OGRERR_NONE;
   10374             :         else
   10375           0 :             SoftRollbackTransaction();
   10376             :     }
   10377           1 :     return bRet;
   10378             : }
   10379             : 
   10380             : /************************************************************************/
   10381             : /*                         DeleteFieldDomain()                          */
   10382             : /************************************************************************/
   10383             : 
   10384          18 : bool GDALGeoPackageDataset::DeleteFieldDomain(const std::string &name,
   10385             :                                               std::string &failureReason)
   10386             : {
   10387          18 :     if (eAccess != GA_Update)
   10388             :     {
   10389           1 :         CPLError(CE_Failure, CPLE_NotSupported,
   10390             :                  "DeleteFieldDomain() not supported on read-only dataset");
   10391           1 :         return false;
   10392             :     }
   10393          17 :     if (GetFieldDomain(name) == nullptr)
   10394             :     {
   10395           1 :         failureReason = "Domain does not exist";
   10396           1 :         return false;
   10397             :     }
   10398             : 
   10399             :     char *pszSQL =
   10400          16 :         sqlite3_mprintf("DELETE FROM gpkg_data_column_constraints WHERE "
   10401             :                         "constraint_name IN ('%q', '_%q_domain_description')",
   10402             :                         name.c_str(), name.c_str());
   10403          16 :     const bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10404          16 :     sqlite3_free(pszSQL);
   10405          16 :     if (ok)
   10406          16 :         m_oMapFieldDomains.erase(name);
   10407          16 :     return ok;
   10408             : }
   10409             : 
   10410             : /************************************************************************/
   10411             : /*                          AddRelationship()                           */
   10412             : /************************************************************************/
   10413             : 
   10414          26 : bool GDALGeoPackageDataset::AddRelationship(
   10415             :     std::unique_ptr<GDALRelationship> &&relationship,
   10416             :     std::string &failureReason)
   10417             : {
   10418          26 :     if (!GetUpdate())
   10419             :     {
   10420           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10421             :                  "AddRelationship() not supported on read-only dataset");
   10422           0 :         return false;
   10423             :     }
   10424             : 
   10425             :     const std::string osRelationshipName = GenerateNameForRelationship(
   10426          26 :         relationship->GetLeftTableName().c_str(),
   10427          26 :         relationship->GetRightTableName().c_str(),
   10428         104 :         relationship->GetRelatedTableType().c_str());
   10429             :     // sanity checks
   10430          26 :     if (GetRelationship(osRelationshipName) != nullptr)
   10431             :     {
   10432           1 :         failureReason = "A relationship of identical name already exists";
   10433           1 :         return false;
   10434             :     }
   10435             : 
   10436          25 :     if (!ValidateRelationship(relationship.get(), failureReason))
   10437             :     {
   10438          14 :         return false;
   10439             :     }
   10440             : 
   10441          75 :     for (auto &poLayer : m_apoLayers)
   10442             :     {
   10443          64 :         if (poLayer->SyncToDisk() != OGRERR_NONE)
   10444           0 :             return false;
   10445             :     }
   10446             : 
   10447          11 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
   10448             :     {
   10449           0 :         return false;
   10450             :     }
   10451          11 :     if (!CreateRelationsTableIfNecessary())
   10452             :     {
   10453           0 :         failureReason = "Could not create gpkgext_relations table";
   10454           0 :         return false;
   10455             :     }
   10456          11 :     if (SQLGetInteger(GetDB(),
   10457             :                       "SELECT 1 FROM gpkg_extensions WHERE "
   10458             :                       "table_name = 'gpkgext_relations'",
   10459          11 :                       nullptr) != 1)
   10460             :     {
   10461           5 :         if (OGRERR_NONE !=
   10462           5 :             SQLCommand(
   10463             :                 GetDB(),
   10464             :                 "INSERT INTO gpkg_extensions "
   10465             :                 "(table_name,column_name,extension_name,definition,scope) "
   10466             :                 "VALUES ('gpkgext_relations', NULL, 'gpkg_related_tables', "
   10467             :                 "'http://www.geopackage.org/18-000.html', "
   10468             :                 "'read-write')"))
   10469             :         {
   10470             :             failureReason =
   10471           0 :                 "Could not create gpkg_extensions entry for gpkgext_relations";
   10472           0 :             return false;
   10473             :         }
   10474             :     }
   10475             : 
   10476          11 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10477          11 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10478          11 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10479          11 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10480             : 
   10481          22 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10482          11 :     if (osRelatedTableType.empty())
   10483             :     {
   10484           5 :         osRelatedTableType = "features";
   10485             :     }
   10486             : 
   10487             :     // generate mapping table if not set
   10488          22 :     CPLString osMappingTableName = relationship->GetMappingTableName();
   10489          11 :     if (osMappingTableName.empty())
   10490             :     {
   10491           5 :         int nIndex = 1;
   10492           5 :         osMappingTableName = osLeftTableName + "_" + osRightTableName;
   10493           5 :         while (FindLayerIndex(osMappingTableName.c_str()) >= 0)
   10494             :         {
   10495           0 :             nIndex += 1;
   10496             :             osMappingTableName.Printf("%s_%s_%d", osLeftTableName.c_str(),
   10497           0 :                                       osRightTableName.c_str(), nIndex);
   10498             :         }
   10499             : 
   10500             :         // determine whether base/related keys are unique
   10501           5 :         bool bBaseKeyIsUnique = false;
   10502             :         {
   10503             :             const std::set<std::string> uniqueBaseFieldsUC =
   10504             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10505          10 :                                                osLeftTableName.c_str());
   10506          10 :             if (uniqueBaseFieldsUC.find(
   10507           5 :                     CPLString(aosLeftTableFields[0]).toupper()) !=
   10508          10 :                 uniqueBaseFieldsUC.end())
   10509             :             {
   10510           2 :                 bBaseKeyIsUnique = true;
   10511             :             }
   10512             :         }
   10513           5 :         bool bRelatedKeyIsUnique = false;
   10514             :         {
   10515             :             const std::set<std::string> uniqueRelatedFieldsUC =
   10516             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10517          10 :                                                osRightTableName.c_str());
   10518          10 :             if (uniqueRelatedFieldsUC.find(
   10519           5 :                     CPLString(aosRightTableFields[0]).toupper()) !=
   10520          10 :                 uniqueRelatedFieldsUC.end())
   10521             :             {
   10522           2 :                 bRelatedKeyIsUnique = true;
   10523             :             }
   10524             :         }
   10525             : 
   10526             :         // create mapping table
   10527             : 
   10528           5 :         std::string osBaseIdDefinition = "base_id INTEGER";
   10529           5 :         if (bBaseKeyIsUnique)
   10530             :         {
   10531           2 :             char *pszSQL = sqlite3_mprintf(
   10532             :                 " CONSTRAINT 'fk_base_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10533             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10534             :                 "DEFERRED",
   10535             :                 osMappingTableName.c_str(), osLeftTableName.c_str(),
   10536           2 :                 aosLeftTableFields[0].c_str());
   10537           2 :             osBaseIdDefinition += pszSQL;
   10538           2 :             sqlite3_free(pszSQL);
   10539             :         }
   10540             : 
   10541           5 :         std::string osRelatedIdDefinition = "related_id INTEGER";
   10542           5 :         if (bRelatedKeyIsUnique)
   10543             :         {
   10544           2 :             char *pszSQL = sqlite3_mprintf(
   10545             :                 " CONSTRAINT 'fk_related_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10546             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10547             :                 "DEFERRED",
   10548             :                 osMappingTableName.c_str(), osRightTableName.c_str(),
   10549           2 :                 aosRightTableFields[0].c_str());
   10550           2 :             osRelatedIdDefinition += pszSQL;
   10551           2 :             sqlite3_free(pszSQL);
   10552             :         }
   10553             : 
   10554           5 :         char *pszSQL = sqlite3_mprintf("CREATE TABLE \"%w\" ("
   10555             :                                        "id INTEGER PRIMARY KEY AUTOINCREMENT, "
   10556             :                                        "%s, %s);",
   10557             :                                        osMappingTableName.c_str(),
   10558             :                                        osBaseIdDefinition.c_str(),
   10559             :                                        osRelatedIdDefinition.c_str());
   10560           5 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
   10561           5 :         sqlite3_free(pszSQL);
   10562           5 :         if (eErr != OGRERR_NONE)
   10563             :         {
   10564             :             failureReason =
   10565           0 :                 ("Could not create mapping table " + osMappingTableName)
   10566           0 :                     .c_str();
   10567           0 :             return false;
   10568             :         }
   10569             : 
   10570             :         /*
   10571             :          * Strictly speaking we should NOT be inserting the mapping table into gpkg_contents.
   10572             :          * The related tables extension explicitly states that the mapping table should only be
   10573             :          * in the gpkgext_relations table and not in gpkg_contents. (See also discussion at
   10574             :          * https://github.com/opengeospatial/geopackage/issues/679).
   10575             :          *
   10576             :          * However, if we don't insert the mapping table into gpkg_contents then it is no longer
   10577             :          * visible to some clients (eg ESRI software only allows opening tables that are present
   10578             :          * in gpkg_contents). So we'll do this anyway, for maximum compatibility and flexibility.
   10579             :          *
   10580             :          * More related discussion is at https://github.com/OSGeo/gdal/pull/9258
   10581             :          */
   10582           5 :         pszSQL = sqlite3_mprintf(
   10583             :             "INSERT INTO gpkg_contents "
   10584             :             "(table_name,data_type,identifier,description,last_change,srs_id) "
   10585             :             "VALUES "
   10586             :             "('%q','attributes','%q','Mapping table for relationship between "
   10587             :             "%q and %q',%s,0)",
   10588             :             osMappingTableName.c_str(), /*table_name*/
   10589             :             osMappingTableName.c_str(), /*identifier*/
   10590             :             osLeftTableName.c_str(),    /*description left table name*/
   10591             :             osRightTableName.c_str(),   /*description right table name*/
   10592          10 :             GDALGeoPackageDataset::GetCurrentDateEscapedSQL().c_str());
   10593             : 
   10594             :         // Note -- we explicitly ignore failures here, because hey, we aren't really
   10595             :         // supposed to be adding this table to gpkg_contents anyway!
   10596           5 :         (void)SQLCommand(hDB, pszSQL);
   10597           5 :         sqlite3_free(pszSQL);
   10598             : 
   10599           5 :         pszSQL = sqlite3_mprintf(
   10600             :             "CREATE INDEX \"idx_%w_base_id\" ON \"%w\" (base_id);",
   10601             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10602           5 :         eErr = SQLCommand(hDB, pszSQL);
   10603           5 :         sqlite3_free(pszSQL);
   10604           5 :         if (eErr != OGRERR_NONE)
   10605             :         {
   10606           0 :             failureReason = ("Could not create index for " +
   10607           0 :                              osMappingTableName + " (base_id)")
   10608           0 :                                 .c_str();
   10609           0 :             return false;
   10610             :         }
   10611             : 
   10612           5 :         pszSQL = sqlite3_mprintf(
   10613             :             "CREATE INDEX \"idx_%qw_related_id\" ON \"%w\" (related_id);",
   10614             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10615           5 :         eErr = SQLCommand(hDB, pszSQL);
   10616           5 :         sqlite3_free(pszSQL);
   10617           5 :         if (eErr != OGRERR_NONE)
   10618             :         {
   10619           0 :             failureReason = ("Could not create index for " +
   10620           0 :                              osMappingTableName + " (related_id)")
   10621           0 :                                 .c_str();
   10622           0 :             return false;
   10623             :         }
   10624             : 
   10625             :         auto poLayer = std::make_unique<OGRGeoPackageTableLayer>(
   10626          10 :             this, osMappingTableName.c_str());
   10627           5 :         poLayer->SetOpeningParameters(osMappingTableName.c_str(), "table",
   10628             :                                       /* bIsInGpkgContents = */ true,
   10629             :                                       /* bIsSpatial = */ false,
   10630             :                                       /* pszGeomColName =*/nullptr,
   10631             :                                       /* pszGeomType =*/nullptr,
   10632             :                                       /* bHasZ = */ false, /* bHasM = */ false);
   10633           5 :         m_apoLayers.push_back(std::move(poLayer));
   10634             :     }
   10635             :     else
   10636             :     {
   10637             :         // validate mapping table structure
   10638           6 :         if (OGRGeoPackageTableLayer *poLayer =
   10639           6 :                 cpl::down_cast<OGRGeoPackageTableLayer *>(
   10640           6 :                     GetLayerByName(osMappingTableName)))
   10641             :         {
   10642           4 :             if (poLayer->GetLayerDefn()->GetFieldIndex("base_id") < 0)
   10643             :             {
   10644             :                 failureReason =
   10645           2 :                     ("Field base_id must exist in " + osMappingTableName)
   10646           1 :                         .c_str();
   10647           1 :                 return false;
   10648             :             }
   10649           3 :             if (poLayer->GetLayerDefn()->GetFieldIndex("related_id") < 0)
   10650             :             {
   10651             :                 failureReason =
   10652           2 :                     ("Field related_id must exist in " + osMappingTableName)
   10653           1 :                         .c_str();
   10654           1 :                 return false;
   10655             :             }
   10656             :         }
   10657             :         else
   10658             :         {
   10659             :             failureReason =
   10660           2 :                 ("Could not retrieve table " + osMappingTableName).c_str();
   10661           2 :             return false;
   10662             :         }
   10663             :     }
   10664             : 
   10665           7 :     char *pszSQL = sqlite3_mprintf(
   10666             :         "INSERT INTO gpkg_extensions "
   10667             :         "(table_name,column_name,extension_name,definition,scope) "
   10668             :         "VALUES ('%q', NULL, 'gpkg_related_tables', "
   10669             :         "'http://www.geopackage.org/18-000.html', "
   10670             :         "'read-write')",
   10671             :         osMappingTableName.c_str());
   10672           7 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10673           7 :     sqlite3_free(pszSQL);
   10674           7 :     if (eErr != OGRERR_NONE)
   10675             :     {
   10676           0 :         failureReason = ("Could not insert mapping table " +
   10677           0 :                          osMappingTableName + " into gpkg_extensions")
   10678           0 :                             .c_str();
   10679           0 :         return false;
   10680             :     }
   10681             : 
   10682          21 :     pszSQL = sqlite3_mprintf(
   10683             :         "INSERT INTO gpkgext_relations "
   10684             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10685             :         "primary_column,relation_name,mapping_table_name) "
   10686             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10687           7 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10688           7 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10689             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10690           7 :     eErr = SQLCommand(hDB, pszSQL);
   10691           7 :     sqlite3_free(pszSQL);
   10692           7 :     if (eErr != OGRERR_NONE)
   10693             :     {
   10694           0 :         failureReason = "Could not insert relationship into gpkgext_relations";
   10695           0 :         return false;
   10696             :     }
   10697             : 
   10698           7 :     ClearCachedRelationships();
   10699           7 :     LoadRelationships();
   10700           7 :     return true;
   10701             : }
   10702             : 
   10703             : /************************************************************************/
   10704             : /*                         DeleteRelationship()                         */
   10705             : /************************************************************************/
   10706             : 
   10707           4 : bool GDALGeoPackageDataset::DeleteRelationship(const std::string &name,
   10708             :                                                std::string &failureReason)
   10709             : {
   10710           4 :     if (eAccess != GA_Update)
   10711             :     {
   10712           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10713             :                  "DeleteRelationship() not supported on read-only dataset");
   10714           0 :         return false;
   10715             :     }
   10716             : 
   10717             :     // ensure relationships are up to date before we try to remove one
   10718           4 :     ClearCachedRelationships();
   10719           4 :     LoadRelationships();
   10720             : 
   10721           8 :     std::string osMappingTableName;
   10722             :     {
   10723           4 :         const GDALRelationship *poRelationship = GetRelationship(name);
   10724           4 :         if (poRelationship == nullptr)
   10725             :         {
   10726           1 :             failureReason = "Could not find relationship with name " + name;
   10727           1 :             return false;
   10728             :         }
   10729             : 
   10730           3 :         osMappingTableName = poRelationship->GetMappingTableName();
   10731             :     }
   10732             : 
   10733             :     // DeleteLayerCommon will delete existing relationship objects, so we can't
   10734             :     // refer to poRelationship or any of its members previously obtained here
   10735           3 :     if (DeleteLayerCommon(osMappingTableName.c_str()) != OGRERR_NONE)
   10736             :     {
   10737             :         failureReason =
   10738           0 :             "Could not remove mapping layer name " + osMappingTableName;
   10739             : 
   10740             :         // relationships may have been left in an inconsistent state -- reload
   10741             :         // them now
   10742           0 :         ClearCachedRelationships();
   10743           0 :         LoadRelationships();
   10744           0 :         return false;
   10745             :     }
   10746             : 
   10747           3 :     ClearCachedRelationships();
   10748           3 :     LoadRelationships();
   10749           3 :     return true;
   10750             : }
   10751             : 
   10752             : /************************************************************************/
   10753             : /*                         UpdateRelationship()                         */
   10754             : /************************************************************************/
   10755             : 
   10756           6 : bool GDALGeoPackageDataset::UpdateRelationship(
   10757             :     std::unique_ptr<GDALRelationship> &&relationship,
   10758             :     std::string &failureReason)
   10759             : {
   10760           6 :     if (eAccess != GA_Update)
   10761             :     {
   10762           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10763             :                  "UpdateRelationship() not supported on read-only dataset");
   10764           0 :         return false;
   10765             :     }
   10766             : 
   10767             :     // ensure relationships are up to date before we try to update one
   10768           6 :     ClearCachedRelationships();
   10769           6 :     LoadRelationships();
   10770             : 
   10771           6 :     const std::string &osRelationshipName = relationship->GetName();
   10772           6 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10773           6 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10774           6 :     const std::string &osMappingTableName = relationship->GetMappingTableName();
   10775           6 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10776           6 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10777             : 
   10778             :     // sanity checks
   10779             :     {
   10780             :         const GDALRelationship *poExistingRelationship =
   10781           6 :             GetRelationship(osRelationshipName);
   10782           6 :         if (poExistingRelationship == nullptr)
   10783             :         {
   10784             :             failureReason =
   10785           1 :                 "The relationship should already exist to be updated";
   10786           1 :             return false;
   10787             :         }
   10788             : 
   10789           5 :         if (!ValidateRelationship(relationship.get(), failureReason))
   10790             :         {
   10791           2 :             return false;
   10792             :         }
   10793             : 
   10794             :         // we don't permit changes to the participating tables
   10795           3 :         if (osLeftTableName != poExistingRelationship->GetLeftTableName())
   10796             :         {
   10797           0 :             failureReason = ("Cannot change base table from " +
   10798           0 :                              poExistingRelationship->GetLeftTableName() +
   10799           0 :                              " to " + osLeftTableName)
   10800           0 :                                 .c_str();
   10801           0 :             return false;
   10802             :         }
   10803           3 :         if (osRightTableName != poExistingRelationship->GetRightTableName())
   10804             :         {
   10805           0 :             failureReason = ("Cannot change related table from " +
   10806           0 :                              poExistingRelationship->GetRightTableName() +
   10807           0 :                              " to " + osRightTableName)
   10808           0 :                                 .c_str();
   10809           0 :             return false;
   10810             :         }
   10811           3 :         if (osMappingTableName != poExistingRelationship->GetMappingTableName())
   10812             :         {
   10813           0 :             failureReason = ("Cannot change mapping table from " +
   10814           0 :                              poExistingRelationship->GetMappingTableName() +
   10815           0 :                              " to " + osMappingTableName)
   10816           0 :                                 .c_str();
   10817           0 :             return false;
   10818             :         }
   10819             :     }
   10820             : 
   10821           6 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10822           3 :     if (osRelatedTableType.empty())
   10823             :     {
   10824           0 :         osRelatedTableType = "features";
   10825             :     }
   10826             : 
   10827           3 :     char *pszSQL = sqlite3_mprintf(
   10828             :         "DELETE FROM gpkgext_relations WHERE mapping_table_name='%q'",
   10829             :         osMappingTableName.c_str());
   10830           3 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10831           3 :     sqlite3_free(pszSQL);
   10832           3 :     if (eErr != OGRERR_NONE)
   10833             :     {
   10834             :         failureReason =
   10835           0 :             "Could not delete old relationship from gpkgext_relations";
   10836           0 :         return false;
   10837             :     }
   10838             : 
   10839           9 :     pszSQL = sqlite3_mprintf(
   10840             :         "INSERT INTO gpkgext_relations "
   10841             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10842             :         "primary_column,relation_name,mapping_table_name) "
   10843             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10844           3 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10845           3 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10846             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10847           3 :     eErr = SQLCommand(hDB, pszSQL);
   10848           3 :     sqlite3_free(pszSQL);
   10849           3 :     if (eErr != OGRERR_NONE)
   10850             :     {
   10851             :         failureReason =
   10852           0 :             "Could not insert updated relationship into gpkgext_relations";
   10853           0 :         return false;
   10854             :     }
   10855             : 
   10856           3 :     ClearCachedRelationships();
   10857           3 :     LoadRelationships();
   10858           3 :     return true;
   10859             : }
   10860             : 
   10861             : /************************************************************************/
   10862             : /*                       GetSqliteMasterContent()                       */
   10863             : /************************************************************************/
   10864             : 
   10865             : const std::vector<SQLSqliteMasterContent> &
   10866           2 : GDALGeoPackageDataset::GetSqliteMasterContent()
   10867             : {
   10868           2 :     if (m_aoSqliteMasterContent.empty())
   10869             :     {
   10870             :         auto oResultTable =
   10871           2 :             SQLQuery(hDB, "SELECT sql, type, tbl_name FROM sqlite_master");
   10872           1 :         if (oResultTable)
   10873             :         {
   10874          58 :             for (int rowCnt = 0; rowCnt < oResultTable->RowCount(); ++rowCnt)
   10875             :             {
   10876         114 :                 SQLSqliteMasterContent row;
   10877          57 :                 const char *pszSQL = oResultTable->GetValue(0, rowCnt);
   10878          57 :                 row.osSQL = pszSQL ? pszSQL : "";
   10879          57 :                 const char *pszType = oResultTable->GetValue(1, rowCnt);
   10880          57 :                 row.osType = pszType ? pszType : "";
   10881          57 :                 const char *pszTableName = oResultTable->GetValue(2, rowCnt);
   10882          57 :                 row.osTableName = pszTableName ? pszTableName : "";
   10883          57 :                 m_aoSqliteMasterContent.emplace_back(std::move(row));
   10884             :             }
   10885             :         }
   10886             :     }
   10887           2 :     return m_aoSqliteMasterContent;
   10888             : }

Generated by: LCOV version 1.14