LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/gpkg - ogrgeopackagedatasource.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 4121 4595 89.7 %
Date: 2026-04-10 15:59:41 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         573 : GetTilingScheme(const char *pszName)
      83             : {
      84         573 :     if (EQUAL(pszName, "CUSTOM"))
      85         445 :         return nullptr;
      86             : 
      87         256 :     for (const auto &tilingScheme : asTilingSchemes)
      88             :     {
      89         195 :         if (EQUAL(pszName, tilingScheme.pszName))
      90             :         {
      91          67 :             return std::make_unique<TilingSchemeDefinition>(tilingScheme);
      92             :         }
      93             :     }
      94             : 
      95          61 :     if (EQUAL(pszName, "PseudoTMS_GlobalGeodetic"))
      96           6 :         pszName = "InspireCRS84Quad";
      97             : 
      98         122 :     auto poTM = gdal::TileMatrixSet::parse(pszName);
      99          61 :     if (poTM == nullptr)
     100           1 :         return nullptr;
     101          60 :     if (!poTM->haveAllLevelsSameTopLeft())
     102             :     {
     103           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     104             :                  "Unsupported tiling scheme: not all zoom levels have same top "
     105             :                  "left corner");
     106           0 :         return nullptr;
     107             :     }
     108          60 :     if (!poTM->haveAllLevelsSameTileSize())
     109             :     {
     110           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     111             :                  "Unsupported tiling scheme: not all zoom levels have same "
     112             :                  "tile size");
     113           0 :         return nullptr;
     114             :     }
     115          60 :     if (!poTM->hasOnlyPowerOfTwoVaryingScales())
     116             :     {
     117           1 :         CPLError(CE_Failure, CPLE_NotSupported,
     118             :                  "Unsupported tiling scheme: resolution of consecutive zoom "
     119             :                  "levels is not always 2");
     120           1 :         return nullptr;
     121             :     }
     122          59 :     if (poTM->hasVariableMatrixWidth())
     123             :     {
     124           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     125             :                  "Unsupported tiling scheme: some levels have variable matrix "
     126             :                  "width");
     127           0 :         return nullptr;
     128             :     }
     129         118 :     auto poTilingScheme = std::make_unique<TilingSchemeDefinition>();
     130          59 :     poTilingScheme->pszName = pszName;
     131             : 
     132         118 :     OGRSpatialReference oSRS;
     133          59 :     if (oSRS.SetFromUserInput(poTM->crs().c_str()) != OGRERR_NONE)
     134             :     {
     135           0 :         return nullptr;
     136             :     }
     137          59 :     if (poTM->crs() == "http://www.opengis.net/def/crs/OGC/1.3/CRS84")
     138             :     {
     139           6 :         poTilingScheme->nEPSGCode = 4326;
     140             :     }
     141             :     else
     142             :     {
     143          53 :         const char *pszAuthName = oSRS.GetAuthorityName(nullptr);
     144          53 :         const char *pszAuthCode = oSRS.GetAuthorityCode(nullptr);
     145          53 :         if (pszAuthName == nullptr || !EQUAL(pszAuthName, "EPSG") ||
     146             :             pszAuthCode == nullptr)
     147             :         {
     148           0 :             CPLError(CE_Failure, CPLE_NotSupported,
     149             :                      "Unsupported tiling scheme: only EPSG CRS supported");
     150           0 :             return nullptr;
     151             :         }
     152          53 :         poTilingScheme->nEPSGCode = atoi(pszAuthCode);
     153             :     }
     154          59 :     const auto &zoomLevel0 = poTM->tileMatrixList()[0];
     155          59 :     poTilingScheme->dfMinX = zoomLevel0.mTopLeftX;
     156          59 :     poTilingScheme->dfMaxY = zoomLevel0.mTopLeftY;
     157          59 :     poTilingScheme->nTileXCountZoomLevel0 = zoomLevel0.mMatrixWidth;
     158          59 :     poTilingScheme->nTileYCountZoomLevel0 = zoomLevel0.mMatrixHeight;
     159          59 :     poTilingScheme->nTileWidth = zoomLevel0.mTileWidth;
     160          59 :     poTilingScheme->nTileHeight = zoomLevel0.mTileHeight;
     161          59 :     poTilingScheme->dfPixelXSizeZoomLevel0 = zoomLevel0.mResX;
     162          59 :     poTilingScheme->dfPixelYSizeZoomLevel0 = zoomLevel0.mResY;
     163             : 
     164         118 :     const bool bInvertAxis = oSRS.EPSGTreatsAsLatLong() != FALSE ||
     165          59 :                              oSRS.EPSGTreatsAsNorthingEasting() != FALSE;
     166          59 :     if (bInvertAxis)
     167             :     {
     168           6 :         std::swap(poTilingScheme->dfMinX, poTilingScheme->dfMaxY);
     169           6 :         std::swap(poTilingScheme->dfPixelXSizeZoomLevel0,
     170           6 :                   poTilingScheme->dfPixelYSizeZoomLevel0);
     171             :     }
     172          59 :     return poTilingScheme;
     173             : }
     174             : 
     175             : static const char *pszCREATE_GPKG_GEOMETRY_COLUMNS =
     176             :     "CREATE TABLE gpkg_geometry_columns ("
     177             :     "table_name TEXT NOT NULL,"
     178             :     "column_name TEXT NOT NULL,"
     179             :     "geometry_type_name TEXT NOT NULL,"
     180             :     "srs_id INTEGER NOT NULL,"
     181             :     "z TINYINT NOT NULL,"
     182             :     "m TINYINT NOT NULL,"
     183             :     "CONSTRAINT pk_geom_cols PRIMARY KEY (table_name, column_name),"
     184             :     "CONSTRAINT uk_gc_table_name UNIQUE (table_name),"
     185             :     "CONSTRAINT fk_gc_tn FOREIGN KEY (table_name) REFERENCES "
     186             :     "gpkg_contents(table_name),"
     187             :     "CONSTRAINT fk_gc_srs FOREIGN KEY (srs_id) REFERENCES gpkg_spatial_ref_sys "
     188             :     "(srs_id)"
     189             :     ")";
     190             : 
     191        1037 : OGRErr GDALGeoPackageDataset::SetApplicationAndUserVersionId()
     192             : {
     193        1037 :     CPLAssert(hDB != nullptr);
     194             : 
     195        1037 :     const CPLString osPragma(CPLString().Printf("PRAGMA application_id = %u;"
     196             :                                                 "PRAGMA user_version = %u",
     197             :                                                 m_nApplicationId,
     198        2074 :                                                 m_nUserVersion));
     199        2074 :     return SQLCommand(hDB, osPragma.c_str());
     200             : }
     201             : 
     202        2794 : bool GDALGeoPackageDataset::CloseDB()
     203             : {
     204        2794 :     OGRSQLiteUnregisterSQLFunctions(m_pSQLFunctionData);
     205        2794 :     m_pSQLFunctionData = nullptr;
     206        2794 :     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         934 : static OGRErr GDALGPKGImportFromEPSG(OGRSpatialReference *poSpatialRef,
     223             :                                      int nEPSGCode)
     224             : {
     225         934 :     CPLPushErrorHandler(CPLQuietErrorHandler);
     226         934 :     const OGRErr eErr = poSpatialRef->importFromEPSG(nEPSGCode);
     227         934 :     CPLPopErrorHandler();
     228         934 :     CPLErrorReset();
     229         934 :     return eErr;
     230             : }
     231             : 
     232             : OGRSpatialReferenceRefCountedPtr
     233        1364 : GDALGeoPackageDataset::GetSpatialRef(int iSrsId, bool bFallbackToEPSG,
     234             :                                      bool bEmitErrorIfNotFound)
     235             : {
     236        1364 :     const auto oIter = m_oMapSrsIdToSrs.find(iSrsId);
     237        1364 :     if (oIter != m_oMapSrsIdToSrs.end())
     238             :     {
     239         103 :         return oIter->second;
     240             :     }
     241             : 
     242        1261 :     if (iSrsId == 0 || iSrsId == -1)
     243             :     {
     244         120 :         auto poSpatialRef = OGRSpatialReferenceRefCountedPtr::makeInstance();
     245         120 :         poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     246             : 
     247             :         // See corresponding tests in GDALGeoPackageDataset::GetSrsId
     248         120 :         if (iSrsId == 0)
     249             :         {
     250          30 :             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         240 :         return m_oMapSrsIdToSrs.insert({iSrsId, std::move(poSpatialRef)})
     261         120 :             .first->second;
     262             :     }
     263             : 
     264        2282 :     CPLString oSQL;
     265        1141 :     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        1141 :                 m_bHasDefinition12_063 ? ", definition_12_063" : "",
     270        1141 :                 m_bHasEpochColumn ? ", epoch" : "", iSrsId);
     271             : 
     272        2282 :     auto oResult = SQLQuery(hDB, oSQL.c_str());
     273             : 
     274        1141 :     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        1129 :     const char *pszName = oResult->GetValue(0, 0);
     299        1129 :     if (pszName && EQUAL(pszName, "Undefined SRS"))
     300             :     {
     301         459 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     302         459 :         return nullptr;
     303             :     }
     304         670 :     const char *pszWkt = oResult->GetValue(1, 0);
     305         670 :     if (pszWkt == nullptr)
     306           0 :         return nullptr;
     307         670 :     const char *pszOrganization = oResult->GetValue(2, 0);
     308         670 :     const char *pszOrganizationCoordsysID = oResult->GetValue(3, 0);
     309             :     const char *pszWkt2 =
     310         670 :         m_bHasDefinition12_063 ? oResult->GetValue(4, 0) : nullptr;
     311         670 :     if (pszWkt2 && !EQUAL(pszWkt2, "undefined"))
     312          76 :         pszWkt = pszWkt2;
     313             :     const char *pszCoordinateEpoch =
     314         670 :         m_bHasEpochColumn ? oResult->GetValue(5, 0) : nullptr;
     315             :     const double dfCoordinateEpoch =
     316         670 :         pszCoordinateEpoch ? CPLAtof(pszCoordinateEpoch) : 0.0;
     317             : 
     318        1340 :     auto poSpatialRef = OGRSpatialReferenceRefCountedPtr::makeInstance();
     319         670 :     poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     320             :     // Try to import first from EPSG code, and then from WKT
     321         670 :     if (!(pszOrganization && pszOrganizationCoordsysID &&
     322         670 :           EQUAL(pszOrganization, "EPSG") &&
     323         646 :           (atoi(pszOrganizationCoordsysID) == iSrsId ||
     324           4 :            (dfCoordinateEpoch > 0 && strstr(pszWkt, "DYNAMIC[") == nullptr)) &&
     325         646 :           GDALGPKGImportFromEPSG(poSpatialRef.get(),
     326             :                                  atoi(pszOrganizationCoordsysID)) ==
     327        1340 :               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         670 :     poSpatialRef->StripTOWGS84IfKnownDatumAndAllowed();
     338         670 :     poSpatialRef->SetCoordinateEpoch(dfCoordinateEpoch);
     339        1340 :     return m_oMapSrsIdToSrs.insert({iSrsId, std::move(poSpatialRef)})
     340         670 :         .first->second;
     341             : }
     342             : 
     343         319 : const char *GDALGeoPackageDataset::GetSrsName(const OGRSpatialReference &oSRS)
     344             : {
     345         319 :     const char *pszName = oSRS.GetName();
     346         319 :     if (pszName)
     347         319 :         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        1014 : int GDALGeoPackageDataset::GetSrsId(const OGRSpatialReference *poSRSIn)
     520             : {
     521        1014 :     const char *pszName = poSRSIn ? poSRSIn->GetName() : nullptr;
     522        1483 :     if (!poSRSIn || poSRSIn->IsEmpty() ||
     523         469 :         (pszName && EQUAL(pszName, "Undefined SRS")))
     524             :     {
     525         547 :         OGRErr err = OGRERR_NONE;
     526         547 :         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         547 :         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         487 :         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         486 :             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         487 :         if (SQLCommand(hDB, pszSQL) == OGRERR_NONE)
     576         487 :             return UNDEFINED_CRS_SRS_ID;
     577             : #undef UNDEFINED_CRS_SRS_ID
     578             : #undef XSTRINGIFY
     579             : #undef STRINGIFY
     580           0 :         return -1;
     581             :     }
     582             : 
     583         934 :     auto poSRS = OGRSpatialReferenceRefCountedPtr::makeClone(poSRSIn);
     584         467 :     if (poSRS->IsGeographic() || poSRS->IsLocal())
     585             :     {
     586             :         // See corresponding tests in GDALGeoPackageDataset::GetSpatialRef
     587         166 :         if (pszName != nullptr && strlen(pszName) > 0)
     588             :         {
     589         166 :             if (EQUAL(pszName, "Undefined geographic SRS"))
     590           2 :                 return 0;
     591             : 
     592         164 :             if (EQUAL(pszName, "Undefined Cartesian SRS"))
     593           1 :                 return -1;
     594             :         }
     595             :     }
     596             : 
     597         464 :     const char *pszAuthorityName = poSRS->GetAuthorityName(nullptr);
     598             : 
     599         464 :     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(nullptr);
     605          28 :         if (pszAuthorityName != nullptr && EQUAL(pszAuthorityName, "EPSG"))
     606             :         {
     607           0 :             const char *pszAuthorityCode = poSRS->GetAuthorityCode(nullptr);
     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(nullptr);
     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         464 :     char *pszSQL = nullptr;
     623         464 :     int nSRSId = DEFAULT_SRID;
     624         464 :     int nAuthorityCode = 0;
     625         464 :     OGRErr err = OGRERR_NONE;
     626         464 :     bool bCanUseAuthorityCode = false;
     627         464 :     const char *const apszIsSameOptions[] = {
     628             :         "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES",
     629             :         "IGNORE_COORDINATE_EPOCH=YES", nullptr};
     630         464 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0)
     631             :     {
     632         436 :         const char *pszAuthorityCode = poSRS->GetAuthorityCode(nullptr);
     633         436 :         if (pszAuthorityCode)
     634             :         {
     635         436 :             if (CPLGetValueType(pszAuthorityCode) == CPL_VALUE_INTEGER)
     636             :             {
     637         436 :                 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         900 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     652         436 :         poSRSIn->GetCoordinateEpoch() == 0)
     653             :     {
     654             :         pszSQL =
     655         431 :             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         431 :         nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     661         431 :         sqlite3_free(pszSQL);
     662             : 
     663             :         // Got a match? Return it!
     664         431 :         if (OGRERR_NONE == err)
     665             :         {
     666         141 :             auto poRefSRS = GetSpatialRef(nSRSId);
     667             :             bool bOK =
     668         141 :                 (poRefSRS == nullptr ||
     669         142 :                  poSRS->IsSame(poRefSRS.get(), apszIsSameOptions) ||
     670           1 :                  !CPLTestBool(CPLGetConfigOption("OGR_GPKG_CHECK_SRS", "YES")));
     671         141 :             if (bOK)
     672             :             {
     673         140 :                 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         324 :     CPLCharUniquePtr pszWKT1;
     691         324 :     CPLCharUniquePtr pszWKT2_2015;
     692         324 :     CPLCharUniquePtr pszWKT2_2019;
     693         324 :     const char *const apszOptionsWkt1[] = {"FORMAT=WKT1_GDAL", nullptr};
     694         324 :     const char *const apszOptionsWkt2_2015[] = {"FORMAT=WKT2_2015", nullptr};
     695         324 :     const char *const apszOptionsWkt2_2019[] = {"FORMAT=WKT2_2019", nullptr};
     696             : 
     697         648 :     std::string osEpochTest;
     698         324 :     if (poSRSIn->GetCoordinateEpoch() > 0 && m_bHasEpochColumn)
     699             :     {
     700             :         osEpochTest =
     701           3 :             CPLSPrintf(" AND epoch = %.17g", poSRSIn->GetCoordinateEpoch());
     702             :     }
     703             : 
     704         639 :     if (!(poSRS->IsGeographic() && poSRS->GetAxesCount() == 3) &&
     705         315 :         !poSRS->IsDerivedGeographic())
     706             :     {
     707         630 :         CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
     708         315 :         char *pszTmp = nullptr;
     709         315 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt1);
     710         315 :         pszWKT1.reset(pszTmp);
     711         315 :         if (pszWKT1 && pszWKT1.get()[0] == '\0')
     712             :         {
     713           0 :             pszWKT1.reset();
     714             :         }
     715             :     }
     716             :     {
     717         648 :         CPLErrorStateBackuper oBackuper(CPLQuietErrorHandler);
     718         324 :         char *pszTmp = nullptr;
     719         324 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2015);
     720         324 :         pszWKT2_2015.reset(pszTmp);
     721         324 :         if (pszWKT2_2015 && pszWKT2_2015.get()[0] == '\0')
     722             :         {
     723           0 :             pszWKT2_2015.reset();
     724             :         }
     725             :     }
     726             :     {
     727         324 :         char *pszTmp = nullptr;
     728         324 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2019);
     729         324 :         pszWKT2_2019.reset(pszTmp);
     730         324 :         if (pszWKT2_2019 && pszWKT2_2019.get()[0] == '\0')
     731             :         {
     732           0 :             pszWKT2_2019.reset();
     733             :         }
     734             :     }
     735             : 
     736         324 :     if (!pszWKT1 && !pszWKT2_2015 && !pszWKT2_2019)
     737             :     {
     738           0 :         return DEFAULT_SRID;
     739             :     }
     740             : 
     741         324 :     if (poSRSIn->GetCoordinateEpoch() == 0 || m_bHasEpochColumn)
     742             :     {
     743             :         // Search if there is already an existing entry with this WKT
     744         321 :         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         279 :         else if (pszWKT1)
     767             :         {
     768             :             pszSQL =
     769         276 :                 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         321 :         if (pszSQL)
     778             :         {
     779         318 :             nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     780         318 :             sqlite3_free(pszSQL);
     781         318 :             if (OGRERR_NONE == err)
     782             :             {
     783           5 :                 return nSRSId;
     784             :             }
     785             :         }
     786             :     }
     787             : 
     788         612 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     789         293 :         poSRSIn->GetCoordinateEpoch() == 0)
     790             :     {
     791         289 :         bool bTryToReuseSRSId = true;
     792         289 :         if (EQUAL(pszAuthorityName, "EPSG"))
     793             :         {
     794         576 :             OGRSpatialReference oSRS_EPSG;
     795         288 :             if (GDALGPKGImportFromEPSG(&oSRS_EPSG, nAuthorityCode) ==
     796             :                 OGRERR_NONE)
     797             :             {
     798         289 :                 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         289 :         if (bTryToReuseSRSId)
     816             :         {
     817             :             // No match, but maybe we can use the nAuthorityCode as the nSRSId?
     818         288 :             pszSQL = sqlite3_mprintf(
     819             :                 "SELECT Count(*) FROM gpkg_spatial_ref_sys WHERE "
     820             :                 "srs_id = %d",
     821             :                 nAuthorityCode);
     822             : 
     823             :             // Yep, we can!
     824         288 :             if (SQLGetInteger(hDB, pszSQL, nullptr) == 0)
     825         287 :                 bCanUseAuthorityCode = true;
     826         288 :             sqlite3_free(pszSQL);
     827             :         }
     828             :     }
     829             : 
     830         319 :     bool bConvertGpkgSpatialRefSysToExtensionWkt2 = false;
     831         319 :     bool bForceEpoch = false;
     832         322 :     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         319 :     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         325 :     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         319 :     if (bCanUseAuthorityCode)
     885             :     {
     886         287 :         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         638 :     std::string osEpochColumn;
     898         319 :     std::string osEpochVal;
     899         319 :     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         319 :     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         274 :         if (pszAuthorityName != nullptr && nAuthorityCode > 0)
     943             :         {
     944         518 :             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         259 :                 GetSrsName(*poSRS), nSRSId, pszAuthorityName, nAuthorityCode,
     949         518 :                 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         319 :     CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
     964             : 
     965             :     // Free everything that was allocated.
     966         319 :     sqlite3_free(pszSQL);
     967             : 
     968         319 :     return nSRSId;
     969             : }
     970             : 
     971             : /************************************************************************/
     972             : /*                       ~GDALGeoPackageDataset()                       */
     973             : /************************************************************************/
     974             : 
     975        5566 : GDALGeoPackageDataset::~GDALGeoPackageDataset()
     976             : {
     977        2783 :     GDALGeoPackageDataset::Close();
     978        5566 : }
     979             : 
     980             : /************************************************************************/
     981             : /*                               Close()                                */
     982             : /************************************************************************/
     983             : 
     984        4703 : CPLErr GDALGeoPackageDataset::Close(GDALProgressFunc, void *)
     985             : {
     986        4703 :     CPLErr eErr = CE_None;
     987        4703 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     988             :     {
     989        1634 :         if (eAccess == GA_Update && m_poParentDS == nullptr &&
     990        4417 :             !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        5555 :         if (!IsMarkedSuppressOnClose() &&
     999        2772 :             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        4608 :         for (int i = 0; i < nBands; i++)
    1008        1825 :             delete papoBands[i];
    1009        2783 :         nBands = 0;
    1010        2783 :         CPLFree(papoBands);
    1011        2783 :         papoBands = nullptr;
    1012             : 
    1013             :         // Destroy overviews before cleaning m_hTempDB as they could still
    1014             :         // need it
    1015        2783 :         m_apoOverviewDS.clear();
    1016             : 
    1017        2783 :         if (m_poParentDS)
    1018             :         {
    1019         325 :             hDB = nullptr;
    1020             :         }
    1021             : 
    1022        2783 :         m_apoLayers.clear();
    1023             : 
    1024        2783 :         m_oMapSrsIdToSrs.clear();
    1025             : 
    1026        2783 :         if (!CloseDB())
    1027           0 :             eErr = CE_Failure;
    1028             : 
    1029        2783 :         if (OGRSQLiteBaseDataSource::Close() != CE_None)
    1030           0 :             eErr = CE_Failure;
    1031             :     }
    1032        4703 :     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        4539 : static int GetOGRTableLimit()
    1127             : {
    1128        4539 :     return atoi(CPLGetConfigOption("OGR_TABLE_LIMIT", "10000"));
    1129             : }
    1130             : 
    1131             : /************************************************************************/
    1132             : /*                   GetNameTypeMapFromSQliteMaster()                   */
    1133             : /************************************************************************/
    1134             : 
    1135             : const std::map<CPLString, CPLString> &
    1136        1414 : GDALGeoPackageDataset::GetNameTypeMapFromSQliteMaster()
    1137             : {
    1138        1414 :     if (!m_oMapNameToType.empty())
    1139         378 :         return m_oMapNameToType;
    1140             : 
    1141             :     CPLString osSQL(
    1142             :         "SELECT name, type FROM sqlite_master WHERE "
    1143             :         "type IN ('view', 'table') OR "
    1144        2072 :         "(name LIKE 'trigger_%_feature_count_%' AND type = 'trigger')");
    1145        1036 :     const int nTableLimit = GetOGRTableLimit();
    1146        1036 :     if (nTableLimit > 0)
    1147             :     {
    1148        1036 :         osSQL += " LIMIT ";
    1149        1036 :         osSQL += CPLSPrintf("%d", 1 + 3 * nTableLimit);
    1150             :     }
    1151             : 
    1152        1036 :     auto oResult = SQLQuery(hDB, osSQL);
    1153        1036 :     if (oResult)
    1154             :     {
    1155       17317 :         for (int i = 0; i < oResult->RowCount(); i++)
    1156             :         {
    1157       16281 :             const char *pszName = oResult->GetValue(0, i);
    1158       16281 :             const char *pszType = oResult->GetValue(1, i);
    1159       16281 :             m_oMapNameToType[CPLString(pszName).toupper()] = pszType;
    1160             :         }
    1161             :     }
    1162             : 
    1163        1036 :     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         985 : GDALGeoPackageDataset::GetUnknownExtensionsTableSpecific()
    1182             : {
    1183         985 :     if (m_bMapTableToExtensionsBuilt)
    1184         107 :         return m_oMapTableToExtensions;
    1185         878 :     m_bMapTableToExtensionsBuilt = true;
    1186             : 
    1187         878 :     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        1652 :         ")");
    1210         826 :     const int nTableLimit = GetOGRTableLimit();
    1211         826 :     if (nTableLimit > 0)
    1212             :     {
    1213         826 :         osSQL += " LIMIT ";
    1214         826 :         osSQL += CPLSPrintf("%d", 1 + 10 * nTableLimit);
    1215             :     }
    1216             : 
    1217         826 :     auto oResult = SQLQuery(hDB, osSQL);
    1218         826 :     if (oResult)
    1219             :     {
    1220        1529 :         for (int i = 0; i < oResult->RowCount(); i++)
    1221             :         {
    1222         703 :             const char *pszTableName = oResult->GetValue(0, i);
    1223         703 :             const char *pszExtensionName = oResult->GetValue(1, i);
    1224         703 :             const char *pszDefinition = oResult->GetValue(2, i);
    1225         703 :             const char *pszScope = oResult->GetValue(3, i);
    1226         703 :             if (pszTableName && pszExtensionName && pszDefinition && pszScope)
    1227             :             {
    1228         703 :                 GPKGExtensionDesc oDesc;
    1229         703 :                 oDesc.osExtensionName = pszExtensionName;
    1230         703 :                 oDesc.osDefinition = pszDefinition;
    1231         703 :                 oDesc.osScope = pszScope;
    1232        1406 :                 m_oMapTableToExtensions[CPLString(pszTableName).toupper()]
    1233         703 :                     .push_back(std::move(oDesc));
    1234             :             }
    1235             :         }
    1236             :     }
    1237             : 
    1238         826 :     return m_oMapTableToExtensions;
    1239             : }
    1240             : 
    1241             : /************************************************************************/
    1242             : /*                            GetContents()                             */
    1243             : /************************************************************************/
    1244             : 
    1245             : const std::map<CPLString, GPKGContentsDesc> &
    1246         966 : GDALGeoPackageDataset::GetContents()
    1247             : {
    1248         966 :     if (m_bMapTableToContentsBuilt)
    1249          90 :         return m_oMapTableToContents;
    1250         876 :     m_bMapTableToContentsBuilt = true;
    1251             : 
    1252             :     CPLString osSQL("SELECT table_name, data_type, identifier, "
    1253             :                     "description, min_x, min_y, max_x, max_y "
    1254        1752 :                     "FROM gpkg_contents");
    1255         876 :     const int nTableLimit = GetOGRTableLimit();
    1256         876 :     if (nTableLimit > 0)
    1257             :     {
    1258         876 :         osSQL += " LIMIT ";
    1259         876 :         osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1260             :     }
    1261             : 
    1262         876 :     auto oResult = SQLQuery(hDB, osSQL);
    1263         876 :     if (oResult)
    1264             :     {
    1265        1899 :         for (int i = 0; i < oResult->RowCount(); i++)
    1266             :         {
    1267        1023 :             const char *pszTableName = oResult->GetValue(0, i);
    1268        1023 :             if (pszTableName == nullptr)
    1269           0 :                 continue;
    1270        1023 :             const char *pszDataType = oResult->GetValue(1, i);
    1271        1023 :             const char *pszIdentifier = oResult->GetValue(2, i);
    1272        1023 :             const char *pszDescription = oResult->GetValue(3, i);
    1273        1023 :             const char *pszMinX = oResult->GetValue(4, i);
    1274        1023 :             const char *pszMinY = oResult->GetValue(5, i);
    1275        1023 :             const char *pszMaxX = oResult->GetValue(6, i);
    1276        1023 :             const char *pszMaxY = oResult->GetValue(7, i);
    1277        1023 :             GPKGContentsDesc oDesc;
    1278        1023 :             if (pszDataType)
    1279        1023 :                 oDesc.osDataType = pszDataType;
    1280        1023 :             if (pszIdentifier)
    1281        1023 :                 oDesc.osIdentifier = pszIdentifier;
    1282        1023 :             if (pszDescription)
    1283        1022 :                 oDesc.osDescription = pszDescription;
    1284        1023 :             if (pszMinX)
    1285         682 :                 oDesc.osMinX = pszMinX;
    1286        1023 :             if (pszMinY)
    1287         682 :                 oDesc.osMinY = pszMinY;
    1288        1023 :             if (pszMaxX)
    1289         682 :                 oDesc.osMaxX = pszMaxX;
    1290        1023 :             if (pszMaxY)
    1291         682 :                 oDesc.osMaxY = pszMaxY;
    1292        2046 :             m_oMapTableToContents[CPLString(pszTableName).toupper()] =
    1293        2046 :                 std::move(oDesc);
    1294             :         }
    1295             :     }
    1296             : 
    1297         876 :     return m_oMapTableToContents;
    1298             : }
    1299             : 
    1300             : /************************************************************************/
    1301             : /*                                Open()                                */
    1302             : /************************************************************************/
    1303             : 
    1304        1393 : int GDALGeoPackageDataset::Open(GDALOpenInfo *poOpenInfo,
    1305             :                                 const std::string &osFilenameInZip)
    1306             : {
    1307        1393 :     m_osFilenameInZip = osFilenameInZip;
    1308        1393 :     CPLAssert(m_apoLayers.empty());
    1309        1393 :     CPLAssert(hDB == nullptr);
    1310             : 
    1311        1393 :     SetDescription(poOpenInfo->pszFilename);
    1312        2786 :     CPLString osFilename(poOpenInfo->pszFilename);
    1313        2786 :     CPLString osSubdatasetTableName;
    1314             :     GByte abyHeaderLetMeHerePlease[100];
    1315        1393 :     const GByte *pabyHeader = poOpenInfo->pabyHeader;
    1316        1393 :     if (STARTS_WITH_CI(poOpenInfo->pszFilename, "GPKG:"))
    1317             :     {
    1318         260 :         char **papszTokens = CSLTokenizeString2(poOpenInfo->pszFilename, ":",
    1319             :                                                 CSLT_HONOURSTRINGS);
    1320         260 :         int nCount = CSLCount(papszTokens);
    1321         260 :         if (nCount < 2)
    1322             :         {
    1323           0 :             CSLDestroy(papszTokens);
    1324           0 :             return FALSE;
    1325             :         }
    1326             : 
    1327         260 :         if (nCount <= 3)
    1328             :         {
    1329         258 :             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         260 :         if (nCount >= 3)
    1350          14 :             osSubdatasetTableName = papszTokens[nCount - 1];
    1351             : 
    1352         260 :         CSLDestroy(papszTokens);
    1353         260 :         VSILFILE *fp = VSIFOpenL(osFilename, "rb");
    1354         260 :         if (fp != nullptr)
    1355             :         {
    1356         260 :             VSIFReadL(abyHeaderLetMeHerePlease, 1, 100, fp);
    1357         260 :             VSIFCloseL(fp);
    1358             :         }
    1359         260 :         pabyHeader = abyHeaderLetMeHerePlease;
    1360             :     }
    1361        1133 :     else if (poOpenInfo->pabyHeader &&
    1362        1133 :              STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1363             :                          "SQLite format 3"))
    1364             :     {
    1365        1126 :         m_bCallUndeclareFileNotToOpen = true;
    1366        1126 :         GDALOpenInfoDeclareFileNotToOpen(osFilename, poOpenInfo->pabyHeader,
    1367             :                                          poOpenInfo->nHeaderBytes);
    1368             :     }
    1369             : 
    1370        1393 :     eAccess = poOpenInfo->eAccess;
    1371        1393 :     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        1391 :         m_pszFilename = CPLStrdup(osFilename);
    1379             :     }
    1380             : 
    1381        1393 :     if (poOpenInfo->papszOpenOptions)
    1382             :     {
    1383         100 :         CSLDestroy(papszOpenOptions);
    1384         100 :         papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
    1385             :     }
    1386             : 
    1387             : #ifdef ENABLE_SQL_GPKG_FORMAT
    1388        1393 :     if (poOpenInfo->pabyHeader &&
    1389        1133 :         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        1388 :     else if (pabyHeader != nullptr)
    1424             : #endif
    1425             :     {
    1426        1388 :         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        1010 :             VSIFCloseL(poOpenInfo->fpL);
    1431        1010 :             poOpenInfo->fpL = nullptr;
    1432             :         }
    1433             : 
    1434             :         /* See if we can open the SQLite database */
    1435        1388 :         if (!OpenOrCreateDB(GetUpdate() ? SQLITE_OPEN_READWRITE
    1436             :                                         : SQLITE_OPEN_READONLY))
    1437           3 :             return FALSE;
    1438             : 
    1439        1385 :         memcpy(&m_nApplicationId, pabyHeader + knApplicationIdPos, 4);
    1440        1385 :         m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    1441        1385 :         memcpy(&m_nUserVersion, pabyHeader + knUserVersionPos, 4);
    1442        1385 :         m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    1443        1385 :         if (m_nApplicationId == GP10_APPLICATION_ID)
    1444             :         {
    1445           9 :             CPLDebug("GPKG", "GeoPackage v1.0");
    1446             :         }
    1447        1376 :         else if (m_nApplicationId == GP11_APPLICATION_ID)
    1448             :         {
    1449           2 :             CPLDebug("GPKG", "GeoPackage v1.1");
    1450             :         }
    1451        1374 :         else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    1452        1370 :                  m_nUserVersion >= GPKG_1_2_VERSION)
    1453             :         {
    1454        1368 :             CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    1455        1368 :                      (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        1390 :     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        1390 :     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        1390 :     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        1390 :                       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        1390 :     DetectSpatialRefSysColumns();
    1500             : 
    1501             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    1502        1390 :     if (SQLGetInteger(hDB,
    1503             :                       "SELECT 1 FROM sqlite_master WHERE "
    1504             :                       "name = 'gpkg_ogr_contents' AND type = 'table'",
    1505        1390 :                       nullptr) == 1)
    1506             :     {
    1507        1379 :         m_bHasGPKGOGRContents = true;
    1508             :     }
    1509             : #endif
    1510             : 
    1511        1390 :     CheckUnknownExtensions();
    1512             : 
    1513        1390 :     int bRet = FALSE;
    1514        1390 :     bool bHasGPKGExtRelations = false;
    1515        1390 :     if (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR)
    1516             :     {
    1517        1201 :         m_bHasGPKGGeometryColumns =
    1518        1201 :             SQLGetInteger(hDB,
    1519             :                           "SELECT 1 FROM sqlite_master WHERE "
    1520             :                           "name = 'gpkg_geometry_columns' AND "
    1521             :                           "type IN ('table', 'view')",
    1522        1201 :                           nullptr) == 1;
    1523        1201 :         bHasGPKGExtRelations = HasGpkgextRelationsTable();
    1524             :     }
    1525        1390 :     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        1199 :             "  WHERE data_type IN ('aspatial', 'attributes') ";
    1551             : 
    1552        2398 :         const char *pszListAllTables = CSLFetchNameValueDef(
    1553        1199 :             poOpenInfo->papszOpenOptions, "LIST_ALL_TABLES", "AUTO");
    1554        1199 :         bool bHasASpatialOrAttributes = HasGDALAspatialExtension();
    1555        1199 :         if (!bHasASpatialOrAttributes)
    1556             :         {
    1557             :             auto oResultTable =
    1558             :                 SQLQuery(hDB, "SELECT * FROM gpkg_contents WHERE "
    1559        1198 :                               "data_type = 'attributes' LIMIT 1");
    1560        1198 :             bHasASpatialOrAttributes =
    1561        1198 :                 (oResultTable && oResultTable->RowCount() == 1);
    1562             :         }
    1563        1199 :         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        1199 :         if (EQUAL(pszListAllTables, "YES") ||
    1578        1198 :             (!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        1129 :                 "gpkg_contents)";
    1595        1129 :             if (bHasGPKGExtRelations)
    1596             :             {
    1597             :                 osSQL += " AND lower(name) NOT IN (SELECT "
    1598             :                          "lower(mapping_table_name) FROM "
    1599          15 :                          "gpkgext_relations)";
    1600             :             }
    1601             :         }
    1602        1199 :         const int nTableLimit = GetOGRTableLimit();
    1603        1199 :         if (nTableLimit > 0)
    1604             :         {
    1605        1199 :             osSQL += " LIMIT ";
    1606        1199 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1607             :         }
    1608             : 
    1609        1199 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1610        1199 :         if (!oResult)
    1611             :         {
    1612           0 :             return FALSE;
    1613             :         }
    1614             : 
    1615        1199 :         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        1199 :         if (oResult->RowCount() > 0)
    1626             :         {
    1627        1082 :             bRet = TRUE;
    1628             : 
    1629        1082 :             m_apoLayers.reserve(oResult->RowCount());
    1630             : 
    1631        2164 :             std::map<std::string, int> oMapTableRefCount;
    1632        4392 :             for (int i = 0; i < oResult->RowCount(); i++)
    1633             :             {
    1634        3310 :                 const char *pszTableName = oResult->GetValue(0, i);
    1635        3310 :                 if (pszTableName == nullptr)
    1636           0 :                     continue;
    1637        3310 :                 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        2164 :             std::set<std::string> oExistingLayers;
    1649        4392 :             for (int i = 0; i < oResult->RowCount(); i++)
    1650             :             {
    1651        3310 :                 const char *pszTableName = oResult->GetValue(0, i);
    1652        3310 :                 if (pszTableName == nullptr)
    1653           2 :                     continue;
    1654             :                 const bool bTableHasSeveralGeomColumns =
    1655        3310 :                     oMapTableRefCount[pszTableName] > 1;
    1656        3310 :                 bool bIsSpatial = CPL_TO_BOOL(oResult->GetValueAsInteger(2, i));
    1657        3310 :                 const char *pszGeomColName = oResult->GetValue(3, i);
    1658        3310 :                 const char *pszGeomType = oResult->GetValue(4, i);
    1659        3310 :                 const char *pszZ = oResult->GetValue(5, i);
    1660        3310 :                 const char *pszM = oResult->GetValue(6, i);
    1661             :                 bool bIsInGpkgContents =
    1662        3310 :                     CPL_TO_BOOL(oResult->GetValueAsInteger(11, i));
    1663        3310 :                 if (!bIsInGpkgContents)
    1664          46 :                     m_bNonSpatialTablesNonRegisteredInGpkgContentsFound = true;
    1665        3310 :                 const char *pszObjectType = oResult->GetValue(12, i);
    1666        3310 :                 if (pszObjectType == nullptr ||
    1667        3309 :                     !(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        6876 :                     pszGeomColName ? std::string(pszTableName) + " (" +
    1684             :                                          pszGeomColName + ')'
    1685        6618 :                                    : std::string(pszTableName);
    1686        3309 :                 if (cpl::contains(oExistingLayers, osLayerNameWithGeomColName))
    1687           1 :                     continue;
    1688        3308 :                 oExistingLayers.insert(osLayerNameWithGeomColName);
    1689             :                 const std::string osLayerName =
    1690             :                     bTableHasSeveralGeomColumns
    1691           3 :                         ? std::move(osLayerNameWithGeomColName)
    1692        6619 :                         : std::string(pszTableName);
    1693             :                 auto poLayer = std::make_unique<OGRGeoPackageTableLayer>(
    1694        6616 :                     this, osLayerName.c_str());
    1695        3308 :                 bool bHasZ = pszZ && atoi(pszZ) > 0;
    1696        3308 :                 bool bHasM = pszM && atoi(pszM) > 0;
    1697        3308 :                 if (pszGeomType && EQUAL(pszGeomType, "GEOMETRY"))
    1698             :                 {
    1699         659 :                     if (pszZ && atoi(pszZ) == 2)
    1700          14 :                         bHasZ = false;
    1701         659 :                     if (pszM && atoi(pszM) == 2)
    1702           6 :                         bHasM = false;
    1703             :                 }
    1704        3308 :                 poLayer->SetOpeningParameters(
    1705             :                     pszTableName, pszObjectType, bIsInGpkgContents, bIsSpatial,
    1706             :                     pszGeomColName, pszGeomType, bHasZ, bHasM);
    1707        3308 :                 m_apoLayers.push_back(std::move(poLayer));
    1708             :             }
    1709             :         }
    1710             :     }
    1711             : 
    1712        1390 :     bool bHasTileMatrixSet = false;
    1713        1390 :     if (poOpenInfo->nOpenFlags & GDAL_OF_RASTER)
    1714             :     {
    1715         605 :         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        1390 :     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         602 :             "data_type IN ('tiles', '2d-gridded-coverage')";
    1730         602 :         if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE"))
    1731             :             osSubdatasetTableName =
    1732           2 :                 CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE");
    1733         602 :         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         602 :         const int nTableLimit = GetOGRTableLimit();
    1742         602 :         if (nTableLimit > 0)
    1743             :         {
    1744         602 :             osSQL += " LIMIT ";
    1745         602 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1746             :         }
    1747             : 
    1748         602 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1749         602 :         if (!oResult)
    1750             :         {
    1751           0 :             return FALSE;
    1752             :         }
    1753             : 
    1754         602 :         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         601 :         else if (oResult->RowCount() == 1)
    1761             :         {
    1762         281 :             const char *pszTableName = oResult->GetValue(0, 0);
    1763         281 :             const char *pszIdentifier = oResult->GetValue(1, 0);
    1764         281 :             const char *pszDescription = oResult->GetValue(2, 0);
    1765         281 :             const char *pszSRSId = oResult->GetValue(3, 0);
    1766         281 :             const char *pszMinX = oResult->GetValue(4, 0);
    1767         281 :             const char *pszMinY = oResult->GetValue(5, 0);
    1768         281 :             const char *pszMaxX = oResult->GetValue(6, 0);
    1769         281 :             const char *pszMaxY = oResult->GetValue(7, 0);
    1770         281 :             const char *pszTMSMinX = oResult->GetValue(8, 0);
    1771         281 :             const char *pszTMSMinY = oResult->GetValue(9, 0);
    1772         281 :             const char *pszTMSMaxX = oResult->GetValue(10, 0);
    1773         281 :             const char *pszTMSMaxY = oResult->GetValue(11, 0);
    1774         281 :             const char *pszDataType = oResult->GetValue(12, 0);
    1775         281 :             if (pszTableName && pszTMSMinX && pszTMSMinY && pszTMSMaxX &&
    1776             :                 pszTMSMaxY)
    1777             :             {
    1778         562 :                 bRet = OpenRaster(
    1779             :                     pszTableName, pszIdentifier, pszDescription,
    1780         281 :                     pszSRSId ? atoi(pszSRSId) : 0, CPLAtof(pszTMSMinX),
    1781             :                     CPLAtof(pszTMSMinY), CPLAtof(pszTMSMaxX),
    1782             :                     CPLAtof(pszTMSMaxY), pszMinX, pszMinY, pszMaxX, pszMaxY,
    1783         281 :                     EQUAL(pszDataType, "tiles"), poOpenInfo->papszOpenOptions);
    1784             :             }
    1785             :         }
    1786         320 :         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        1390 :     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        1390 :     if (eAccess == GA_Update)
    1836             :     {
    1837         285 :         FixupWrongRTreeTrigger();
    1838         285 :         FixupWrongMedataReferenceColumnNameUpdate();
    1839             :     }
    1840             : 
    1841        1390 :     SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    1842             : 
    1843        1390 :     return bRet;
    1844             : }
    1845             : 
    1846             : /************************************************************************/
    1847             : /*                     DetectSpatialRefSysColumns()                     */
    1848             : /************************************************************************/
    1849             : 
    1850        1400 : void GDALGeoPackageDataset::DetectSpatialRefSysColumns()
    1851             : {
    1852             :     // Detect definition_12_063 column
    1853             :     {
    1854        1400 :         sqlite3_stmt *hSQLStmt = nullptr;
    1855        1400 :         int rc = sqlite3_prepare_v2(
    1856             :             hDB, "SELECT definition_12_063 FROM gpkg_spatial_ref_sys ", -1,
    1857             :             &hSQLStmt, nullptr);
    1858        1400 :         if (rc == SQLITE_OK)
    1859             :         {
    1860          85 :             m_bHasDefinition12_063 = true;
    1861          85 :             sqlite3_finalize(hSQLStmt);
    1862             :         }
    1863             :     }
    1864             : 
    1865             :     // Detect epoch column
    1866        1400 :     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        1400 : }
    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         365 : 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         365 :     m_osRasterTable = pszTableName;
    2274         365 :     m_dfTMSMinX = dfMinX;
    2275         365 :     m_dfTMSMaxY = dfMaxY;
    2276             : 
    2277             :     // Despite prior checking, the type might be Binary and
    2278             :     // SQLResultGetValue() not working properly on it
    2279         365 :     int nZoomLevel = atoi(oResult.GetValue(0, nIdxInResult));
    2280         365 :     if (nZoomLevel < 0 || nZoomLevel > 65536)
    2281             :     {
    2282           0 :         return false;
    2283             :     }
    2284         365 :     double dfPixelXSize = CPLAtof(oResult.GetValue(1, nIdxInResult));
    2285         365 :     double dfPixelYSize = CPLAtof(oResult.GetValue(2, nIdxInResult));
    2286         365 :     if (dfPixelXSize <= 0 || dfPixelYSize <= 0)
    2287             :     {
    2288           0 :         return false;
    2289             :     }
    2290         365 :     int nTileWidth = atoi(oResult.GetValue(3, nIdxInResult));
    2291         365 :     int nTileHeight = atoi(oResult.GetValue(4, nIdxInResult));
    2292         365 :     if (nTileWidth <= 0 || nTileWidth > 65536 || nTileHeight <= 0 ||
    2293             :         nTileHeight > 65536)
    2294             :     {
    2295           0 :         return false;
    2296             :     }
    2297             :     int nTileMatrixWidth = static_cast<int>(
    2298         730 :         std::min(static_cast<GIntBig>(INT_MAX),
    2299         365 :                  CPLAtoGIntBig(oResult.GetValue(5, nIdxInResult))));
    2300             :     int nTileMatrixHeight = static_cast<int>(
    2301         730 :         std::min(static_cast<GIntBig>(INT_MAX),
    2302         365 :                  CPLAtoGIntBig(oResult.GetValue(6, nIdxInResult))));
    2303         365 :     if (nTileMatrixWidth <= 0 || nTileMatrixHeight <= 0)
    2304             :     {
    2305           0 :         return false;
    2306             :     }
    2307             : 
    2308             :     /* Use content bounds in priority over tile_matrix_set bounds */
    2309         365 :     double dfGDALMinX = dfMinX;
    2310         365 :     double dfGDALMinY = dfMinY;
    2311         365 :     double dfGDALMaxX = dfMaxX;
    2312         365 :     double dfGDALMaxY = dfMaxY;
    2313             :     pszContentsMinX =
    2314         365 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINX", pszContentsMinX);
    2315             :     pszContentsMinY =
    2316         365 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINY", pszContentsMinY);
    2317             :     pszContentsMaxX =
    2318         365 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXX", pszContentsMaxX);
    2319             :     pszContentsMaxY =
    2320         365 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXY", pszContentsMaxY);
    2321         365 :     if (pszContentsMinX != nullptr && pszContentsMinY != nullptr &&
    2322         365 :         pszContentsMaxX != nullptr && pszContentsMaxY != nullptr)
    2323             :     {
    2324         729 :         if (CPLAtof(pszContentsMinX) < CPLAtof(pszContentsMaxX) &&
    2325         364 :             CPLAtof(pszContentsMinY) < CPLAtof(pszContentsMaxY))
    2326             :         {
    2327         364 :             dfGDALMinX = CPLAtof(pszContentsMinX);
    2328         364 :             dfGDALMinY = CPLAtof(pszContentsMinY);
    2329         364 :             dfGDALMaxX = CPLAtof(pszContentsMaxX);
    2330         364 :             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         365 :     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         365 :     int nBandCount = 0;
    2349             :     const char *pszBAND_COUNT =
    2350         365 :         CSLFetchNameValue(papszOpenOptionsIn, "BAND_COUNT");
    2351         365 :     if (poParentDS)
    2352             :     {
    2353          86 :         nBandCount = poParentDS->GetRasterCount();
    2354             :     }
    2355         279 :     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         214 :         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         145 :             GetMetadata("IMAGE_STRUCTURE");
    2376         145 :             nBandCount = m_nBandCountFromMetadata;
    2377         145 :             if (nBandCount == 1)
    2378          46 :                 m_eTF = GPKG_TF_PNG;
    2379             :         }
    2380         214 :         if (nBandCount == 1 && !m_osTFFromMetadata.empty())
    2381             :         {
    2382           2 :             m_eTF = GDALGPKGMBTilesGetTileFormat(m_osTFFromMetadata.c_str());
    2383             :         }
    2384         214 :         if (nBandCount <= 0 || nBandCount > 4)
    2385          85 :             nBandCount = 4;
    2386             :     }
    2387             : 
    2388         365 :     return InitRaster(poParentDS, pszTableName, nZoomLevel, nBandCount, dfMinX,
    2389             :                       dfMaxY, dfPixelXSize, dfPixelYSize, nTileWidth,
    2390             :                       nTileHeight, nTileMatrixWidth, nTileMatrixHeight,
    2391         365 :                       dfGDALMinX, dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    2392             : }
    2393             : 
    2394             : /************************************************************************/
    2395             : /*                     ComputeTileAndPixelShifts()                      */
    2396             : /************************************************************************/
    2397             : 
    2398         792 : bool GDALGeoPackageDataset::ComputeTileAndPixelShifts()
    2399             : {
    2400             :     int nTileWidth, nTileHeight;
    2401         792 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2402             : 
    2403             :     // Compute shift between GDAL origin and TileMatrixSet origin
    2404         792 :     const double dfShiftXPixels = (m_gt[0] - m_dfTMSMinX) / m_gt[1];
    2405         792 :     if (!(dfShiftXPixels / nTileWidth >= INT_MIN &&
    2406         789 :           dfShiftXPixels / nTileWidth < INT_MAX))
    2407             :     {
    2408           3 :         return false;
    2409             :     }
    2410         789 :     const int64_t nShiftXPixels =
    2411         789 :         static_cast<int64_t>(floor(0.5 + dfShiftXPixels));
    2412         789 :     m_nShiftXTiles = static_cast<int>(nShiftXPixels / nTileWidth);
    2413         789 :     if (nShiftXPixels < 0 && (nShiftXPixels % nTileWidth) != 0)
    2414          11 :         m_nShiftXTiles--;
    2415         789 :     m_nShiftXPixelsMod =
    2416         789 :         (static_cast<int>(nShiftXPixels % nTileWidth) + nTileWidth) %
    2417             :         nTileWidth;
    2418             : 
    2419         789 :     const double dfShiftYPixels = (m_gt[3] - m_dfTMSMaxY) / m_gt[5];
    2420         789 :     if (!(dfShiftYPixels / nTileHeight >= INT_MIN &&
    2421         789 :           dfShiftYPixels / nTileHeight < INT_MAX))
    2422             :     {
    2423           1 :         return false;
    2424             :     }
    2425         788 :     const int64_t nShiftYPixels =
    2426         788 :         static_cast<int64_t>(floor(0.5 + dfShiftYPixels));
    2427         788 :     m_nShiftYTiles = static_cast<int>(nShiftYPixels / nTileHeight);
    2428         788 :     if (nShiftYPixels < 0 && (nShiftYPixels % nTileHeight) != 0)
    2429          11 :         m_nShiftYTiles--;
    2430         788 :     m_nShiftYPixelsMod =
    2431         788 :         (static_cast<int>(nShiftYPixels % nTileHeight) + nTileHeight) %
    2432             :         nTileHeight;
    2433         788 :     return true;
    2434             : }
    2435             : 
    2436             : /************************************************************************/
    2437             : /*                          AllocCachedTiles()                          */
    2438             : /************************************************************************/
    2439             : 
    2440         788 : bool GDALGeoPackageDataset::AllocCachedTiles()
    2441             : {
    2442             :     int nTileWidth, nTileHeight;
    2443         788 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2444             : 
    2445             :     // We currently need 4 caches because of
    2446             :     // GDALGPKGMBTilesLikePseudoDataset::ReadTile(int nRow, int nCol)
    2447         788 :     const int nCacheCount = 4;
    2448             :     /*
    2449             :             (m_nShiftXPixelsMod != 0 || m_nShiftYPixelsMod != 0) ? 4 :
    2450             :             (GetUpdate() && m_eDT == GDT_UInt8) ? 2 : 1;
    2451             :     */
    2452         788 :     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         788 :     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         788 :     return true;
    2464             : }
    2465             : 
    2466             : /************************************************************************/
    2467             : /*                             InitRaster()                             */
    2468             : /************************************************************************/
    2469             : 
    2470         604 : 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         604 :     m_osRasterTable = pszTableName;
    2478         604 :     m_dfTMSMinX = dfTMSMinX;
    2479         604 :     m_dfTMSMaxY = dfTMSMaxY;
    2480         604 :     m_nZoomLevel = nZoomLevel;
    2481         604 :     m_nTileMatrixWidth = nTileMatrixWidth;
    2482         604 :     m_nTileMatrixHeight = nTileMatrixHeight;
    2483             : 
    2484         604 :     m_bGeoTransformValid = true;
    2485         604 :     m_gt[0] = dfGDALMinX;
    2486         604 :     m_gt[1] = dfPixelXSize;
    2487         604 :     m_gt[3] = dfGDALMaxY;
    2488         604 :     m_gt[5] = -dfPixelYSize;
    2489         604 :     double dfRasterXSize = 0.5 + (dfGDALMaxX - dfGDALMinX) / dfPixelXSize;
    2490         604 :     double dfRasterYSize = 0.5 + (dfGDALMaxY - dfGDALMinY) / dfPixelYSize;
    2491         604 :     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         604 :     nRasterXSize = std::max(1, static_cast<int>(dfRasterXSize));
    2498         604 :     nRasterYSize = std::max(1, static_cast<int>(dfRasterYSize));
    2499             : 
    2500         604 :     if (poParentDS)
    2501             :     {
    2502         325 :         m_poParentDS = poParentDS;
    2503         325 :         eAccess = poParentDS->eAccess;
    2504         325 :         hDB = poParentDS->hDB;
    2505         325 :         m_eTF = poParentDS->m_eTF;
    2506         325 :         m_eDT = poParentDS->m_eDT;
    2507         325 :         m_nDTSize = poParentDS->m_nDTSize;
    2508         325 :         m_dfScale = poParentDS->m_dfScale;
    2509         325 :         m_dfOffset = poParentDS->m_dfOffset;
    2510         325 :         m_dfPrecision = poParentDS->m_dfPrecision;
    2511         325 :         m_usGPKGNull = poParentDS->m_usGPKGNull;
    2512         325 :         m_nQuality = poParentDS->m_nQuality;
    2513         325 :         m_nZLevel = poParentDS->m_nZLevel;
    2514         325 :         m_bDither = poParentDS->m_bDither;
    2515             :         /*m_nSRID = poParentDS->m_nSRID;*/
    2516         325 :         m_osWHERE = poParentDS->m_osWHERE;
    2517         325 :         SetDescription(CPLSPrintf("%s - zoom_level=%d",
    2518         325 :                                   poParentDS->GetDescription(), m_nZoomLevel));
    2519             :     }
    2520             : 
    2521        2105 :     for (int i = 1; i <= nBandCount; i++)
    2522             :     {
    2523             :         auto poNewBand = std::make_unique<GDALGeoPackageRasterBand>(
    2524        1501 :             this, nTileWidth, nTileHeight);
    2525        1501 :         if (poParentDS)
    2526             :         {
    2527         761 :             int bHasNoData = FALSE;
    2528             :             double dfNoDataValue =
    2529         761 :                 poParentDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    2530         761 :             if (bHasNoData)
    2531          24 :                 poNewBand->SetNoDataValueInternal(dfNoDataValue);
    2532             :         }
    2533             : 
    2534        1501 :         if (nBandCount == 1 && m_poCTFromMetadata)
    2535             :         {
    2536           3 :             poNewBand->AssignColorTable(m_poCTFromMetadata.get());
    2537             :         }
    2538        1501 :         if (!m_osNodataValueFromMetadata.empty())
    2539             :         {
    2540           8 :             poNewBand->SetNoDataValueInternal(
    2541             :                 CPLAtof(m_osNodataValueFromMetadata.c_str()));
    2542             :         }
    2543             : 
    2544        1501 :         SetBand(i, std::move(poNewBand));
    2545             :     }
    2546             : 
    2547         604 :     if (!ComputeTileAndPixelShifts())
    2548             :     {
    2549           3 :         CPLError(CE_Failure, CPLE_AppDefined,
    2550             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    2551           3 :         return false;
    2552             :     }
    2553             : 
    2554         601 :     GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    2555         601 :     GDALPamDataset::SetMetadataItem("ZOOM_LEVEL",
    2556             :                                     CPLSPrintf("%d", m_nZoomLevel));
    2557             : 
    2558         601 :     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         281 : 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         281 :     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         562 :     CPLString osDataNull = CPLGetConfigOption("GPKG_NODATA", "");
    2625         562 :     CPLString osUom;
    2626         562 :     CPLString osFieldName;
    2627         562 :     CPLString osGridCellEncoding;
    2628         281 :     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         281 :     m_bRecordInsertedInGPKGContent = true;
    2753         281 :     m_nSRID = nSRSId;
    2754             : 
    2755         561 :     if (auto poSRS = GetSpatialRef(nSRSId))
    2756             :     {
    2757         280 :         m_oSRS = *(poSRS.get());
    2758             :     }
    2759             : 
    2760             :     /* Various sanity checks added in the SELECT */
    2761         281 :     char *pszQuotedTableName = sqlite3_mprintf("'%q'", pszTableName);
    2762         562 :     CPLString osQuotedTableName(pszQuotedTableName);
    2763         281 :     sqlite3_free(pszQuotedTableName);
    2764         281 :     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         562 :     CPLString osSQL(pszSQL);
    2778             :     const char *pszZoomLevel =
    2779         281 :         CSLFetchNameValue(papszOpenOptionsIn, "ZOOM_LEVEL");
    2780         281 :     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         276 :     else if (!GetUpdate())
    2795             :     {
    2796             :         osSQL += CPLSPrintf(" AND EXISTS(SELECT 1 FROM %s WHERE zoom_level = "
    2797             :                             "tm.zoom_level LIMIT 1)",
    2798         222 :                             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         281 :     osSQL += " ORDER BY zoom_level DESC";
    2807             :     // To avoid denial of service.
    2808         281 :     osSQL += " LIMIT 100";
    2809             : 
    2810         562 :     auto oResult = SQLQuery(hDB, osSQL.c_str());
    2811         281 :     if (!oResult || oResult->RowCount() == 0)
    2812             :     {
    2813         114 :         if (oResult && oResult->RowCount() == 0 && pszContentsMinX != nullptr &&
    2814         114 :             pszContentsMinY != nullptr && pszContentsMaxX != nullptr &&
    2815             :             pszContentsMaxY != nullptr)
    2816             :         {
    2817          56 :             osSQL = pszSQL;
    2818          56 :             osSQL += " ORDER BY zoom_level DESC";
    2819          56 :             if (!GetUpdate())
    2820          30 :                 osSQL += " LIMIT 1";
    2821          56 :             oResult = SQLQuery(hDB, osSQL.c_str());
    2822             :         }
    2823          57 :         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         280 :     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         560 :     CPLString osContentsMinX, osContentsMinY, osContentsMaxX, osContentsMaxY;
    2842             : 
    2843         280 :     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         279 :     if (!InitRaster(nullptr, pszTableName, dfMinX, dfMinY, dfMaxX, dfMaxY,
    2884             :                     pszContentsMinX, pszContentsMinY, pszContentsMaxX,
    2885         279 :                     pszContentsMaxY, papszOpenOptionsIn, *oResult, 0))
    2886             :     {
    2887           3 :         return false;
    2888             :     }
    2889             : 
    2890         276 :     auto poBand = cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(1));
    2891         276 :     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         276 :     if (!osUom.empty())
    2924             :     {
    2925           2 :         poBand->SetUnitTypeInternal(osUom);
    2926             :     }
    2927         276 :     if (!osFieldName.empty())
    2928             :     {
    2929          64 :         GetRasterBand(1)->GDALRasterBand::SetDescription(osFieldName);
    2930             :     }
    2931         276 :     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         276 :     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         276 :     const char *pszTF = CSLFetchNameValue(papszOpenOptionsIn, "TILE_FORMAT");
    2957         276 :     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         276 :     ParseCompressionOptions(papszOpenOptionsIn);
    2983             : 
    2984         276 :     m_osWHERE = CSLFetchNameValueDef(papszOpenOptionsIn, "WHERE", "");
    2985             : 
    2986             :     // Set metadata
    2987         276 :     if (pszIdentifier && pszIdentifier[0])
    2988         276 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", pszIdentifier);
    2989         276 :     if (pszDescription && pszDescription[0])
    2990          21 :         GDALPamDataset::SetMetadataItem("DESCRIPTION", pszDescription);
    2991             : 
    2992             :     // Add overviews
    2993         361 :     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         276 :     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         153 : CPLErr GDALGeoPackageDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    3049             : {
    3050         153 :     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         152 :     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         151 :     const int nSRID = GetSrsId(poSRS);
    3064         302 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3065         151 :     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         150 :     m_nSRID = nSRID;
    3074         150 :     m_oSRS.Clear();
    3075         150 :     if (poSRS)
    3076         149 :         m_oSRS = *poSRS;
    3077             : 
    3078         150 :     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         150 :     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         193 : CPLErr GDALGeoPackageDataset::SetGeoTransform(const GDALGeoTransform &gt)
    3118             : {
    3119         193 :     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         191 :     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         190 :     if (m_bGeoTransformValid)
    3132             :     {
    3133           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3134             :                  "Cannot modify geotransform once set");
    3135           1 :         return CE_Failure;
    3136             :     }
    3137         189 :     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         189 :     if (m_nZoomLevel < 0)
    3145             :     {
    3146         188 :         const auto poTS = GetTilingScheme(m_osTilingScheme);
    3147         188 :         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         188 :     m_gt = gt;
    3180         188 :     m_bGeoTransformValid = true;
    3181             : 
    3182         188 :     return FinalizeRasterRegistration();
    3183             : }
    3184             : 
    3185             : /************************************************************************/
    3186             : /*                     FinalizeRasterRegistration()                     */
    3187             : /************************************************************************/
    3188             : 
    3189         188 : CPLErr GDALGeoPackageDataset::FinalizeRasterRegistration()
    3190             : {
    3191             :     OGRErr eErr;
    3192             : 
    3193         188 :     m_dfTMSMinX = m_gt[0];
    3194         188 :     m_dfTMSMaxY = m_gt[3];
    3195             : 
    3196             :     int nTileWidth, nTileHeight;
    3197         188 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3198             : 
    3199         188 :     if (m_nZoomLevel < 0)
    3200             :     {
    3201         168 :         m_nZoomLevel = 0;
    3202         242 :         while ((nRasterXSize >> m_nZoomLevel) > nTileWidth ||
    3203         168 :                (nRasterYSize >> m_nZoomLevel) > nTileHeight)
    3204          74 :             m_nZoomLevel++;
    3205             :     }
    3206             : 
    3207         188 :     double dfPixelXSizeZoomLevel0 = m_gt[1] * (1 << m_nZoomLevel);
    3208         188 :     double dfPixelYSizeZoomLevel0 = fabs(m_gt[5]) * (1 << m_nZoomLevel);
    3209             :     int nTileXCountZoomLevel0 =
    3210         188 :         std::max(1, DIV_ROUND_UP((nRasterXSize >> m_nZoomLevel), nTileWidth));
    3211             :     int nTileYCountZoomLevel0 =
    3212         188 :         std::max(1, DIV_ROUND_UP((nRasterYSize >> m_nZoomLevel), nTileHeight));
    3213             : 
    3214         376 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3215         188 :     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         188 :     m_nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << m_nZoomLevel);
    3226         188 :     m_nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << m_nZoomLevel);
    3227             : 
    3228         188 :     if (!ComputeTileAndPixelShifts())
    3229             :     {
    3230           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    3231             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    3232           1 :         return CE_Failure;
    3233             :     }
    3234             : 
    3235         187 :     if (!AllocCachedTiles())
    3236             :     {
    3237           0 :         return CE_Failure;
    3238             :     }
    3239             : 
    3240         187 :     double dfGDALMinX = m_gt[0];
    3241         187 :     double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3242         187 :     double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3243         187 :     double dfGDALMaxY = m_gt[3];
    3244             : 
    3245         187 :     if (SoftStartTransaction() != OGRERR_NONE)
    3246           0 :         return CE_Failure;
    3247             : 
    3248             :     const char *pszCurrentDate =
    3249         187 :         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         374 :         "('%q','%q','%q','%q',%.17g,%.17g,%.17g,%.17g,");
    3255         187 :     osInsertGpkgContentsFormatting += (pszCurrentDate) ? "'%q'" : "%s";
    3256         187 :     osInsertGpkgContentsFormatting += ",%d)";
    3257         374 :     char *pszSQL = sqlite3_mprintf(
    3258             :         osInsertGpkgContentsFormatting.c_str(), m_osRasterTable.c_str(),
    3259         187 :         (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         187 :     eErr = SQLCommand(hDB, pszSQL);
    3267         187 :     sqlite3_free(pszSQL);
    3268         187 :     if (eErr != OGRERR_NONE)
    3269             :     {
    3270           8 :         SoftRollbackTransaction();
    3271           8 :         return CE_Failure;
    3272             :     }
    3273             : 
    3274         179 :     double dfTMSMaxX = m_dfTMSMinX + nTileXCountZoomLevel0 * nTileWidth *
    3275             :                                          dfPixelXSizeZoomLevel0;
    3276         179 :     double dfTMSMinY = m_dfTMSMaxY - nTileYCountZoomLevel0 * nTileHeight *
    3277             :                                          dfPixelYSizeZoomLevel0;
    3278             : 
    3279             :     pszSQL =
    3280         179 :         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         179 :     eErr = SQLCommand(hDB, pszSQL);
    3286         179 :     sqlite3_free(pszSQL);
    3287         179 :     if (eErr != OGRERR_NONE)
    3288             :     {
    3289           0 :         SoftRollbackTransaction();
    3290           0 :         return CE_Failure;
    3291             :     }
    3292             : 
    3293         179 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3294             : 
    3295         593 :     for (int i = 0; i <= m_nZoomLevel; i++)
    3296             :     {
    3297         414 :         double dfPixelXSizeZoomLevel = 0.0;
    3298         414 :         double dfPixelYSizeZoomLevel = 0.0;
    3299         414 :         int nTileMatrixWidth = 0;
    3300         414 :         int nTileMatrixHeight = 0;
    3301         414 :         if (EQUAL(m_osTilingScheme, "CUSTOM"))
    3302             :         {
    3303         233 :             dfPixelXSizeZoomLevel = m_gt[1] * (1 << (m_nZoomLevel - i));
    3304         233 :             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         414 :         nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << i);
    3312         414 :         nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << i);
    3313             : 
    3314         414 :         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         414 :         eErr = SQLCommand(hDB, pszSQL);
    3323         414 :         sqlite3_free(pszSQL);
    3324         414 :         if (eErr != OGRERR_NONE)
    3325             :         {
    3326           0 :             SoftRollbackTransaction();
    3327           0 :             return CE_Failure;
    3328             :         }
    3329             : 
    3330         414 :         if (i < m_nZoomLevel)
    3331             :         {
    3332         470 :             auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3333         235 :             poOvrDS->ShareLockWithParentDataset(this);
    3334         235 :             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         235 :             m_apoOverviewDS[m_nZoomLevel - 1 - i] = std::move(poOvrDS);
    3341             :         }
    3342             :     }
    3343             : 
    3344         179 :     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         179 :     SoftCommitTransaction();
    3357             : 
    3358         179 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3359         179 :     m_bRecordInsertedInGPKGContent = true;
    3360             : 
    3361         179 :     return CE_None;
    3362             : }
    3363             : 
    3364             : /************************************************************************/
    3365             : /*                             FlushCache()                             */
    3366             : /************************************************************************/
    3367             : 
    3368        2994 : CPLErr GDALGeoPackageDataset::FlushCache(bool bAtClosing)
    3369             : {
    3370        2994 :     if (m_bInFlushCache)
    3371           0 :         return CE_None;
    3372             : 
    3373        2994 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3374             :     {
    3375        2991 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3376             :     }
    3377             : 
    3378        2994 :     if (m_bRemoveOGREmptyTable)
    3379             :     {
    3380         835 :         m_bRemoveOGREmptyTable = false;
    3381         835 :         RemoveOGREmptyTable();
    3382             :     }
    3383             : 
    3384        2994 :     CPLErr eErr = IFlushCacheWithErrCode(bAtClosing);
    3385             : 
    3386        2994 :     FlushMetadata();
    3387             : 
    3388        2994 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3389             :     {
    3390             :         // Needed again as above IFlushCacheWithErrCode()
    3391             :         // may have call GDALGeoPackageRasterBand::InvalidateStatistics()
    3392             :         // which modifies metadata
    3393        2994 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3394             :     }
    3395             : 
    3396        2994 :     return eErr;
    3397             : }
    3398             : 
    3399        5238 : CPLErr GDALGeoPackageDataset::IFlushCacheWithErrCode(bool bAtClosing)
    3400             : 
    3401             : {
    3402        5238 :     if (m_bInFlushCache)
    3403        2177 :         return CE_None;
    3404        3061 :     m_bInFlushCache = true;
    3405        3061 :     if (hDB && eAccess == GA_ReadOnly && bAtClosing)
    3406             :     {
    3407             :         // Clean-up metadata that will go to PAM by removing items that
    3408             :         // are reconstructed.
    3409        2236 :         CPLStringList aosMD;
    3410        1762 :         for (CSLConstList papszIter = GetMetadata(); papszIter && *papszIter;
    3411             :              ++papszIter)
    3412             :         {
    3413         644 :             char *pszKey = nullptr;
    3414         644 :             CPLParseNameValue(*papszIter, &pszKey);
    3415        1288 :             if (pszKey &&
    3416         644 :                 (EQUAL(pszKey, "AREA_OR_POINT") ||
    3417         491 :                  EQUAL(pszKey, "IDENTIFIER") || EQUAL(pszKey, "DESCRIPTION") ||
    3418         263 :                  EQUAL(pszKey, "ZOOM_LEVEL") ||
    3419         674 :                  STARTS_WITH(pszKey, "GPKG_METADATA_ITEM_")))
    3420             :             {
    3421             :                 // remove it
    3422             :             }
    3423             :             else
    3424             :             {
    3425          30 :                 aosMD.AddString(*papszIter);
    3426             :             }
    3427         644 :             CPLFree(pszKey);
    3428             :         }
    3429        1118 :         oMDMD.SetMetadata(aosMD.List());
    3430        1118 :         oMDMD.SetMetadata(nullptr, "IMAGE_STRUCTURE");
    3431             : 
    3432        2236 :         GDALPamDataset::FlushCache(bAtClosing);
    3433             :     }
    3434             :     else
    3435             :     {
    3436             :         // Short circuit GDALPamDataset to avoid serialization to .aux.xml
    3437        1943 :         GDALDataset::FlushCache(bAtClosing);
    3438             :     }
    3439             : 
    3440        7431 :     for (auto &poLayer : m_apoLayers)
    3441             :     {
    3442        4370 :         poLayer->RunDeferredCreationIfNecessary();
    3443        4370 :         poLayer->CreateSpatialIndexIfNecessary();
    3444             :     }
    3445             : 
    3446             :     // Update raster table last_change column in gpkg_contents if needed
    3447        3061 :     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        3061 :     CPLErr eErr = FlushTiles();
    3467             : 
    3468        3061 :     m_bInFlushCache = false;
    3469        3061 :     return eErr;
    3470             : }
    3471             : 
    3472             : /************************************************************************/
    3473             : /*                      GetCurrentDateEscapedSQL()                      */
    3474             : /************************************************************************/
    3475             : 
    3476        2269 : std::string GDALGeoPackageDataset::GetCurrentDateEscapedSQL()
    3477             : {
    3478             :     const char *pszCurrentDate =
    3479        2269 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3480        2269 :     if (pszCurrentDate)
    3481          10 :         return '\'' + SQLEscapeLiteral(pszCurrentDate) + '\'';
    3482        2264 :     return "strftime('%Y-%m-%dT%H:%M:%fZ','now')";
    3483             : }
    3484             : 
    3485             : /************************************************************************/
    3486             : /*                    UpdateGpkgContentsLastChange()                    */
    3487             : /************************************************************************/
    3488             : 
    3489             : OGRErr
    3490         974 : GDALGeoPackageDataset::UpdateGpkgContentsLastChange(const char *pszTableName)
    3491             : {
    3492             :     char *pszSQL =
    3493         974 :         sqlite3_mprintf("UPDATE gpkg_contents SET "
    3494             :                         "last_change = %s "
    3495             :                         "WHERE lower(table_name) = lower('%q')",
    3496        1948 :                         GetCurrentDateEscapedSQL().c_str(), pszTableName);
    3497         974 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    3498         974 :     sqlite3_free(pszSQL);
    3499         974 :     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        6299 : const char *GDALGeoPackageDataset::CheckMetadataDomain(const char *pszDomain)
    3819             : {
    3820        6485 :     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        6295 :     return pszDomain;
    3830             : }
    3831             : 
    3832             : /************************************************************************/
    3833             : /*                         HasMetadataTables()                          */
    3834             : /************************************************************************/
    3835             : 
    3836        6021 : bool GDALGeoPackageDataset::HasMetadataTables() const
    3837             : {
    3838        6021 :     if (m_nHasMetadataTables < 0)
    3839             :     {
    3840             :         const int nCount =
    3841        2316 :             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        2316 :         m_nHasMetadataTables = nCount == 2;
    3847             :     }
    3848        6021 :     return CPL_TO_BOOL(m_nHasMetadataTables);
    3849             : }
    3850             : 
    3851             : /************************************************************************/
    3852             : /*                        HasDataColumnsTable()                         */
    3853             : /************************************************************************/
    3854             : 
    3855        1343 : bool GDALGeoPackageDataset::HasDataColumnsTable() const
    3856             : {
    3857        2686 :     const int nCount = SQLGetInteger(
    3858        1343 :         hDB,
    3859             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_data_columns'"
    3860             :         "AND type IN ('table', 'view')",
    3861             :         nullptr);
    3862        1343 :     return nCount == 1;
    3863             : }
    3864             : 
    3865             : /************************************************************************/
    3866             : /*                   HasDataColumnConstraintsTable()                    */
    3867             : /************************************************************************/
    3868             : 
    3869         164 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTable() const
    3870             : {
    3871         164 :     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         164 :     return nCount == 1;
    3877             : }
    3878             : 
    3879             : /************************************************************************/
    3880             : /*               HasDataColumnConstraintsTableGPKG_1_0()                */
    3881             : /************************************************************************/
    3882             : 
    3883         110 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTableGPKG_1_0() const
    3884             : {
    3885         110 :     if (m_nApplicationId != GP10_APPLICATION_ID)
    3886         108 :         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        1377 : bool GDALGeoPackageDataset::HasGpkgextRelationsTable() const
    4006             : {
    4007        2754 :     const int nCount = SQLGetInteger(
    4008        1377 :         hDB,
    4009             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkgext_relations'"
    4010             :         "AND type IN ('table', 'view')",
    4011             :         nullptr);
    4012        1377 :     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        4135 : CSLConstList GDALGeoPackageDataset::GetMetadata(const char *pszDomain)
    4076             : 
    4077             : {
    4078        4135 :     pszDomain = CheckMetadataDomain(pszDomain);
    4079        4135 :     if (pszDomain != nullptr && EQUAL(pszDomain, "SUBDATASETS"))
    4080          74 :         return m_aosSubDatasets.List();
    4081             : 
    4082        4061 :     if (m_bHasReadMetadataFromStorage)
    4083        1813 :         return GDALPamDataset::GetMetadata(pszDomain);
    4084             : 
    4085        2248 :     m_bHasReadMetadataFromStorage = true;
    4086             : 
    4087        2248 :     TryLoadXML();
    4088             : 
    4089        2248 :     if (!HasMetadataTables())
    4090        1715 :         return GDALPamDataset::GetMetadata(pszDomain);
    4091             : 
    4092         533 :     char *pszSQL = nullptr;
    4093         533 :     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         356 :         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        1066 :     auto oResult = SQLQuery(hDB, pszSQL);
    4119         533 :     sqlite3_free(pszSQL);
    4120         533 :     if (!oResult)
    4121             :     {
    4122           0 :         return GDALPamDataset::GetMetadata(pszDomain);
    4123             :     }
    4124             : 
    4125         533 :     char **papszMetadata = CSLDuplicate(GDALPamDataset::GetMetadata());
    4126             : 
    4127             :     /* GDAL metadata */
    4128         730 :     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         533 :     GDALPamDataset::SetMetadata(papszMetadata);
    4228         533 :     CSLDestroy(papszMetadata);
    4229         533 :     papszMetadata = nullptr;
    4230             : 
    4231             :     /* Add non-GDAL metadata now */
    4232         533 :     int nNonGDALMDILocal = 1;
    4233         533 :     int nNonGDALMDIGeopackage = 1;
    4234         730 :     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         533 :     return GDALPamDataset::GetMetadata(pszDomain);
    4278             : }
    4279             : 
    4280             : /************************************************************************/
    4281             : /*                           WriteMetadata()                            */
    4282             : /************************************************************************/
    4283             : 
    4284         756 : void GDALGeoPackageDataset::WriteMetadata(
    4285             :     CPLXMLNode *psXMLNode, /* will be destroyed by the method */
    4286             :     const char *pszTableName)
    4287             : {
    4288         756 :     const bool bIsEmpty = (psXMLNode == nullptr);
    4289         756 :     if (!HasMetadataTables())
    4290             :     {
    4291         551 :         if (bIsEmpty || !CreateMetadataTables())
    4292             :         {
    4293         252 :             CPLDestroyXMLNode(psXMLNode);
    4294         252 :             return;
    4295             :         }
    4296             :     }
    4297             : 
    4298         504 :     char *pszXML = nullptr;
    4299         504 :     if (!bIsEmpty)
    4300             :     {
    4301             :         CPLXMLNode *psMasterXMLNode =
    4302         349 :             CPLCreateXMLNode(nullptr, CXT_Element, "GDALMultiDomainMetadata");
    4303         349 :         psMasterXMLNode->psChild = psXMLNode;
    4304         349 :         pszXML = CPLSerializeXMLTree(psMasterXMLNode);
    4305         349 :         CPLDestroyXMLNode(psMasterXMLNode);
    4306             :     }
    4307             :     // cppcheck-suppress uselessAssignmentPtrArg
    4308         504 :     psXMLNode = nullptr;
    4309             : 
    4310         504 :     char *pszSQL = nullptr;
    4311         504 :     if (pszTableName && pszTableName[0] != '\0')
    4312             :     {
    4313         357 :         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         504 :     int mdId = SQLGetInteger(hDB, pszSQL, &err);
    4334         504 :     if (err != OGRERR_NONE)
    4335         471 :         mdId = -1;
    4336         504 :     sqlite3_free(pszSQL);
    4337             : 
    4338         504 :     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         349 :         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         322 :                 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         349 :         SQLCommand(hDB, pszSQL);
    4369         349 :         sqlite3_free(pszSQL);
    4370             : 
    4371         349 :         CPLFree(pszXML);
    4372             : 
    4373         349 :         if (mdId < 0)
    4374             :         {
    4375         322 :             const sqlite_int64 nFID = sqlite3_last_insert_rowid(hDB);
    4376         322 :             if (pszTableName != nullptr && pszTableName[0] != '\0')
    4377             :             {
    4378         310 :                 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         620 :                     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         349 :         SQLCommand(hDB, pszSQL);
    4401         349 :         sqlite3_free(pszSQL);
    4402             :     }
    4403             : }
    4404             : 
    4405             : /************************************************************************/
    4406             : /*                        CreateMetadataTables()                        */
    4407             : /************************************************************************/
    4408             : 
    4409         318 : bool GDALGeoPackageDataset::CreateMetadataTables()
    4410             : {
    4411             :     const bool bCreateTriggers =
    4412         318 :         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         636 :                       ")";
    4422             : 
    4423             :     /* From D.2. metadata Table 40. metadata Trigger Definition SQL  */
    4424         318 :     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         318 :     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         318 :              ")";
    4478             : 
    4479             :     /* From D.3. metadata_reference Table 41. gpkg_metadata_reference Trigger
    4480             :      * Definition SQL   */
    4481         318 :     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         318 :     if (bCreateTriggers)
    4575             :     {
    4576           0 :         osSQL += ";";
    4577           0 :         osSQL += pszMetadataReferenceTriggers;
    4578             :     }
    4579             : 
    4580         318 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    4581           2 :         return false;
    4582             : 
    4583         316 :     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         316 :              "'read-write')";
    4590             : 
    4591         316 :     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         316 :              "'read-write')";
    4598             : 
    4599         316 :     const bool bOK = SQLCommand(hDB, osSQL) == OGRERR_NONE;
    4600         316 :     m_nHasMetadataTables = bOK;
    4601         316 :     return bOK;
    4602             : }
    4603             : 
    4604             : /************************************************************************/
    4605             : /*                           FlushMetadata()                            */
    4606             : /************************************************************************/
    4607             : 
    4608        9114 : void GDALGeoPackageDataset::FlushMetadata()
    4609             : {
    4610        9114 :     if (!m_bMetadataDirty || m_poParentDS != nullptr ||
    4611         378 :         m_nCreateMetadataTables == FALSE)
    4612        8742 :         return;
    4613         372 :     m_bMetadataDirty = false;
    4614             : 
    4615         372 :     if (eAccess == GA_ReadOnly)
    4616             :     {
    4617           3 :         return;
    4618             :     }
    4619             : 
    4620         369 :     bool bCanWriteAreaOrPoint =
    4621         736 :         !m_bGridCellEncodingAsCO &&
    4622         367 :         (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT);
    4623         369 :     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         369 :     char **papszMDDup = nullptr;
    4681         206 :     for (const char *pszKeyValue :
    4682         781 :          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         369 :     CPLXMLNode *psXMLNode = nullptr;
    4702             :     {
    4703         369 :         GDALMultiDomainMetadata oLocalMDMD;
    4704         369 :         CSLConstList papszDomainList = oMDMD.GetDomainList();
    4705         369 :         CSLConstList papszIter = papszDomainList;
    4706         369 :         oLocalMDMD.SetMetadata(papszMDDup);
    4707         700 :         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         369 :         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         514 :         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         619 :         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         369 :         psXMLNode = oLocalMDMD.Serialize();
    4799             :     }
    4800             : 
    4801         369 :     CSLDestroy(papszMDDup);
    4802         369 :     papszMDDup = nullptr;
    4803             : 
    4804         369 :     WriteMetadata(psXMLNode, m_osRasterTable.c_str());
    4805             : 
    4806         369 :     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         611 :     for (auto &poLayer : m_apoLayers)
    4828             :     {
    4829         242 :         const char *pszIdentifier = poLayer->GetMetadataItem("IDENTIFIER");
    4830         242 :         const char *pszDescription = poLayer->GetMetadataItem("DESCRIPTION");
    4831         242 :         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         242 :         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         242 :         papszMDDup = nullptr;
    4851         651 :         for (CSLConstList papszIter = poLayer->GetMetadata();
    4852         651 :              papszIter && *papszIter; ++papszIter)
    4853             :         {
    4854         409 :             if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4855           3 :                 continue;
    4856         406 :             if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4857           3 :                 continue;
    4858         403 :             if (STARTS_WITH_CI(*papszIter, "OLMD_FID64="))
    4859           0 :                 continue;
    4860         403 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4861             :         }
    4862             : 
    4863             :         {
    4864         242 :             GDALMultiDomainMetadata oLocalMDMD;
    4865         242 :             char **papszDomainList = poLayer->GetMetadataDomainList();
    4866         242 :             char **papszIter = papszDomainList;
    4867         242 :             oLocalMDMD.SetMetadata(papszMDDup);
    4868         539 :             while (papszIter && *papszIter)
    4869             :             {
    4870         297 :                 if (!EQUAL(*papszIter, ""))
    4871          68 :                     oLocalMDMD.SetMetadata(poLayer->GetMetadata(*papszIter),
    4872             :                                            *papszIter);
    4873         297 :                 papszIter++;
    4874             :             }
    4875         242 :             CSLDestroy(papszDomainList);
    4876         242 :             psXMLNode = oLocalMDMD.Serialize();
    4877             :         }
    4878             : 
    4879         242 :         CSLDestroy(papszMDDup);
    4880         242 :         papszMDDup = nullptr;
    4881             : 
    4882         242 :         WriteMetadata(psXMLNode, poLayer->GetName());
    4883             :     }
    4884             : }
    4885             : 
    4886             : /************************************************************************/
    4887             : /*                          GetMetadataItem()                           */
    4888             : /************************************************************************/
    4889             : 
    4890        2009 : const char *GDALGeoPackageDataset::GetMetadataItem(const char *pszName,
    4891             :                                                    const char *pszDomain)
    4892             : {
    4893        2009 :     pszDomain = CheckMetadataDomain(pszDomain);
    4894        2009 :     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        1065 : int GDALGeoPackageDataset::Create(const char *pszFilename, int nXSize,
    4929             :                                   int nYSize, int nBandsIn, GDALDataType eDT,
    4930             :                                   CSLConstList papszOptions)
    4931             : {
    4932        2130 :     CPLString osCommand;
    4933             : 
    4934             :     /* First, ensure there isn't any such file yet. */
    4935             :     VSIStatBufL sStatBuf;
    4936             : 
    4937        1065 :     if (nBandsIn != 0)
    4938             :     {
    4939         227 :         if (eDT == GDT_UInt8)
    4940             :         {
    4941         157 :             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        1034 :     const size_t nFilenameLen = strlen(pszFilename);
    4970        1034 :     const bool bGpkgZip =
    4971        1029 :         (nFilenameLen > strlen(".gpkg.zip") &&
    4972        2063 :          !STARTS_WITH(pszFilename, "/vsizip/") &&
    4973        1029 :          EQUAL(pszFilename + nFilenameLen - strlen(".gpkg.zip"), ".gpkg.zip"));
    4974             : 
    4975             :     const bool bUseTempFile =
    4976        1035 :         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        1034 :                             "FORCED")));
    4982             : 
    4983        1034 :     bool bFileExists = false;
    4984        1034 :     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        1034 :     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        1031 :         m_pszFilename = CPLStrdup(pszFilename);
    5019             :     }
    5020        1034 :     m_bNew = true;
    5021        1034 :     eAccess = GA_Update;
    5022        1034 :     m_bDateTimeWithTZ =
    5023        1034 :         EQUAL(CSLFetchNameValueDef(papszOptions, "DATETIME_FORMAT", "WITH_TZ"),
    5024             :               "WITH_TZ");
    5025             : 
    5026             :     // for test/debug purposes only. true is the nominal value
    5027        1034 :     m_bPNGSupports2Bands =
    5028        1034 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_2BANDS", "TRUE"));
    5029        1034 :     m_bPNGSupportsCT =
    5030        1034 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_CT", "TRUE"));
    5031             : 
    5032        1034 :     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        2042 :     if (!bFileExists &&
    5039        1016 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5040             :     {
    5041         501 :         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        1026 :     SQLCommand(hDB, "PRAGMA encoding = \"UTF-8\"");
    5047             : 
    5048        1026 :     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        1026 :     const char *pszVersion = CSLFetchNameValue(papszOptions, "VERSION");
    5082        1026 :     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        1026 :     SoftStartTransaction();
    5112             : 
    5113        2052 :     CPLString osSQL;
    5114        1026 :     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        1016 :                 "description TEXT";
    5126        1016 :         if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "CRS_WKT_EXTENSION",
    5127        1198 :                                              "NO")) ||
    5128         182 :             (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        1016 :                  "definition, description";
    5148        1016 :         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        1016 :             "84 spheroid'";
    5161        1016 :         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        1016 :             "definition, description";
    5183        1016 :         if (m_bHasDefinition12_063)
    5184          42 :             osSQL += ", definition_12_063";
    5185             :         osSQL += ") VALUES ("
    5186             :                  "'Undefined Cartesian SRS', -1, 'NONE', -1, 'undefined', "
    5187        1016 :                  "'undefined Cartesian coordinate reference system'";
    5188        1016 :         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        1016 :             "definition, description";
    5203        1016 :         if (m_bHasDefinition12_063)
    5204          42 :             osSQL += ", definition_12_063";
    5205             :         osSQL += ") VALUES ("
    5206             :                  "'Undefined geographic SRS', 0, 'NONE', 0, 'undefined', "
    5207        1016 :                  "'undefined geographic coordinate reference system'";
    5208        1016 :         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        1016 :                  ")";
    5228             : 
    5229             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5230        1016 :         if (CPLFetchBool(papszOptions, "ADD_GPKG_OGR_CONTENTS", true))
    5231             :         {
    5232        1010 :             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        1010 :                      ")";
    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        1016 :             CPLTestBool(CPLGetConfigOption("CREATE_GEOMETRY_COLUMNS", "YES"));
    5248        1016 :         if (bCreateGeometryColumns)
    5249             :         {
    5250        1015 :             m_bHasGPKGGeometryColumns = true;
    5251        1015 :             osSQL += ";";
    5252        1015 :             osSQL += pszCREATE_GPKG_GEOMETRY_COLUMNS;
    5253             :         }
    5254             :     }
    5255             : 
    5256             :     const bool bCreateTriggers =
    5257        1026 :         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        2052 :              nullptr) == 0) ||
    5264        1025 :         (!bFileExists &&
    5265        1016 :          CPLTestBool(CPLGetConfigOption("CREATE_RASTER_TABLES", "YES"))))
    5266             :     {
    5267        1016 :         if (!osSQL.empty())
    5268        1015 :             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        1016 :                  ")";
    5301             : 
    5302        1016 :         if (bCreateTriggers)
    5303             :         {
    5304             :             /* From D.1. gpkg_tile_matrix Table 39. gpkg_tile_matrix Trigger
    5305             :              * Definition SQL */
    5306        1016 :             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        1016 :             osSQL += ";";
    5378        1016 :             osSQL += pszTileMatrixTrigger;
    5379             :         }
    5380             :     }
    5381             : 
    5382        1026 :     if (!osSQL.empty() && OGRERR_NONE != SQLCommand(hDB, osSQL))
    5383           1 :         return FALSE;
    5384             : 
    5385        1025 :     if (!bFileExists)
    5386             :     {
    5387             :         const char *pszMetadataTables =
    5388        1015 :             CSLFetchNameValue(papszOptions, "METADATA_TABLES");
    5389        1015 :         if (pszMetadataTables)
    5390          10 :             m_nCreateMetadataTables = int(CPLTestBool(pszMetadataTables));
    5391             : 
    5392        1015 :         if (m_nCreateMetadataTables == TRUE && !CreateMetadataTables())
    5393           0 :             return FALSE;
    5394             : 
    5395        1015 :         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        1025 :     if (nBandsIn != 0)
    5435             :     {
    5436         191 :         const std::string osTableName = CPLGetBasenameSafe(m_pszFilename);
    5437             :         m_osRasterTable = CSLFetchNameValueDef(papszOptions, "RASTER_TABLE",
    5438         191 :                                                osTableName.c_str());
    5439         191 :         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         191 :         m_bIdentifierAsCO =
    5446         191 :             CSLFetchNameValue(papszOptions, "RASTER_IDENTIFIER") != nullptr;
    5447             :         m_osIdentifier = CSLFetchNameValueDef(papszOptions, "RASTER_IDENTIFIER",
    5448         191 :                                               m_osRasterTable);
    5449         191 :         m_bDescriptionAsCO =
    5450         191 :             CSLFetchNameValue(papszOptions, "RASTER_DESCRIPTION") != nullptr;
    5451             :         m_osDescription =
    5452         191 :             CSLFetchNameValueDef(papszOptions, "RASTER_DESCRIPTION", "");
    5453         191 :         SetDataType(eDT);
    5454         191 :         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         191 :             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         191 :         osSQL = pszSQL;
    5470         191 :         sqlite3_free(pszSQL);
    5471             : 
    5472         191 :         if (bCreateTriggers)
    5473             :         {
    5474         191 :             osSQL += ";";
    5475         191 :             osSQL += CreateRasterTriggersSQL(m_osRasterTable);
    5476             :         }
    5477             : 
    5478         191 :         OGRErr eErr = SQLCommand(hDB, osSQL);
    5479         191 :         if (OGRERR_NONE != eErr)
    5480           0 :             return FALSE;
    5481             : 
    5482         191 :         const char *pszTF = CSLFetchNameValue(papszOptions, "TILE_FORMAT");
    5483         191 :         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         164 :         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         151 :             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          80 :             else if (nBandsIn == 1)
    5520          69 :                 m_eTF = GPKG_TF_PNG;
    5521             :         }
    5522             : 
    5523         191 :         if (eDT != GDT_UInt8)
    5524             :         {
    5525          40 :             if (!CreateTileGriddedTable(papszOptions))
    5526           0 :                 return FALSE;
    5527             :         }
    5528             : 
    5529         191 :         nRasterXSize = nXSize;
    5530         191 :         nRasterYSize = nYSize;
    5531             : 
    5532             :         const char *pszTileSize =
    5533         191 :             CSLFetchNameValueDef(papszOptions, "BLOCKSIZE", "256");
    5534             :         const char *pszTileWidth =
    5535         191 :             CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", pszTileSize);
    5536             :         const char *pszTileHeight =
    5537         191 :             CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", pszTileSize);
    5538         191 :         int nTileWidth = atoi(pszTileWidth);
    5539         191 :         int nTileHeight = atoi(pszTileHeight);
    5540         191 :         if ((nTileWidth < 8 || nTileWidth > 4096 || nTileHeight < 8 ||
    5541         382 :              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         515 :         for (int i = 1; i <= nBandsIn; i++)
    5551             :         {
    5552         324 :             SetBand(i, std::make_unique<GDALGeoPackageRasterBand>(
    5553             :                            this, nTileWidth, nTileHeight));
    5554             :         }
    5555             : 
    5556         191 :         GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL",
    5557             :                                         "IMAGE_STRUCTURE");
    5558         191 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", m_osIdentifier);
    5559         191 :         if (!m_osDescription.empty())
    5560           1 :             GDALPamDataset::SetMetadataItem("DESCRIPTION", m_osDescription);
    5561             : 
    5562         191 :         ParseCompressionOptions(papszOptions);
    5563             : 
    5564         191 :         if (m_eTF == GPKG_TF_WEBP)
    5565             :         {
    5566          10 :             if (!RegisterWebPExtension())
    5567           0 :                 return FALSE;
    5568             :         }
    5569             : 
    5570             :         m_osTilingScheme =
    5571         191 :             CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5572         191 :         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         169 :             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        1024 :     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        1024 :     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        1024 :     SetApplicationAndUserVersionId();
    5645             : 
    5646             :     /* Default to synchronous=off for performance for new file */
    5647        2038 :     if (!bFileExists &&
    5648        1014 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5649             :     {
    5650         501 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5651             :     }
    5652             : 
    5653        1024 :     return TRUE;
    5654             : }
    5655             : 
    5656             : /************************************************************************/
    5657             : /*                        RemoveOGREmptyTable()                         */
    5658             : /************************************************************************/
    5659             : 
    5660         844 : void GDALGeoPackageDataset::RemoveOGREmptyTable()
    5661             : {
    5662             :     // Run with sqlite3_exec since we don't want errors to be emitted
    5663         844 :     sqlite3_exec(hDB, "DROP TABLE IF EXISTS ogr_empty_table", nullptr, nullptr,
    5664             :                  nullptr);
    5665         844 :     sqlite3_exec(
    5666             :         hDB, "DELETE FROM gpkg_contents WHERE table_name = 'ogr_empty_table'",
    5667             :         nullptr, nullptr, nullptr);
    5668             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5669         844 :     if (m_bHasGPKGOGRContents)
    5670             :     {
    5671         829 :         sqlite3_exec(hDB,
    5672             :                      "DELETE FROM gpkg_ogr_contents WHERE "
    5673             :                      "table_name = 'ogr_empty_table'",
    5674             :                      nullptr, nullptr, nullptr);
    5675             :     }
    5676             : #endif
    5677         844 :     sqlite3_exec(hDB,
    5678             :                  "DELETE FROM gpkg_geometry_columns WHERE "
    5679             :                  "table_name = 'ogr_empty_table'",
    5680             :                  nullptr, nullptr, nullptr);
    5681         844 : }
    5682             : 
    5683             : /************************************************************************/
    5684             : /*                       CreateTileGriddedTable()                       */
    5685             : /************************************************************************/
    5686             : 
    5687          40 : bool GDALGeoPackageDataset::CreateTileGriddedTable(CSLConstList papszOptions)
    5688             : {
    5689          80 :     CPLString osSQL;
    5690          40 :     if (!HasGriddedCoverageAncillaryTable())
    5691             :     {
    5692             :         // It doesn't exist. So create gpkg_extensions table if necessary, and
    5693             :         // gpkg_2d_gridded_coverage_ancillary & gpkg_2d_gridded_tile_ancillary,
    5694             :         // and register them as extensions.
    5695          40 :         if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    5696           0 :             return false;
    5697             : 
    5698             :         // Req 1 /table-defs/coverage-ancillary
    5699             :         osSQL = "CREATE TABLE gpkg_2d_gridded_coverage_ancillary ("
    5700             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5701             :                 "tile_matrix_set_name TEXT NOT NULL UNIQUE,"
    5702             :                 "datatype TEXT NOT NULL DEFAULT 'integer',"
    5703             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5704             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5705             :                 "precision REAL DEFAULT 1.0,"
    5706             :                 "data_null REAL,"
    5707             :                 "grid_cell_encoding TEXT DEFAULT 'grid-value-is-center',"
    5708             :                 "uom TEXT,"
    5709             :                 "field_name TEXT DEFAULT 'Height',"
    5710             :                 "quantity_definition TEXT DEFAULT 'Height',"
    5711             :                 "CONSTRAINT fk_g2dgtct_name FOREIGN KEY(tile_matrix_set_name) "
    5712             :                 "REFERENCES gpkg_tile_matrix_set ( table_name ) "
    5713             :                 "CHECK (datatype in ('integer','float')))"
    5714             :                 ";"
    5715             :                 // Requirement 2 /table-defs/tile-ancillary
    5716             :                 "CREATE TABLE gpkg_2d_gridded_tile_ancillary ("
    5717             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5718             :                 "tpudt_name TEXT NOT NULL,"
    5719             :                 "tpudt_id INTEGER NOT NULL,"
    5720             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5721             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5722             :                 "min REAL DEFAULT NULL,"
    5723             :                 "max REAL DEFAULT NULL,"
    5724             :                 "mean REAL DEFAULT NULL,"
    5725             :                 "std_dev REAL DEFAULT NULL,"
    5726             :                 "CONSTRAINT fk_g2dgtat_name FOREIGN KEY (tpudt_name) "
    5727             :                 "REFERENCES gpkg_contents(table_name),"
    5728             :                 "UNIQUE (tpudt_name, tpudt_id))"
    5729             :                 ";"
    5730             :                 // Requirement 6 /gpkg-extensions
    5731             :                 "INSERT INTO gpkg_extensions "
    5732             :                 "(table_name, column_name, extension_name, definition, scope) "
    5733             :                 "VALUES ('gpkg_2d_gridded_coverage_ancillary', NULL, "
    5734             :                 "'gpkg_2d_gridded_coverage', "
    5735             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5736             :                 "'read-write')"
    5737             :                 ";"
    5738             :                 // Requirement 6 /gpkg-extensions
    5739             :                 "INSERT INTO gpkg_extensions "
    5740             :                 "(table_name, column_name, extension_name, definition, scope) "
    5741             :                 "VALUES ('gpkg_2d_gridded_tile_ancillary', NULL, "
    5742             :                 "'gpkg_2d_gridded_coverage', "
    5743             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5744             :                 "'read-write')"
    5745          40 :                 ";";
    5746             :     }
    5747             : 
    5748             :     // Requirement 6 /gpkg-extensions
    5749          40 :     char *pszSQL = sqlite3_mprintf(
    5750             :         "INSERT INTO gpkg_extensions "
    5751             :         "(table_name, column_name, extension_name, definition, scope) "
    5752             :         "VALUES ('%q', 'tile_data', "
    5753             :         "'gpkg_2d_gridded_coverage', "
    5754             :         "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5755             :         "'read-write')",
    5756             :         m_osRasterTable.c_str());
    5757          40 :     osSQL += pszSQL;
    5758          40 :     osSQL += ";";
    5759          40 :     sqlite3_free(pszSQL);
    5760             : 
    5761             :     // Requirement 7 /gpkg-2d-gridded-coverage-ancillary
    5762             :     // Requirement 8 /gpkg-2d-gridded-coverage-ancillary-set-name
    5763             :     // Requirement 9 /gpkg-2d-gridded-coverage-ancillary-datatype
    5764          40 :     m_dfPrecision =
    5765          40 :         CPLAtof(CSLFetchNameValueDef(papszOptions, "PRECISION", "1"));
    5766             :     CPLString osGridCellEncoding(CSLFetchNameValueDef(
    5767          80 :         papszOptions, "GRID_CELL_ENCODING", "grid-value-is-center"));
    5768          40 :     m_bGridCellEncodingAsCO =
    5769          40 :         CSLFetchNameValue(papszOptions, "GRID_CELL_ENCODING") != nullptr;
    5770          80 :     CPLString osUom(CSLFetchNameValueDef(papszOptions, "UOM", ""));
    5771             :     CPLString osFieldName(
    5772          80 :         CSLFetchNameValueDef(papszOptions, "FIELD_NAME", "Height"));
    5773             :     CPLString osQuantityDefinition(
    5774          80 :         CSLFetchNameValueDef(papszOptions, "QUANTITY_DEFINITION", "Height"));
    5775             : 
    5776         121 :     pszSQL = sqlite3_mprintf(
    5777             :         "INSERT INTO gpkg_2d_gridded_coverage_ancillary "
    5778             :         "(tile_matrix_set_name, datatype, scale, offset, precision, "
    5779             :         "grid_cell_encoding, uom, field_name, quantity_definition) "
    5780             :         "VALUES (%Q, '%s', %.17g, %.17g, %.17g, %Q, %Q, %Q, %Q)",
    5781             :         m_osRasterTable.c_str(),
    5782          40 :         (m_eTF == GPKG_TF_PNG_16BIT) ? "integer" : "float", m_dfScale,
    5783             :         m_dfOffset, m_dfPrecision, osGridCellEncoding.c_str(),
    5784          41 :         osUom.empty() ? nullptr : osUom.c_str(), osFieldName.c_str(),
    5785             :         osQuantityDefinition.c_str());
    5786          40 :     m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary = pszSQL;
    5787          40 :     sqlite3_free(pszSQL);
    5788             : 
    5789             :     // Requirement 3 /gpkg-spatial-ref-sys-row
    5790             :     auto oResultTable = SQLQuery(
    5791          80 :         hDB, "SELECT * FROM gpkg_spatial_ref_sys WHERE srs_id = 4979 LIMIT 2");
    5792          40 :     bool bHasEPSG4979 = (oResultTable && oResultTable->RowCount() == 1);
    5793          40 :     if (!bHasEPSG4979)
    5794             :     {
    5795          41 :         if (!m_bHasDefinition12_063 &&
    5796           1 :             !ConvertGpkgSpatialRefSysToExtensionWkt2(/*bForceEpoch=*/false))
    5797             :         {
    5798           0 :             return false;
    5799             :         }
    5800             : 
    5801             :         // This is WKT 2...
    5802          40 :         const char *pszWKT =
    5803             :             "GEODCRS[\"WGS 84\","
    5804             :             "DATUM[\"World Geodetic System 1984\","
    5805             :             "  ELLIPSOID[\"WGS 84\",6378137,298.257223563,"
    5806             :             "LENGTHUNIT[\"metre\",1.0]]],"
    5807             :             "CS[ellipsoidal,3],"
    5808             :             "  AXIS[\"latitude\",north,ORDER[1],ANGLEUNIT[\"degree\","
    5809             :             "0.0174532925199433]],"
    5810             :             "  AXIS[\"longitude\",east,ORDER[2],ANGLEUNIT[\"degree\","
    5811             :             "0.0174532925199433]],"
    5812             :             "  AXIS[\"ellipsoidal height\",up,ORDER[3],"
    5813             :             "LENGTHUNIT[\"metre\",1.0]],"
    5814             :             "ID[\"EPSG\",4979]]";
    5815             : 
    5816          40 :         pszSQL = sqlite3_mprintf(
    5817             :             "INSERT INTO gpkg_spatial_ref_sys "
    5818             :             "(srs_name,srs_id,organization,organization_coordsys_id,"
    5819             :             "definition,definition_12_063) VALUES "
    5820             :             "('WGS 84 3D', 4979, 'EPSG', 4979, 'undefined', '%q')",
    5821             :             pszWKT);
    5822          40 :         osSQL += ";";
    5823          40 :         osSQL += pszSQL;
    5824          40 :         sqlite3_free(pszSQL);
    5825             :     }
    5826             : 
    5827          40 :     return SQLCommand(hDB, osSQL) == OGRERR_NONE;
    5828             : }
    5829             : 
    5830             : /************************************************************************/
    5831             : /*                  HasGriddedCoverageAncillaryTable()                  */
    5832             : /************************************************************************/
    5833             : 
    5834          44 : bool GDALGeoPackageDataset::HasGriddedCoverageAncillaryTable()
    5835             : {
    5836             :     auto oResultTable = SQLQuery(
    5837             :         hDB, "SELECT * FROM sqlite_master WHERE type IN ('table', 'view') AND "
    5838          44 :              "name = 'gpkg_2d_gridded_coverage_ancillary'");
    5839          44 :     bool bHasTable = (oResultTable && oResultTable->RowCount() == 1);
    5840          88 :     return bHasTable;
    5841             : }
    5842             : 
    5843             : /************************************************************************/
    5844             : /*                        GetUnderlyingDataset()                        */
    5845             : /************************************************************************/
    5846             : 
    5847           3 : static GDALDataset *GetUnderlyingDataset(GDALDataset *poSrcDS)
    5848             : {
    5849           3 :     if (auto poVRTDS = dynamic_cast<VRTDataset *>(poSrcDS))
    5850             :     {
    5851           0 :         auto poTmpDS = poVRTDS->GetSingleSimpleSource();
    5852           0 :         if (poTmpDS)
    5853           0 :             return poTmpDS;
    5854             :     }
    5855             : 
    5856           3 :     return poSrcDS;
    5857             : }
    5858             : 
    5859             : /************************************************************************/
    5860             : /*                             CreateCopy()                             */
    5861             : /************************************************************************/
    5862             : 
    5863             : typedef struct
    5864             : {
    5865             :     const char *pszName;
    5866             :     GDALResampleAlg eResampleAlg;
    5867             : } WarpResamplingAlg;
    5868             : 
    5869             : static const WarpResamplingAlg asResamplingAlg[] = {
    5870             :     {"NEAREST", GRA_NearestNeighbour},
    5871             :     {"BILINEAR", GRA_Bilinear},
    5872             :     {"CUBIC", GRA_Cubic},
    5873             :     {"CUBICSPLINE", GRA_CubicSpline},
    5874             :     {"LANCZOS", GRA_Lanczos},
    5875             :     {"MODE", GRA_Mode},
    5876             :     {"AVERAGE", GRA_Average},
    5877             :     {"RMS", GRA_RMS},
    5878             : };
    5879             : 
    5880         163 : GDALDataset *GDALGeoPackageDataset::CreateCopy(const char *pszFilename,
    5881             :                                                GDALDataset *poSrcDS,
    5882             :                                                int bStrict,
    5883             :                                                CSLConstList papszOptions,
    5884             :                                                GDALProgressFunc pfnProgress,
    5885             :                                                void *pProgressData)
    5886             : {
    5887         163 :     const int nBands = poSrcDS->GetRasterCount();
    5888         163 :     if (nBands == 0)
    5889             :     {
    5890           2 :         GDALDataset *poDS = nullptr;
    5891             :         GDALDriver *poThisDriver =
    5892           2 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5893           2 :         if (poThisDriver != nullptr)
    5894             :         {
    5895           2 :             poDS = poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS,
    5896             :                                                    bStrict, papszOptions,
    5897             :                                                    pfnProgress, pProgressData);
    5898             :         }
    5899           2 :         return poDS;
    5900             :     }
    5901             : 
    5902             :     const char *pszTilingScheme =
    5903         161 :         CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5904             : 
    5905         322 :     CPLStringList apszUpdatedOptions(CSLDuplicate(papszOptions));
    5906         161 :     if (CPLTestBool(
    5907         167 :             CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")) &&
    5908           6 :         CSLFetchNameValue(papszOptions, "RASTER_TABLE") == nullptr)
    5909             :     {
    5910             :         const std::string osBasename(CPLGetBasenameSafe(
    5911           6 :             GetUnderlyingDataset(poSrcDS)->GetDescription()));
    5912           3 :         apszUpdatedOptions.SetNameValue("RASTER_TABLE", osBasename.c_str());
    5913             :     }
    5914             : 
    5915         161 :     if (nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4)
    5916             :     {
    5917           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    5918             :                  "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or "
    5919             :                  "4 (RGBA) band dataset supported");
    5920           1 :         return nullptr;
    5921             :     }
    5922             : 
    5923         160 :     const char *pszUnitType = poSrcDS->GetRasterBand(1)->GetUnitType();
    5924         320 :     if (CSLFetchNameValue(papszOptions, "UOM") == nullptr && pszUnitType &&
    5925         160 :         !EQUAL(pszUnitType, ""))
    5926             :     {
    5927           1 :         apszUpdatedOptions.SetNameValue("UOM", pszUnitType);
    5928             :     }
    5929             : 
    5930         160 :     if (EQUAL(pszTilingScheme, "CUSTOM"))
    5931             :     {
    5932         136 :         if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5933             :         {
    5934           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    5935             :                      "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5936           0 :             return nullptr;
    5937             :         }
    5938             : 
    5939         136 :         GDALGeoPackageDataset *poDS = nullptr;
    5940             :         GDALDriver *poThisDriver =
    5941         136 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5942         136 :         if (poThisDriver != nullptr)
    5943             :         {
    5944         136 :             apszUpdatedOptions.SetNameValue("SKIP_HOLES", "YES");
    5945         136 :             poDS = cpl::down_cast<GDALGeoPackageDataset *>(
    5946             :                 poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS, bStrict,
    5947             :                                                 apszUpdatedOptions, pfnProgress,
    5948         136 :                                                 pProgressData));
    5949             : 
    5950         252 :             if (poDS != nullptr &&
    5951         136 :                 poSrcDS->GetRasterBand(1)->GetRasterDataType() == GDT_UInt8 &&
    5952             :                 nBands <= 3)
    5953             :             {
    5954          76 :                 poDS->m_nBandCountFromMetadata = nBands;
    5955          76 :                 poDS->m_bMetadataDirty = true;
    5956             :             }
    5957             :         }
    5958         136 :         if (poDS)
    5959         116 :             poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    5960         136 :         return poDS;
    5961             :     }
    5962             : 
    5963          48 :     const auto poTS = GetTilingScheme(pszTilingScheme);
    5964          24 :     if (!poTS)
    5965             :     {
    5966           2 :         return nullptr;
    5967             :     }
    5968          22 :     const int nEPSGCode = poTS->nEPSGCode;
    5969             : 
    5970          44 :     OGRSpatialReference oSRS;
    5971          22 :     if (oSRS.importFromEPSG(nEPSGCode) != OGRERR_NONE)
    5972             :     {
    5973           0 :         return nullptr;
    5974             :     }
    5975          22 :     char *pszWKT = nullptr;
    5976          22 :     oSRS.exportToWkt(&pszWKT);
    5977          22 :     char **papszTO = CSLSetNameValue(nullptr, "DST_SRS", pszWKT);
    5978             : 
    5979          22 :     void *hTransformArg = nullptr;
    5980             : 
    5981             :     // Hack to compensate for GDALSuggestedWarpOutput2() failure (or not
    5982             :     // ideal suggestion with PROJ 8) when reprojecting latitude = +/- 90 to
    5983             :     // EPSG:3857.
    5984          22 :     GDALGeoTransform srcGT;
    5985          22 :     std::unique_ptr<GDALDataset> poTmpDS;
    5986          22 :     bool bEPSG3857Adjust = false;
    5987           8 :     if (nEPSGCode == 3857 && poSrcDS->GetGeoTransform(srcGT) == CE_None &&
    5988          30 :         srcGT[2] == 0 && srcGT[4] == 0 && srcGT[5] < 0)
    5989             :     {
    5990           8 :         const auto poSrcSRS = poSrcDS->GetSpatialRef();
    5991           8 :         if (poSrcSRS && poSrcSRS->IsGeographic())
    5992             :         {
    5993           2 :             double maxLat = srcGT[3];
    5994           2 :             double minLat = srcGT[3] + poSrcDS->GetRasterYSize() * srcGT[5];
    5995             :             // Corresponds to the latitude of below MAX_GM
    5996           2 :             constexpr double MAX_LAT = 85.0511287798066;
    5997           2 :             bool bModified = false;
    5998           2 :             if (maxLat > MAX_LAT)
    5999             :             {
    6000           2 :                 maxLat = MAX_LAT;
    6001           2 :                 bModified = true;
    6002             :             }
    6003           2 :             if (minLat < -MAX_LAT)
    6004             :             {
    6005           2 :                 minLat = -MAX_LAT;
    6006           2 :                 bModified = true;
    6007             :             }
    6008           2 :             if (bModified)
    6009             :             {
    6010           4 :                 CPLStringList aosOptions;
    6011           2 :                 aosOptions.AddString("-of");
    6012           2 :                 aosOptions.AddString("VRT");
    6013           2 :                 aosOptions.AddString("-projwin");
    6014           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", srcGT[0]));
    6015           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", maxLat));
    6016             :                 aosOptions.AddString(CPLSPrintf(
    6017           2 :                     "%.17g", srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1]));
    6018           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", minLat));
    6019             :                 auto psOptions =
    6020           2 :                     GDALTranslateOptionsNew(aosOptions.List(), nullptr);
    6021           2 :                 poTmpDS.reset(GDALDataset::FromHandle(GDALTranslate(
    6022             :                     "", GDALDataset::ToHandle(poSrcDS), psOptions, nullptr)));
    6023           2 :                 GDALTranslateOptionsFree(psOptions);
    6024           2 :                 if (poTmpDS)
    6025             :                 {
    6026           2 :                     bEPSG3857Adjust = true;
    6027           2 :                     hTransformArg = GDALCreateGenImgProjTransformer2(
    6028           2 :                         GDALDataset::FromHandle(poTmpDS.get()), nullptr,
    6029             :                         papszTO);
    6030             :                 }
    6031             :             }
    6032             :         }
    6033             :     }
    6034          22 :     if (hTransformArg == nullptr)
    6035             :     {
    6036             :         hTransformArg =
    6037          20 :             GDALCreateGenImgProjTransformer2(poSrcDS, nullptr, papszTO);
    6038             :     }
    6039             : 
    6040          22 :     if (hTransformArg == nullptr)
    6041             :     {
    6042           1 :         CPLFree(pszWKT);
    6043           1 :         CSLDestroy(papszTO);
    6044           1 :         return nullptr;
    6045             :     }
    6046             : 
    6047          21 :     GDALTransformerInfo *psInfo =
    6048             :         static_cast<GDALTransformerInfo *>(hTransformArg);
    6049          21 :     GDALGeoTransform gt;
    6050             :     double adfExtent[4];
    6051             :     int nXSize, nYSize;
    6052             : 
    6053          21 :     if (GDALSuggestedWarpOutput2(poSrcDS, psInfo->pfnTransform, hTransformArg,
    6054             :                                  gt.data(), &nXSize, &nYSize, adfExtent,
    6055          21 :                                  0) != CE_None)
    6056             :     {
    6057           0 :         CPLFree(pszWKT);
    6058           0 :         CSLDestroy(papszTO);
    6059           0 :         GDALDestroyGenImgProjTransformer(hTransformArg);
    6060           0 :         return nullptr;
    6061             :     }
    6062             : 
    6063          21 :     GDALDestroyGenImgProjTransformer(hTransformArg);
    6064          21 :     hTransformArg = nullptr;
    6065          21 :     poTmpDS.reset();
    6066             : 
    6067          21 :     if (bEPSG3857Adjust)
    6068             :     {
    6069           2 :         constexpr double SPHERICAL_RADIUS = 6378137.0;
    6070           2 :         constexpr double MAX_GM =
    6071             :             SPHERICAL_RADIUS * M_PI;  // 20037508.342789244
    6072           2 :         double maxNorthing = gt[3];
    6073           2 :         double minNorthing = gt[3] + gt[5] * nYSize;
    6074           2 :         bool bChanged = false;
    6075           2 :         if (maxNorthing > MAX_GM)
    6076             :         {
    6077           2 :             bChanged = true;
    6078           2 :             maxNorthing = MAX_GM;
    6079             :         }
    6080           2 :         if (minNorthing < -MAX_GM)
    6081             :         {
    6082           2 :             bChanged = true;
    6083           2 :             minNorthing = -MAX_GM;
    6084             :         }
    6085           2 :         if (bChanged)
    6086             :         {
    6087           2 :             gt[3] = maxNorthing;
    6088           2 :             nYSize = int((maxNorthing - minNorthing) / (-gt[5]) + 0.5);
    6089           2 :             adfExtent[1] = maxNorthing + nYSize * gt[5];
    6090           2 :             adfExtent[3] = maxNorthing;
    6091             :         }
    6092             :     }
    6093             : 
    6094          21 :     double dfComputedRes = gt[1];
    6095          21 :     double dfPrevRes = 0.0;
    6096          21 :     double dfRes = 0.0;
    6097          21 :     int nZoomLevel = 0;  // Used after for.
    6098          21 :     const char *pszZoomLevel = CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    6099          21 :     if (pszZoomLevel)
    6100             :     {
    6101           2 :         nZoomLevel = atoi(pszZoomLevel);
    6102             : 
    6103           2 :         int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    6104           2 :         while ((1 << nMaxZoomLevelForThisTM) >
    6105           4 :                    INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6106           2 :                (1 << nMaxZoomLevelForThisTM) >
    6107           2 :                    INT_MAX / poTS->nTileYCountZoomLevel0)
    6108             :         {
    6109           0 :             --nMaxZoomLevelForThisTM;
    6110             :         }
    6111             : 
    6112           2 :         if (nZoomLevel < 0 || nZoomLevel > nMaxZoomLevelForThisTM)
    6113             :         {
    6114           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6115             :                      "ZOOM_LEVEL = %s is invalid. It should be in [0,%d] range",
    6116             :                      pszZoomLevel, nMaxZoomLevelForThisTM);
    6117           1 :             CPLFree(pszWKT);
    6118           1 :             CSLDestroy(papszTO);
    6119           1 :             return nullptr;
    6120             :         }
    6121             :     }
    6122             :     else
    6123             :     {
    6124         171 :         for (; nZoomLevel < MAX_ZOOM_LEVEL; nZoomLevel++)
    6125             :         {
    6126         171 :             dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6127         171 :             if (dfComputedRes > dfRes ||
    6128         152 :                 fabs(dfComputedRes - dfRes) / dfRes <= 1e-8)
    6129             :                 break;
    6130         152 :             dfPrevRes = dfRes;
    6131             :         }
    6132          38 :         if (nZoomLevel == MAX_ZOOM_LEVEL ||
    6133          38 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6134          19 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileYCountZoomLevel0)
    6135             :         {
    6136           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6137             :                      "Could not find an appropriate zoom level");
    6138           0 :             CPLFree(pszWKT);
    6139           0 :             CSLDestroy(papszTO);
    6140           0 :             return nullptr;
    6141             :         }
    6142             : 
    6143          19 :         if (nZoomLevel > 0 && fabs(dfComputedRes - dfRes) / dfRes > 1e-8)
    6144             :         {
    6145          17 :             const char *pszZoomLevelStrategy = CSLFetchNameValueDef(
    6146             :                 papszOptions, "ZOOM_LEVEL_STRATEGY", "AUTO");
    6147          17 :             if (EQUAL(pszZoomLevelStrategy, "LOWER"))
    6148             :             {
    6149           1 :                 nZoomLevel--;
    6150             :             }
    6151          16 :             else if (EQUAL(pszZoomLevelStrategy, "UPPER"))
    6152             :             {
    6153             :                 /* do nothing */
    6154             :             }
    6155             :             else
    6156             :             {
    6157          15 :                 if (dfPrevRes / dfComputedRes < dfComputedRes / dfRes)
    6158          13 :                     nZoomLevel--;
    6159             :             }
    6160             :         }
    6161             :     }
    6162             : 
    6163          20 :     dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6164             : 
    6165          20 :     double dfMinX = adfExtent[0];
    6166          20 :     double dfMinY = adfExtent[1];
    6167          20 :     double dfMaxX = adfExtent[2];
    6168          20 :     double dfMaxY = adfExtent[3];
    6169             : 
    6170          20 :     nXSize = static_cast<int>(0.5 + (dfMaxX - dfMinX) / dfRes);
    6171          20 :     nYSize = static_cast<int>(0.5 + (dfMaxY - dfMinY) / dfRes);
    6172          20 :     gt[1] = dfRes;
    6173          20 :     gt[5] = -dfRes;
    6174             : 
    6175          20 :     const GDALDataType eDT = poSrcDS->GetRasterBand(1)->GetRasterDataType();
    6176          20 :     int nTargetBands = nBands;
    6177             :     /* For grey level or RGB, if there's reprojection involved, add an alpha */
    6178             :     /* channel */
    6179          37 :     if (eDT == GDT_UInt8 &&
    6180          13 :         ((nBands == 1 &&
    6181          17 :           poSrcDS->GetRasterBand(1)->GetColorTable() == nullptr) ||
    6182             :          nBands == 3))
    6183             :     {
    6184          30 :         OGRSpatialReference oSrcSRS;
    6185          15 :         oSrcSRS.SetFromUserInput(poSrcDS->GetProjectionRef());
    6186          15 :         oSrcSRS.AutoIdentifyEPSG();
    6187          30 :         if (oSrcSRS.GetAuthorityCode(nullptr) == nullptr ||
    6188          15 :             atoi(oSrcSRS.GetAuthorityCode(nullptr)) != nEPSGCode)
    6189             :         {
    6190          13 :             nTargetBands++;
    6191             :         }
    6192             :     }
    6193             : 
    6194          20 :     GDALResampleAlg eResampleAlg = GRA_Bilinear;
    6195          20 :     const char *pszResampling = CSLFetchNameValue(papszOptions, "RESAMPLING");
    6196          20 :     if (pszResampling)
    6197             :     {
    6198           6 :         for (size_t iAlg = 0;
    6199           6 :              iAlg < sizeof(asResamplingAlg) / sizeof(asResamplingAlg[0]);
    6200             :              iAlg++)
    6201             :         {
    6202           6 :             if (EQUAL(pszResampling, asResamplingAlg[iAlg].pszName))
    6203             :             {
    6204           3 :                 eResampleAlg = asResamplingAlg[iAlg].eResampleAlg;
    6205           3 :                 break;
    6206             :             }
    6207             :         }
    6208             :     }
    6209             : 
    6210          16 :     if (nBands == 1 && poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    6211          36 :         eResampleAlg != GRA_NearestNeighbour && eResampleAlg != GRA_Mode)
    6212             :     {
    6213           0 :         CPLError(
    6214             :             CE_Warning, CPLE_AppDefined,
    6215             :             "Input dataset has a color table, which will likely lead to "
    6216             :             "bad results when using a resampling method other than "
    6217             :             "nearest neighbour or mode. Converting the dataset to 24/32 bit "
    6218             :             "(e.g. with gdal_translate -expand rgb/rgba) is advised.");
    6219             :     }
    6220             : 
    6221          40 :     auto poDS = std::make_unique<GDALGeoPackageDataset>();
    6222          40 :     if (!(poDS->Create(pszFilename, nXSize, nYSize, nTargetBands, eDT,
    6223          20 :                        apszUpdatedOptions)))
    6224             :     {
    6225           1 :         CPLFree(pszWKT);
    6226           1 :         CSLDestroy(papszTO);
    6227           1 :         return nullptr;
    6228             :     }
    6229             : 
    6230             :     // Assign nodata values before the SetGeoTransform call.
    6231             :     // SetGeoTransform will trigger creation of the overview datasets for each
    6232             :     // zoom level and at that point the nodata value needs to be known.
    6233          19 :     int bHasNoData = FALSE;
    6234             :     double dfNoDataValue =
    6235          19 :         poSrcDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    6236          19 :     if (eDT != GDT_UInt8 && bHasNoData)
    6237             :     {
    6238           3 :         poDS->GetRasterBand(1)->SetNoDataValue(dfNoDataValue);
    6239             :     }
    6240             : 
    6241          19 :     poDS->SetGeoTransform(gt);
    6242          19 :     poDS->SetProjection(pszWKT);
    6243          19 :     CPLFree(pszWKT);
    6244          19 :     pszWKT = nullptr;
    6245          24 :     if (nTargetBands == 1 && nBands == 1 &&
    6246           5 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
    6247             :     {
    6248           2 :         poDS->GetRasterBand(1)->SetColorTable(
    6249           1 :             poSrcDS->GetRasterBand(1)->GetColorTable());
    6250             :     }
    6251             : 
    6252             :     hTransformArg =
    6253          19 :         GDALCreateGenImgProjTransformer2(poSrcDS, poDS.get(), papszTO);
    6254          19 :     CSLDestroy(papszTO);
    6255          19 :     if (hTransformArg == nullptr)
    6256             :     {
    6257           0 :         return nullptr;
    6258             :     }
    6259             : 
    6260          19 :     poDS->SetMetadata(poSrcDS->GetMetadata());
    6261             : 
    6262             :     /* -------------------------------------------------------------------- */
    6263             :     /*      Warp the transformer with a linear approximator                 */
    6264             :     /* -------------------------------------------------------------------- */
    6265          19 :     hTransformArg = GDALCreateApproxTransformer(GDALGenImgProjTransform,
    6266             :                                                 hTransformArg, 0.125);
    6267          19 :     GDALApproxTransformerOwnsSubtransformer(hTransformArg, TRUE);
    6268             : 
    6269             :     /* -------------------------------------------------------------------- */
    6270             :     /*      Setup warp options.                                             */
    6271             :     /* -------------------------------------------------------------------- */
    6272          19 :     GDALWarpOptions *psWO = GDALCreateWarpOptions();
    6273             : 
    6274          19 :     psWO->papszWarpOptions = CSLSetNameValue(nullptr, "OPTIMIZE_SIZE", "YES");
    6275          19 :     psWO->papszWarpOptions =
    6276          19 :         CSLSetNameValue(psWO->papszWarpOptions, "SAMPLE_GRID", "YES");
    6277          19 :     if (bHasNoData)
    6278             :     {
    6279           3 :         if (dfNoDataValue == 0.0)
    6280             :         {
    6281             :             // Do not initialize in the case where nodata != 0, since we
    6282             :             // want the GeoPackage driver to return empty tiles at the nodata
    6283             :             // value instead of 0 as GDAL core would
    6284           0 :             psWO->papszWarpOptions =
    6285           0 :                 CSLSetNameValue(psWO->papszWarpOptions, "INIT_DEST", "0");
    6286             :         }
    6287             : 
    6288           3 :         psWO->padfSrcNoDataReal =
    6289           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6290           3 :         psWO->padfSrcNoDataReal[0] = dfNoDataValue;
    6291             : 
    6292           3 :         psWO->padfDstNoDataReal =
    6293           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6294           3 :         psWO->padfDstNoDataReal[0] = dfNoDataValue;
    6295             :     }
    6296          19 :     psWO->eWorkingDataType = eDT;
    6297          19 :     psWO->eResampleAlg = eResampleAlg;
    6298             : 
    6299          19 :     psWO->hSrcDS = poSrcDS;
    6300          19 :     psWO->hDstDS = poDS.get();
    6301             : 
    6302          19 :     psWO->pfnTransformer = GDALApproxTransform;
    6303          19 :     psWO->pTransformerArg = hTransformArg;
    6304             : 
    6305          19 :     psWO->pfnProgress = pfnProgress;
    6306          19 :     psWO->pProgressArg = pProgressData;
    6307             : 
    6308             :     /* -------------------------------------------------------------------- */
    6309             :     /*      Setup band mapping.                                             */
    6310             :     /* -------------------------------------------------------------------- */
    6311             : 
    6312          19 :     if (nBands == 2 || nBands == 4)
    6313           1 :         psWO->nBandCount = nBands - 1;
    6314             :     else
    6315          18 :         psWO->nBandCount = nBands;
    6316             : 
    6317          19 :     psWO->panSrcBands =
    6318          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6319          19 :     psWO->panDstBands =
    6320          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6321             : 
    6322          46 :     for (int i = 0; i < psWO->nBandCount; i++)
    6323             :     {
    6324          27 :         psWO->panSrcBands[i] = i + 1;
    6325          27 :         psWO->panDstBands[i] = i + 1;
    6326             :     }
    6327             : 
    6328          19 :     if (nBands == 2 || nBands == 4)
    6329             :     {
    6330           1 :         psWO->nSrcAlphaBand = nBands;
    6331             :     }
    6332          19 :     if (nTargetBands == 2 || nTargetBands == 4)
    6333             :     {
    6334          13 :         psWO->nDstAlphaBand = nTargetBands;
    6335             :     }
    6336             : 
    6337             :     /* -------------------------------------------------------------------- */
    6338             :     /*      Initialize and execute the warp.                                */
    6339             :     /* -------------------------------------------------------------------- */
    6340          38 :     GDALWarpOperation oWO;
    6341             : 
    6342          19 :     CPLErr eErr = oWO.Initialize(psWO);
    6343          19 :     if (eErr == CE_None)
    6344             :     {
    6345             :         /*if( bMulti )
    6346             :             eErr = oWO.ChunkAndWarpMulti( 0, 0, nXSize, nYSize );
    6347             :         else*/
    6348          19 :         eErr = oWO.ChunkAndWarpImage(0, 0, nXSize, nYSize);
    6349             :     }
    6350          19 :     if (eErr != CE_None)
    6351             :     {
    6352           0 :         poDS.reset();
    6353             :     }
    6354             : 
    6355          19 :     GDALDestroyTransformer(hTransformArg);
    6356          19 :     GDALDestroyWarpOptions(psWO);
    6357             : 
    6358          19 :     if (poDS)
    6359          19 :         poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    6360             : 
    6361          19 :     return poDS.release();
    6362             : }
    6363             : 
    6364             : /************************************************************************/
    6365             : /*                      ParseCompressionOptions()                       */
    6366             : /************************************************************************/
    6367             : 
    6368         467 : void GDALGeoPackageDataset::ParseCompressionOptions(CSLConstList papszOptions)
    6369             : {
    6370         467 :     const char *pszZLevel = CSLFetchNameValue(papszOptions, "ZLEVEL");
    6371         467 :     if (pszZLevel)
    6372           0 :         m_nZLevel = atoi(pszZLevel);
    6373             : 
    6374         467 :     const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
    6375         467 :     if (pszQuality)
    6376           0 :         m_nQuality = atoi(pszQuality);
    6377             : 
    6378         467 :     const char *pszDither = CSLFetchNameValue(papszOptions, "DITHER");
    6379         467 :     if (pszDither)
    6380           0 :         m_bDither = CPLTestBool(pszDither);
    6381         467 : }
    6382             : 
    6383             : /************************************************************************/
    6384             : /*                       RegisterWebPExtension()                        */
    6385             : /************************************************************************/
    6386             : 
    6387          11 : bool GDALGeoPackageDataset::RegisterWebPExtension()
    6388             : {
    6389          11 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6390           0 :         return false;
    6391             : 
    6392          11 :     char *pszSQL = sqlite3_mprintf(
    6393             :         "INSERT INTO gpkg_extensions "
    6394             :         "(table_name, column_name, extension_name, definition, scope) "
    6395             :         "VALUES "
    6396             :         "('%q', 'tile_data', 'gpkg_webp', "
    6397             :         "'http://www.geopackage.org/spec120/#extension_tiles_webp', "
    6398             :         "'read-write')",
    6399             :         m_osRasterTable.c_str());
    6400          11 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6401          11 :     sqlite3_free(pszSQL);
    6402             : 
    6403          11 :     return OGRERR_NONE == eErr;
    6404             : }
    6405             : 
    6406             : /************************************************************************/
    6407             : /*                     RegisterZoomOtherExtension()                     */
    6408             : /************************************************************************/
    6409             : 
    6410           1 : bool GDALGeoPackageDataset::RegisterZoomOtherExtension()
    6411             : {
    6412           1 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6413           0 :         return false;
    6414             : 
    6415           1 :     char *pszSQL = sqlite3_mprintf(
    6416             :         "INSERT INTO gpkg_extensions "
    6417             :         "(table_name, column_name, extension_name, definition, scope) "
    6418             :         "VALUES "
    6419             :         "('%q', 'tile_data', 'gpkg_zoom_other', "
    6420             :         "'http://www.geopackage.org/spec120/#extension_zoom_other_intervals', "
    6421             :         "'read-write')",
    6422             :         m_osRasterTable.c_str());
    6423           1 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6424           1 :     sqlite3_free(pszSQL);
    6425           1 :     return OGRERR_NONE == eErr;
    6426             : }
    6427             : 
    6428             : /************************************************************************/
    6429             : /*                              GetLayer()                              */
    6430             : /************************************************************************/
    6431             : 
    6432       16818 : const OGRLayer *GDALGeoPackageDataset::GetLayer(int iLayer) const
    6433             : 
    6434             : {
    6435       16818 :     if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
    6436           7 :         return nullptr;
    6437             :     else
    6438       16811 :         return m_apoLayers[iLayer].get();
    6439             : }
    6440             : 
    6441             : /************************************************************************/
    6442             : /*                            LaunderName()                             */
    6443             : /************************************************************************/
    6444             : 
    6445             : /** Launder identifiers (table, column names) according to guidance at
    6446             :  * https://www.geopackage.org/guidance/getting-started.html:
    6447             :  * "For maximum interoperability, start your database identifiers (table names,
    6448             :  * column names, etc.) with a lowercase character and only use lowercase
    6449             :  * characters, numbers 0-9, and underscores (_)."
    6450             :  */
    6451             : 
    6452             : /* static */
    6453           5 : std::string GDALGeoPackageDataset::LaunderName(const std::string &osStr)
    6454             : {
    6455           5 :     char *pszASCII = CPLUTF8ForceToASCII(osStr.c_str(), '_');
    6456          10 :     const std::string osStrASCII(pszASCII);
    6457           5 :     CPLFree(pszASCII);
    6458             : 
    6459          10 :     std::string osRet;
    6460           5 :     osRet.reserve(osStrASCII.size());
    6461             : 
    6462          29 :     for (size_t i = 0; i < osStrASCII.size(); ++i)
    6463             :     {
    6464          24 :         if (osRet.empty())
    6465             :         {
    6466           5 :             if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6467             :             {
    6468           2 :                 osRet += (osStrASCII[i] - 'A' + 'a');
    6469             :             }
    6470           3 :             else if (osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z')
    6471             :             {
    6472           2 :                 osRet += osStrASCII[i];
    6473             :             }
    6474             :             else
    6475             :             {
    6476           1 :                 continue;
    6477             :             }
    6478             :         }
    6479          19 :         else if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6480             :         {
    6481          11 :             osRet += (osStrASCII[i] - 'A' + 'a');
    6482             :         }
    6483           9 :         else if ((osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z') ||
    6484          14 :                  (osStrASCII[i] >= '0' && osStrASCII[i] <= '9') ||
    6485           5 :                  osStrASCII[i] == '_')
    6486             :         {
    6487           7 :             osRet += osStrASCII[i];
    6488             :         }
    6489             :         else
    6490             :         {
    6491           1 :             osRet += '_';
    6492             :         }
    6493             :     }
    6494             : 
    6495           5 :     if (osRet.empty() && !osStrASCII.empty())
    6496           2 :         return LaunderName(std::string("x").append(osStrASCII));
    6497             : 
    6498           4 :     if (osRet != osStr)
    6499             :     {
    6500           3 :         CPLDebug("PG", "LaunderName('%s') -> '%s'", osStr.c_str(),
    6501             :                  osRet.c_str());
    6502             :     }
    6503             : 
    6504           4 :     return osRet;
    6505             : }
    6506             : 
    6507             : /************************************************************************/
    6508             : /*                            ICreateLayer()                            */
    6509             : /************************************************************************/
    6510             : 
    6511             : OGRLayer *
    6512         949 : GDALGeoPackageDataset::ICreateLayer(const char *pszLayerName,
    6513             :                                     const OGRGeomFieldDefn *poSrcGeomFieldDefn,
    6514             :                                     CSLConstList papszOptions)
    6515             : {
    6516             :     /* -------------------------------------------------------------------- */
    6517             :     /*      Verify we are in update mode.                                   */
    6518             :     /* -------------------------------------------------------------------- */
    6519         949 :     if (!GetUpdate())
    6520             :     {
    6521           0 :         CPLError(CE_Failure, CPLE_NoWriteAccess,
    6522             :                  "Data source %s opened read-only.\n"
    6523             :                  "New layer %s cannot be created.\n",
    6524             :                  m_pszFilename, pszLayerName);
    6525             : 
    6526           0 :         return nullptr;
    6527             :     }
    6528             : 
    6529             :     const bool bLaunder =
    6530         949 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "LAUNDER", "NO"));
    6531             :     const std::string osTableName(bLaunder ? LaunderName(pszLayerName)
    6532        2847 :                                            : std::string(pszLayerName));
    6533             : 
    6534             :     const auto eGType =
    6535         949 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
    6536             :     const auto poSpatialRef =
    6537         949 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
    6538             : 
    6539         949 :     if (!m_bHasGPKGGeometryColumns)
    6540             :     {
    6541           1 :         if (SQLCommand(hDB, pszCREATE_GPKG_GEOMETRY_COLUMNS) != OGRERR_NONE)
    6542             :         {
    6543           0 :             return nullptr;
    6544             :         }
    6545           1 :         m_bHasGPKGGeometryColumns = true;
    6546             :     }
    6547             : 
    6548             :     // Check identifier unicity
    6549         949 :     const char *pszIdentifier = CSLFetchNameValue(papszOptions, "IDENTIFIER");
    6550         949 :     if (pszIdentifier != nullptr && pszIdentifier[0] == '\0')
    6551           0 :         pszIdentifier = nullptr;
    6552         949 :     if (pszIdentifier != nullptr)
    6553             :     {
    6554          13 :         for (auto &poLayer : m_apoLayers)
    6555             :         {
    6556             :             const char *pszOtherIdentifier =
    6557           9 :                 poLayer->GetMetadataItem("IDENTIFIER");
    6558           9 :             if (pszOtherIdentifier == nullptr)
    6559           6 :                 pszOtherIdentifier = poLayer->GetName();
    6560          18 :             if (pszOtherIdentifier != nullptr &&
    6561          12 :                 EQUAL(pszOtherIdentifier, pszIdentifier) &&
    6562           3 :                 !EQUAL(poLayer->GetName(), osTableName.c_str()))
    6563             :             {
    6564           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6565             :                          "Identifier %s is already used by table %s",
    6566             :                          pszIdentifier, poLayer->GetName());
    6567           2 :                 return nullptr;
    6568             :             }
    6569             :         }
    6570             : 
    6571             :         // In case there would be table in gpkg_contents not listed as a
    6572             :         // vector layer
    6573           4 :         char *pszSQL = sqlite3_mprintf(
    6574             :             "SELECT table_name FROM gpkg_contents WHERE identifier = '%q' "
    6575             :             "LIMIT 2",
    6576             :             pszIdentifier);
    6577           4 :         auto oResult = SQLQuery(hDB, pszSQL);
    6578           4 :         sqlite3_free(pszSQL);
    6579           8 :         if (oResult && oResult->RowCount() > 0 &&
    6580           9 :             oResult->GetValue(0, 0) != nullptr &&
    6581           1 :             !EQUAL(oResult->GetValue(0, 0), osTableName.c_str()))
    6582             :         {
    6583           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6584             :                      "Identifier %s is already used by table %s", pszIdentifier,
    6585             :                      oResult->GetValue(0, 0));
    6586           1 :             return nullptr;
    6587             :         }
    6588             :     }
    6589             : 
    6590             :     /* Read GEOMETRY_NAME option */
    6591             :     const char *pszGeomColumnName =
    6592         946 :         CSLFetchNameValue(papszOptions, "GEOMETRY_NAME");
    6593         946 :     if (pszGeomColumnName == nullptr) /* deprecated name */
    6594         859 :         pszGeomColumnName = CSLFetchNameValue(papszOptions, "GEOMETRY_COLUMN");
    6595         946 :     if (pszGeomColumnName == nullptr && poSrcGeomFieldDefn)
    6596             :     {
    6597         777 :         pszGeomColumnName = poSrcGeomFieldDefn->GetNameRef();
    6598         777 :         if (pszGeomColumnName && pszGeomColumnName[0] == 0)
    6599         742 :             pszGeomColumnName = nullptr;
    6600             :     }
    6601         946 :     if (pszGeomColumnName == nullptr)
    6602         824 :         pszGeomColumnName = "geom";
    6603             :     const bool bGeomNullable =
    6604         946 :         CPLFetchBool(papszOptions, "GEOMETRY_NULLABLE", true);
    6605             : 
    6606             :     /* Read FID option */
    6607         946 :     const char *pszFIDColumnName = CSLFetchNameValue(papszOptions, "FID");
    6608         946 :     if (pszFIDColumnName == nullptr)
    6609         855 :         pszFIDColumnName = "fid";
    6610             : 
    6611         946 :     if (CPLTestBool(CPLGetConfigOption("GPKG_NAME_CHECK", "YES")))
    6612             :     {
    6613         946 :         if (strspn(pszFIDColumnName, "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") > 0)
    6614             :         {
    6615           2 :             CPLError(CE_Failure, CPLE_AppDefined,
    6616             :                      "The primary key (%s) name may not contain special "
    6617             :                      "characters or spaces",
    6618             :                      pszFIDColumnName);
    6619           2 :             return nullptr;
    6620             :         }
    6621             : 
    6622             :         /* Avoiding gpkg prefixes is not an official requirement, but seems wise
    6623             :          */
    6624         944 :         if (STARTS_WITH(osTableName.c_str(), "gpkg"))
    6625             :         {
    6626           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6627             :                      "The layer name may not begin with 'gpkg' as it is a "
    6628             :                      "reserved geopackage prefix");
    6629           0 :             return nullptr;
    6630             :         }
    6631             : 
    6632             :         /* Preemptively try and avoid sqlite3 syntax errors due to  */
    6633             :         /* illegal characters. */
    6634         944 :         if (strspn(osTableName.c_str(), "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") >
    6635             :             0)
    6636             :         {
    6637           0 :             CPLError(
    6638             :                 CE_Failure, CPLE_AppDefined,
    6639             :                 "The layer name may not contain special characters or spaces");
    6640           0 :             return nullptr;
    6641             :         }
    6642             :     }
    6643             : 
    6644             :     /* Check for any existing layers that already use this name */
    6645        1187 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6646             :          iLayer++)
    6647             :     {
    6648         244 :         if (EQUAL(osTableName.c_str(), m_apoLayers[iLayer]->GetName()))
    6649             :         {
    6650             :             const char *pszOverwrite =
    6651           2 :                 CSLFetchNameValue(papszOptions, "OVERWRITE");
    6652           2 :             if (pszOverwrite != nullptr && CPLTestBool(pszOverwrite))
    6653             :             {
    6654           1 :                 DeleteLayer(iLayer);
    6655             :             }
    6656             :             else
    6657             :             {
    6658           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6659             :                          "Layer %s already exists, CreateLayer failed.\n"
    6660             :                          "Use the layer creation option OVERWRITE=YES to "
    6661             :                          "replace it.",
    6662             :                          osTableName.c_str());
    6663           1 :                 return nullptr;
    6664             :             }
    6665             :         }
    6666             :     }
    6667             : 
    6668         943 :     if (m_apoLayers.size() == 1)
    6669             :     {
    6670             :         // Async RTree building doesn't play well with multiple layer:
    6671             :         // SQLite3 locks being hold for a long time, random failed commits,
    6672             :         // etc.
    6673          95 :         m_apoLayers[0]->FinishOrDisableThreadedRTree();
    6674             :     }
    6675             : 
    6676             :     /* Create a blank layer. */
    6677             :     auto poLayer =
    6678        1886 :         std::make_unique<OGRGeoPackageTableLayer>(this, osTableName.c_str());
    6679             : 
    6680        1886 :     OGRSpatialReferenceRefCountedPtr poSRS;
    6681         943 :     if (poSpatialRef)
    6682             :     {
    6683         313 :         poSRS = OGRSpatialReferenceRefCountedPtr::makeClone(poSpatialRef);
    6684         313 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    6685             :     }
    6686        2830 :     poLayer->SetCreationParameters(
    6687             :         eGType,
    6688         944 :         bLaunder ? LaunderName(pszGeomColumnName).c_str() : pszGeomColumnName,
    6689         943 :         bGeomNullable, poSRS.get(), CSLFetchNameValue(papszOptions, "SRID"),
    6690        1886 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetCoordinatePrecision()
    6691             :                            : OGRGeomCoordinatePrecision(),
    6692         943 :         CPLTestBool(
    6693             :             CSLFetchNameValueDef(papszOptions, "DISCARD_COORD_LSB", "NO")),
    6694         943 :         CPLTestBool(CSLFetchNameValueDef(
    6695             :             papszOptions, "UNDO_DISCARD_COORD_LSB_ON_READING", "NO")),
    6696         944 :         bLaunder ? LaunderName(pszFIDColumnName).c_str() : pszFIDColumnName,
    6697             :         pszIdentifier, CSLFetchNameValue(papszOptions, "DESCRIPTION"));
    6698             : 
    6699         943 :     poLayer->SetLaunder(bLaunder);
    6700             : 
    6701             :     /* Should we create a spatial index ? */
    6702         943 :     const char *pszSI = CSLFetchNameValue(papszOptions, "SPATIAL_INDEX");
    6703         943 :     int bCreateSpatialIndex = (pszSI == nullptr || CPLTestBool(pszSI));
    6704         943 :     if (eGType != wkbNone && bCreateSpatialIndex)
    6705             :     {
    6706         839 :         poLayer->SetDeferredSpatialIndexCreation(true);
    6707             :     }
    6708             : 
    6709         943 :     poLayer->SetPrecisionFlag(CPLFetchBool(papszOptions, "PRECISION", true));
    6710         943 :     poLayer->SetTruncateFieldsFlag(
    6711         943 :         CPLFetchBool(papszOptions, "TRUNCATE_FIELDS", false));
    6712         943 :     if (eGType == wkbNone)
    6713             :     {
    6714          82 :         const char *pszASpatialVariant = CSLFetchNameValueDef(
    6715             :             papszOptions, "ASPATIAL_VARIANT",
    6716          82 :             m_bNonSpatialTablesNonRegisteredInGpkgContentsFound
    6717             :                 ? "NOT_REGISTERED"
    6718             :                 : "GPKG_ATTRIBUTES");
    6719          82 :         GPKGASpatialVariant eASpatialVariant = GPKG_ATTRIBUTES;
    6720          82 :         if (EQUAL(pszASpatialVariant, "GPKG_ATTRIBUTES"))
    6721          70 :             eASpatialVariant = GPKG_ATTRIBUTES;
    6722          12 :         else if (EQUAL(pszASpatialVariant, "OGR_ASPATIAL"))
    6723             :         {
    6724           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6725             :                      "ASPATIAL_VARIANT=OGR_ASPATIAL is no longer supported");
    6726           0 :             return nullptr;
    6727             :         }
    6728          12 :         else if (EQUAL(pszASpatialVariant, "NOT_REGISTERED"))
    6729          12 :             eASpatialVariant = NOT_REGISTERED;
    6730             :         else
    6731             :         {
    6732           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6733             :                      "Unsupported value for ASPATIAL_VARIANT: %s",
    6734             :                      pszASpatialVariant);
    6735           0 :             return nullptr;
    6736             :         }
    6737          82 :         poLayer->SetASpatialVariant(eASpatialVariant);
    6738             :     }
    6739             : 
    6740             :     const char *pszDateTimePrecision =
    6741         943 :         CSLFetchNameValueDef(papszOptions, "DATETIME_PRECISION", "AUTO");
    6742         943 :     if (EQUAL(pszDateTimePrecision, "MILLISECOND"))
    6743             :     {
    6744           2 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6745             :     }
    6746         941 :     else if (EQUAL(pszDateTimePrecision, "SECOND"))
    6747             :     {
    6748           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6749           0 :             CPLError(
    6750             :                 CE_Warning, CPLE_AppDefined,
    6751             :                 "DATETIME_PRECISION=SECOND is only valid since GeoPackage 1.4");
    6752           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::SECOND);
    6753             :     }
    6754         940 :     else if (EQUAL(pszDateTimePrecision, "MINUTE"))
    6755             :     {
    6756           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6757           0 :             CPLError(
    6758             :                 CE_Warning, CPLE_AppDefined,
    6759             :                 "DATETIME_PRECISION=MINUTE is only valid since GeoPackage 1.4");
    6760           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MINUTE);
    6761             :     }
    6762         939 :     else if (EQUAL(pszDateTimePrecision, "AUTO"))
    6763             :     {
    6764         938 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6765          13 :             poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6766             :     }
    6767             :     else
    6768             :     {
    6769           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    6770             :                  "Unsupported value for DATETIME_PRECISION: %s",
    6771             :                  pszDateTimePrecision);
    6772           1 :         return nullptr;
    6773             :     }
    6774             : 
    6775             :     // If there was an ogr_empty_table table, we can remove it
    6776             :     // But do it at dataset closing, otherwise locking performance issues
    6777             :     // can arise (probably when transactions are used).
    6778         942 :     m_bRemoveOGREmptyTable = true;
    6779             : 
    6780         942 :     m_apoLayers.emplace_back(std::move(poLayer));
    6781         942 :     return m_apoLayers.back().get();
    6782             : }
    6783             : 
    6784             : /************************************************************************/
    6785             : /*                           FindLayerIndex()                           */
    6786             : /************************************************************************/
    6787             : 
    6788          29 : int GDALGeoPackageDataset::FindLayerIndex(const char *pszLayerName)
    6789             : 
    6790             : {
    6791          51 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6792             :          iLayer++)
    6793             :     {
    6794          35 :         if (EQUAL(pszLayerName, m_apoLayers[iLayer]->GetName()))
    6795          13 :             return iLayer;
    6796             :     }
    6797          16 :     return -1;
    6798             : }
    6799             : 
    6800             : /************************************************************************/
    6801             : /*                         DeleteLayerCommon()                          */
    6802             : /************************************************************************/
    6803             : 
    6804          43 : OGRErr GDALGeoPackageDataset::DeleteLayerCommon(const char *pszLayerName)
    6805             : {
    6806             :     // Temporary remove foreign key checks
    6807             :     const GPKGTemporaryForeignKeyCheckDisabler
    6808          43 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6809             : 
    6810          43 :     char *pszSQL = sqlite3_mprintf(
    6811             :         "DELETE FROM gpkg_contents WHERE lower(table_name) = lower('%q')",
    6812             :         pszLayerName);
    6813          43 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    6814          43 :     sqlite3_free(pszSQL);
    6815             : 
    6816          43 :     if (eErr == OGRERR_NONE && HasExtensionsTable())
    6817             :     {
    6818          41 :         pszSQL = sqlite3_mprintf(
    6819             :             "DELETE FROM gpkg_extensions WHERE lower(table_name) = lower('%q')",
    6820             :             pszLayerName);
    6821          41 :         eErr = SQLCommand(hDB, pszSQL);
    6822          41 :         sqlite3_free(pszSQL);
    6823             :     }
    6824             : 
    6825          43 :     if (eErr == OGRERR_NONE && HasMetadataTables())
    6826             :     {
    6827             :         // Delete from gpkg_metadata metadata records that are only referenced
    6828             :         // by the table we are about to drop
    6829          12 :         pszSQL = sqlite3_mprintf(
    6830             :             "DELETE FROM gpkg_metadata WHERE id IN ("
    6831             :             "SELECT DISTINCT md_file_id FROM "
    6832             :             "gpkg_metadata_reference WHERE "
    6833             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6834             :             "AND id NOT IN ("
    6835             :             "SELECT DISTINCT md_file_id FROM gpkg_metadata_reference WHERE "
    6836             :             "md_file_id IN (SELECT DISTINCT md_file_id FROM "
    6837             :             "gpkg_metadata_reference WHERE "
    6838             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6839             :             "AND lower(table_name) <> lower('%q'))",
    6840             :             pszLayerName, pszLayerName, pszLayerName);
    6841          12 :         eErr = SQLCommand(hDB, pszSQL);
    6842          12 :         sqlite3_free(pszSQL);
    6843             : 
    6844          12 :         if (eErr == OGRERR_NONE)
    6845             :         {
    6846             :             pszSQL =
    6847          12 :                 sqlite3_mprintf("DELETE FROM gpkg_metadata_reference WHERE "
    6848             :                                 "lower(table_name) = lower('%q')",
    6849             :                                 pszLayerName);
    6850          12 :             eErr = SQLCommand(hDB, pszSQL);
    6851          12 :             sqlite3_free(pszSQL);
    6852             :         }
    6853             :     }
    6854             : 
    6855          43 :     if (eErr == OGRERR_NONE && HasGpkgextRelationsTable())
    6856             :     {
    6857             :         // Remove reference to potential corresponding mapping table in
    6858             :         // gpkg_extensions
    6859           4 :         pszSQL = sqlite3_mprintf(
    6860             :             "DELETE FROM gpkg_extensions WHERE "
    6861             :             "extension_name IN ('related_tables', "
    6862             :             "'gpkg_related_tables') AND lower(table_name) = "
    6863             :             "(SELECT lower(mapping_table_name) FROM gpkgext_relations WHERE "
    6864             :             "lower(base_table_name) = lower('%q') OR "
    6865             :             "lower(related_table_name) = lower('%q') OR "
    6866             :             "lower(mapping_table_name) = lower('%q'))",
    6867             :             pszLayerName, pszLayerName, pszLayerName);
    6868           4 :         eErr = SQLCommand(hDB, pszSQL);
    6869           4 :         sqlite3_free(pszSQL);
    6870             : 
    6871           4 :         if (eErr == OGRERR_NONE)
    6872             :         {
    6873             :             // Remove reference to potential corresponding mapping table in
    6874             :             // gpkgext_relations
    6875             :             pszSQL =
    6876           4 :                 sqlite3_mprintf("DELETE FROM gpkgext_relations WHERE "
    6877             :                                 "lower(base_table_name) = lower('%q') OR "
    6878             :                                 "lower(related_table_name) = lower('%q') OR "
    6879             :                                 "lower(mapping_table_name) = lower('%q')",
    6880             :                                 pszLayerName, pszLayerName, pszLayerName);
    6881           4 :             eErr = SQLCommand(hDB, pszSQL);
    6882           4 :             sqlite3_free(pszSQL);
    6883             :         }
    6884             : 
    6885           4 :         if (eErr == OGRERR_NONE && HasExtensionsTable())
    6886             :         {
    6887             :             // If there is no longer any mapping table, then completely
    6888             :             // remove any reference to the extension in gpkg_extensions
    6889             :             // as mandated per the related table specification.
    6890             :             OGRErr err;
    6891           4 :             if (SQLGetInteger(hDB,
    6892             :                               "SELECT COUNT(*) FROM gpkg_extensions WHERE "
    6893             :                               "extension_name IN ('related_tables', "
    6894             :                               "'gpkg_related_tables') AND "
    6895             :                               "lower(table_name) != 'gpkgext_relations'",
    6896           4 :                               &err) == 0)
    6897             :             {
    6898           2 :                 eErr = SQLCommand(hDB, "DELETE FROM gpkg_extensions WHERE "
    6899             :                                        "extension_name IN ('related_tables', "
    6900             :                                        "'gpkg_related_tables')");
    6901             :             }
    6902             : 
    6903           4 :             ClearCachedRelationships();
    6904             :         }
    6905             :     }
    6906             : 
    6907          43 :     if (eErr == OGRERR_NONE)
    6908             :     {
    6909          43 :         pszSQL = sqlite3_mprintf("DROP TABLE \"%w\"", pszLayerName);
    6910          43 :         eErr = SQLCommand(hDB, pszSQL);
    6911          43 :         sqlite3_free(pszSQL);
    6912             :     }
    6913             : 
    6914             :     // Check foreign key integrity
    6915          43 :     if (eErr == OGRERR_NONE)
    6916             :     {
    6917          43 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    6918             :     }
    6919             : 
    6920          86 :     return eErr;
    6921             : }
    6922             : 
    6923             : /************************************************************************/
    6924             : /*                            DeleteLayer()                             */
    6925             : /************************************************************************/
    6926             : 
    6927          40 : OGRErr GDALGeoPackageDataset::DeleteLayer(int iLayer)
    6928             : {
    6929          79 :     if (!GetUpdate() || iLayer < 0 ||
    6930          39 :         iLayer >= static_cast<int>(m_apoLayers.size()))
    6931           2 :         return OGRERR_FAILURE;
    6932             : 
    6933          38 :     m_apoLayers[iLayer]->ResetReading();
    6934          38 :     m_apoLayers[iLayer]->SyncToDisk();
    6935             : 
    6936          76 :     CPLString osLayerName = m_apoLayers[iLayer]->GetName();
    6937             : 
    6938          38 :     CPLDebug("GPKG", "DeleteLayer(%s)", osLayerName.c_str());
    6939             : 
    6940             :     // Temporary remove foreign key checks
    6941             :     const GPKGTemporaryForeignKeyCheckDisabler
    6942          38 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6943             : 
    6944          38 :     OGRErr eErr = SoftStartTransaction();
    6945             : 
    6946          38 :     if (eErr == OGRERR_NONE)
    6947             :     {
    6948          38 :         if (m_apoLayers[iLayer]->HasSpatialIndex())
    6949          35 :             m_apoLayers[iLayer]->DropSpatialIndex();
    6950             : 
    6951             :         char *pszSQL =
    6952          38 :             sqlite3_mprintf("DELETE FROM gpkg_geometry_columns WHERE "
    6953             :                             "lower(table_name) = lower('%q')",
    6954             :                             osLayerName.c_str());
    6955          38 :         eErr = SQLCommand(hDB, pszSQL);
    6956          38 :         sqlite3_free(pszSQL);
    6957             :     }
    6958             : 
    6959          38 :     if (eErr == OGRERR_NONE && HasDataColumnsTable())
    6960             :     {
    6961           1 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_data_columns WHERE "
    6962             :                                        "lower(table_name) = lower('%q')",
    6963             :                                        osLayerName.c_str());
    6964           1 :         eErr = SQLCommand(hDB, pszSQL);
    6965           1 :         sqlite3_free(pszSQL);
    6966             :     }
    6967             : 
    6968             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    6969          38 :     if (eErr == OGRERR_NONE && m_bHasGPKGOGRContents)
    6970             :     {
    6971          38 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_ogr_contents WHERE "
    6972             :                                        "lower(table_name) = lower('%q')",
    6973             :                                        osLayerName.c_str());
    6974          38 :         eErr = SQLCommand(hDB, pszSQL);
    6975          38 :         sqlite3_free(pszSQL);
    6976             :     }
    6977             : #endif
    6978             : 
    6979          38 :     if (eErr == OGRERR_NONE)
    6980             :     {
    6981          38 :         eErr = DeleteLayerCommon(osLayerName.c_str());
    6982             :     }
    6983             : 
    6984          38 :     if (eErr == OGRERR_NONE)
    6985             :     {
    6986          38 :         eErr = SoftCommitTransaction();
    6987          38 :         if (eErr == OGRERR_NONE)
    6988             :         {
    6989             :             /* Delete the layer object */
    6990          38 :             m_apoLayers.erase(m_apoLayers.begin() + iLayer);
    6991             :         }
    6992             :     }
    6993             :     else
    6994             :     {
    6995           0 :         SoftRollbackTransaction();
    6996             :     }
    6997             : 
    6998          38 :     return eErr;
    6999             : }
    7000             : 
    7001             : /************************************************************************/
    7002             : /*                         DeleteRasterLayer()                          */
    7003             : /************************************************************************/
    7004             : 
    7005           2 : OGRErr GDALGeoPackageDataset::DeleteRasterLayer(const char *pszLayerName)
    7006             : {
    7007             :     // Temporary remove foreign key checks
    7008             :     const GPKGTemporaryForeignKeyCheckDisabler
    7009           2 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7010             : 
    7011           2 :     OGRErr eErr = SoftStartTransaction();
    7012             : 
    7013           2 :     if (eErr == OGRERR_NONE)
    7014             :     {
    7015           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix WHERE "
    7016             :                                        "lower(table_name) = lower('%q')",
    7017             :                                        pszLayerName);
    7018           2 :         eErr = SQLCommand(hDB, pszSQL);
    7019           2 :         sqlite3_free(pszSQL);
    7020             :     }
    7021             : 
    7022           2 :     if (eErr == OGRERR_NONE)
    7023             :     {
    7024           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix_set WHERE "
    7025             :                                        "lower(table_name) = lower('%q')",
    7026             :                                        pszLayerName);
    7027           2 :         eErr = SQLCommand(hDB, pszSQL);
    7028           2 :         sqlite3_free(pszSQL);
    7029             :     }
    7030             : 
    7031           2 :     if (eErr == OGRERR_NONE && HasGriddedCoverageAncillaryTable())
    7032             :     {
    7033             :         char *pszSQL =
    7034           1 :             sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_coverage_ancillary "
    7035             :                             "WHERE lower(tile_matrix_set_name) = lower('%q')",
    7036             :                             pszLayerName);
    7037           1 :         eErr = SQLCommand(hDB, pszSQL);
    7038           1 :         sqlite3_free(pszSQL);
    7039             : 
    7040           1 :         if (eErr == OGRERR_NONE)
    7041             :         {
    7042             :             pszSQL =
    7043           1 :                 sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_tile_ancillary "
    7044             :                                 "WHERE lower(tpudt_name) = lower('%q')",
    7045             :                                 pszLayerName);
    7046           1 :             eErr = SQLCommand(hDB, pszSQL);
    7047           1 :             sqlite3_free(pszSQL);
    7048             :         }
    7049             :     }
    7050             : 
    7051           2 :     if (eErr == OGRERR_NONE)
    7052             :     {
    7053           2 :         eErr = DeleteLayerCommon(pszLayerName);
    7054             :     }
    7055             : 
    7056           2 :     if (eErr == OGRERR_NONE)
    7057             :     {
    7058           2 :         eErr = SoftCommitTransaction();
    7059             :     }
    7060             :     else
    7061             :     {
    7062           0 :         SoftRollbackTransaction();
    7063             :     }
    7064             : 
    7065           4 :     return eErr;
    7066             : }
    7067             : 
    7068             : /************************************************************************/
    7069             : /*                     DeleteVectorOrRasterLayer()                      */
    7070             : /************************************************************************/
    7071             : 
    7072          13 : bool GDALGeoPackageDataset::DeleteVectorOrRasterLayer(const char *pszLayerName)
    7073             : {
    7074             : 
    7075          13 :     int idx = FindLayerIndex(pszLayerName);
    7076          13 :     if (idx >= 0)
    7077             :     {
    7078           5 :         DeleteLayer(idx);
    7079           5 :         return true;
    7080             :     }
    7081             : 
    7082             :     char *pszSQL =
    7083           8 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7084             :                         "lower(table_name) = lower('%q') "
    7085             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7086             :                         pszLayerName);
    7087           8 :     bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7088           8 :     sqlite3_free(pszSQL);
    7089           8 :     if (bIsRasterTable)
    7090             :     {
    7091           2 :         DeleteRasterLayer(pszLayerName);
    7092           2 :         return true;
    7093             :     }
    7094           6 :     return false;
    7095             : }
    7096             : 
    7097           7 : bool GDALGeoPackageDataset::RenameVectorOrRasterLayer(
    7098             :     const char *pszLayerName, const char *pszNewLayerName)
    7099             : {
    7100           7 :     int idx = FindLayerIndex(pszLayerName);
    7101           7 :     if (idx >= 0)
    7102             :     {
    7103           4 :         m_apoLayers[idx]->Rename(pszNewLayerName);
    7104           4 :         return true;
    7105             :     }
    7106             : 
    7107             :     char *pszSQL =
    7108           3 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7109             :                         "lower(table_name) = lower('%q') "
    7110             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7111             :                         pszLayerName);
    7112           3 :     const bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7113           3 :     sqlite3_free(pszSQL);
    7114             : 
    7115           3 :     if (bIsRasterTable)
    7116             :     {
    7117           2 :         return RenameRasterLayer(pszLayerName, pszNewLayerName);
    7118             :     }
    7119             : 
    7120           1 :     return false;
    7121             : }
    7122             : 
    7123           2 : bool GDALGeoPackageDataset::RenameRasterLayer(const char *pszLayerName,
    7124             :                                               const char *pszNewLayerName)
    7125             : {
    7126           4 :     std::string osSQL;
    7127             : 
    7128           2 :     char *pszSQL = sqlite3_mprintf(
    7129             :         "SELECT 1 FROM sqlite_master WHERE lower(name) = lower('%q') "
    7130             :         "AND type IN ('table', 'view')",
    7131             :         pszNewLayerName);
    7132           2 :     const bool bAlreadyExists = SQLGetInteger(GetDB(), pszSQL, nullptr) == 1;
    7133           2 :     sqlite3_free(pszSQL);
    7134           2 :     if (bAlreadyExists)
    7135             :     {
    7136           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Table %s already exists",
    7137             :                  pszNewLayerName);
    7138           0 :         return false;
    7139             :     }
    7140             : 
    7141             :     // Temporary remove foreign key checks
    7142             :     const GPKGTemporaryForeignKeyCheckDisabler
    7143           4 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7144             : 
    7145           2 :     if (SoftStartTransaction() != OGRERR_NONE)
    7146             :     {
    7147           0 :         return false;
    7148             :     }
    7149             : 
    7150           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET table_name = '%q' WHERE "
    7151             :                              "lower(table_name) = lower('%q');",
    7152             :                              pszNewLayerName, pszLayerName);
    7153           2 :     osSQL = pszSQL;
    7154           2 :     sqlite3_free(pszSQL);
    7155             : 
    7156           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' WHERE "
    7157             :                              "lower(identifier) = lower('%q');",
    7158             :                              pszNewLayerName, pszLayerName);
    7159           2 :     osSQL += pszSQL;
    7160           2 :     sqlite3_free(pszSQL);
    7161             : 
    7162             :     pszSQL =
    7163           2 :         sqlite3_mprintf("UPDATE gpkg_tile_matrix SET table_name = '%q' WHERE "
    7164             :                         "lower(table_name) = lower('%q');",
    7165             :                         pszNewLayerName, pszLayerName);
    7166           2 :     osSQL += pszSQL;
    7167           2 :     sqlite3_free(pszSQL);
    7168             : 
    7169           2 :     pszSQL = sqlite3_mprintf(
    7170             :         "UPDATE gpkg_tile_matrix_set 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 :     if (HasGriddedCoverageAncillaryTable())
    7177             :     {
    7178           1 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_2d_gridded_coverage_ancillary "
    7179             :                                  "SET tile_matrix_set_name = '%q' WHERE "
    7180             :                                  "lower(tile_matrix_set_name) = lower('%q');",
    7181             :                                  pszNewLayerName, pszLayerName);
    7182           1 :         osSQL += pszSQL;
    7183           1 :         sqlite3_free(pszSQL);
    7184             : 
    7185           1 :         pszSQL = sqlite3_mprintf(
    7186             :             "UPDATE gpkg_2d_gridded_tile_ancillary SET tpudt_name = '%q' WHERE "
    7187             :             "lower(tpudt_name) = lower('%q');",
    7188             :             pszNewLayerName, pszLayerName);
    7189           1 :         osSQL += pszSQL;
    7190           1 :         sqlite3_free(pszSQL);
    7191             :     }
    7192             : 
    7193           2 :     if (HasExtensionsTable())
    7194             :     {
    7195           2 :         pszSQL = sqlite3_mprintf(
    7196             :             "UPDATE gpkg_extensions SET table_name = '%q' WHERE "
    7197             :             "lower(table_name) = lower('%q');",
    7198             :             pszNewLayerName, pszLayerName);
    7199           2 :         osSQL += pszSQL;
    7200           2 :         sqlite3_free(pszSQL);
    7201             :     }
    7202             : 
    7203           2 :     if (HasMetadataTables())
    7204             :     {
    7205           1 :         pszSQL = sqlite3_mprintf(
    7206             :             "UPDATE gpkg_metadata_reference SET table_name = '%q' WHERE "
    7207             :             "lower(table_name) = lower('%q');",
    7208             :             pszNewLayerName, pszLayerName);
    7209           1 :         osSQL += pszSQL;
    7210           1 :         sqlite3_free(pszSQL);
    7211             :     }
    7212             : 
    7213           2 :     if (HasDataColumnsTable())
    7214             :     {
    7215           0 :         pszSQL = sqlite3_mprintf(
    7216             :             "UPDATE gpkg_data_columns SET table_name = '%q' WHERE "
    7217             :             "lower(table_name) = lower('%q');",
    7218             :             pszNewLayerName, pszLayerName);
    7219           0 :         osSQL += pszSQL;
    7220           0 :         sqlite3_free(pszSQL);
    7221             :     }
    7222             : 
    7223           2 :     if (HasQGISLayerStyles())
    7224             :     {
    7225             :         // Update QGIS styles
    7226             :         pszSQL =
    7227           0 :             sqlite3_mprintf("UPDATE layer_styles SET f_table_name = '%q' WHERE "
    7228             :                             "lower(f_table_name) = lower('%q');",
    7229             :                             pszNewLayerName, pszLayerName);
    7230           0 :         osSQL += pszSQL;
    7231           0 :         sqlite3_free(pszSQL);
    7232             :     }
    7233             : 
    7234             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7235           2 :     if (m_bHasGPKGOGRContents)
    7236             :     {
    7237           2 :         pszSQL = sqlite3_mprintf(
    7238             :             "UPDATE gpkg_ogr_contents SET table_name = '%q' WHERE "
    7239             :             "lower(table_name) = lower('%q');",
    7240             :             pszNewLayerName, pszLayerName);
    7241           2 :         osSQL += pszSQL;
    7242           2 :         sqlite3_free(pszSQL);
    7243             :     }
    7244             : #endif
    7245             : 
    7246           2 :     if (HasGpkgextRelationsTable())
    7247             :     {
    7248           0 :         pszSQL = sqlite3_mprintf(
    7249             :             "UPDATE gpkgext_relations SET base_table_name = '%q' WHERE "
    7250             :             "lower(base_table_name) = lower('%q');",
    7251             :             pszNewLayerName, pszLayerName);
    7252           0 :         osSQL += pszSQL;
    7253           0 :         sqlite3_free(pszSQL);
    7254             : 
    7255           0 :         pszSQL = sqlite3_mprintf(
    7256             :             "UPDATE gpkgext_relations SET related_table_name = '%q' WHERE "
    7257             :             "lower(related_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 mapping_table_name = '%q' WHERE "
    7264             :             "lower(mapping_table_name) = lower('%q');",
    7265             :             pszNewLayerName, pszLayerName);
    7266           0 :         osSQL += pszSQL;
    7267           0 :         sqlite3_free(pszSQL);
    7268             :     }
    7269             : 
    7270             :     // Drop all triggers for the layer
    7271           2 :     pszSQL = sqlite3_mprintf("SELECT name FROM sqlite_master WHERE type = "
    7272             :                              "'trigger' AND tbl_name = '%q'",
    7273             :                              pszLayerName);
    7274           2 :     auto oTriggerResult = SQLQuery(GetDB(), pszSQL);
    7275           2 :     sqlite3_free(pszSQL);
    7276           2 :     if (oTriggerResult)
    7277             :     {
    7278          14 :         for (int i = 0; i < oTriggerResult->RowCount(); i++)
    7279             :         {
    7280          12 :             const char *pszTriggerName = oTriggerResult->GetValue(0, i);
    7281          12 :             pszSQL = sqlite3_mprintf("DROP TRIGGER IF EXISTS \"%w\";",
    7282             :                                      pszTriggerName);
    7283          12 :             osSQL += pszSQL;
    7284          12 :             sqlite3_free(pszSQL);
    7285             :         }
    7286             :     }
    7287             : 
    7288           2 :     pszSQL = sqlite3_mprintf("ALTER TABLE \"%w\" RENAME TO \"%w\";",
    7289             :                              pszLayerName, pszNewLayerName);
    7290           2 :     osSQL += pszSQL;
    7291           2 :     sqlite3_free(pszSQL);
    7292             : 
    7293             :     // Recreate all zoom/tile triggers
    7294           2 :     if (oTriggerResult)
    7295             :     {
    7296           2 :         osSQL += CreateRasterTriggersSQL(pszNewLayerName);
    7297             :     }
    7298             : 
    7299           2 :     OGRErr eErr = SQLCommand(GetDB(), osSQL.c_str());
    7300             : 
    7301             :     // Check foreign key integrity
    7302           2 :     if (eErr == OGRERR_NONE)
    7303             :     {
    7304           2 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    7305             :     }
    7306             : 
    7307           2 :     if (eErr == OGRERR_NONE)
    7308             :     {
    7309           2 :         eErr = SoftCommitTransaction();
    7310             :     }
    7311             :     else
    7312             :     {
    7313           0 :         SoftRollbackTransaction();
    7314             :     }
    7315             : 
    7316           2 :     return eErr == OGRERR_NONE;
    7317             : }
    7318             : 
    7319             : /************************************************************************/
    7320             : /*                           TestCapability()                           */
    7321             : /************************************************************************/
    7322             : 
    7323         555 : int GDALGeoPackageDataset::TestCapability(const char *pszCap) const
    7324             : {
    7325         555 :     if (EQUAL(pszCap, ODsCCreateLayer) || EQUAL(pszCap, ODsCDeleteLayer) ||
    7326         359 :         EQUAL(pszCap, "RenameLayer"))
    7327             :     {
    7328         196 :         return GetUpdate();
    7329             :     }
    7330         359 :     else if (EQUAL(pszCap, ODsCCurveGeometries))
    7331          12 :         return TRUE;
    7332         347 :     else if (EQUAL(pszCap, ODsCMeasuredGeometries))
    7333           8 :         return TRUE;
    7334         339 :     else if (EQUAL(pszCap, ODsCZGeometries))
    7335           8 :         return TRUE;
    7336         331 :     else if (EQUAL(pszCap, ODsCRandomLayerWrite) ||
    7337         331 :              EQUAL(pszCap, GDsCAddRelationship) ||
    7338         331 :              EQUAL(pszCap, GDsCDeleteRelationship) ||
    7339         331 :              EQUAL(pszCap, GDsCUpdateRelationship) ||
    7340         331 :              EQUAL(pszCap, ODsCAddFieldDomain) ||
    7341         329 :              EQUAL(pszCap, ODsCUpdateFieldDomain) ||
    7342         327 :              EQUAL(pszCap, ODsCDeleteFieldDomain))
    7343             :     {
    7344           6 :         return GetUpdate();
    7345             :     }
    7346             : 
    7347         325 :     return OGRSQLiteBaseDataSource::TestCapability(pszCap);
    7348             : }
    7349             : 
    7350             : /************************************************************************/
    7351             : /*                       ResetReadingAllLayers()                        */
    7352             : /************************************************************************/
    7353             : 
    7354         205 : void GDALGeoPackageDataset::ResetReadingAllLayers()
    7355             : {
    7356         415 :     for (auto &poLayer : m_apoLayers)
    7357             :     {
    7358         210 :         poLayer->ResetReading();
    7359             :     }
    7360         205 : }
    7361             : 
    7362             : /************************************************************************/
    7363             : /*                             ExecuteSQL()                             */
    7364             : /************************************************************************/
    7365             : 
    7366             : static const char *const apszFuncsWithSideEffects[] = {
    7367             :     "CreateSpatialIndex",
    7368             :     "DisableSpatialIndex",
    7369             :     "HasSpatialIndex",
    7370             :     "RegisterGeometryExtension",
    7371             : };
    7372             : 
    7373        5717 : OGRLayer *GDALGeoPackageDataset::ExecuteSQL(const char *pszSQLCommand,
    7374             :                                             OGRGeometry *poSpatialFilter,
    7375             :                                             const char *pszDialect)
    7376             : 
    7377             : {
    7378        5717 :     m_bHasReadMetadataFromStorage = false;
    7379             : 
    7380        5717 :     FlushMetadata();
    7381             : 
    7382        5735 :     while (*pszSQLCommand != '\0' &&
    7383        5735 :            isspace(static_cast<unsigned char>(*pszSQLCommand)))
    7384          18 :         pszSQLCommand++;
    7385             : 
    7386       11434 :     CPLString osSQLCommand(pszSQLCommand);
    7387        5717 :     if (!osSQLCommand.empty() && osSQLCommand.back() == ';')
    7388          48 :         osSQLCommand.pop_back();
    7389             : 
    7390       11433 :     if (osSQLCommand.ifind("AsGPB(ST_") != std::string::npos ||
    7391        5716 :         osSQLCommand.ifind("AsGPB( ST_") != std::string::npos)
    7392             :     {
    7393           1 :         CPLError(CE_Warning, CPLE_AppDefined,
    7394             :                  "Use of AsGPB(ST_xxx(...)) found in \"%s\". Since GDAL 3.13, "
    7395             :                  "ST_xxx() functions return a GeoPackage geometry when used "
    7396             :                  "with a GeoPackage connection, and the use of AsGPB() is no "
    7397             :                  "longer needed. It is here automatically removed",
    7398             :                  osSQLCommand.c_str());
    7399           1 :         osSQLCommand.replaceAll("AsGPB(ST_", "(ST_");
    7400           1 :         osSQLCommand.replaceAll("AsGPB( ST_", "(ST_");
    7401             :     }
    7402             : 
    7403        5717 :     if (pszDialect == nullptr || !EQUAL(pszDialect, "DEBUG"))
    7404             :     {
    7405             :         // Some SQL commands will influence the feature count behind our
    7406             :         // back, so disable it in that case.
    7407             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7408             :         const bool bInsertOrDelete =
    7409        5648 :             osSQLCommand.ifind("insert into ") != std::string::npos ||
    7410        2527 :             osSQLCommand.ifind("insert or replace into ") !=
    7411        8175 :                 std::string::npos ||
    7412        2490 :             osSQLCommand.ifind("delete from ") != std::string::npos;
    7413             :         const bool bRollback =
    7414        5648 :             osSQLCommand.ifind("rollback ") != std::string::npos;
    7415             : #endif
    7416             : 
    7417        7557 :         for (auto &poLayer : m_apoLayers)
    7418             :         {
    7419        1909 :             if (poLayer->SyncToDisk() != OGRERR_NONE)
    7420           0 :                 return nullptr;
    7421             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7422        2114 :             if (bRollback ||
    7423         205 :                 (bInsertOrDelete &&
    7424         205 :                  osSQLCommand.ifind(poLayer->GetName()) != std::string::npos))
    7425             :             {
    7426         203 :                 poLayer->DisableFeatureCount();
    7427             :             }
    7428             : #endif
    7429             :         }
    7430             :     }
    7431             : 
    7432        5717 :     if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 0") ||
    7433        5716 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=0") ||
    7434        5716 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =0") ||
    7435        5716 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 0"))
    7436             :     {
    7437           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, false);
    7438             :     }
    7439        5716 :     else if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 1") ||
    7440        5715 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=1") ||
    7441        5715 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =1") ||
    7442        5715 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 1"))
    7443             :     {
    7444           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, true);
    7445             :     }
    7446             : 
    7447             :     /* -------------------------------------------------------------------- */
    7448             :     /*      DEBUG "SELECT nolock" command.                                  */
    7449             :     /* -------------------------------------------------------------------- */
    7450        5786 :     if (pszDialect != nullptr && EQUAL(pszDialect, "DEBUG") &&
    7451          69 :         EQUAL(osSQLCommand, "SELECT nolock"))
    7452             :     {
    7453           3 :         return new OGRSQLiteSingleFeatureLayer(osSQLCommand, m_bNoLock ? 1 : 0);
    7454             :     }
    7455             : 
    7456             :     /* -------------------------------------------------------------------- */
    7457             :     /*      Special case DELLAYER: command.                                 */
    7458             :     /* -------------------------------------------------------------------- */
    7459        5714 :     if (STARTS_WITH_CI(osSQLCommand, "DELLAYER:"))
    7460             :     {
    7461           4 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DELLAYER:");
    7462             : 
    7463           4 :         while (*pszLayerName == ' ')
    7464           0 :             pszLayerName++;
    7465             : 
    7466           4 :         if (!DeleteVectorOrRasterLayer(pszLayerName))
    7467             :         {
    7468           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7469             :                      pszLayerName);
    7470             :         }
    7471           4 :         return nullptr;
    7472             :     }
    7473             : 
    7474             :     /* -------------------------------------------------------------------- */
    7475             :     /*      Special case RECOMPUTE EXTENT ON command.                       */
    7476             :     /* -------------------------------------------------------------------- */
    7477        5710 :     if (STARTS_WITH_CI(osSQLCommand, "RECOMPUTE EXTENT ON "))
    7478             :     {
    7479             :         const char *pszLayerName =
    7480           4 :             osSQLCommand.c_str() + strlen("RECOMPUTE EXTENT ON ");
    7481             : 
    7482           4 :         while (*pszLayerName == ' ')
    7483           0 :             pszLayerName++;
    7484             : 
    7485           4 :         int idx = FindLayerIndex(pszLayerName);
    7486           4 :         if (idx >= 0)
    7487             :         {
    7488           4 :             m_apoLayers[idx]->RecomputeExtent();
    7489             :         }
    7490             :         else
    7491           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7492             :                      pszLayerName);
    7493           4 :         return nullptr;
    7494             :     }
    7495             : 
    7496             :     /* -------------------------------------------------------------------- */
    7497             :     /*      Intercept DROP TABLE                                            */
    7498             :     /* -------------------------------------------------------------------- */
    7499        5706 :     if (STARTS_WITH_CI(osSQLCommand, "DROP TABLE "))
    7500             :     {
    7501           9 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DROP TABLE ");
    7502             : 
    7503           9 :         while (*pszLayerName == ' ')
    7504           0 :             pszLayerName++;
    7505             : 
    7506           9 :         if (DeleteVectorOrRasterLayer(SQLUnescape(pszLayerName)))
    7507           4 :             return nullptr;
    7508             :     }
    7509             : 
    7510             :     /* -------------------------------------------------------------------- */
    7511             :     /*      Intercept ALTER TABLE src_table RENAME TO dst_table             */
    7512             :     /*      and       ALTER TABLE table RENAME COLUMN src_name TO dst_name  */
    7513             :     /*      and       ALTER TABLE table DROP COLUMN col_name                */
    7514             :     /*                                                                      */
    7515             :     /*      We do this because SQLite mechanisms can't deal with updating   */
    7516             :     /*      literal values in gpkg_ tables that refer to table and column   */
    7517             :     /*      names.                                                          */
    7518             :     /* -------------------------------------------------------------------- */
    7519        5702 :     if (STARTS_WITH_CI(osSQLCommand, "ALTER TABLE "))
    7520             :     {
    7521           9 :         char **papszTokens = SQLTokenize(osSQLCommand);
    7522             :         /* ALTER TABLE src_table RENAME TO dst_table */
    7523          16 :         if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "RENAME") &&
    7524           7 :             EQUAL(papszTokens[4], "TO"))
    7525             :         {
    7526           7 :             const char *pszSrcTableName = papszTokens[2];
    7527           7 :             const char *pszDstTableName = papszTokens[5];
    7528           7 :             if (RenameVectorOrRasterLayer(SQLUnescape(pszSrcTableName),
    7529          14 :                                           SQLUnescape(pszDstTableName)))
    7530             :             {
    7531           6 :                 CSLDestroy(papszTokens);
    7532           6 :                 return nullptr;
    7533             :             }
    7534             :         }
    7535             :         /* ALTER TABLE table RENAME COLUMN src_name TO dst_name */
    7536           2 :         else if (CSLCount(papszTokens) == 8 &&
    7537           1 :                  EQUAL(papszTokens[3], "RENAME") &&
    7538           3 :                  EQUAL(papszTokens[4], "COLUMN") && EQUAL(papszTokens[6], "TO"))
    7539             :         {
    7540           1 :             const char *pszTableName = papszTokens[2];
    7541           1 :             const char *pszSrcColumn = papszTokens[5];
    7542           1 :             const char *pszDstColumn = papszTokens[7];
    7543             :             OGRGeoPackageTableLayer *poLayer =
    7544           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7545           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7546           1 :             if (poLayer)
    7547             :             {
    7548           2 :                 int nSrcFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7549           2 :                     SQLUnescape(pszSrcColumn));
    7550           1 :                 if (nSrcFieldIdx >= 0)
    7551             :                 {
    7552             :                     // OFTString or any type will do as we just alter the name
    7553             :                     // so it will be ignored.
    7554           1 :                     OGRFieldDefn oFieldDefn(SQLUnescape(pszDstColumn),
    7555           1 :                                             OFTString);
    7556           1 :                     poLayer->AlterFieldDefn(nSrcFieldIdx, &oFieldDefn,
    7557             :                                             ALTER_NAME_FLAG);
    7558           1 :                     CSLDestroy(papszTokens);
    7559           1 :                     return nullptr;
    7560             :                 }
    7561             :             }
    7562             :         }
    7563             :         /* ALTER TABLE table DROP COLUMN col_name */
    7564           2 :         else if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "DROP") &&
    7565           1 :                  EQUAL(papszTokens[4], "COLUMN"))
    7566             :         {
    7567           1 :             const char *pszTableName = papszTokens[2];
    7568           1 :             const char *pszColumnName = papszTokens[5];
    7569             :             OGRGeoPackageTableLayer *poLayer =
    7570           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7571           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7572           1 :             if (poLayer)
    7573             :             {
    7574           2 :                 int nFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7575           2 :                     SQLUnescape(pszColumnName));
    7576           1 :                 if (nFieldIdx >= 0)
    7577             :                 {
    7578           1 :                     poLayer->DeleteField(nFieldIdx);
    7579           1 :                     CSLDestroy(papszTokens);
    7580           1 :                     return nullptr;
    7581             :                 }
    7582             :             }
    7583             :         }
    7584           1 :         CSLDestroy(papszTokens);
    7585             :     }
    7586             : 
    7587        5694 :     if (ProcessTransactionSQL(osSQLCommand))
    7588             :     {
    7589         253 :         return nullptr;
    7590             :     }
    7591             : 
    7592        5441 :     if (EQUAL(osSQLCommand, "VACUUM"))
    7593             :     {
    7594          13 :         ResetReadingAllLayers();
    7595             :     }
    7596        5428 :     else if (STARTS_WITH_CI(osSQLCommand, "DELETE FROM "))
    7597             :     {
    7598             :         // Optimize truncation of a table, especially if it has a spatial
    7599             :         // index.
    7600          23 :         const CPLStringList aosTokens(SQLTokenize(osSQLCommand));
    7601          23 :         if (aosTokens.size() == 3)
    7602             :         {
    7603          16 :             const char *pszTableName = aosTokens[2];
    7604             :             OGRGeoPackageTableLayer *poLayer =
    7605           8 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7606          24 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7607          16 :             if (poLayer)
    7608             :             {
    7609           8 :                 poLayer->Truncate();
    7610           8 :                 return nullptr;
    7611             :             }
    7612             :         }
    7613             :     }
    7614        5405 :     else if (pszDialect != nullptr && EQUAL(pszDialect, "INDIRECT_SQLITE"))
    7615           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter, "SQLITE");
    7616        5404 :     else if (pszDialect != nullptr && !EQUAL(pszDialect, "") &&
    7617          67 :              !EQUAL(pszDialect, "NATIVE") && !EQUAL(pszDialect, "SQLITE") &&
    7618          67 :              !EQUAL(pszDialect, "DEBUG"))
    7619           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter,
    7620           1 :                                        pszDialect);
    7621             : 
    7622             :     /* -------------------------------------------------------------------- */
    7623             :     /*      Prepare statement.                                              */
    7624             :     /* -------------------------------------------------------------------- */
    7625             :     /* This will speed-up layer creation */
    7626             :     /* ORDER BY are costly to evaluate and are not necessary to establish */
    7627             :     /* the layer definition. */
    7628        5431 :     bool bUseStatementForGetNextFeature = true;
    7629        5431 :     bool bEmptyLayer = false;
    7630       10862 :     CPLString osSQLCommandTruncated(osSQLCommand);
    7631             : 
    7632       18035 :     if (osSQLCommand.ifind("SELECT ") == 0 &&
    7633        6302 :         CPLString(osSQLCommand.substr(1)).ifind("SELECT ") ==
    7634         830 :             std::string::npos &&
    7635         830 :         osSQLCommand.ifind(" UNION ") == std::string::npos &&
    7636        7132 :         osSQLCommand.ifind(" INTERSECT ") == std::string::npos &&
    7637         830 :         osSQLCommand.ifind(" EXCEPT ") == std::string::npos)
    7638             :     {
    7639         830 :         size_t nOrderByPos = osSQLCommand.ifind(" ORDER BY ");
    7640         830 :         if (nOrderByPos != std::string::npos)
    7641             :         {
    7642           9 :             osSQLCommandTruncated.resize(nOrderByPos);
    7643           9 :             bUseStatementForGetNextFeature = false;
    7644             :         }
    7645             :     }
    7646             : 
    7647        5431 :     const auto nErrorCount = CPLGetErrorCounter();
    7648             :     sqlite3_stmt *hSQLStmt =
    7649        5431 :         prepareSql(hDB, osSQLCommandTruncated.c_str(),
    7650        5431 :                    static_cast<int>(osSQLCommandTruncated.size()));
    7651        5431 :     if (!hSQLStmt)
    7652             :     {
    7653          12 :         if (nErrorCount == CPLGetErrorCounter())
    7654             :         {
    7655           9 :             CPLError(CE_Failure, CPLE_AppDefined, "%s",
    7656          18 :                      SQLFormatErrorMsgFailedPrepare(
    7657             :                          GetDB(), "In ExecuteSQL(): sqlite3_prepare_v2(): ",
    7658             :                          osSQLCommand.c_str())
    7659             :                          .c_str());
    7660             :         }
    7661          12 :         return nullptr;
    7662             :     }
    7663             : 
    7664             :     /* -------------------------------------------------------------------- */
    7665             :     /*      Do we get a resultset?                                          */
    7666             :     /* -------------------------------------------------------------------- */
    7667        5419 :     int rc = sqlite3_step(hSQLStmt);
    7668             : 
    7669        7090 :     for (auto &poLayer : m_apoLayers)
    7670             :     {
    7671        1671 :         if (!poLayer->RunDeferredDropRTreeTableIfNecessary())
    7672           0 :             return nullptr;
    7673             :     }
    7674             : 
    7675        5419 :     if (rc != SQLITE_ROW)
    7676             :     {
    7677        4635 :         if (rc != SQLITE_DONE)
    7678             :         {
    7679           7 :             CPLError(CE_Failure, CPLE_AppDefined,
    7680             :                      "In ExecuteSQL(): sqlite3_step(%s):\n  %s",
    7681             :                      osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7682             : 
    7683           7 :             sqlite3_finalize(hSQLStmt);
    7684           7 :             return nullptr;
    7685             :         }
    7686             : 
    7687        4628 :         if (EQUAL(osSQLCommand, "VACUUM"))
    7688             :         {
    7689          13 :             sqlite3_finalize(hSQLStmt);
    7690             :             /* VACUUM rewrites the DB, so we need to reset the application id */
    7691          13 :             SetApplicationAndUserVersionId();
    7692          13 :             return nullptr;
    7693             :         }
    7694             : 
    7695        4615 :         if (!STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7696             :         {
    7697        4487 :             sqlite3_finalize(hSQLStmt);
    7698        4487 :             return nullptr;
    7699             :         }
    7700             : 
    7701         128 :         bUseStatementForGetNextFeature = false;
    7702         128 :         bEmptyLayer = true;
    7703             :     }
    7704             : 
    7705             :     /* -------------------------------------------------------------------- */
    7706             :     /*      Special case for some functions which must be run               */
    7707             :     /*      only once                                                       */
    7708             :     /* -------------------------------------------------------------------- */
    7709         912 :     if (STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7710             :     {
    7711        4184 :         for (unsigned int i = 0; i < sizeof(apszFuncsWithSideEffects) /
    7712             :                                          sizeof(apszFuncsWithSideEffects[0]);
    7713             :              i++)
    7714             :         {
    7715        3373 :             if (EQUALN(apszFuncsWithSideEffects[i], osSQLCommand.c_str() + 7,
    7716             :                        strlen(apszFuncsWithSideEffects[i])))
    7717             :             {
    7718         112 :                 if (sqlite3_column_count(hSQLStmt) == 1 &&
    7719          56 :                     sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7720             :                 {
    7721          56 :                     int ret = sqlite3_column_int(hSQLStmt, 0);
    7722             : 
    7723          56 :                     sqlite3_finalize(hSQLStmt);
    7724             : 
    7725             :                     return new OGRSQLiteSingleFeatureLayer(
    7726          56 :                         apszFuncsWithSideEffects[i], ret);
    7727             :                 }
    7728             :             }
    7729             :         }
    7730             :     }
    7731          45 :     else if (STARTS_WITH_CI(osSQLCommand, "PRAGMA "))
    7732             :     {
    7733          63 :         if (sqlite3_column_count(hSQLStmt) == 1 &&
    7734          18 :             sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7735             :         {
    7736          15 :             int ret = sqlite3_column_int(hSQLStmt, 0);
    7737             : 
    7738          15 :             sqlite3_finalize(hSQLStmt);
    7739             : 
    7740          15 :             return new OGRSQLiteSingleFeatureLayer(osSQLCommand.c_str() + 7,
    7741          15 :                                                    ret);
    7742             :         }
    7743          33 :         else if (sqlite3_column_count(hSQLStmt) == 1 &&
    7744           3 :                  sqlite3_column_type(hSQLStmt, 0) == SQLITE_TEXT)
    7745             :         {
    7746             :             const char *pszRet = reinterpret_cast<const char *>(
    7747           3 :                 sqlite3_column_text(hSQLStmt, 0));
    7748             : 
    7749             :             OGRLayer *poRet = new OGRSQLiteSingleFeatureLayer(
    7750           3 :                 osSQLCommand.c_str() + 7, pszRet);
    7751             : 
    7752           3 :             sqlite3_finalize(hSQLStmt);
    7753             : 
    7754           3 :             return poRet;
    7755             :         }
    7756             :     }
    7757             : 
    7758             :     /* -------------------------------------------------------------------- */
    7759             :     /*      Create layer.                                                   */
    7760             :     /* -------------------------------------------------------------------- */
    7761             : 
    7762             :     auto poLayer = std::make_unique<OGRGeoPackageSelectLayer>(
    7763             :         this, osSQLCommand, hSQLStmt, bUseStatementForGetNextFeature,
    7764        1676 :         bEmptyLayer);
    7765             : 
    7766         841 :     if (poSpatialFilter != nullptr &&
    7767           3 :         poLayer->GetLayerDefn()->GetGeomFieldCount() > 0)
    7768           3 :         poLayer->SetSpatialFilter(0, poSpatialFilter);
    7769             : 
    7770         838 :     return poLayer.release();
    7771             : }
    7772             : 
    7773             : /************************************************************************/
    7774             : /*                          ReleaseResultSet()                          */
    7775             : /************************************************************************/
    7776             : 
    7777         871 : void GDALGeoPackageDataset::ReleaseResultSet(OGRLayer *poLayer)
    7778             : 
    7779             : {
    7780         871 :     delete poLayer;
    7781         871 : }
    7782             : 
    7783             : /************************************************************************/
    7784             : /*                         HasExtensionsTable()                         */
    7785             : /************************************************************************/
    7786             : 
    7787        7509 : bool GDALGeoPackageDataset::HasExtensionsTable()
    7788             : {
    7789        7509 :     return SQLGetInteger(
    7790             :                hDB,
    7791             :                "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_extensions' "
    7792             :                "AND type IN ('table', 'view')",
    7793        7509 :                nullptr) == 1;
    7794             : }
    7795             : 
    7796             : /************************************************************************/
    7797             : /*                       CheckUnknownExtensions()                       */
    7798             : /************************************************************************/
    7799             : 
    7800        1666 : void GDALGeoPackageDataset::CheckUnknownExtensions(bool bCheckRasterTable)
    7801             : {
    7802        1666 :     if (!HasExtensionsTable())
    7803         211 :         return;
    7804             : 
    7805        1455 :     char *pszSQL = nullptr;
    7806        1455 :     if (!bCheckRasterTable)
    7807        1239 :         pszSQL = sqlite3_mprintf(
    7808             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7809             :             "WHERE (table_name IS NULL "
    7810             :             "AND extension_name IS NOT NULL "
    7811             :             "AND definition IS NOT NULL "
    7812             :             "AND scope IS NOT NULL "
    7813             :             "AND extension_name NOT IN ("
    7814             :             "'gdal_aspatial', "
    7815             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7816             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7817             :                                        // 17-066r1 finalization
    7818             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7819             :             "'gpkg_metadata', "
    7820             :             "'gpkg_schema', "
    7821             :             "'gpkg_crs_wkt', "
    7822             :             "'gpkg_crs_wkt_1_1', "
    7823             :             "'related_tables', 'gpkg_related_tables')) "
    7824             : #ifdef WORKAROUND_SQLITE3_BUGS
    7825             :             "OR 0 "
    7826             : #endif
    7827             :             "LIMIT 1000");
    7828             :     else
    7829         216 :         pszSQL = sqlite3_mprintf(
    7830             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7831             :             "WHERE (lower(table_name) = lower('%q') "
    7832             :             "AND extension_name IS NOT NULL "
    7833             :             "AND definition IS NOT NULL "
    7834             :             "AND scope IS NOT NULL "
    7835             :             "AND extension_name NOT IN ("
    7836             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7837             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7838             :                                        // 17-066r1 finalization
    7839             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7840             :             "'gpkg_metadata', "
    7841             :             "'gpkg_schema', "
    7842             :             "'gpkg_crs_wkt', "
    7843             :             "'gpkg_crs_wkt_1_1', "
    7844             :             "'related_tables', 'gpkg_related_tables')) "
    7845             : #ifdef WORKAROUND_SQLITE3_BUGS
    7846             :             "OR 0 "
    7847             : #endif
    7848             :             "LIMIT 1000",
    7849             :             m_osRasterTable.c_str());
    7850             : 
    7851        2910 :     auto oResultTable = SQLQuery(GetDB(), pszSQL);
    7852        1455 :     sqlite3_free(pszSQL);
    7853        1455 :     if (oResultTable && oResultTable->RowCount() > 0)
    7854             :     {
    7855          42 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    7856             :         {
    7857          21 :             const char *pszExtName = oResultTable->GetValue(0, i);
    7858          21 :             const char *pszDefinition = oResultTable->GetValue(1, i);
    7859          21 :             const char *pszScope = oResultTable->GetValue(2, i);
    7860          21 :             if (pszExtName == nullptr || pszDefinition == nullptr ||
    7861             :                 pszScope == nullptr)
    7862             :             {
    7863           0 :                 continue;
    7864             :             }
    7865             : 
    7866          21 :             if (EQUAL(pszExtName, "gpkg_webp"))
    7867             :             {
    7868          15 :                 if (GDALGetDriverByName("WEBP") == nullptr)
    7869             :                 {
    7870           1 :                     CPLError(
    7871             :                         CE_Warning, CPLE_AppDefined,
    7872             :                         "Table %s contains WEBP tiles, but GDAL configured "
    7873             :                         "without WEBP support. Data will be missing",
    7874             :                         m_osRasterTable.c_str());
    7875             :                 }
    7876          15 :                 m_eTF = GPKG_TF_WEBP;
    7877          15 :                 continue;
    7878             :             }
    7879           6 :             if (EQUAL(pszExtName, "gpkg_zoom_other"))
    7880             :             {
    7881           2 :                 m_bZoomOther = true;
    7882           2 :                 continue;
    7883             :             }
    7884             : 
    7885           4 :             if (GetUpdate() && EQUAL(pszScope, "write-only"))
    7886             :             {
    7887           1 :                 CPLError(
    7888             :                     CE_Warning, CPLE_AppDefined,
    7889             :                     "Database relies on the '%s' (%s) extension that should "
    7890             :                     "be implemented for safe write-support, but is not "
    7891             :                     "currently. "
    7892             :                     "Update of that database are strongly discouraged to avoid "
    7893             :                     "corruption.",
    7894             :                     pszExtName, pszDefinition);
    7895             :             }
    7896           3 :             else if (GetUpdate() && EQUAL(pszScope, "read-write"))
    7897             :             {
    7898           1 :                 CPLError(
    7899             :                     CE_Warning, CPLE_AppDefined,
    7900             :                     "Database relies on the '%s' (%s) extension that should "
    7901             :                     "be implemented in order to read/write it safely, but is "
    7902             :                     "not currently. "
    7903             :                     "Some data may be missing while reading that database, and "
    7904             :                     "updates are strongly discouraged.",
    7905             :                     pszExtName, pszDefinition);
    7906             :             }
    7907           2 :             else if (EQUAL(pszScope, "read-write") &&
    7908             :                      // None of the NGA extensions at
    7909             :                      // http://ngageoint.github.io/GeoPackage/docs/extensions/
    7910             :                      // affect read-only scenarios
    7911           1 :                      !STARTS_WITH(pszExtName, "nga_"))
    7912             :             {
    7913           1 :                 CPLError(
    7914             :                     CE_Warning, CPLE_AppDefined,
    7915             :                     "Database relies on the '%s' (%s) extension that should "
    7916             :                     "be implemented in order to read it safely, but is not "
    7917             :                     "currently. "
    7918             :                     "Some data may be missing while reading that database.",
    7919             :                     pszExtName, pszDefinition);
    7920             :             }
    7921             :         }
    7922             :     }
    7923             : }
    7924             : 
    7925             : /************************************************************************/
    7926             : /*                      HasGDALAspatialExtension()                      */
    7927             : /************************************************************************/
    7928             : 
    7929        1199 : bool GDALGeoPackageDataset::HasGDALAspatialExtension()
    7930             : {
    7931        1199 :     if (!HasExtensionsTable())
    7932         103 :         return false;
    7933             : 
    7934             :     auto oResultTable = SQLQuery(hDB, "SELECT * FROM gpkg_extensions "
    7935             :                                       "WHERE (extension_name = 'gdal_aspatial' "
    7936             :                                       "AND table_name IS NULL "
    7937             :                                       "AND column_name IS NULL)"
    7938             : #ifdef WORKAROUND_SQLITE3_BUGS
    7939             :                                       " OR 0"
    7940             : #endif
    7941        1096 :     );
    7942        1096 :     bool bHasExtension = (oResultTable && oResultTable->RowCount() == 1);
    7943        1096 :     return bHasExtension;
    7944             : }
    7945             : 
    7946             : std::string
    7947         193 : GDALGeoPackageDataset::CreateRasterTriggersSQL(const std::string &osTableName)
    7948             : {
    7949             :     char *pszSQL;
    7950         193 :     std::string osSQL;
    7951             :     /* From D.5. sample_tile_pyramid Table 43. tiles table Trigger
    7952             :      * Definition SQL  */
    7953         193 :     pszSQL = sqlite3_mprintf(
    7954             :         "CREATE TRIGGER \"%w_zoom_insert\" "
    7955             :         "BEFORE INSERT ON \"%w\" "
    7956             :         "FOR EACH ROW BEGIN "
    7957             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7958             :         "constraint: zoom_level not specified for table in "
    7959             :         "gpkg_tile_matrix') "
    7960             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7961             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7962             :         "END; "
    7963             :         "CREATE TRIGGER \"%w_zoom_update\" "
    7964             :         "BEFORE UPDATE OF zoom_level ON \"%w\" "
    7965             :         "FOR EACH ROW BEGIN "
    7966             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7967             :         "constraint: zoom_level not specified for table in "
    7968             :         "gpkg_tile_matrix') "
    7969             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7970             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7971             :         "END; "
    7972             :         "CREATE TRIGGER \"%w_tile_column_insert\" "
    7973             :         "BEFORE INSERT ON \"%w\" "
    7974             :         "FOR EACH ROW BEGIN "
    7975             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7976             :         "constraint: tile_column cannot be < 0') "
    7977             :         "WHERE (NEW.tile_column < 0) ; "
    7978             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7979             :         "constraint: tile_column must by < matrix_width specified for "
    7980             :         "table and zoom level in gpkg_tile_matrix') "
    7981             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    7982             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    7983             :         "zoom_level = NEW.zoom_level)); "
    7984             :         "END; "
    7985             :         "CREATE TRIGGER \"%w_tile_column_update\" "
    7986             :         "BEFORE UPDATE OF tile_column ON \"%w\" "
    7987             :         "FOR EACH ROW BEGIN "
    7988             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7989             :         "constraint: tile_column cannot be < 0') "
    7990             :         "WHERE (NEW.tile_column < 0) ; "
    7991             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7992             :         "constraint: tile_column must by < matrix_width specified for "
    7993             :         "table and zoom level in gpkg_tile_matrix') "
    7994             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    7995             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    7996             :         "zoom_level = NEW.zoom_level)); "
    7997             :         "END; "
    7998             :         "CREATE TRIGGER \"%w_tile_row_insert\" "
    7999             :         "BEFORE INSERT ON \"%w\" "
    8000             :         "FOR EACH ROW BEGIN "
    8001             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8002             :         "constraint: tile_row cannot be < 0') "
    8003             :         "WHERE (NEW.tile_row < 0) ; "
    8004             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8005             :         "constraint: tile_row must by < matrix_height specified for "
    8006             :         "table and zoom level in gpkg_tile_matrix') "
    8007             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8008             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8009             :         "zoom_level = NEW.zoom_level)); "
    8010             :         "END; "
    8011             :         "CREATE TRIGGER \"%w_tile_row_update\" "
    8012             :         "BEFORE UPDATE OF tile_row ON \"%w\" "
    8013             :         "FOR EACH ROW BEGIN "
    8014             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8015             :         "constraint: tile_row cannot be < 0') "
    8016             :         "WHERE (NEW.tile_row < 0) ; "
    8017             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8018             :         "constraint: tile_row must by < matrix_height specified for "
    8019             :         "table and zoom level in gpkg_tile_matrix') "
    8020             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8021             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8022             :         "zoom_level = NEW.zoom_level)); "
    8023             :         "END; ",
    8024             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8025             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8026             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8027             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8028             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8029             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8030             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8031             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8032             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8033             :         osTableName.c_str());
    8034         193 :     osSQL = pszSQL;
    8035         193 :     sqlite3_free(pszSQL);
    8036         193 :     return osSQL;
    8037             : }
    8038             : 
    8039             : /************************************************************************/
    8040             : /*                  CreateExtensionsTableIfNecessary()                  */
    8041             : /************************************************************************/
    8042             : 
    8043        1345 : OGRErr GDALGeoPackageDataset::CreateExtensionsTableIfNecessary()
    8044             : {
    8045             :     /* Check if the table gpkg_extensions exists */
    8046        1345 :     if (HasExtensionsTable())
    8047         454 :         return OGRERR_NONE;
    8048             : 
    8049             :     /* Requirement 79 : Every extension of a GeoPackage SHALL be registered */
    8050             :     /* in a corresponding row in the gpkg_extensions table. The absence of a */
    8051             :     /* gpkg_extensions table or the absence of rows in gpkg_extensions table */
    8052             :     /* SHALL both indicate the absence of extensions to a GeoPackage. */
    8053         891 :     const char *pszCreateGpkgExtensions =
    8054             :         "CREATE TABLE gpkg_extensions ("
    8055             :         "table_name TEXT,"
    8056             :         "column_name TEXT,"
    8057             :         "extension_name TEXT NOT NULL,"
    8058             :         "definition TEXT NOT NULL,"
    8059             :         "scope TEXT NOT NULL,"
    8060             :         "CONSTRAINT ge_tce UNIQUE (table_name, column_name, extension_name)"
    8061             :         ")";
    8062             : 
    8063         891 :     return SQLCommand(hDB, pszCreateGpkgExtensions);
    8064             : }
    8065             : 
    8066             : /************************************************************************/
    8067             : /*                 OGR_GPKG_Intersects_Spatial_Filter()                 */
    8068             : /************************************************************************/
    8069             : 
    8070       23236 : void OGR_GPKG_Intersects_Spatial_Filter(sqlite3_context *pContext, int argc,
    8071             :                                         sqlite3_value **argv)
    8072             : {
    8073       23236 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8074             :     {
    8075           0 :         sqlite3_result_int(pContext, 0);
    8076       23226 :         return;
    8077             :     }
    8078             : 
    8079             :     auto poLayer =
    8080       23236 :         static_cast<OGRGeoPackageTableLayer *>(sqlite3_user_data(pContext));
    8081             : 
    8082       23236 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8083             :     const GByte *pabyBLOB =
    8084       23236 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8085             : 
    8086             :     GPkgHeader sHeader;
    8087       46472 :     if (poLayer->m_bFilterIsEnvelope &&
    8088       23236 :         OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false, 0))
    8089             :     {
    8090       23236 :         if (sHeader.bExtentHasXY)
    8091             :         {
    8092          95 :             OGREnvelope sEnvelope;
    8093          95 :             sEnvelope.MinX = sHeader.MinX;
    8094          95 :             sEnvelope.MinY = sHeader.MinY;
    8095          95 :             sEnvelope.MaxX = sHeader.MaxX;
    8096          95 :             sEnvelope.MaxY = sHeader.MaxY;
    8097          95 :             if (poLayer->m_sFilterEnvelope.Contains(sEnvelope))
    8098             :             {
    8099          31 :                 sqlite3_result_int(pContext, 1);
    8100          31 :                 return;
    8101             :             }
    8102             :         }
    8103             : 
    8104             :         // Check if at least one point falls into the layer filter envelope
    8105             :         // nHeaderLen is > 0 for GeoPackage geometries
    8106       46410 :         if (sHeader.nHeaderLen > 0 &&
    8107       23205 :             OGRWKBIntersectsPessimistic(pabyBLOB + sHeader.nHeaderLen,
    8108       23205 :                                         nBLOBLen - sHeader.nHeaderLen,
    8109       23205 :                                         poLayer->m_sFilterEnvelope))
    8110             :         {
    8111       23195 :             sqlite3_result_int(pContext, 1);
    8112       23195 :             return;
    8113             :         }
    8114             :     }
    8115             : 
    8116             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8117          10 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8118          10 :     if (poGeom == nullptr)
    8119             :     {
    8120             :         // Try also spatialite geometry blobs
    8121           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8122           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8123           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8124             :         {
    8125           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8126           0 :             sqlite3_result_int(pContext, 0);
    8127           0 :             return;
    8128             :         }
    8129           0 :         poGeom.reset(poGeomSpatialite);
    8130             :     }
    8131             : 
    8132          10 :     sqlite3_result_int(pContext, poLayer->FilterGeometry(poGeom.get()));
    8133             : }
    8134             : 
    8135             : /************************************************************************/
    8136             : /*                        OGRGeoPackageSTMinX()                         */
    8137             : /************************************************************************/
    8138             : 
    8139      253039 : static void OGRGeoPackageSTMinX(sqlite3_context *pContext, int argc,
    8140             :                                 sqlite3_value **argv)
    8141             : {
    8142             :     GPkgHeader sHeader;
    8143      253039 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8144             :     {
    8145          17 :         sqlite3_result_null(pContext);
    8146          17 :         return;
    8147             :     }
    8148      253022 :     sqlite3_result_double(pContext, sHeader.MinX);
    8149             : }
    8150             : 
    8151             : /************************************************************************/
    8152             : /*                        OGRGeoPackageSTMinY()                         */
    8153             : /************************************************************************/
    8154             : 
    8155      253023 : static void OGRGeoPackageSTMinY(sqlite3_context *pContext, int argc,
    8156             :                                 sqlite3_value **argv)
    8157             : {
    8158             :     GPkgHeader sHeader;
    8159      253023 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8160             :     {
    8161           1 :         sqlite3_result_null(pContext);
    8162           1 :         return;
    8163             :     }
    8164      253022 :     sqlite3_result_double(pContext, sHeader.MinY);
    8165             : }
    8166             : 
    8167             : /************************************************************************/
    8168             : /*                        OGRGeoPackageSTMaxX()                         */
    8169             : /************************************************************************/
    8170             : 
    8171      253023 : static void OGRGeoPackageSTMaxX(sqlite3_context *pContext, int argc,
    8172             :                                 sqlite3_value **argv)
    8173             : {
    8174             :     GPkgHeader sHeader;
    8175      253023 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8176             :     {
    8177           1 :         sqlite3_result_null(pContext);
    8178           1 :         return;
    8179             :     }
    8180      253022 :     sqlite3_result_double(pContext, sHeader.MaxX);
    8181             : }
    8182             : 
    8183             : /************************************************************************/
    8184             : /*                        OGRGeoPackageSTMaxY()                         */
    8185             : /************************************************************************/
    8186             : 
    8187      253023 : static void OGRGeoPackageSTMaxY(sqlite3_context *pContext, int argc,
    8188             :                                 sqlite3_value **argv)
    8189             : {
    8190             :     GPkgHeader sHeader;
    8191      253023 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8192             :     {
    8193           1 :         sqlite3_result_null(pContext);
    8194           1 :         return;
    8195             :     }
    8196      253022 :     sqlite3_result_double(pContext, sHeader.MaxY);
    8197             : }
    8198             : 
    8199             : /************************************************************************/
    8200             : /*                       OGRGeoPackageSTIsEmpty()                       */
    8201             : /************************************************************************/
    8202             : 
    8203      254460 : static void OGRGeoPackageSTIsEmpty(sqlite3_context *pContext, int argc,
    8204             :                                    sqlite3_value **argv)
    8205             : {
    8206             :     GPkgHeader sHeader;
    8207      254460 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8208             :     {
    8209           2 :         sqlite3_result_null(pContext);
    8210           2 :         return;
    8211             :     }
    8212      254458 :     sqlite3_result_int(pContext, sHeader.bEmpty);
    8213             : }
    8214             : 
    8215             : /************************************************************************/
    8216             : /*                    OGRGeoPackageSTGeometryType()                     */
    8217             : /************************************************************************/
    8218             : 
    8219           7 : static void OGRGeoPackageSTGeometryType(sqlite3_context *pContext, int /*argc*/,
    8220             :                                         sqlite3_value **argv)
    8221             : {
    8222             :     GPkgHeader sHeader;
    8223             : 
    8224           7 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8225             :     const GByte *pabyBLOB =
    8226           7 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8227             :     OGRwkbGeometryType eGeometryType;
    8228             : 
    8229          13 :     if (nBLOBLen < 8 ||
    8230           6 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8231             :     {
    8232           2 :         if (OGRSQLiteGetSpatialiteGeometryHeader(
    8233             :                 pabyBLOB, nBLOBLen, nullptr, &eGeometryType, nullptr, nullptr,
    8234           2 :                 nullptr, nullptr, nullptr) == OGRERR_NONE)
    8235             :         {
    8236           1 :             sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8237             :                                 SQLITE_TRANSIENT);
    8238           4 :             return;
    8239             :         }
    8240             :         else
    8241             :         {
    8242           1 :             sqlite3_result_null(pContext);
    8243           1 :             return;
    8244             :         }
    8245             :     }
    8246             : 
    8247           5 :     if (static_cast<size_t>(nBLOBLen) < sHeader.nHeaderLen + 5)
    8248             :     {
    8249           2 :         sqlite3_result_null(pContext);
    8250           2 :         return;
    8251             :     }
    8252             : 
    8253           3 :     OGRErr err = OGRReadWKBGeometryType(pabyBLOB + sHeader.nHeaderLen,
    8254             :                                         wkbVariantIso, &eGeometryType);
    8255           3 :     if (err != OGRERR_NONE)
    8256           1 :         sqlite3_result_null(pContext);
    8257             :     else
    8258           2 :         sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8259             :                             SQLITE_TRANSIENT);
    8260             : }
    8261             : 
    8262             : /************************************************************************/
    8263             : /*                 OGRGeoPackageSTEnvelopesIntersects()                 */
    8264             : /************************************************************************/
    8265             : 
    8266         118 : static void OGRGeoPackageSTEnvelopesIntersects(sqlite3_context *pContext,
    8267             :                                                int argc, sqlite3_value **argv)
    8268             : {
    8269             :     GPkgHeader sHeader;
    8270         118 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8271             :     {
    8272           2 :         sqlite3_result_int(pContext, FALSE);
    8273         107 :         return;
    8274             :     }
    8275         116 :     const double dfMinX = sqlite3_value_double(argv[1]);
    8276         116 :     if (sHeader.MaxX < dfMinX)
    8277             :     {
    8278          93 :         sqlite3_result_int(pContext, FALSE);
    8279          93 :         return;
    8280             :     }
    8281          23 :     const double dfMinY = sqlite3_value_double(argv[2]);
    8282          23 :     if (sHeader.MaxY < dfMinY)
    8283             :     {
    8284          11 :         sqlite3_result_int(pContext, FALSE);
    8285          11 :         return;
    8286             :     }
    8287          12 :     const double dfMaxX = sqlite3_value_double(argv[3]);
    8288          12 :     if (sHeader.MinX > dfMaxX)
    8289             :     {
    8290           1 :         sqlite3_result_int(pContext, FALSE);
    8291           1 :         return;
    8292             :     }
    8293          11 :     const double dfMaxY = sqlite3_value_double(argv[4]);
    8294          11 :     sqlite3_result_int(pContext, sHeader.MinY <= dfMaxY);
    8295             : }
    8296             : 
    8297             : /************************************************************************/
    8298             : /*            OGRGeoPackageSTEnvelopesIntersectsTwoParams()             */
    8299             : /************************************************************************/
    8300             : 
    8301             : static void
    8302           3 : OGRGeoPackageSTEnvelopesIntersectsTwoParams(sqlite3_context *pContext, int argc,
    8303             :                                             sqlite3_value **argv)
    8304             : {
    8305             :     GPkgHeader sHeader;
    8306           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false, 0))
    8307             :     {
    8308           0 :         sqlite3_result_int(pContext, FALSE);
    8309           2 :         return;
    8310             :     }
    8311             :     GPkgHeader sHeader2;
    8312           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader2, true, false,
    8313             :                                 1))
    8314             :     {
    8315           0 :         sqlite3_result_int(pContext, FALSE);
    8316           0 :         return;
    8317             :     }
    8318           3 :     if (sHeader.MaxX < sHeader2.MinX)
    8319             :     {
    8320           1 :         sqlite3_result_int(pContext, FALSE);
    8321           1 :         return;
    8322             :     }
    8323           2 :     if (sHeader.MaxY < sHeader2.MinY)
    8324             :     {
    8325           0 :         sqlite3_result_int(pContext, FALSE);
    8326           0 :         return;
    8327             :     }
    8328           2 :     if (sHeader.MinX > sHeader2.MaxX)
    8329             :     {
    8330           1 :         sqlite3_result_int(pContext, FALSE);
    8331           1 :         return;
    8332             :     }
    8333           1 :     sqlite3_result_int(pContext, sHeader.MinY <= sHeader2.MaxY);
    8334             : }
    8335             : 
    8336             : /************************************************************************/
    8337             : /*                   OGRGeoPackageGPKGIsAssignable()                    */
    8338             : /************************************************************************/
    8339             : 
    8340           8 : static void OGRGeoPackageGPKGIsAssignable(sqlite3_context *pContext,
    8341             :                                           int /*argc*/, sqlite3_value **argv)
    8342             : {
    8343          15 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8344           7 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8345             :     {
    8346           2 :         sqlite3_result_int(pContext, 0);
    8347           2 :         return;
    8348             :     }
    8349             : 
    8350             :     const char *pszExpected =
    8351           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8352             :     const char *pszActual =
    8353           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8354           6 :     int bIsAssignable = OGR_GT_IsSubClassOf(OGRFromOGCGeomType(pszActual),
    8355             :                                             OGRFromOGCGeomType(pszExpected));
    8356           6 :     sqlite3_result_int(pContext, bIsAssignable);
    8357             : }
    8358             : 
    8359             : /************************************************************************/
    8360             : /*                        OGRGeoPackageSTSRID()                         */
    8361             : /************************************************************************/
    8362             : 
    8363          12 : static void OGRGeoPackageSTSRID(sqlite3_context *pContext, int argc,
    8364             :                                 sqlite3_value **argv)
    8365             : {
    8366             :     GPkgHeader sHeader;
    8367          12 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8368             :     {
    8369           2 :         sqlite3_result_null(pContext);
    8370           2 :         return;
    8371             :     }
    8372          10 :     sqlite3_result_int(pContext, sHeader.iSrsId);
    8373             : }
    8374             : 
    8375             : /************************************************************************/
    8376             : /*                        OGRGeoPackageSetSRID()                        */
    8377             : /************************************************************************/
    8378             : 
    8379          28 : static void OGRGeoPackageSetSRID(sqlite3_context *pContext, int /* argc */,
    8380             :                                  sqlite3_value **argv)
    8381             : {
    8382          28 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8383             :     {
    8384           1 :         sqlite3_result_null(pContext);
    8385           1 :         return;
    8386             :     }
    8387          27 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8388             :     GPkgHeader sHeader;
    8389          27 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8390             :     const GByte *pabyBLOB =
    8391          27 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8392             : 
    8393          54 :     if (nBLOBLen < 8 ||
    8394          27 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8395             :     {
    8396             :         // Try also spatialite geometry blobs
    8397           0 :         OGRGeometry *poGeom = nullptr;
    8398           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeom) !=
    8399             :             OGRERR_NONE)
    8400             :         {
    8401           0 :             sqlite3_result_null(pContext);
    8402           0 :             return;
    8403             :         }
    8404           0 :         size_t nBLOBDestLen = 0;
    8405             :         GByte *pabyDestBLOB =
    8406           0 :             GPkgGeometryFromOGR(poGeom, nDestSRID, nullptr, &nBLOBDestLen);
    8407           0 :         if (!pabyDestBLOB)
    8408             :         {
    8409           0 :             sqlite3_result_null(pContext);
    8410           0 :             return;
    8411             :         }
    8412           0 :         sqlite3_result_blob(pContext, pabyDestBLOB,
    8413             :                             static_cast<int>(nBLOBDestLen), VSIFree);
    8414           0 :         return;
    8415             :     }
    8416             : 
    8417          27 :     GByte *pabyDestBLOB = static_cast<GByte *>(CPLMalloc(nBLOBLen));
    8418          27 :     memcpy(pabyDestBLOB, pabyBLOB, nBLOBLen);
    8419          27 :     int32_t nSRIDToSerialize = nDestSRID;
    8420          27 :     if (OGR_SWAP(sHeader.eByteOrder))
    8421           0 :         nSRIDToSerialize = CPL_SWAP32(nSRIDToSerialize);
    8422          27 :     memcpy(pabyDestBLOB + 4, &nSRIDToSerialize, 4);
    8423          27 :     sqlite3_result_blob(pContext, pabyDestBLOB, nBLOBLen, VSIFree);
    8424             : }
    8425             : 
    8426             : /************************************************************************/
    8427             : /*                      OGRGeoPackageSTMakeValid()                      */
    8428             : /************************************************************************/
    8429             : 
    8430           3 : static void OGRGeoPackageSTMakeValid(sqlite3_context *pContext, int argc,
    8431             :                                      sqlite3_value **argv)
    8432             : {
    8433           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8434             :     {
    8435           2 :         sqlite3_result_null(pContext);
    8436           2 :         return;
    8437             :     }
    8438           1 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8439             :     const GByte *pabyBLOB =
    8440           1 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8441             : 
    8442             :     GPkgHeader sHeader;
    8443           1 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8444             :     {
    8445           0 :         sqlite3_result_null(pContext);
    8446           0 :         return;
    8447             :     }
    8448             : 
    8449             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8450           1 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8451           1 :     if (poGeom == nullptr)
    8452             :     {
    8453             :         // Try also spatialite geometry blobs
    8454           0 :         OGRGeometry *poGeomPtr = nullptr;
    8455           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8456             :             OGRERR_NONE)
    8457             :         {
    8458           0 :             sqlite3_result_null(pContext);
    8459           0 :             return;
    8460             :         }
    8461           0 :         poGeom.reset(poGeomPtr);
    8462             :     }
    8463           1 :     auto poValid = std::unique_ptr<OGRGeometry>(poGeom->MakeValid());
    8464           1 :     if (poValid == nullptr)
    8465             :     {
    8466           0 :         sqlite3_result_null(pContext);
    8467           0 :         return;
    8468             :     }
    8469             : 
    8470           1 :     size_t nBLOBDestLen = 0;
    8471           1 :     GByte *pabyDestBLOB = GPkgGeometryFromOGR(poValid.get(), sHeader.iSrsId,
    8472             :                                               nullptr, &nBLOBDestLen);
    8473           1 :     if (!pabyDestBLOB)
    8474             :     {
    8475           0 :         sqlite3_result_null(pContext);
    8476           0 :         return;
    8477             :     }
    8478           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8479             :                         VSIFree);
    8480             : }
    8481             : 
    8482             : /************************************************************************/
    8483             : /*                        OGRGeoPackageSTArea()                         */
    8484             : /************************************************************************/
    8485             : 
    8486          19 : static void OGRGeoPackageSTArea(sqlite3_context *pContext, int /*argc*/,
    8487             :                                 sqlite3_value **argv)
    8488             : {
    8489          19 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8490             :     {
    8491           1 :         sqlite3_result_null(pContext);
    8492          15 :         return;
    8493             :     }
    8494          18 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8495             :     const GByte *pabyBLOB =
    8496          18 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8497             : 
    8498             :     GPkgHeader sHeader;
    8499           0 :     std::unique_ptr<OGRGeometry> poGeom;
    8500          18 :     if (GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) == OGRERR_NONE)
    8501             :     {
    8502          16 :         if (sHeader.bEmpty)
    8503             :         {
    8504           3 :             sqlite3_result_double(pContext, 0);
    8505          13 :             return;
    8506             :         }
    8507          13 :         const GByte *pabyWkb = pabyBLOB + sHeader.nHeaderLen;
    8508          13 :         size_t nWKBSize = nBLOBLen - sHeader.nHeaderLen;
    8509             :         bool bNeedSwap;
    8510             :         uint32_t nType;
    8511          13 :         if (OGRWKBGetGeomType(pabyWkb, nWKBSize, bNeedSwap, nType))
    8512             :         {
    8513          13 :             if (nType == wkbPolygon || nType == wkbPolygon25D ||
    8514          11 :                 nType == wkbPolygon + 1000 ||  // wkbPolygonZ
    8515          10 :                 nType == wkbPolygonM || nType == wkbPolygonZM)
    8516             :             {
    8517             :                 double dfArea;
    8518           5 :                 if (OGRWKBPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8519             :                 {
    8520           5 :                     sqlite3_result_double(pContext, dfArea);
    8521           5 :                     return;
    8522           0 :                 }
    8523             :             }
    8524           8 :             else if (nType == wkbMultiPolygon || nType == wkbMultiPolygon25D ||
    8525           6 :                      nType == wkbMultiPolygon + 1000 ||  // wkbMultiPolygonZ
    8526           5 :                      nType == wkbMultiPolygonM || nType == wkbMultiPolygonZM)
    8527             :             {
    8528             :                 double dfArea;
    8529           5 :                 if (OGRWKBMultiPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8530             :                 {
    8531           5 :                     sqlite3_result_double(pContext, dfArea);
    8532           5 :                     return;
    8533             :                 }
    8534             :             }
    8535             :         }
    8536             : 
    8537             :         // For curve geometries, fallback to OGRGeometry methods
    8538           3 :         poGeom.reset(GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8539             :     }
    8540             :     else
    8541             :     {
    8542             :         // Try also spatialite geometry blobs
    8543           2 :         OGRGeometry *poGeomPtr = nullptr;
    8544           2 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8545             :             OGRERR_NONE)
    8546             :         {
    8547           1 :             sqlite3_result_null(pContext);
    8548           1 :             return;
    8549             :         }
    8550           1 :         poGeom.reset(poGeomPtr);
    8551             :     }
    8552           4 :     auto poSurface = dynamic_cast<OGRSurface *>(poGeom.get());
    8553           4 :     if (poSurface == nullptr)
    8554             :     {
    8555           2 :         auto poMultiSurface = dynamic_cast<OGRMultiSurface *>(poGeom.get());
    8556           2 :         if (poMultiSurface == nullptr)
    8557             :         {
    8558           1 :             sqlite3_result_double(pContext, 0);
    8559             :         }
    8560             :         else
    8561             :         {
    8562           1 :             sqlite3_result_double(pContext, poMultiSurface->get_Area());
    8563             :         }
    8564             :     }
    8565             :     else
    8566             :     {
    8567           2 :         sqlite3_result_double(pContext, poSurface->get_Area());
    8568             :     }
    8569             : }
    8570             : 
    8571             : /************************************************************************/
    8572             : /*                     OGRGeoPackageGeodesicArea()                      */
    8573             : /************************************************************************/
    8574             : 
    8575           5 : static void OGRGeoPackageGeodesicArea(sqlite3_context *pContext, int argc,
    8576             :                                       sqlite3_value **argv)
    8577             : {
    8578           5 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8579             :     {
    8580           1 :         sqlite3_result_null(pContext);
    8581           3 :         return;
    8582             :     }
    8583           4 :     if (sqlite3_value_int(argv[1]) != 1)
    8584             :     {
    8585           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8586             :                  "ST_Area(geom, use_ellipsoid) is only supported for "
    8587             :                  "use_ellipsoid = 1");
    8588             :     }
    8589             : 
    8590           4 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8591             :     const GByte *pabyBLOB =
    8592           4 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8593             :     GPkgHeader sHeader;
    8594           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8595             :     {
    8596           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8597           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8598           1 :         return;
    8599             :     }
    8600             : 
    8601             :     GDALGeoPackageDataset *poDS =
    8602           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8603             : 
    8604           3 :     auto poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8605           3 :     if (poSrcSRS == nullptr)
    8606             :     {
    8607           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    8608             :                  "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8609           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8610           1 :         return;
    8611             :     }
    8612             : 
    8613             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8614           2 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8615           2 :     if (poGeom == nullptr)
    8616             :     {
    8617             :         // Try also spatialite geometry blobs
    8618           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8619           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8620           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8621             :         {
    8622           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8623           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8624           0 :             return;
    8625             :         }
    8626           0 :         poGeom.reset(poGeomSpatialite);
    8627             :     }
    8628             : 
    8629           2 :     poGeom->assignSpatialReference(poSrcSRS.get());
    8630           2 :     sqlite3_result_double(
    8631             :         pContext, OGR_G_GeodesicArea(OGRGeometry::ToHandle(poGeom.get())));
    8632             : }
    8633             : 
    8634             : /************************************************************************/
    8635             : /*                OGRGeoPackageLengthOrGeodesicLength()                 */
    8636             : /************************************************************************/
    8637             : 
    8638           8 : static void OGRGeoPackageLengthOrGeodesicLength(sqlite3_context *pContext,
    8639             :                                                 int argc, sqlite3_value **argv)
    8640             : {
    8641           8 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8642             :     {
    8643           2 :         sqlite3_result_null(pContext);
    8644           5 :         return;
    8645             :     }
    8646           6 :     if (argc == 2 && sqlite3_value_int(argv[1]) != 1)
    8647             :     {
    8648           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8649             :                  "ST_Length(geom, use_ellipsoid) is only supported for "
    8650             :                  "use_ellipsoid = 1");
    8651             :     }
    8652             : 
    8653           6 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8654             :     const GByte *pabyBLOB =
    8655           6 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8656             :     GPkgHeader sHeader;
    8657           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8658             :     {
    8659           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8660           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8661           2 :         return;
    8662             :     }
    8663             : 
    8664             :     GDALGeoPackageDataset *poDS =
    8665           4 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8666             : 
    8667           4 :     OGRSpatialReferenceRefCountedPtr poSrcSRS;
    8668           4 :     if (argc == 2)
    8669             :     {
    8670           3 :         poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8671           3 :         if (!poSrcSRS)
    8672             :         {
    8673           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    8674             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8675           1 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8676           1 :             return;
    8677             :         }
    8678             :     }
    8679             : 
    8680             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8681           3 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8682           3 :     if (poGeom == nullptr)
    8683             :     {
    8684             :         // Try also spatialite geometry blobs
    8685           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8686           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8687           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8688             :         {
    8689           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8690           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8691           0 :             return;
    8692             :         }
    8693           0 :         poGeom.reset(poGeomSpatialite);
    8694             :     }
    8695             : 
    8696           3 :     if (argc == 2)
    8697           2 :         poGeom->assignSpatialReference(poSrcSRS.get());
    8698             : 
    8699           6 :     sqlite3_result_double(
    8700             :         pContext,
    8701           1 :         argc == 1 ? OGR_G_Length(OGRGeometry::ToHandle(poGeom.get()))
    8702           2 :                   : OGR_G_GeodesicLength(OGRGeometry::ToHandle(poGeom.get())));
    8703             : }
    8704             : 
    8705             : /************************************************************************/
    8706             : /*                       OGRGeoPackageTransform()                       */
    8707             : /************************************************************************/
    8708             : 
    8709             : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8710             :                             sqlite3_value **argv);
    8711             : 
    8712          32 : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8713             :                             sqlite3_value **argv)
    8714             : {
    8715          63 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB ||
    8716          31 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8717             :     {
    8718           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8719          32 :         return;
    8720             :     }
    8721             : 
    8722          30 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8723             :     const GByte *pabyBLOB =
    8724          30 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8725             :     GPkgHeader sHeader;
    8726          30 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8727             :     {
    8728           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8729           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8730           1 :         return;
    8731             :     }
    8732             : 
    8733          29 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8734          29 :     if (sHeader.iSrsId == nDestSRID)
    8735             :     {
    8736             :         // Return blob unmodified
    8737           3 :         sqlite3_result_blob(pContext, pabyBLOB, nBLOBLen, SQLITE_TRANSIENT);
    8738           3 :         return;
    8739             :     }
    8740             : 
    8741             :     GDALGeoPackageDataset *poDS =
    8742          26 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8743             : 
    8744             :     // Try to get the cached coordinate transformation
    8745             :     OGRCoordinateTransformation *poCT;
    8746          26 :     if (poDS->m_nLastCachedCTSrcSRId == sHeader.iSrsId &&
    8747          20 :         poDS->m_nLastCachedCTDstSRId == nDestSRID)
    8748             :     {
    8749          20 :         poCT = poDS->m_poLastCachedCT.get();
    8750             :     }
    8751             :     else
    8752             :     {
    8753           6 :         auto poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8754           6 :         if (poSrcSRS == nullptr)
    8755             :         {
    8756           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    8757             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8758           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8759           0 :             return;
    8760             :         }
    8761             : 
    8762           6 :         auto poDstSRS = poDS->GetSpatialRef(nDestSRID, true);
    8763           6 :         if (poDstSRS == nullptr)
    8764             :         {
    8765           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Target SRID (%d) is invalid",
    8766             :                      nDestSRID);
    8767           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8768           0 :             return;
    8769             :         }
    8770             :         poCT =
    8771           6 :             OGRCreateCoordinateTransformation(poSrcSRS.get(), poDstSRS.get());
    8772           6 :         if (poCT == nullptr)
    8773             :         {
    8774           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8775           0 :             return;
    8776             :         }
    8777             : 
    8778             :         // Cache coordinate transformation for potential later reuse
    8779           6 :         poDS->m_nLastCachedCTSrcSRId = sHeader.iSrsId;
    8780           6 :         poDS->m_nLastCachedCTDstSRId = nDestSRID;
    8781           6 :         poDS->m_poLastCachedCT.reset(poCT);
    8782           6 :         poCT = poDS->m_poLastCachedCT.get();
    8783             :     }
    8784             : 
    8785          26 :     if (sHeader.nHeaderLen >= 8)
    8786             :     {
    8787          26 :         std::vector<GByte> &abyNewBLOB = poDS->m_abyWKBTransformCache;
    8788          26 :         abyNewBLOB.resize(nBLOBLen);
    8789          26 :         memcpy(abyNewBLOB.data(), pabyBLOB, nBLOBLen);
    8790             : 
    8791          26 :         OGREnvelope3D oEnv3d;
    8792          26 :         if (!OGRWKBTransform(abyNewBLOB.data() + sHeader.nHeaderLen,
    8793          26 :                              nBLOBLen - sHeader.nHeaderLen, poCT,
    8794          78 :                              poDS->m_oWKBTransformCache, oEnv3d) ||
    8795          26 :             !GPkgUpdateHeader(abyNewBLOB.data(), nBLOBLen, nDestSRID,
    8796             :                               oEnv3d.MinX, oEnv3d.MaxX, oEnv3d.MinY,
    8797             :                               oEnv3d.MaxY, oEnv3d.MinZ, oEnv3d.MaxZ))
    8798             :         {
    8799           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8800           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8801           0 :             return;
    8802             :         }
    8803             : 
    8804          26 :         sqlite3_result_blob(pContext, abyNewBLOB.data(), nBLOBLen,
    8805             :                             SQLITE_TRANSIENT);
    8806          26 :         return;
    8807             :     }
    8808             : 
    8809             :     // Try also spatialite geometry blobs
    8810           0 :     OGRGeometry *poGeomSpatialite = nullptr;
    8811           0 :     if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8812           0 :                                           &poGeomSpatialite) != OGRERR_NONE)
    8813             :     {
    8814           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8815           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8816           0 :         return;
    8817             :     }
    8818           0 :     auto poGeom = std::unique_ptr<OGRGeometry>(poGeomSpatialite);
    8819             : 
    8820           0 :     if (poGeom->transform(poCT) != OGRERR_NONE)
    8821             :     {
    8822           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8823           0 :         return;
    8824             :     }
    8825             : 
    8826           0 :     size_t nBLOBDestLen = 0;
    8827             :     GByte *pabyDestBLOB =
    8828           0 :         GPkgGeometryFromOGR(poGeom.get(), nDestSRID, nullptr, &nBLOBDestLen);
    8829           0 :     if (!pabyDestBLOB)
    8830             :     {
    8831           0 :         sqlite3_result_null(pContext);
    8832           0 :         return;
    8833             :     }
    8834           0 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8835             :                         VSIFree);
    8836             : }
    8837             : 
    8838             : /************************************************************************/
    8839             : /*                    OGRGeoPackageSridFromAuthCRS()                    */
    8840             : /************************************************************************/
    8841             : 
    8842           4 : static void OGRGeoPackageSridFromAuthCRS(sqlite3_context *pContext,
    8843             :                                          int /*argc*/, sqlite3_value **argv)
    8844             : {
    8845           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8846           3 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8847             :     {
    8848           2 :         sqlite3_result_int(pContext, -1);
    8849           2 :         return;
    8850             :     }
    8851             : 
    8852             :     GDALGeoPackageDataset *poDS =
    8853           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8854             : 
    8855           2 :     char *pszSQL = sqlite3_mprintf(
    8856             :         "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
    8857             :         "lower(organization) = lower('%q') AND organization_coordsys_id = %d",
    8858           2 :         sqlite3_value_text(argv[0]), sqlite3_value_int(argv[1]));
    8859           2 :     OGRErr err = OGRERR_NONE;
    8860           2 :     int nSRSId = SQLGetInteger(poDS->GetDB(), pszSQL, &err);
    8861           2 :     sqlite3_free(pszSQL);
    8862           2 :     if (err != OGRERR_NONE)
    8863           1 :         nSRSId = -1;
    8864           2 :     sqlite3_result_int(pContext, nSRSId);
    8865             : }
    8866             : 
    8867             : /************************************************************************/
    8868             : /*                    OGRGeoPackageImportFromEPSG()                     */
    8869             : /************************************************************************/
    8870             : 
    8871           4 : static void OGRGeoPackageImportFromEPSG(sqlite3_context *pContext, int /*argc*/,
    8872             :                                         sqlite3_value **argv)
    8873             : {
    8874           4 :     if (sqlite3_value_type(argv[0]) != SQLITE_INTEGER)
    8875             :     {
    8876           1 :         sqlite3_result_int(pContext, -1);
    8877           2 :         return;
    8878             :     }
    8879             : 
    8880             :     GDALGeoPackageDataset *poDS =
    8881           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8882           3 :     OGRSpatialReference oSRS;
    8883           3 :     if (oSRS.importFromEPSG(sqlite3_value_int(argv[0])) != OGRERR_NONE)
    8884             :     {
    8885           1 :         sqlite3_result_int(pContext, -1);
    8886           1 :         return;
    8887             :     }
    8888             : 
    8889           2 :     sqlite3_result_int(pContext, poDS->GetSrsId(&oSRS));
    8890             : }
    8891             : 
    8892             : /************************************************************************/
    8893             : /*               OGRGeoPackageRegisterGeometryExtension()               */
    8894             : /************************************************************************/
    8895             : 
    8896           1 : static void OGRGeoPackageRegisterGeometryExtension(sqlite3_context *pContext,
    8897             :                                                    int /*argc*/,
    8898             :                                                    sqlite3_value **argv)
    8899             : {
    8900           1 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8901           2 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT ||
    8902           1 :         sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    8903             :     {
    8904           0 :         sqlite3_result_int(pContext, 0);
    8905           0 :         return;
    8906             :     }
    8907             : 
    8908             :     const char *pszTableName =
    8909           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8910             :     const char *pszGeomName =
    8911           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8912             :     const char *pszGeomType =
    8913           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    8914             : 
    8915             :     GDALGeoPackageDataset *poDS =
    8916           1 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8917             : 
    8918           1 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8919           1 :         poDS->GetLayerByName(pszTableName));
    8920           1 :     if (poLyr == nullptr)
    8921             :     {
    8922           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8923           0 :         sqlite3_result_int(pContext, 0);
    8924           0 :         return;
    8925             :     }
    8926           1 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8927             :     {
    8928           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8929           0 :         sqlite3_result_int(pContext, 0);
    8930           0 :         return;
    8931             :     }
    8932           1 :     const OGRwkbGeometryType eGeomType = OGRFromOGCGeomType(pszGeomType);
    8933           1 :     if (eGeomType == wkbUnknown)
    8934             :     {
    8935           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry type name");
    8936           0 :         sqlite3_result_int(pContext, 0);
    8937           0 :         return;
    8938             :     }
    8939             : 
    8940           1 :     sqlite3_result_int(
    8941             :         pContext,
    8942           1 :         static_cast<int>(poLyr->CreateGeometryExtensionIfNecessary(eGeomType)));
    8943             : }
    8944             : 
    8945             : /************************************************************************/
    8946             : /*                  OGRGeoPackageCreateSpatialIndex()                   */
    8947             : /************************************************************************/
    8948             : 
    8949          14 : static void OGRGeoPackageCreateSpatialIndex(sqlite3_context *pContext,
    8950             :                                             int /*argc*/, sqlite3_value **argv)
    8951             : {
    8952          27 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8953          13 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8954             :     {
    8955           2 :         sqlite3_result_int(pContext, 0);
    8956           2 :         return;
    8957             :     }
    8958             : 
    8959             :     const char *pszTableName =
    8960          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8961             :     const char *pszGeomName =
    8962          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8963             :     GDALGeoPackageDataset *poDS =
    8964          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8965             : 
    8966          12 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8967          12 :         poDS->GetLayerByName(pszTableName));
    8968          12 :     if (poLyr == nullptr)
    8969             :     {
    8970           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8971           1 :         sqlite3_result_int(pContext, 0);
    8972           1 :         return;
    8973             :     }
    8974          11 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8975             :     {
    8976           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8977           1 :         sqlite3_result_int(pContext, 0);
    8978           1 :         return;
    8979             :     }
    8980             : 
    8981          10 :     sqlite3_result_int(pContext, poLyr->CreateSpatialIndex());
    8982             : }
    8983             : 
    8984             : /************************************************************************/
    8985             : /*                  OGRGeoPackageDisableSpatialIndex()                  */
    8986             : /************************************************************************/
    8987             : 
    8988          12 : static void OGRGeoPackageDisableSpatialIndex(sqlite3_context *pContext,
    8989             :                                              int /*argc*/, sqlite3_value **argv)
    8990             : {
    8991          23 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8992          11 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8993             :     {
    8994           2 :         sqlite3_result_int(pContext, 0);
    8995           2 :         return;
    8996             :     }
    8997             : 
    8998             :     const char *pszTableName =
    8999          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9000             :     const char *pszGeomName =
    9001          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9002             :     GDALGeoPackageDataset *poDS =
    9003          10 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9004             : 
    9005          10 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9006          10 :         poDS->GetLayerByName(pszTableName));
    9007          10 :     if (poLyr == nullptr)
    9008             :     {
    9009           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9010           1 :         sqlite3_result_int(pContext, 0);
    9011           1 :         return;
    9012             :     }
    9013           9 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9014             :     {
    9015           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9016           1 :         sqlite3_result_int(pContext, 0);
    9017           1 :         return;
    9018             :     }
    9019             : 
    9020           8 :     sqlite3_result_int(pContext, poLyr->DropSpatialIndex(true));
    9021             : }
    9022             : 
    9023             : /************************************************************************/
    9024             : /*                    OGRGeoPackageHasSpatialIndex()                    */
    9025             : /************************************************************************/
    9026             : 
    9027          29 : static void OGRGeoPackageHasSpatialIndex(sqlite3_context *pContext,
    9028             :                                          int /*argc*/, sqlite3_value **argv)
    9029             : {
    9030          57 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9031          28 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9032             :     {
    9033           2 :         sqlite3_result_int(pContext, 0);
    9034           2 :         return;
    9035             :     }
    9036             : 
    9037             :     const char *pszTableName =
    9038          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9039             :     const char *pszGeomName =
    9040          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9041             :     GDALGeoPackageDataset *poDS =
    9042          27 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9043             : 
    9044          27 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9045          27 :         poDS->GetLayerByName(pszTableName));
    9046          27 :     if (poLyr == nullptr)
    9047             :     {
    9048           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9049           1 :         sqlite3_result_int(pContext, 0);
    9050           1 :         return;
    9051             :     }
    9052          26 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9053             :     {
    9054           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9055           1 :         sqlite3_result_int(pContext, 0);
    9056           1 :         return;
    9057             :     }
    9058             : 
    9059          25 :     poLyr->RunDeferredCreationIfNecessary();
    9060          25 :     poLyr->CreateSpatialIndexIfNecessary();
    9061             : 
    9062          25 :     sqlite3_result_int(pContext, poLyr->HasSpatialIndex());
    9063             : }
    9064             : 
    9065             : /************************************************************************/
    9066             : /*                       GPKG_hstore_get_value()                        */
    9067             : /************************************************************************/
    9068             : 
    9069           4 : static void GPKG_hstore_get_value(sqlite3_context *pContext, int /*argc*/,
    9070             :                                   sqlite3_value **argv)
    9071             : {
    9072           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9073           3 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9074             :     {
    9075           2 :         sqlite3_result_null(pContext);
    9076           2 :         return;
    9077             :     }
    9078             : 
    9079             :     const char *pszHStore =
    9080           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9081             :     const char *pszSearchedKey =
    9082           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9083           2 :     char *pszValue = OGRHStoreGetValue(pszHStore, pszSearchedKey);
    9084           2 :     if (pszValue != nullptr)
    9085           1 :         sqlite3_result_text(pContext, pszValue, -1, CPLFree);
    9086             :     else
    9087           1 :         sqlite3_result_null(pContext);
    9088             : }
    9089             : 
    9090             : /************************************************************************/
    9091             : /*                    GPKG_GDAL_GetMemFileFromBlob()                    */
    9092             : /************************************************************************/
    9093             : 
    9094         105 : static CPLString GPKG_GDAL_GetMemFileFromBlob(sqlite3_value **argv)
    9095             : {
    9096         105 :     int nBytes = sqlite3_value_bytes(argv[0]);
    9097             :     const GByte *pabyBLOB =
    9098         105 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    9099             :     CPLString osMemFileName(
    9100         105 :         VSIMemGenerateHiddenFilename("GPKG_GDAL_GetMemFileFromBlob"));
    9101         105 :     VSILFILE *fp = VSIFileFromMemBuffer(
    9102             :         osMemFileName.c_str(), const_cast<GByte *>(pabyBLOB), nBytes, FALSE);
    9103         105 :     VSIFCloseL(fp);
    9104         105 :     return osMemFileName;
    9105             : }
    9106             : 
    9107             : /************************************************************************/
    9108             : /*                       GPKG_GDAL_GetMimeType()                        */
    9109             : /************************************************************************/
    9110             : 
    9111          35 : static void GPKG_GDAL_GetMimeType(sqlite3_context *pContext, int /*argc*/,
    9112             :                                   sqlite3_value **argv)
    9113             : {
    9114          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9115             :     {
    9116           0 :         sqlite3_result_null(pContext);
    9117           0 :         return;
    9118             :     }
    9119             : 
    9120          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9121             :     GDALDriver *poDriver =
    9122          35 :         GDALDriver::FromHandle(GDALIdentifyDriver(osMemFileName, nullptr));
    9123          35 :     if (poDriver != nullptr)
    9124             :     {
    9125          35 :         const char *pszRes = nullptr;
    9126          35 :         if (EQUAL(poDriver->GetDescription(), "PNG"))
    9127          23 :             pszRes = "image/png";
    9128          12 :         else if (EQUAL(poDriver->GetDescription(), "JPEG"))
    9129           6 :             pszRes = "image/jpeg";
    9130           6 :         else if (EQUAL(poDriver->GetDescription(), "WEBP"))
    9131           6 :             pszRes = "image/x-webp";
    9132           0 :         else if (EQUAL(poDriver->GetDescription(), "GTIFF"))
    9133           0 :             pszRes = "image/tiff";
    9134             :         else
    9135           0 :             pszRes = CPLSPrintf("gdal/%s", poDriver->GetDescription());
    9136          35 :         sqlite3_result_text(pContext, pszRes, -1, SQLITE_TRANSIENT);
    9137             :     }
    9138             :     else
    9139           0 :         sqlite3_result_null(pContext);
    9140          35 :     VSIUnlink(osMemFileName);
    9141             : }
    9142             : 
    9143             : /************************************************************************/
    9144             : /*                       GPKG_GDAL_GetBandCount()                       */
    9145             : /************************************************************************/
    9146             : 
    9147          35 : static void GPKG_GDAL_GetBandCount(sqlite3_context *pContext, int /*argc*/,
    9148             :                                    sqlite3_value **argv)
    9149             : {
    9150          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9151             :     {
    9152           0 :         sqlite3_result_null(pContext);
    9153           0 :         return;
    9154             :     }
    9155             : 
    9156          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9157             :     auto poDS = std::unique_ptr<GDALDataset>(
    9158             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9159          70 :                           nullptr, nullptr, nullptr));
    9160          35 :     if (poDS != nullptr)
    9161             :     {
    9162          35 :         sqlite3_result_int(pContext, poDS->GetRasterCount());
    9163             :     }
    9164             :     else
    9165           0 :         sqlite3_result_null(pContext);
    9166          35 :     VSIUnlink(osMemFileName);
    9167             : }
    9168             : 
    9169             : /************************************************************************/
    9170             : /*                      GPKG_GDAL_HasColorTable()                       */
    9171             : /************************************************************************/
    9172             : 
    9173          35 : static void GPKG_GDAL_HasColorTable(sqlite3_context *pContext, int /*argc*/,
    9174             :                                     sqlite3_value **argv)
    9175             : {
    9176          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9177             :     {
    9178           0 :         sqlite3_result_null(pContext);
    9179           0 :         return;
    9180             :     }
    9181             : 
    9182          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9183             :     auto poDS = std::unique_ptr<GDALDataset>(
    9184             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9185          70 :                           nullptr, nullptr, nullptr));
    9186          35 :     if (poDS != nullptr)
    9187             :     {
    9188          35 :         sqlite3_result_int(
    9189          46 :             pContext, poDS->GetRasterCount() == 1 &&
    9190          11 :                           poDS->GetRasterBand(1)->GetColorTable() != nullptr);
    9191             :     }
    9192             :     else
    9193           0 :         sqlite3_result_null(pContext);
    9194          35 :     VSIUnlink(osMemFileName);
    9195             : }
    9196             : 
    9197             : /************************************************************************/
    9198             : /*                       GetRasterLayerDataset()                        */
    9199             : /************************************************************************/
    9200             : 
    9201             : GDALDataset *
    9202          12 : GDALGeoPackageDataset::GetRasterLayerDataset(const char *pszLayerName)
    9203             : {
    9204          12 :     const auto oIter = m_oCachedRasterDS.find(pszLayerName);
    9205          12 :     if (oIter != m_oCachedRasterDS.end())
    9206          10 :         return oIter->second.get();
    9207             : 
    9208             :     auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
    9209           4 :         (std::string("GPKG:\"") + m_pszFilename + "\":" + pszLayerName).c_str(),
    9210           4 :         GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR));
    9211           2 :     if (!poDS)
    9212             :     {
    9213           0 :         return nullptr;
    9214             :     }
    9215           2 :     m_oCachedRasterDS[pszLayerName] = std::move(poDS);
    9216           2 :     return m_oCachedRasterDS[pszLayerName].get();
    9217             : }
    9218             : 
    9219             : /************************************************************************/
    9220             : /*                  GPKG_gdal_get_layer_pixel_value()                   */
    9221             : /************************************************************************/
    9222             : 
    9223             : // NOTE: keep in sync implementations in ogrsqlitesqlfunctionscommon.cpp
    9224             : // and ogrgeopackagedatasource.cpp
    9225          13 : static void GPKG_gdal_get_layer_pixel_value(sqlite3_context *pContext, int argc,
    9226             :                                             sqlite3_value **argv)
    9227             : {
    9228          13 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9229             :     {
    9230           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9231             :                  "Invalid arguments to gdal_get_layer_pixel_value()");
    9232           1 :         sqlite3_result_null(pContext);
    9233           1 :         return;
    9234             :     }
    9235             : 
    9236             :     const char *pszLayerName =
    9237          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9238             : 
    9239             :     GDALGeoPackageDataset *poGlobalDS =
    9240          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9241          12 :     auto poDS = poGlobalDS->GetRasterLayerDataset(pszLayerName);
    9242          12 :     if (!poDS)
    9243             :     {
    9244           0 :         sqlite3_result_null(pContext);
    9245           0 :         return;
    9246             :     }
    9247             : 
    9248          12 :     OGRSQLite_gdal_get_pixel_value_common("gdal_get_layer_pixel_value",
    9249             :                                           pContext, argc, argv, poDS);
    9250             : }
    9251             : 
    9252             : /************************************************************************/
    9253             : /*                       GPKG_ogr_layer_Extent()                        */
    9254             : /************************************************************************/
    9255             : 
    9256           3 : static void GPKG_ogr_layer_Extent(sqlite3_context *pContext, int /*argc*/,
    9257             :                                   sqlite3_value **argv)
    9258             : {
    9259           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9260             :     {
    9261           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Invalid argument type",
    9262             :                  "ogr_layer_Extent");
    9263           1 :         sqlite3_result_null(pContext);
    9264           2 :         return;
    9265             :     }
    9266             : 
    9267             :     const char *pszLayerName =
    9268           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9269             :     GDALGeoPackageDataset *poDS =
    9270           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9271           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9272           2 :     if (!poLayer)
    9273             :     {
    9274           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer",
    9275             :                  "ogr_layer_Extent");
    9276           1 :         sqlite3_result_null(pContext);
    9277           1 :         return;
    9278             :     }
    9279             : 
    9280           1 :     if (poLayer->GetGeomType() == wkbNone)
    9281             :     {
    9282           0 :         sqlite3_result_null(pContext);
    9283           0 :         return;
    9284             :     }
    9285             : 
    9286           1 :     OGREnvelope sExtent;
    9287           1 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9288             :     {
    9289           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9290             :                  "ogr_layer_Extent");
    9291           0 :         sqlite3_result_null(pContext);
    9292           0 :         return;
    9293             :     }
    9294             : 
    9295           1 :     OGRPolygon oPoly;
    9296           1 :     auto poRing = std::make_unique<OGRLinearRing>();
    9297           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9298           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MinY);
    9299           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MaxY);
    9300           1 :     poRing->addPoint(sExtent.MinX, sExtent.MaxY);
    9301           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9302           1 :     oPoly.addRing(std::move(poRing));
    9303             : 
    9304           1 :     const auto poSRS = poLayer->GetSpatialRef();
    9305           1 :     const int nSRID = poDS->GetSrsId(poSRS);
    9306           1 :     size_t nBLOBDestLen = 0;
    9307             :     GByte *pabyDestBLOB =
    9308           1 :         GPkgGeometryFromOGR(&oPoly, nSRID, nullptr, &nBLOBDestLen);
    9309           1 :     if (!pabyDestBLOB)
    9310             :     {
    9311           0 :         sqlite3_result_null(pContext);
    9312           0 :         return;
    9313             :     }
    9314           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    9315             :                         VSIFree);
    9316             : }
    9317             : 
    9318             : /************************************************************************/
    9319             : /*                   GPKG_ST_Hilbert_X_Y_TableName()                    */
    9320             : /************************************************************************/
    9321             : 
    9322           8 : static void GPKG_ST_Hilbert_X_Y_TableName(sqlite3_context *pContext,
    9323             :                                           [[maybe_unused]] int argc,
    9324             :                                           sqlite3_value **argv)
    9325             : {
    9326           8 :     CPLAssert(argc == 3);
    9327           8 :     const double dfX = sqlite3_value_double(argv[0]);
    9328           8 :     const double dfY = sqlite3_value_double(argv[1]);
    9329             : 
    9330           8 :     if (sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    9331             :     {
    9332           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9333             :                  "%s: Invalid argument type for 3rd argument. Text expected",
    9334             :                  "ST_Hilbert()");
    9335           1 :         sqlite3_result_null(pContext);
    9336           6 :         return;
    9337             :     }
    9338             : 
    9339             :     const char *pszLayerName =
    9340           7 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    9341             :     GDALGeoPackageDataset *poDS =
    9342           7 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9343           7 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9344           7 :     if (!poLayer)
    9345             :     {
    9346           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer '%s'",
    9347             :                  "ST_Hilbert()", pszLayerName);
    9348           1 :         sqlite3_result_null(pContext);
    9349           1 :         return;
    9350             :     }
    9351             : 
    9352           6 :     OGREnvelope sExtent;
    9353           6 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9354             :     {
    9355           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9356             :                  "ST_Hilbert()");
    9357           0 :         sqlite3_result_null(pContext);
    9358           0 :         return;
    9359             :     }
    9360           6 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9361           3 :           dfY <= sExtent.MaxY))
    9362             :     {
    9363           4 :         CPLError(CE_Warning, CPLE_AppDefined,
    9364             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9365             :                  dfX, dfY);
    9366           4 :         sqlite3_result_null(pContext);
    9367           4 :         return;
    9368             :     }
    9369           2 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9370             : }
    9371             : 
    9372             : /************************************************************************/
    9373             : /*                     GPKG_ST_Hilbert_Geom_BBOX()                      */
    9374             : /************************************************************************/
    9375             : 
    9376           6 : static void GPKG_ST_Hilbert_Geom_BBOX(sqlite3_context *pContext, int argc,
    9377             :                                       sqlite3_value **argv)
    9378             : {
    9379           6 :     CPLAssert(argc == 5);
    9380             :     GPkgHeader sHeader;
    9381           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    9382             :     {
    9383           1 :         sqlite3_result_null(pContext);
    9384           5 :         return;
    9385             :     }
    9386           5 :     const double dfX = (sHeader.MinX + sHeader.MaxX) / 2;
    9387           5 :     const double dfY = (sHeader.MinY + sHeader.MaxY) / 2;
    9388             : 
    9389           5 :     OGREnvelope sExtent;
    9390           5 :     sExtent.MinX = sqlite3_value_double(argv[1]);
    9391           5 :     sExtent.MinY = sqlite3_value_double(argv[2]);
    9392           5 :     sExtent.MaxX = sqlite3_value_double(argv[3]);
    9393           5 :     sExtent.MaxY = sqlite3_value_double(argv[4]);
    9394           5 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9395           2 :           dfY <= sExtent.MaxY))
    9396             :     {
    9397           4 :         CPLError(CE_Warning, CPLE_AppDefined,
    9398             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9399             :                  dfX, dfY);
    9400           4 :         sqlite3_result_null(pContext);
    9401           4 :         return;
    9402             :     }
    9403           1 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9404             : }
    9405             : 
    9406             : /************************************************************************/
    9407             : /*                   GPKG_ST_Hilbert_Geom_TableName()                   */
    9408             : /************************************************************************/
    9409             : 
    9410           4 : static void GPKG_ST_Hilbert_Geom_TableName(sqlite3_context *pContext, int argc,
    9411             :                                            sqlite3_value **argv)
    9412             : {
    9413           4 :     CPLAssert(argc == 2);
    9414             :     GPkgHeader sHeader;
    9415           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    9416             :     {
    9417           1 :         sqlite3_result_null(pContext);
    9418           3 :         return;
    9419             :     }
    9420           3 :     const double dfX = (sHeader.MinX + sHeader.MaxX) / 2;
    9421           3 :     const double dfY = (sHeader.MinY + sHeader.MaxY) / 2;
    9422             : 
    9423           3 :     if (sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9424             :     {
    9425           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9426             :                  "%s: Invalid argument type for 2nd argument. Text expected",
    9427             :                  "ST_Hilbert()");
    9428           1 :         sqlite3_result_null(pContext);
    9429           1 :         return;
    9430             :     }
    9431             : 
    9432             :     const char *pszLayerName =
    9433           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9434             :     GDALGeoPackageDataset *poDS =
    9435           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9436           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9437           2 :     if (!poLayer)
    9438             :     {
    9439           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer '%s'",
    9440             :                  "ST_Hilbert()", pszLayerName);
    9441           1 :         sqlite3_result_null(pContext);
    9442           1 :         return;
    9443             :     }
    9444             : 
    9445           1 :     OGREnvelope sExtent;
    9446           1 :     if (poLayer->GetExtent(&sExtent, true) != OGRERR_NONE)
    9447             :     {
    9448           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9449             :                  "ST_Hilbert()");
    9450           0 :         sqlite3_result_null(pContext);
    9451           0 :         return;
    9452             :     }
    9453           1 :     if (!(dfX >= sExtent.MinX && dfY >= sExtent.MinY && dfX <= sExtent.MaxX &&
    9454           1 :           dfY <= sExtent.MaxY))
    9455             :     {
    9456           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9457             :                  "ST_Hilbert(): (%g, %g) is not within passed bounding box",
    9458             :                  dfX, dfY);
    9459           0 :         sqlite3_result_null(pContext);
    9460           0 :         return;
    9461             :     }
    9462           1 :     sqlite3_result_int64(pContext, GDALHilbertCode(&sExtent, dfX, dfY));
    9463             : }
    9464             : 
    9465             : /************************************************************************/
    9466             : /*                        InstallSQLFunctions()                         */
    9467             : /************************************************************************/
    9468             : 
    9469             : #ifndef SQLITE_DETERMINISTIC
    9470             : #define SQLITE_DETERMINISTIC 0
    9471             : #endif
    9472             : 
    9473             : #ifndef SQLITE_INNOCUOUS
    9474             : #define SQLITE_INNOCUOUS 0
    9475             : #endif
    9476             : 
    9477             : #ifndef UTF8_INNOCUOUS
    9478             : #define UTF8_INNOCUOUS (SQLITE_UTF8 | SQLITE_DETERMINISTIC | SQLITE_INNOCUOUS)
    9479             : #endif
    9480             : 
    9481        2427 : void GDALGeoPackageDataset::InstallSQLFunctions()
    9482             : {
    9483        2427 :     InitSpatialite();
    9484             : 
    9485             :     // Enable SpatiaLite 4.3 GPKG mode, i.e. that SpatiaLite functions
    9486             :     // that take geometries will accept and return GPKG encoded geometries without
    9487             :     // explicit conversion.
    9488             :     // Use sqlite3_exec() instead of SQLCommand() since we don't want verbose
    9489             :     // error.
    9490        2427 :     sqlite3_exec(hDB, "SELECT EnableGpkgMode()", nullptr, nullptr, nullptr);
    9491             : 
    9492             :     /* Used by RTree Spatial Index Extension */
    9493        2427 :     sqlite3_create_function(hDB, "ST_MinX", 1, UTF8_INNOCUOUS, nullptr,
    9494             :                             OGRGeoPackageSTMinX, nullptr, nullptr);
    9495        2427 :     sqlite3_create_function(hDB, "ST_MinY", 1, UTF8_INNOCUOUS, nullptr,
    9496             :                             OGRGeoPackageSTMinY, nullptr, nullptr);
    9497        2427 :     sqlite3_create_function(hDB, "ST_MaxX", 1, UTF8_INNOCUOUS, nullptr,
    9498             :                             OGRGeoPackageSTMaxX, nullptr, nullptr);
    9499        2427 :     sqlite3_create_function(hDB, "ST_MaxY", 1, UTF8_INNOCUOUS, nullptr,
    9500             :                             OGRGeoPackageSTMaxY, nullptr, nullptr);
    9501        2427 :     sqlite3_create_function(hDB, "ST_IsEmpty", 1, UTF8_INNOCUOUS, nullptr,
    9502             :                             OGRGeoPackageSTIsEmpty, nullptr, nullptr);
    9503             : 
    9504             :     /* Used by Geometry Type Triggers Extension */
    9505        2427 :     sqlite3_create_function(hDB, "ST_GeometryType", 1, UTF8_INNOCUOUS, nullptr,
    9506             :                             OGRGeoPackageSTGeometryType, nullptr, nullptr);
    9507        2427 :     sqlite3_create_function(hDB, "GPKG_IsAssignable", 2, UTF8_INNOCUOUS,
    9508             :                             nullptr, OGRGeoPackageGPKGIsAssignable, nullptr,
    9509             :                             nullptr);
    9510             : 
    9511             :     /* Used by Geometry SRS ID Triggers Extension */
    9512        2427 :     sqlite3_create_function(hDB, "ST_SRID", 1, UTF8_INNOCUOUS, nullptr,
    9513             :                             OGRGeoPackageSTSRID, nullptr, nullptr);
    9514             : 
    9515             :     /* Spatialite-like functions */
    9516        2427 :     sqlite3_create_function(hDB, "CreateSpatialIndex", 2, SQLITE_UTF8, this,
    9517             :                             OGRGeoPackageCreateSpatialIndex, nullptr, nullptr);
    9518        2427 :     sqlite3_create_function(hDB, "DisableSpatialIndex", 2, SQLITE_UTF8, this,
    9519             :                             OGRGeoPackageDisableSpatialIndex, nullptr, nullptr);
    9520        2427 :     sqlite3_create_function(hDB, "HasSpatialIndex", 2, SQLITE_UTF8, this,
    9521             :                             OGRGeoPackageHasSpatialIndex, nullptr, nullptr);
    9522             : 
    9523             :     // HSTORE functions
    9524        2427 :     sqlite3_create_function(hDB, "hstore_get_value", 2, UTF8_INNOCUOUS, nullptr,
    9525             :                             GPKG_hstore_get_value, nullptr, nullptr);
    9526             : 
    9527             :     // Override a few Spatialite functions to work with gpkg_spatial_ref_sys
    9528        2427 :     sqlite3_create_function(hDB, "ST_Transform", 2, UTF8_INNOCUOUS, this,
    9529             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9530        2427 :     sqlite3_create_function(hDB, "Transform", 2, UTF8_INNOCUOUS, this,
    9531             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9532        2427 :     sqlite3_create_function(hDB, "SridFromAuthCRS", 2, SQLITE_UTF8, this,
    9533             :                             OGRGeoPackageSridFromAuthCRS, nullptr, nullptr);
    9534             : 
    9535        2427 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9536             :                             OGRGeoPackageSTEnvelopesIntersectsTwoParams,
    9537             :                             nullptr, nullptr);
    9538        2427 :     sqlite3_create_function(
    9539             :         hDB, "ST_EnvelopesIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9540             :         OGRGeoPackageSTEnvelopesIntersectsTwoParams, nullptr, nullptr);
    9541             : 
    9542        2427 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 5, UTF8_INNOCUOUS, nullptr,
    9543             :                             OGRGeoPackageSTEnvelopesIntersects, nullptr,
    9544             :                             nullptr);
    9545        2427 :     sqlite3_create_function(hDB, "ST_EnvelopesIntersects", 5, UTF8_INNOCUOUS,
    9546             :                             nullptr, OGRGeoPackageSTEnvelopesIntersects,
    9547             :                             nullptr, nullptr);
    9548             : 
    9549             :     // Implementation that directly hacks the GeoPackage geometry blob header
    9550        2427 :     sqlite3_create_function(hDB, "SetSRID", 2, UTF8_INNOCUOUS, nullptr,
    9551             :                             OGRGeoPackageSetSRID, nullptr, nullptr);
    9552             : 
    9553             :     // GDAL specific function
    9554        2427 :     sqlite3_create_function(hDB, "ImportFromEPSG", 1, SQLITE_UTF8, this,
    9555             :                             OGRGeoPackageImportFromEPSG, nullptr, nullptr);
    9556             : 
    9557             :     // May be used by ogrmerge.py
    9558        2427 :     sqlite3_create_function(hDB, "RegisterGeometryExtension", 3, SQLITE_UTF8,
    9559             :                             this, OGRGeoPackageRegisterGeometryExtension,
    9560             :                             nullptr, nullptr);
    9561             : 
    9562        2427 :     if (OGRGeometryFactory::haveGEOS())
    9563             :     {
    9564        2427 :         sqlite3_create_function(hDB, "ST_MakeValid", 1, UTF8_INNOCUOUS, nullptr,
    9565             :                                 OGRGeoPackageSTMakeValid, nullptr, nullptr);
    9566             :     }
    9567             : 
    9568        2427 :     sqlite3_create_function(hDB, "ST_Length", 1, UTF8_INNOCUOUS, nullptr,
    9569             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9570             :                             nullptr);
    9571        2427 :     sqlite3_create_function(hDB, "ST_Length", 2, UTF8_INNOCUOUS, this,
    9572             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9573             :                             nullptr);
    9574             : 
    9575        2427 :     sqlite3_create_function(hDB, "ST_Area", 1, UTF8_INNOCUOUS, nullptr,
    9576             :                             OGRGeoPackageSTArea, nullptr, nullptr);
    9577        2427 :     sqlite3_create_function(hDB, "ST_Area", 2, UTF8_INNOCUOUS, this,
    9578             :                             OGRGeoPackageGeodesicArea, nullptr, nullptr);
    9579             : 
    9580             :     // Debug functions
    9581        2427 :     if (CPLTestBool(CPLGetConfigOption("GPKG_DEBUG", "FALSE")))
    9582             :     {
    9583         422 :         sqlite3_create_function(hDB, "GDAL_GetMimeType", 1,
    9584             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9585             :                                 GPKG_GDAL_GetMimeType, nullptr, nullptr);
    9586         422 :         sqlite3_create_function(hDB, "GDAL_GetBandCount", 1,
    9587             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9588             :                                 GPKG_GDAL_GetBandCount, nullptr, nullptr);
    9589         422 :         sqlite3_create_function(hDB, "GDAL_HasColorTable", 1,
    9590             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9591             :                                 GPKG_GDAL_HasColorTable, nullptr, nullptr);
    9592             :     }
    9593             : 
    9594        2427 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 5, SQLITE_UTF8,
    9595             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9596             :                             nullptr);
    9597        2427 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 6, SQLITE_UTF8,
    9598             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9599             :                             nullptr);
    9600             : 
    9601             :     // Function from VirtualOGR
    9602        2427 :     sqlite3_create_function(hDB, "ogr_layer_Extent", 1, SQLITE_UTF8, this,
    9603             :                             GPKG_ogr_layer_Extent, nullptr, nullptr);
    9604             : 
    9605        2427 :     m_pSQLFunctionData = OGRSQLiteRegisterSQLFunctionsCommon(hDB);
    9606             : 
    9607             :     // ST_Hilbert() inspired from https://duckdb.org/docs/stable/core_extensions/spatial/functions#st_hilbert
    9608             :     // Override the generic version of OGRSQLiteRegisterSQLFunctionsCommon()
    9609             : 
    9610             :     // X,Y,table_name
    9611        2427 :     sqlite3_create_function(hDB, "ST_Hilbert", 2 + 1, UTF8_INNOCUOUS, this,
    9612             :                             GPKG_ST_Hilbert_X_Y_TableName, nullptr, nullptr);
    9613             : 
    9614             :     // geometry,minX,minY,maxX,maxY
    9615        2427 :     sqlite3_create_function(hDB, "ST_Hilbert", 1 + 4, UTF8_INNOCUOUS, nullptr,
    9616             :                             GPKG_ST_Hilbert_Geom_BBOX, nullptr, nullptr);
    9617             : 
    9618             :     // geometry,table_name
    9619        2427 :     sqlite3_create_function(hDB, "ST_Hilbert", 1 + 1, UTF8_INNOCUOUS, this,
    9620             :                             GPKG_ST_Hilbert_Geom_TableName, nullptr, nullptr);
    9621        2427 : }
    9622             : 
    9623             : /************************************************************************/
    9624             : /*                           OpenOrCreateDB()                           */
    9625             : /************************************************************************/
    9626             : 
    9627        2433 : bool GDALGeoPackageDataset::OpenOrCreateDB(int flags)
    9628             : {
    9629        2433 :     const bool bSuccess = OGRSQLiteBaseDataSource::OpenOrCreateDB(
    9630             :         flags, /*bRegisterOGR2SQLiteExtensions=*/false,
    9631             :         /*bLoadExtensions=*/true);
    9632        2433 :     if (!bSuccess)
    9633          11 :         return false;
    9634             : 
    9635             :     // Turning on recursive_triggers is needed so that DELETE triggers fire
    9636             :     // in a INSERT OR REPLACE statement. In particular this is needed to
    9637             :     // make sure gpkg_ogr_contents.feature_count is properly updated.
    9638        2422 :     SQLCommand(hDB, "PRAGMA recursive_triggers = 1");
    9639             : 
    9640        2422 :     InstallSQLFunctions();
    9641             : 
    9642             :     const char *pszSqlitePragma =
    9643        2422 :         CPLGetConfigOption("OGR_SQLITE_PRAGMA", nullptr);
    9644        2422 :     OGRErr eErr = OGRERR_NONE;
    9645           6 :     if ((!pszSqlitePragma || !strstr(pszSqlitePragma, "trusted_schema")) &&
    9646             :         // Older sqlite versions don't have this pragma
    9647        4850 :         SQLGetInteger(hDB, "PRAGMA trusted_schema", &eErr) == 0 &&
    9648        2422 :         eErr == OGRERR_NONE)
    9649             :     {
    9650        2422 :         bool bNeedsTrustedSchema = false;
    9651             : 
    9652             :         // Current SQLite versions require PRAGMA trusted_schema = 1 to be
    9653             :         // able to use the RTree from triggers, which is only needed when
    9654             :         // modifying the RTree.
    9655        5945 :         if (((flags & SQLITE_OPEN_READWRITE) != 0 ||
    9656        3743 :              (flags & SQLITE_OPEN_CREATE) != 0) &&
    9657        1321 :             OGRSQLiteRTreeRequiresTrustedSchemaOn())
    9658             :         {
    9659        1321 :             bNeedsTrustedSchema = true;
    9660             :         }
    9661             : 
    9662             : #ifdef HAVE_SPATIALITE
    9663             :         // Spatialite <= 5.1.0 doesn't declare its functions as SQLITE_INNOCUOUS
    9664        1101 :         if (!bNeedsTrustedSchema && HasExtensionsTable() &&
    9665        1009 :             SQLGetInteger(
    9666             :                 hDB,
    9667             :                 "SELECT 1 FROM gpkg_extensions WHERE "
    9668             :                 "extension_name ='gdal_spatialite_computed_geom_column'",
    9669           1 :                 nullptr) == 1 &&
    9670        3523 :             SpatialiteRequiresTrustedSchemaOn() && AreSpatialiteTriggersSafe())
    9671             :         {
    9672           1 :             bNeedsTrustedSchema = true;
    9673             :         }
    9674             : #endif
    9675             : 
    9676        2422 :         if (bNeedsTrustedSchema)
    9677             :         {
    9678        1322 :             CPLDebug("GPKG", "Setting PRAGMA trusted_schema = 1");
    9679        1322 :             SQLCommand(hDB, "PRAGMA trusted_schema = 1");
    9680             :         }
    9681             :     }
    9682             : 
    9683             :     const char *pszPreludeStatements =
    9684        2422 :         CSLFetchNameValue(papszOpenOptions, "PRELUDE_STATEMENTS");
    9685        2422 :     if (pszPreludeStatements)
    9686             :     {
    9687           2 :         if (SQLCommand(hDB, pszPreludeStatements) != OGRERR_NONE)
    9688           0 :             return false;
    9689             :     }
    9690             : 
    9691        2422 :     return true;
    9692             : }
    9693             : 
    9694             : /************************************************************************/
    9695             : /*                 GetLayerWithGetSpatialWhereByName()                  */
    9696             : /************************************************************************/
    9697             : 
    9698             : std::pair<OGRLayer *, IOGRSQLiteGetSpatialWhere *>
    9699          90 : GDALGeoPackageDataset::GetLayerWithGetSpatialWhereByName(const char *pszName)
    9700             : {
    9701             :     OGRGeoPackageLayer *poRet =
    9702          90 :         cpl::down_cast<OGRGeoPackageLayer *>(GetLayerByName(pszName));
    9703          90 :     return std::pair(poRet, poRet);
    9704             : }
    9705             : 
    9706             : /************************************************************************/
    9707             : /*                         CommitTransaction()                          */
    9708             : /************************************************************************/
    9709             : 
    9710         373 : OGRErr GDALGeoPackageDataset::CommitTransaction()
    9711             : 
    9712             : {
    9713         373 :     if (m_nSoftTransactionLevel == 1)
    9714             :     {
    9715         367 :         FlushMetadata();
    9716         789 :         for (auto &poLayer : m_apoLayers)
    9717             :         {
    9718         422 :             poLayer->DoJobAtTransactionCommit();
    9719             :         }
    9720             :     }
    9721             : 
    9722         373 :     return OGRSQLiteBaseDataSource::CommitTransaction();
    9723             : }
    9724             : 
    9725             : /************************************************************************/
    9726             : /*                        RollbackTransaction()                         */
    9727             : /************************************************************************/
    9728             : 
    9729          37 : OGRErr GDALGeoPackageDataset::RollbackTransaction()
    9730             : 
    9731             : {
    9732             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9733          74 :     std::vector<bool> abAddTriggers;
    9734          37 :     std::vector<bool> abTriggersDeletedInTransaction;
    9735             : #endif
    9736          37 :     if (m_nSoftTransactionLevel == 1)
    9737             :     {
    9738          36 :         FlushMetadata();
    9739          74 :         for (auto &poLayer : m_apoLayers)
    9740             :         {
    9741             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9742          38 :             abAddTriggers.push_back(poLayer->GetAddOGRFeatureCountTriggers());
    9743          38 :             abTriggersDeletedInTransaction.push_back(
    9744          38 :                 poLayer->GetOGRFeatureCountTriggersDeletedInTransaction());
    9745          38 :             poLayer->SetAddOGRFeatureCountTriggers(false);
    9746             : #endif
    9747          38 :             poLayer->DoJobAtTransactionRollback();
    9748             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9749          38 :             poLayer->DisableFeatureCount();
    9750             : #endif
    9751             :         }
    9752             :     }
    9753             : 
    9754          37 :     const OGRErr eErr = OGRSQLiteBaseDataSource::RollbackTransaction();
    9755             : 
    9756             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9757          37 :     if (!abAddTriggers.empty())
    9758             :     {
    9759          72 :         for (size_t i = 0; i < m_apoLayers.size(); ++i)
    9760             :         {
    9761          38 :             auto &poLayer = m_apoLayers[i];
    9762          38 :             if (abTriggersDeletedInTransaction[i])
    9763             :             {
    9764           7 :                 poLayer->SetOGRFeatureCountTriggersEnabled(true);
    9765             :             }
    9766             :             else
    9767             :             {
    9768          31 :                 poLayer->SetAddOGRFeatureCountTriggers(abAddTriggers[i]);
    9769             :             }
    9770             :         }
    9771             :     }
    9772             : #endif
    9773          74 :     return eErr;
    9774             : }
    9775             : 
    9776             : /************************************************************************/
    9777             : /*                       GetGeometryTypeString()                        */
    9778             : /************************************************************************/
    9779             : 
    9780             : const char *
    9781        1769 : GDALGeoPackageDataset::GetGeometryTypeString(OGRwkbGeometryType eType)
    9782             : {
    9783        1769 :     const char *pszGPKGGeomType = OGRToOGCGeomType(eType);
    9784        1781 :     if (EQUAL(pszGPKGGeomType, "GEOMETRYCOLLECTION") &&
    9785          12 :         CPLTestBool(CPLGetConfigOption("OGR_GPKG_GEOMCOLLECTION", "NO")))
    9786             :     {
    9787           0 :         pszGPKGGeomType = "GEOMCOLLECTION";
    9788             :     }
    9789        1769 :     return pszGPKGGeomType;
    9790             : }
    9791             : 
    9792             : /************************************************************************/
    9793             : /*                        GetFieldDomainNames()                         */
    9794             : /************************************************************************/
    9795             : 
    9796             : std::vector<std::string>
    9797          15 : GDALGeoPackageDataset::GetFieldDomainNames(CSLConstList) const
    9798             : {
    9799          15 :     if (!HasDataColumnConstraintsTable())
    9800           3 :         return std::vector<std::string>();
    9801             : 
    9802          24 :     std::vector<std::string> oDomainNamesList;
    9803             : 
    9804          12 :     std::unique_ptr<SQLResult> oResultTable;
    9805             :     {
    9806             :         std::string osSQL =
    9807             :             "SELECT DISTINCT constraint_name "
    9808             :             "FROM gpkg_data_column_constraints "
    9809             :             "WHERE constraint_name NOT LIKE '_%_domain_description' "
    9810             :             "ORDER BY constraint_name "
    9811          12 :             "LIMIT 10000"  // to avoid denial of service
    9812             :             ;
    9813          12 :         oResultTable = SQLQuery(hDB, osSQL.c_str());
    9814          12 :         if (!oResultTable)
    9815           0 :             return oDomainNamesList;
    9816             :     }
    9817             : 
    9818          12 :     if (oResultTable->RowCount() == 10000)
    9819             :     {
    9820           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9821             :                  "Number of rows returned for field domain names has been "
    9822             :                  "truncated.");
    9823             :     }
    9824          12 :     else if (oResultTable->RowCount() > 0)
    9825             :     {
    9826          11 :         oDomainNamesList.reserve(oResultTable->RowCount());
    9827         126 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    9828             :         {
    9829         115 :             const char *pszConstraintName = oResultTable->GetValue(0, i);
    9830         115 :             if (!pszConstraintName)
    9831           0 :                 continue;
    9832             : 
    9833         115 :             oDomainNamesList.emplace_back(pszConstraintName);
    9834             :         }
    9835             :     }
    9836             : 
    9837          12 :     return oDomainNamesList;
    9838             : }
    9839             : 
    9840             : /************************************************************************/
    9841             : /*                           GetFieldDomain()                           */
    9842             : /************************************************************************/
    9843             : 
    9844             : const OGRFieldDomain *
    9845         139 : GDALGeoPackageDataset::GetFieldDomain(const std::string &name) const
    9846             : {
    9847         139 :     const auto baseRet = GDALDataset::GetFieldDomain(name);
    9848         139 :     if (baseRet)
    9849          43 :         return baseRet;
    9850             : 
    9851          96 :     if (!HasDataColumnConstraintsTable())
    9852           4 :         return nullptr;
    9853             : 
    9854          92 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
    9855          92 :     const char *min_is_inclusive =
    9856          92 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
    9857          92 :     const char *max_is_inclusive =
    9858          92 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
    9859             : 
    9860          92 :     std::unique_ptr<SQLResult> oResultTable;
    9861             :     // Note: for coded domains, we use a little trick by using a dummy
    9862             :     // _{domainname}_domain_description enum that has a single entry whose
    9863             :     // description is the description of the main domain.
    9864             :     {
    9865          92 :         char *pszSQL = sqlite3_mprintf(
    9866             :             "SELECT constraint_type, value, min, %s, "
    9867             :             "max, %s, description, constraint_name "
    9868             :             "FROM gpkg_data_column_constraints "
    9869             :             "WHERE constraint_name IN ('%q', "
    9870             :             "'_%q_domain_description') "
    9871             :             "AND length(constraint_type) < 100 "  // to
    9872             :                                                   // avoid
    9873             :                                                   // denial
    9874             :                                                   // of
    9875             :                                                   // service
    9876             :             "AND (value IS NULL OR length(value) < "
    9877             :             "10000) "  // to avoid denial
    9878             :                        // of service
    9879             :             "AND (description IS NULL OR "
    9880             :             "length(description) < 10000) "  // to
    9881             :                                              // avoid
    9882             :                                              // denial
    9883             :                                              // of
    9884             :                                              // service
    9885             :             "ORDER BY value "
    9886             :             "LIMIT 10000",  // to avoid denial of
    9887             :                             // service
    9888             :             min_is_inclusive, max_is_inclusive, name.c_str(), name.c_str());
    9889          92 :         oResultTable = SQLQuery(hDB, pszSQL);
    9890          92 :         sqlite3_free(pszSQL);
    9891          92 :         if (!oResultTable)
    9892           0 :             return nullptr;
    9893             :     }
    9894          92 :     if (oResultTable->RowCount() == 0)
    9895             :     {
    9896          33 :         return nullptr;
    9897             :     }
    9898          59 :     if (oResultTable->RowCount() == 10000)
    9899             :     {
    9900           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9901             :                  "Number of rows returned for field domain %s has been "
    9902             :                  "truncated.",
    9903             :                  name.c_str());
    9904             :     }
    9905             : 
    9906             :     // Try to find the field domain data type from fields that implement it
    9907          59 :     int nFieldType = -1;
    9908          59 :     OGRFieldSubType eSubType = OFSTNone;
    9909          59 :     if (HasDataColumnsTable())
    9910             :     {
    9911          54 :         char *pszSQL = sqlite3_mprintf(
    9912             :             "SELECT table_name, column_name FROM gpkg_data_columns WHERE "
    9913             :             "constraint_name = '%q' LIMIT 10",
    9914             :             name.c_str());
    9915         108 :         auto oResultTable2 = SQLQuery(hDB, pszSQL);
    9916          54 :         sqlite3_free(pszSQL);
    9917          54 :         if (oResultTable2 && oResultTable2->RowCount() >= 1)
    9918             :         {
    9919          60 :             for (int iRecord = 0; iRecord < oResultTable2->RowCount();
    9920             :                  iRecord++)
    9921             :             {
    9922          30 :                 const char *pszTableName = oResultTable2->GetValue(0, iRecord);
    9923          30 :                 const char *pszColumnName = oResultTable2->GetValue(1, iRecord);
    9924          30 :                 if (pszTableName == nullptr || pszColumnName == nullptr)
    9925           0 :                     continue;
    9926             :                 OGRLayer *poLayer =
    9927          60 :                     const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    9928          30 :                         pszTableName);
    9929          30 :                 if (poLayer)
    9930             :                 {
    9931          30 :                     const auto poFDefn = poLayer->GetLayerDefn();
    9932          30 :                     int nIdx = poFDefn->GetFieldIndex(pszColumnName);
    9933          30 :                     if (nIdx >= 0)
    9934             :                     {
    9935          30 :                         const auto poFieldDefn = poFDefn->GetFieldDefn(nIdx);
    9936          30 :                         const auto eType = poFieldDefn->GetType();
    9937          30 :                         if (nFieldType < 0)
    9938             :                         {
    9939          30 :                             nFieldType = eType;
    9940          30 :                             eSubType = poFieldDefn->GetSubType();
    9941             :                         }
    9942           0 :                         else if ((eType == OFTInteger64 || eType == OFTReal) &&
    9943             :                                  nFieldType == OFTInteger)
    9944             :                         {
    9945             :                             // ok
    9946             :                         }
    9947           0 :                         else if (eType == OFTInteger &&
    9948           0 :                                  (nFieldType == OFTInteger64 ||
    9949             :                                   nFieldType == OFTReal))
    9950             :                         {
    9951           0 :                             nFieldType = OFTInteger;
    9952           0 :                             eSubType = OFSTNone;
    9953             :                         }
    9954           0 :                         else if (nFieldType != eType)
    9955             :                         {
    9956           0 :                             nFieldType = -1;
    9957           0 :                             eSubType = OFSTNone;
    9958           0 :                             break;
    9959             :                         }
    9960             :                     }
    9961             :                 }
    9962             :             }
    9963             :         }
    9964             :     }
    9965             : 
    9966          59 :     std::unique_ptr<OGRFieldDomain> poDomain;
    9967         118 :     std::vector<OGRCodedValue> asValues;
    9968          59 :     bool error = false;
    9969         118 :     CPLString osLastConstraintType;
    9970          59 :     int nFieldTypeFromEnumCode = -1;
    9971         118 :     std::string osConstraintDescription;
    9972         118 :     std::string osDescrConstraintName("_");
    9973          59 :     osDescrConstraintName += name;
    9974          59 :     osDescrConstraintName += "_domain_description";
    9975         148 :     for (int iRecord = 0; iRecord < oResultTable->RowCount(); iRecord++)
    9976             :     {
    9977          93 :         const char *pszConstraintType = oResultTable->GetValue(0, iRecord);
    9978          93 :         if (pszConstraintType == nullptr)
    9979           2 :             continue;
    9980          93 :         const char *pszValue = oResultTable->GetValue(1, iRecord);
    9981          93 :         const char *pszMin = oResultTable->GetValue(2, iRecord);
    9982             :         const bool bIsMinIncluded =
    9983          93 :             oResultTable->GetValueAsInteger(3, iRecord) == 1;
    9984          93 :         const char *pszMax = oResultTable->GetValue(4, iRecord);
    9985             :         const bool bIsMaxIncluded =
    9986          93 :             oResultTable->GetValueAsInteger(5, iRecord) == 1;
    9987          93 :         const char *pszDescription = oResultTable->GetValue(6, iRecord);
    9988          93 :         const char *pszConstraintName = oResultTable->GetValue(7, iRecord);
    9989             : 
    9990          93 :         if (!osLastConstraintType.empty() && osLastConstraintType != "enum")
    9991             :         {
    9992           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    9993             :                      "Only constraint of type 'enum' can have multiple rows");
    9994           1 :             error = true;
    9995           4 :             break;
    9996             :         }
    9997             : 
    9998          92 :         if (strcmp(pszConstraintType, "enum") == 0)
    9999             :         {
   10000          65 :             if (pszValue == nullptr)
   10001             :             {
   10002           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10003             :                          "NULL in 'value' column of enumeration");
   10004           1 :                 error = true;
   10005           1 :                 break;
   10006             :             }
   10007          64 :             if (osDescrConstraintName == pszConstraintName)
   10008             :             {
   10009           2 :                 if (pszDescription)
   10010             :                 {
   10011           2 :                     osConstraintDescription = pszDescription;
   10012             :                 }
   10013           2 :                 continue;
   10014             :             }
   10015          62 :             if (asValues.empty())
   10016             :             {
   10017          31 :                 asValues.reserve(oResultTable->RowCount() + 1);
   10018             :             }
   10019             :             OGRCodedValue cv;
   10020             :             // intended: the 'value' column in GPKG is actually the code
   10021          62 :             cv.pszCode = VSI_STRDUP_VERBOSE(pszValue);
   10022          62 :             if (cv.pszCode == nullptr)
   10023             :             {
   10024           0 :                 error = true;
   10025           0 :                 break;
   10026             :             }
   10027          62 :             if (pszDescription)
   10028             :             {
   10029          49 :                 cv.pszValue = VSI_STRDUP_VERBOSE(pszDescription);
   10030          49 :                 if (cv.pszValue == nullptr)
   10031             :                 {
   10032           0 :                     VSIFree(cv.pszCode);
   10033           0 :                     error = true;
   10034           0 :                     break;
   10035             :                 }
   10036             :             }
   10037             :             else
   10038             :             {
   10039          13 :                 cv.pszValue = nullptr;
   10040             :             }
   10041             : 
   10042             :             // If we can't get the data type from field definition, guess it
   10043             :             // from code.
   10044          62 :             if (nFieldType < 0 && nFieldTypeFromEnumCode != OFTString)
   10045             :             {
   10046          36 :                 switch (CPLGetValueType(cv.pszCode))
   10047             :                 {
   10048          26 :                     case CPL_VALUE_INTEGER:
   10049             :                     {
   10050          26 :                         if (nFieldTypeFromEnumCode != OFTReal &&
   10051             :                             nFieldTypeFromEnumCode != OFTInteger64)
   10052             :                         {
   10053          18 :                             const auto nVal = CPLAtoGIntBig(cv.pszCode);
   10054          34 :                             if (nVal < std::numeric_limits<int>::min() ||
   10055          16 :                                 nVal > std::numeric_limits<int>::max())
   10056             :                             {
   10057           6 :                                 nFieldTypeFromEnumCode = OFTInteger64;
   10058             :                             }
   10059             :                             else
   10060             :                             {
   10061          12 :                                 nFieldTypeFromEnumCode = OFTInteger;
   10062             :                             }
   10063             :                         }
   10064          26 :                         break;
   10065             :                     }
   10066             : 
   10067           6 :                     case CPL_VALUE_REAL:
   10068           6 :                         nFieldTypeFromEnumCode = OFTReal;
   10069           6 :                         break;
   10070             : 
   10071           4 :                     case CPL_VALUE_STRING:
   10072           4 :                         nFieldTypeFromEnumCode = OFTString;
   10073           4 :                         break;
   10074             :                 }
   10075             :             }
   10076             : 
   10077          62 :             asValues.emplace_back(cv);
   10078             :         }
   10079          27 :         else if (strcmp(pszConstraintType, "range") == 0)
   10080             :         {
   10081             :             OGRField sMin;
   10082             :             OGRField sMax;
   10083          20 :             OGR_RawField_SetUnset(&sMin);
   10084          20 :             OGR_RawField_SetUnset(&sMax);
   10085          20 :             if (nFieldType != OFTInteger && nFieldType != OFTInteger64)
   10086          11 :                 nFieldType = OFTReal;
   10087          39 :             if (pszMin != nullptr &&
   10088          19 :                 CPLAtof(pszMin) != -std::numeric_limits<double>::infinity())
   10089             :             {
   10090          15 :                 if (nFieldType == OFTInteger)
   10091           6 :                     sMin.Integer = atoi(pszMin);
   10092           9 :                 else if (nFieldType == OFTInteger64)
   10093           3 :                     sMin.Integer64 = CPLAtoGIntBig(pszMin);
   10094             :                 else /* if( nFieldType == OFTReal ) */
   10095           6 :                     sMin.Real = CPLAtof(pszMin);
   10096             :             }
   10097          39 :             if (pszMax != nullptr &&
   10098          19 :                 CPLAtof(pszMax) != std::numeric_limits<double>::infinity())
   10099             :             {
   10100          15 :                 if (nFieldType == OFTInteger)
   10101           6 :                     sMax.Integer = atoi(pszMax);
   10102           9 :                 else if (nFieldType == OFTInteger64)
   10103           3 :                     sMax.Integer64 = CPLAtoGIntBig(pszMax);
   10104             :                 else /* if( nFieldType == OFTReal ) */
   10105           6 :                     sMax.Real = CPLAtof(pszMax);
   10106             :             }
   10107          20 :             poDomain = std::make_unique<OGRRangeFieldDomain>(
   10108          20 :                 name, pszDescription ? pszDescription : "",
   10109          40 :                 static_cast<OGRFieldType>(nFieldType), eSubType, sMin,
   10110          20 :                 bIsMinIncluded, sMax, bIsMaxIncluded);
   10111             :         }
   10112           7 :         else if (strcmp(pszConstraintType, "glob") == 0)
   10113             :         {
   10114           6 :             if (pszValue == nullptr)
   10115             :             {
   10116           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10117             :                          "NULL in 'value' column of glob");
   10118           1 :                 error = true;
   10119           1 :                 break;
   10120             :             }
   10121           5 :             if (nFieldType < 0)
   10122           1 :                 nFieldType = OFTString;
   10123           5 :             poDomain = std::make_unique<OGRGlobFieldDomain>(
   10124           5 :                 name, pszDescription ? pszDescription : "",
   10125          15 :                 static_cast<OGRFieldType>(nFieldType), eSubType, pszValue);
   10126             :         }
   10127             :         else
   10128             :         {
   10129           1 :             CPLError(CE_Failure, CPLE_AppDefined,
   10130             :                      "Unhandled constraint_type: %s", pszConstraintType);
   10131           1 :             error = true;
   10132           1 :             break;
   10133             :         }
   10134             : 
   10135          87 :         osLastConstraintType = pszConstraintType;
   10136             :     }
   10137             : 
   10138          59 :     if (!asValues.empty())
   10139             :     {
   10140          31 :         if (nFieldType < 0)
   10141          18 :             nFieldType = nFieldTypeFromEnumCode;
   10142          31 :         poDomain = std::make_unique<OGRCodedFieldDomain>(
   10143             :             name, osConstraintDescription,
   10144          62 :             static_cast<OGRFieldType>(nFieldType), eSubType,
   10145          62 :             std::move(asValues));
   10146             :     }
   10147             : 
   10148          59 :     if (error)
   10149             :     {
   10150           4 :         return nullptr;
   10151             :     }
   10152             : 
   10153          55 :     m_oMapFieldDomains[name] = std::move(poDomain);
   10154          55 :     return GDALDataset::GetFieldDomain(name);
   10155             : }
   10156             : 
   10157             : /************************************************************************/
   10158             : /*                           AddFieldDomain()                           */
   10159             : /************************************************************************/
   10160             : 
   10161          19 : bool GDALGeoPackageDataset::AddFieldDomain(
   10162             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10163             : {
   10164          38 :     const std::string domainName(domain->GetName());
   10165          19 :     if (!GetUpdate())
   10166             :     {
   10167           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10168             :                  "AddFieldDomain() not supported on read-only dataset");
   10169           0 :         return false;
   10170             :     }
   10171          19 :     if (GetFieldDomain(domainName) != nullptr)
   10172             :     {
   10173           1 :         failureReason = "A domain of identical name already exists";
   10174           1 :         return false;
   10175             :     }
   10176          18 :     if (!CreateColumnsTableAndColumnConstraintsTablesIfNecessary())
   10177           0 :         return false;
   10178             : 
   10179          18 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
   10180          18 :     const char *min_is_inclusive =
   10181          18 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
   10182          18 :     const char *max_is_inclusive =
   10183          18 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
   10184             : 
   10185          18 :     const auto &osDescription = domain->GetDescription();
   10186          18 :     switch (domain->GetDomainType())
   10187             :     {
   10188          11 :         case OFDT_CODED:
   10189             :         {
   10190             :             const auto poCodedDomain =
   10191          11 :                 cpl::down_cast<const OGRCodedFieldDomain *>(domain.get());
   10192          11 :             if (!osDescription.empty())
   10193             :             {
   10194             :                 // We use a little trick by using a dummy
   10195             :                 // _{domainname}_domain_description enum that has a single
   10196             :                 // entry whose description is the description of the main
   10197             :                 // domain.
   10198           1 :                 char *pszSQL = sqlite3_mprintf(
   10199             :                     "INSERT INTO gpkg_data_column_constraints ("
   10200             :                     "constraint_name, constraint_type, value, "
   10201             :                     "min, %s, max, %s, "
   10202             :                     "description) VALUES ("
   10203             :                     "'_%q_domain_description', 'enum', '', NULL, NULL, NULL, "
   10204             :                     "NULL, %Q)",
   10205             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10206             :                     osDescription.c_str());
   10207           1 :                 CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
   10208           1 :                 sqlite3_free(pszSQL);
   10209             :             }
   10210          11 :             const auto &enumeration = poCodedDomain->GetEnumeration();
   10211          33 :             for (int i = 0; enumeration[i].pszCode != nullptr; ++i)
   10212             :             {
   10213          22 :                 char *pszSQL = sqlite3_mprintf(
   10214             :                     "INSERT INTO gpkg_data_column_constraints ("
   10215             :                     "constraint_name, constraint_type, value, "
   10216             :                     "min, %s, max, %s, "
   10217             :                     "description) VALUES ("
   10218             :                     "'%q', 'enum', '%q', NULL, NULL, NULL, NULL, %Q)",
   10219             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10220          22 :                     enumeration[i].pszCode, enumeration[i].pszValue);
   10221          22 :                 bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10222          22 :                 sqlite3_free(pszSQL);
   10223          22 :                 if (!ok)
   10224           0 :                     return false;
   10225             :             }
   10226          11 :             break;
   10227             :         }
   10228             : 
   10229           6 :         case OFDT_RANGE:
   10230             :         {
   10231             :             const auto poRangeDomain =
   10232           6 :                 cpl::down_cast<const OGRRangeFieldDomain *>(domain.get());
   10233           6 :             const auto eFieldType = poRangeDomain->GetFieldType();
   10234           6 :             if (eFieldType != OFTInteger && eFieldType != OFTInteger64 &&
   10235             :                 eFieldType != OFTReal)
   10236             :             {
   10237             :                 failureReason = "Only range domains of numeric type are "
   10238           0 :                                 "supported in GeoPackage";
   10239           0 :                 return false;
   10240             :             }
   10241             : 
   10242           6 :             double dfMin = -std::numeric_limits<double>::infinity();
   10243           6 :             double dfMax = std::numeric_limits<double>::infinity();
   10244           6 :             bool bMinIsInclusive = true;
   10245           6 :             const auto &sMin = poRangeDomain->GetMin(bMinIsInclusive);
   10246           6 :             bool bMaxIsInclusive = true;
   10247           6 :             const auto &sMax = poRangeDomain->GetMax(bMaxIsInclusive);
   10248           6 :             if (eFieldType == OFTInteger)
   10249             :             {
   10250           2 :                 if (!OGR_RawField_IsUnset(&sMin))
   10251           2 :                     dfMin = sMin.Integer;
   10252           2 :                 if (!OGR_RawField_IsUnset(&sMax))
   10253           2 :                     dfMax = sMax.Integer;
   10254             :             }
   10255           4 :             else if (eFieldType == OFTInteger64)
   10256             :             {
   10257           1 :                 if (!OGR_RawField_IsUnset(&sMin))
   10258           1 :                     dfMin = static_cast<double>(sMin.Integer64);
   10259           1 :                 if (!OGR_RawField_IsUnset(&sMax))
   10260           1 :                     dfMax = static_cast<double>(sMax.Integer64);
   10261             :             }
   10262             :             else /* if( eFieldType == OFTReal ) */
   10263             :             {
   10264           3 :                 if (!OGR_RawField_IsUnset(&sMin))
   10265           3 :                     dfMin = sMin.Real;
   10266           3 :                 if (!OGR_RawField_IsUnset(&sMax))
   10267           3 :                     dfMax = sMax.Real;
   10268             :             }
   10269             : 
   10270           6 :             sqlite3_stmt *hInsertStmt = nullptr;
   10271             :             const char *pszSQL =
   10272           6 :                 CPLSPrintf("INSERT INTO gpkg_data_column_constraints ("
   10273             :                            "constraint_name, constraint_type, value, "
   10274             :                            "min, %s, max, %s, "
   10275             :                            "description) VALUES ("
   10276             :                            "?, 'range', NULL, ?, ?, ?, ?, ?)",
   10277             :                            min_is_inclusive, max_is_inclusive);
   10278           6 :             if (SQLPrepareWithError(hDB, pszSQL, -1, &hInsertStmt, nullptr) !=
   10279             :                 SQLITE_OK)
   10280             :             {
   10281           0 :                 return false;
   10282             :             }
   10283           6 :             sqlite3_bind_text(hInsertStmt, 1, domainName.c_str(),
   10284           6 :                               static_cast<int>(domainName.size()),
   10285             :                               SQLITE_TRANSIENT);
   10286           6 :             sqlite3_bind_double(hInsertStmt, 2, dfMin);
   10287           6 :             sqlite3_bind_int(hInsertStmt, 3, bMinIsInclusive ? 1 : 0);
   10288           6 :             sqlite3_bind_double(hInsertStmt, 4, dfMax);
   10289           6 :             sqlite3_bind_int(hInsertStmt, 5, bMaxIsInclusive ? 1 : 0);
   10290           6 :             if (osDescription.empty())
   10291             :             {
   10292           3 :                 sqlite3_bind_null(hInsertStmt, 6);
   10293             :             }
   10294             :             else
   10295             :             {
   10296           3 :                 sqlite3_bind_text(hInsertStmt, 6, osDescription.c_str(),
   10297           3 :                                   static_cast<int>(osDescription.size()),
   10298             :                                   SQLITE_TRANSIENT);
   10299             :             }
   10300           6 :             const int sqlite_err = sqlite3_step(hInsertStmt);
   10301           6 :             sqlite3_finalize(hInsertStmt);
   10302           6 :             if (sqlite_err != SQLITE_OK && sqlite_err != SQLITE_DONE)
   10303             :             {
   10304           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10305             :                          "failed to execute insertion '%s': %s", pszSQL,
   10306             :                          sqlite3_errmsg(hDB));
   10307           0 :                 return false;
   10308             :             }
   10309             : 
   10310           6 :             break;
   10311             :         }
   10312             : 
   10313           1 :         case OFDT_GLOB:
   10314             :         {
   10315             :             const auto poGlobDomain =
   10316           1 :                 cpl::down_cast<const OGRGlobFieldDomain *>(domain.get());
   10317           2 :             char *pszSQL = sqlite3_mprintf(
   10318             :                 "INSERT INTO gpkg_data_column_constraints ("
   10319             :                 "constraint_name, constraint_type, value, "
   10320             :                 "min, %s, max, %s, "
   10321             :                 "description) VALUES ("
   10322             :                 "'%q', 'glob', '%q', NULL, NULL, NULL, NULL, %Q)",
   10323             :                 min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10324           1 :                 poGlobDomain->GetGlob().c_str(),
   10325           2 :                 osDescription.empty() ? nullptr : osDescription.c_str());
   10326           1 :             bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10327           1 :             sqlite3_free(pszSQL);
   10328           1 :             if (!ok)
   10329           0 :                 return false;
   10330             : 
   10331           1 :             break;
   10332             :         }
   10333             :     }
   10334             : 
   10335          18 :     m_oMapFieldDomains[domainName] = std::move(domain);
   10336          18 :     return true;
   10337             : }
   10338             : 
   10339             : /************************************************************************/
   10340             : /*                         UpdateFieldDomain()                          */
   10341             : /************************************************************************/
   10342             : 
   10343           3 : bool GDALGeoPackageDataset::UpdateFieldDomain(
   10344             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10345             : {
   10346           6 :     const std::string domainName(domain->GetName());
   10347           3 :     if (eAccess != GA_Update)
   10348             :     {
   10349           1 :         CPLError(CE_Failure, CPLE_NotSupported,
   10350             :                  "UpdateFieldDomain() not supported on read-only dataset");
   10351           1 :         return false;
   10352             :     }
   10353             : 
   10354           2 :     if (GetFieldDomain(domainName) == nullptr)
   10355             :     {
   10356           1 :         failureReason = "The domain should already exist to be updated";
   10357           1 :         return false;
   10358             :     }
   10359             : 
   10360           1 :     bool bRet = SoftStartTransaction() == OGRERR_NONE;
   10361           1 :     if (bRet)
   10362             :     {
   10363           2 :         bRet = DeleteFieldDomain(domainName, failureReason) &&
   10364           1 :                AddFieldDomain(std::move(domain), failureReason);
   10365           1 :         if (bRet)
   10366           1 :             bRet = SoftCommitTransaction() == OGRERR_NONE;
   10367             :         else
   10368           0 :             SoftRollbackTransaction();
   10369             :     }
   10370           1 :     return bRet;
   10371             : }
   10372             : 
   10373             : /************************************************************************/
   10374             : /*                         DeleteFieldDomain()                          */
   10375             : /************************************************************************/
   10376             : 
   10377          18 : bool GDALGeoPackageDataset::DeleteFieldDomain(const std::string &name,
   10378             :                                               std::string &failureReason)
   10379             : {
   10380          18 :     if (eAccess != GA_Update)
   10381             :     {
   10382           1 :         CPLError(CE_Failure, CPLE_NotSupported,
   10383             :                  "DeleteFieldDomain() not supported on read-only dataset");
   10384           1 :         return false;
   10385             :     }
   10386          17 :     if (GetFieldDomain(name) == nullptr)
   10387             :     {
   10388           1 :         failureReason = "Domain does not exist";
   10389           1 :         return false;
   10390             :     }
   10391             : 
   10392             :     char *pszSQL =
   10393          16 :         sqlite3_mprintf("DELETE FROM gpkg_data_column_constraints WHERE "
   10394             :                         "constraint_name IN ('%q', '_%q_domain_description')",
   10395             :                         name.c_str(), name.c_str());
   10396          16 :     const bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10397          16 :     sqlite3_free(pszSQL);
   10398          16 :     if (ok)
   10399          16 :         m_oMapFieldDomains.erase(name);
   10400          16 :     return ok;
   10401             : }
   10402             : 
   10403             : /************************************************************************/
   10404             : /*                          AddRelationship()                           */
   10405             : /************************************************************************/
   10406             : 
   10407          26 : bool GDALGeoPackageDataset::AddRelationship(
   10408             :     std::unique_ptr<GDALRelationship> &&relationship,
   10409             :     std::string &failureReason)
   10410             : {
   10411          26 :     if (!GetUpdate())
   10412             :     {
   10413           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10414             :                  "AddRelationship() not supported on read-only dataset");
   10415           0 :         return false;
   10416             :     }
   10417             : 
   10418             :     const std::string osRelationshipName = GenerateNameForRelationship(
   10419          26 :         relationship->GetLeftTableName().c_str(),
   10420          26 :         relationship->GetRightTableName().c_str(),
   10421         104 :         relationship->GetRelatedTableType().c_str());
   10422             :     // sanity checks
   10423          26 :     if (GetRelationship(osRelationshipName) != nullptr)
   10424             :     {
   10425           1 :         failureReason = "A relationship of identical name already exists";
   10426           1 :         return false;
   10427             :     }
   10428             : 
   10429          25 :     if (!ValidateRelationship(relationship.get(), failureReason))
   10430             :     {
   10431          14 :         return false;
   10432             :     }
   10433             : 
   10434          75 :     for (auto &poLayer : m_apoLayers)
   10435             :     {
   10436          64 :         if (poLayer->SyncToDisk() != OGRERR_NONE)
   10437           0 :             return false;
   10438             :     }
   10439             : 
   10440          11 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
   10441             :     {
   10442           0 :         return false;
   10443             :     }
   10444          11 :     if (!CreateRelationsTableIfNecessary())
   10445             :     {
   10446           0 :         failureReason = "Could not create gpkgext_relations table";
   10447           0 :         return false;
   10448             :     }
   10449          11 :     if (SQLGetInteger(GetDB(),
   10450             :                       "SELECT 1 FROM gpkg_extensions WHERE "
   10451             :                       "table_name = 'gpkgext_relations'",
   10452          11 :                       nullptr) != 1)
   10453             :     {
   10454           5 :         if (OGRERR_NONE !=
   10455           5 :             SQLCommand(
   10456             :                 GetDB(),
   10457             :                 "INSERT INTO gpkg_extensions "
   10458             :                 "(table_name,column_name,extension_name,definition,scope) "
   10459             :                 "VALUES ('gpkgext_relations', NULL, 'gpkg_related_tables', "
   10460             :                 "'http://www.geopackage.org/18-000.html', "
   10461             :                 "'read-write')"))
   10462             :         {
   10463             :             failureReason =
   10464           0 :                 "Could not create gpkg_extensions entry for gpkgext_relations";
   10465           0 :             return false;
   10466             :         }
   10467             :     }
   10468             : 
   10469          11 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10470          11 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10471          11 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10472          11 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10473             : 
   10474          22 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10475          11 :     if (osRelatedTableType.empty())
   10476             :     {
   10477           5 :         osRelatedTableType = "features";
   10478             :     }
   10479             : 
   10480             :     // generate mapping table if not set
   10481          22 :     CPLString osMappingTableName = relationship->GetMappingTableName();
   10482          11 :     if (osMappingTableName.empty())
   10483             :     {
   10484           5 :         int nIndex = 1;
   10485           5 :         osMappingTableName = osLeftTableName + "_" + osRightTableName;
   10486           5 :         while (FindLayerIndex(osMappingTableName.c_str()) >= 0)
   10487             :         {
   10488           0 :             nIndex += 1;
   10489             :             osMappingTableName.Printf("%s_%s_%d", osLeftTableName.c_str(),
   10490           0 :                                       osRightTableName.c_str(), nIndex);
   10491             :         }
   10492             : 
   10493             :         // determine whether base/related keys are unique
   10494           5 :         bool bBaseKeyIsUnique = false;
   10495             :         {
   10496             :             const std::set<std::string> uniqueBaseFieldsUC =
   10497             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10498          10 :                                                osLeftTableName.c_str());
   10499          10 :             if (uniqueBaseFieldsUC.find(
   10500           5 :                     CPLString(aosLeftTableFields[0]).toupper()) !=
   10501          10 :                 uniqueBaseFieldsUC.end())
   10502             :             {
   10503           2 :                 bBaseKeyIsUnique = true;
   10504             :             }
   10505             :         }
   10506           5 :         bool bRelatedKeyIsUnique = false;
   10507             :         {
   10508             :             const std::set<std::string> uniqueRelatedFieldsUC =
   10509             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10510          10 :                                                osRightTableName.c_str());
   10511          10 :             if (uniqueRelatedFieldsUC.find(
   10512           5 :                     CPLString(aosRightTableFields[0]).toupper()) !=
   10513          10 :                 uniqueRelatedFieldsUC.end())
   10514             :             {
   10515           2 :                 bRelatedKeyIsUnique = true;
   10516             :             }
   10517             :         }
   10518             : 
   10519             :         // create mapping table
   10520             : 
   10521           5 :         std::string osBaseIdDefinition = "base_id INTEGER";
   10522           5 :         if (bBaseKeyIsUnique)
   10523             :         {
   10524           2 :             char *pszSQL = sqlite3_mprintf(
   10525             :                 " CONSTRAINT 'fk_base_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10526             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10527             :                 "DEFERRED",
   10528             :                 osMappingTableName.c_str(), osLeftTableName.c_str(),
   10529           2 :                 aosLeftTableFields[0].c_str());
   10530           2 :             osBaseIdDefinition += pszSQL;
   10531           2 :             sqlite3_free(pszSQL);
   10532             :         }
   10533             : 
   10534           5 :         std::string osRelatedIdDefinition = "related_id INTEGER";
   10535           5 :         if (bRelatedKeyIsUnique)
   10536             :         {
   10537           2 :             char *pszSQL = sqlite3_mprintf(
   10538             :                 " CONSTRAINT 'fk_related_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10539             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10540             :                 "DEFERRED",
   10541             :                 osMappingTableName.c_str(), osRightTableName.c_str(),
   10542           2 :                 aosRightTableFields[0].c_str());
   10543           2 :             osRelatedIdDefinition += pszSQL;
   10544           2 :             sqlite3_free(pszSQL);
   10545             :         }
   10546             : 
   10547           5 :         char *pszSQL = sqlite3_mprintf("CREATE TABLE \"%w\" ("
   10548             :                                        "id INTEGER PRIMARY KEY AUTOINCREMENT, "
   10549             :                                        "%s, %s);",
   10550             :                                        osMappingTableName.c_str(),
   10551             :                                        osBaseIdDefinition.c_str(),
   10552             :                                        osRelatedIdDefinition.c_str());
   10553           5 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
   10554           5 :         sqlite3_free(pszSQL);
   10555           5 :         if (eErr != OGRERR_NONE)
   10556             :         {
   10557             :             failureReason =
   10558           0 :                 ("Could not create mapping table " + osMappingTableName)
   10559           0 :                     .c_str();
   10560           0 :             return false;
   10561             :         }
   10562             : 
   10563             :         /*
   10564             :          * Strictly speaking we should NOT be inserting the mapping table into gpkg_contents.
   10565             :          * The related tables extension explicitly states that the mapping table should only be
   10566             :          * in the gpkgext_relations table and not in gpkg_contents. (See also discussion at
   10567             :          * https://github.com/opengeospatial/geopackage/issues/679).
   10568             :          *
   10569             :          * However, if we don't insert the mapping table into gpkg_contents then it is no longer
   10570             :          * visible to some clients (eg ESRI software only allows opening tables that are present
   10571             :          * in gpkg_contents). So we'll do this anyway, for maximum compatibility and flexibility.
   10572             :          *
   10573             :          * More related discussion is at https://github.com/OSGeo/gdal/pull/9258
   10574             :          */
   10575           5 :         pszSQL = sqlite3_mprintf(
   10576             :             "INSERT INTO gpkg_contents "
   10577             :             "(table_name,data_type,identifier,description,last_change,srs_id) "
   10578             :             "VALUES "
   10579             :             "('%q','attributes','%q','Mapping table for relationship between "
   10580             :             "%q and %q',%s,0)",
   10581             :             osMappingTableName.c_str(), /*table_name*/
   10582             :             osMappingTableName.c_str(), /*identifier*/
   10583             :             osLeftTableName.c_str(),    /*description left table name*/
   10584             :             osRightTableName.c_str(),   /*description right table name*/
   10585          10 :             GDALGeoPackageDataset::GetCurrentDateEscapedSQL().c_str());
   10586             : 
   10587             :         // Note -- we explicitly ignore failures here, because hey, we aren't really
   10588             :         // supposed to be adding this table to gpkg_contents anyway!
   10589           5 :         (void)SQLCommand(hDB, pszSQL);
   10590           5 :         sqlite3_free(pszSQL);
   10591             : 
   10592           5 :         pszSQL = sqlite3_mprintf(
   10593             :             "CREATE INDEX \"idx_%w_base_id\" ON \"%w\" (base_id);",
   10594             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10595           5 :         eErr = SQLCommand(hDB, pszSQL);
   10596           5 :         sqlite3_free(pszSQL);
   10597           5 :         if (eErr != OGRERR_NONE)
   10598             :         {
   10599           0 :             failureReason = ("Could not create index for " +
   10600           0 :                              osMappingTableName + " (base_id)")
   10601           0 :                                 .c_str();
   10602           0 :             return false;
   10603             :         }
   10604             : 
   10605           5 :         pszSQL = sqlite3_mprintf(
   10606             :             "CREATE INDEX \"idx_%qw_related_id\" ON \"%w\" (related_id);",
   10607             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10608           5 :         eErr = SQLCommand(hDB, pszSQL);
   10609           5 :         sqlite3_free(pszSQL);
   10610           5 :         if (eErr != OGRERR_NONE)
   10611             :         {
   10612           0 :             failureReason = ("Could not create index for " +
   10613           0 :                              osMappingTableName + " (related_id)")
   10614           0 :                                 .c_str();
   10615           0 :             return false;
   10616             :         }
   10617             : 
   10618             :         auto poLayer = std::make_unique<OGRGeoPackageTableLayer>(
   10619          10 :             this, osMappingTableName.c_str());
   10620           5 :         poLayer->SetOpeningParameters(osMappingTableName.c_str(), "table",
   10621             :                                       /* bIsInGpkgContents = */ true,
   10622             :                                       /* bIsSpatial = */ false,
   10623             :                                       /* pszGeomColName =*/nullptr,
   10624             :                                       /* pszGeomType =*/nullptr,
   10625             :                                       /* bHasZ = */ false, /* bHasM = */ false);
   10626           5 :         m_apoLayers.push_back(std::move(poLayer));
   10627             :     }
   10628             :     else
   10629             :     {
   10630             :         // validate mapping table structure
   10631           6 :         if (OGRGeoPackageTableLayer *poLayer =
   10632           6 :                 cpl::down_cast<OGRGeoPackageTableLayer *>(
   10633           6 :                     GetLayerByName(osMappingTableName)))
   10634             :         {
   10635           4 :             if (poLayer->GetLayerDefn()->GetFieldIndex("base_id") < 0)
   10636             :             {
   10637             :                 failureReason =
   10638           2 :                     ("Field base_id must exist in " + osMappingTableName)
   10639           1 :                         .c_str();
   10640           1 :                 return false;
   10641             :             }
   10642           3 :             if (poLayer->GetLayerDefn()->GetFieldIndex("related_id") < 0)
   10643             :             {
   10644             :                 failureReason =
   10645           2 :                     ("Field related_id must exist in " + osMappingTableName)
   10646           1 :                         .c_str();
   10647           1 :                 return false;
   10648             :             }
   10649             :         }
   10650             :         else
   10651             :         {
   10652             :             failureReason =
   10653           2 :                 ("Could not retrieve table " + osMappingTableName).c_str();
   10654           2 :             return false;
   10655             :         }
   10656             :     }
   10657             : 
   10658           7 :     char *pszSQL = sqlite3_mprintf(
   10659             :         "INSERT INTO gpkg_extensions "
   10660             :         "(table_name,column_name,extension_name,definition,scope) "
   10661             :         "VALUES ('%q', NULL, 'gpkg_related_tables', "
   10662             :         "'http://www.geopackage.org/18-000.html', "
   10663             :         "'read-write')",
   10664             :         osMappingTableName.c_str());
   10665           7 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10666           7 :     sqlite3_free(pszSQL);
   10667           7 :     if (eErr != OGRERR_NONE)
   10668             :     {
   10669           0 :         failureReason = ("Could not insert mapping table " +
   10670           0 :                          osMappingTableName + " into gpkg_extensions")
   10671           0 :                             .c_str();
   10672           0 :         return false;
   10673             :     }
   10674             : 
   10675          21 :     pszSQL = sqlite3_mprintf(
   10676             :         "INSERT INTO gpkgext_relations "
   10677             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10678             :         "primary_column,relation_name,mapping_table_name) "
   10679             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10680           7 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10681           7 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10682             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10683           7 :     eErr = SQLCommand(hDB, pszSQL);
   10684           7 :     sqlite3_free(pszSQL);
   10685           7 :     if (eErr != OGRERR_NONE)
   10686             :     {
   10687           0 :         failureReason = "Could not insert relationship into gpkgext_relations";
   10688           0 :         return false;
   10689             :     }
   10690             : 
   10691           7 :     ClearCachedRelationships();
   10692           7 :     LoadRelationships();
   10693           7 :     return true;
   10694             : }
   10695             : 
   10696             : /************************************************************************/
   10697             : /*                         DeleteRelationship()                         */
   10698             : /************************************************************************/
   10699             : 
   10700           4 : bool GDALGeoPackageDataset::DeleteRelationship(const std::string &name,
   10701             :                                                std::string &failureReason)
   10702             : {
   10703           4 :     if (eAccess != GA_Update)
   10704             :     {
   10705           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10706             :                  "DeleteRelationship() not supported on read-only dataset");
   10707           0 :         return false;
   10708             :     }
   10709             : 
   10710             :     // ensure relationships are up to date before we try to remove one
   10711           4 :     ClearCachedRelationships();
   10712           4 :     LoadRelationships();
   10713             : 
   10714           8 :     std::string osMappingTableName;
   10715             :     {
   10716           4 :         const GDALRelationship *poRelationship = GetRelationship(name);
   10717           4 :         if (poRelationship == nullptr)
   10718             :         {
   10719           1 :             failureReason = "Could not find relationship with name " + name;
   10720           1 :             return false;
   10721             :         }
   10722             : 
   10723           3 :         osMappingTableName = poRelationship->GetMappingTableName();
   10724             :     }
   10725             : 
   10726             :     // DeleteLayerCommon will delete existing relationship objects, so we can't
   10727             :     // refer to poRelationship or any of its members previously obtained here
   10728           3 :     if (DeleteLayerCommon(osMappingTableName.c_str()) != OGRERR_NONE)
   10729             :     {
   10730             :         failureReason =
   10731           0 :             "Could not remove mapping layer name " + osMappingTableName;
   10732             : 
   10733             :         // relationships may have been left in an inconsistent state -- reload
   10734             :         // them now
   10735           0 :         ClearCachedRelationships();
   10736           0 :         LoadRelationships();
   10737           0 :         return false;
   10738             :     }
   10739             : 
   10740           3 :     ClearCachedRelationships();
   10741           3 :     LoadRelationships();
   10742           3 :     return true;
   10743             : }
   10744             : 
   10745             : /************************************************************************/
   10746             : /*                         UpdateRelationship()                         */
   10747             : /************************************************************************/
   10748             : 
   10749           6 : bool GDALGeoPackageDataset::UpdateRelationship(
   10750             :     std::unique_ptr<GDALRelationship> &&relationship,
   10751             :     std::string &failureReason)
   10752             : {
   10753           6 :     if (eAccess != GA_Update)
   10754             :     {
   10755           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10756             :                  "UpdateRelationship() not supported on read-only dataset");
   10757           0 :         return false;
   10758             :     }
   10759             : 
   10760             :     // ensure relationships are up to date before we try to update one
   10761           6 :     ClearCachedRelationships();
   10762           6 :     LoadRelationships();
   10763             : 
   10764           6 :     const std::string &osRelationshipName = relationship->GetName();
   10765           6 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10766           6 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10767           6 :     const std::string &osMappingTableName = relationship->GetMappingTableName();
   10768           6 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10769           6 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10770             : 
   10771             :     // sanity checks
   10772             :     {
   10773             :         const GDALRelationship *poExistingRelationship =
   10774           6 :             GetRelationship(osRelationshipName);
   10775           6 :         if (poExistingRelationship == nullptr)
   10776             :         {
   10777             :             failureReason =
   10778           1 :                 "The relationship should already exist to be updated";
   10779           1 :             return false;
   10780             :         }
   10781             : 
   10782           5 :         if (!ValidateRelationship(relationship.get(), failureReason))
   10783             :         {
   10784           2 :             return false;
   10785             :         }
   10786             : 
   10787             :         // we don't permit changes to the participating tables
   10788           3 :         if (osLeftTableName != poExistingRelationship->GetLeftTableName())
   10789             :         {
   10790           0 :             failureReason = ("Cannot change base table from " +
   10791           0 :                              poExistingRelationship->GetLeftTableName() +
   10792           0 :                              " to " + osLeftTableName)
   10793           0 :                                 .c_str();
   10794           0 :             return false;
   10795             :         }
   10796           3 :         if (osRightTableName != poExistingRelationship->GetRightTableName())
   10797             :         {
   10798           0 :             failureReason = ("Cannot change related table from " +
   10799           0 :                              poExistingRelationship->GetRightTableName() +
   10800           0 :                              " to " + osRightTableName)
   10801           0 :                                 .c_str();
   10802           0 :             return false;
   10803             :         }
   10804           3 :         if (osMappingTableName != poExistingRelationship->GetMappingTableName())
   10805             :         {
   10806           0 :             failureReason = ("Cannot change mapping table from " +
   10807           0 :                              poExistingRelationship->GetMappingTableName() +
   10808           0 :                              " to " + osMappingTableName)
   10809           0 :                                 .c_str();
   10810           0 :             return false;
   10811             :         }
   10812             :     }
   10813             : 
   10814           6 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10815           3 :     if (osRelatedTableType.empty())
   10816             :     {
   10817           0 :         osRelatedTableType = "features";
   10818             :     }
   10819             : 
   10820           3 :     char *pszSQL = sqlite3_mprintf(
   10821             :         "DELETE FROM gpkgext_relations WHERE mapping_table_name='%q'",
   10822             :         osMappingTableName.c_str());
   10823           3 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10824           3 :     sqlite3_free(pszSQL);
   10825           3 :     if (eErr != OGRERR_NONE)
   10826             :     {
   10827             :         failureReason =
   10828           0 :             "Could not delete old relationship from gpkgext_relations";
   10829           0 :         return false;
   10830             :     }
   10831             : 
   10832           9 :     pszSQL = sqlite3_mprintf(
   10833             :         "INSERT INTO gpkgext_relations "
   10834             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10835             :         "primary_column,relation_name,mapping_table_name) "
   10836             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10837           3 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10838           3 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10839             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10840           3 :     eErr = SQLCommand(hDB, pszSQL);
   10841           3 :     sqlite3_free(pszSQL);
   10842           3 :     if (eErr != OGRERR_NONE)
   10843             :     {
   10844             :         failureReason =
   10845           0 :             "Could not insert updated relationship into gpkgext_relations";
   10846           0 :         return false;
   10847             :     }
   10848             : 
   10849           3 :     ClearCachedRelationships();
   10850           3 :     LoadRelationships();
   10851           3 :     return true;
   10852             : }
   10853             : 
   10854             : /************************************************************************/
   10855             : /*                       GetSqliteMasterContent()                       */
   10856             : /************************************************************************/
   10857             : 
   10858             : const std::vector<SQLSqliteMasterContent> &
   10859           2 : GDALGeoPackageDataset::GetSqliteMasterContent()
   10860             : {
   10861           2 :     if (m_aoSqliteMasterContent.empty())
   10862             :     {
   10863             :         auto oResultTable =
   10864           2 :             SQLQuery(hDB, "SELECT sql, type, tbl_name FROM sqlite_master");
   10865           1 :         if (oResultTable)
   10866             :         {
   10867          58 :             for (int rowCnt = 0; rowCnt < oResultTable->RowCount(); ++rowCnt)
   10868             :             {
   10869         114 :                 SQLSqliteMasterContent row;
   10870          57 :                 const char *pszSQL = oResultTable->GetValue(0, rowCnt);
   10871          57 :                 row.osSQL = pszSQL ? pszSQL : "";
   10872          57 :                 const char *pszType = oResultTable->GetValue(1, rowCnt);
   10873          57 :                 row.osType = pszType ? pszType : "";
   10874          57 :                 const char *pszTableName = oResultTable->GetValue(2, rowCnt);
   10875          57 :                 row.osTableName = pszTableName ? pszTableName : "";
   10876          57 :                 m_aoSqliteMasterContent.emplace_back(std::move(row));
   10877             :             }
   10878             :         }
   10879             :     }
   10880           2 :     return m_aoSqliteMasterContent;
   10881             : }

Generated by: LCOV version 1.14