LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/gpkg - ogrgeopackagedatasource.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 4020 4485 89.6 %
Date: 2025-06-19 12:30:01 Functions: 135 135 100.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GeoPackage Translator
       4             :  * Purpose:  Implements GDALGeoPackageDataset class
       5             :  * Author:   Paul Ramsey <pramsey@boundlessgeo.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2013, Paul Ramsey <pramsey@boundlessgeo.com>
       9             :  * Copyright (c) 2014, Even Rouault <even dot rouault at spatialys.com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "ogr_geopackage.h"
      15             : #include "ogr_p.h"
      16             : #include "ogr_swq.h"
      17             : #include "gdalwarper.h"
      18             : #include "gdal_utils.h"
      19             : #include "ogrgeopackageutility.h"
      20             : #include "ogrsqliteutility.h"
      21             : #include "ogr_wkb.h"
      22             : #include "vrt/vrtdataset.h"
      23             : 
      24             : #include "tilematrixset.hpp"
      25             : 
      26             : #include <cstdlib>
      27             : 
      28             : #include <algorithm>
      29             : #include <limits>
      30             : #include <sstream>
      31             : 
      32             : #define COMPILATION_ALLOWED
      33             : #define DEFINE_OGRSQLiteSQLFunctionsSetCaseSensitiveLike
      34             : #include "ogrsqlitesqlfunctionscommon.cpp"
      35             : 
      36             : // Keep in sync prototype of those 2 functions between gdalopeninfo.cpp,
      37             : // ogrsqlitedatasource.cpp and ogrgeopackagedatasource.cpp
      38             : void GDALOpenInfoDeclareFileNotToOpen(const char *pszFilename,
      39             :                                       const GByte *pabyHeader,
      40             :                                       int nHeaderBytes);
      41             : void GDALOpenInfoUnDeclareFileNotToOpen(const char *pszFilename);
      42             : 
      43             : /************************************************************************/
      44             : /*                             Tiling schemes                           */
      45             : /************************************************************************/
      46             : 
      47             : typedef struct
      48             : {
      49             :     const char *pszName;
      50             :     int nEPSGCode;
      51             :     double dfMinX;
      52             :     double dfMaxY;
      53             :     int nTileXCountZoomLevel0;
      54             :     int nTileYCountZoomLevel0;
      55             :     int nTileWidth;
      56             :     int nTileHeight;
      57             :     double dfPixelXSizeZoomLevel0;
      58             :     double dfPixelYSizeZoomLevel0;
      59             : } TilingSchemeDefinition;
      60             : 
      61             : static const TilingSchemeDefinition asTilingSchemes[] = {
      62             :     /* See http://portal.opengeospatial.org/files/?artifact_id=35326 (WMTS 1.0),
      63             :        Annex E.3 */
      64             :     {"GoogleCRS84Quad", 4326, -180.0, 180.0, 1, 1, 256, 256, 360.0 / 256,
      65             :      360.0 / 256},
      66             : 
      67             :     /* See global-mercator at
      68             :        http://wiki.osgeo.org/wiki/Tile_Map_Service_Specification */
      69             :     {"PseudoTMS_GlobalMercator", 3857, -20037508.34, 20037508.34, 2, 2, 256,
      70             :      256, 78271.516, 78271.516},
      71             : };
      72             : 
      73             : // Setting it above 30 would lead to integer overflow ((1 << 31) > INT_MAX)
      74             : constexpr int MAX_ZOOM_LEVEL = 30;
      75             : 
      76             : /************************************************************************/
      77             : /*                     GetTilingScheme()                                */
      78             : /************************************************************************/
      79             : 
      80             : static std::unique_ptr<TilingSchemeDefinition>
      81         564 : GetTilingScheme(const char *pszName)
      82             : {
      83         564 :     if (EQUAL(pszName, "CUSTOM"))
      84         436 :         return nullptr;
      85             : 
      86         256 :     for (const auto &tilingScheme : asTilingSchemes)
      87             :     {
      88         195 :         if (EQUAL(pszName, tilingScheme.pszName))
      89             :         {
      90          67 :             return std::make_unique<TilingSchemeDefinition>(tilingScheme);
      91             :         }
      92             :     }
      93             : 
      94          61 :     if (EQUAL(pszName, "PseudoTMS_GlobalGeodetic"))
      95           6 :         pszName = "InspireCRS84Quad";
      96             : 
      97         122 :     auto poTM = gdal::TileMatrixSet::parse(pszName);
      98          61 :     if (poTM == nullptr)
      99           1 :         return nullptr;
     100          60 :     if (!poTM->haveAllLevelsSameTopLeft())
     101             :     {
     102           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     103             :                  "Unsupported tiling scheme: not all zoom levels have same top "
     104             :                  "left corner");
     105           0 :         return nullptr;
     106             :     }
     107          60 :     if (!poTM->haveAllLevelsSameTileSize())
     108             :     {
     109           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     110             :                  "Unsupported tiling scheme: not all zoom levels have same "
     111             :                  "tile size");
     112           0 :         return nullptr;
     113             :     }
     114          60 :     if (!poTM->hasOnlyPowerOfTwoVaryingScales())
     115             :     {
     116           1 :         CPLError(CE_Failure, CPLE_NotSupported,
     117             :                  "Unsupported tiling scheme: resolution of consecutive zoom "
     118             :                  "levels is not always 2");
     119           1 :         return nullptr;
     120             :     }
     121          59 :     if (poTM->hasVariableMatrixWidth())
     122             :     {
     123           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     124             :                  "Unsupported tiling scheme: some levels have variable matrix "
     125             :                  "width");
     126           0 :         return nullptr;
     127             :     }
     128         118 :     auto poTilingScheme = std::make_unique<TilingSchemeDefinition>();
     129          59 :     poTilingScheme->pszName = pszName;
     130             : 
     131         118 :     OGRSpatialReference oSRS;
     132          59 :     if (oSRS.SetFromUserInput(poTM->crs().c_str()) != OGRERR_NONE)
     133             :     {
     134           0 :         return nullptr;
     135             :     }
     136          59 :     if (poTM->crs() == "http://www.opengis.net/def/crs/OGC/1.3/CRS84")
     137             :     {
     138           6 :         poTilingScheme->nEPSGCode = 4326;
     139             :     }
     140             :     else
     141             :     {
     142          53 :         const char *pszAuthName = oSRS.GetAuthorityName(nullptr);
     143          53 :         const char *pszAuthCode = oSRS.GetAuthorityCode(nullptr);
     144          53 :         if (pszAuthName == nullptr || !EQUAL(pszAuthName, "EPSG") ||
     145             :             pszAuthCode == nullptr)
     146             :         {
     147           0 :             CPLError(CE_Failure, CPLE_NotSupported,
     148             :                      "Unsupported tiling scheme: only EPSG CRS supported");
     149           0 :             return nullptr;
     150             :         }
     151          53 :         poTilingScheme->nEPSGCode = atoi(pszAuthCode);
     152             :     }
     153          59 :     const auto &zoomLevel0 = poTM->tileMatrixList()[0];
     154          59 :     poTilingScheme->dfMinX = zoomLevel0.mTopLeftX;
     155          59 :     poTilingScheme->dfMaxY = zoomLevel0.mTopLeftY;
     156          59 :     poTilingScheme->nTileXCountZoomLevel0 = zoomLevel0.mMatrixWidth;
     157          59 :     poTilingScheme->nTileYCountZoomLevel0 = zoomLevel0.mMatrixHeight;
     158          59 :     poTilingScheme->nTileWidth = zoomLevel0.mTileWidth;
     159          59 :     poTilingScheme->nTileHeight = zoomLevel0.mTileHeight;
     160          59 :     poTilingScheme->dfPixelXSizeZoomLevel0 = zoomLevel0.mResX;
     161          59 :     poTilingScheme->dfPixelYSizeZoomLevel0 = zoomLevel0.mResY;
     162             : 
     163         118 :     const bool bInvertAxis = oSRS.EPSGTreatsAsLatLong() != FALSE ||
     164          59 :                              oSRS.EPSGTreatsAsNorthingEasting() != FALSE;
     165          59 :     if (bInvertAxis)
     166             :     {
     167           6 :         std::swap(poTilingScheme->dfMinX, poTilingScheme->dfMaxY);
     168           6 :         std::swap(poTilingScheme->dfPixelXSizeZoomLevel0,
     169           6 :                   poTilingScheme->dfPixelYSizeZoomLevel0);
     170             :     }
     171          59 :     return poTilingScheme;
     172             : }
     173             : 
     174             : static const char *pszCREATE_GPKG_GEOMETRY_COLUMNS =
     175             :     "CREATE TABLE gpkg_geometry_columns ("
     176             :     "table_name TEXT NOT NULL,"
     177             :     "column_name TEXT NOT NULL,"
     178             :     "geometry_type_name TEXT NOT NULL,"
     179             :     "srs_id INTEGER NOT NULL,"
     180             :     "z TINYINT NOT NULL,"
     181             :     "m TINYINT NOT NULL,"
     182             :     "CONSTRAINT pk_geom_cols PRIMARY KEY (table_name, column_name),"
     183             :     "CONSTRAINT uk_gc_table_name UNIQUE (table_name),"
     184             :     "CONSTRAINT fk_gc_tn FOREIGN KEY (table_name) REFERENCES "
     185             :     "gpkg_contents(table_name),"
     186             :     "CONSTRAINT fk_gc_srs FOREIGN KEY (srs_id) REFERENCES gpkg_spatial_ref_sys "
     187             :     "(srs_id)"
     188             :     ")";
     189             : 
     190         865 : OGRErr GDALGeoPackageDataset::SetApplicationAndUserVersionId()
     191             : {
     192         865 :     CPLAssert(hDB != nullptr);
     193             : 
     194         865 :     const CPLString osPragma(CPLString().Printf("PRAGMA application_id = %u;"
     195             :                                                 "PRAGMA user_version = %u",
     196             :                                                 m_nApplicationId,
     197        1730 :                                                 m_nUserVersion));
     198        1730 :     return SQLCommand(hDB, osPragma.c_str());
     199             : }
     200             : 
     201        2438 : bool GDALGeoPackageDataset::CloseDB()
     202             : {
     203        2438 :     OGRSQLiteUnregisterSQLFunctions(m_pSQLFunctionData);
     204        2438 :     m_pSQLFunctionData = nullptr;
     205        2438 :     return OGRSQLiteBaseDataSource::CloseDB();
     206             : }
     207             : 
     208          11 : bool GDALGeoPackageDataset::ReOpenDB()
     209             : {
     210          11 :     CPLAssert(hDB != nullptr);
     211          11 :     CPLAssert(m_pszFilename != nullptr);
     212             : 
     213          11 :     FinishSpatialite();
     214             : 
     215          11 :     CloseDB();
     216             : 
     217             :     /* And re-open the file */
     218          11 :     return OpenOrCreateDB(SQLITE_OPEN_READWRITE);
     219             : }
     220             : 
     221         802 : static OGRErr GDALGPKGImportFromEPSG(OGRSpatialReference *poSpatialRef,
     222             :                                      int nEPSGCode)
     223             : {
     224         802 :     CPLPushErrorHandler(CPLQuietErrorHandler);
     225         802 :     const OGRErr eErr = poSpatialRef->importFromEPSG(nEPSGCode);
     226         802 :     CPLPopErrorHandler();
     227         802 :     CPLErrorReset();
     228         802 :     return eErr;
     229             : }
     230             : 
     231             : std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
     232        1208 : GDALGeoPackageDataset::GetSpatialRef(int iSrsId, bool bFallbackToEPSG,
     233             :                                      bool bEmitErrorIfNotFound)
     234             : {
     235        1208 :     const auto oIter = m_oMapSrsIdToSrs.find(iSrsId);
     236        1208 :     if (oIter != m_oMapSrsIdToSrs.end())
     237             :     {
     238          88 :         if (oIter->second == nullptr)
     239          31 :             return nullptr;
     240          57 :         oIter->second->Reference();
     241             :         return std::unique_ptr<OGRSpatialReference,
     242          57 :                                OGRSpatialReferenceReleaser>(oIter->second);
     243             :     }
     244             : 
     245        1120 :     if (iSrsId == 0 || iSrsId == -1)
     246             :     {
     247         120 :         OGRSpatialReference *poSpatialRef = new OGRSpatialReference();
     248         120 :         poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     249             : 
     250             :         // See corresponding tests in GDALGeoPackageDataset::GetSrsId
     251         120 :         if (iSrsId == 0)
     252             :         {
     253          29 :             poSpatialRef->SetGeogCS("Undefined geographic SRS", "unknown",
     254             :                                     "unknown", SRS_WGS84_SEMIMAJOR,
     255             :                                     SRS_WGS84_INVFLATTENING);
     256             :         }
     257          91 :         else if (iSrsId == -1)
     258             :         {
     259          91 :             poSpatialRef->SetLocalCS("Undefined Cartesian SRS");
     260          91 :             poSpatialRef->SetLinearUnits(SRS_UL_METER, 1.0);
     261             :         }
     262             : 
     263         120 :         m_oMapSrsIdToSrs[iSrsId] = poSpatialRef;
     264         120 :         poSpatialRef->Reference();
     265             :         return std::unique_ptr<OGRSpatialReference,
     266         120 :                                OGRSpatialReferenceReleaser>(poSpatialRef);
     267             :     }
     268             : 
     269        2000 :     CPLString oSQL;
     270        1000 :     oSQL.Printf("SELECT srs_name, definition, organization, "
     271             :                 "organization_coordsys_id%s%s "
     272             :                 "FROM gpkg_spatial_ref_sys WHERE "
     273             :                 "srs_id = %d LIMIT 2",
     274        1000 :                 m_bHasDefinition12_063 ? ", definition_12_063" : "",
     275        1000 :                 m_bHasEpochColumn ? ", epoch" : "", iSrsId);
     276             : 
     277        2000 :     auto oResult = SQLQuery(hDB, oSQL.c_str());
     278             : 
     279        1000 :     if (!oResult || oResult->RowCount() != 1)
     280             :     {
     281          12 :         if (bFallbackToEPSG)
     282             :         {
     283           7 :             CPLDebug("GPKG",
     284             :                      "unable to read srs_id '%d' from gpkg_spatial_ref_sys",
     285             :                      iSrsId);
     286           7 :             OGRSpatialReference *poSRS = new OGRSpatialReference();
     287           7 :             if (poSRS->importFromEPSG(iSrsId) == OGRERR_NONE)
     288             :             {
     289           5 :                 poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     290             :                 return std::unique_ptr<OGRSpatialReference,
     291           5 :                                        OGRSpatialReferenceReleaser>(poSRS);
     292             :             }
     293           2 :             poSRS->Release();
     294             :         }
     295           5 :         else if (bEmitErrorIfNotFound)
     296             :         {
     297           2 :             CPLError(CE_Warning, CPLE_AppDefined,
     298             :                      "unable to read srs_id '%d' from gpkg_spatial_ref_sys",
     299             :                      iSrsId);
     300           2 :             m_oMapSrsIdToSrs[iSrsId] = nullptr;
     301             :         }
     302           7 :         return nullptr;
     303             :     }
     304             : 
     305         988 :     const char *pszName = oResult->GetValue(0, 0);
     306         988 :     if (pszName && EQUAL(pszName, "Undefined SRS"))
     307             :     {
     308         408 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     309         408 :         return nullptr;
     310             :     }
     311         580 :     const char *pszWkt = oResult->GetValue(1, 0);
     312         580 :     if (pszWkt == nullptr)
     313           0 :         return nullptr;
     314         580 :     const char *pszOrganization = oResult->GetValue(2, 0);
     315         580 :     const char *pszOrganizationCoordsysID = oResult->GetValue(3, 0);
     316             :     const char *pszWkt2 =
     317         580 :         m_bHasDefinition12_063 ? oResult->GetValue(4, 0) : nullptr;
     318         580 :     if (pszWkt2 && !EQUAL(pszWkt2, "undefined"))
     319          76 :         pszWkt = pszWkt2;
     320             :     const char *pszCoordinateEpoch =
     321         580 :         m_bHasEpochColumn ? oResult->GetValue(5, 0) : nullptr;
     322             :     const double dfCoordinateEpoch =
     323         580 :         pszCoordinateEpoch ? CPLAtof(pszCoordinateEpoch) : 0.0;
     324             : 
     325         580 :     OGRSpatialReference *poSpatialRef = new OGRSpatialReference();
     326         580 :     poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     327             :     // Try to import first from EPSG code, and then from WKT
     328         580 :     if (!(pszOrganization && pszOrganizationCoordsysID &&
     329         580 :           EQUAL(pszOrganization, "EPSG") &&
     330         560 :           (atoi(pszOrganizationCoordsysID) == iSrsId ||
     331           4 :            (dfCoordinateEpoch > 0 && strstr(pszWkt, "DYNAMIC[") == nullptr)) &&
     332         560 :           GDALGPKGImportFromEPSG(
     333        1160 :               poSpatialRef, atoi(pszOrganizationCoordsysID)) == OGRERR_NONE) &&
     334          20 :         poSpatialRef->importFromWkt(pszWkt) != OGRERR_NONE)
     335             :     {
     336           0 :         CPLError(CE_Warning, CPLE_AppDefined,
     337             :                  "Unable to parse srs_id '%d' well-known text '%s'", iSrsId,
     338             :                  pszWkt);
     339           0 :         delete poSpatialRef;
     340           0 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     341           0 :         return nullptr;
     342             :     }
     343             : 
     344         580 :     poSpatialRef->StripTOWGS84IfKnownDatumAndAllowed();
     345         580 :     poSpatialRef->SetCoordinateEpoch(dfCoordinateEpoch);
     346         580 :     m_oMapSrsIdToSrs[iSrsId] = poSpatialRef;
     347         580 :     poSpatialRef->Reference();
     348             :     return std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>(
     349         580 :         poSpatialRef);
     350             : }
     351             : 
     352         271 : const char *GDALGeoPackageDataset::GetSrsName(const OGRSpatialReference &oSRS)
     353             : {
     354         271 :     const char *pszName = oSRS.GetName();
     355         271 :     if (pszName)
     356         271 :         return pszName;
     357             : 
     358             :     // Something odd.  Return empty.
     359           0 :     return "Unnamed SRS";
     360             : }
     361             : 
     362             : /* Add the definition_12_063 column to an existing gpkg_spatial_ref_sys table */
     363           7 : bool GDALGeoPackageDataset::ConvertGpkgSpatialRefSysToExtensionWkt2(
     364             :     bool bForceEpoch)
     365             : {
     366           7 :     const bool bAddEpoch = (m_nUserVersion >= GPKG_1_4_VERSION || bForceEpoch);
     367             :     auto oResultTable = SQLQuery(
     368             :         hDB, "SELECT srs_name, srs_id, organization, organization_coordsys_id, "
     369          14 :              "definition, description FROM gpkg_spatial_ref_sys LIMIT 100000");
     370           7 :     if (!oResultTable)
     371           0 :         return false;
     372             : 
     373             :     // Temporary remove foreign key checks
     374             :     const GPKGTemporaryForeignKeyCheckDisabler
     375           7 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
     376             : 
     377           7 :     bool bRet = SoftStartTransaction() == OGRERR_NONE;
     378             : 
     379           7 :     if (bRet)
     380             :     {
     381             :         std::string osSQL("CREATE TABLE gpkg_spatial_ref_sys_temp ("
     382             :                           "srs_name TEXT NOT NULL,"
     383             :                           "srs_id INTEGER NOT NULL PRIMARY KEY,"
     384             :                           "organization TEXT NOT NULL,"
     385             :                           "organization_coordsys_id INTEGER NOT NULL,"
     386             :                           "definition TEXT NOT NULL,"
     387             :                           "description TEXT, "
     388           7 :                           "definition_12_063 TEXT NOT NULL");
     389           7 :         if (bAddEpoch)
     390           6 :             osSQL += ", epoch DOUBLE";
     391           7 :         osSQL += ")";
     392           7 :         bRet = SQLCommand(hDB, osSQL.c_str()) == OGRERR_NONE;
     393             :     }
     394             : 
     395           7 :     if (bRet)
     396             :     {
     397          32 :         for (int i = 0; bRet && i < oResultTable->RowCount(); i++)
     398             :         {
     399          25 :             const char *pszSrsName = oResultTable->GetValue(0, i);
     400          25 :             const char *pszSrsId = oResultTable->GetValue(1, i);
     401          25 :             const char *pszOrganization = oResultTable->GetValue(2, i);
     402             :             const char *pszOrganizationCoordsysID =
     403          25 :                 oResultTable->GetValue(3, i);
     404          25 :             const char *pszDefinition = oResultTable->GetValue(4, i);
     405             :             if (pszSrsName == nullptr || pszSrsId == nullptr ||
     406             :                 pszOrganization == nullptr ||
     407             :                 pszOrganizationCoordsysID == nullptr)
     408             :             {
     409             :                 // should not happen as there are NOT NULL constraints
     410             :                 // But a database could lack such NOT NULL constraints or have
     411             :                 // large values that would cause a memory allocation failure.
     412             :             }
     413          25 :             const char *pszDescription = oResultTable->GetValue(5, i);
     414             :             char *pszSQL;
     415             : 
     416          50 :             OGRSpatialReference oSRS;
     417          25 :             if (pszOrganization && pszOrganizationCoordsysID &&
     418          25 :                 EQUAL(pszOrganization, "EPSG"))
     419             :             {
     420           9 :                 oSRS.importFromEPSG(atoi(pszOrganizationCoordsysID));
     421             :             }
     422          34 :             if (!oSRS.IsEmpty() && pszDefinition &&
     423           9 :                 !EQUAL(pszDefinition, "undefined"))
     424             :             {
     425           9 :                 oSRS.SetFromUserInput(pszDefinition);
     426             :             }
     427          25 :             char *pszWKT2 = nullptr;
     428          25 :             if (!oSRS.IsEmpty())
     429             :             {
     430           9 :                 const char *const apszOptionsWkt2[] = {"FORMAT=WKT2_2015",
     431             :                                                        nullptr};
     432           9 :                 oSRS.exportToWkt(&pszWKT2, apszOptionsWkt2);
     433           9 :                 if (pszWKT2 && pszWKT2[0] == '\0')
     434             :                 {
     435           0 :                     CPLFree(pszWKT2);
     436           0 :                     pszWKT2 = nullptr;
     437             :                 }
     438             :             }
     439          25 :             if (pszWKT2 == nullptr)
     440             :             {
     441          16 :                 pszWKT2 = CPLStrdup("undefined");
     442             :             }
     443             : 
     444          25 :             if (pszDescription)
     445             :             {
     446          22 :                 pszSQL = sqlite3_mprintf(
     447             :                     "INSERT INTO gpkg_spatial_ref_sys_temp(srs_name, srs_id, "
     448             :                     "organization, organization_coordsys_id, definition, "
     449             :                     "description, definition_12_063) VALUES ('%q', '%q', '%q', "
     450             :                     "'%q', '%q', '%q', '%q')",
     451             :                     pszSrsName, pszSrsId, pszOrganization,
     452             :                     pszOrganizationCoordsysID, pszDefinition, pszDescription,
     453             :                     pszWKT2);
     454             :             }
     455             :             else
     456             :             {
     457           3 :                 pszSQL = sqlite3_mprintf(
     458             :                     "INSERT INTO gpkg_spatial_ref_sys_temp(srs_name, srs_id, "
     459             :                     "organization, organization_coordsys_id, definition, "
     460             :                     "description, definition_12_063) VALUES ('%q', '%q', '%q', "
     461             :                     "'%q', '%q', NULL, '%q')",
     462             :                     pszSrsName, pszSrsId, pszOrganization,
     463             :                     pszOrganizationCoordsysID, pszDefinition, pszWKT2);
     464             :             }
     465             : 
     466          25 :             CPLFree(pszWKT2);
     467          25 :             bRet &= SQLCommand(hDB, pszSQL) == OGRERR_NONE;
     468          25 :             sqlite3_free(pszSQL);
     469             :         }
     470             :     }
     471             : 
     472           7 :     if (bRet)
     473             :     {
     474           7 :         bRet =
     475           7 :             SQLCommand(hDB, "DROP TABLE gpkg_spatial_ref_sys") == OGRERR_NONE;
     476             :     }
     477           7 :     if (bRet)
     478             :     {
     479           7 :         bRet = SQLCommand(hDB, "ALTER TABLE gpkg_spatial_ref_sys_temp RENAME "
     480             :                                "TO gpkg_spatial_ref_sys") == OGRERR_NONE;
     481             :     }
     482           7 :     if (bRet)
     483             :     {
     484          14 :         bRet = OGRERR_NONE == CreateExtensionsTableIfNecessary() &&
     485           7 :                OGRERR_NONE == SQLCommand(hDB,
     486             :                                          "INSERT INTO gpkg_extensions "
     487             :                                          "(table_name, column_name, "
     488             :                                          "extension_name, definition, scope) "
     489             :                                          "VALUES "
     490             :                                          "('gpkg_spatial_ref_sys', "
     491             :                                          "'definition_12_063', 'gpkg_crs_wkt', "
     492             :                                          "'http://www.geopackage.org/spec120/"
     493             :                                          "#extension_crs_wkt', 'read-write')");
     494             :     }
     495           7 :     if (bRet && bAddEpoch)
     496             :     {
     497           6 :         bRet =
     498             :             OGRERR_NONE ==
     499           6 :                 SQLCommand(hDB, "UPDATE gpkg_extensions SET extension_name = "
     500             :                                 "'gpkg_crs_wkt_1_1' "
     501          12 :                                 "WHERE extension_name = 'gpkg_crs_wkt'") &&
     502             :             OGRERR_NONE ==
     503           6 :                 SQLCommand(
     504             :                     hDB,
     505             :                     "INSERT INTO gpkg_extensions "
     506             :                     "(table_name, column_name, extension_name, definition, "
     507             :                     "scope) "
     508             :                     "VALUES "
     509             :                     "('gpkg_spatial_ref_sys', 'epoch', 'gpkg_crs_wkt_1_1', "
     510             :                     "'http://www.geopackage.org/spec/#extension_crs_wkt', "
     511             :                     "'read-write')");
     512             :     }
     513           7 :     if (bRet)
     514             :     {
     515           7 :         SoftCommitTransaction();
     516           7 :         m_bHasDefinition12_063 = true;
     517           7 :         if (bAddEpoch)
     518           6 :             m_bHasEpochColumn = true;
     519             :     }
     520             :     else
     521             :     {
     522           0 :         SoftRollbackTransaction();
     523             :     }
     524             : 
     525           7 :     return bRet;
     526             : }
     527             : 
     528         850 : int GDALGeoPackageDataset::GetSrsId(const OGRSpatialReference *poSRSIn)
     529             : {
     530         850 :     const char *pszName = poSRSIn ? poSRSIn->GetName() : nullptr;
     531        1244 :     if (!poSRSIn || poSRSIn->IsEmpty() ||
     532         394 :         (pszName && EQUAL(pszName, "Undefined SRS")))
     533             :     {
     534         458 :         OGRErr err = OGRERR_NONE;
     535         458 :         const int nSRSId = SQLGetInteger(
     536             :             hDB,
     537             :             "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE srs_name = "
     538             :             "'Undefined SRS' AND organization = 'GDAL'",
     539             :             &err);
     540         458 :         if (err == OGRERR_NONE)
     541          55 :             return nSRSId;
     542             : 
     543             :         // The below WKT definitions are somehow questionable (using a unknown
     544             :         // unit). For GDAL >= 3.9, they won't be used. They will only be used
     545             :         // for earlier versions.
     546             :         const char *pszSQL;
     547             : #define UNDEFINED_CRS_SRS_ID 99999
     548             :         static_assert(UNDEFINED_CRS_SRS_ID == FIRST_CUSTOM_SRSID - 1);
     549             : #define STRINGIFY(x) #x
     550             : #define XSTRINGIFY(x) STRINGIFY(x)
     551         403 :         if (m_bHasDefinition12_063)
     552             :         {
     553             :             /* clang-format off */
     554           1 :             pszSQL =
     555             :                 "INSERT INTO gpkg_spatial_ref_sys "
     556             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     557             :                 "definition, definition_12_063, description) VALUES "
     558             :                 "('Undefined SRS'," XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ",'GDAL',"
     559             :                 XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ","
     560             :                 "'LOCAL_CS[\"Undefined SRS\",LOCAL_DATUM[\"unknown\",32767],"
     561             :                 "UNIT[\"unknown\",0],AXIS[\"Easting\",EAST],"
     562             :                 "AXIS[\"Northing\",NORTH]]',"
     563             :                 "'ENGCRS[\"Undefined SRS\",EDATUM[\"unknown\"],CS[Cartesian,2],"
     564             :                 "AXIS[\"easting\",east,ORDER[1],LENGTHUNIT[\"unknown\",0]],"
     565             :                 "AXIS[\"northing\",north,ORDER[2],LENGTHUNIT[\"unknown\",0]]]',"
     566             :                 "'Custom undefined coordinate reference system')";
     567             :             /* clang-format on */
     568             :         }
     569             :         else
     570             :         {
     571             :             /* clang-format off */
     572         402 :             pszSQL =
     573             :                 "INSERT INTO gpkg_spatial_ref_sys "
     574             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     575             :                 "definition, description) VALUES "
     576             :                 "('Undefined SRS'," XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ",'GDAL',"
     577             :                 XSTRINGIFY(UNDEFINED_CRS_SRS_ID) ","
     578             :                 "'LOCAL_CS[\"Undefined SRS\",LOCAL_DATUM[\"unknown\",32767],"
     579             :                 "UNIT[\"unknown\",0],AXIS[\"Easting\",EAST],"
     580             :                 "AXIS[\"Northing\",NORTH]]',"
     581             :                 "'Custom undefined coordinate reference system')";
     582             :             /* clang-format on */
     583             :         }
     584         403 :         if (SQLCommand(hDB, pszSQL) == OGRERR_NONE)
     585         403 :             return UNDEFINED_CRS_SRS_ID;
     586             : #undef UNDEFINED_CRS_SRS_ID
     587             : #undef XSTRINGIFY
     588             : #undef STRINGIFY
     589           0 :         return -1;
     590             :     }
     591             : 
     592         784 :     std::unique_ptr<OGRSpatialReference> poSRS(poSRSIn->Clone());
     593             : 
     594         392 :     if (poSRS->IsGeographic() || poSRS->IsLocal())
     595             :     {
     596             :         // See corresponding tests in GDALGeoPackageDataset::GetSpatialRef
     597         138 :         if (pszName != nullptr && strlen(pszName) > 0)
     598             :         {
     599         138 :             if (EQUAL(pszName, "Undefined geographic SRS"))
     600           2 :                 return 0;
     601             : 
     602         136 :             if (EQUAL(pszName, "Undefined Cartesian SRS"))
     603           1 :                 return -1;
     604             :         }
     605             :     }
     606             : 
     607         389 :     const char *pszAuthorityName = poSRS->GetAuthorityName(nullptr);
     608             : 
     609         389 :     if (pszAuthorityName == nullptr || strlen(pszAuthorityName) == 0)
     610             :     {
     611             :         // Try to force identify an EPSG code.
     612          26 :         poSRS->AutoIdentifyEPSG();
     613             : 
     614          26 :         pszAuthorityName = poSRS->GetAuthorityName(nullptr);
     615          26 :         if (pszAuthorityName != nullptr && EQUAL(pszAuthorityName, "EPSG"))
     616             :         {
     617           0 :             const char *pszAuthorityCode = poSRS->GetAuthorityCode(nullptr);
     618           0 :             if (pszAuthorityCode != nullptr && strlen(pszAuthorityCode) > 0)
     619             :             {
     620             :                 /* Import 'clean' SRS */
     621           0 :                 poSRS->importFromEPSG(atoi(pszAuthorityCode));
     622             : 
     623           0 :                 pszAuthorityName = poSRS->GetAuthorityName(nullptr);
     624             :             }
     625             :         }
     626             : 
     627          26 :         poSRS->SetCoordinateEpoch(poSRSIn->GetCoordinateEpoch());
     628             :     }
     629             : 
     630             :     // Check whether the EPSG authority code is already mapped to a
     631             :     // SRS ID.
     632         389 :     char *pszSQL = nullptr;
     633         389 :     int nSRSId = DEFAULT_SRID;
     634         389 :     int nAuthorityCode = 0;
     635         389 :     OGRErr err = OGRERR_NONE;
     636         389 :     bool bCanUseAuthorityCode = false;
     637         389 :     const char *const apszIsSameOptions[] = {
     638             :         "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES",
     639             :         "IGNORE_COORDINATE_EPOCH=YES", nullptr};
     640         389 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0)
     641             :     {
     642         363 :         const char *pszAuthorityCode = poSRS->GetAuthorityCode(nullptr);
     643         363 :         if (pszAuthorityCode)
     644             :         {
     645         363 :             if (CPLGetValueType(pszAuthorityCode) == CPL_VALUE_INTEGER)
     646             :             {
     647         363 :                 nAuthorityCode = atoi(pszAuthorityCode);
     648             :             }
     649             :             else
     650             :             {
     651           0 :                 CPLDebug("GPKG",
     652             :                          "SRS has %s:%s identification, but the code not "
     653             :                          "being an integer value cannot be stored as such "
     654             :                          "in the database.",
     655             :                          pszAuthorityName, pszAuthorityCode);
     656           0 :                 pszAuthorityName = nullptr;
     657             :             }
     658             :         }
     659             :     }
     660             : 
     661         752 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     662         363 :         poSRSIn->GetCoordinateEpoch() == 0)
     663             :     {
     664             :         pszSQL =
     665         358 :             sqlite3_mprintf("SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     666             :                             "upper(organization) = upper('%q') AND "
     667             :                             "organization_coordsys_id = %d",
     668             :                             pszAuthorityName, nAuthorityCode);
     669             : 
     670         358 :         nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     671         358 :         sqlite3_free(pszSQL);
     672             : 
     673             :         // Got a match? Return it!
     674         358 :         if (OGRERR_NONE == err)
     675             :         {
     676         114 :             auto poRefSRS = GetSpatialRef(nSRSId);
     677             :             bool bOK =
     678         114 :                 (poRefSRS == nullptr ||
     679         115 :                  poSRS->IsSame(poRefSRS.get(), apszIsSameOptions) ||
     680           1 :                  !CPLTestBool(CPLGetConfigOption("OGR_GPKG_CHECK_SRS", "YES")));
     681         114 :             if (bOK)
     682             :             {
     683         113 :                 return nSRSId;
     684             :             }
     685             :             else
     686             :             {
     687           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
     688             :                          "Passed SRS uses %s:%d identification, but its "
     689             :                          "definition is not compatible with the "
     690             :                          "definition of that object already in the database. "
     691             :                          "Registering it as a new entry into the database.",
     692             :                          pszAuthorityName, nAuthorityCode);
     693           1 :                 pszAuthorityName = nullptr;
     694           1 :                 nAuthorityCode = 0;
     695             :             }
     696             :         }
     697             :     }
     698             : 
     699             :     // Translate SRS to WKT.
     700         276 :     CPLCharUniquePtr pszWKT1;
     701         276 :     CPLCharUniquePtr pszWKT2_2015;
     702         276 :     CPLCharUniquePtr pszWKT2_2019;
     703         276 :     const char *const apszOptionsWkt1[] = {"FORMAT=WKT1_GDAL", nullptr};
     704         276 :     const char *const apszOptionsWkt2_2015[] = {"FORMAT=WKT2_2015", nullptr};
     705         276 :     const char *const apszOptionsWkt2_2019[] = {"FORMAT=WKT2_2019", nullptr};
     706             : 
     707         552 :     std::string osEpochTest;
     708         276 :     if (poSRSIn->GetCoordinateEpoch() > 0 && m_bHasEpochColumn)
     709             :     {
     710             :         osEpochTest =
     711           3 :             CPLSPrintf(" AND epoch = %.17g", poSRSIn->GetCoordinateEpoch());
     712             :     }
     713             : 
     714         276 :     if (!(poSRS->IsGeographic() && poSRS->GetAxesCount() == 3))
     715             :     {
     716         267 :         char *pszTmp = nullptr;
     717         267 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt1);
     718         267 :         pszWKT1.reset(pszTmp);
     719         267 :         if (pszWKT1 && pszWKT1.get()[0] == '\0')
     720             :         {
     721           0 :             pszWKT1.reset();
     722             :         }
     723             :     }
     724             :     {
     725         276 :         char *pszTmp = nullptr;
     726         276 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2015);
     727         276 :         pszWKT2_2015.reset(pszTmp);
     728         276 :         if (pszWKT2_2015 && pszWKT2_2015.get()[0] == '\0')
     729             :         {
     730           0 :             pszWKT2_2015.reset();
     731             :         }
     732             :     }
     733             :     {
     734         276 :         char *pszTmp = nullptr;
     735         276 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2019);
     736         276 :         pszWKT2_2019.reset(pszTmp);
     737         276 :         if (pszWKT2_2019 && pszWKT2_2019.get()[0] == '\0')
     738             :         {
     739           0 :             pszWKT2_2019.reset();
     740             :         }
     741             :     }
     742             : 
     743         276 :     if (!pszWKT1 && !pszWKT2_2015 && !pszWKT2_2019)
     744             :     {
     745           0 :         return DEFAULT_SRID;
     746             :     }
     747             : 
     748         276 :     if (poSRSIn->GetCoordinateEpoch() == 0 || m_bHasEpochColumn)
     749             :     {
     750             :         // Search if there is already an existing entry with this WKT
     751         273 :         if (m_bHasDefinition12_063 && (pszWKT2_2015 || pszWKT2_2019))
     752             :         {
     753          42 :             if (pszWKT1)
     754             :             {
     755         144 :                 pszSQL = sqlite3_mprintf(
     756             :                     "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     757             :                     "(definition = '%q' OR definition_12_063 IN ('%q','%q'))%s",
     758             :                     pszWKT1.get(),
     759          72 :                     pszWKT2_2015 ? pszWKT2_2015.get() : "invalid",
     760          72 :                     pszWKT2_2019 ? pszWKT2_2019.get() : "invalid",
     761             :                     osEpochTest.c_str());
     762             :             }
     763             :             else
     764             :             {
     765          24 :                 pszSQL = sqlite3_mprintf(
     766             :                     "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     767             :                     "definition_12_063 IN ('%q', '%q')%s",
     768          12 :                     pszWKT2_2015 ? pszWKT2_2015.get() : "invalid",
     769          12 :                     pszWKT2_2019 ? pszWKT2_2019.get() : "invalid",
     770             :                     osEpochTest.c_str());
     771             :             }
     772             :         }
     773         231 :         else if (pszWKT1)
     774             :         {
     775             :             pszSQL =
     776         228 :                 sqlite3_mprintf("SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
     777             :                                 "definition = '%q'%s",
     778             :                                 pszWKT1.get(), osEpochTest.c_str());
     779             :         }
     780             :         else
     781             :         {
     782           3 :             pszSQL = nullptr;
     783             :         }
     784         273 :         if (pszSQL)
     785             :         {
     786         270 :             nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     787         270 :             sqlite3_free(pszSQL);
     788         270 :             if (OGRERR_NONE == err)
     789             :             {
     790           5 :                 return nSRSId;
     791             :             }
     792             :         }
     793             :     }
     794             : 
     795         518 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     796         247 :         poSRSIn->GetCoordinateEpoch() == 0)
     797             :     {
     798         243 :         bool bTryToReuseSRSId = true;
     799         243 :         if (EQUAL(pszAuthorityName, "EPSG"))
     800             :         {
     801         484 :             OGRSpatialReference oSRS_EPSG;
     802         242 :             if (GDALGPKGImportFromEPSG(&oSRS_EPSG, nAuthorityCode) ==
     803             :                 OGRERR_NONE)
     804             :             {
     805         243 :                 if (!poSRS->IsSame(&oSRS_EPSG, apszIsSameOptions) &&
     806           1 :                     CPLTestBool(
     807             :                         CPLGetConfigOption("OGR_GPKG_CHECK_SRS", "YES")))
     808             :                 {
     809           1 :                     bTryToReuseSRSId = false;
     810           1 :                     CPLError(
     811             :                         CE_Warning, CPLE_AppDefined,
     812             :                         "Passed SRS uses %s:%d identification, but its "
     813             :                         "definition is not compatible with the "
     814             :                         "official definition of the object. "
     815             :                         "Registering it as a non-%s entry into the database.",
     816             :                         pszAuthorityName, nAuthorityCode, pszAuthorityName);
     817           1 :                     pszAuthorityName = nullptr;
     818           1 :                     nAuthorityCode = 0;
     819             :                 }
     820             :             }
     821             :         }
     822         243 :         if (bTryToReuseSRSId)
     823             :         {
     824             :             // No match, but maybe we can use the nAuthorityCode as the nSRSId?
     825         242 :             pszSQL = sqlite3_mprintf(
     826             :                 "SELECT Count(*) FROM gpkg_spatial_ref_sys WHERE "
     827             :                 "srs_id = %d",
     828             :                 nAuthorityCode);
     829             : 
     830             :             // Yep, we can!
     831         242 :             if (SQLGetInteger(hDB, pszSQL, nullptr) == 0)
     832         241 :                 bCanUseAuthorityCode = true;
     833         242 :             sqlite3_free(pszSQL);
     834             :         }
     835             :     }
     836             : 
     837         271 :     bool bConvertGpkgSpatialRefSysToExtensionWkt2 = false;
     838         271 :     bool bForceEpoch = false;
     839         274 :     if (!m_bHasDefinition12_063 && pszWKT1 == nullptr &&
     840           3 :         (pszWKT2_2015 != nullptr || pszWKT2_2019 != nullptr))
     841             :     {
     842           3 :         bConvertGpkgSpatialRefSysToExtensionWkt2 = true;
     843             :     }
     844             : 
     845             :     // Add epoch column if needed
     846         271 :     if (poSRSIn->GetCoordinateEpoch() > 0 && !m_bHasEpochColumn)
     847             :     {
     848           3 :         if (m_bHasDefinition12_063)
     849             :         {
     850           0 :             if (SoftStartTransaction() != OGRERR_NONE)
     851           0 :                 return DEFAULT_SRID;
     852           0 :             if (SQLCommand(hDB, "ALTER TABLE gpkg_spatial_ref_sys "
     853           0 :                                 "ADD COLUMN epoch DOUBLE") != OGRERR_NONE ||
     854           0 :                 SQLCommand(hDB, "UPDATE gpkg_extensions SET extension_name = "
     855             :                                 "'gpkg_crs_wkt_1_1' "
     856             :                                 "WHERE extension_name = 'gpkg_crs_wkt'") !=
     857           0 :                     OGRERR_NONE ||
     858           0 :                 SQLCommand(
     859             :                     hDB,
     860             :                     "INSERT INTO gpkg_extensions "
     861             :                     "(table_name, column_name, extension_name, definition, "
     862             :                     "scope) "
     863             :                     "VALUES "
     864             :                     "('gpkg_spatial_ref_sys', 'epoch', 'gpkg_crs_wkt_1_1', "
     865             :                     "'http://www.geopackage.org/spec/#extension_crs_wkt', "
     866             :                     "'read-write')") != OGRERR_NONE)
     867             :             {
     868           0 :                 SoftRollbackTransaction();
     869           0 :                 return DEFAULT_SRID;
     870             :             }
     871             : 
     872           0 :             if (SoftCommitTransaction() != OGRERR_NONE)
     873           0 :                 return DEFAULT_SRID;
     874             : 
     875           0 :             m_bHasEpochColumn = true;
     876             :         }
     877             :         else
     878             :         {
     879           3 :             bConvertGpkgSpatialRefSysToExtensionWkt2 = true;
     880           3 :             bForceEpoch = true;
     881             :         }
     882             :     }
     883             : 
     884         277 :     if (bConvertGpkgSpatialRefSysToExtensionWkt2 &&
     885           6 :         !ConvertGpkgSpatialRefSysToExtensionWkt2(bForceEpoch))
     886             :     {
     887           0 :         return DEFAULT_SRID;
     888             :     }
     889             : 
     890             :     // Reuse the authority code number as SRS_ID if we can
     891         271 :     if (bCanUseAuthorityCode)
     892             :     {
     893         241 :         nSRSId = nAuthorityCode;
     894             :     }
     895             :     // Otherwise, generate a new SRS_ID number (max + 1)
     896             :     else
     897             :     {
     898             :         // Get the current maximum srid in the srs table.
     899          30 :         const int nMaxSRSId = SQLGetInteger(
     900             :             hDB, "SELECT MAX(srs_id) FROM gpkg_spatial_ref_sys", nullptr);
     901          30 :         nSRSId = std::max(FIRST_CUSTOM_SRSID, nMaxSRSId + 1);
     902             :     }
     903             : 
     904         542 :     std::string osEpochColumn;
     905         271 :     std::string osEpochVal;
     906         271 :     if (poSRSIn->GetCoordinateEpoch() > 0)
     907             :     {
     908           5 :         osEpochColumn = ", epoch";
     909           5 :         osEpochVal = CPLSPrintf(", %.17g", poSRSIn->GetCoordinateEpoch());
     910             :     }
     911             : 
     912             :     // Add new SRS row to gpkg_spatial_ref_sys.
     913         271 :     if (m_bHasDefinition12_063)
     914             :     {
     915             :         // Force WKT2_2019 when we have a dynamic CRS and coordinate epoch
     916          45 :         const char *pszWKT2 = poSRSIn->IsDynamic() &&
     917          10 :                                       poSRSIn->GetCoordinateEpoch() > 0 &&
     918           1 :                                       pszWKT2_2019
     919           1 :                                   ? pszWKT2_2019.get()
     920          44 :                               : pszWKT2_2015 ? pszWKT2_2015.get()
     921          97 :                                              : pszWKT2_2019.get();
     922             : 
     923          45 :         if (pszAuthorityName != nullptr && nAuthorityCode > 0)
     924             :         {
     925          99 :             pszSQL = sqlite3_mprintf(
     926             :                 "INSERT INTO gpkg_spatial_ref_sys "
     927             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     928             :                 "definition, definition_12_063%s) VALUES "
     929             :                 "('%q', %d, upper('%q'), %d, '%q', '%q'%s)",
     930          33 :                 osEpochColumn.c_str(), GetSrsName(*poSRS), nSRSId,
     931             :                 pszAuthorityName, nAuthorityCode,
     932          62 :                 pszWKT1 ? pszWKT1.get() : "undefined",
     933             :                 pszWKT2 ? pszWKT2 : "undefined", osEpochVal.c_str());
     934             :         }
     935             :         else
     936             :         {
     937          36 :             pszSQL = sqlite3_mprintf(
     938             :                 "INSERT INTO gpkg_spatial_ref_sys "
     939             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     940             :                 "definition, definition_12_063%s) VALUES "
     941             :                 "('%q', %d, upper('%q'), %d, '%q', '%q'%s)",
     942          12 :                 osEpochColumn.c_str(), GetSrsName(*poSRS), nSRSId, "NONE",
     943          21 :                 nSRSId, pszWKT1 ? pszWKT1.get() : "undefined",
     944             :                 pszWKT2 ? pszWKT2 : "undefined", osEpochVal.c_str());
     945             :         }
     946             :     }
     947             :     else
     948             :     {
     949         226 :         if (pszAuthorityName != nullptr && nAuthorityCode > 0)
     950             :         {
     951         426 :             pszSQL = sqlite3_mprintf(
     952             :                 "INSERT INTO gpkg_spatial_ref_sys "
     953             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     954             :                 "definition) VALUES ('%q', %d, upper('%q'), %d, '%q')",
     955         213 :                 GetSrsName(*poSRS), nSRSId, pszAuthorityName, nAuthorityCode,
     956         426 :                 pszWKT1 ? pszWKT1.get() : "undefined");
     957             :         }
     958             :         else
     959             :         {
     960          26 :             pszSQL = sqlite3_mprintf(
     961             :                 "INSERT INTO gpkg_spatial_ref_sys "
     962             :                 "(srs_name,srs_id,organization,organization_coordsys_id,"
     963             :                 "definition) VALUES ('%q', %d, upper('%q'), %d, '%q')",
     964          13 :                 GetSrsName(*poSRS), nSRSId, "NONE", nSRSId,
     965          26 :                 pszWKT1 ? pszWKT1.get() : "undefined");
     966             :         }
     967             :     }
     968             : 
     969             :     // Add new row to gpkg_spatial_ref_sys.
     970         271 :     CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
     971             : 
     972             :     // Free everything that was allocated.
     973         271 :     sqlite3_free(pszSQL);
     974             : 
     975         271 :     return nSRSId;
     976             : }
     977             : 
     978             : /************************************************************************/
     979             : /*                       ~GDALGeoPackageDataset()                       */
     980             : /************************************************************************/
     981             : 
     982        4854 : GDALGeoPackageDataset::~GDALGeoPackageDataset()
     983             : {
     984        2427 :     GDALGeoPackageDataset::Close();
     985        4854 : }
     986             : 
     987             : /************************************************************************/
     988             : /*                              Close()                                 */
     989             : /************************************************************************/
     990             : 
     991        4088 : CPLErr GDALGeoPackageDataset::Close()
     992             : {
     993        4088 :     CPLErr eErr = CE_None;
     994        4088 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     995             :     {
     996        1421 :         if (eAccess == GA_Update && m_poParentDS == nullptr &&
     997        3848 :             !m_osRasterTable.empty() && !m_bGeoTransformValid)
     998             :         {
     999           3 :             CPLError(CE_Failure, CPLE_AppDefined,
    1000             :                      "Raster table %s not correctly initialized due to missing "
    1001             :                      "call to SetGeoTransform()",
    1002             :                      m_osRasterTable.c_str());
    1003             :         }
    1004             : 
    1005        2427 :         if (GDALGeoPackageDataset::FlushCache(true) != CE_None)
    1006           7 :             eErr = CE_Failure;
    1007             : 
    1008             :         // Destroy bands now since we don't want
    1009             :         // GDALGPKGMBTilesLikeRasterBand::FlushCache() to run after dataset
    1010             :         // destruction
    1011        4245 :         for (int i = 0; i < nBands; i++)
    1012        1818 :             delete papoBands[i];
    1013        2427 :         nBands = 0;
    1014        2427 :         CPLFree(papoBands);
    1015        2427 :         papoBands = nullptr;
    1016             : 
    1017             :         // Destroy overviews before cleaning m_hTempDB as they could still
    1018             :         // need it
    1019        2427 :         m_apoOverviewDS.clear();
    1020             : 
    1021        2427 :         if (m_poParentDS)
    1022             :         {
    1023         325 :             hDB = nullptr;
    1024             :         }
    1025             : 
    1026        2427 :         m_apoLayers.clear();
    1027             : 
    1028             :         std::map<int, OGRSpatialReference *>::iterator oIter =
    1029        2427 :             m_oMapSrsIdToSrs.begin();
    1030        3537 :         for (; oIter != m_oMapSrsIdToSrs.end(); ++oIter)
    1031             :         {
    1032        1110 :             OGRSpatialReference *poSRS = oIter->second;
    1033        1110 :             if (poSRS)
    1034         700 :                 poSRS->Release();
    1035             :         }
    1036             : 
    1037        2427 :         if (!CloseDB())
    1038           0 :             eErr = CE_Failure;
    1039             : 
    1040        2427 :         if (OGRSQLiteBaseDataSource::Close() != CE_None)
    1041           0 :             eErr = CE_Failure;
    1042             :     }
    1043        4088 :     return eErr;
    1044             : }
    1045             : 
    1046             : /************************************************************************/
    1047             : /*                         ICanIWriteBlock()                            */
    1048             : /************************************************************************/
    1049             : 
    1050        5694 : bool GDALGeoPackageDataset::ICanIWriteBlock()
    1051             : {
    1052        5694 :     if (!GetUpdate())
    1053             :     {
    1054           0 :         CPLError(
    1055             :             CE_Failure, CPLE_NotSupported,
    1056             :             "IWriteBlock() not supported on dataset opened in read-only mode");
    1057           0 :         return false;
    1058             :     }
    1059             : 
    1060        5694 :     if (m_pabyCachedTiles == nullptr)
    1061             :     {
    1062           0 :         return false;
    1063             :     }
    1064             : 
    1065        5694 :     if (!m_bGeoTransformValid || m_nSRID == UNKNOWN_SRID)
    1066             :     {
    1067           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    1068             :                  "IWriteBlock() not supported if georeferencing not set");
    1069           0 :         return false;
    1070             :     }
    1071        5694 :     return true;
    1072             : }
    1073             : 
    1074             : /************************************************************************/
    1075             : /*                            IRasterIO()                               */
    1076             : /************************************************************************/
    1077             : 
    1078         130 : CPLErr GDALGeoPackageDataset::IRasterIO(
    1079             :     GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
    1080             :     void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
    1081             :     int nBandCount, BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
    1082             :     GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg)
    1083             : 
    1084             : {
    1085         130 :     CPLErr eErr = OGRSQLiteBaseDataSource::IRasterIO(
    1086             :         eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    1087             :         eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
    1088             :         psExtraArg);
    1089             : 
    1090             :     // If writing all bands, in non-shifted mode, flush all entirely written
    1091             :     // tiles This can avoid "stressing" the block cache with too many dirty
    1092             :     // blocks. Note: this logic would be useless with a per-dataset block cache.
    1093         130 :     if (eErr == CE_None && eRWFlag == GF_Write && nXSize == nBufXSize &&
    1094         121 :         nYSize == nBufYSize && nBandCount == nBands &&
    1095         118 :         m_nShiftXPixelsMod == 0 && m_nShiftYPixelsMod == 0)
    1096             :     {
    1097             :         auto poBand =
    1098         114 :             cpl::down_cast<GDALGPKGMBTilesLikeRasterBand *>(GetRasterBand(1));
    1099             :         int nBlockXSize, nBlockYSize;
    1100         114 :         poBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
    1101         114 :         const int nBlockXStart = DIV_ROUND_UP(nXOff, nBlockXSize);
    1102         114 :         const int nBlockYStart = DIV_ROUND_UP(nYOff, nBlockYSize);
    1103         114 :         const int nBlockXEnd = (nXOff + nXSize) / nBlockXSize;
    1104         114 :         const int nBlockYEnd = (nYOff + nYSize) / nBlockYSize;
    1105         268 :         for (int nBlockY = nBlockXStart; nBlockY < nBlockYEnd; nBlockY++)
    1106             :         {
    1107        4371 :             for (int nBlockX = nBlockYStart; nBlockX < nBlockXEnd; nBlockX++)
    1108             :             {
    1109             :                 GDALRasterBlock *poBlock =
    1110        4217 :                     poBand->AccessibleTryGetLockedBlockRef(nBlockX, nBlockY);
    1111        4217 :                 if (poBlock)
    1112             :                 {
    1113             :                     // GetDirty() should be true in most situation (otherwise
    1114             :                     // it means the block cache is under extreme pressure!)
    1115        4215 :                     if (poBlock->GetDirty())
    1116             :                     {
    1117             :                         // IWriteBlock() on one band will check the dirty state
    1118             :                         // of the corresponding blocks in other bands, to decide
    1119             :                         // if it can call WriteTile(), so we have only to do
    1120             :                         // that on one of the bands
    1121        4215 :                         if (poBlock->Write() != CE_None)
    1122         250 :                             eErr = CE_Failure;
    1123             :                     }
    1124        4215 :                     poBlock->DropLock();
    1125             :                 }
    1126             :             }
    1127             :         }
    1128             :     }
    1129             : 
    1130         130 :     return eErr;
    1131             : }
    1132             : 
    1133             : /************************************************************************/
    1134             : /*                          GetOGRTableLimit()                          */
    1135             : /************************************************************************/
    1136             : 
    1137        3954 : static int GetOGRTableLimit()
    1138             : {
    1139        3954 :     return atoi(CPLGetConfigOption("OGR_TABLE_LIMIT", "10000"));
    1140             : }
    1141             : 
    1142             : /************************************************************************/
    1143             : /*                      GetNameTypeMapFromSQliteMaster()                */
    1144             : /************************************************************************/
    1145             : 
    1146             : const std::map<CPLString, CPLString> &
    1147        1227 : GDALGeoPackageDataset::GetNameTypeMapFromSQliteMaster()
    1148             : {
    1149        1227 :     if (!m_oMapNameToType.empty())
    1150         337 :         return m_oMapNameToType;
    1151             : 
    1152             :     CPLString osSQL(
    1153             :         "SELECT name, type FROM sqlite_master WHERE "
    1154             :         "type IN ('view', 'table') OR "
    1155        1780 :         "(name LIKE 'trigger_%_feature_count_%' AND type = 'trigger')");
    1156         890 :     const int nTableLimit = GetOGRTableLimit();
    1157         890 :     if (nTableLimit > 0)
    1158             :     {
    1159         890 :         osSQL += " LIMIT ";
    1160         890 :         osSQL += CPLSPrintf("%d", 1 + 3 * nTableLimit);
    1161             :     }
    1162             : 
    1163         890 :     auto oResult = SQLQuery(hDB, osSQL);
    1164         890 :     if (oResult)
    1165             :     {
    1166       14877 :         for (int i = 0; i < oResult->RowCount(); i++)
    1167             :         {
    1168       13987 :             const char *pszName = oResult->GetValue(0, i);
    1169       13987 :             const char *pszType = oResult->GetValue(1, i);
    1170       13987 :             m_oMapNameToType[CPLString(pszName).toupper()] = pszType;
    1171             :         }
    1172             :     }
    1173             : 
    1174         890 :     return m_oMapNameToType;
    1175             : }
    1176             : 
    1177             : /************************************************************************/
    1178             : /*                    RemoveTableFromSQLiteMasterCache()                */
    1179             : /************************************************************************/
    1180             : 
    1181          55 : void GDALGeoPackageDataset::RemoveTableFromSQLiteMasterCache(
    1182             :     const char *pszTableName)
    1183             : {
    1184          55 :     m_oMapNameToType.erase(CPLString(pszTableName).toupper());
    1185          55 : }
    1186             : 
    1187             : /************************************************************************/
    1188             : /*                  GetUnknownExtensionsTableSpecific()                 */
    1189             : /************************************************************************/
    1190             : 
    1191             : const std::map<CPLString, std::vector<GPKGExtensionDesc>> &
    1192         848 : GDALGeoPackageDataset::GetUnknownExtensionsTableSpecific()
    1193             : {
    1194         848 :     if (m_bMapTableToExtensionsBuilt)
    1195          89 :         return m_oMapTableToExtensions;
    1196         759 :     m_bMapTableToExtensionsBuilt = true;
    1197             : 
    1198         759 :     if (!HasExtensionsTable())
    1199          40 :         return m_oMapTableToExtensions;
    1200             : 
    1201             :     CPLString osSQL(
    1202             :         "SELECT table_name, extension_name, definition, scope "
    1203             :         "FROM gpkg_extensions WHERE "
    1204             :         "table_name IS NOT NULL "
    1205             :         "AND extension_name IS NOT NULL "
    1206             :         "AND definition IS NOT NULL "
    1207             :         "AND scope IS NOT NULL "
    1208             :         "AND extension_name NOT IN ('gpkg_geom_CIRCULARSTRING', "
    1209             :         "'gpkg_geom_COMPOUNDCURVE', 'gpkg_geom_CURVEPOLYGON', "
    1210             :         "'gpkg_geom_MULTICURVE', "
    1211             :         "'gpkg_geom_MULTISURFACE', 'gpkg_geom_CURVE', 'gpkg_geom_SURFACE', "
    1212             :         "'gpkg_geom_POLYHEDRALSURFACE', 'gpkg_geom_TIN', 'gpkg_geom_TRIANGLE', "
    1213             :         "'gpkg_rtree_index', 'gpkg_geometry_type_trigger', "
    1214             :         "'gpkg_srs_id_trigger', "
    1215             :         "'gpkg_crs_wkt', 'gpkg_crs_wkt_1_1', 'gpkg_schema', "
    1216             :         "'gpkg_related_tables', 'related_tables'"
    1217             : #ifdef HAVE_SPATIALITE
    1218             :         ", 'gdal_spatialite_computed_geom_column'"
    1219             : #endif
    1220        1438 :         ")");
    1221         719 :     const int nTableLimit = GetOGRTableLimit();
    1222         719 :     if (nTableLimit > 0)
    1223             :     {
    1224         719 :         osSQL += " LIMIT ";
    1225         719 :         osSQL += CPLSPrintf("%d", 1 + 10 * nTableLimit);
    1226             :     }
    1227             : 
    1228         719 :     auto oResult = SQLQuery(hDB, osSQL);
    1229         719 :     if (oResult)
    1230             :     {
    1231        1374 :         for (int i = 0; i < oResult->RowCount(); i++)
    1232             :         {
    1233         655 :             const char *pszTableName = oResult->GetValue(0, i);
    1234         655 :             const char *pszExtensionName = oResult->GetValue(1, i);
    1235         655 :             const char *pszDefinition = oResult->GetValue(2, i);
    1236         655 :             const char *pszScope = oResult->GetValue(3, i);
    1237         655 :             if (pszTableName && pszExtensionName && pszDefinition && pszScope)
    1238             :             {
    1239         655 :                 GPKGExtensionDesc oDesc;
    1240         655 :                 oDesc.osExtensionName = pszExtensionName;
    1241         655 :                 oDesc.osDefinition = pszDefinition;
    1242         655 :                 oDesc.osScope = pszScope;
    1243        1310 :                 m_oMapTableToExtensions[CPLString(pszTableName).toupper()]
    1244         655 :                     .push_back(std::move(oDesc));
    1245             :             }
    1246             :         }
    1247             :     }
    1248             : 
    1249         719 :     return m_oMapTableToExtensions;
    1250             : }
    1251             : 
    1252             : /************************************************************************/
    1253             : /*                           GetContents()                              */
    1254             : /************************************************************************/
    1255             : 
    1256             : const std::map<CPLString, GPKGContentsDesc> &
    1257         830 : GDALGeoPackageDataset::GetContents()
    1258             : {
    1259         830 :     if (m_bMapTableToContentsBuilt)
    1260          73 :         return m_oMapTableToContents;
    1261         757 :     m_bMapTableToContentsBuilt = true;
    1262             : 
    1263             :     CPLString osSQL("SELECT table_name, data_type, identifier, "
    1264             :                     "description, min_x, min_y, max_x, max_y "
    1265        1514 :                     "FROM gpkg_contents");
    1266         757 :     const int nTableLimit = GetOGRTableLimit();
    1267         757 :     if (nTableLimit > 0)
    1268             :     {
    1269         757 :         osSQL += " LIMIT ";
    1270         757 :         osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1271             :     }
    1272             : 
    1273         757 :     auto oResult = SQLQuery(hDB, osSQL);
    1274         757 :     if (oResult)
    1275             :     {
    1276        1632 :         for (int i = 0; i < oResult->RowCount(); i++)
    1277             :         {
    1278         875 :             const char *pszTableName = oResult->GetValue(0, i);
    1279         875 :             if (pszTableName == nullptr)
    1280           0 :                 continue;
    1281         875 :             const char *pszDataType = oResult->GetValue(1, i);
    1282         875 :             const char *pszIdentifier = oResult->GetValue(2, i);
    1283         875 :             const char *pszDescription = oResult->GetValue(3, i);
    1284         875 :             const char *pszMinX = oResult->GetValue(4, i);
    1285         875 :             const char *pszMinY = oResult->GetValue(5, i);
    1286         875 :             const char *pszMaxX = oResult->GetValue(6, i);
    1287         875 :             const char *pszMaxY = oResult->GetValue(7, i);
    1288         875 :             GPKGContentsDesc oDesc;
    1289         875 :             if (pszDataType)
    1290         875 :                 oDesc.osDataType = pszDataType;
    1291         875 :             if (pszIdentifier)
    1292         875 :                 oDesc.osIdentifier = pszIdentifier;
    1293         875 :             if (pszDescription)
    1294         874 :                 oDesc.osDescription = pszDescription;
    1295         875 :             if (pszMinX)
    1296         597 :                 oDesc.osMinX = pszMinX;
    1297         875 :             if (pszMinY)
    1298         597 :                 oDesc.osMinY = pszMinY;
    1299         875 :             if (pszMaxX)
    1300         597 :                 oDesc.osMaxX = pszMaxX;
    1301         875 :             if (pszMaxY)
    1302         597 :                 oDesc.osMaxY = pszMaxY;
    1303        1750 :             m_oMapTableToContents[CPLString(pszTableName).toupper()] =
    1304        1750 :                 std::move(oDesc);
    1305             :         }
    1306             :     }
    1307             : 
    1308         757 :     return m_oMapTableToContents;
    1309             : }
    1310             : 
    1311             : /************************************************************************/
    1312             : /*                                Open()                                */
    1313             : /************************************************************************/
    1314             : 
    1315        1210 : int GDALGeoPackageDataset::Open(GDALOpenInfo *poOpenInfo,
    1316             :                                 const std::string &osFilenameInZip)
    1317             : {
    1318        1210 :     m_osFilenameInZip = osFilenameInZip;
    1319        1210 :     CPLAssert(m_apoLayers.empty());
    1320        1210 :     CPLAssert(hDB == nullptr);
    1321             : 
    1322        1210 :     SetDescription(poOpenInfo->pszFilename);
    1323        2420 :     CPLString osFilename(poOpenInfo->pszFilename);
    1324        2420 :     CPLString osSubdatasetTableName;
    1325             :     GByte abyHeaderLetMeHerePlease[100];
    1326        1210 :     const GByte *pabyHeader = poOpenInfo->pabyHeader;
    1327        1210 :     if (STARTS_WITH_CI(poOpenInfo->pszFilename, "GPKG:"))
    1328             :     {
    1329         245 :         char **papszTokens = CSLTokenizeString2(poOpenInfo->pszFilename, ":",
    1330             :                                                 CSLT_HONOURSTRINGS);
    1331         245 :         int nCount = CSLCount(papszTokens);
    1332         245 :         if (nCount < 2)
    1333             :         {
    1334           0 :             CSLDestroy(papszTokens);
    1335           0 :             return FALSE;
    1336             :         }
    1337             : 
    1338         245 :         if (nCount <= 3)
    1339             :         {
    1340         243 :             osFilename = papszTokens[1];
    1341             :         }
    1342             :         /* GPKG:C:\BLA.GPKG:foo */
    1343           2 :         else if (nCount == 4 && strlen(papszTokens[1]) == 1 &&
    1344           2 :                  (papszTokens[2][0] == '/' || papszTokens[2][0] == '\\'))
    1345             :         {
    1346           2 :             osFilename = CPLString(papszTokens[1]) + ":" + papszTokens[2];
    1347             :         }
    1348             :         // GPKG:/vsicurl/http[s]://[user:passwd@]example.com[:8080]/foo.gpkg:bar
    1349           0 :         else if (/*nCount >= 4 && */
    1350           0 :                  (EQUAL(papszTokens[1], "/vsicurl/http") ||
    1351           0 :                   EQUAL(papszTokens[1], "/vsicurl/https")))
    1352             :         {
    1353           0 :             osFilename = CPLString(papszTokens[1]);
    1354           0 :             for (int i = 2; i < nCount - 1; i++)
    1355             :             {
    1356           0 :                 osFilename += ':';
    1357           0 :                 osFilename += papszTokens[i];
    1358             :             }
    1359             :         }
    1360         245 :         if (nCount >= 3)
    1361          14 :             osSubdatasetTableName = papszTokens[nCount - 1];
    1362             : 
    1363         245 :         CSLDestroy(papszTokens);
    1364         245 :         VSILFILE *fp = VSIFOpenL(osFilename, "rb");
    1365         245 :         if (fp != nullptr)
    1366             :         {
    1367         245 :             VSIFReadL(abyHeaderLetMeHerePlease, 1, 100, fp);
    1368         245 :             VSIFCloseL(fp);
    1369             :         }
    1370         245 :         pabyHeader = abyHeaderLetMeHerePlease;
    1371             :     }
    1372         965 :     else if (poOpenInfo->pabyHeader &&
    1373         965 :              STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1374             :                          "SQLite format 3"))
    1375             :     {
    1376         958 :         m_bCallUndeclareFileNotToOpen = true;
    1377         958 :         GDALOpenInfoDeclareFileNotToOpen(osFilename, poOpenInfo->pabyHeader,
    1378             :                                          poOpenInfo->nHeaderBytes);
    1379             :     }
    1380             : 
    1381        1210 :     eAccess = poOpenInfo->eAccess;
    1382        1210 :     if (!m_osFilenameInZip.empty())
    1383             :     {
    1384           2 :         m_pszFilename = CPLStrdup(CPLSPrintf(
    1385             :             "/vsizip/{%s}/%s", osFilename.c_str(), m_osFilenameInZip.c_str()));
    1386             :     }
    1387             :     else
    1388             :     {
    1389        1208 :         m_pszFilename = CPLStrdup(osFilename);
    1390             :     }
    1391             : 
    1392        1210 :     if (poOpenInfo->papszOpenOptions)
    1393             :     {
    1394         100 :         CSLDestroy(papszOpenOptions);
    1395         100 :         papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
    1396             :     }
    1397             : 
    1398             : #ifdef ENABLE_SQL_GPKG_FORMAT
    1399        1210 :     if (poOpenInfo->pabyHeader &&
    1400         965 :         STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1401           5 :                     "-- SQL GPKG") &&
    1402           5 :         poOpenInfo->fpL != nullptr)
    1403             :     {
    1404           5 :         if (sqlite3_open_v2(":memory:", &hDB, SQLITE_OPEN_READWRITE, nullptr) !=
    1405             :             SQLITE_OK)
    1406             :         {
    1407           0 :             return FALSE;
    1408             :         }
    1409             : 
    1410           5 :         InstallSQLFunctions();
    1411             : 
    1412             :         // Ingest the lines of the dump
    1413           5 :         VSIFSeekL(poOpenInfo->fpL, 0, SEEK_SET);
    1414             :         const char *pszLine;
    1415          76 :         while ((pszLine = CPLReadLineL(poOpenInfo->fpL)) != nullptr)
    1416             :         {
    1417          71 :             if (STARTS_WITH(pszLine, "--"))
    1418           5 :                 continue;
    1419             : 
    1420          66 :             if (!SQLCheckLineIsSafe(pszLine))
    1421           0 :                 return false;
    1422             : 
    1423          66 :             char *pszErrMsg = nullptr;
    1424          66 :             if (sqlite3_exec(hDB, pszLine, nullptr, nullptr, &pszErrMsg) !=
    1425             :                 SQLITE_OK)
    1426             :             {
    1427           0 :                 if (pszErrMsg)
    1428           0 :                     CPLDebug("SQLITE", "Error %s", pszErrMsg);
    1429             :             }
    1430          66 :             sqlite3_free(pszErrMsg);
    1431           5 :         }
    1432             :     }
    1433             : 
    1434        1205 :     else if (pabyHeader != nullptr)
    1435             : #endif
    1436             :     {
    1437        1205 :         if (poOpenInfo->fpL)
    1438             :         {
    1439             :             // See above comment about -wal locking for the importance of
    1440             :             // closing that file, prior to calling sqlite3_open()
    1441         860 :             VSIFCloseL(poOpenInfo->fpL);
    1442         860 :             poOpenInfo->fpL = nullptr;
    1443             :         }
    1444             : 
    1445             :         /* See if we can open the SQLite database */
    1446        1205 :         if (!OpenOrCreateDB(GetUpdate() ? SQLITE_OPEN_READWRITE
    1447             :                                         : SQLITE_OPEN_READONLY))
    1448           2 :             return FALSE;
    1449             : 
    1450        1203 :         memcpy(&m_nApplicationId, pabyHeader + knApplicationIdPos, 4);
    1451        1203 :         m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    1452        1203 :         memcpy(&m_nUserVersion, pabyHeader + knUserVersionPos, 4);
    1453        1203 :         m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    1454        1203 :         if (m_nApplicationId == GP10_APPLICATION_ID)
    1455             :         {
    1456           7 :             CPLDebug("GPKG", "GeoPackage v1.0");
    1457             :         }
    1458        1196 :         else if (m_nApplicationId == GP11_APPLICATION_ID)
    1459             :         {
    1460           2 :             CPLDebug("GPKG", "GeoPackage v1.1");
    1461             :         }
    1462        1194 :         else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    1463        1190 :                  m_nUserVersion >= GPKG_1_2_VERSION)
    1464             :         {
    1465        1188 :             CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    1466        1188 :                      (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    1467             :         }
    1468             :     }
    1469             : 
    1470             :     /* Requirement 6: The SQLite PRAGMA integrity_check SQL command SHALL return
    1471             :      * “ok” */
    1472             :     /* http://opengis.github.io/geopackage/#_file_integrity */
    1473             :     /* Disable integrity check by default, since it is expensive on big files */
    1474        1208 :     if (CPLTestBool(CPLGetConfigOption("OGR_GPKG_INTEGRITY_CHECK", "NO")) &&
    1475           0 :         OGRERR_NONE != PragmaCheck("integrity_check", "ok", 1))
    1476             :     {
    1477           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1478             :                  "pragma integrity_check on '%s' failed", m_pszFilename);
    1479           0 :         return FALSE;
    1480             :     }
    1481             : 
    1482             :     /* Requirement 7: The SQLite PRAGMA foreign_key_check() SQL with no */
    1483             :     /* parameter value SHALL return an empty result set */
    1484             :     /* http://opengis.github.io/geopackage/#_file_integrity */
    1485             :     /* Disable the check by default, since it is to corrupt databases, and */
    1486             :     /* that causes issues to downstream software that can't open them. */
    1487        1208 :     if (CPLTestBool(CPLGetConfigOption("OGR_GPKG_FOREIGN_KEY_CHECK", "NO")) &&
    1488           0 :         OGRERR_NONE != PragmaCheck("foreign_key_check", "", 0))
    1489             :     {
    1490           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1491             :                  "pragma foreign_key_check on '%s' failed.", m_pszFilename);
    1492           0 :         return FALSE;
    1493             :     }
    1494             : 
    1495             :     /* Check for requirement metadata tables */
    1496             :     /* Requirement 10: gpkg_spatial_ref_sys must exist */
    1497             :     /* Requirement 13: gpkg_contents must exist */
    1498        1208 :     if (SQLGetInteger(hDB,
    1499             :                       "SELECT COUNT(*) FROM sqlite_master WHERE "
    1500             :                       "name IN ('gpkg_spatial_ref_sys', 'gpkg_contents') AND "
    1501             :                       "type IN ('table', 'view')",
    1502        1208 :                       nullptr) != 2)
    1503             :     {
    1504           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1505             :                  "At least one of the required GeoPackage tables, "
    1506             :                  "gpkg_spatial_ref_sys or gpkg_contents, is missing");
    1507           0 :         return FALSE;
    1508             :     }
    1509             : 
    1510        1208 :     DetectSpatialRefSysColumns();
    1511             : 
    1512             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    1513        1208 :     if (SQLGetInteger(hDB,
    1514             :                       "SELECT 1 FROM sqlite_master WHERE "
    1515             :                       "name = 'gpkg_ogr_contents' AND type = 'table'",
    1516        1208 :                       nullptr) == 1)
    1517             :     {
    1518        1200 :         m_bHasGPKGOGRContents = true;
    1519             :     }
    1520             : #endif
    1521             : 
    1522        1208 :     CheckUnknownExtensions();
    1523             : 
    1524        1208 :     int bRet = FALSE;
    1525        1208 :     bool bHasGPKGExtRelations = false;
    1526        1208 :     if (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR)
    1527             :     {
    1528        1021 :         m_bHasGPKGGeometryColumns =
    1529        1021 :             SQLGetInteger(hDB,
    1530             :                           "SELECT 1 FROM sqlite_master WHERE "
    1531             :                           "name = 'gpkg_geometry_columns' AND "
    1532             :                           "type IN ('table', 'view')",
    1533        1021 :                           nullptr) == 1;
    1534        1021 :         bHasGPKGExtRelations = HasGpkgextRelationsTable();
    1535             :     }
    1536        1208 :     if (m_bHasGPKGGeometryColumns)
    1537             :     {
    1538             :         /* Load layer definitions for all tables in gpkg_contents &
    1539             :          * gpkg_geometry_columns */
    1540             :         /* and non-spatial tables as well */
    1541             :         std::string osSQL =
    1542             :             "SELECT c.table_name, c.identifier, 1 as is_spatial, "
    1543             :             "g.column_name, g.geometry_type_name, g.z, g.m, c.min_x, c.min_y, "
    1544             :             "c.max_x, c.max_y, 1 AS is_in_gpkg_contents, "
    1545             :             "(SELECT type FROM sqlite_master WHERE lower(name) = "
    1546             :             "lower(c.table_name) AND type IN ('table', 'view')) AS object_type "
    1547             :             "  FROM gpkg_geometry_columns g "
    1548             :             "  JOIN gpkg_contents c ON (g.table_name = c.table_name)"
    1549             :             "  WHERE "
    1550             :             "  c.table_name <> 'ogr_empty_table' AND"
    1551             :             "  c.data_type = 'features' "
    1552             :             // aspatial: Was the only method available in OGR 2.0 and 2.1
    1553             :             // attributes: GPKG 1.2 or later
    1554             :             "UNION ALL "
    1555             :             "SELECT table_name, identifier, 0 as is_spatial, NULL, NULL, 0, 0, "
    1556             :             "0 AS xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 1 AS "
    1557             :             "is_in_gpkg_contents, "
    1558             :             "(SELECT type FROM sqlite_master WHERE lower(name) = "
    1559             :             "lower(table_name) AND type IN ('table', 'view')) AS object_type "
    1560             :             "  FROM gpkg_contents"
    1561        1020 :             "  WHERE data_type IN ('aspatial', 'attributes') ";
    1562             : 
    1563        2040 :         const char *pszListAllTables = CSLFetchNameValueDef(
    1564        1020 :             poOpenInfo->papszOpenOptions, "LIST_ALL_TABLES", "AUTO");
    1565        1020 :         bool bHasASpatialOrAttributes = HasGDALAspatialExtension();
    1566        1020 :         if (!bHasASpatialOrAttributes)
    1567             :         {
    1568             :             auto oResultTable =
    1569             :                 SQLQuery(hDB, "SELECT * FROM gpkg_contents WHERE "
    1570        1019 :                               "data_type = 'attributes' LIMIT 1");
    1571        1019 :             bHasASpatialOrAttributes =
    1572        1019 :                 (oResultTable && oResultTable->RowCount() == 1);
    1573             :         }
    1574        1020 :         if (bHasGPKGExtRelations)
    1575             :         {
    1576             :             osSQL += "UNION ALL "
    1577             :                      "SELECT mapping_table_name, mapping_table_name, 0 as "
    1578             :                      "is_spatial, NULL, NULL, 0, 0, 0 AS "
    1579             :                      "xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 0 AS "
    1580             :                      "is_in_gpkg_contents, 'table' AS object_type "
    1581             :                      "FROM gpkgext_relations WHERE "
    1582             :                      "lower(mapping_table_name) NOT IN (SELECT "
    1583             :                      "lower(table_name) FROM gpkg_contents) AND "
    1584             :                      "EXISTS (SELECT 1 FROM sqlite_master WHERE "
    1585             :                      "type IN ('table', 'view') AND "
    1586          18 :                      "lower(name) = lower(mapping_table_name))";
    1587             :         }
    1588        1020 :         if (EQUAL(pszListAllTables, "YES") ||
    1589        1019 :             (!bHasASpatialOrAttributes && EQUAL(pszListAllTables, "AUTO")))
    1590             :         {
    1591             :             // vgpkg_ is Spatialite virtual table
    1592             :             osSQL +=
    1593             :                 "UNION ALL "
    1594             :                 "SELECT name, name, 0 as is_spatial, NULL, NULL, 0, 0, 0 AS "
    1595             :                 "xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 0 AS "
    1596             :                 "is_in_gpkg_contents, type AS object_type "
    1597             :                 "FROM sqlite_master WHERE type IN ('table', 'view') "
    1598             :                 "AND name NOT LIKE 'gpkg_%' "
    1599             :                 "AND name NOT LIKE 'vgpkg_%' "
    1600             :                 "AND name NOT LIKE 'rtree_%' AND name NOT LIKE 'sqlite_%' "
    1601             :                 // Avoid reading those views from simple_sewer_features.gpkg
    1602             :                 "AND name NOT IN ('st_spatial_ref_sys', 'spatial_ref_sys', "
    1603             :                 "'st_geometry_columns', 'geometry_columns') "
    1604             :                 "AND lower(name) NOT IN (SELECT lower(table_name) FROM "
    1605         961 :                 "gpkg_contents)";
    1606         961 :             if (bHasGPKGExtRelations)
    1607             :             {
    1608             :                 osSQL += " AND lower(name) NOT IN (SELECT "
    1609             :                          "lower(mapping_table_name) FROM "
    1610          13 :                          "gpkgext_relations)";
    1611             :             }
    1612             :         }
    1613        1020 :         const int nTableLimit = GetOGRTableLimit();
    1614        1020 :         if (nTableLimit > 0)
    1615             :         {
    1616        1020 :             osSQL += " LIMIT ";
    1617        1020 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1618             :         }
    1619             : 
    1620        1020 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1621        1020 :         if (!oResult)
    1622             :         {
    1623           0 :             return FALSE;
    1624             :         }
    1625             : 
    1626        1020 :         if (nTableLimit > 0 && oResult->RowCount() > nTableLimit)
    1627             :         {
    1628           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    1629             :                      "File has more than %d vector tables. "
    1630             :                      "Limiting to first %d (can be overridden with "
    1631             :                      "OGR_TABLE_LIMIT config option)",
    1632             :                      nTableLimit, nTableLimit);
    1633           1 :             oResult->LimitRowCount(nTableLimit);
    1634             :         }
    1635             : 
    1636        1020 :         if (oResult->RowCount() > 0)
    1637             :         {
    1638         904 :             bRet = TRUE;
    1639             : 
    1640         904 :             m_apoLayers.reserve(oResult->RowCount());
    1641             : 
    1642        1808 :             std::map<std::string, int> oMapTableRefCount;
    1643        4004 :             for (int i = 0; i < oResult->RowCount(); i++)
    1644             :             {
    1645        3100 :                 const char *pszTableName = oResult->GetValue(0, i);
    1646        3100 :                 if (pszTableName == nullptr)
    1647           0 :                     continue;
    1648        3100 :                 if (++oMapTableRefCount[pszTableName] == 2)
    1649             :                 {
    1650             :                     // This should normally not happen if all constraints are
    1651             :                     // properly set
    1652           2 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1653             :                              "Table %s appearing several times in "
    1654             :                              "gpkg_contents and/or gpkg_geometry_columns",
    1655             :                              pszTableName);
    1656             :                 }
    1657             :             }
    1658             : 
    1659        1808 :             std::set<std::string> oExistingLayers;
    1660        4004 :             for (int i = 0; i < oResult->RowCount(); i++)
    1661             :             {
    1662        3100 :                 const char *pszTableName = oResult->GetValue(0, i);
    1663        3100 :                 if (pszTableName == nullptr)
    1664           2 :                     continue;
    1665             :                 const bool bTableHasSeveralGeomColumns =
    1666        3100 :                     oMapTableRefCount[pszTableName] > 1;
    1667        3100 :                 bool bIsSpatial = CPL_TO_BOOL(oResult->GetValueAsInteger(2, i));
    1668        3100 :                 const char *pszGeomColName = oResult->GetValue(3, i);
    1669        3100 :                 const char *pszGeomType = oResult->GetValue(4, i);
    1670        3100 :                 const char *pszZ = oResult->GetValue(5, i);
    1671        3100 :                 const char *pszM = oResult->GetValue(6, i);
    1672             :                 bool bIsInGpkgContents =
    1673        3100 :                     CPL_TO_BOOL(oResult->GetValueAsInteger(11, i));
    1674        3100 :                 if (!bIsInGpkgContents)
    1675          44 :                     m_bNonSpatialTablesNonRegisteredInGpkgContentsFound = true;
    1676        3100 :                 const char *pszObjectType = oResult->GetValue(12, i);
    1677        3100 :                 if (pszObjectType == nullptr ||
    1678        3099 :                     !(EQUAL(pszObjectType, "table") ||
    1679          21 :                       EQUAL(pszObjectType, "view")))
    1680             :                 {
    1681           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1682             :                              "Table/view %s is referenced in gpkg_contents, "
    1683             :                              "but does not exist",
    1684             :                              pszTableName);
    1685           1 :                     continue;
    1686             :                 }
    1687             :                 // Non-standard and undocumented behavior:
    1688             :                 // if the same table appears to have several geometry columns,
    1689             :                 // handle it for now as multiple layers named
    1690             :                 // "table_name (geom_col_name)"
    1691             :                 // The way we handle that might change in the future (e.g
    1692             :                 // could be a single layer with multiple geometry columns)
    1693             :                 std::string osLayerNameWithGeomColName =
    1694        6078 :                     pszGeomColName ? std::string(pszTableName) + " (" +
    1695             :                                          pszGeomColName + ')'
    1696        6198 :                                    : std::string(pszTableName);
    1697        3099 :                 if (cpl::contains(oExistingLayers, osLayerNameWithGeomColName))
    1698           1 :                     continue;
    1699        3098 :                 oExistingLayers.insert(osLayerNameWithGeomColName);
    1700             :                 const std::string osLayerName =
    1701             :                     bTableHasSeveralGeomColumns
    1702           3 :                         ? std::move(osLayerNameWithGeomColName)
    1703        6199 :                         : std::string(pszTableName);
    1704             :                 auto poLayer = std::make_unique<OGRGeoPackageTableLayer>(
    1705        6196 :                     this, osLayerName.c_str());
    1706        3098 :                 bool bHasZ = pszZ && atoi(pszZ) > 0;
    1707        3098 :                 bool bHasM = pszM && atoi(pszM) > 0;
    1708        3098 :                 if (pszGeomType && EQUAL(pszGeomType, "GEOMETRY"))
    1709             :                 {
    1710         615 :                     if (pszZ && atoi(pszZ) == 2)
    1711           7 :                         bHasZ = false;
    1712         615 :                     if (pszM && atoi(pszM) == 2)
    1713           6 :                         bHasM = false;
    1714             :                 }
    1715        3098 :                 poLayer->SetOpeningParameters(
    1716             :                     pszTableName, pszObjectType, bIsInGpkgContents, bIsSpatial,
    1717             :                     pszGeomColName, pszGeomType, bHasZ, bHasM);
    1718        3098 :                 m_apoLayers.push_back(std::move(poLayer));
    1719             :             }
    1720             :         }
    1721             :     }
    1722             : 
    1723        1208 :     bool bHasTileMatrixSet = false;
    1724        1208 :     if (poOpenInfo->nOpenFlags & GDAL_OF_RASTER)
    1725             :     {
    1726         570 :         bHasTileMatrixSet = SQLGetInteger(hDB,
    1727             :                                           "SELECT 1 FROM sqlite_master WHERE "
    1728             :                                           "name = 'gpkg_tile_matrix_set' AND "
    1729             :                                           "type IN ('table', 'view')",
    1730             :                                           nullptr) == 1;
    1731             :     }
    1732        1208 :     if (bHasTileMatrixSet)
    1733             :     {
    1734             :         std::string osSQL =
    1735             :             "SELECT c.table_name, c.identifier, c.description, c.srs_id, "
    1736             :             "c.min_x, c.min_y, c.max_x, c.max_y, "
    1737             :             "tms.min_x, tms.min_y, tms.max_x, tms.max_y, c.data_type "
    1738             :             "FROM gpkg_contents c JOIN gpkg_tile_matrix_set tms ON "
    1739             :             "c.table_name = tms.table_name WHERE "
    1740         568 :             "data_type IN ('tiles', '2d-gridded-coverage')";
    1741         568 :         if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE"))
    1742             :             osSubdatasetTableName =
    1743           2 :                 CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE");
    1744         568 :         if (!osSubdatasetTableName.empty())
    1745             :         {
    1746          16 :             char *pszTmp = sqlite3_mprintf(" AND c.table_name='%q'",
    1747             :                                            osSubdatasetTableName.c_str());
    1748          16 :             osSQL += pszTmp;
    1749          16 :             sqlite3_free(pszTmp);
    1750          16 :             SetPhysicalFilename(osFilename.c_str());
    1751             :         }
    1752         568 :         const int nTableLimit = GetOGRTableLimit();
    1753         568 :         if (nTableLimit > 0)
    1754             :         {
    1755         568 :             osSQL += " LIMIT ";
    1756         568 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1757             :         }
    1758             : 
    1759         568 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1760         568 :         if (!oResult)
    1761             :         {
    1762           0 :             return FALSE;
    1763             :         }
    1764             : 
    1765         568 :         if (oResult->RowCount() == 0 && !osSubdatasetTableName.empty())
    1766             :         {
    1767           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1768             :                      "Cannot find table '%s' in GeoPackage dataset",
    1769             :                      osSubdatasetTableName.c_str());
    1770             :         }
    1771         567 :         else if (oResult->RowCount() == 1)
    1772             :         {
    1773         274 :             const char *pszTableName = oResult->GetValue(0, 0);
    1774         274 :             const char *pszIdentifier = oResult->GetValue(1, 0);
    1775         274 :             const char *pszDescription = oResult->GetValue(2, 0);
    1776         274 :             const char *pszSRSId = oResult->GetValue(3, 0);
    1777         274 :             const char *pszMinX = oResult->GetValue(4, 0);
    1778         274 :             const char *pszMinY = oResult->GetValue(5, 0);
    1779         274 :             const char *pszMaxX = oResult->GetValue(6, 0);
    1780         274 :             const char *pszMaxY = oResult->GetValue(7, 0);
    1781         274 :             const char *pszTMSMinX = oResult->GetValue(8, 0);
    1782         274 :             const char *pszTMSMinY = oResult->GetValue(9, 0);
    1783         274 :             const char *pszTMSMaxX = oResult->GetValue(10, 0);
    1784         274 :             const char *pszTMSMaxY = oResult->GetValue(11, 0);
    1785         274 :             const char *pszDataType = oResult->GetValue(12, 0);
    1786         274 :             if (pszTableName && pszTMSMinX && pszTMSMinY && pszTMSMaxX &&
    1787             :                 pszTMSMaxY)
    1788             :             {
    1789         548 :                 bRet = OpenRaster(
    1790             :                     pszTableName, pszIdentifier, pszDescription,
    1791         274 :                     pszSRSId ? atoi(pszSRSId) : 0, CPLAtof(pszTMSMinX),
    1792             :                     CPLAtof(pszTMSMinY), CPLAtof(pszTMSMaxX),
    1793             :                     CPLAtof(pszTMSMaxY), pszMinX, pszMinY, pszMaxX, pszMaxY,
    1794         274 :                     EQUAL(pszDataType, "tiles"), poOpenInfo->papszOpenOptions);
    1795             :             }
    1796             :         }
    1797         293 :         else if (oResult->RowCount() >= 1)
    1798             :         {
    1799           5 :             bRet = TRUE;
    1800             : 
    1801           5 :             if (nTableLimit > 0 && oResult->RowCount() > nTableLimit)
    1802             :             {
    1803           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1804             :                          "File has more than %d raster tables. "
    1805             :                          "Limiting to first %d (can be overridden with "
    1806             :                          "OGR_TABLE_LIMIT config option)",
    1807             :                          nTableLimit, nTableLimit);
    1808           1 :                 oResult->LimitRowCount(nTableLimit);
    1809             :             }
    1810             : 
    1811           5 :             int nSDSCount = 0;
    1812        2013 :             for (int i = 0; i < oResult->RowCount(); i++)
    1813             :             {
    1814        2008 :                 const char *pszTableName = oResult->GetValue(0, i);
    1815        2008 :                 const char *pszIdentifier = oResult->GetValue(1, i);
    1816        2008 :                 if (pszTableName == nullptr)
    1817           0 :                     continue;
    1818             :                 m_aosSubDatasets.AddNameValue(
    1819             :                     CPLSPrintf("SUBDATASET_%d_NAME", nSDSCount + 1),
    1820        2008 :                     CPLSPrintf("GPKG:%s:%s", m_pszFilename, pszTableName));
    1821             :                 m_aosSubDatasets.AddNameValue(
    1822             :                     CPLSPrintf("SUBDATASET_%d_DESC", nSDSCount + 1),
    1823             :                     pszIdentifier
    1824        2008 :                         ? CPLSPrintf("%s - %s", pszTableName, pszIdentifier)
    1825        4016 :                         : pszTableName);
    1826        2008 :                 nSDSCount++;
    1827             :             }
    1828             :         }
    1829             :     }
    1830             : 
    1831        1208 :     if (!bRet && (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR))
    1832             :     {
    1833          32 :         if ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE))
    1834             :         {
    1835          21 :             bRet = TRUE;
    1836             :         }
    1837             :         else
    1838             :         {
    1839          11 :             CPLDebug("GPKG",
    1840             :                      "This GeoPackage has no vector content and is opened "
    1841             :                      "in read-only mode. If you open it in update mode, "
    1842             :                      "opening will be successful.");
    1843             :         }
    1844             :     }
    1845             : 
    1846        1208 :     if (eAccess == GA_Update)
    1847             :     {
    1848         246 :         FixupWrongRTreeTrigger();
    1849         246 :         FixupWrongMedataReferenceColumnNameUpdate();
    1850             :     }
    1851             : 
    1852        1208 :     SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    1853             : 
    1854        1208 :     return bRet;
    1855             : }
    1856             : 
    1857             : /************************************************************************/
    1858             : /*                    DetectSpatialRefSysColumns()                      */
    1859             : /************************************************************************/
    1860             : 
    1861        1218 : void GDALGeoPackageDataset::DetectSpatialRefSysColumns()
    1862             : {
    1863             :     // Detect definition_12_063 column
    1864             :     {
    1865        1218 :         sqlite3_stmt *hSQLStmt = nullptr;
    1866        1218 :         int rc = sqlite3_prepare_v2(
    1867             :             hDB, "SELECT definition_12_063 FROM gpkg_spatial_ref_sys ", -1,
    1868             :             &hSQLStmt, nullptr);
    1869        1218 :         if (rc == SQLITE_OK)
    1870             :         {
    1871          85 :             m_bHasDefinition12_063 = true;
    1872          85 :             sqlite3_finalize(hSQLStmt);
    1873             :         }
    1874             :     }
    1875             : 
    1876             :     // Detect epoch column
    1877        1218 :     if (m_bHasDefinition12_063)
    1878             :     {
    1879          85 :         sqlite3_stmt *hSQLStmt = nullptr;
    1880             :         int rc =
    1881          85 :             sqlite3_prepare_v2(hDB, "SELECT epoch FROM gpkg_spatial_ref_sys ",
    1882             :                                -1, &hSQLStmt, nullptr);
    1883          85 :         if (rc == SQLITE_OK)
    1884             :         {
    1885          76 :             m_bHasEpochColumn = true;
    1886          76 :             sqlite3_finalize(hSQLStmt);
    1887             :         }
    1888             :     }
    1889        1218 : }
    1890             : 
    1891             : /************************************************************************/
    1892             : /*                    FixupWrongRTreeTrigger()                          */
    1893             : /************************************************************************/
    1894             : 
    1895         246 : void GDALGeoPackageDataset::FixupWrongRTreeTrigger()
    1896             : {
    1897             :     auto oResult = SQLQuery(
    1898             :         hDB,
    1899             :         "SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND "
    1900         246 :         "NAME LIKE 'rtree_%_update3' AND sql LIKE '% AFTER UPDATE OF % ON %'");
    1901         246 :     if (oResult == nullptr)
    1902           0 :         return;
    1903         246 :     if (oResult->RowCount() > 0)
    1904             :     {
    1905           1 :         CPLDebug("GPKG", "Fixing incorrect trigger(s) related to RTree");
    1906             :     }
    1907         248 :     for (int i = 0; i < oResult->RowCount(); i++)
    1908             :     {
    1909           2 :         const char *pszName = oResult->GetValue(0, i);
    1910           2 :         const char *pszSQL = oResult->GetValue(1, i);
    1911           2 :         const char *pszPtr1 = strstr(pszSQL, " AFTER UPDATE OF ");
    1912           2 :         if (pszPtr1)
    1913             :         {
    1914           2 :             const char *pszPtr = pszPtr1 + strlen(" AFTER UPDATE OF ");
    1915             :             // Skipping over geometry column name
    1916           4 :             while (*pszPtr == ' ')
    1917           2 :                 pszPtr++;
    1918           2 :             if (pszPtr[0] == '"' || pszPtr[0] == '\'')
    1919             :             {
    1920           1 :                 char chStringDelim = pszPtr[0];
    1921           1 :                 pszPtr++;
    1922           9 :                 while (*pszPtr != '\0' && *pszPtr != chStringDelim)
    1923             :                 {
    1924           8 :                     if (*pszPtr == '\\' && pszPtr[1] == chStringDelim)
    1925           0 :                         pszPtr += 2;
    1926             :                     else
    1927           8 :                         pszPtr += 1;
    1928             :                 }
    1929           1 :                 if (*pszPtr == chStringDelim)
    1930           1 :                     pszPtr++;
    1931             :             }
    1932             :             else
    1933             :             {
    1934           1 :                 pszPtr++;
    1935           8 :                 while (*pszPtr != ' ')
    1936           7 :                     pszPtr++;
    1937             :             }
    1938           2 :             if (*pszPtr == ' ')
    1939             :             {
    1940           2 :                 SQLCommand(hDB,
    1941           4 :                            ("DROP TRIGGER \"" + SQLEscapeName(pszName) + "\"")
    1942             :                                .c_str());
    1943           4 :                 CPLString newSQL;
    1944           2 :                 newSQL.assign(pszSQL, pszPtr1 - pszSQL);
    1945           2 :                 newSQL += " AFTER UPDATE";
    1946           2 :                 newSQL += pszPtr;
    1947           2 :                 SQLCommand(hDB, newSQL);
    1948             :             }
    1949             :         }
    1950             :     }
    1951             : }
    1952             : 
    1953             : /************************************************************************/
    1954             : /*             FixupWrongMedataReferenceColumnNameUpdate()              */
    1955             : /************************************************************************/
    1956             : 
    1957         246 : void GDALGeoPackageDataset::FixupWrongMedataReferenceColumnNameUpdate()
    1958             : {
    1959             :     // Fix wrong trigger that was generated by GDAL < 2.4.0
    1960             :     // See https://github.com/qgis/QGIS/issues/42768
    1961             :     auto oResult = SQLQuery(
    1962             :         hDB, "SELECT sql FROM sqlite_master WHERE type = 'trigger' AND "
    1963             :              "NAME ='gpkg_metadata_reference_column_name_update' AND "
    1964         246 :              "sql LIKE '%column_nameIS%'");
    1965         246 :     if (oResult == nullptr)
    1966           0 :         return;
    1967         246 :     if (oResult->RowCount() == 1)
    1968             :     {
    1969           1 :         CPLDebug("GPKG", "Fixing incorrect trigger "
    1970             :                          "gpkg_metadata_reference_column_name_update");
    1971           1 :         const char *pszSQL = oResult->GetValue(0, 0);
    1972             :         std::string osNewSQL(
    1973           3 :             CPLString(pszSQL).replaceAll("column_nameIS", "column_name IS"));
    1974             : 
    1975           1 :         SQLCommand(hDB,
    1976             :                    "DROP TRIGGER gpkg_metadata_reference_column_name_update");
    1977           1 :         SQLCommand(hDB, osNewSQL.c_str());
    1978             :     }
    1979             : }
    1980             : 
    1981             : /************************************************************************/
    1982             : /*                  ClearCachedRelationships()                          */
    1983             : /************************************************************************/
    1984             : 
    1985          36 : void GDALGeoPackageDataset::ClearCachedRelationships()
    1986             : {
    1987          36 :     m_bHasPopulatedRelationships = false;
    1988          36 :     m_osMapRelationships.clear();
    1989          36 : }
    1990             : 
    1991             : /************************************************************************/
    1992             : /*                           LoadRelationships()                        */
    1993             : /************************************************************************/
    1994             : 
    1995          83 : void GDALGeoPackageDataset::LoadRelationships() const
    1996             : {
    1997          83 :     m_osMapRelationships.clear();
    1998             : 
    1999          83 :     std::vector<std::string> oExcludedTables;
    2000          83 :     if (HasGpkgextRelationsTable())
    2001             :     {
    2002          37 :         LoadRelationshipsUsingRelatedTablesExtension();
    2003             : 
    2004          89 :         for (const auto &oRelationship : m_osMapRelationships)
    2005             :         {
    2006             :             oExcludedTables.emplace_back(
    2007          52 :                 oRelationship.second->GetMappingTableName());
    2008             :         }
    2009             :     }
    2010             : 
    2011             :     // Also load relationships defined using foreign keys (i.e. one-to-many
    2012             :     // relationships). Here we must exclude any relationships defined from the
    2013             :     // related tables extension, we don't want them included twice.
    2014          83 :     LoadRelationshipsFromForeignKeys(oExcludedTables);
    2015          83 :     m_bHasPopulatedRelationships = true;
    2016          83 : }
    2017             : 
    2018             : /************************************************************************/
    2019             : /*         LoadRelationshipsUsingRelatedTablesExtension()               */
    2020             : /************************************************************************/
    2021             : 
    2022          37 : void GDALGeoPackageDataset::LoadRelationshipsUsingRelatedTablesExtension() const
    2023             : {
    2024          37 :     m_osMapRelationships.clear();
    2025             : 
    2026             :     auto oResultTable = SQLQuery(
    2027          37 :         hDB, "SELECT base_table_name, base_primary_column, "
    2028             :              "related_table_name, related_primary_column, relation_name, "
    2029          74 :              "mapping_table_name FROM gpkgext_relations");
    2030          37 :     if (oResultTable && oResultTable->RowCount() > 0)
    2031             :     {
    2032          86 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    2033             :         {
    2034          53 :             const char *pszBaseTableName = oResultTable->GetValue(0, i);
    2035          53 :             if (!pszBaseTableName)
    2036             :             {
    2037           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2038             :                          "Could not retrieve base_table_name from "
    2039             :                          "gpkgext_relations");
    2040           1 :                 continue;
    2041             :             }
    2042          53 :             const char *pszBasePrimaryColumn = oResultTable->GetValue(1, i);
    2043          53 :             if (!pszBasePrimaryColumn)
    2044             :             {
    2045           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2046             :                          "Could not retrieve base_primary_column from "
    2047             :                          "gpkgext_relations");
    2048           0 :                 continue;
    2049             :             }
    2050          53 :             const char *pszRelatedTableName = oResultTable->GetValue(2, i);
    2051          53 :             if (!pszRelatedTableName)
    2052             :             {
    2053           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2054             :                          "Could not retrieve related_table_name from "
    2055             :                          "gpkgext_relations");
    2056           0 :                 continue;
    2057             :             }
    2058          53 :             const char *pszRelatedPrimaryColumn = oResultTable->GetValue(3, i);
    2059          53 :             if (!pszRelatedPrimaryColumn)
    2060             :             {
    2061           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2062             :                          "Could not retrieve related_primary_column from "
    2063             :                          "gpkgext_relations");
    2064           0 :                 continue;
    2065             :             }
    2066          53 :             const char *pszRelationName = oResultTable->GetValue(4, i);
    2067          53 :             if (!pszRelationName)
    2068             :             {
    2069           0 :                 CPLError(
    2070             :                     CE_Warning, CPLE_AppDefined,
    2071             :                     "Could not retrieve relation_name from gpkgext_relations");
    2072           0 :                 continue;
    2073             :             }
    2074          53 :             const char *pszMappingTableName = oResultTable->GetValue(5, i);
    2075          53 :             if (!pszMappingTableName)
    2076             :             {
    2077           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2078             :                          "Could not retrieve mapping_table_name from "
    2079             :                          "gpkgext_relations");
    2080           0 :                 continue;
    2081             :             }
    2082             : 
    2083             :             // confirm that mapping table exists
    2084             :             char *pszSQL =
    2085          53 :                 sqlite3_mprintf("SELECT 1 FROM sqlite_master WHERE "
    2086             :                                 "name='%q' AND type IN ('table', 'view')",
    2087             :                                 pszMappingTableName);
    2088          53 :             const int nMappingTableCount = SQLGetInteger(hDB, pszSQL, nullptr);
    2089          53 :             sqlite3_free(pszSQL);
    2090             : 
    2091          55 :             if (nMappingTableCount < 1 &&
    2092           2 :                 !const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    2093           2 :                     pszMappingTableName))
    2094             :             {
    2095           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2096             :                          "Relationship mapping table %s does not exist",
    2097             :                          pszMappingTableName);
    2098           1 :                 continue;
    2099             :             }
    2100             : 
    2101             :             const std::string osRelationName = GenerateNameForRelationship(
    2102         104 :                 pszBaseTableName, pszRelatedTableName, pszRelationName);
    2103             : 
    2104         104 :             std::string osType{};
    2105             :             // defined requirement classes -- for these types the relation name
    2106             :             // will be specific string value from the related tables extension.
    2107             :             // In this case we need to construct a unique relationship name
    2108             :             // based on the related tables
    2109          52 :             if (EQUAL(pszRelationName, "media") ||
    2110          40 :                 EQUAL(pszRelationName, "simple_attributes") ||
    2111          40 :                 EQUAL(pszRelationName, "features") ||
    2112          18 :                 EQUAL(pszRelationName, "attributes") ||
    2113           2 :                 EQUAL(pszRelationName, "tiles"))
    2114             :             {
    2115          50 :                 osType = pszRelationName;
    2116             :             }
    2117             :             else
    2118             :             {
    2119             :                 // user defined types default to features
    2120           2 :                 osType = "features";
    2121             :             }
    2122             : 
    2123             :             auto poRelationship = std::make_unique<GDALRelationship>(
    2124             :                 osRelationName, pszBaseTableName, pszRelatedTableName,
    2125         104 :                 GRC_MANY_TO_MANY);
    2126             : 
    2127         104 :             poRelationship->SetLeftTableFields({pszBasePrimaryColumn});
    2128         104 :             poRelationship->SetRightTableFields({pszRelatedPrimaryColumn});
    2129         104 :             poRelationship->SetLeftMappingTableFields({"base_id"});
    2130         104 :             poRelationship->SetRightMappingTableFields({"related_id"});
    2131          52 :             poRelationship->SetMappingTableName(pszMappingTableName);
    2132          52 :             poRelationship->SetRelatedTableType(osType);
    2133             : 
    2134          52 :             m_osMapRelationships[osRelationName] = std::move(poRelationship);
    2135             :         }
    2136             :     }
    2137          37 : }
    2138             : 
    2139             : /************************************************************************/
    2140             : /*                GenerateNameForRelationship()                         */
    2141             : /************************************************************************/
    2142             : 
    2143          76 : std::string GDALGeoPackageDataset::GenerateNameForRelationship(
    2144             :     const char *pszBaseTableName, const char *pszRelatedTableName,
    2145             :     const char *pszType)
    2146             : {
    2147             :     // defined requirement classes -- for these types the relation name will be
    2148             :     // specific string value from the related tables extension. In this case we
    2149             :     // need to construct a unique relationship name based on the related tables
    2150          76 :     if (EQUAL(pszType, "media") || EQUAL(pszType, "simple_attributes") ||
    2151          53 :         EQUAL(pszType, "features") || EQUAL(pszType, "attributes") ||
    2152           8 :         EQUAL(pszType, "tiles"))
    2153             :     {
    2154         136 :         std::ostringstream stream;
    2155             :         stream << pszBaseTableName << '_' << pszRelatedTableName << '_'
    2156          68 :                << pszType;
    2157          68 :         return stream.str();
    2158             :     }
    2159             :     else
    2160             :     {
    2161             :         // user defined types default to features
    2162           8 :         return pszType;
    2163             :     }
    2164             : }
    2165             : 
    2166             : /************************************************************************/
    2167             : /*                       ValidateRelationship()                         */
    2168             : /************************************************************************/
    2169             : 
    2170          28 : bool GDALGeoPackageDataset::ValidateRelationship(
    2171             :     const GDALRelationship *poRelationship, std::string &failureReason)
    2172             : {
    2173             : 
    2174          28 :     if (poRelationship->GetCardinality() !=
    2175             :         GDALRelationshipCardinality::GRC_MANY_TO_MANY)
    2176             :     {
    2177           3 :         failureReason = "Only many to many relationships are supported";
    2178           3 :         return false;
    2179             :     }
    2180             : 
    2181          50 :     std::string osRelatedTableType = poRelationship->GetRelatedTableType();
    2182          65 :     if (!osRelatedTableType.empty() && osRelatedTableType != "features" &&
    2183          30 :         osRelatedTableType != "media" &&
    2184          20 :         osRelatedTableType != "simple_attributes" &&
    2185          55 :         osRelatedTableType != "attributes" && osRelatedTableType != "tiles")
    2186             :     {
    2187             :         failureReason =
    2188           4 :             ("Related table type " + osRelatedTableType +
    2189             :              " is not a valid value for the GeoPackage specification. "
    2190             :              "Valid values are: features, media, simple_attributes, "
    2191             :              "attributes, tiles.")
    2192           2 :                 .c_str();
    2193           2 :         return false;
    2194             :     }
    2195             : 
    2196          23 :     const std::string &osLeftTableName = poRelationship->GetLeftTableName();
    2197          23 :     OGRGeoPackageLayer *poLeftTable = cpl::down_cast<OGRGeoPackageLayer *>(
    2198          23 :         GetLayerByName(osLeftTableName.c_str()));
    2199          23 :     if (!poLeftTable)
    2200             :     {
    2201           4 :         failureReason = ("Left table " + osLeftTableName +
    2202             :                          " is not an existing layer in the dataset")
    2203           2 :                             .c_str();
    2204           2 :         return false;
    2205             :     }
    2206          21 :     const std::string &osRightTableName = poRelationship->GetRightTableName();
    2207          21 :     OGRGeoPackageLayer *poRightTable = cpl::down_cast<OGRGeoPackageLayer *>(
    2208          21 :         GetLayerByName(osRightTableName.c_str()));
    2209          21 :     if (!poRightTable)
    2210             :     {
    2211           4 :         failureReason = ("Right table " + osRightTableName +
    2212             :                          " is not an existing layer in the dataset")
    2213           2 :                             .c_str();
    2214           2 :         return false;
    2215             :     }
    2216             : 
    2217          19 :     const auto &aosLeftTableFields = poRelationship->GetLeftTableFields();
    2218          19 :     if (aosLeftTableFields.empty())
    2219             :     {
    2220           1 :         failureReason = "No left table fields were specified";
    2221           1 :         return false;
    2222             :     }
    2223          18 :     else if (aosLeftTableFields.size() > 1)
    2224             :     {
    2225             :         failureReason = "Only a single left table field is permitted for the "
    2226           1 :                         "GeoPackage specification";
    2227           1 :         return false;
    2228             :     }
    2229             :     else
    2230             :     {
    2231             :         // validate left field exists
    2232          34 :         if (poLeftTable->GetLayerDefn()->GetFieldIndex(
    2233          37 :                 aosLeftTableFields[0].c_str()) < 0 &&
    2234           3 :             !EQUAL(poLeftTable->GetFIDColumn(), aosLeftTableFields[0].c_str()))
    2235             :         {
    2236           2 :             failureReason = ("Left table field " + aosLeftTableFields[0] +
    2237           2 :                              " does not exist in " + osLeftTableName)
    2238           1 :                                 .c_str();
    2239           1 :             return false;
    2240             :         }
    2241             :     }
    2242             : 
    2243          16 :     const auto &aosRightTableFields = poRelationship->GetRightTableFields();
    2244          16 :     if (aosRightTableFields.empty())
    2245             :     {
    2246           1 :         failureReason = "No right table fields were specified";
    2247           1 :         return false;
    2248             :     }
    2249          15 :     else if (aosRightTableFields.size() > 1)
    2250             :     {
    2251             :         failureReason = "Only a single right table field is permitted for the "
    2252           1 :                         "GeoPackage specification";
    2253           1 :         return false;
    2254             :     }
    2255             :     else
    2256             :     {
    2257             :         // validate right field exists
    2258          28 :         if (poRightTable->GetLayerDefn()->GetFieldIndex(
    2259          32 :                 aosRightTableFields[0].c_str()) < 0 &&
    2260           4 :             !EQUAL(poRightTable->GetFIDColumn(),
    2261             :                    aosRightTableFields[0].c_str()))
    2262             :         {
    2263           4 :             failureReason = ("Right table field " + aosRightTableFields[0] +
    2264           4 :                              " does not exist in " + osRightTableName)
    2265           2 :                                 .c_str();
    2266           2 :             return false;
    2267             :         }
    2268             :     }
    2269             : 
    2270          12 :     return true;
    2271             : }
    2272             : 
    2273             : /************************************************************************/
    2274             : /*                         InitRaster()                                 */
    2275             : /************************************************************************/
    2276             : 
    2277         358 : bool GDALGeoPackageDataset::InitRaster(
    2278             :     GDALGeoPackageDataset *poParentDS, const char *pszTableName, double dfMinX,
    2279             :     double dfMinY, double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2280             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2281             :     const char *pszContentsMaxY, char **papszOpenOptionsIn,
    2282             :     const SQLResult &oResult, int nIdxInResult)
    2283             : {
    2284         358 :     m_osRasterTable = pszTableName;
    2285         358 :     m_dfTMSMinX = dfMinX;
    2286         358 :     m_dfTMSMaxY = dfMaxY;
    2287             : 
    2288             :     // Despite prior checking, the type might be Binary and
    2289             :     // SQLResultGetValue() not working properly on it
    2290         358 :     int nZoomLevel = atoi(oResult.GetValue(0, nIdxInResult));
    2291         358 :     if (nZoomLevel < 0 || nZoomLevel > 65536)
    2292             :     {
    2293           0 :         return false;
    2294             :     }
    2295         358 :     double dfPixelXSize = CPLAtof(oResult.GetValue(1, nIdxInResult));
    2296         358 :     double dfPixelYSize = CPLAtof(oResult.GetValue(2, nIdxInResult));
    2297         358 :     if (dfPixelXSize <= 0 || dfPixelYSize <= 0)
    2298             :     {
    2299           0 :         return false;
    2300             :     }
    2301         358 :     int nTileWidth = atoi(oResult.GetValue(3, nIdxInResult));
    2302         358 :     int nTileHeight = atoi(oResult.GetValue(4, nIdxInResult));
    2303         358 :     if (nTileWidth <= 0 || nTileWidth > 65536 || nTileHeight <= 0 ||
    2304             :         nTileHeight > 65536)
    2305             :     {
    2306           0 :         return false;
    2307             :     }
    2308             :     int nTileMatrixWidth = static_cast<int>(
    2309         716 :         std::min(static_cast<GIntBig>(INT_MAX),
    2310         358 :                  CPLAtoGIntBig(oResult.GetValue(5, nIdxInResult))));
    2311             :     int nTileMatrixHeight = static_cast<int>(
    2312         716 :         std::min(static_cast<GIntBig>(INT_MAX),
    2313         358 :                  CPLAtoGIntBig(oResult.GetValue(6, nIdxInResult))));
    2314         358 :     if (nTileMatrixWidth <= 0 || nTileMatrixHeight <= 0)
    2315             :     {
    2316           0 :         return false;
    2317             :     }
    2318             : 
    2319             :     /* Use content bounds in priority over tile_matrix_set bounds */
    2320         358 :     double dfGDALMinX = dfMinX;
    2321         358 :     double dfGDALMinY = dfMinY;
    2322         358 :     double dfGDALMaxX = dfMaxX;
    2323         358 :     double dfGDALMaxY = dfMaxY;
    2324             :     pszContentsMinX =
    2325         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINX", pszContentsMinX);
    2326             :     pszContentsMinY =
    2327         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINY", pszContentsMinY);
    2328             :     pszContentsMaxX =
    2329         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXX", pszContentsMaxX);
    2330             :     pszContentsMaxY =
    2331         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXY", pszContentsMaxY);
    2332         358 :     if (pszContentsMinX != nullptr && pszContentsMinY != nullptr &&
    2333         358 :         pszContentsMaxX != nullptr && pszContentsMaxY != nullptr)
    2334             :     {
    2335         715 :         if (CPLAtof(pszContentsMinX) < CPLAtof(pszContentsMaxX) &&
    2336         357 :             CPLAtof(pszContentsMinY) < CPLAtof(pszContentsMaxY))
    2337             :         {
    2338         357 :             dfGDALMinX = CPLAtof(pszContentsMinX);
    2339         357 :             dfGDALMinY = CPLAtof(pszContentsMinY);
    2340         357 :             dfGDALMaxX = CPLAtof(pszContentsMaxX);
    2341         357 :             dfGDALMaxY = CPLAtof(pszContentsMaxY);
    2342             :         }
    2343             :         else
    2344             :         {
    2345           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    2346             :                      "Illegal min_x/min_y/max_x/max_y values for %s in open "
    2347             :                      "options and/or gpkg_contents. Using bounds of "
    2348             :                      "gpkg_tile_matrix_set instead",
    2349             :                      pszTableName);
    2350             :         }
    2351             :     }
    2352         358 :     if (dfGDALMinX >= dfGDALMaxX || dfGDALMinY >= dfGDALMaxY)
    2353             :     {
    2354           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2355             :                  "Illegal min_x/min_y/max_x/max_y values for %s", pszTableName);
    2356           0 :         return false;
    2357             :     }
    2358             : 
    2359         358 :     int nBandCount = 0;
    2360             :     const char *pszBAND_COUNT =
    2361         358 :         CSLFetchNameValue(papszOpenOptionsIn, "BAND_COUNT");
    2362         358 :     if (poParentDS)
    2363             :     {
    2364          86 :         nBandCount = poParentDS->GetRasterCount();
    2365             :     }
    2366         272 :     else if (m_eDT != GDT_Byte)
    2367             :     {
    2368          65 :         if (pszBAND_COUNT != nullptr && !EQUAL(pszBAND_COUNT, "AUTO") &&
    2369           0 :             !EQUAL(pszBAND_COUNT, "1"))
    2370             :         {
    2371           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2372             :                      "BAND_COUNT ignored for non-Byte data");
    2373             :         }
    2374          65 :         nBandCount = 1;
    2375             :     }
    2376             :     else
    2377             :     {
    2378         207 :         if (pszBAND_COUNT != nullptr && !EQUAL(pszBAND_COUNT, "AUTO"))
    2379             :         {
    2380          69 :             nBandCount = atoi(pszBAND_COUNT);
    2381          69 :             if (nBandCount == 1)
    2382           5 :                 GetMetadata("IMAGE_STRUCTURE");
    2383             :         }
    2384             :         else
    2385             :         {
    2386         138 :             GetMetadata("IMAGE_STRUCTURE");
    2387         138 :             nBandCount = m_nBandCountFromMetadata;
    2388         138 :             if (nBandCount == 1)
    2389          38 :                 m_eTF = GPKG_TF_PNG;
    2390             :         }
    2391         207 :         if (nBandCount == 1 && !m_osTFFromMetadata.empty())
    2392             :         {
    2393           2 :             m_eTF = GDALGPKGMBTilesGetTileFormat(m_osTFFromMetadata.c_str());
    2394             :         }
    2395         207 :         if (nBandCount <= 0 || nBandCount > 4)
    2396          86 :             nBandCount = 4;
    2397             :     }
    2398             : 
    2399         358 :     return InitRaster(poParentDS, pszTableName, nZoomLevel, nBandCount, dfMinX,
    2400             :                       dfMaxY, dfPixelXSize, dfPixelYSize, nTileWidth,
    2401             :                       nTileHeight, nTileMatrixWidth, nTileMatrixHeight,
    2402         358 :                       dfGDALMinX, dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    2403             : }
    2404             : 
    2405             : /************************************************************************/
    2406             : /*                      ComputeTileAndPixelShifts()                     */
    2407             : /************************************************************************/
    2408             : 
    2409         782 : bool GDALGeoPackageDataset::ComputeTileAndPixelShifts()
    2410             : {
    2411             :     int nTileWidth, nTileHeight;
    2412         782 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2413             : 
    2414             :     // Compute shift between GDAL origin and TileMatrixSet origin
    2415             :     const double dfShiftXPixels =
    2416         782 :         (m_adfGeoTransform[0] - m_dfTMSMinX) / m_adfGeoTransform[1];
    2417         782 :     if (!(dfShiftXPixels / nTileWidth >= INT_MIN &&
    2418         779 :           dfShiftXPixels / nTileWidth < INT_MAX))
    2419             :     {
    2420           3 :         return false;
    2421             :     }
    2422         779 :     const int64_t nShiftXPixels =
    2423         779 :         static_cast<int64_t>(floor(0.5 + dfShiftXPixels));
    2424         779 :     m_nShiftXTiles = static_cast<int>(nShiftXPixels / nTileWidth);
    2425         779 :     if (nShiftXPixels < 0 && (nShiftXPixels % nTileWidth) != 0)
    2426          11 :         m_nShiftXTiles--;
    2427         779 :     m_nShiftXPixelsMod =
    2428         779 :         (static_cast<int>(nShiftXPixels % nTileWidth) + nTileWidth) %
    2429             :         nTileWidth;
    2430             : 
    2431             :     const double dfShiftYPixels =
    2432         779 :         (m_adfGeoTransform[3] - m_dfTMSMaxY) / m_adfGeoTransform[5];
    2433         779 :     if (!(dfShiftYPixels / nTileHeight >= INT_MIN &&
    2434         779 :           dfShiftYPixels / nTileHeight < INT_MAX))
    2435             :     {
    2436           1 :         return false;
    2437             :     }
    2438         778 :     const int64_t nShiftYPixels =
    2439         778 :         static_cast<int64_t>(floor(0.5 + dfShiftYPixels));
    2440         778 :     m_nShiftYTiles = static_cast<int>(nShiftYPixels / nTileHeight);
    2441         778 :     if (nShiftYPixels < 0 && (nShiftYPixels % nTileHeight) != 0)
    2442          11 :         m_nShiftYTiles--;
    2443         778 :     m_nShiftYPixelsMod =
    2444         778 :         (static_cast<int>(nShiftYPixels % nTileHeight) + nTileHeight) %
    2445             :         nTileHeight;
    2446         778 :     return true;
    2447             : }
    2448             : 
    2449             : /************************************************************************/
    2450             : /*                            AllocCachedTiles()                        */
    2451             : /************************************************************************/
    2452             : 
    2453         778 : bool GDALGeoPackageDataset::AllocCachedTiles()
    2454             : {
    2455             :     int nTileWidth, nTileHeight;
    2456         778 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2457             : 
    2458             :     // We currently need 4 caches because of
    2459             :     // GDALGPKGMBTilesLikePseudoDataset::ReadTile(int nRow, int nCol)
    2460         778 :     const int nCacheCount = 4;
    2461             :     /*
    2462             :             (m_nShiftXPixelsMod != 0 || m_nShiftYPixelsMod != 0) ? 4 :
    2463             :             (GetUpdate() && m_eDT == GDT_Byte) ? 2 : 1;
    2464             :     */
    2465         778 :     m_pabyCachedTiles = static_cast<GByte *>(VSI_MALLOC3_VERBOSE(
    2466             :         cpl::fits_on<int>(nCacheCount * (m_eDT == GDT_Byte ? 4 : 1) *
    2467             :                           m_nDTSize),
    2468             :         nTileWidth, nTileHeight));
    2469         778 :     if (m_pabyCachedTiles == nullptr)
    2470             :     {
    2471           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Too big tiles: %d x %d",
    2472             :                  nTileWidth, nTileHeight);
    2473           0 :         return false;
    2474             :     }
    2475             : 
    2476         778 :     return true;
    2477             : }
    2478             : 
    2479             : /************************************************************************/
    2480             : /*                         InitRaster()                                 */
    2481             : /************************************************************************/
    2482             : 
    2483         597 : bool GDALGeoPackageDataset::InitRaster(
    2484             :     GDALGeoPackageDataset *poParentDS, const char *pszTableName, int nZoomLevel,
    2485             :     int nBandCount, double dfTMSMinX, double dfTMSMaxY, double dfPixelXSize,
    2486             :     double dfPixelYSize, int nTileWidth, int nTileHeight, int nTileMatrixWidth,
    2487             :     int nTileMatrixHeight, double dfGDALMinX, double dfGDALMinY,
    2488             :     double dfGDALMaxX, double dfGDALMaxY)
    2489             : {
    2490         597 :     m_osRasterTable = pszTableName;
    2491         597 :     m_dfTMSMinX = dfTMSMinX;
    2492         597 :     m_dfTMSMaxY = dfTMSMaxY;
    2493         597 :     m_nZoomLevel = nZoomLevel;
    2494         597 :     m_nTileMatrixWidth = nTileMatrixWidth;
    2495         597 :     m_nTileMatrixHeight = nTileMatrixHeight;
    2496             : 
    2497         597 :     m_bGeoTransformValid = true;
    2498         597 :     m_adfGeoTransform[0] = dfGDALMinX;
    2499         597 :     m_adfGeoTransform[1] = dfPixelXSize;
    2500         597 :     m_adfGeoTransform[3] = dfGDALMaxY;
    2501         597 :     m_adfGeoTransform[5] = -dfPixelYSize;
    2502         597 :     double dfRasterXSize = 0.5 + (dfGDALMaxX - dfGDALMinX) / dfPixelXSize;
    2503         597 :     double dfRasterYSize = 0.5 + (dfGDALMaxY - dfGDALMinY) / dfPixelYSize;
    2504         597 :     if (dfRasterXSize > INT_MAX || dfRasterYSize > INT_MAX)
    2505             :     {
    2506           0 :         CPLError(CE_Failure, CPLE_NotSupported, "Too big raster: %f x %f",
    2507             :                  dfRasterXSize, dfRasterYSize);
    2508           0 :         return false;
    2509             :     }
    2510         597 :     nRasterXSize = std::max(1, static_cast<int>(dfRasterXSize));
    2511         597 :     nRasterYSize = std::max(1, static_cast<int>(dfRasterYSize));
    2512             : 
    2513         597 :     if (poParentDS)
    2514             :     {
    2515         325 :         m_poParentDS = poParentDS;
    2516         325 :         eAccess = poParentDS->eAccess;
    2517         325 :         hDB = poParentDS->hDB;
    2518         325 :         m_eTF = poParentDS->m_eTF;
    2519         325 :         m_eDT = poParentDS->m_eDT;
    2520         325 :         m_nDTSize = poParentDS->m_nDTSize;
    2521         325 :         m_dfScale = poParentDS->m_dfScale;
    2522         325 :         m_dfOffset = poParentDS->m_dfOffset;
    2523         325 :         m_dfPrecision = poParentDS->m_dfPrecision;
    2524         325 :         m_usGPKGNull = poParentDS->m_usGPKGNull;
    2525         325 :         m_nQuality = poParentDS->m_nQuality;
    2526         325 :         m_nZLevel = poParentDS->m_nZLevel;
    2527         325 :         m_bDither = poParentDS->m_bDither;
    2528             :         /*m_nSRID = poParentDS->m_nSRID;*/
    2529         325 :         m_osWHERE = poParentDS->m_osWHERE;
    2530         325 :         SetDescription(CPLSPrintf("%s - zoom_level=%d",
    2531         325 :                                   poParentDS->GetDescription(), m_nZoomLevel));
    2532             :     }
    2533             : 
    2534        2094 :     for (int i = 1; i <= nBandCount; i++)
    2535             :     {
    2536             :         auto poNewBand = std::make_unique<GDALGeoPackageRasterBand>(
    2537        1497 :             this, nTileWidth, nTileHeight);
    2538        1497 :         if (poParentDS)
    2539             :         {
    2540         761 :             int bHasNoData = FALSE;
    2541             :             double dfNoDataValue =
    2542         761 :                 poParentDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    2543         761 :             if (bHasNoData)
    2544          24 :                 poNewBand->SetNoDataValueInternal(dfNoDataValue);
    2545             :         }
    2546             : 
    2547        1497 :         if (nBandCount == 1 && m_poCTFromMetadata)
    2548             :         {
    2549           3 :             poNewBand->AssignColorTable(m_poCTFromMetadata.get());
    2550             :         }
    2551        1497 :         if (!m_osNodataValueFromMetadata.empty())
    2552             :         {
    2553           8 :             poNewBand->SetNoDataValueInternal(
    2554             :                 CPLAtof(m_osNodataValueFromMetadata.c_str()));
    2555             :         }
    2556             : 
    2557        1497 :         SetBand(i, std::move(poNewBand));
    2558             :     }
    2559             : 
    2560         597 :     if (!ComputeTileAndPixelShifts())
    2561             :     {
    2562           3 :         CPLError(CE_Failure, CPLE_AppDefined,
    2563             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    2564           3 :         return false;
    2565             :     }
    2566             : 
    2567         594 :     GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    2568         594 :     GDALPamDataset::SetMetadataItem("ZOOM_LEVEL",
    2569             :                                     CPLSPrintf("%d", m_nZoomLevel));
    2570             : 
    2571         594 :     return AllocCachedTiles();
    2572             : }
    2573             : 
    2574             : /************************************************************************/
    2575             : /*                 GDALGPKGMBTilesGetTileFormat()                       */
    2576             : /************************************************************************/
    2577             : 
    2578          80 : GPKGTileFormat GDALGPKGMBTilesGetTileFormat(const char *pszTF)
    2579             : {
    2580          80 :     GPKGTileFormat eTF = GPKG_TF_PNG_JPEG;
    2581          80 :     if (pszTF)
    2582             :     {
    2583          80 :         if (EQUAL(pszTF, "PNG_JPEG") || EQUAL(pszTF, "AUTO"))
    2584           1 :             eTF = GPKG_TF_PNG_JPEG;
    2585          79 :         else if (EQUAL(pszTF, "PNG"))
    2586          46 :             eTF = GPKG_TF_PNG;
    2587          33 :         else if (EQUAL(pszTF, "PNG8"))
    2588           6 :             eTF = GPKG_TF_PNG8;
    2589          27 :         else if (EQUAL(pszTF, "JPEG"))
    2590          14 :             eTF = GPKG_TF_JPEG;
    2591          13 :         else if (EQUAL(pszTF, "WEBP"))
    2592          13 :             eTF = GPKG_TF_WEBP;
    2593             :         else
    2594             :         {
    2595           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2596             :                      "Unsuppoted value for TILE_FORMAT: %s", pszTF);
    2597             :         }
    2598             :     }
    2599          80 :     return eTF;
    2600             : }
    2601             : 
    2602          28 : const char *GDALMBTilesGetTileFormatName(GPKGTileFormat eTF)
    2603             : {
    2604          28 :     switch (eTF)
    2605             :     {
    2606          26 :         case GPKG_TF_PNG:
    2607             :         case GPKG_TF_PNG8:
    2608          26 :             return "png";
    2609           1 :         case GPKG_TF_JPEG:
    2610           1 :             return "jpg";
    2611           1 :         case GPKG_TF_WEBP:
    2612           1 :             return "webp";
    2613           0 :         default:
    2614           0 :             break;
    2615             :     }
    2616           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2617             :              "Unsuppoted value for TILE_FORMAT: %d", static_cast<int>(eTF));
    2618           0 :     return nullptr;
    2619             : }
    2620             : 
    2621             : /************************************************************************/
    2622             : /*                         OpenRaster()                                 */
    2623             : /************************************************************************/
    2624             : 
    2625         274 : bool GDALGeoPackageDataset::OpenRaster(
    2626             :     const char *pszTableName, const char *pszIdentifier,
    2627             :     const char *pszDescription, int nSRSId, double dfMinX, double dfMinY,
    2628             :     double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2629             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2630             :     const char *pszContentsMaxY, bool bIsTiles, char **papszOpenOptionsIn)
    2631             : {
    2632         274 :     if (dfMinX >= dfMaxX || dfMinY >= dfMaxY)
    2633           0 :         return false;
    2634             : 
    2635             :     // Config option just for debug, and for example force set to NaN
    2636             :     // which is not supported
    2637         548 :     CPLString osDataNull = CPLGetConfigOption("GPKG_NODATA", "");
    2638         548 :     CPLString osUom;
    2639         548 :     CPLString osFieldName;
    2640         548 :     CPLString osGridCellEncoding;
    2641         274 :     if (!bIsTiles)
    2642             :     {
    2643          65 :         char *pszSQL = sqlite3_mprintf(
    2644             :             "SELECT datatype, scale, offset, data_null, precision FROM "
    2645             :             "gpkg_2d_gridded_coverage_ancillary "
    2646             :             "WHERE tile_matrix_set_name = '%q' "
    2647             :             "AND datatype IN ('integer', 'float')"
    2648             :             "AND (scale > 0 OR scale IS NULL)",
    2649             :             pszTableName);
    2650          65 :         auto oResult = SQLQuery(hDB, pszSQL);
    2651          65 :         sqlite3_free(pszSQL);
    2652          65 :         if (!oResult || oResult->RowCount() == 0)
    2653             :         {
    2654           0 :             return false;
    2655             :         }
    2656          65 :         const char *pszDataType = oResult->GetValue(0, 0);
    2657          65 :         const char *pszScale = oResult->GetValue(1, 0);
    2658          65 :         const char *pszOffset = oResult->GetValue(2, 0);
    2659          65 :         const char *pszDataNull = oResult->GetValue(3, 0);
    2660          65 :         const char *pszPrecision = oResult->GetValue(4, 0);
    2661          65 :         if (pszDataNull)
    2662          23 :             osDataNull = pszDataNull;
    2663          65 :         if (EQUAL(pszDataType, "float"))
    2664             :         {
    2665           6 :             SetDataType(GDT_Float32);
    2666           6 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    2667             :         }
    2668             :         else
    2669             :         {
    2670          59 :             SetDataType(GDT_Float32);
    2671          59 :             m_eTF = GPKG_TF_PNG_16BIT;
    2672          59 :             const double dfScale = pszScale ? CPLAtof(pszScale) : 1.0;
    2673          59 :             const double dfOffset = pszOffset ? CPLAtof(pszOffset) : 0.0;
    2674          59 :             if (dfScale == 1.0)
    2675             :             {
    2676          59 :                 if (dfOffset == 0.0)
    2677             :                 {
    2678          24 :                     SetDataType(GDT_UInt16);
    2679             :                 }
    2680          35 :                 else if (dfOffset == -32768.0)
    2681             :                 {
    2682          35 :                     SetDataType(GDT_Int16);
    2683             :                 }
    2684             :                 // coverity[tainted_data]
    2685           0 :                 else if (dfOffset == -32767.0 && !osDataNull.empty() &&
    2686           0 :                          CPLAtof(osDataNull) == 65535.0)
    2687             :                 // Given that we will map the nodata value to -32768
    2688             :                 {
    2689           0 :                     SetDataType(GDT_Int16);
    2690             :                 }
    2691             :             }
    2692             : 
    2693             :             // Check that the tile offset and scales are compatible of a
    2694             :             // final integer result.
    2695          59 :             if (m_eDT != GDT_Float32)
    2696             :             {
    2697             :                 // coverity[tainted_data]
    2698          59 :                 if (dfScale == 1.0 && dfOffset == -32768.0 &&
    2699         118 :                     !osDataNull.empty() && CPLAtof(osDataNull) == 65535.0)
    2700             :                 {
    2701             :                     // Given that we will map the nodata value to -32768
    2702           9 :                     pszSQL = sqlite3_mprintf(
    2703             :                         "SELECT 1 FROM "
    2704             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2705             :                         "tpudt_name = '%q' "
    2706             :                         "AND NOT ((offset = 0.0 or offset = 1.0) "
    2707             :                         "AND scale = 1.0) "
    2708             :                         "LIMIT 1",
    2709             :                         pszTableName);
    2710             :                 }
    2711             :                 else
    2712             :                 {
    2713          50 :                     pszSQL = sqlite3_mprintf(
    2714             :                         "SELECT 1 FROM "
    2715             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2716             :                         "tpudt_name = '%q' "
    2717             :                         "AND NOT (offset = 0.0 AND scale = 1.0) LIMIT 1",
    2718             :                         pszTableName);
    2719             :                 }
    2720          59 :                 sqlite3_stmt *hSQLStmt = nullptr;
    2721             :                 int rc =
    2722          59 :                     SQLPrepareWithError(hDB, pszSQL, -1, &hSQLStmt, nullptr);
    2723             : 
    2724          59 :                 if (rc == SQLITE_OK)
    2725             :                 {
    2726          59 :                     if (sqlite3_step(hSQLStmt) == SQLITE_ROW)
    2727             :                     {
    2728           8 :                         SetDataType(GDT_Float32);
    2729             :                     }
    2730          59 :                     sqlite3_finalize(hSQLStmt);
    2731             :                 }
    2732          59 :                 sqlite3_free(pszSQL);
    2733             :             }
    2734             : 
    2735          59 :             SetGlobalOffsetScale(dfOffset, dfScale);
    2736             :         }
    2737          65 :         if (pszPrecision)
    2738          65 :             m_dfPrecision = CPLAtof(pszPrecision);
    2739             : 
    2740             :         // Request those columns in a separate query, so as to keep
    2741             :         // compatibility with pre OGC 17-066r1 databases
    2742             :         pszSQL =
    2743          65 :             sqlite3_mprintf("SELECT uom, field_name, grid_cell_encoding FROM "
    2744             :                             "gpkg_2d_gridded_coverage_ancillary "
    2745             :                             "WHERE tile_matrix_set_name = '%q'",
    2746             :                             pszTableName);
    2747          65 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    2748          65 :         oResult = SQLQuery(hDB, pszSQL);
    2749          65 :         CPLPopErrorHandler();
    2750          65 :         sqlite3_free(pszSQL);
    2751          65 :         if (oResult && oResult->RowCount() == 1)
    2752             :         {
    2753          64 :             const char *pszUom = oResult->GetValue(0, 0);
    2754          64 :             if (pszUom)
    2755           2 :                 osUom = pszUom;
    2756          64 :             const char *pszFieldName = oResult->GetValue(1, 0);
    2757          64 :             if (pszFieldName)
    2758          64 :                 osFieldName = pszFieldName;
    2759          64 :             const char *pszGridCellEncoding = oResult->GetValue(2, 0);
    2760          64 :             if (pszGridCellEncoding)
    2761          64 :                 osGridCellEncoding = pszGridCellEncoding;
    2762             :         }
    2763             :     }
    2764             : 
    2765         274 :     m_bRecordInsertedInGPKGContent = true;
    2766         274 :     m_nSRID = nSRSId;
    2767             : 
    2768         547 :     if (auto poSRS = GetSpatialRef(nSRSId))
    2769             :     {
    2770         273 :         m_oSRS = *(poSRS.get());
    2771             :     }
    2772             : 
    2773             :     /* Various sanity checks added in the SELECT */
    2774         274 :     char *pszQuotedTableName = sqlite3_mprintf("'%q'", pszTableName);
    2775         548 :     CPLString osQuotedTableName(pszQuotedTableName);
    2776         274 :     sqlite3_free(pszQuotedTableName);
    2777         274 :     char *pszSQL = sqlite3_mprintf(
    2778             :         "SELECT zoom_level, pixel_x_size, pixel_y_size, tile_width, "
    2779             :         "tile_height, matrix_width, matrix_height "
    2780             :         "FROM gpkg_tile_matrix tm "
    2781             :         "WHERE table_name = %s "
    2782             :         // INT_MAX would be the theoretical maximum value to avoid
    2783             :         // overflows, but that's already a insane value.
    2784             :         "AND zoom_level >= 0 AND zoom_level <= 65536 "
    2785             :         "AND pixel_x_size > 0 AND pixel_y_size > 0 "
    2786             :         "AND tile_width >= 1 AND tile_width <= 65536 "
    2787             :         "AND tile_height >= 1 AND tile_height <= 65536 "
    2788             :         "AND matrix_width >= 1 AND matrix_height >= 1",
    2789             :         osQuotedTableName.c_str());
    2790         548 :     CPLString osSQL(pszSQL);
    2791             :     const char *pszZoomLevel =
    2792         274 :         CSLFetchNameValue(papszOpenOptionsIn, "ZOOM_LEVEL");
    2793         274 :     if (pszZoomLevel)
    2794             :     {
    2795           5 :         if (GetUpdate())
    2796           1 :             osSQL += CPLSPrintf(" AND zoom_level <= %d", atoi(pszZoomLevel));
    2797             :         else
    2798             :         {
    2799             :             osSQL += CPLSPrintf(
    2800             :                 " AND (zoom_level = %d OR (zoom_level < %d AND EXISTS(SELECT 1 "
    2801             :                 "FROM %s WHERE zoom_level = tm.zoom_level LIMIT 1)))",
    2802             :                 atoi(pszZoomLevel), atoi(pszZoomLevel),
    2803           4 :                 osQuotedTableName.c_str());
    2804             :         }
    2805             :     }
    2806             :     // In read-only mode, only lists non empty zoom levels
    2807         269 :     else if (!GetUpdate())
    2808             :     {
    2809             :         osSQL += CPLSPrintf(" AND EXISTS(SELECT 1 FROM %s WHERE zoom_level = "
    2810             :                             "tm.zoom_level LIMIT 1)",
    2811         215 :                             osQuotedTableName.c_str());
    2812             :     }
    2813             :     else  // if( pszZoomLevel == nullptr )
    2814             :     {
    2815             :         osSQL +=
    2816             :             CPLSPrintf(" AND zoom_level <= (SELECT MAX(zoom_level) FROM %s)",
    2817          54 :                        osQuotedTableName.c_str());
    2818             :     }
    2819         274 :     osSQL += " ORDER BY zoom_level DESC";
    2820             :     // To avoid denial of service.
    2821         274 :     osSQL += " LIMIT 100";
    2822             : 
    2823         548 :     auto oResult = SQLQuery(hDB, osSQL.c_str());
    2824         274 :     if (!oResult || oResult->RowCount() == 0)
    2825             :     {
    2826         114 :         if (oResult && oResult->RowCount() == 0 && pszContentsMinX != nullptr &&
    2827         114 :             pszContentsMinY != nullptr && pszContentsMaxX != nullptr &&
    2828             :             pszContentsMaxY != nullptr)
    2829             :         {
    2830          56 :             osSQL = pszSQL;
    2831          56 :             osSQL += " ORDER BY zoom_level DESC";
    2832          56 :             if (!GetUpdate())
    2833          30 :                 osSQL += " LIMIT 1";
    2834          56 :             oResult = SQLQuery(hDB, osSQL.c_str());
    2835             :         }
    2836          57 :         if (!oResult || oResult->RowCount() == 0)
    2837             :         {
    2838           1 :             if (oResult && pszZoomLevel != nullptr)
    2839             :             {
    2840           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2841             :                          "ZOOM_LEVEL is probably not valid w.r.t tile "
    2842             :                          "table content");
    2843             :             }
    2844           1 :             sqlite3_free(pszSQL);
    2845           1 :             return false;
    2846             :         }
    2847             :     }
    2848         273 :     sqlite3_free(pszSQL);
    2849             : 
    2850             :     // If USE_TILE_EXTENT=YES, then query the tile table to find which tiles
    2851             :     // actually exist.
    2852             : 
    2853             :     // CAUTION: Do not move those variables inside inner scope !
    2854         546 :     CPLString osContentsMinX, osContentsMinY, osContentsMaxX, osContentsMaxY;
    2855             : 
    2856         273 :     if (CPLTestBool(
    2857             :             CSLFetchNameValueDef(papszOpenOptionsIn, "USE_TILE_EXTENT", "NO")))
    2858             :     {
    2859          13 :         pszSQL = sqlite3_mprintf(
    2860             :             "SELECT MIN(tile_column), MIN(tile_row), MAX(tile_column), "
    2861             :             "MAX(tile_row) FROM \"%w\" WHERE zoom_level = %d",
    2862             :             pszTableName, atoi(oResult->GetValue(0, 0)));
    2863          13 :         auto oResult2 = SQLQuery(hDB, pszSQL);
    2864          13 :         sqlite3_free(pszSQL);
    2865          26 :         if (!oResult2 || oResult2->RowCount() == 0 ||
    2866             :             // Can happen if table is empty
    2867          38 :             oResult2->GetValue(0, 0) == nullptr ||
    2868             :             // Can happen if table has no NOT NULL constraint on tile_row
    2869             :             // and that all tile_row are NULL
    2870          12 :             oResult2->GetValue(1, 0) == nullptr)
    2871             :         {
    2872           1 :             return false;
    2873             :         }
    2874          12 :         const double dfPixelXSize = CPLAtof(oResult->GetValue(1, 0));
    2875          12 :         const double dfPixelYSize = CPLAtof(oResult->GetValue(2, 0));
    2876          12 :         const int nTileWidth = atoi(oResult->GetValue(3, 0));
    2877          12 :         const int nTileHeight = atoi(oResult->GetValue(4, 0));
    2878             :         osContentsMinX =
    2879          24 :             CPLSPrintf("%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2880          12 :                                              atoi(oResult2->GetValue(0, 0)));
    2881             :         osContentsMaxY =
    2882          24 :             CPLSPrintf("%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2883          12 :                                              atoi(oResult2->GetValue(1, 0)));
    2884             :         osContentsMaxX = CPLSPrintf(
    2885          24 :             "%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2886          12 :                                   (1 + atoi(oResult2->GetValue(2, 0))));
    2887             :         osContentsMinY = CPLSPrintf(
    2888          24 :             "%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2889          12 :                                   (1 + atoi(oResult2->GetValue(3, 0))));
    2890          12 :         pszContentsMinX = osContentsMinX.c_str();
    2891          12 :         pszContentsMinY = osContentsMinY.c_str();
    2892          12 :         pszContentsMaxX = osContentsMaxX.c_str();
    2893          12 :         pszContentsMaxY = osContentsMaxY.c_str();
    2894             :     }
    2895             : 
    2896         272 :     if (!InitRaster(nullptr, pszTableName, dfMinX, dfMinY, dfMaxX, dfMaxY,
    2897             :                     pszContentsMinX, pszContentsMinY, pszContentsMaxX,
    2898         272 :                     pszContentsMaxY, papszOpenOptionsIn, *oResult, 0))
    2899             :     {
    2900           3 :         return false;
    2901             :     }
    2902             : 
    2903             :     auto poBand =
    2904         269 :         reinterpret_cast<GDALGeoPackageRasterBand *>(GetRasterBand(1));
    2905         269 :     if (!osDataNull.empty())
    2906             :     {
    2907          23 :         double dfGPKGNoDataValue = CPLAtof(osDataNull);
    2908          23 :         if (m_eTF == GPKG_TF_PNG_16BIT)
    2909             :         {
    2910          21 :             if (dfGPKGNoDataValue < 0 || dfGPKGNoDataValue > 65535 ||
    2911          21 :                 static_cast<int>(dfGPKGNoDataValue) != dfGPKGNoDataValue)
    2912             :             {
    2913           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2914             :                          "data_null = %.17g is invalid for integer data_type",
    2915             :                          dfGPKGNoDataValue);
    2916             :             }
    2917             :             else
    2918             :             {
    2919          21 :                 m_usGPKGNull = static_cast<GUInt16>(dfGPKGNoDataValue);
    2920          21 :                 if (m_eDT == GDT_Int16 && m_usGPKGNull > 32767)
    2921           9 :                     dfGPKGNoDataValue = -32768.0;
    2922          12 :                 else if (m_eDT == GDT_Float32)
    2923             :                 {
    2924             :                     // Pick a value that is unlikely to be hit with offset &
    2925             :                     // scale
    2926           4 :                     dfGPKGNoDataValue = -std::numeric_limits<float>::max();
    2927             :                 }
    2928          21 :                 poBand->SetNoDataValueInternal(dfGPKGNoDataValue);
    2929             :             }
    2930             :         }
    2931             :         else
    2932             :         {
    2933           2 :             poBand->SetNoDataValueInternal(
    2934           2 :                 static_cast<float>(dfGPKGNoDataValue));
    2935             :         }
    2936             :     }
    2937         269 :     if (!osUom.empty())
    2938             :     {
    2939           2 :         poBand->SetUnitTypeInternal(osUom);
    2940             :     }
    2941         269 :     if (!osFieldName.empty())
    2942             :     {
    2943          64 :         GetRasterBand(1)->GDALRasterBand::SetDescription(osFieldName);
    2944             :     }
    2945         269 :     if (!osGridCellEncoding.empty())
    2946             :     {
    2947          64 :         if (osGridCellEncoding == "grid-value-is-center")
    2948             :         {
    2949          15 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2950             :                                             GDALMD_AOP_POINT);
    2951             :         }
    2952          49 :         else if (osGridCellEncoding == "grid-value-is-area")
    2953             :         {
    2954          45 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2955             :                                             GDALMD_AOP_AREA);
    2956             :         }
    2957             :         else
    2958             :         {
    2959           4 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2960             :                                             GDALMD_AOP_POINT);
    2961           4 :             GetRasterBand(1)->GDALRasterBand::SetMetadataItem(
    2962             :                 "GRID_CELL_ENCODING", osGridCellEncoding);
    2963             :         }
    2964             :     }
    2965             : 
    2966         269 :     CheckUnknownExtensions(true);
    2967             : 
    2968             :     // Do this after CheckUnknownExtensions() so that m_eTF is set to
    2969             :     // GPKG_TF_WEBP if the table already registers the gpkg_webp extension
    2970         269 :     const char *pszTF = CSLFetchNameValue(papszOpenOptionsIn, "TILE_FORMAT");
    2971         269 :     if (pszTF)
    2972             :     {
    2973           4 :         if (!GetUpdate())
    2974             :         {
    2975           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2976             :                      "TILE_FORMAT open option ignored in read-only mode");
    2977             :         }
    2978           4 :         else if (m_eTF == GPKG_TF_PNG_16BIT ||
    2979           4 :                  m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    2980             :         {
    2981           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2982             :                      "TILE_FORMAT open option ignored on gridded coverages");
    2983             :         }
    2984             :         else
    2985             :         {
    2986           4 :             GPKGTileFormat eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    2987           4 :             if (eTF == GPKG_TF_WEBP && m_eTF != eTF)
    2988             :             {
    2989           1 :                 if (!RegisterWebPExtension())
    2990           0 :                     return false;
    2991             :             }
    2992           4 :             m_eTF = eTF;
    2993             :         }
    2994             :     }
    2995             : 
    2996         269 :     ParseCompressionOptions(papszOpenOptionsIn);
    2997             : 
    2998         269 :     m_osWHERE = CSLFetchNameValueDef(papszOpenOptionsIn, "WHERE", "");
    2999             : 
    3000             :     // Set metadata
    3001         269 :     if (pszIdentifier && pszIdentifier[0])
    3002         269 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", pszIdentifier);
    3003         269 :     if (pszDescription && pszDescription[0])
    3004          21 :         GDALPamDataset::SetMetadataItem("DESCRIPTION", pszDescription);
    3005             : 
    3006             :     // Add overviews
    3007         354 :     for (int i = 1; i < oResult->RowCount(); i++)
    3008             :     {
    3009          86 :         auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3010          86 :         poOvrDS->ShareLockWithParentDataset(this);
    3011         172 :         if (!poOvrDS->InitRaster(this, pszTableName, dfMinX, dfMinY, dfMaxX,
    3012             :                                  dfMaxY, pszContentsMinX, pszContentsMinY,
    3013             :                                  pszContentsMaxX, pszContentsMaxY,
    3014          86 :                                  papszOpenOptionsIn, *oResult, i))
    3015             :         {
    3016           0 :             break;
    3017             :         }
    3018             : 
    3019             :         int nTileWidth, nTileHeight;
    3020          86 :         poOvrDS->GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3021             :         const bool bStop =
    3022          87 :             (eAccess == GA_ReadOnly && poOvrDS->GetRasterXSize() < nTileWidth &&
    3023           1 :              poOvrDS->GetRasterYSize() < nTileHeight);
    3024             : 
    3025          86 :         m_apoOverviewDS.push_back(std::move(poOvrDS));
    3026             : 
    3027          86 :         if (bStop)
    3028             :         {
    3029           1 :             break;
    3030             :         }
    3031             :     }
    3032             : 
    3033         269 :     return true;
    3034             : }
    3035             : 
    3036             : /************************************************************************/
    3037             : /*                           GetSpatialRef()                            */
    3038             : /************************************************************************/
    3039             : 
    3040          17 : const OGRSpatialReference *GDALGeoPackageDataset::GetSpatialRef() const
    3041             : {
    3042          17 :     return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
    3043             : }
    3044             : 
    3045             : /************************************************************************/
    3046             : /*                           SetSpatialRef()                            */
    3047             : /************************************************************************/
    3048             : 
    3049         150 : CPLErr GDALGeoPackageDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    3050             : {
    3051         150 :     if (nBands == 0)
    3052             :     {
    3053           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3054             :                  "SetProjection() not supported on a dataset with 0 band");
    3055           1 :         return CE_Failure;
    3056             :     }
    3057         149 :     if (eAccess != GA_Update)
    3058             :     {
    3059           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3060             :                  "SetProjection() not supported on read-only dataset");
    3061           1 :         return CE_Failure;
    3062             :     }
    3063             : 
    3064         148 :     const int nSRID = GetSrsId(poSRS);
    3065         296 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3066         148 :     if (poTS && nSRID != poTS->nEPSGCode)
    3067             :     {
    3068           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3069             :                  "Projection should be EPSG:%d for %s tiling scheme",
    3070           1 :                  poTS->nEPSGCode, m_osTilingScheme.c_str());
    3071           1 :         return CE_Failure;
    3072             :     }
    3073             : 
    3074         147 :     m_nSRID = nSRID;
    3075         147 :     m_oSRS.Clear();
    3076         147 :     if (poSRS)
    3077         146 :         m_oSRS = *poSRS;
    3078             : 
    3079         147 :     if (m_bRecordInsertedInGPKGContent)
    3080             :     {
    3081         119 :         char *pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET srs_id = %d "
    3082             :                                        "WHERE lower(table_name) = lower('%q')",
    3083             :                                        m_nSRID, m_osRasterTable.c_str());
    3084         119 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3085         119 :         sqlite3_free(pszSQL);
    3086         119 :         if (eErr != OGRERR_NONE)
    3087           0 :             return CE_Failure;
    3088             : 
    3089         119 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_tile_matrix_set SET srs_id = %d "
    3090             :                                  "WHERE lower(table_name) = lower('%q')",
    3091             :                                  m_nSRID, m_osRasterTable.c_str());
    3092         119 :         eErr = SQLCommand(hDB, pszSQL);
    3093         119 :         sqlite3_free(pszSQL);
    3094         119 :         if (eErr != OGRERR_NONE)
    3095           0 :             return CE_Failure;
    3096             :     }
    3097             : 
    3098         147 :     return CE_None;
    3099             : }
    3100             : 
    3101             : /************************************************************************/
    3102             : /*                          GetGeoTransform()                           */
    3103             : /************************************************************************/
    3104             : 
    3105          33 : CPLErr GDALGeoPackageDataset::GetGeoTransform(double *padfGeoTransform)
    3106             : {
    3107          33 :     memcpy(padfGeoTransform, m_adfGeoTransform.data(), 6 * sizeof(double));
    3108          33 :     if (!m_bGeoTransformValid)
    3109           2 :         return CE_Failure;
    3110             :     else
    3111          31 :         return CE_None;
    3112             : }
    3113             : 
    3114             : /************************************************************************/
    3115             : /*                          SetGeoTransform()                           */
    3116             : /************************************************************************/
    3117             : 
    3118         190 : CPLErr GDALGeoPackageDataset::SetGeoTransform(double *padfGeoTransform)
    3119             : {
    3120         190 :     if (nBands == 0)
    3121             :     {
    3122           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3123             :                  "SetGeoTransform() not supported on a dataset with 0 band");
    3124           2 :         return CE_Failure;
    3125             :     }
    3126         188 :     if (eAccess != GA_Update)
    3127             :     {
    3128           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3129             :                  "SetGeoTransform() not supported on read-only dataset");
    3130           1 :         return CE_Failure;
    3131             :     }
    3132         187 :     if (m_bGeoTransformValid)
    3133             :     {
    3134           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3135             :                  "Cannot modify geotransform once set");
    3136           1 :         return CE_Failure;
    3137             :     }
    3138         186 :     if (padfGeoTransform[2] != 0.0 || padfGeoTransform[4] != 0 ||
    3139         186 :         padfGeoTransform[5] > 0.0)
    3140             :     {
    3141           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3142             :                  "Only north-up non rotated geotransform supported");
    3143           0 :         return CE_Failure;
    3144             :     }
    3145             : 
    3146         186 :     if (m_nZoomLevel < 0)
    3147             :     {
    3148         185 :         const auto poTS = GetTilingScheme(m_osTilingScheme);
    3149         185 :         if (poTS)
    3150             :         {
    3151          20 :             double dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3152          20 :             double dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3153         199 :             for (m_nZoomLevel = 0; m_nZoomLevel < MAX_ZOOM_LEVEL;
    3154         179 :                  m_nZoomLevel++)
    3155             :             {
    3156         198 :                 double dfExpectedPixelXSize =
    3157         198 :                     dfPixelXSizeZoomLevel0 / (1 << m_nZoomLevel);
    3158         198 :                 double dfExpectedPixelYSize =
    3159         198 :                     dfPixelYSizeZoomLevel0 / (1 << m_nZoomLevel);
    3160         198 :                 if (fabs(padfGeoTransform[1] - dfExpectedPixelXSize) <
    3161         198 :                         1e-8 * dfExpectedPixelXSize &&
    3162          19 :                     fabs(fabs(padfGeoTransform[5]) - dfExpectedPixelYSize) <
    3163          19 :                         1e-8 * dfExpectedPixelYSize)
    3164             :                 {
    3165          19 :                     break;
    3166             :                 }
    3167             :             }
    3168          20 :             if (m_nZoomLevel == MAX_ZOOM_LEVEL)
    3169             :             {
    3170           1 :                 m_nZoomLevel = -1;
    3171           1 :                 CPLError(
    3172             :                     CE_Failure, CPLE_NotSupported,
    3173             :                     "Could not find an appropriate zoom level of %s tiling "
    3174             :                     "scheme that matches raster pixel size",
    3175             :                     m_osTilingScheme.c_str());
    3176           1 :                 return CE_Failure;
    3177             :             }
    3178             :         }
    3179             :     }
    3180             : 
    3181         185 :     memcpy(m_adfGeoTransform.data(), padfGeoTransform, 6 * sizeof(double));
    3182         185 :     m_bGeoTransformValid = true;
    3183             : 
    3184         185 :     return FinalizeRasterRegistration();
    3185             : }
    3186             : 
    3187             : /************************************************************************/
    3188             : /*                      FinalizeRasterRegistration()                    */
    3189             : /************************************************************************/
    3190             : 
    3191         185 : CPLErr GDALGeoPackageDataset::FinalizeRasterRegistration()
    3192             : {
    3193             :     OGRErr eErr;
    3194             : 
    3195         185 :     m_dfTMSMinX = m_adfGeoTransform[0];
    3196         185 :     m_dfTMSMaxY = m_adfGeoTransform[3];
    3197             : 
    3198             :     int nTileWidth, nTileHeight;
    3199         185 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3200             : 
    3201         185 :     if (m_nZoomLevel < 0)
    3202             :     {
    3203         165 :         m_nZoomLevel = 0;
    3204         239 :         while ((nRasterXSize >> m_nZoomLevel) > nTileWidth ||
    3205         165 :                (nRasterYSize >> m_nZoomLevel) > nTileHeight)
    3206          74 :             m_nZoomLevel++;
    3207             :     }
    3208             : 
    3209         185 :     double dfPixelXSizeZoomLevel0 = m_adfGeoTransform[1] * (1 << m_nZoomLevel);
    3210             :     double dfPixelYSizeZoomLevel0 =
    3211         185 :         fabs(m_adfGeoTransform[5]) * (1 << m_nZoomLevel);
    3212             :     int nTileXCountZoomLevel0 =
    3213         185 :         std::max(1, DIV_ROUND_UP((nRasterXSize >> m_nZoomLevel), nTileWidth));
    3214             :     int nTileYCountZoomLevel0 =
    3215         185 :         std::max(1, DIV_ROUND_UP((nRasterYSize >> m_nZoomLevel), nTileHeight));
    3216             : 
    3217         370 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3218         185 :     if (poTS)
    3219             :     {
    3220          20 :         CPLAssert(m_nZoomLevel >= 0);
    3221          20 :         m_dfTMSMinX = poTS->dfMinX;
    3222          20 :         m_dfTMSMaxY = poTS->dfMaxY;
    3223          20 :         dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3224          20 :         dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3225          20 :         nTileXCountZoomLevel0 = poTS->nTileXCountZoomLevel0;
    3226          20 :         nTileYCountZoomLevel0 = poTS->nTileYCountZoomLevel0;
    3227             :     }
    3228         185 :     m_nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << m_nZoomLevel);
    3229         185 :     m_nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << m_nZoomLevel);
    3230             : 
    3231         185 :     if (!ComputeTileAndPixelShifts())
    3232             :     {
    3233           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    3234             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    3235           1 :         return CE_Failure;
    3236             :     }
    3237             : 
    3238         184 :     if (!AllocCachedTiles())
    3239             :     {
    3240           0 :         return CE_Failure;
    3241             :     }
    3242             : 
    3243         184 :     double dfGDALMinX = m_adfGeoTransform[0];
    3244             :     double dfGDALMinY =
    3245         184 :         m_adfGeoTransform[3] + nRasterYSize * m_adfGeoTransform[5];
    3246             :     double dfGDALMaxX =
    3247         184 :         m_adfGeoTransform[0] + nRasterXSize * m_adfGeoTransform[1];
    3248         184 :     double dfGDALMaxY = m_adfGeoTransform[3];
    3249             : 
    3250         184 :     if (SoftStartTransaction() != OGRERR_NONE)
    3251           0 :         return CE_Failure;
    3252             : 
    3253             :     const char *pszCurrentDate =
    3254         184 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3255             :     CPLString osInsertGpkgContentsFormatting(
    3256             :         "INSERT INTO gpkg_contents "
    3257             :         "(table_name,data_type,identifier,description,min_x,min_y,max_x,max_y,"
    3258             :         "last_change,srs_id) VALUES "
    3259         368 :         "('%q','%q','%q','%q',%.17g,%.17g,%.17g,%.17g,");
    3260         184 :     osInsertGpkgContentsFormatting += (pszCurrentDate) ? "'%q'" : "%s";
    3261         184 :     osInsertGpkgContentsFormatting += ",%d)";
    3262         368 :     char *pszSQL = sqlite3_mprintf(
    3263             :         osInsertGpkgContentsFormatting.c_str(), m_osRasterTable.c_str(),
    3264         184 :         (m_eDT == GDT_Byte) ? "tiles" : "2d-gridded-coverage",
    3265             :         m_osIdentifier.c_str(), m_osDescription.c_str(), dfGDALMinX, dfGDALMinY,
    3266             :         dfGDALMaxX, dfGDALMaxY,
    3267             :         pszCurrentDate ? pszCurrentDate
    3268             :                        : "strftime('%Y-%m-%dT%H:%M:%fZ','now')",
    3269             :         m_nSRID);
    3270             : 
    3271         184 :     eErr = SQLCommand(hDB, pszSQL);
    3272         184 :     sqlite3_free(pszSQL);
    3273         184 :     if (eErr != OGRERR_NONE)
    3274             :     {
    3275           8 :         SoftRollbackTransaction();
    3276           8 :         return CE_Failure;
    3277             :     }
    3278             : 
    3279         176 :     double dfTMSMaxX = m_dfTMSMinX + nTileXCountZoomLevel0 * nTileWidth *
    3280             :                                          dfPixelXSizeZoomLevel0;
    3281         176 :     double dfTMSMinY = m_dfTMSMaxY - nTileYCountZoomLevel0 * nTileHeight *
    3282             :                                          dfPixelYSizeZoomLevel0;
    3283             : 
    3284             :     pszSQL =
    3285         176 :         sqlite3_mprintf("INSERT INTO gpkg_tile_matrix_set "
    3286             :                         "(table_name,srs_id,min_x,min_y,max_x,max_y) VALUES "
    3287             :                         "('%q',%d,%.17g,%.17g,%.17g,%.17g)",
    3288             :                         m_osRasterTable.c_str(), m_nSRID, m_dfTMSMinX,
    3289             :                         dfTMSMinY, dfTMSMaxX, m_dfTMSMaxY);
    3290         176 :     eErr = SQLCommand(hDB, pszSQL);
    3291         176 :     sqlite3_free(pszSQL);
    3292         176 :     if (eErr != OGRERR_NONE)
    3293             :     {
    3294           0 :         SoftRollbackTransaction();
    3295           0 :         return CE_Failure;
    3296             :     }
    3297             : 
    3298         176 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3299             : 
    3300         587 :     for (int i = 0; i <= m_nZoomLevel; i++)
    3301             :     {
    3302         411 :         double dfPixelXSizeZoomLevel = 0.0;
    3303         411 :         double dfPixelYSizeZoomLevel = 0.0;
    3304         411 :         int nTileMatrixWidth = 0;
    3305         411 :         int nTileMatrixHeight = 0;
    3306         411 :         if (EQUAL(m_osTilingScheme, "CUSTOM"))
    3307             :         {
    3308         230 :             dfPixelXSizeZoomLevel =
    3309         230 :                 m_adfGeoTransform[1] * (1 << (m_nZoomLevel - i));
    3310         230 :             dfPixelYSizeZoomLevel =
    3311         230 :                 fabs(m_adfGeoTransform[5]) * (1 << (m_nZoomLevel - i));
    3312             :         }
    3313             :         else
    3314             :         {
    3315         181 :             dfPixelXSizeZoomLevel = dfPixelXSizeZoomLevel0 / (1 << i);
    3316         181 :             dfPixelYSizeZoomLevel = dfPixelYSizeZoomLevel0 / (1 << i);
    3317             :         }
    3318         411 :         nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << i);
    3319         411 :         nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << i);
    3320             : 
    3321         411 :         pszSQL = sqlite3_mprintf(
    3322             :             "INSERT INTO gpkg_tile_matrix "
    3323             :             "(table_name,zoom_level,matrix_width,matrix_height,tile_width,tile_"
    3324             :             "height,pixel_x_size,pixel_y_size) VALUES "
    3325             :             "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3326             :             m_osRasterTable.c_str(), i, nTileMatrixWidth, nTileMatrixHeight,
    3327             :             nTileWidth, nTileHeight, dfPixelXSizeZoomLevel,
    3328             :             dfPixelYSizeZoomLevel);
    3329         411 :         eErr = SQLCommand(hDB, pszSQL);
    3330         411 :         sqlite3_free(pszSQL);
    3331         411 :         if (eErr != OGRERR_NONE)
    3332             :         {
    3333           0 :             SoftRollbackTransaction();
    3334           0 :             return CE_Failure;
    3335             :         }
    3336             : 
    3337         411 :         if (i < m_nZoomLevel)
    3338             :         {
    3339         470 :             auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3340         235 :             poOvrDS->ShareLockWithParentDataset(this);
    3341         235 :             poOvrDS->InitRaster(this, m_osRasterTable, i, nBands, m_dfTMSMinX,
    3342             :                                 m_dfTMSMaxY, dfPixelXSizeZoomLevel,
    3343             :                                 dfPixelYSizeZoomLevel, nTileWidth, nTileHeight,
    3344             :                                 nTileMatrixWidth, nTileMatrixHeight, dfGDALMinX,
    3345             :                                 dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    3346             : 
    3347         235 :             m_apoOverviewDS[m_nZoomLevel - 1 - i] = std::move(poOvrDS);
    3348             :         }
    3349             :     }
    3350             : 
    3351         176 :     if (!m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.empty())
    3352             :     {
    3353          40 :         eErr = SQLCommand(
    3354             :             hDB, m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.c_str());
    3355          40 :         m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.clear();
    3356          40 :         if (eErr != OGRERR_NONE)
    3357             :         {
    3358           0 :             SoftRollbackTransaction();
    3359           0 :             return CE_Failure;
    3360             :         }
    3361             :     }
    3362             : 
    3363         176 :     SoftCommitTransaction();
    3364             : 
    3365         176 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3366         176 :     m_bRecordInsertedInGPKGContent = true;
    3367             : 
    3368         176 :     return CE_None;
    3369             : }
    3370             : 
    3371             : /************************************************************************/
    3372             : /*                             FlushCache()                             */
    3373             : /************************************************************************/
    3374             : 
    3375        2611 : CPLErr GDALGeoPackageDataset::FlushCache(bool bAtClosing)
    3376             : {
    3377        2611 :     if (m_bInFlushCache)
    3378           0 :         return CE_None;
    3379             : 
    3380        2611 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3381             :     {
    3382        2608 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3383             :     }
    3384             : 
    3385        2611 :     if (m_bRemoveOGREmptyTable)
    3386             :     {
    3387         656 :         m_bRemoveOGREmptyTable = false;
    3388         656 :         RemoveOGREmptyTable();
    3389             :     }
    3390             : 
    3391        2611 :     CPLErr eErr = IFlushCacheWithErrCode(bAtClosing);
    3392             : 
    3393        2611 :     FlushMetadata();
    3394             : 
    3395        2611 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3396             :     {
    3397             :         // Needed again as above IFlushCacheWithErrCode()
    3398             :         // may have call GDALGeoPackageRasterBand::InvalidateStatistics()
    3399             :         // which modifies metadata
    3400        2611 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3401             :     }
    3402             : 
    3403        2611 :     return eErr;
    3404             : }
    3405             : 
    3406        4846 : CPLErr GDALGeoPackageDataset::IFlushCacheWithErrCode(bool bAtClosing)
    3407             : 
    3408             : {
    3409        4846 :     if (m_bInFlushCache)
    3410        2168 :         return CE_None;
    3411        2678 :     m_bInFlushCache = true;
    3412        2678 :     if (hDB && eAccess == GA_ReadOnly && bAtClosing)
    3413             :     {
    3414             :         // Clean-up metadata that will go to PAM by removing items that
    3415             :         // are reconstructed.
    3416        1950 :         CPLStringList aosMD;
    3417        1597 :         for (CSLConstList papszIter = GetMetadata(); papszIter && *papszIter;
    3418             :              ++papszIter)
    3419             :         {
    3420         622 :             char *pszKey = nullptr;
    3421         622 :             CPLParseNameValue(*papszIter, &pszKey);
    3422        1244 :             if (pszKey &&
    3423         622 :                 (EQUAL(pszKey, "AREA_OR_POINT") ||
    3424         477 :                  EQUAL(pszKey, "IDENTIFIER") || EQUAL(pszKey, "DESCRIPTION") ||
    3425         256 :                  EQUAL(pszKey, "ZOOM_LEVEL") ||
    3426         652 :                  STARTS_WITH(pszKey, "GPKG_METADATA_ITEM_")))
    3427             :             {
    3428             :                 // remove it
    3429             :             }
    3430             :             else
    3431             :             {
    3432          30 :                 aosMD.AddString(*papszIter);
    3433             :             }
    3434         622 :             CPLFree(pszKey);
    3435             :         }
    3436         975 :         oMDMD.SetMetadata(aosMD.List());
    3437         975 :         oMDMD.SetMetadata(nullptr, "IMAGE_STRUCTURE");
    3438             : 
    3439        1950 :         GDALPamDataset::FlushCache(bAtClosing);
    3440             :     }
    3441             :     else
    3442             :     {
    3443             :         // Short circuit GDALPamDataset to avoid serialization to .aux.xml
    3444        1703 :         GDALDataset::FlushCache(bAtClosing);
    3445             :     }
    3446             : 
    3447        6617 :     for (auto &poLayer : m_apoLayers)
    3448             :     {
    3449        3939 :         poLayer->RunDeferredCreationIfNecessary();
    3450        3939 :         poLayer->CreateSpatialIndexIfNecessary();
    3451             :     }
    3452             : 
    3453             :     // Update raster table last_change column in gpkg_contents if needed
    3454        2678 :     if (m_bHasModifiedTiles)
    3455             :     {
    3456         536 :         for (int i = 1; i <= nBands; ++i)
    3457             :         {
    3458             :             auto poBand =
    3459         357 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    3460         357 :             if (!poBand->HaveStatsMetadataBeenSetInThisSession())
    3461             :             {
    3462         344 :                 poBand->InvalidateStatistics();
    3463         344 :                 if (psPam && psPam->pszPamFilename)
    3464         344 :                     VSIUnlink(psPam->pszPamFilename);
    3465             :             }
    3466             :         }
    3467             : 
    3468         179 :         UpdateGpkgContentsLastChange(m_osRasterTable);
    3469             : 
    3470         179 :         m_bHasModifiedTiles = false;
    3471             :     }
    3472             : 
    3473        2678 :     CPLErr eErr = FlushTiles();
    3474             : 
    3475        2678 :     m_bInFlushCache = false;
    3476        2678 :     return eErr;
    3477             : }
    3478             : 
    3479             : /************************************************************************/
    3480             : /*                       GetCurrentDateEscapedSQL()                      */
    3481             : /************************************************************************/
    3482             : 
    3483        1901 : std::string GDALGeoPackageDataset::GetCurrentDateEscapedSQL()
    3484             : {
    3485             :     const char *pszCurrentDate =
    3486        1901 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3487        1901 :     if (pszCurrentDate)
    3488          10 :         return '\'' + SQLEscapeLiteral(pszCurrentDate) + '\'';
    3489        1896 :     return "strftime('%Y-%m-%dT%H:%M:%fZ','now')";
    3490             : }
    3491             : 
    3492             : /************************************************************************/
    3493             : /*                    UpdateGpkgContentsLastChange()                    */
    3494             : /************************************************************************/
    3495             : 
    3496             : OGRErr
    3497         820 : GDALGeoPackageDataset::UpdateGpkgContentsLastChange(const char *pszTableName)
    3498             : {
    3499             :     char *pszSQL =
    3500         820 :         sqlite3_mprintf("UPDATE gpkg_contents SET "
    3501             :                         "last_change = %s "
    3502             :                         "WHERE lower(table_name) = lower('%q')",
    3503        1640 :                         GetCurrentDateEscapedSQL().c_str(), pszTableName);
    3504         820 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    3505         820 :     sqlite3_free(pszSQL);
    3506         820 :     return eErr;
    3507             : }
    3508             : 
    3509             : /************************************************************************/
    3510             : /*                          IBuildOverviews()                           */
    3511             : /************************************************************************/
    3512             : 
    3513          20 : CPLErr GDALGeoPackageDataset::IBuildOverviews(
    3514             :     const char *pszResampling, int nOverviews, const int *panOverviewList,
    3515             :     int nBandsIn, const int * /*panBandList*/, GDALProgressFunc pfnProgress,
    3516             :     void *pProgressData, CSLConstList papszOptions)
    3517             : {
    3518          20 :     if (GetAccess() != GA_Update)
    3519             :     {
    3520           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3521             :                  "Overview building not supported on a database opened in "
    3522             :                  "read-only mode");
    3523           1 :         return CE_Failure;
    3524             :     }
    3525          19 :     if (m_poParentDS != nullptr)
    3526             :     {
    3527           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3528             :                  "Overview building not supported on overview dataset");
    3529           1 :         return CE_Failure;
    3530             :     }
    3531             : 
    3532          18 :     if (nOverviews == 0)
    3533             :     {
    3534           5 :         for (auto &poOvrDS : m_apoOverviewDS)
    3535           3 :             poOvrDS->FlushCache(false);
    3536             : 
    3537           2 :         SoftStartTransaction();
    3538             : 
    3539           2 :         if (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    3540             :         {
    3541           1 :             char *pszSQL = sqlite3_mprintf(
    3542             :                 "DELETE FROM gpkg_2d_gridded_tile_ancillary WHERE id IN "
    3543             :                 "(SELECT y.id FROM \"%w\" x "
    3544             :                 "JOIN gpkg_2d_gridded_tile_ancillary y "
    3545             :                 "ON x.id = y.tpudt_id AND y.tpudt_name = '%q' AND "
    3546             :                 "x.zoom_level < %d)",
    3547             :                 m_osRasterTable.c_str(), m_osRasterTable.c_str(), m_nZoomLevel);
    3548           1 :             OGRErr eErr = SQLCommand(hDB, pszSQL);
    3549           1 :             sqlite3_free(pszSQL);
    3550           1 :             if (eErr != OGRERR_NONE)
    3551             :             {
    3552           0 :                 SoftRollbackTransaction();
    3553           0 :                 return CE_Failure;
    3554             :             }
    3555             :         }
    3556             : 
    3557             :         char *pszSQL =
    3558           2 :             sqlite3_mprintf("DELETE FROM \"%w\" WHERE zoom_level < %d",
    3559             :                             m_osRasterTable.c_str(), m_nZoomLevel);
    3560           2 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3561           2 :         sqlite3_free(pszSQL);
    3562           2 :         if (eErr != OGRERR_NONE)
    3563             :         {
    3564           0 :             SoftRollbackTransaction();
    3565           0 :             return CE_Failure;
    3566             :         }
    3567             : 
    3568           2 :         SoftCommitTransaction();
    3569             : 
    3570           2 :         return CE_None;
    3571             :     }
    3572             : 
    3573          16 :     if (nBandsIn != nBands)
    3574             :     {
    3575           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3576             :                  "Generation of overviews in GPKG only"
    3577             :                  "supported when operating on all bands.");
    3578           0 :         return CE_Failure;
    3579             :     }
    3580             : 
    3581          16 :     if (m_apoOverviewDS.empty())
    3582             :     {
    3583           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3584             :                  "Image too small to support overviews");
    3585           0 :         return CE_Failure;
    3586             :     }
    3587             : 
    3588          16 :     FlushCache(false);
    3589          60 :     for (int i = 0; i < nOverviews; i++)
    3590             :     {
    3591          47 :         if (panOverviewList[i] < 2)
    3592             :         {
    3593           1 :             CPLError(CE_Failure, CPLE_IllegalArg,
    3594             :                      "Overview factor must be >= 2");
    3595           1 :             return CE_Failure;
    3596             :         }
    3597             : 
    3598          46 :         bool bFound = false;
    3599          46 :         int jCandidate = -1;
    3600          46 :         int nMaxOvFactor = 0;
    3601         196 :         for (int j = 0; j < static_cast<int>(m_apoOverviewDS.size()); j++)
    3602             :         {
    3603         190 :             const auto poODS = m_apoOverviewDS[j].get();
    3604             :             const int nOvFactor = static_cast<int>(
    3605         190 :                 0.5 + poODS->m_adfGeoTransform[1] / m_adfGeoTransform[1]);
    3606             : 
    3607         190 :             nMaxOvFactor = nOvFactor;
    3608             : 
    3609         190 :             if (nOvFactor == panOverviewList[i])
    3610             :             {
    3611          40 :                 bFound = true;
    3612          40 :                 break;
    3613             :             }
    3614             : 
    3615         150 :             if (jCandidate < 0 && nOvFactor > panOverviewList[i])
    3616           1 :                 jCandidate = j;
    3617             :         }
    3618             : 
    3619          46 :         if (!bFound)
    3620             :         {
    3621             :             /* Mostly for debug */
    3622           6 :             if (!CPLTestBool(CPLGetConfigOption(
    3623             :                     "ALLOW_GPKG_ZOOM_OTHER_EXTENSION", "YES")))
    3624             :             {
    3625           2 :                 CPLString osOvrList;
    3626           4 :                 for (const auto &poODS : m_apoOverviewDS)
    3627             :                 {
    3628             :                     const int nOvFactor =
    3629           2 :                         static_cast<int>(0.5 + poODS->m_adfGeoTransform[1] /
    3630           2 :                                                    m_adfGeoTransform[1]);
    3631             : 
    3632           2 :                     if (!osOvrList.empty())
    3633           0 :                         osOvrList += ' ';
    3634           2 :                     osOvrList += CPLSPrintf("%d", nOvFactor);
    3635             :                 }
    3636           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    3637             :                          "Only overviews %s can be computed",
    3638             :                          osOvrList.c_str());
    3639           2 :                 return CE_Failure;
    3640             :             }
    3641             :             else
    3642             :             {
    3643           4 :                 int nOvFactor = panOverviewList[i];
    3644           4 :                 if (jCandidate < 0)
    3645           3 :                     jCandidate = static_cast<int>(m_apoOverviewDS.size());
    3646             : 
    3647           4 :                 int nOvXSize = std::max(1, GetRasterXSize() / nOvFactor);
    3648           4 :                 int nOvYSize = std::max(1, GetRasterYSize() / nOvFactor);
    3649           4 :                 if (!(jCandidate == static_cast<int>(m_apoOverviewDS.size()) &&
    3650           5 :                       nOvFactor == 2 * nMaxOvFactor) &&
    3651           1 :                     !m_bZoomOther)
    3652             :                 {
    3653           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    3654             :                              "Use of overview factor %d causes gpkg_zoom_other "
    3655             :                              "extension to be needed",
    3656             :                              nOvFactor);
    3657           1 :                     RegisterZoomOtherExtension();
    3658           1 :                     m_bZoomOther = true;
    3659             :                 }
    3660             : 
    3661           4 :                 SoftStartTransaction();
    3662             : 
    3663           4 :                 CPLAssert(jCandidate > 0);
    3664             :                 const int nNewZoomLevel =
    3665           4 :                     m_apoOverviewDS[jCandidate - 1]->m_nZoomLevel;
    3666             : 
    3667             :                 char *pszSQL;
    3668             :                 OGRErr eErr;
    3669          24 :                 for (int k = 0; k <= jCandidate; k++)
    3670             :                 {
    3671          60 :                     pszSQL = sqlite3_mprintf(
    3672             :                         "UPDATE gpkg_tile_matrix SET zoom_level = %d "
    3673             :                         "WHERE lower(table_name) = lower('%q') AND zoom_level "
    3674             :                         "= %d",
    3675          20 :                         m_nZoomLevel - k + 1, m_osRasterTable.c_str(),
    3676          20 :                         m_nZoomLevel - k);
    3677          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3678          20 :                     sqlite3_free(pszSQL);
    3679          20 :                     if (eErr != OGRERR_NONE)
    3680             :                     {
    3681           0 :                         SoftRollbackTransaction();
    3682           0 :                         return CE_Failure;
    3683             :                     }
    3684             : 
    3685             :                     pszSQL =
    3686          20 :                         sqlite3_mprintf("UPDATE \"%w\" SET zoom_level = %d "
    3687             :                                         "WHERE zoom_level = %d",
    3688             :                                         m_osRasterTable.c_str(),
    3689          20 :                                         m_nZoomLevel - k + 1, m_nZoomLevel - k);
    3690          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3691          20 :                     sqlite3_free(pszSQL);
    3692          20 :                     if (eErr != OGRERR_NONE)
    3693             :                     {
    3694           0 :                         SoftRollbackTransaction();
    3695           0 :                         return CE_Failure;
    3696             :                     }
    3697             :                 }
    3698             : 
    3699           4 :                 double dfGDALMinX = m_adfGeoTransform[0];
    3700             :                 double dfGDALMinY =
    3701           4 :                     m_adfGeoTransform[3] + nRasterYSize * m_adfGeoTransform[5];
    3702             :                 double dfGDALMaxX =
    3703           4 :                     m_adfGeoTransform[0] + nRasterXSize * m_adfGeoTransform[1];
    3704           4 :                 double dfGDALMaxY = m_adfGeoTransform[3];
    3705           4 :                 double dfPixelXSizeZoomLevel = m_adfGeoTransform[1] * nOvFactor;
    3706             :                 double dfPixelYSizeZoomLevel =
    3707           4 :                     fabs(m_adfGeoTransform[5]) * nOvFactor;
    3708             :                 int nTileWidth, nTileHeight;
    3709           4 :                 GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3710           4 :                 int nTileMatrixWidth = DIV_ROUND_UP(nOvXSize, nTileWidth);
    3711           4 :                 int nTileMatrixHeight = DIV_ROUND_UP(nOvYSize, nTileHeight);
    3712           4 :                 pszSQL = sqlite3_mprintf(
    3713             :                     "INSERT INTO gpkg_tile_matrix "
    3714             :                     "(table_name,zoom_level,matrix_width,matrix_height,tile_"
    3715             :                     "width,tile_height,pixel_x_size,pixel_y_size) VALUES "
    3716             :                     "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3717             :                     m_osRasterTable.c_str(), nNewZoomLevel, nTileMatrixWidth,
    3718             :                     nTileMatrixHeight, nTileWidth, nTileHeight,
    3719             :                     dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel);
    3720           4 :                 eErr = SQLCommand(hDB, pszSQL);
    3721           4 :                 sqlite3_free(pszSQL);
    3722           4 :                 if (eErr != OGRERR_NONE)
    3723             :                 {
    3724           0 :                     SoftRollbackTransaction();
    3725           0 :                     return CE_Failure;
    3726             :                 }
    3727             : 
    3728           4 :                 SoftCommitTransaction();
    3729             : 
    3730           4 :                 m_nZoomLevel++; /* this change our zoom level as well as
    3731             :                                    previous overviews */
    3732          20 :                 for (int k = 0; k < jCandidate; k++)
    3733          16 :                     m_apoOverviewDS[k]->m_nZoomLevel++;
    3734             : 
    3735           4 :                 auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3736           4 :                 poOvrDS->ShareLockWithParentDataset(this);
    3737           4 :                 poOvrDS->InitRaster(
    3738             :                     this, m_osRasterTable, nNewZoomLevel, nBands, m_dfTMSMinX,
    3739             :                     m_dfTMSMaxY, dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel,
    3740             :                     nTileWidth, nTileHeight, nTileMatrixWidth,
    3741             :                     nTileMatrixHeight, dfGDALMinX, dfGDALMinY, dfGDALMaxX,
    3742             :                     dfGDALMaxY);
    3743           4 :                 m_apoOverviewDS.insert(m_apoOverviewDS.begin() + jCandidate,
    3744           8 :                                        std::move(poOvrDS));
    3745             :             }
    3746             :         }
    3747             :     }
    3748             : 
    3749             :     GDALRasterBand ***papapoOverviewBands = static_cast<GDALRasterBand ***>(
    3750          13 :         CPLCalloc(sizeof(GDALRasterBand **), nBands));
    3751          13 :     CPLErr eErr = CE_None;
    3752          49 :     for (int iBand = 0; eErr == CE_None && iBand < nBands; iBand++)
    3753             :     {
    3754          72 :         papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
    3755          36 :             CPLCalloc(sizeof(GDALRasterBand *), nOverviews));
    3756          36 :         int iCurOverview = 0;
    3757         185 :         for (int i = 0; i < nOverviews; i++)
    3758             :         {
    3759         149 :             bool bFound = false;
    3760         724 :             for (const auto &poODS : m_apoOverviewDS)
    3761             :             {
    3762             :                 const int nOvFactor = static_cast<int>(
    3763         724 :                     0.5 + poODS->m_adfGeoTransform[1] / m_adfGeoTransform[1]);
    3764             : 
    3765         724 :                 if (nOvFactor == panOverviewList[i])
    3766             :                 {
    3767         298 :                     papapoOverviewBands[iBand][iCurOverview] =
    3768         149 :                         poODS->GetRasterBand(iBand + 1);
    3769         149 :                     iCurOverview++;
    3770         149 :                     bFound = true;
    3771         149 :                     break;
    3772             :                 }
    3773             :             }
    3774         149 :             if (!bFound)
    3775             :             {
    3776           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3777             :                          "Could not find dataset corresponding to ov factor %d",
    3778           0 :                          panOverviewList[i]);
    3779           0 :                 eErr = CE_Failure;
    3780             :             }
    3781             :         }
    3782          36 :         if (eErr == CE_None)
    3783             :         {
    3784          36 :             CPLAssert(iCurOverview == nOverviews);
    3785             :         }
    3786             :     }
    3787             : 
    3788          13 :     if (eErr == CE_None)
    3789          13 :         eErr = GDALRegenerateOverviewsMultiBand(
    3790          13 :             nBands, papoBands, nOverviews, papapoOverviewBands, pszResampling,
    3791             :             pfnProgress, pProgressData, papszOptions);
    3792             : 
    3793          49 :     for (int iBand = 0; iBand < nBands; iBand++)
    3794             :     {
    3795          36 :         CPLFree(papapoOverviewBands[iBand]);
    3796             :     }
    3797          13 :     CPLFree(papapoOverviewBands);
    3798             : 
    3799          13 :     return eErr;
    3800             : }
    3801             : 
    3802             : /************************************************************************/
    3803             : /*                            GetFileList()                             */
    3804             : /************************************************************************/
    3805             : 
    3806          36 : char **GDALGeoPackageDataset::GetFileList()
    3807             : {
    3808          36 :     TryLoadXML();
    3809          36 :     return GDALPamDataset::GetFileList();
    3810             : }
    3811             : 
    3812             : /************************************************************************/
    3813             : /*                      GetMetadataDomainList()                         */
    3814             : /************************************************************************/
    3815             : 
    3816          47 : char **GDALGeoPackageDataset::GetMetadataDomainList()
    3817             : {
    3818          47 :     GetMetadata();
    3819          47 :     if (!m_osRasterTable.empty())
    3820           5 :         GetMetadata("GEOPACKAGE");
    3821          47 :     return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
    3822          47 :                                    TRUE, "SUBDATASETS", nullptr);
    3823             : }
    3824             : 
    3825             : /************************************************************************/
    3826             : /*                        CheckMetadataDomain()                         */
    3827             : /************************************************************************/
    3828             : 
    3829        5240 : const char *GDALGeoPackageDataset::CheckMetadataDomain(const char *pszDomain)
    3830             : {
    3831        5423 :     if (pszDomain != nullptr && EQUAL(pszDomain, "GEOPACKAGE") &&
    3832         183 :         m_osRasterTable.empty())
    3833             :     {
    3834           4 :         CPLError(
    3835             :             CE_Warning, CPLE_IllegalArg,
    3836             :             "Using GEOPACKAGE for a non-raster geopackage is not supported. "
    3837             :             "Using default domain instead");
    3838           4 :         return nullptr;
    3839             :     }
    3840        5236 :     return pszDomain;
    3841             : }
    3842             : 
    3843             : /************************************************************************/
    3844             : /*                           HasMetadataTables()                        */
    3845             : /************************************************************************/
    3846             : 
    3847        5329 : bool GDALGeoPackageDataset::HasMetadataTables() const
    3848             : {
    3849        5329 :     if (m_nHasMetadataTables < 0)
    3850             :     {
    3851             :         const int nCount =
    3852        1980 :             SQLGetInteger(hDB,
    3853             :                           "SELECT COUNT(*) FROM sqlite_master WHERE name IN "
    3854             :                           "('gpkg_metadata', 'gpkg_metadata_reference') "
    3855             :                           "AND type IN ('table', 'view')",
    3856             :                           nullptr);
    3857        1980 :         m_nHasMetadataTables = nCount == 2;
    3858             :     }
    3859        5329 :     return CPL_TO_BOOL(m_nHasMetadataTables);
    3860             : }
    3861             : 
    3862             : /************************************************************************/
    3863             : /*                         HasDataColumnsTable()                        */
    3864             : /************************************************************************/
    3865             : 
    3866        1180 : bool GDALGeoPackageDataset::HasDataColumnsTable() const
    3867             : {
    3868        2360 :     const int nCount = SQLGetInteger(
    3869        1180 :         hDB,
    3870             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_data_columns'"
    3871             :         "AND type IN ('table', 'view')",
    3872             :         nullptr);
    3873        1180 :     return nCount == 1;
    3874             : }
    3875             : 
    3876             : /************************************************************************/
    3877             : /*                    HasDataColumnConstraintsTable()                   */
    3878             : /************************************************************************/
    3879             : 
    3880         120 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTable() const
    3881             : {
    3882         120 :     const int nCount = SQLGetInteger(hDB,
    3883             :                                      "SELECT 1 FROM sqlite_master WHERE name = "
    3884             :                                      "'gpkg_data_column_constraints'"
    3885             :                                      "AND type IN ('table', 'view')",
    3886             :                                      nullptr);
    3887         120 :     return nCount == 1;
    3888             : }
    3889             : 
    3890             : /************************************************************************/
    3891             : /*                  HasDataColumnConstraintsTableGPKG_1_0()             */
    3892             : /************************************************************************/
    3893             : 
    3894          73 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTableGPKG_1_0() const
    3895             : {
    3896          73 :     if (m_nApplicationId != GP10_APPLICATION_ID)
    3897          71 :         return false;
    3898             :     // In GPKG 1.0, the columns were named minIsInclusive, maxIsInclusive
    3899             :     // They were changed in 1.1 to min_is_inclusive, max_is_inclusive
    3900           2 :     bool bRet = false;
    3901           2 :     sqlite3_stmt *hSQLStmt = nullptr;
    3902           2 :     int rc = sqlite3_prepare_v2(hDB,
    3903             :                                 "SELECT minIsInclusive, maxIsInclusive FROM "
    3904             :                                 "gpkg_data_column_constraints",
    3905             :                                 -1, &hSQLStmt, nullptr);
    3906           2 :     if (rc == SQLITE_OK)
    3907             :     {
    3908           2 :         bRet = true;
    3909           2 :         sqlite3_finalize(hSQLStmt);
    3910             :     }
    3911           2 :     return bRet;
    3912             : }
    3913             : 
    3914             : /************************************************************************/
    3915             : /*      CreateColumnsTableAndColumnConstraintsTablesIfNecessary()       */
    3916             : /************************************************************************/
    3917             : 
    3918          49 : bool GDALGeoPackageDataset::
    3919             :     CreateColumnsTableAndColumnConstraintsTablesIfNecessary()
    3920             : {
    3921          49 :     if (!HasDataColumnsTable())
    3922             :     {
    3923             :         // Geopackage < 1.3 had
    3924             :         // CONSTRAINT fk_gdc_tn FOREIGN KEY (table_name) REFERENCES
    3925             :         // gpkg_contents(table_name) instead of the unique constraint.
    3926          10 :         if (OGRERR_NONE !=
    3927          10 :             SQLCommand(
    3928             :                 GetDB(),
    3929             :                 "CREATE TABLE gpkg_data_columns ("
    3930             :                 "table_name TEXT NOT NULL,"
    3931             :                 "column_name TEXT NOT NULL,"
    3932             :                 "name TEXT,"
    3933             :                 "title TEXT,"
    3934             :                 "description TEXT,"
    3935             :                 "mime_type TEXT,"
    3936             :                 "constraint_name TEXT,"
    3937             :                 "CONSTRAINT pk_gdc PRIMARY KEY (table_name, column_name),"
    3938             :                 "CONSTRAINT gdc_tn UNIQUE (table_name, name));"))
    3939             :         {
    3940           0 :             return false;
    3941             :         }
    3942             :     }
    3943          49 :     if (!HasDataColumnConstraintsTable())
    3944             :     {
    3945          22 :         const char *min_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3946          11 :                                            ? "min_is_inclusive"
    3947             :                                            : "minIsInclusive";
    3948          22 :         const char *max_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3949          11 :                                            ? "max_is_inclusive"
    3950             :                                            : "maxIsInclusive";
    3951             : 
    3952             :         const std::string osSQL(
    3953             :             CPLSPrintf("CREATE TABLE gpkg_data_column_constraints ("
    3954             :                        "constraint_name TEXT NOT NULL,"
    3955             :                        "constraint_type TEXT NOT NULL,"
    3956             :                        "value TEXT,"
    3957             :                        "min NUMERIC,"
    3958             :                        "%s BOOLEAN,"
    3959             :                        "max NUMERIC,"
    3960             :                        "%s BOOLEAN,"
    3961             :                        "description TEXT,"
    3962             :                        "CONSTRAINT gdcc_ntv UNIQUE (constraint_name, "
    3963             :                        "constraint_type, value));",
    3964          11 :                        min_is_inclusive, max_is_inclusive));
    3965          11 :         if (OGRERR_NONE != SQLCommand(GetDB(), osSQL.c_str()))
    3966             :         {
    3967           0 :             return false;
    3968             :         }
    3969             :     }
    3970          49 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    3971             :     {
    3972           0 :         return false;
    3973             :     }
    3974          49 :     if (SQLGetInteger(GetDB(),
    3975             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3976             :                       "table_name = 'gpkg_data_columns'",
    3977          49 :                       nullptr) != 1)
    3978             :     {
    3979          11 :         if (OGRERR_NONE !=
    3980          11 :             SQLCommand(
    3981             :                 GetDB(),
    3982             :                 "INSERT INTO gpkg_extensions "
    3983             :                 "(table_name,column_name,extension_name,definition,scope) "
    3984             :                 "VALUES ('gpkg_data_columns', NULL, 'gpkg_schema', "
    3985             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    3986             :                 "'read-write')"))
    3987             :         {
    3988           0 :             return false;
    3989             :         }
    3990             :     }
    3991          49 :     if (SQLGetInteger(GetDB(),
    3992             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3993             :                       "table_name = 'gpkg_data_column_constraints'",
    3994          49 :                       nullptr) != 1)
    3995             :     {
    3996          11 :         if (OGRERR_NONE !=
    3997          11 :             SQLCommand(
    3998             :                 GetDB(),
    3999             :                 "INSERT INTO gpkg_extensions "
    4000             :                 "(table_name,column_name,extension_name,definition,scope) "
    4001             :                 "VALUES ('gpkg_data_column_constraints', NULL, 'gpkg_schema', "
    4002             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    4003             :                 "'read-write')"))
    4004             :         {
    4005           0 :             return false;
    4006             :         }
    4007             :     }
    4008             : 
    4009          49 :     return true;
    4010             : }
    4011             : 
    4012             : /************************************************************************/
    4013             : /*                        HasGpkgextRelationsTable()                    */
    4014             : /************************************************************************/
    4015             : 
    4016        1176 : bool GDALGeoPackageDataset::HasGpkgextRelationsTable() const
    4017             : {
    4018        2352 :     const int nCount = SQLGetInteger(
    4019        1176 :         hDB,
    4020             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkgext_relations'"
    4021             :         "AND type IN ('table', 'view')",
    4022             :         nullptr);
    4023        1176 :     return nCount == 1;
    4024             : }
    4025             : 
    4026             : /************************************************************************/
    4027             : /*                    CreateRelationsTableIfNecessary()                 */
    4028             : /************************************************************************/
    4029             : 
    4030           9 : bool GDALGeoPackageDataset::CreateRelationsTableIfNecessary()
    4031             : {
    4032           9 :     if (HasGpkgextRelationsTable())
    4033             :     {
    4034           5 :         return true;
    4035             :     }
    4036             : 
    4037           4 :     if (OGRERR_NONE !=
    4038           4 :         SQLCommand(GetDB(), "CREATE TABLE gpkgext_relations ("
    4039             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    4040             :                             "base_table_name TEXT NOT NULL,"
    4041             :                             "base_primary_column TEXT NOT NULL DEFAULT 'id',"
    4042             :                             "related_table_name TEXT NOT NULL,"
    4043             :                             "related_primary_column TEXT NOT NULL DEFAULT 'id',"
    4044             :                             "relation_name TEXT NOT NULL,"
    4045             :                             "mapping_table_name TEXT NOT NULL UNIQUE);"))
    4046             :     {
    4047           0 :         return false;
    4048             :     }
    4049             : 
    4050           4 :     return true;
    4051             : }
    4052             : 
    4053             : /************************************************************************/
    4054             : /*                        HasQGISLayerStyles()                          */
    4055             : /************************************************************************/
    4056             : 
    4057          11 : bool GDALGeoPackageDataset::HasQGISLayerStyles() const
    4058             : {
    4059             :     // QGIS layer_styles extension:
    4060             :     // https://github.com/pka/qgpkg/blob/master/qgis_geopackage_extension.md
    4061          11 :     bool bRet = false;
    4062             :     const int nCount =
    4063          11 :         SQLGetInteger(hDB,
    4064             :                       "SELECT 1 FROM sqlite_master WHERE name = 'layer_styles'"
    4065             :                       "AND type = 'table'",
    4066             :                       nullptr);
    4067          11 :     if (nCount == 1)
    4068             :     {
    4069           1 :         sqlite3_stmt *hSQLStmt = nullptr;
    4070           2 :         int rc = sqlite3_prepare_v2(
    4071           1 :             hDB, "SELECT f_table_name, f_geometry_column FROM layer_styles", -1,
    4072             :             &hSQLStmt, nullptr);
    4073           1 :         if (rc == SQLITE_OK)
    4074             :         {
    4075           1 :             bRet = true;
    4076           1 :             sqlite3_finalize(hSQLStmt);
    4077             :         }
    4078             :     }
    4079          11 :     return bRet;
    4080             : }
    4081             : 
    4082             : /************************************************************************/
    4083             : /*                            GetMetadata()                             */
    4084             : /************************************************************************/
    4085             : 
    4086        3523 : char **GDALGeoPackageDataset::GetMetadata(const char *pszDomain)
    4087             : 
    4088             : {
    4089        3523 :     pszDomain = CheckMetadataDomain(pszDomain);
    4090        3523 :     if (pszDomain != nullptr && EQUAL(pszDomain, "SUBDATASETS"))
    4091          67 :         return m_aosSubDatasets.List();
    4092             : 
    4093        3456 :     if (m_bHasReadMetadataFromStorage)
    4094        1532 :         return GDALPamDataset::GetMetadata(pszDomain);
    4095             : 
    4096        1924 :     m_bHasReadMetadataFromStorage = true;
    4097             : 
    4098        1924 :     TryLoadXML();
    4099             : 
    4100        1924 :     if (!HasMetadataTables())
    4101        1418 :         return GDALPamDataset::GetMetadata(pszDomain);
    4102             : 
    4103         506 :     char *pszSQL = nullptr;
    4104         506 :     if (!m_osRasterTable.empty())
    4105             :     {
    4106         169 :         pszSQL = sqlite3_mprintf(
    4107             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4108             :             "mdr.reference_scope FROM gpkg_metadata md "
    4109             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4110             :             "WHERE "
    4111             :             "(mdr.reference_scope = 'geopackage' OR "
    4112             :             "(mdr.reference_scope = 'table' AND lower(mdr.table_name) = "
    4113             :             "lower('%q'))) ORDER BY md.id "
    4114             :             "LIMIT 1000",  // to avoid denial of service
    4115             :             m_osRasterTable.c_str());
    4116             :     }
    4117             :     else
    4118             :     {
    4119         337 :         pszSQL = sqlite3_mprintf(
    4120             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4121             :             "mdr.reference_scope FROM gpkg_metadata md "
    4122             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4123             :             "WHERE "
    4124             :             "mdr.reference_scope = 'geopackage' ORDER BY md.id "
    4125             :             "LIMIT 1000"  // to avoid denial of service
    4126             :         );
    4127             :     }
    4128             : 
    4129        1012 :     auto oResult = SQLQuery(hDB, pszSQL);
    4130         506 :     sqlite3_free(pszSQL);
    4131         506 :     if (!oResult)
    4132             :     {
    4133           0 :         return GDALPamDataset::GetMetadata(pszDomain);
    4134             :     }
    4135             : 
    4136         506 :     char **papszMetadata = CSLDuplicate(GDALPamDataset::GetMetadata());
    4137             : 
    4138             :     /* GDAL metadata */
    4139         695 :     for (int i = 0; i < oResult->RowCount(); i++)
    4140             :     {
    4141         189 :         const char *pszMetadata = oResult->GetValue(0, i);
    4142         189 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4143         189 :         const char *pszMimeType = oResult->GetValue(2, i);
    4144         189 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4145         189 :         if (pszMetadata && pszMDStandardURI && pszMimeType &&
    4146         189 :             pszReferenceScope && EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4147         173 :             EQUAL(pszMimeType, "text/xml"))
    4148             :         {
    4149         173 :             CPLXMLNode *psXMLNode = CPLParseXMLString(pszMetadata);
    4150         173 :             if (psXMLNode)
    4151             :             {
    4152         346 :                 GDALMultiDomainMetadata oLocalMDMD;
    4153         173 :                 oLocalMDMD.XMLInit(psXMLNode, FALSE);
    4154         331 :                 if (!m_osRasterTable.empty() &&
    4155         158 :                     EQUAL(pszReferenceScope, "geopackage"))
    4156             :                 {
    4157           6 :                     oMDMD.SetMetadata(oLocalMDMD.GetMetadata(), "GEOPACKAGE");
    4158             :                 }
    4159             :                 else
    4160             :                 {
    4161             :                     papszMetadata =
    4162         167 :                         CSLMerge(papszMetadata, oLocalMDMD.GetMetadata());
    4163         167 :                     CSLConstList papszDomainList = oLocalMDMD.GetDomainList();
    4164         167 :                     CSLConstList papszIter = papszDomainList;
    4165         444 :                     while (papszIter && *papszIter)
    4166             :                     {
    4167         277 :                         if (EQUAL(*papszIter, "IMAGE_STRUCTURE"))
    4168             :                         {
    4169             :                             CSLConstList papszMD =
    4170         125 :                                 oLocalMDMD.GetMetadata(*papszIter);
    4171             :                             const char *pszBAND_COUNT =
    4172         125 :                                 CSLFetchNameValue(papszMD, "BAND_COUNT");
    4173         125 :                             if (pszBAND_COUNT)
    4174         123 :                                 m_nBandCountFromMetadata = atoi(pszBAND_COUNT);
    4175             : 
    4176             :                             const char *pszCOLOR_TABLE =
    4177         125 :                                 CSLFetchNameValue(papszMD, "COLOR_TABLE");
    4178         125 :                             if (pszCOLOR_TABLE)
    4179             :                             {
    4180             :                                 const CPLStringList aosTokens(
    4181             :                                     CSLTokenizeString2(pszCOLOR_TABLE, "{,",
    4182          26 :                                                        0));
    4183          13 :                                 if ((aosTokens.size() % 4) == 0)
    4184             :                                 {
    4185          13 :                                     const int nColors = aosTokens.size() / 4;
    4186             :                                     m_poCTFromMetadata =
    4187          13 :                                         std::make_unique<GDALColorTable>();
    4188        3341 :                                     for (int iColor = 0; iColor < nColors;
    4189             :                                          ++iColor)
    4190             :                                     {
    4191             :                                         GDALColorEntry sEntry;
    4192        3328 :                                         sEntry.c1 = static_cast<short>(
    4193        3328 :                                             atoi(aosTokens[4 * iColor + 0]));
    4194        3328 :                                         sEntry.c2 = static_cast<short>(
    4195        3328 :                                             atoi(aosTokens[4 * iColor + 1]));
    4196        3328 :                                         sEntry.c3 = static_cast<short>(
    4197        3328 :                                             atoi(aosTokens[4 * iColor + 2]));
    4198        3328 :                                         sEntry.c4 = static_cast<short>(
    4199        3328 :                                             atoi(aosTokens[4 * iColor + 3]));
    4200        3328 :                                         m_poCTFromMetadata->SetColorEntry(
    4201             :                                             iColor, &sEntry);
    4202             :                                     }
    4203             :                                 }
    4204             :                             }
    4205             : 
    4206             :                             const char *pszTILE_FORMAT =
    4207         125 :                                 CSLFetchNameValue(papszMD, "TILE_FORMAT");
    4208         125 :                             if (pszTILE_FORMAT)
    4209             :                             {
    4210           8 :                                 m_osTFFromMetadata = pszTILE_FORMAT;
    4211           8 :                                 oMDMD.SetMetadataItem("TILE_FORMAT",
    4212             :                                                       pszTILE_FORMAT,
    4213             :                                                       "IMAGE_STRUCTURE");
    4214             :                             }
    4215             : 
    4216             :                             const char *pszNodataValue =
    4217         125 :                                 CSLFetchNameValue(papszMD, "NODATA_VALUE");
    4218         125 :                             if (pszNodataValue)
    4219             :                             {
    4220           2 :                                 m_osNodataValueFromMetadata = pszNodataValue;
    4221             :                             }
    4222             :                         }
    4223             : 
    4224         152 :                         else if (!EQUAL(*papszIter, "") &&
    4225          16 :                                  !STARTS_WITH(*papszIter, "BAND_"))
    4226             :                         {
    4227          12 :                             oMDMD.SetMetadata(
    4228           6 :                                 oLocalMDMD.GetMetadata(*papszIter), *papszIter);
    4229             :                         }
    4230         277 :                         papszIter++;
    4231             :                     }
    4232             :                 }
    4233         173 :                 CPLDestroyXMLNode(psXMLNode);
    4234             :             }
    4235             :         }
    4236             :     }
    4237             : 
    4238         506 :     GDALPamDataset::SetMetadata(papszMetadata);
    4239         506 :     CSLDestroy(papszMetadata);
    4240         506 :     papszMetadata = nullptr;
    4241             : 
    4242             :     /* Add non-GDAL metadata now */
    4243         506 :     int nNonGDALMDILocal = 1;
    4244         506 :     int nNonGDALMDIGeopackage = 1;
    4245         695 :     for (int i = 0; i < oResult->RowCount(); i++)
    4246             :     {
    4247         189 :         const char *pszMetadata = oResult->GetValue(0, i);
    4248         189 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4249         189 :         const char *pszMimeType = oResult->GetValue(2, i);
    4250         189 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4251         189 :         if (pszMetadata == nullptr || pszMDStandardURI == nullptr ||
    4252         189 :             pszMimeType == nullptr || pszReferenceScope == nullptr)
    4253             :         {
    4254             :             // should not happen as there are NOT NULL constraints
    4255             :             // But a database could lack such NOT NULL constraints or have
    4256             :             // large values that would cause a memory allocation failure.
    4257           0 :             continue;
    4258             :         }
    4259         189 :         int bIsGPKGScope = EQUAL(pszReferenceScope, "geopackage");
    4260         189 :         if (EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4261         173 :             EQUAL(pszMimeType, "text/xml"))
    4262         173 :             continue;
    4263             : 
    4264          16 :         if (!m_osRasterTable.empty() && bIsGPKGScope)
    4265             :         {
    4266           8 :             oMDMD.SetMetadataItem(
    4267             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDIGeopackage),
    4268             :                 pszMetadata, "GEOPACKAGE");
    4269           8 :             nNonGDALMDIGeopackage++;
    4270             :         }
    4271             :         /*else if( strcmp( pszMDStandardURI, "http://www.isotc211.org/2005/gmd"
    4272             :         ) == 0 && strcmp( pszMimeType, "text/xml" ) == 0 )
    4273             :         {
    4274             :             char* apszMD[2];
    4275             :             apszMD[0] = (char*)pszMetadata;
    4276             :             apszMD[1] = NULL;
    4277             :             oMDMD.SetMetadata(apszMD, "xml:MD_Metadata");
    4278             :         }*/
    4279             :         else
    4280             :         {
    4281           8 :             oMDMD.SetMetadataItem(
    4282             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDILocal),
    4283             :                 pszMetadata);
    4284           8 :             nNonGDALMDILocal++;
    4285             :         }
    4286             :     }
    4287             : 
    4288         506 :     return GDALPamDataset::GetMetadata(pszDomain);
    4289             : }
    4290             : 
    4291             : /************************************************************************/
    4292             : /*                            WriteMetadata()                           */
    4293             : /************************************************************************/
    4294             : 
    4295         744 : void GDALGeoPackageDataset::WriteMetadata(
    4296             :     CPLXMLNode *psXMLNode, /* will be destroyed by the method */
    4297             :     const char *pszTableName)
    4298             : {
    4299         744 :     const bool bIsEmpty = (psXMLNode == nullptr);
    4300         744 :     if (!HasMetadataTables())
    4301             :     {
    4302         536 :         if (bIsEmpty || !CreateMetadataTables())
    4303             :         {
    4304         255 :             CPLDestroyXMLNode(psXMLNode);
    4305         255 :             return;
    4306             :         }
    4307             :     }
    4308             : 
    4309         489 :     char *pszXML = nullptr;
    4310         489 :     if (!bIsEmpty)
    4311             :     {
    4312             :         CPLXMLNode *psMasterXMLNode =
    4313         328 :             CPLCreateXMLNode(nullptr, CXT_Element, "GDALMultiDomainMetadata");
    4314         328 :         psMasterXMLNode->psChild = psXMLNode;
    4315         328 :         pszXML = CPLSerializeXMLTree(psMasterXMLNode);
    4316         328 :         CPLDestroyXMLNode(psMasterXMLNode);
    4317             :     }
    4318             :     // cppcheck-suppress uselessAssignmentPtrArg
    4319         489 :     psXMLNode = nullptr;
    4320             : 
    4321         489 :     char *pszSQL = nullptr;
    4322         489 :     if (pszTableName && pszTableName[0] != '\0')
    4323             :     {
    4324         341 :         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 = 'table' AND "
    4330             :             "lower(mdr.table_name) = lower('%q')",
    4331             :             pszTableName);
    4332             :     }
    4333             :     else
    4334             :     {
    4335         148 :         pszSQL = sqlite3_mprintf(
    4336             :             "SELECT md.id FROM gpkg_metadata md "
    4337             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4338             :             "WHERE md.md_scope = 'dataset' AND "
    4339             :             "md.md_standard_uri='http://gdal.org' "
    4340             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = "
    4341             :             "'geopackage'");
    4342             :     }
    4343             :     OGRErr err;
    4344         489 :     int mdId = SQLGetInteger(hDB, pszSQL, &err);
    4345         489 :     if (err != OGRERR_NONE)
    4346         457 :         mdId = -1;
    4347         489 :     sqlite3_free(pszSQL);
    4348             : 
    4349         489 :     if (bIsEmpty)
    4350             :     {
    4351         161 :         if (mdId >= 0)
    4352             :         {
    4353           6 :             SQLCommand(
    4354             :                 hDB,
    4355             :                 CPLSPrintf(
    4356             :                     "DELETE FROM gpkg_metadata_reference WHERE md_file_id = %d",
    4357             :                     mdId));
    4358           6 :             SQLCommand(
    4359             :                 hDB,
    4360             :                 CPLSPrintf("DELETE FROM gpkg_metadata WHERE id = %d", mdId));
    4361             :         }
    4362             :     }
    4363             :     else
    4364             :     {
    4365         328 :         if (mdId >= 0)
    4366             :         {
    4367          26 :             pszSQL = sqlite3_mprintf(
    4368             :                 "UPDATE gpkg_metadata SET metadata = '%q' WHERE id = %d",
    4369             :                 pszXML, mdId);
    4370             :         }
    4371             :         else
    4372             :         {
    4373             :             pszSQL =
    4374         302 :                 sqlite3_mprintf("INSERT INTO gpkg_metadata (md_scope, "
    4375             :                                 "md_standard_uri, mime_type, metadata) VALUES "
    4376             :                                 "('dataset','http://gdal.org','text/xml','%q')",
    4377             :                                 pszXML);
    4378             :         }
    4379         328 :         SQLCommand(hDB, pszSQL);
    4380         328 :         sqlite3_free(pszSQL);
    4381             : 
    4382         328 :         CPLFree(pszXML);
    4383             : 
    4384         328 :         if (mdId < 0)
    4385             :         {
    4386         302 :             const sqlite_int64 nFID = sqlite3_last_insert_rowid(hDB);
    4387         302 :             if (pszTableName != nullptr && pszTableName[0] != '\0')
    4388             :             {
    4389         290 :                 pszSQL = sqlite3_mprintf(
    4390             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4391             :                     "table_name, timestamp, md_file_id) VALUES "
    4392             :                     "('table', '%q', %s, %d)",
    4393         580 :                     pszTableName, GetCurrentDateEscapedSQL().c_str(),
    4394             :                     static_cast<int>(nFID));
    4395             :             }
    4396             :             else
    4397             :             {
    4398          12 :                 pszSQL = sqlite3_mprintf(
    4399             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4400             :                     "timestamp, md_file_id) VALUES "
    4401             :                     "('geopackage', %s, %d)",
    4402          24 :                     GetCurrentDateEscapedSQL().c_str(), static_cast<int>(nFID));
    4403             :             }
    4404             :         }
    4405             :         else
    4406             :         {
    4407          26 :             pszSQL = sqlite3_mprintf("UPDATE gpkg_metadata_reference SET "
    4408             :                                      "timestamp = %s WHERE md_file_id = %d",
    4409          52 :                                      GetCurrentDateEscapedSQL().c_str(), mdId);
    4410             :         }
    4411         328 :         SQLCommand(hDB, pszSQL);
    4412         328 :         sqlite3_free(pszSQL);
    4413             :     }
    4414             : }
    4415             : 
    4416             : /************************************************************************/
    4417             : /*                        CreateMetadataTables()                        */
    4418             : /************************************************************************/
    4419             : 
    4420         299 : bool GDALGeoPackageDataset::CreateMetadataTables()
    4421             : {
    4422             :     const bool bCreateTriggers =
    4423         299 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "NO"));
    4424             : 
    4425             :     /* From C.10. gpkg_metadata Table 35. gpkg_metadata Table Definition SQL  */
    4426             :     CPLString osSQL = "CREATE TABLE gpkg_metadata ("
    4427             :                       "id INTEGER CONSTRAINT m_pk PRIMARY KEY ASC NOT NULL,"
    4428             :                       "md_scope TEXT NOT NULL DEFAULT 'dataset',"
    4429             :                       "md_standard_uri TEXT NOT NULL,"
    4430             :                       "mime_type TEXT NOT NULL DEFAULT 'text/xml',"
    4431             :                       "metadata TEXT NOT NULL DEFAULT ''"
    4432         598 :                       ")";
    4433             : 
    4434             :     /* From D.2. metadata Table 40. metadata Trigger Definition SQL  */
    4435         299 :     const char *pszMetadataTriggers =
    4436             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_insert' "
    4437             :         "BEFORE INSERT ON 'gpkg_metadata' "
    4438             :         "FOR EACH ROW BEGIN "
    4439             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata violates "
    4440             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4441             :         "collectionSession | series | dataset | featureType | feature | "
    4442             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4443             :         "taxonomy software | service | collectionHardware | "
    4444             :         "nonGeographicDataset | dimensionGroup') "
    4445             :         "WHERE NOT(NEW.md_scope IN "
    4446             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4447             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4448             :         "'catalogue','schema','taxonomy','software','service', "
    4449             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4450             :         "END; "
    4451             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_update' "
    4452             :         "BEFORE UPDATE OF 'md_scope' ON 'gpkg_metadata' "
    4453             :         "FOR EACH ROW BEGIN "
    4454             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata violates "
    4455             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4456             :         "collectionSession | series | dataset | featureType | feature | "
    4457             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4458             :         "taxonomy software | service | collectionHardware | "
    4459             :         "nonGeographicDataset | dimensionGroup') "
    4460             :         "WHERE NOT(NEW.md_scope IN "
    4461             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4462             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4463             :         "'catalogue','schema','taxonomy','software','service', "
    4464             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4465             :         "END";
    4466         299 :     if (bCreateTriggers)
    4467             :     {
    4468           0 :         osSQL += ";";
    4469           0 :         osSQL += pszMetadataTriggers;
    4470             :     }
    4471             : 
    4472             :     /* From C.11. gpkg_metadata_reference Table 36. gpkg_metadata_reference
    4473             :      * Table Definition SQL */
    4474             :     osSQL += ";"
    4475             :              "CREATE TABLE gpkg_metadata_reference ("
    4476             :              "reference_scope TEXT NOT NULL,"
    4477             :              "table_name TEXT,"
    4478             :              "column_name TEXT,"
    4479             :              "row_id_value INTEGER,"
    4480             :              "timestamp DATETIME NOT NULL DEFAULT "
    4481             :              "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    4482             :              "md_file_id INTEGER NOT NULL,"
    4483             :              "md_parent_id INTEGER,"
    4484             :              "CONSTRAINT crmr_mfi_fk FOREIGN KEY (md_file_id) REFERENCES "
    4485             :              "gpkg_metadata(id),"
    4486             :              "CONSTRAINT crmr_mpi_fk FOREIGN KEY (md_parent_id) REFERENCES "
    4487             :              "gpkg_metadata(id)"
    4488         299 :              ")";
    4489             : 
    4490             :     /* From D.3. metadata_reference Table 41. gpkg_metadata_reference Trigger
    4491             :      * Definition SQL   */
    4492         299 :     const char *pszMetadataReferenceTriggers =
    4493             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_insert' "
    4494             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4495             :         "FOR EACH ROW BEGIN "
    4496             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4497             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4498             :         "table\", \"column\", \"row\", \"row/col\"') "
    4499             :         "WHERE NOT NEW.reference_scope IN "
    4500             :         "('geopackage','table','column','row','row/col'); "
    4501             :         "END; "
    4502             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_update' "
    4503             :         "BEFORE UPDATE OF 'reference_scope' ON 'gpkg_metadata_reference' "
    4504             :         "FOR EACH ROW BEGIN "
    4505             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4506             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4507             :         "\"table\", \"column\", \"row\", \"row/col\"') "
    4508             :         "WHERE NOT NEW.reference_scope IN "
    4509             :         "('geopackage','table','column','row','row/col'); "
    4510             :         "END; "
    4511             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_insert' "
    4512             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4513             :         "FOR EACH ROW BEGIN "
    4514             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4515             :         "violates constraint: column name must be NULL when reference_scope "
    4516             :         "is \"geopackage\", \"table\" or \"row\"') "
    4517             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4518             :         "AND NEW.column_name IS NOT NULL); "
    4519             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4520             :         "violates constraint: column name must be defined for the specified "
    4521             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4522             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4523             :         "AND NOT NEW.table_name IN ( "
    4524             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4525             :         "AND name = NEW.table_name "
    4526             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4527             :         "END; "
    4528             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_update' "
    4529             :         "BEFORE UPDATE OF column_name ON 'gpkg_metadata_reference' "
    4530             :         "FOR EACH ROW BEGIN "
    4531             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4532             :         "violates constraint: column name must be NULL when reference_scope "
    4533             :         "is \"geopackage\", \"table\" or \"row\"') "
    4534             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4535             :         "AND NEW.column_name IS NOT NULL); "
    4536             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4537             :         "violates constraint: column name must be defined for the specified "
    4538             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4539             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4540             :         "AND NOT NEW.table_name IN ( "
    4541             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4542             :         "AND name = NEW.table_name "
    4543             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4544             :         "END; "
    4545             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_insert' "
    4546             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4547             :         "FOR EACH ROW BEGIN "
    4548             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4549             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4550             :         "is \"geopackage\", \"table\" or \"column\"') "
    4551             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4552             :         "AND NEW.row_id_value IS NOT NULL; "
    4553             :         "END; "
    4554             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_update' "
    4555             :         "BEFORE UPDATE OF 'row_id_value' ON 'gpkg_metadata_reference' "
    4556             :         "FOR EACH ROW BEGIN "
    4557             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4558             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4559             :         "is \"geopackage\", \"table\" or \"column\"') "
    4560             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4561             :         "AND NEW.row_id_value IS NOT NULL; "
    4562             :         "END; "
    4563             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_insert' "
    4564             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4565             :         "FOR EACH ROW BEGIN "
    4566             :         "SELECT RAISE(ABORT, 'insert 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             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_update' "
    4575             :         "BEFORE UPDATE OF 'timestamp' ON 'gpkg_metadata_reference' "
    4576             :         "FOR EACH ROW BEGIN "
    4577             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4578             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4579             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4580             :         "WHERE NOT (NEW.timestamp GLOB "
    4581             :         "'[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-"
    4582             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4583             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4584             :         "END";
    4585         299 :     if (bCreateTriggers)
    4586             :     {
    4587           0 :         osSQL += ";";
    4588           0 :         osSQL += pszMetadataReferenceTriggers;
    4589             :     }
    4590             : 
    4591         299 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    4592           2 :         return false;
    4593             : 
    4594         297 :     osSQL += ";";
    4595             :     osSQL += "INSERT INTO gpkg_extensions "
    4596             :              "(table_name, column_name, extension_name, definition, scope) "
    4597             :              "VALUES "
    4598             :              "('gpkg_metadata', NULL, 'gpkg_metadata', "
    4599             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4600         297 :              "'read-write')";
    4601             : 
    4602         297 :     osSQL += ";";
    4603             :     osSQL += "INSERT INTO gpkg_extensions "
    4604             :              "(table_name, column_name, extension_name, definition, scope) "
    4605             :              "VALUES "
    4606             :              "('gpkg_metadata_reference', NULL, 'gpkg_metadata', "
    4607             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4608         297 :              "'read-write')";
    4609             : 
    4610         297 :     const bool bOK = SQLCommand(hDB, osSQL) == OGRERR_NONE;
    4611         297 :     m_nHasMetadataTables = bOK;
    4612         297 :     return bOK;
    4613             : }
    4614             : 
    4615             : /************************************************************************/
    4616             : /*                            FlushMetadata()                           */
    4617             : /************************************************************************/
    4618             : 
    4619        8502 : void GDALGeoPackageDataset::FlushMetadata()
    4620             : {
    4621        8502 :     if (!m_bMetadataDirty || m_poParentDS != nullptr ||
    4622         374 :         m_nCreateMetadataTables == FALSE)
    4623        8134 :         return;
    4624         368 :     m_bMetadataDirty = false;
    4625             : 
    4626         368 :     if (eAccess == GA_ReadOnly)
    4627             :     {
    4628           3 :         return;
    4629             :     }
    4630             : 
    4631         365 :     bool bCanWriteAreaOrPoint =
    4632         728 :         !m_bGridCellEncodingAsCO &&
    4633         363 :         (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT);
    4634         365 :     if (!m_osRasterTable.empty())
    4635             :     {
    4636             :         const char *pszIdentifier =
    4637         142 :             GDALGeoPackageDataset::GetMetadataItem("IDENTIFIER");
    4638             :         const char *pszDescription =
    4639         142 :             GDALGeoPackageDataset::GetMetadataItem("DESCRIPTION");
    4640         171 :         if (!m_bIdentifierAsCO && pszIdentifier != nullptr &&
    4641          29 :             pszIdentifier != m_osIdentifier)
    4642             :         {
    4643          14 :             m_osIdentifier = pszIdentifier;
    4644             :             char *pszSQL =
    4645          14 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4646             :                                 "WHERE lower(table_name) = lower('%q')",
    4647             :                                 pszIdentifier, m_osRasterTable.c_str());
    4648          14 :             SQLCommand(hDB, pszSQL);
    4649          14 :             sqlite3_free(pszSQL);
    4650             :         }
    4651         149 :         if (!m_bDescriptionAsCO && pszDescription != nullptr &&
    4652           7 :             pszDescription != m_osDescription)
    4653             :         {
    4654           7 :             m_osDescription = pszDescription;
    4655             :             char *pszSQL =
    4656           7 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4657             :                                 "WHERE lower(table_name) = lower('%q')",
    4658             :                                 pszDescription, m_osRasterTable.c_str());
    4659           7 :             SQLCommand(hDB, pszSQL);
    4660           7 :             sqlite3_free(pszSQL);
    4661             :         }
    4662         142 :         if (bCanWriteAreaOrPoint)
    4663             :         {
    4664             :             const char *pszAreaOrPoint =
    4665          28 :                 GDALGeoPackageDataset::GetMetadataItem(GDALMD_AREA_OR_POINT);
    4666          28 :             if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_AREA))
    4667             :             {
    4668          23 :                 bCanWriteAreaOrPoint = false;
    4669          23 :                 char *pszSQL = sqlite3_mprintf(
    4670             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4671             :                     "grid_cell_encoding = 'grid-value-is-area' WHERE "
    4672             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4673             :                     m_osRasterTable.c_str());
    4674          23 :                 SQLCommand(hDB, pszSQL);
    4675          23 :                 sqlite3_free(pszSQL);
    4676             :             }
    4677           5 :             else if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_POINT))
    4678             :             {
    4679           1 :                 bCanWriteAreaOrPoint = false;
    4680           1 :                 char *pszSQL = sqlite3_mprintf(
    4681             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4682             :                     "grid_cell_encoding = 'grid-value-is-center' WHERE "
    4683             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4684             :                     m_osRasterTable.c_str());
    4685           1 :                 SQLCommand(hDB, pszSQL);
    4686           1 :                 sqlite3_free(pszSQL);
    4687             :             }
    4688             :         }
    4689             :     }
    4690             : 
    4691         365 :     char **papszMDDup = nullptr;
    4692         568 :     for (char **papszIter = GDALGeoPackageDataset::GetMetadata();
    4693         568 :          papszIter && *papszIter; ++papszIter)
    4694             :     {
    4695         203 :         if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4696          29 :             continue;
    4697         174 :         if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4698           8 :             continue;
    4699         166 :         if (STARTS_WITH_CI(*papszIter, "ZOOM_LEVEL="))
    4700          14 :             continue;
    4701         152 :         if (STARTS_WITH_CI(*papszIter, "GPKG_METADATA_ITEM_"))
    4702           4 :             continue;
    4703         148 :         if ((m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT) &&
    4704          29 :             !bCanWriteAreaOrPoint &&
    4705          26 :             STARTS_WITH_CI(*papszIter, GDALMD_AREA_OR_POINT))
    4706             :         {
    4707          26 :             continue;
    4708             :         }
    4709         122 :         papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4710             :     }
    4711             : 
    4712         365 :     CPLXMLNode *psXMLNode = nullptr;
    4713             :     {
    4714         365 :         GDALMultiDomainMetadata oLocalMDMD;
    4715         365 :         CSLConstList papszDomainList = oMDMD.GetDomainList();
    4716         365 :         CSLConstList papszIter = papszDomainList;
    4717         365 :         oLocalMDMD.SetMetadata(papszMDDup);
    4718         705 :         while (papszIter && *papszIter)
    4719             :         {
    4720         340 :             if (!EQUAL(*papszIter, "") &&
    4721         172 :                 !EQUAL(*papszIter, "IMAGE_STRUCTURE") &&
    4722          15 :                 !EQUAL(*papszIter, "GEOPACKAGE"))
    4723             :             {
    4724           8 :                 oLocalMDMD.SetMetadata(oMDMD.GetMetadata(*papszIter),
    4725             :                                        *papszIter);
    4726             :             }
    4727         340 :             papszIter++;
    4728             :         }
    4729         365 :         if (m_nBandCountFromMetadata > 0)
    4730             :         {
    4731          72 :             oLocalMDMD.SetMetadataItem(
    4732             :                 "BAND_COUNT", CPLSPrintf("%d", m_nBandCountFromMetadata),
    4733             :                 "IMAGE_STRUCTURE");
    4734          72 :             if (nBands == 1)
    4735             :             {
    4736          48 :                 const auto poCT = GetRasterBand(1)->GetColorTable();
    4737          48 :                 if (poCT)
    4738             :                 {
    4739          16 :                     std::string osVal("{");
    4740           8 :                     const int nColorCount = poCT->GetColorEntryCount();
    4741        2056 :                     for (int i = 0; i < nColorCount; ++i)
    4742             :                     {
    4743        2048 :                         if (i > 0)
    4744        2040 :                             osVal += ',';
    4745        2048 :                         const GDALColorEntry *psEntry = poCT->GetColorEntry(i);
    4746             :                         osVal +=
    4747        2048 :                             CPLSPrintf("{%d,%d,%d,%d}", psEntry->c1,
    4748        2048 :                                        psEntry->c2, psEntry->c3, psEntry->c4);
    4749             :                     }
    4750           8 :                     osVal += '}';
    4751           8 :                     oLocalMDMD.SetMetadataItem("COLOR_TABLE", osVal.c_str(),
    4752             :                                                "IMAGE_STRUCTURE");
    4753             :                 }
    4754             :             }
    4755          72 :             if (nBands == 1)
    4756             :             {
    4757          48 :                 const char *pszTILE_FORMAT = nullptr;
    4758          48 :                 switch (m_eTF)
    4759             :                 {
    4760           0 :                     case GPKG_TF_PNG_JPEG:
    4761           0 :                         pszTILE_FORMAT = "JPEG_PNG";
    4762           0 :                         break;
    4763          42 :                     case GPKG_TF_PNG:
    4764          42 :                         break;
    4765           0 :                     case GPKG_TF_PNG8:
    4766           0 :                         pszTILE_FORMAT = "PNG8";
    4767           0 :                         break;
    4768           3 :                     case GPKG_TF_JPEG:
    4769           3 :                         pszTILE_FORMAT = "JPEG";
    4770           3 :                         break;
    4771           3 :                     case GPKG_TF_WEBP:
    4772           3 :                         pszTILE_FORMAT = "WEBP";
    4773           3 :                         break;
    4774           0 :                     case GPKG_TF_PNG_16BIT:
    4775           0 :                         break;
    4776           0 :                     case GPKG_TF_TIFF_32BIT_FLOAT:
    4777           0 :                         break;
    4778             :                 }
    4779          48 :                 if (pszTILE_FORMAT)
    4780           6 :                     oLocalMDMD.SetMetadataItem("TILE_FORMAT", pszTILE_FORMAT,
    4781             :                                                "IMAGE_STRUCTURE");
    4782             :             }
    4783             :         }
    4784         507 :         if (GetRasterCount() > 0 &&
    4785         142 :             GetRasterBand(1)->GetRasterDataType() == GDT_Byte)
    4786             :         {
    4787         112 :             int bHasNoData = FALSE;
    4788             :             const double dfNoDataValue =
    4789         112 :                 GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    4790         112 :             if (bHasNoData)
    4791             :             {
    4792           3 :                 oLocalMDMD.SetMetadataItem("NODATA_VALUE",
    4793             :                                            CPLSPrintf("%.17g", dfNoDataValue),
    4794             :                                            "IMAGE_STRUCTURE");
    4795             :             }
    4796             :         }
    4797         612 :         for (int i = 1; i <= GetRasterCount(); ++i)
    4798             :         {
    4799             :             auto poBand =
    4800         247 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    4801         247 :             poBand->AddImplicitStatistics(false);
    4802         247 :             char **papszMD = GetRasterBand(i)->GetMetadata();
    4803         247 :             poBand->AddImplicitStatistics(true);
    4804         247 :             if (papszMD)
    4805             :             {
    4806          14 :                 oLocalMDMD.SetMetadata(papszMD, CPLSPrintf("BAND_%d", i));
    4807             :             }
    4808             :         }
    4809         365 :         psXMLNode = oLocalMDMD.Serialize();
    4810             :     }
    4811             : 
    4812         365 :     CSLDestroy(papszMDDup);
    4813         365 :     papszMDDup = nullptr;
    4814             : 
    4815         365 :     WriteMetadata(psXMLNode, m_osRasterTable.c_str());
    4816             : 
    4817         365 :     if (!m_osRasterTable.empty())
    4818             :     {
    4819             :         char **papszGeopackageMD =
    4820         142 :             GDALGeoPackageDataset::GetMetadata("GEOPACKAGE");
    4821             : 
    4822         142 :         papszMDDup = nullptr;
    4823         151 :         for (char **papszIter = papszGeopackageMD; papszIter && *papszIter;
    4824             :              ++papszIter)
    4825             :         {
    4826           9 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4827             :         }
    4828             : 
    4829         284 :         GDALMultiDomainMetadata oLocalMDMD;
    4830         142 :         oLocalMDMD.SetMetadata(papszMDDup);
    4831         142 :         CSLDestroy(papszMDDup);
    4832         142 :         papszMDDup = nullptr;
    4833         142 :         psXMLNode = oLocalMDMD.Serialize();
    4834             : 
    4835         142 :         WriteMetadata(psXMLNode, nullptr);
    4836             :     }
    4837             : 
    4838         602 :     for (auto &poLayer : m_apoLayers)
    4839             :     {
    4840         237 :         const char *pszIdentifier = poLayer->GetMetadataItem("IDENTIFIER");
    4841         237 :         const char *pszDescription = poLayer->GetMetadataItem("DESCRIPTION");
    4842         237 :         if (pszIdentifier != nullptr)
    4843             :         {
    4844             :             char *pszSQL =
    4845           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4846             :                                 "WHERE lower(table_name) = lower('%q')",
    4847             :                                 pszIdentifier, poLayer->GetName());
    4848           3 :             SQLCommand(hDB, pszSQL);
    4849           3 :             sqlite3_free(pszSQL);
    4850             :         }
    4851         237 :         if (pszDescription != nullptr)
    4852             :         {
    4853             :             char *pszSQL =
    4854           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4855             :                                 "WHERE lower(table_name) = lower('%q')",
    4856             :                                 pszDescription, poLayer->GetName());
    4857           3 :             SQLCommand(hDB, pszSQL);
    4858           3 :             sqlite3_free(pszSQL);
    4859             :         }
    4860             : 
    4861         237 :         papszMDDup = nullptr;
    4862         625 :         for (char **papszIter = poLayer->GetMetadata(); papszIter && *papszIter;
    4863             :              ++papszIter)
    4864             :         {
    4865         388 :             if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4866           3 :                 continue;
    4867         385 :             if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4868           3 :                 continue;
    4869         382 :             if (STARTS_WITH_CI(*papszIter, "OLMD_FID64="))
    4870           0 :                 continue;
    4871         382 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4872             :         }
    4873             : 
    4874             :         {
    4875         237 :             GDALMultiDomainMetadata oLocalMDMD;
    4876         237 :             char **papszDomainList = poLayer->GetMetadataDomainList();
    4877         237 :             char **papszIter = papszDomainList;
    4878         237 :             oLocalMDMD.SetMetadata(papszMDDup);
    4879         513 :             while (papszIter && *papszIter)
    4880             :             {
    4881         276 :                 if (!EQUAL(*papszIter, ""))
    4882          60 :                     oLocalMDMD.SetMetadata(poLayer->GetMetadata(*papszIter),
    4883             :                                            *papszIter);
    4884         276 :                 papszIter++;
    4885             :             }
    4886         237 :             CSLDestroy(papszDomainList);
    4887         237 :             psXMLNode = oLocalMDMD.Serialize();
    4888             :         }
    4889             : 
    4890         237 :         CSLDestroy(papszMDDup);
    4891         237 :         papszMDDup = nullptr;
    4892             : 
    4893         237 :         WriteMetadata(psXMLNode, poLayer->GetName());
    4894             :     }
    4895             : }
    4896             : 
    4897             : /************************************************************************/
    4898             : /*                          GetMetadataItem()                           */
    4899             : /************************************************************************/
    4900             : 
    4901        1550 : const char *GDALGeoPackageDataset::GetMetadataItem(const char *pszName,
    4902             :                                                    const char *pszDomain)
    4903             : {
    4904        1550 :     pszDomain = CheckMetadataDomain(pszDomain);
    4905        1550 :     return CSLFetchNameValue(GetMetadata(pszDomain), pszName);
    4906             : }
    4907             : 
    4908             : /************************************************************************/
    4909             : /*                            SetMetadata()                             */
    4910             : /************************************************************************/
    4911             : 
    4912         146 : CPLErr GDALGeoPackageDataset::SetMetadata(char **papszMetadata,
    4913             :                                           const char *pszDomain)
    4914             : {
    4915         146 :     pszDomain = CheckMetadataDomain(pszDomain);
    4916         146 :     m_bMetadataDirty = true;
    4917         146 :     GetMetadata(); /* force loading from storage if needed */
    4918         146 :     return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
    4919             : }
    4920             : 
    4921             : /************************************************************************/
    4922             : /*                          SetMetadataItem()                           */
    4923             : /************************************************************************/
    4924             : 
    4925          21 : CPLErr GDALGeoPackageDataset::SetMetadataItem(const char *pszName,
    4926             :                                               const char *pszValue,
    4927             :                                               const char *pszDomain)
    4928             : {
    4929          21 :     pszDomain = CheckMetadataDomain(pszDomain);
    4930          21 :     m_bMetadataDirty = true;
    4931          21 :     GetMetadata(); /* force loading from storage if needed */
    4932          21 :     return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    4933             : }
    4934             : 
    4935             : /************************************************************************/
    4936             : /*                                Create()                              */
    4937             : /************************************************************************/
    4938             : 
    4939         892 : int GDALGeoPackageDataset::Create(const char *pszFilename, int nXSize,
    4940             :                                   int nYSize, int nBandsIn, GDALDataType eDT,
    4941             :                                   char **papszOptions)
    4942             : {
    4943        1784 :     CPLString osCommand;
    4944             : 
    4945             :     /* First, ensure there isn't any such file yet. */
    4946             :     VSIStatBufL sStatBuf;
    4947             : 
    4948         892 :     if (nBandsIn != 0)
    4949             :     {
    4950         224 :         if (eDT == GDT_Byte)
    4951             :         {
    4952         154 :             if (nBandsIn != 1 && nBandsIn != 2 && nBandsIn != 3 &&
    4953             :                 nBandsIn != 4)
    4954             :             {
    4955           1 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4956             :                          "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), "
    4957             :                          "3 (RGB) or 4 (RGBA) band dataset supported for "
    4958             :                          "Byte datatype");
    4959           1 :                 return FALSE;
    4960             :             }
    4961             :         }
    4962          70 :         else if (eDT == GDT_Int16 || eDT == GDT_UInt16 || eDT == GDT_Float32)
    4963             :         {
    4964          43 :             if (nBandsIn != 1)
    4965             :             {
    4966           3 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4967             :                          "Only single band dataset supported for non Byte "
    4968             :                          "datatype");
    4969           3 :                 return FALSE;
    4970             :             }
    4971             :         }
    4972             :         else
    4973             :         {
    4974          27 :             CPLError(CE_Failure, CPLE_NotSupported,
    4975             :                      "Only Byte, Int16, UInt16 or Float32 supported");
    4976          27 :             return FALSE;
    4977             :         }
    4978             :     }
    4979             : 
    4980         861 :     const size_t nFilenameLen = strlen(pszFilename);
    4981         861 :     const bool bGpkgZip =
    4982         856 :         (nFilenameLen > strlen(".gpkg.zip") &&
    4983        1717 :          !STARTS_WITH(pszFilename, "/vsizip/") &&
    4984         856 :          EQUAL(pszFilename + nFilenameLen - strlen(".gpkg.zip"), ".gpkg.zip"));
    4985             : 
    4986             :     const bool bUseTempFile =
    4987         862 :         bGpkgZip || (CPLTestBool(CPLGetConfigOption(
    4988           1 :                          "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", "NO")) &&
    4989           1 :                      (VSIHasOptimizedReadMultiRange(pszFilename) != FALSE ||
    4990           1 :                       EQUAL(CPLGetConfigOption(
    4991             :                                 "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", ""),
    4992         861 :                             "FORCED")));
    4993             : 
    4994         861 :     bool bFileExists = false;
    4995         861 :     if (VSIStatL(pszFilename, &sStatBuf) == 0)
    4996             :     {
    4997          10 :         bFileExists = true;
    4998          20 :         if (nBandsIn == 0 || bUseTempFile ||
    4999          10 :             !CPLTestBool(
    5000             :                 CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")))
    5001             :         {
    5002           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5003             :                      "A file system object called '%s' already exists.",
    5004             :                      pszFilename);
    5005             : 
    5006           0 :             return FALSE;
    5007             :         }
    5008             :     }
    5009             : 
    5010         861 :     if (bUseTempFile)
    5011             :     {
    5012           3 :         if (bGpkgZip)
    5013             :         {
    5014           2 :             std::string osFilenameInZip(CPLGetFilename(pszFilename));
    5015           2 :             osFilenameInZip.resize(osFilenameInZip.size() - strlen(".zip"));
    5016             :             m_osFinalFilename =
    5017           2 :                 std::string("/vsizip/{") + pszFilename + "}/" + osFilenameInZip;
    5018             :         }
    5019             :         else
    5020             :         {
    5021           1 :             m_osFinalFilename = pszFilename;
    5022             :         }
    5023           3 :         m_pszFilename = CPLStrdup(
    5024           6 :             CPLGenerateTempFilenameSafe(CPLGetFilename(pszFilename)).c_str());
    5025           3 :         CPLDebug("GPKG", "Creating temporary file %s", m_pszFilename);
    5026             :     }
    5027             :     else
    5028             :     {
    5029         858 :         m_pszFilename = CPLStrdup(pszFilename);
    5030             :     }
    5031         861 :     m_bNew = true;
    5032         861 :     eAccess = GA_Update;
    5033         861 :     m_bDateTimeWithTZ =
    5034         861 :         EQUAL(CSLFetchNameValueDef(papszOptions, "DATETIME_FORMAT", "WITH_TZ"),
    5035             :               "WITH_TZ");
    5036             : 
    5037             :     // for test/debug purposes only. true is the nominal value
    5038         861 :     m_bPNGSupports2Bands =
    5039         861 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_2BANDS", "TRUE"));
    5040         861 :     m_bPNGSupportsCT =
    5041         861 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_CT", "TRUE"));
    5042             : 
    5043         861 :     if (!OpenOrCreateDB(bFileExists
    5044             :                             ? SQLITE_OPEN_READWRITE
    5045             :                             : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE))
    5046           7 :         return FALSE;
    5047             : 
    5048             :     /* Default to synchronous=off for performance for new file */
    5049        1698 :     if (!bFileExists &&
    5050         844 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5051             :     {
    5052         345 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5053             :     }
    5054             : 
    5055             :     /* OGR UTF-8 support. If we set the UTF-8 Pragma early on, it */
    5056             :     /* will be written into the main file and supported henceforth */
    5057         854 :     SQLCommand(hDB, "PRAGMA encoding = \"UTF-8\"");
    5058             : 
    5059         854 :     if (bFileExists)
    5060             :     {
    5061          10 :         VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
    5062          10 :         if (fp)
    5063             :         {
    5064             :             GByte abyHeader[100];
    5065          10 :             VSIFReadL(abyHeader, 1, sizeof(abyHeader), fp);
    5066          10 :             VSIFCloseL(fp);
    5067             : 
    5068          10 :             memcpy(&m_nApplicationId, abyHeader + knApplicationIdPos, 4);
    5069          10 :             m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    5070          10 :             memcpy(&m_nUserVersion, abyHeader + knUserVersionPos, 4);
    5071          10 :             m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    5072             : 
    5073          10 :             if (m_nApplicationId == GP10_APPLICATION_ID)
    5074             :             {
    5075           0 :                 CPLDebug("GPKG", "GeoPackage v1.0");
    5076             :             }
    5077          10 :             else if (m_nApplicationId == GP11_APPLICATION_ID)
    5078             :             {
    5079           0 :                 CPLDebug("GPKG", "GeoPackage v1.1");
    5080             :             }
    5081          10 :             else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    5082          10 :                      m_nUserVersion >= GPKG_1_2_VERSION)
    5083             :             {
    5084          10 :                 CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    5085          10 :                          (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    5086             :             }
    5087             :         }
    5088             : 
    5089          10 :         DetectSpatialRefSysColumns();
    5090             :     }
    5091             : 
    5092         854 :     const char *pszVersion = CSLFetchNameValue(papszOptions, "VERSION");
    5093         854 :     if (pszVersion && !EQUAL(pszVersion, "AUTO"))
    5094             :     {
    5095          40 :         if (EQUAL(pszVersion, "1.0"))
    5096             :         {
    5097           2 :             m_nApplicationId = GP10_APPLICATION_ID;
    5098           2 :             m_nUserVersion = 0;
    5099             :         }
    5100          38 :         else if (EQUAL(pszVersion, "1.1"))
    5101             :         {
    5102           1 :             m_nApplicationId = GP11_APPLICATION_ID;
    5103           1 :             m_nUserVersion = 0;
    5104             :         }
    5105          37 :         else if (EQUAL(pszVersion, "1.2"))
    5106             :         {
    5107          15 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5108          15 :             m_nUserVersion = GPKG_1_2_VERSION;
    5109             :         }
    5110          22 :         else if (EQUAL(pszVersion, "1.3"))
    5111             :         {
    5112           3 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5113           3 :             m_nUserVersion = GPKG_1_3_VERSION;
    5114             :         }
    5115          19 :         else if (EQUAL(pszVersion, "1.4"))
    5116             :         {
    5117          19 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5118          19 :             m_nUserVersion = GPKG_1_4_VERSION;
    5119             :         }
    5120             :     }
    5121             : 
    5122         854 :     SoftStartTransaction();
    5123             : 
    5124        1708 :     CPLString osSQL;
    5125         854 :     if (!bFileExists)
    5126             :     {
    5127             :         /* Requirement 10: A GeoPackage SHALL include a gpkg_spatial_ref_sys
    5128             :          * table */
    5129             :         /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5130             :         osSQL = "CREATE TABLE gpkg_spatial_ref_sys ("
    5131             :                 "srs_name TEXT NOT NULL,"
    5132             :                 "srs_id INTEGER NOT NULL PRIMARY KEY,"
    5133             :                 "organization TEXT NOT NULL,"
    5134             :                 "organization_coordsys_id INTEGER NOT NULL,"
    5135             :                 "definition  TEXT NOT NULL,"
    5136         844 :                 "description TEXT";
    5137         844 :         if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "CRS_WKT_EXTENSION",
    5138        1023 :                                              "NO")) ||
    5139         179 :             (nBandsIn != 0 && eDT != GDT_Byte))
    5140             :         {
    5141          42 :             m_bHasDefinition12_063 = true;
    5142          42 :             osSQL += ", definition_12_063 TEXT NOT NULL";
    5143          42 :             if (m_nUserVersion >= GPKG_1_4_VERSION)
    5144             :             {
    5145          40 :                 osSQL += ", epoch DOUBLE";
    5146          40 :                 m_bHasEpochColumn = true;
    5147             :             }
    5148             :         }
    5149             :         osSQL += ")"
    5150             :                  ";"
    5151             :                  /* Requirement 11: The gpkg_spatial_ref_sys table in a
    5152             :                     GeoPackage SHALL */
    5153             :                  /* contain a record for EPSG:4326, the geodetic WGS84 SRS */
    5154             :                  /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5155             : 
    5156             :                  "INSERT INTO gpkg_spatial_ref_sys ("
    5157             :                  "srs_name, srs_id, organization, organization_coordsys_id, "
    5158         844 :                  "definition, description";
    5159         844 :         if (m_bHasDefinition12_063)
    5160          42 :             osSQL += ", definition_12_063";
    5161             :         osSQL +=
    5162             :             ") VALUES ("
    5163             :             "'WGS 84 geodetic', 4326, 'EPSG', 4326, '"
    5164             :             "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS "
    5165             :             "84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],"
    5166             :             "AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY["
    5167             :             "\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY["
    5168             :             "\"EPSG\",\"9122\"]],AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\","
    5169             :             "EAST],AUTHORITY[\"EPSG\",\"4326\"]]"
    5170             :             "', 'longitude/latitude coordinates in decimal degrees on the WGS "
    5171         844 :             "84 spheroid'";
    5172         844 :         if (m_bHasDefinition12_063)
    5173             :             osSQL +=
    5174             :                 ", 'GEODCRS[\"WGS 84\", DATUM[\"World Geodetic System 1984\", "
    5175             :                 "ELLIPSOID[\"WGS 84\",6378137, 298.257223563, "
    5176             :                 "LENGTHUNIT[\"metre\", 1.0]]], PRIMEM[\"Greenwich\", 0.0, "
    5177             :                 "ANGLEUNIT[\"degree\",0.0174532925199433]], CS[ellipsoidal, "
    5178             :                 "2], AXIS[\"latitude\", north, ORDER[1]], AXIS[\"longitude\", "
    5179             :                 "east, ORDER[2]], ANGLEUNIT[\"degree\", 0.0174532925199433], "
    5180          42 :                 "ID[\"EPSG\", 4326]]'";
    5181             :         osSQL +=
    5182             :             ")"
    5183             :             ";"
    5184             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5185             :                SHALL */
    5186             :             /* contain a record with an srs_id of -1, an organization of “NONE”,
    5187             :              */
    5188             :             /* an organization_coordsys_id of -1, and definition “undefined” */
    5189             :             /* for undefined Cartesian coordinate reference systems */
    5190             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5191             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5192             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5193         844 :             "definition, description";
    5194         844 :         if (m_bHasDefinition12_063)
    5195          42 :             osSQL += ", definition_12_063";
    5196             :         osSQL += ") VALUES ("
    5197             :                  "'Undefined Cartesian SRS', -1, 'NONE', -1, 'undefined', "
    5198         844 :                  "'undefined Cartesian coordinate reference system'";
    5199         844 :         if (m_bHasDefinition12_063)
    5200          42 :             osSQL += ", 'undefined'";
    5201             :         osSQL +=
    5202             :             ")"
    5203             :             ";"
    5204             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5205             :                SHALL */
    5206             :             /* contain a record with an srs_id of 0, an organization of “NONE”,
    5207             :              */
    5208             :             /* an organization_coordsys_id of 0, and definition “undefined” */
    5209             :             /* for undefined geographic coordinate reference systems */
    5210             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5211             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5212             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5213         844 :             "definition, description";
    5214         844 :         if (m_bHasDefinition12_063)
    5215          42 :             osSQL += ", definition_12_063";
    5216             :         osSQL += ") VALUES ("
    5217             :                  "'Undefined geographic SRS', 0, 'NONE', 0, 'undefined', "
    5218         844 :                  "'undefined geographic coordinate reference system'";
    5219         844 :         if (m_bHasDefinition12_063)
    5220          42 :             osSQL += ", 'undefined'";
    5221             :         osSQL += ")"
    5222             :                  ";"
    5223             :                  /* Requirement 13: A GeoPackage file SHALL include a
    5224             :                     gpkg_contents table */
    5225             :                  /* http://opengis.github.io/geopackage/#_contents */
    5226             :                  "CREATE TABLE gpkg_contents ("
    5227             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5228             :                  "data_type TEXT NOT NULL,"
    5229             :                  "identifier TEXT UNIQUE,"
    5230             :                  "description TEXT DEFAULT '',"
    5231             :                  "last_change DATETIME NOT NULL DEFAULT "
    5232             :                  "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    5233             :                  "min_x DOUBLE, min_y DOUBLE,"
    5234             :                  "max_x DOUBLE, max_y DOUBLE,"
    5235             :                  "srs_id INTEGER,"
    5236             :                  "CONSTRAINT fk_gc_r_srs_id FOREIGN KEY (srs_id) REFERENCES "
    5237             :                  "gpkg_spatial_ref_sys(srs_id)"
    5238         844 :                  ")";
    5239             : 
    5240             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5241         844 :         if (CPLFetchBool(papszOptions, "ADD_GPKG_OGR_CONTENTS", true))
    5242             :         {
    5243         839 :             m_bHasGPKGOGRContents = true;
    5244             :             osSQL += ";"
    5245             :                      "CREATE TABLE gpkg_ogr_contents("
    5246             :                      "table_name TEXT NOT NULL PRIMARY KEY,"
    5247             :                      "feature_count INTEGER DEFAULT NULL"
    5248         839 :                      ")";
    5249             :         }
    5250             : #endif
    5251             : 
    5252             :         /* Requirement 21: A GeoPackage with a gpkg_contents table row with a
    5253             :          * “features” */
    5254             :         /* data_type SHALL contain a gpkg_geometry_columns table or updateable
    5255             :          * view */
    5256             :         /* http://opengis.github.io/geopackage/#_geometry_columns */
    5257             :         const bool bCreateGeometryColumns =
    5258         844 :             CPLTestBool(CPLGetConfigOption("CREATE_GEOMETRY_COLUMNS", "YES"));
    5259         844 :         if (bCreateGeometryColumns)
    5260             :         {
    5261         843 :             m_bHasGPKGGeometryColumns = true;
    5262         843 :             osSQL += ";";
    5263         843 :             osSQL += pszCREATE_GPKG_GEOMETRY_COLUMNS;
    5264             :         }
    5265             :     }
    5266             : 
    5267             :     const bool bCreateTriggers =
    5268         854 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "YES"));
    5269          10 :     if ((bFileExists && nBandsIn != 0 &&
    5270          10 :          SQLGetInteger(
    5271             :              hDB,
    5272             :              "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_tile_matrix_set' "
    5273             :              "AND type in ('table', 'view')",
    5274        1708 :              nullptr) == 0) ||
    5275         853 :         (!bFileExists &&
    5276         844 :          CPLTestBool(CPLGetConfigOption("CREATE_RASTER_TABLES", "YES"))))
    5277             :     {
    5278         844 :         if (!osSQL.empty())
    5279         843 :             osSQL += ";";
    5280             : 
    5281             :         /* From C.5. gpkg_tile_matrix_set Table 28. gpkg_tile_matrix_set Table
    5282             :          * Creation SQL  */
    5283             :         osSQL += "CREATE TABLE gpkg_tile_matrix_set ("
    5284             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5285             :                  "srs_id INTEGER NOT NULL,"
    5286             :                  "min_x DOUBLE NOT NULL,"
    5287             :                  "min_y DOUBLE NOT NULL,"
    5288             :                  "max_x DOUBLE NOT NULL,"
    5289             :                  "max_y DOUBLE NOT NULL,"
    5290             :                  "CONSTRAINT fk_gtms_table_name FOREIGN KEY (table_name) "
    5291             :                  "REFERENCES gpkg_contents(table_name),"
    5292             :                  "CONSTRAINT fk_gtms_srs FOREIGN KEY (srs_id) REFERENCES "
    5293             :                  "gpkg_spatial_ref_sys (srs_id)"
    5294             :                  ")"
    5295             :                  ";"
    5296             : 
    5297             :                  /* From C.6. gpkg_tile_matrix Table 29. gpkg_tile_matrix Table
    5298             :                     Creation SQL */
    5299             :                  "CREATE TABLE gpkg_tile_matrix ("
    5300             :                  "table_name TEXT NOT NULL,"
    5301             :                  "zoom_level INTEGER NOT NULL,"
    5302             :                  "matrix_width INTEGER NOT NULL,"
    5303             :                  "matrix_height INTEGER NOT NULL,"
    5304             :                  "tile_width INTEGER NOT NULL,"
    5305             :                  "tile_height INTEGER NOT NULL,"
    5306             :                  "pixel_x_size DOUBLE NOT NULL,"
    5307             :                  "pixel_y_size DOUBLE NOT NULL,"
    5308             :                  "CONSTRAINT pk_ttm PRIMARY KEY (table_name, zoom_level),"
    5309             :                  "CONSTRAINT fk_tmm_table_name FOREIGN KEY (table_name) "
    5310             :                  "REFERENCES gpkg_contents(table_name)"
    5311         844 :                  ")";
    5312             : 
    5313         844 :         if (bCreateTriggers)
    5314             :         {
    5315             :             /* From D.1. gpkg_tile_matrix Table 39. gpkg_tile_matrix Trigger
    5316             :              * Definition SQL */
    5317         844 :             const char *pszTileMatrixTrigger =
    5318             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_insert' "
    5319             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5320             :                 "FOR EACH ROW BEGIN "
    5321             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5322             :                 "violates constraint: zoom_level cannot be less than 0') "
    5323             :                 "WHERE (NEW.zoom_level < 0); "
    5324             :                 "END; "
    5325             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_update' "
    5326             :                 "BEFORE UPDATE of zoom_level ON 'gpkg_tile_matrix' "
    5327             :                 "FOR EACH ROW BEGIN "
    5328             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5329             :                 "violates constraint: zoom_level cannot be less than 0') "
    5330             :                 "WHERE (NEW.zoom_level < 0); "
    5331             :                 "END; "
    5332             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_insert' "
    5333             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5334             :                 "FOR EACH ROW BEGIN "
    5335             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5336             :                 "violates constraint: matrix_width cannot be less than 1') "
    5337             :                 "WHERE (NEW.matrix_width < 1); "
    5338             :                 "END; "
    5339             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_update' "
    5340             :                 "BEFORE UPDATE OF matrix_width ON 'gpkg_tile_matrix' "
    5341             :                 "FOR EACH ROW BEGIN "
    5342             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5343             :                 "violates constraint: matrix_width cannot be less than 1') "
    5344             :                 "WHERE (NEW.matrix_width < 1); "
    5345             :                 "END; "
    5346             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_insert' "
    5347             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5348             :                 "FOR EACH ROW BEGIN "
    5349             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5350             :                 "violates constraint: matrix_height cannot be less than 1') "
    5351             :                 "WHERE (NEW.matrix_height < 1); "
    5352             :                 "END; "
    5353             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_update' "
    5354             :                 "BEFORE UPDATE OF matrix_height ON 'gpkg_tile_matrix' "
    5355             :                 "FOR EACH ROW BEGIN "
    5356             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5357             :                 "violates constraint: matrix_height cannot be less than 1') "
    5358             :                 "WHERE (NEW.matrix_height < 1); "
    5359             :                 "END; "
    5360             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_insert' "
    5361             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5362             :                 "FOR EACH ROW BEGIN "
    5363             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5364             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5365             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5366             :                 "END; "
    5367             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_update' "
    5368             :                 "BEFORE UPDATE OF pixel_x_size ON 'gpkg_tile_matrix' "
    5369             :                 "FOR EACH ROW BEGIN "
    5370             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5371             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5372             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5373             :                 "END; "
    5374             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_insert' "
    5375             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5376             :                 "FOR EACH ROW BEGIN "
    5377             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5378             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5379             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5380             :                 "END; "
    5381             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_update' "
    5382             :                 "BEFORE UPDATE OF pixel_y_size ON 'gpkg_tile_matrix' "
    5383             :                 "FOR EACH ROW BEGIN "
    5384             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5385             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5386             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5387             :                 "END;";
    5388         844 :             osSQL += ";";
    5389         844 :             osSQL += pszTileMatrixTrigger;
    5390             :         }
    5391             :     }
    5392             : 
    5393         854 :     if (!osSQL.empty() && OGRERR_NONE != SQLCommand(hDB, osSQL))
    5394           1 :         return FALSE;
    5395             : 
    5396         853 :     if (!bFileExists)
    5397             :     {
    5398             :         const char *pszMetadataTables =
    5399         843 :             CSLFetchNameValue(papszOptions, "METADATA_TABLES");
    5400         843 :         if (pszMetadataTables)
    5401           9 :             m_nCreateMetadataTables = int(CPLTestBool(pszMetadataTables));
    5402             : 
    5403         843 :         if (m_nCreateMetadataTables == TRUE && !CreateMetadataTables())
    5404           0 :             return FALSE;
    5405             : 
    5406         843 :         if (m_bHasDefinition12_063)
    5407             :         {
    5408          84 :             if (OGRERR_NONE != CreateExtensionsTableIfNecessary() ||
    5409             :                 OGRERR_NONE !=
    5410          42 :                     SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5411             :                                     "(table_name, column_name, extension_name, "
    5412             :                                     "definition, scope) "
    5413             :                                     "VALUES "
    5414             :                                     "('gpkg_spatial_ref_sys', "
    5415             :                                     "'definition_12_063', 'gpkg_crs_wkt', "
    5416             :                                     "'http://www.geopackage.org/spec120/"
    5417             :                                     "#extension_crs_wkt', 'read-write')"))
    5418             :             {
    5419           0 :                 return FALSE;
    5420             :             }
    5421          42 :             if (m_bHasEpochColumn)
    5422             :             {
    5423          40 :                 if (OGRERR_NONE !=
    5424          40 :                         SQLCommand(
    5425             :                             hDB, "UPDATE gpkg_extensions SET extension_name = "
    5426             :                                  "'gpkg_crs_wkt_1_1' "
    5427          80 :                                  "WHERE extension_name = 'gpkg_crs_wkt'") ||
    5428             :                     OGRERR_NONE !=
    5429          40 :                         SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5430             :                                         "(table_name, column_name, "
    5431             :                                         "extension_name, definition, scope) "
    5432             :                                         "VALUES "
    5433             :                                         "('gpkg_spatial_ref_sys', 'epoch', "
    5434             :                                         "'gpkg_crs_wkt_1_1', "
    5435             :                                         "'http://www.geopackage.org/spec/"
    5436             :                                         "#extension_crs_wkt', "
    5437             :                                         "'read-write')"))
    5438             :                 {
    5439           0 :                     return FALSE;
    5440             :                 }
    5441             :             }
    5442             :         }
    5443             :     }
    5444             : 
    5445         853 :     if (nBandsIn != 0)
    5446             :     {
    5447         188 :         const std::string osTableName = CPLGetBasenameSafe(m_pszFilename);
    5448             :         m_osRasterTable = CSLFetchNameValueDef(papszOptions, "RASTER_TABLE",
    5449         188 :                                                osTableName.c_str());
    5450         188 :         if (m_osRasterTable.empty())
    5451             :         {
    5452           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5453             :                      "RASTER_TABLE must be set to a non empty value");
    5454           0 :             return FALSE;
    5455             :         }
    5456         188 :         m_bIdentifierAsCO =
    5457         188 :             CSLFetchNameValue(papszOptions, "RASTER_IDENTIFIER") != nullptr;
    5458             :         m_osIdentifier = CSLFetchNameValueDef(papszOptions, "RASTER_IDENTIFIER",
    5459         188 :                                               m_osRasterTable);
    5460         188 :         m_bDescriptionAsCO =
    5461         188 :             CSLFetchNameValue(papszOptions, "RASTER_DESCRIPTION") != nullptr;
    5462             :         m_osDescription =
    5463         188 :             CSLFetchNameValueDef(papszOptions, "RASTER_DESCRIPTION", "");
    5464         188 :         SetDataType(eDT);
    5465         188 :         if (eDT == GDT_Int16)
    5466          16 :             SetGlobalOffsetScale(-32768.0, 1.0);
    5467             : 
    5468             :         /* From C.7. sample_tile_pyramid (Informative) Table 31. EXAMPLE: tiles
    5469             :          * table Create Table SQL (Informative) */
    5470             :         char *pszSQL =
    5471         188 :             sqlite3_mprintf("CREATE TABLE \"%w\" ("
    5472             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    5473             :                             "zoom_level INTEGER NOT NULL,"
    5474             :                             "tile_column INTEGER NOT NULL,"
    5475             :                             "tile_row INTEGER NOT NULL,"
    5476             :                             "tile_data BLOB NOT NULL,"
    5477             :                             "UNIQUE (zoom_level, tile_column, tile_row)"
    5478             :                             ")",
    5479             :                             m_osRasterTable.c_str());
    5480         188 :         osSQL = pszSQL;
    5481         188 :         sqlite3_free(pszSQL);
    5482             : 
    5483         188 :         if (bCreateTriggers)
    5484             :         {
    5485         188 :             osSQL += ";";
    5486         188 :             osSQL += CreateRasterTriggersSQL(m_osRasterTable);
    5487             :         }
    5488             : 
    5489         188 :         OGRErr eErr = SQLCommand(hDB, osSQL);
    5490         188 :         if (OGRERR_NONE != eErr)
    5491           0 :             return FALSE;
    5492             : 
    5493         188 :         const char *pszTF = CSLFetchNameValue(papszOptions, "TILE_FORMAT");
    5494         188 :         if (eDT == GDT_Int16 || eDT == GDT_UInt16)
    5495             :         {
    5496          27 :             m_eTF = GPKG_TF_PNG_16BIT;
    5497          27 :             if (pszTF)
    5498             :             {
    5499           1 :                 if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "PNG"))
    5500             :                 {
    5501           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5502             :                              "Only AUTO or PNG supported "
    5503             :                              "as tile format for Int16 / UInt16");
    5504             :                 }
    5505             :             }
    5506             :         }
    5507         161 :         else if (eDT == GDT_Float32)
    5508             :         {
    5509          13 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    5510          13 :             if (pszTF)
    5511             :             {
    5512           5 :                 if (EQUAL(pszTF, "PNG"))
    5513           5 :                     m_eTF = GPKG_TF_PNG_16BIT;
    5514           0 :                 else if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "TIFF"))
    5515             :                 {
    5516           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5517             :                              "Only AUTO, PNG or TIFF supported "
    5518             :                              "as tile format for Float32");
    5519             :                 }
    5520             :             }
    5521             :         }
    5522             :         else
    5523             :         {
    5524         148 :             if (pszTF)
    5525             :             {
    5526          71 :                 m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    5527          71 :                 if (nBandsIn == 1 && m_eTF != GPKG_TF_PNG)
    5528           7 :                     m_bMetadataDirty = true;
    5529             :             }
    5530          77 :             else if (nBandsIn == 1)
    5531          66 :                 m_eTF = GPKG_TF_PNG;
    5532             :         }
    5533             : 
    5534         188 :         if (eDT != GDT_Byte)
    5535             :         {
    5536          40 :             if (!CreateTileGriddedTable(papszOptions))
    5537           0 :                 return FALSE;
    5538             :         }
    5539             : 
    5540         188 :         nRasterXSize = nXSize;
    5541         188 :         nRasterYSize = nYSize;
    5542             : 
    5543             :         const char *pszTileSize =
    5544         188 :             CSLFetchNameValueDef(papszOptions, "BLOCKSIZE", "256");
    5545             :         const char *pszTileWidth =
    5546         188 :             CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", pszTileSize);
    5547             :         const char *pszTileHeight =
    5548         188 :             CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", pszTileSize);
    5549         188 :         int nTileWidth = atoi(pszTileWidth);
    5550         188 :         int nTileHeight = atoi(pszTileHeight);
    5551         188 :         if ((nTileWidth < 8 || nTileWidth > 4096 || nTileHeight < 8 ||
    5552         376 :              nTileHeight > 4096) &&
    5553           1 :             !CPLTestBool(CPLGetConfigOption("GPKG_ALLOW_CRAZY_SETTINGS", "NO")))
    5554             :         {
    5555           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5556             :                      "Invalid block dimensions: %dx%d", nTileWidth,
    5557             :                      nTileHeight);
    5558           0 :             return FALSE;
    5559             :         }
    5560             : 
    5561         509 :         for (int i = 1; i <= nBandsIn; i++)
    5562             :         {
    5563         321 :             SetBand(i, std::make_unique<GDALGeoPackageRasterBand>(
    5564             :                            this, nTileWidth, nTileHeight));
    5565             :         }
    5566             : 
    5567         188 :         GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL",
    5568             :                                         "IMAGE_STRUCTURE");
    5569         188 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", m_osIdentifier);
    5570         188 :         if (!m_osDescription.empty())
    5571           1 :             GDALPamDataset::SetMetadataItem("DESCRIPTION", m_osDescription);
    5572             : 
    5573         188 :         ParseCompressionOptions(papszOptions);
    5574             : 
    5575         188 :         if (m_eTF == GPKG_TF_WEBP)
    5576             :         {
    5577          10 :             if (!RegisterWebPExtension())
    5578           0 :                 return FALSE;
    5579             :         }
    5580             : 
    5581             :         m_osTilingScheme =
    5582         188 :             CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5583         188 :         if (!EQUAL(m_osTilingScheme, "CUSTOM"))
    5584             :         {
    5585          22 :             const auto poTS = GetTilingScheme(m_osTilingScheme);
    5586          22 :             if (!poTS)
    5587           0 :                 return FALSE;
    5588             : 
    5589          43 :             if (nTileWidth != poTS->nTileWidth ||
    5590          21 :                 nTileHeight != poTS->nTileHeight)
    5591             :             {
    5592           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    5593             :                          "Tile dimension should be %dx%d for %s tiling scheme",
    5594           1 :                          poTS->nTileWidth, poTS->nTileHeight,
    5595             :                          m_osTilingScheme.c_str());
    5596           1 :                 return FALSE;
    5597             :             }
    5598             : 
    5599             :             const char *pszZoomLevel =
    5600          21 :                 CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    5601          21 :             if (pszZoomLevel)
    5602             :             {
    5603           1 :                 m_nZoomLevel = atoi(pszZoomLevel);
    5604           1 :                 int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    5605           1 :                 while ((1 << nMaxZoomLevelForThisTM) >
    5606           2 :                            INT_MAX / poTS->nTileXCountZoomLevel0 ||
    5607           1 :                        (1 << nMaxZoomLevelForThisTM) >
    5608           1 :                            INT_MAX / poTS->nTileYCountZoomLevel0)
    5609             :                 {
    5610           0 :                     --nMaxZoomLevelForThisTM;
    5611             :                 }
    5612             : 
    5613           1 :                 if (m_nZoomLevel < 0 || m_nZoomLevel > nMaxZoomLevelForThisTM)
    5614             :                 {
    5615           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    5616             :                              "ZOOM_LEVEL = %s is invalid. It should be in "
    5617             :                              "[0,%d] range",
    5618             :                              pszZoomLevel, nMaxZoomLevelForThisTM);
    5619           0 :                     return FALSE;
    5620             :                 }
    5621             :             }
    5622             : 
    5623             :             // Implicitly sets SRS.
    5624          21 :             OGRSpatialReference oSRS;
    5625          21 :             if (oSRS.importFromEPSG(poTS->nEPSGCode) != OGRERR_NONE)
    5626           0 :                 return FALSE;
    5627          21 :             char *pszWKT = nullptr;
    5628          21 :             oSRS.exportToWkt(&pszWKT);
    5629          21 :             SetProjection(pszWKT);
    5630          21 :             CPLFree(pszWKT);
    5631             :         }
    5632             :         else
    5633             :         {
    5634         166 :             if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5635             :             {
    5636           0 :                 CPLError(
    5637             :                     CE_Failure, CPLE_NotSupported,
    5638             :                     "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5639           0 :                 return false;
    5640             :             }
    5641             :         }
    5642             :     }
    5643             : 
    5644         852 :     if (bFileExists && nBandsIn > 0 && eDT == GDT_Byte)
    5645             :     {
    5646             :         // If there was an ogr_empty_table table, we can remove it
    5647           9 :         RemoveOGREmptyTable();
    5648             :     }
    5649             : 
    5650         852 :     SoftCommitTransaction();
    5651             : 
    5652             :     /* Requirement 2 */
    5653             :     /* We have to do this after there's some content so the database file */
    5654             :     /* is not zero length */
    5655         852 :     SetApplicationAndUserVersionId();
    5656             : 
    5657             :     /* Default to synchronous=off for performance for new file */
    5658        1694 :     if (!bFileExists &&
    5659         842 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5660             :     {
    5661         345 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5662             :     }
    5663             : 
    5664         852 :     return TRUE;
    5665             : }
    5666             : 
    5667             : /************************************************************************/
    5668             : /*                        RemoveOGREmptyTable()                         */
    5669             : /************************************************************************/
    5670             : 
    5671         665 : void GDALGeoPackageDataset::RemoveOGREmptyTable()
    5672             : {
    5673             :     // Run with sqlite3_exec since we don't want errors to be emitted
    5674         665 :     sqlite3_exec(hDB, "DROP TABLE IF EXISTS ogr_empty_table", nullptr, nullptr,
    5675             :                  nullptr);
    5676         665 :     sqlite3_exec(
    5677             :         hDB, "DELETE FROM gpkg_contents WHERE table_name = 'ogr_empty_table'",
    5678             :         nullptr, nullptr, nullptr);
    5679             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5680         665 :     if (m_bHasGPKGOGRContents)
    5681             :     {
    5682         651 :         sqlite3_exec(hDB,
    5683             :                      "DELETE FROM gpkg_ogr_contents WHERE "
    5684             :                      "table_name = 'ogr_empty_table'",
    5685             :                      nullptr, nullptr, nullptr);
    5686             :     }
    5687             : #endif
    5688         665 :     sqlite3_exec(hDB,
    5689             :                  "DELETE FROM gpkg_geometry_columns WHERE "
    5690             :                  "table_name = 'ogr_empty_table'",
    5691             :                  nullptr, nullptr, nullptr);
    5692         665 : }
    5693             : 
    5694             : /************************************************************************/
    5695             : /*                        CreateTileGriddedTable()                      */
    5696             : /************************************************************************/
    5697             : 
    5698          40 : bool GDALGeoPackageDataset::CreateTileGriddedTable(char **papszOptions)
    5699             : {
    5700          80 :     CPLString osSQL;
    5701          40 :     if (!HasGriddedCoverageAncillaryTable())
    5702             :     {
    5703             :         // It doesn't exist. So create gpkg_extensions table if necessary, and
    5704             :         // gpkg_2d_gridded_coverage_ancillary & gpkg_2d_gridded_tile_ancillary,
    5705             :         // and register them as extensions.
    5706          40 :         if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    5707           0 :             return false;
    5708             : 
    5709             :         // Req 1 /table-defs/coverage-ancillary
    5710             :         osSQL = "CREATE TABLE gpkg_2d_gridded_coverage_ancillary ("
    5711             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5712             :                 "tile_matrix_set_name TEXT NOT NULL UNIQUE,"
    5713             :                 "datatype TEXT NOT NULL DEFAULT 'integer',"
    5714             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5715             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5716             :                 "precision REAL DEFAULT 1.0,"
    5717             :                 "data_null REAL,"
    5718             :                 "grid_cell_encoding TEXT DEFAULT 'grid-value-is-center',"
    5719             :                 "uom TEXT,"
    5720             :                 "field_name TEXT DEFAULT 'Height',"
    5721             :                 "quantity_definition TEXT DEFAULT 'Height',"
    5722             :                 "CONSTRAINT fk_g2dgtct_name FOREIGN KEY(tile_matrix_set_name) "
    5723             :                 "REFERENCES gpkg_tile_matrix_set ( table_name ) "
    5724             :                 "CHECK (datatype in ('integer','float')))"
    5725             :                 ";"
    5726             :                 // Requirement 2 /table-defs/tile-ancillary
    5727             :                 "CREATE TABLE gpkg_2d_gridded_tile_ancillary ("
    5728             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5729             :                 "tpudt_name TEXT NOT NULL,"
    5730             :                 "tpudt_id INTEGER NOT NULL,"
    5731             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5732             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5733             :                 "min REAL DEFAULT NULL,"
    5734             :                 "max REAL DEFAULT NULL,"
    5735             :                 "mean REAL DEFAULT NULL,"
    5736             :                 "std_dev REAL DEFAULT NULL,"
    5737             :                 "CONSTRAINT fk_g2dgtat_name FOREIGN KEY (tpudt_name) "
    5738             :                 "REFERENCES gpkg_contents(table_name),"
    5739             :                 "UNIQUE (tpudt_name, tpudt_id))"
    5740             :                 ";"
    5741             :                 // Requirement 6 /gpkg-extensions
    5742             :                 "INSERT INTO gpkg_extensions "
    5743             :                 "(table_name, column_name, extension_name, definition, scope) "
    5744             :                 "VALUES ('gpkg_2d_gridded_coverage_ancillary', NULL, "
    5745             :                 "'gpkg_2d_gridded_coverage', "
    5746             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5747             :                 "'read-write')"
    5748             :                 ";"
    5749             :                 // Requirement 6 /gpkg-extensions
    5750             :                 "INSERT INTO gpkg_extensions "
    5751             :                 "(table_name, column_name, extension_name, definition, scope) "
    5752             :                 "VALUES ('gpkg_2d_gridded_tile_ancillary', NULL, "
    5753             :                 "'gpkg_2d_gridded_coverage', "
    5754             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5755             :                 "'read-write')"
    5756          40 :                 ";";
    5757             :     }
    5758             : 
    5759             :     // Requirement 6 /gpkg-extensions
    5760          40 :     char *pszSQL = sqlite3_mprintf(
    5761             :         "INSERT INTO gpkg_extensions "
    5762             :         "(table_name, column_name, extension_name, definition, scope) "
    5763             :         "VALUES ('%q', 'tile_data', "
    5764             :         "'gpkg_2d_gridded_coverage', "
    5765             :         "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5766             :         "'read-write')",
    5767             :         m_osRasterTable.c_str());
    5768          40 :     osSQL += pszSQL;
    5769          40 :     osSQL += ";";
    5770          40 :     sqlite3_free(pszSQL);
    5771             : 
    5772             :     // Requirement 7 /gpkg-2d-gridded-coverage-ancillary
    5773             :     // Requirement 8 /gpkg-2d-gridded-coverage-ancillary-set-name
    5774             :     // Requirement 9 /gpkg-2d-gridded-coverage-ancillary-datatype
    5775          40 :     m_dfPrecision =
    5776          40 :         CPLAtof(CSLFetchNameValueDef(papszOptions, "PRECISION", "1"));
    5777             :     CPLString osGridCellEncoding(CSLFetchNameValueDef(
    5778          80 :         papszOptions, "GRID_CELL_ENCODING", "grid-value-is-center"));
    5779          40 :     m_bGridCellEncodingAsCO =
    5780          40 :         CSLFetchNameValue(papszOptions, "GRID_CELL_ENCODING") != nullptr;
    5781          80 :     CPLString osUom(CSLFetchNameValueDef(papszOptions, "UOM", ""));
    5782             :     CPLString osFieldName(
    5783          80 :         CSLFetchNameValueDef(papszOptions, "FIELD_NAME", "Height"));
    5784             :     CPLString osQuantityDefinition(
    5785          80 :         CSLFetchNameValueDef(papszOptions, "QUANTITY_DEFINITION", "Height"));
    5786             : 
    5787         121 :     pszSQL = sqlite3_mprintf(
    5788             :         "INSERT INTO gpkg_2d_gridded_coverage_ancillary "
    5789             :         "(tile_matrix_set_name, datatype, scale, offset, precision, "
    5790             :         "grid_cell_encoding, uom, field_name, quantity_definition) "
    5791             :         "VALUES (%Q, '%s', %.17g, %.17g, %.17g, %Q, %Q, %Q, %Q)",
    5792             :         m_osRasterTable.c_str(),
    5793          40 :         (m_eTF == GPKG_TF_PNG_16BIT) ? "integer" : "float", m_dfScale,
    5794             :         m_dfOffset, m_dfPrecision, osGridCellEncoding.c_str(),
    5795          41 :         osUom.empty() ? nullptr : osUom.c_str(), osFieldName.c_str(),
    5796             :         osQuantityDefinition.c_str());
    5797          40 :     m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary = pszSQL;
    5798          40 :     sqlite3_free(pszSQL);
    5799             : 
    5800             :     // Requirement 3 /gpkg-spatial-ref-sys-row
    5801             :     auto oResultTable = SQLQuery(
    5802          80 :         hDB, "SELECT * FROM gpkg_spatial_ref_sys WHERE srs_id = 4979 LIMIT 2");
    5803          40 :     bool bHasEPSG4979 = (oResultTable && oResultTable->RowCount() == 1);
    5804          40 :     if (!bHasEPSG4979)
    5805             :     {
    5806          41 :         if (!m_bHasDefinition12_063 &&
    5807           1 :             !ConvertGpkgSpatialRefSysToExtensionWkt2(/*bForceEpoch=*/false))
    5808             :         {
    5809           0 :             return false;
    5810             :         }
    5811             : 
    5812             :         // This is WKT 2...
    5813          40 :         const char *pszWKT =
    5814             :             "GEODCRS[\"WGS 84\","
    5815             :             "DATUM[\"World Geodetic System 1984\","
    5816             :             "  ELLIPSOID[\"WGS 84\",6378137,298.257223563,"
    5817             :             "LENGTHUNIT[\"metre\",1.0]]],"
    5818             :             "CS[ellipsoidal,3],"
    5819             :             "  AXIS[\"latitude\",north,ORDER[1],ANGLEUNIT[\"degree\","
    5820             :             "0.0174532925199433]],"
    5821             :             "  AXIS[\"longitude\",east,ORDER[2],ANGLEUNIT[\"degree\","
    5822             :             "0.0174532925199433]],"
    5823             :             "  AXIS[\"ellipsoidal height\",up,ORDER[3],"
    5824             :             "LENGTHUNIT[\"metre\",1.0]],"
    5825             :             "ID[\"EPSG\",4979]]";
    5826             : 
    5827          40 :         pszSQL = sqlite3_mprintf(
    5828             :             "INSERT INTO gpkg_spatial_ref_sys "
    5829             :             "(srs_name,srs_id,organization,organization_coordsys_id,"
    5830             :             "definition,definition_12_063) VALUES "
    5831             :             "('WGS 84 3D', 4979, 'EPSG', 4979, 'undefined', '%q')",
    5832             :             pszWKT);
    5833          40 :         osSQL += ";";
    5834          40 :         osSQL += pszSQL;
    5835          40 :         sqlite3_free(pszSQL);
    5836             :     }
    5837             : 
    5838          40 :     return SQLCommand(hDB, osSQL) == OGRERR_NONE;
    5839             : }
    5840             : 
    5841             : /************************************************************************/
    5842             : /*                    HasGriddedCoverageAncillaryTable()                */
    5843             : /************************************************************************/
    5844             : 
    5845          44 : bool GDALGeoPackageDataset::HasGriddedCoverageAncillaryTable()
    5846             : {
    5847             :     auto oResultTable = SQLQuery(
    5848             :         hDB, "SELECT * FROM sqlite_master WHERE type IN ('table', 'view') AND "
    5849          44 :              "name = 'gpkg_2d_gridded_coverage_ancillary'");
    5850          44 :     bool bHasTable = (oResultTable && oResultTable->RowCount() == 1);
    5851          88 :     return bHasTable;
    5852             : }
    5853             : 
    5854             : /************************************************************************/
    5855             : /*                      GetUnderlyingDataset()                          */
    5856             : /************************************************************************/
    5857             : 
    5858           3 : static GDALDataset *GetUnderlyingDataset(GDALDataset *poSrcDS)
    5859             : {
    5860           3 :     if (auto poVRTDS = dynamic_cast<VRTDataset *>(poSrcDS))
    5861             :     {
    5862           0 :         auto poTmpDS = poVRTDS->GetSingleSimpleSource();
    5863           0 :         if (poTmpDS)
    5864           0 :             return poTmpDS;
    5865             :     }
    5866             : 
    5867           3 :     return poSrcDS;
    5868             : }
    5869             : 
    5870             : /************************************************************************/
    5871             : /*                            CreateCopy()                              */
    5872             : /************************************************************************/
    5873             : 
    5874             : typedef struct
    5875             : {
    5876             :     const char *pszName;
    5877             :     GDALResampleAlg eResampleAlg;
    5878             : } WarpResamplingAlg;
    5879             : 
    5880             : static const WarpResamplingAlg asResamplingAlg[] = {
    5881             :     {"NEAREST", GRA_NearestNeighbour},
    5882             :     {"BILINEAR", GRA_Bilinear},
    5883             :     {"CUBIC", GRA_Cubic},
    5884             :     {"CUBICSPLINE", GRA_CubicSpline},
    5885             :     {"LANCZOS", GRA_Lanczos},
    5886             :     {"MODE", GRA_Mode},
    5887             :     {"AVERAGE", GRA_Average},
    5888             :     {"RMS", GRA_RMS},
    5889             : };
    5890             : 
    5891         160 : GDALDataset *GDALGeoPackageDataset::CreateCopy(const char *pszFilename,
    5892             :                                                GDALDataset *poSrcDS,
    5893             :                                                int bStrict, char **papszOptions,
    5894             :                                                GDALProgressFunc pfnProgress,
    5895             :                                                void *pProgressData)
    5896             : {
    5897         160 :     const int nBands = poSrcDS->GetRasterCount();
    5898         160 :     if (nBands == 0)
    5899             :     {
    5900           2 :         GDALDataset *poDS = nullptr;
    5901             :         GDALDriver *poThisDriver =
    5902           2 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5903           2 :         if (poThisDriver != nullptr)
    5904             :         {
    5905           2 :             poDS = poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS,
    5906             :                                                    bStrict, papszOptions,
    5907             :                                                    pfnProgress, pProgressData);
    5908             :         }
    5909           2 :         return poDS;
    5910             :     }
    5911             : 
    5912             :     const char *pszTilingScheme =
    5913         158 :         CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5914             : 
    5915         316 :     CPLStringList apszUpdatedOptions(CSLDuplicate(papszOptions));
    5916         158 :     if (CPLTestBool(
    5917         164 :             CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")) &&
    5918           6 :         CSLFetchNameValue(papszOptions, "RASTER_TABLE") == nullptr)
    5919             :     {
    5920             :         const std::string osBasename(CPLGetBasenameSafe(
    5921           6 :             GetUnderlyingDataset(poSrcDS)->GetDescription()));
    5922           3 :         apszUpdatedOptions.SetNameValue("RASTER_TABLE", osBasename.c_str());
    5923             :     }
    5924             : 
    5925         158 :     if (nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4)
    5926             :     {
    5927           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    5928             :                  "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or "
    5929             :                  "4 (RGBA) band dataset supported");
    5930           1 :         return nullptr;
    5931             :     }
    5932             : 
    5933         157 :     const char *pszUnitType = poSrcDS->GetRasterBand(1)->GetUnitType();
    5934         314 :     if (CSLFetchNameValue(papszOptions, "UOM") == nullptr && pszUnitType &&
    5935         157 :         !EQUAL(pszUnitType, ""))
    5936             :     {
    5937           1 :         apszUpdatedOptions.SetNameValue("UOM", pszUnitType);
    5938             :     }
    5939             : 
    5940         157 :     if (EQUAL(pszTilingScheme, "CUSTOM"))
    5941             :     {
    5942         133 :         if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5943             :         {
    5944           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    5945             :                      "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5946           0 :             return nullptr;
    5947             :         }
    5948             : 
    5949         133 :         GDALGeoPackageDataset *poDS = nullptr;
    5950             :         GDALDriver *poThisDriver =
    5951         133 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5952         133 :         if (poThisDriver != nullptr)
    5953             :         {
    5954         133 :             apszUpdatedOptions.SetNameValue("SKIP_HOLES", "YES");
    5955         133 :             poDS = cpl::down_cast<GDALGeoPackageDataset *>(
    5956             :                 poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS, bStrict,
    5957             :                                                 apszUpdatedOptions, pfnProgress,
    5958         133 :                                                 pProgressData));
    5959             : 
    5960         246 :             if (poDS != nullptr &&
    5961         133 :                 poSrcDS->GetRasterBand(1)->GetRasterDataType() == GDT_Byte &&
    5962             :                 nBands <= 3)
    5963             :             {
    5964          73 :                 poDS->m_nBandCountFromMetadata = nBands;
    5965          73 :                 poDS->m_bMetadataDirty = true;
    5966             :             }
    5967             :         }
    5968         133 :         if (poDS)
    5969         113 :             poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    5970         133 :         return poDS;
    5971             :     }
    5972             : 
    5973          48 :     const auto poTS = GetTilingScheme(pszTilingScheme);
    5974          24 :     if (!poTS)
    5975             :     {
    5976           2 :         return nullptr;
    5977             :     }
    5978          22 :     const int nEPSGCode = poTS->nEPSGCode;
    5979             : 
    5980          44 :     OGRSpatialReference oSRS;
    5981          22 :     if (oSRS.importFromEPSG(nEPSGCode) != OGRERR_NONE)
    5982             :     {
    5983           0 :         return nullptr;
    5984             :     }
    5985          22 :     char *pszWKT = nullptr;
    5986          22 :     oSRS.exportToWkt(&pszWKT);
    5987          22 :     char **papszTO = CSLSetNameValue(nullptr, "DST_SRS", pszWKT);
    5988             : 
    5989          22 :     void *hTransformArg = nullptr;
    5990             : 
    5991             :     // Hack to compensate for GDALSuggestedWarpOutput2() failure (or not
    5992             :     // ideal suggestion with PROJ 8) when reprojecting latitude = +/- 90 to
    5993             :     // EPSG:3857.
    5994             :     double adfSrcGeoTransform[6];
    5995          22 :     std::unique_ptr<GDALDataset> poTmpDS;
    5996          22 :     bool bEPSG3857Adjust = false;
    5997          30 :     if (nEPSGCode == 3857 &&
    5998           8 :         poSrcDS->GetGeoTransform(adfSrcGeoTransform) == CE_None &&
    5999          38 :         adfSrcGeoTransform[2] == 0 && adfSrcGeoTransform[4] == 0 &&
    6000           8 :         adfSrcGeoTransform[5] < 0)
    6001             :     {
    6002           8 :         const auto poSrcSRS = poSrcDS->GetSpatialRef();
    6003           8 :         if (poSrcSRS && poSrcSRS->IsGeographic())
    6004             :         {
    6005           2 :             double maxLat = adfSrcGeoTransform[3];
    6006           2 :             double minLat = adfSrcGeoTransform[3] +
    6007           2 :                             poSrcDS->GetRasterYSize() * adfSrcGeoTransform[5];
    6008             :             // Corresponds to the latitude of below MAX_GM
    6009           2 :             constexpr double MAX_LAT = 85.0511287798066;
    6010           2 :             bool bModified = false;
    6011           2 :             if (maxLat > MAX_LAT)
    6012             :             {
    6013           2 :                 maxLat = MAX_LAT;
    6014           2 :                 bModified = true;
    6015             :             }
    6016           2 :             if (minLat < -MAX_LAT)
    6017             :             {
    6018           2 :                 minLat = -MAX_LAT;
    6019           2 :                 bModified = true;
    6020             :             }
    6021           2 :             if (bModified)
    6022             :             {
    6023           4 :                 CPLStringList aosOptions;
    6024           2 :                 aosOptions.AddString("-of");
    6025           2 :                 aosOptions.AddString("VRT");
    6026           2 :                 aosOptions.AddString("-projwin");
    6027             :                 aosOptions.AddString(
    6028           2 :                     CPLSPrintf("%.17g", adfSrcGeoTransform[0]));
    6029           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", maxLat));
    6030             :                 aosOptions.AddString(
    6031           2 :                     CPLSPrintf("%.17g", adfSrcGeoTransform[0] +
    6032           2 :                                             poSrcDS->GetRasterXSize() *
    6033           2 :                                                 adfSrcGeoTransform[1]));
    6034           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", minLat));
    6035             :                 auto psOptions =
    6036           2 :                     GDALTranslateOptionsNew(aosOptions.List(), nullptr);
    6037           2 :                 poTmpDS.reset(GDALDataset::FromHandle(GDALTranslate(
    6038             :                     "", GDALDataset::ToHandle(poSrcDS), psOptions, nullptr)));
    6039           2 :                 GDALTranslateOptionsFree(psOptions);
    6040           2 :                 if (poTmpDS)
    6041             :                 {
    6042           2 :                     bEPSG3857Adjust = true;
    6043           2 :                     hTransformArg = GDALCreateGenImgProjTransformer2(
    6044           2 :                         GDALDataset::FromHandle(poTmpDS.get()), nullptr,
    6045             :                         papszTO);
    6046             :                 }
    6047             :             }
    6048             :         }
    6049             :     }
    6050          22 :     if (hTransformArg == nullptr)
    6051             :     {
    6052             :         hTransformArg =
    6053          20 :             GDALCreateGenImgProjTransformer2(poSrcDS, nullptr, papszTO);
    6054             :     }
    6055             : 
    6056          22 :     if (hTransformArg == nullptr)
    6057             :     {
    6058           1 :         CPLFree(pszWKT);
    6059           1 :         CSLDestroy(papszTO);
    6060           1 :         return nullptr;
    6061             :     }
    6062             : 
    6063          21 :     GDALTransformerInfo *psInfo =
    6064             :         static_cast<GDALTransformerInfo *>(hTransformArg);
    6065             :     double adfGeoTransform[6];
    6066             :     double adfExtent[4];
    6067             :     int nXSize, nYSize;
    6068             : 
    6069          21 :     if (GDALSuggestedWarpOutput2(poSrcDS, psInfo->pfnTransform, hTransformArg,
    6070             :                                  adfGeoTransform, &nXSize, &nYSize, adfExtent,
    6071          21 :                                  0) != CE_None)
    6072             :     {
    6073           0 :         CPLFree(pszWKT);
    6074           0 :         CSLDestroy(papszTO);
    6075           0 :         GDALDestroyGenImgProjTransformer(hTransformArg);
    6076           0 :         return nullptr;
    6077             :     }
    6078             : 
    6079          21 :     GDALDestroyGenImgProjTransformer(hTransformArg);
    6080          21 :     hTransformArg = nullptr;
    6081          21 :     poTmpDS.reset();
    6082             : 
    6083          21 :     if (bEPSG3857Adjust)
    6084             :     {
    6085           2 :         constexpr double SPHERICAL_RADIUS = 6378137.0;
    6086           2 :         constexpr double MAX_GM =
    6087             :             SPHERICAL_RADIUS * M_PI;  // 20037508.342789244
    6088           2 :         double maxNorthing = adfGeoTransform[3];
    6089           2 :         double minNorthing = adfGeoTransform[3] + adfGeoTransform[5] * nYSize;
    6090           2 :         bool bChanged = false;
    6091           2 :         if (maxNorthing > MAX_GM)
    6092             :         {
    6093           2 :             bChanged = true;
    6094           2 :             maxNorthing = MAX_GM;
    6095             :         }
    6096           2 :         if (minNorthing < -MAX_GM)
    6097             :         {
    6098           2 :             bChanged = true;
    6099           2 :             minNorthing = -MAX_GM;
    6100             :         }
    6101           2 :         if (bChanged)
    6102             :         {
    6103           2 :             adfGeoTransform[3] = maxNorthing;
    6104           2 :             nYSize =
    6105           2 :                 int((maxNorthing - minNorthing) / (-adfGeoTransform[5]) + 0.5);
    6106           2 :             adfExtent[1] = maxNorthing + nYSize * adfGeoTransform[5];
    6107           2 :             adfExtent[3] = maxNorthing;
    6108             :         }
    6109             :     }
    6110             : 
    6111          21 :     double dfComputedRes = adfGeoTransform[1];
    6112          21 :     double dfPrevRes = 0.0;
    6113          21 :     double dfRes = 0.0;
    6114          21 :     int nZoomLevel = 0;  // Used after for.
    6115          21 :     const char *pszZoomLevel = CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    6116          21 :     if (pszZoomLevel)
    6117             :     {
    6118           2 :         nZoomLevel = atoi(pszZoomLevel);
    6119             : 
    6120           2 :         int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    6121           2 :         while ((1 << nMaxZoomLevelForThisTM) >
    6122           4 :                    INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6123           2 :                (1 << nMaxZoomLevelForThisTM) >
    6124           2 :                    INT_MAX / poTS->nTileYCountZoomLevel0)
    6125             :         {
    6126           0 :             --nMaxZoomLevelForThisTM;
    6127             :         }
    6128             : 
    6129           2 :         if (nZoomLevel < 0 || nZoomLevel > nMaxZoomLevelForThisTM)
    6130             :         {
    6131           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6132             :                      "ZOOM_LEVEL = %s is invalid. It should be in [0,%d] range",
    6133             :                      pszZoomLevel, nMaxZoomLevelForThisTM);
    6134           1 :             CPLFree(pszWKT);
    6135           1 :             CSLDestroy(papszTO);
    6136           1 :             return nullptr;
    6137             :         }
    6138             :     }
    6139             :     else
    6140             :     {
    6141         171 :         for (; nZoomLevel < MAX_ZOOM_LEVEL; nZoomLevel++)
    6142             :         {
    6143         171 :             dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6144         171 :             if (dfComputedRes > dfRes ||
    6145         152 :                 fabs(dfComputedRes - dfRes) / dfRes <= 1e-8)
    6146             :                 break;
    6147         152 :             dfPrevRes = dfRes;
    6148             :         }
    6149          38 :         if (nZoomLevel == MAX_ZOOM_LEVEL ||
    6150          38 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6151          19 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileYCountZoomLevel0)
    6152             :         {
    6153           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6154             :                      "Could not find an appropriate zoom level");
    6155           0 :             CPLFree(pszWKT);
    6156           0 :             CSLDestroy(papszTO);
    6157           0 :             return nullptr;
    6158             :         }
    6159             : 
    6160          19 :         if (nZoomLevel > 0 && fabs(dfComputedRes - dfRes) / dfRes > 1e-8)
    6161             :         {
    6162          17 :             const char *pszZoomLevelStrategy = CSLFetchNameValueDef(
    6163             :                 papszOptions, "ZOOM_LEVEL_STRATEGY", "AUTO");
    6164          17 :             if (EQUAL(pszZoomLevelStrategy, "LOWER"))
    6165             :             {
    6166           1 :                 nZoomLevel--;
    6167             :             }
    6168          16 :             else if (EQUAL(pszZoomLevelStrategy, "UPPER"))
    6169             :             {
    6170             :                 /* do nothing */
    6171             :             }
    6172             :             else
    6173             :             {
    6174          15 :                 if (dfPrevRes / dfComputedRes < dfComputedRes / dfRes)
    6175          13 :                     nZoomLevel--;
    6176             :             }
    6177             :         }
    6178             :     }
    6179             : 
    6180          20 :     dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6181             : 
    6182          20 :     double dfMinX = adfExtent[0];
    6183          20 :     double dfMinY = adfExtent[1];
    6184          20 :     double dfMaxX = adfExtent[2];
    6185          20 :     double dfMaxY = adfExtent[3];
    6186             : 
    6187          20 :     nXSize = static_cast<int>(0.5 + (dfMaxX - dfMinX) / dfRes);
    6188          20 :     nYSize = static_cast<int>(0.5 + (dfMaxY - dfMinY) / dfRes);
    6189          20 :     adfGeoTransform[1] = dfRes;
    6190          20 :     adfGeoTransform[5] = -dfRes;
    6191             : 
    6192          20 :     const GDALDataType eDT = poSrcDS->GetRasterBand(1)->GetRasterDataType();
    6193          20 :     int nTargetBands = nBands;
    6194             :     /* For grey level or RGB, if there's reprojection involved, add an alpha */
    6195             :     /* channel */
    6196          37 :     if (eDT == GDT_Byte &&
    6197          13 :         ((nBands == 1 &&
    6198          17 :           poSrcDS->GetRasterBand(1)->GetColorTable() == nullptr) ||
    6199             :          nBands == 3))
    6200             :     {
    6201          30 :         OGRSpatialReference oSrcSRS;
    6202          15 :         oSrcSRS.SetFromUserInput(poSrcDS->GetProjectionRef());
    6203          15 :         oSrcSRS.AutoIdentifyEPSG();
    6204          30 :         if (oSrcSRS.GetAuthorityCode(nullptr) == nullptr ||
    6205          15 :             atoi(oSrcSRS.GetAuthorityCode(nullptr)) != nEPSGCode)
    6206             :         {
    6207          13 :             nTargetBands++;
    6208             :         }
    6209             :     }
    6210             : 
    6211          20 :     GDALResampleAlg eResampleAlg = GRA_Bilinear;
    6212          20 :     const char *pszResampling = CSLFetchNameValue(papszOptions, "RESAMPLING");
    6213          20 :     if (pszResampling)
    6214             :     {
    6215           6 :         for (size_t iAlg = 0;
    6216           6 :              iAlg < sizeof(asResamplingAlg) / sizeof(asResamplingAlg[0]);
    6217             :              iAlg++)
    6218             :         {
    6219           6 :             if (EQUAL(pszResampling, asResamplingAlg[iAlg].pszName))
    6220             :             {
    6221           3 :                 eResampleAlg = asResamplingAlg[iAlg].eResampleAlg;
    6222           3 :                 break;
    6223             :             }
    6224             :         }
    6225             :     }
    6226             : 
    6227          16 :     if (nBands == 1 && poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    6228          36 :         eResampleAlg != GRA_NearestNeighbour && eResampleAlg != GRA_Mode)
    6229             :     {
    6230           0 :         CPLError(
    6231             :             CE_Warning, CPLE_AppDefined,
    6232             :             "Input dataset has a color table, which will likely lead to "
    6233             :             "bad results when using a resampling method other than "
    6234             :             "nearest neighbour or mode. Converting the dataset to 24/32 bit "
    6235             :             "(e.g. with gdal_translate -expand rgb/rgba) is advised.");
    6236             :     }
    6237             : 
    6238          40 :     auto poDS = std::make_unique<GDALGeoPackageDataset>();
    6239          20 :     if (!(poDS->Create(pszFilename, nXSize, nYSize, nTargetBands, eDT,
    6240             :                        apszUpdatedOptions)))
    6241             :     {
    6242           1 :         CPLFree(pszWKT);
    6243           1 :         CSLDestroy(papszTO);
    6244           1 :         return nullptr;
    6245             :     }
    6246             : 
    6247             :     // Assign nodata values before the SetGeoTransform call.
    6248             :     // SetGeoTransform will trigger creation of the overview datasets for each
    6249             :     // zoom level and at that point the nodata value needs to be known.
    6250          19 :     int bHasNoData = FALSE;
    6251             :     double dfNoDataValue =
    6252          19 :         poSrcDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    6253          19 :     if (eDT != GDT_Byte && bHasNoData)
    6254             :     {
    6255           3 :         poDS->GetRasterBand(1)->SetNoDataValue(dfNoDataValue);
    6256             :     }
    6257             : 
    6258          19 :     poDS->SetGeoTransform(adfGeoTransform);
    6259          19 :     poDS->SetProjection(pszWKT);
    6260          19 :     CPLFree(pszWKT);
    6261          19 :     pszWKT = nullptr;
    6262          24 :     if (nTargetBands == 1 && nBands == 1 &&
    6263           5 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
    6264             :     {
    6265           2 :         poDS->GetRasterBand(1)->SetColorTable(
    6266           1 :             poSrcDS->GetRasterBand(1)->GetColorTable());
    6267             :     }
    6268             : 
    6269             :     hTransformArg =
    6270          19 :         GDALCreateGenImgProjTransformer2(poSrcDS, poDS.get(), papszTO);
    6271          19 :     CSLDestroy(papszTO);
    6272          19 :     if (hTransformArg == nullptr)
    6273             :     {
    6274           0 :         return nullptr;
    6275             :     }
    6276             : 
    6277          19 :     poDS->SetMetadata(poSrcDS->GetMetadata());
    6278             : 
    6279             :     /* -------------------------------------------------------------------- */
    6280             :     /*      Warp the transformer with a linear approximator                 */
    6281             :     /* -------------------------------------------------------------------- */
    6282          19 :     hTransformArg = GDALCreateApproxTransformer(GDALGenImgProjTransform,
    6283             :                                                 hTransformArg, 0.125);
    6284          19 :     GDALApproxTransformerOwnsSubtransformer(hTransformArg, TRUE);
    6285             : 
    6286             :     /* -------------------------------------------------------------------- */
    6287             :     /*      Setup warp options.                                             */
    6288             :     /* -------------------------------------------------------------------- */
    6289          19 :     GDALWarpOptions *psWO = GDALCreateWarpOptions();
    6290             : 
    6291          19 :     psWO->papszWarpOptions = CSLSetNameValue(nullptr, "OPTIMIZE_SIZE", "YES");
    6292          19 :     psWO->papszWarpOptions =
    6293          19 :         CSLSetNameValue(psWO->papszWarpOptions, "SAMPLE_GRID", "YES");
    6294          19 :     if (bHasNoData)
    6295             :     {
    6296           3 :         if (dfNoDataValue == 0.0)
    6297             :         {
    6298             :             // Do not initialize in the case where nodata != 0, since we
    6299             :             // want the GeoPackage driver to return empty tiles at the nodata
    6300             :             // value instead of 0 as GDAL core would
    6301           0 :             psWO->papszWarpOptions =
    6302           0 :                 CSLSetNameValue(psWO->papszWarpOptions, "INIT_DEST", "0");
    6303             :         }
    6304             : 
    6305           3 :         psWO->padfSrcNoDataReal =
    6306           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6307           3 :         psWO->padfSrcNoDataReal[0] = dfNoDataValue;
    6308             : 
    6309           3 :         psWO->padfDstNoDataReal =
    6310           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6311           3 :         psWO->padfDstNoDataReal[0] = dfNoDataValue;
    6312             :     }
    6313          19 :     psWO->eWorkingDataType = eDT;
    6314          19 :     psWO->eResampleAlg = eResampleAlg;
    6315             : 
    6316          19 :     psWO->hSrcDS = poSrcDS;
    6317          19 :     psWO->hDstDS = poDS.get();
    6318             : 
    6319          19 :     psWO->pfnTransformer = GDALApproxTransform;
    6320          19 :     psWO->pTransformerArg = hTransformArg;
    6321             : 
    6322          19 :     psWO->pfnProgress = pfnProgress;
    6323          19 :     psWO->pProgressArg = pProgressData;
    6324             : 
    6325             :     /* -------------------------------------------------------------------- */
    6326             :     /*      Setup band mapping.                                             */
    6327             :     /* -------------------------------------------------------------------- */
    6328             : 
    6329          19 :     if (nBands == 2 || nBands == 4)
    6330           1 :         psWO->nBandCount = nBands - 1;
    6331             :     else
    6332          18 :         psWO->nBandCount = nBands;
    6333             : 
    6334          19 :     psWO->panSrcBands =
    6335          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6336          19 :     psWO->panDstBands =
    6337          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6338             : 
    6339          46 :     for (int i = 0; i < psWO->nBandCount; i++)
    6340             :     {
    6341          27 :         psWO->panSrcBands[i] = i + 1;
    6342          27 :         psWO->panDstBands[i] = i + 1;
    6343             :     }
    6344             : 
    6345          19 :     if (nBands == 2 || nBands == 4)
    6346             :     {
    6347           1 :         psWO->nSrcAlphaBand = nBands;
    6348             :     }
    6349          19 :     if (nTargetBands == 2 || nTargetBands == 4)
    6350             :     {
    6351          13 :         psWO->nDstAlphaBand = nTargetBands;
    6352             :     }
    6353             : 
    6354             :     /* -------------------------------------------------------------------- */
    6355             :     /*      Initialize and execute the warp.                                */
    6356             :     /* -------------------------------------------------------------------- */
    6357          38 :     GDALWarpOperation oWO;
    6358             : 
    6359          19 :     CPLErr eErr = oWO.Initialize(psWO);
    6360          19 :     if (eErr == CE_None)
    6361             :     {
    6362             :         /*if( bMulti )
    6363             :             eErr = oWO.ChunkAndWarpMulti( 0, 0, nXSize, nYSize );
    6364             :         else*/
    6365          19 :         eErr = oWO.ChunkAndWarpImage(0, 0, nXSize, nYSize);
    6366             :     }
    6367          19 :     if (eErr != CE_None)
    6368             :     {
    6369           0 :         poDS.reset();
    6370             :     }
    6371             : 
    6372          19 :     GDALDestroyTransformer(hTransformArg);
    6373          19 :     GDALDestroyWarpOptions(psWO);
    6374             : 
    6375          19 :     if (poDS)
    6376          19 :         poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    6377             : 
    6378          19 :     return poDS.release();
    6379             : }
    6380             : 
    6381             : /************************************************************************/
    6382             : /*                        ParseCompressionOptions()                     */
    6383             : /************************************************************************/
    6384             : 
    6385         457 : void GDALGeoPackageDataset::ParseCompressionOptions(char **papszOptions)
    6386             : {
    6387         457 :     const char *pszZLevel = CSLFetchNameValue(papszOptions, "ZLEVEL");
    6388         457 :     if (pszZLevel)
    6389           0 :         m_nZLevel = atoi(pszZLevel);
    6390             : 
    6391         457 :     const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
    6392         457 :     if (pszQuality)
    6393           0 :         m_nQuality = atoi(pszQuality);
    6394             : 
    6395         457 :     const char *pszDither = CSLFetchNameValue(papszOptions, "DITHER");
    6396         457 :     if (pszDither)
    6397           0 :         m_bDither = CPLTestBool(pszDither);
    6398         457 : }
    6399             : 
    6400             : /************************************************************************/
    6401             : /*                          RegisterWebPExtension()                     */
    6402             : /************************************************************************/
    6403             : 
    6404          11 : bool GDALGeoPackageDataset::RegisterWebPExtension()
    6405             : {
    6406          11 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6407           0 :         return false;
    6408             : 
    6409          11 :     char *pszSQL = sqlite3_mprintf(
    6410             :         "INSERT INTO gpkg_extensions "
    6411             :         "(table_name, column_name, extension_name, definition, scope) "
    6412             :         "VALUES "
    6413             :         "('%q', 'tile_data', 'gpkg_webp', "
    6414             :         "'http://www.geopackage.org/spec120/#extension_tiles_webp', "
    6415             :         "'read-write')",
    6416             :         m_osRasterTable.c_str());
    6417          11 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6418          11 :     sqlite3_free(pszSQL);
    6419             : 
    6420          11 :     return OGRERR_NONE == eErr;
    6421             : }
    6422             : 
    6423             : /************************************************************************/
    6424             : /*                       RegisterZoomOtherExtension()                   */
    6425             : /************************************************************************/
    6426             : 
    6427           1 : bool GDALGeoPackageDataset::RegisterZoomOtherExtension()
    6428             : {
    6429           1 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6430           0 :         return false;
    6431             : 
    6432           1 :     char *pszSQL = sqlite3_mprintf(
    6433             :         "INSERT INTO gpkg_extensions "
    6434             :         "(table_name, column_name, extension_name, definition, scope) "
    6435             :         "VALUES "
    6436             :         "('%q', 'tile_data', 'gpkg_zoom_other', "
    6437             :         "'http://www.geopackage.org/spec120/#extension_zoom_other_intervals', "
    6438             :         "'read-write')",
    6439             :         m_osRasterTable.c_str());
    6440           1 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6441           1 :     sqlite3_free(pszSQL);
    6442           1 :     return OGRERR_NONE == eErr;
    6443             : }
    6444             : 
    6445             : /************************************************************************/
    6446             : /*                              GetLayer()                              */
    6447             : /************************************************************************/
    6448             : 
    6449       15430 : OGRLayer *GDALGeoPackageDataset::GetLayer(int iLayer)
    6450             : 
    6451             : {
    6452       15430 :     if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
    6453           6 :         return nullptr;
    6454             :     else
    6455       15424 :         return m_apoLayers[iLayer].get();
    6456             : }
    6457             : 
    6458             : /************************************************************************/
    6459             : /*                           LaunderName()                              */
    6460             : /************************************************************************/
    6461             : 
    6462             : /** Launder identifiers (table, column names) according to guidance at
    6463             :  * https://www.geopackage.org/guidance/getting-started.html:
    6464             :  * "For maximum interoperability, start your database identifiers (table names,
    6465             :  * column names, etc.) with a lowercase character and only use lowercase
    6466             :  * characters, numbers 0-9, and underscores (_)."
    6467             :  */
    6468             : 
    6469             : /* static */
    6470           5 : std::string GDALGeoPackageDataset::LaunderName(const std::string &osStr)
    6471             : {
    6472           5 :     char *pszASCII = CPLUTF8ForceToASCII(osStr.c_str(), '_');
    6473          10 :     const std::string osStrASCII(pszASCII);
    6474           5 :     CPLFree(pszASCII);
    6475             : 
    6476          10 :     std::string osRet;
    6477           5 :     osRet.reserve(osStrASCII.size());
    6478             : 
    6479          29 :     for (size_t i = 0; i < osStrASCII.size(); ++i)
    6480             :     {
    6481          24 :         if (osRet.empty())
    6482             :         {
    6483           5 :             if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6484             :             {
    6485           2 :                 osRet += (osStrASCII[i] - 'A' + 'a');
    6486             :             }
    6487           3 :             else if (osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z')
    6488             :             {
    6489           2 :                 osRet += osStrASCII[i];
    6490             :             }
    6491             :             else
    6492             :             {
    6493           1 :                 continue;
    6494             :             }
    6495             :         }
    6496          19 :         else if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6497             :         {
    6498          11 :             osRet += (osStrASCII[i] - 'A' + 'a');
    6499             :         }
    6500           9 :         else if ((osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z') ||
    6501          14 :                  (osStrASCII[i] >= '0' && osStrASCII[i] <= '9') ||
    6502           5 :                  osStrASCII[i] == '_')
    6503             :         {
    6504           7 :             osRet += osStrASCII[i];
    6505             :         }
    6506             :         else
    6507             :         {
    6508           1 :             osRet += '_';
    6509             :         }
    6510             :     }
    6511             : 
    6512           5 :     if (osRet.empty() && !osStrASCII.empty())
    6513           2 :         return LaunderName(std::string("x").append(osStrASCII));
    6514             : 
    6515           4 :     if (osRet != osStr)
    6516             :     {
    6517           3 :         CPLDebug("PG", "LaunderName('%s') -> '%s'", osStr.c_str(),
    6518             :                  osRet.c_str());
    6519             :     }
    6520             : 
    6521           4 :     return osRet;
    6522             : }
    6523             : 
    6524             : /************************************************************************/
    6525             : /*                          ICreateLayer()                              */
    6526             : /************************************************************************/
    6527             : 
    6528             : OGRLayer *
    6529         757 : GDALGeoPackageDataset::ICreateLayer(const char *pszLayerName,
    6530             :                                     const OGRGeomFieldDefn *poSrcGeomFieldDefn,
    6531             :                                     CSLConstList papszOptions)
    6532             : {
    6533             :     /* -------------------------------------------------------------------- */
    6534             :     /*      Verify we are in update mode.                                   */
    6535             :     /* -------------------------------------------------------------------- */
    6536         757 :     if (!GetUpdate())
    6537             :     {
    6538           0 :         CPLError(CE_Failure, CPLE_NoWriteAccess,
    6539             :                  "Data source %s opened read-only.\n"
    6540             :                  "New layer %s cannot be created.\n",
    6541             :                  m_pszFilename, pszLayerName);
    6542             : 
    6543           0 :         return nullptr;
    6544             :     }
    6545             : 
    6546             :     const bool bLaunder =
    6547         757 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "LAUNDER", "NO"));
    6548             :     const std::string osTableName(bLaunder ? LaunderName(pszLayerName)
    6549        2271 :                                            : std::string(pszLayerName));
    6550             : 
    6551             :     const auto eGType =
    6552         757 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
    6553             :     const auto poSpatialRef =
    6554         757 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
    6555             : 
    6556         757 :     if (!m_bHasGPKGGeometryColumns)
    6557             :     {
    6558           1 :         if (SQLCommand(hDB, pszCREATE_GPKG_GEOMETRY_COLUMNS) != OGRERR_NONE)
    6559             :         {
    6560           0 :             return nullptr;
    6561             :         }
    6562           1 :         m_bHasGPKGGeometryColumns = true;
    6563             :     }
    6564             : 
    6565             :     // Check identifier unicity
    6566         757 :     const char *pszIdentifier = CSLFetchNameValue(papszOptions, "IDENTIFIER");
    6567         757 :     if (pszIdentifier != nullptr && pszIdentifier[0] == '\0')
    6568           0 :         pszIdentifier = nullptr;
    6569         757 :     if (pszIdentifier != nullptr)
    6570             :     {
    6571          13 :         for (auto &poLayer : m_apoLayers)
    6572             :         {
    6573             :             const char *pszOtherIdentifier =
    6574           9 :                 poLayer->GetMetadataItem("IDENTIFIER");
    6575           9 :             if (pszOtherIdentifier == nullptr)
    6576           6 :                 pszOtherIdentifier = poLayer->GetName();
    6577          18 :             if (pszOtherIdentifier != nullptr &&
    6578          12 :                 EQUAL(pszOtherIdentifier, pszIdentifier) &&
    6579           3 :                 !EQUAL(poLayer->GetName(), osTableName.c_str()))
    6580             :             {
    6581           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6582             :                          "Identifier %s is already used by table %s",
    6583             :                          pszIdentifier, poLayer->GetName());
    6584           2 :                 return nullptr;
    6585             :             }
    6586             :         }
    6587             : 
    6588             :         // In case there would be table in gpkg_contents not listed as a
    6589             :         // vector layer
    6590           4 :         char *pszSQL = sqlite3_mprintf(
    6591             :             "SELECT table_name FROM gpkg_contents WHERE identifier = '%q' "
    6592             :             "LIMIT 2",
    6593             :             pszIdentifier);
    6594           4 :         auto oResult = SQLQuery(hDB, pszSQL);
    6595           4 :         sqlite3_free(pszSQL);
    6596           8 :         if (oResult && oResult->RowCount() > 0 &&
    6597           9 :             oResult->GetValue(0, 0) != nullptr &&
    6598           1 :             !EQUAL(oResult->GetValue(0, 0), osTableName.c_str()))
    6599             :         {
    6600           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6601             :                      "Identifier %s is already used by table %s", pszIdentifier,
    6602             :                      oResult->GetValue(0, 0));
    6603           1 :             return nullptr;
    6604             :         }
    6605             :     }
    6606             : 
    6607             :     /* Read GEOMETRY_NAME option */
    6608             :     const char *pszGeomColumnName =
    6609         754 :         CSLFetchNameValue(papszOptions, "GEOMETRY_NAME");
    6610         754 :     if (pszGeomColumnName == nullptr) /* deprecated name */
    6611         673 :         pszGeomColumnName = CSLFetchNameValue(papszOptions, "GEOMETRY_COLUMN");
    6612         754 :     if (pszGeomColumnName == nullptr && poSrcGeomFieldDefn)
    6613             :     {
    6614         621 :         pszGeomColumnName = poSrcGeomFieldDefn->GetNameRef();
    6615         621 :         if (pszGeomColumnName && pszGeomColumnName[0] == 0)
    6616         617 :             pszGeomColumnName = nullptr;
    6617             :     }
    6618         754 :     if (pszGeomColumnName == nullptr)
    6619         669 :         pszGeomColumnName = "geom";
    6620             :     const bool bGeomNullable =
    6621         754 :         CPLFetchBool(papszOptions, "GEOMETRY_NULLABLE", true);
    6622             : 
    6623             :     /* Read FID option */
    6624         754 :     const char *pszFIDColumnName = CSLFetchNameValue(papszOptions, "FID");
    6625         754 :     if (pszFIDColumnName == nullptr)
    6626         718 :         pszFIDColumnName = "fid";
    6627             : 
    6628         754 :     if (CPLTestBool(CPLGetConfigOption("GPKG_NAME_CHECK", "YES")))
    6629             :     {
    6630         754 :         if (strspn(pszFIDColumnName, "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") > 0)
    6631             :         {
    6632           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6633             :                      "The primary key (%s) name may not contain special "
    6634             :                      "characters or spaces",
    6635             :                      pszFIDColumnName);
    6636           1 :             return nullptr;
    6637             :         }
    6638             : 
    6639             :         /* Avoiding gpkg prefixes is not an official requirement, but seems wise
    6640             :          */
    6641         753 :         if (STARTS_WITH(osTableName.c_str(), "gpkg"))
    6642             :         {
    6643           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6644             :                      "The layer name may not begin with 'gpkg' as it is a "
    6645             :                      "reserved geopackage prefix");
    6646           0 :             return nullptr;
    6647             :         }
    6648             : 
    6649             :         /* Preemptively try and avoid sqlite3 syntax errors due to  */
    6650             :         /* illegal characters. */
    6651         753 :         if (strspn(osTableName.c_str(), "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") >
    6652             :             0)
    6653             :         {
    6654           0 :             CPLError(
    6655             :                 CE_Failure, CPLE_AppDefined,
    6656             :                 "The layer name may not contain special characters or spaces");
    6657           0 :             return nullptr;
    6658             :         }
    6659             :     }
    6660             : 
    6661             :     /* Check for any existing layers that already use this name */
    6662         957 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6663             :          iLayer++)
    6664             :     {
    6665         205 :         if (EQUAL(osTableName.c_str(), m_apoLayers[iLayer]->GetName()))
    6666             :         {
    6667             :             const char *pszOverwrite =
    6668           2 :                 CSLFetchNameValue(papszOptions, "OVERWRITE");
    6669           2 :             if (pszOverwrite != nullptr && CPLTestBool(pszOverwrite))
    6670             :             {
    6671           1 :                 DeleteLayer(iLayer);
    6672             :             }
    6673             :             else
    6674             :             {
    6675           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6676             :                          "Layer %s already exists, CreateLayer failed.\n"
    6677             :                          "Use the layer creation option OVERWRITE=YES to "
    6678             :                          "replace it.",
    6679             :                          osTableName.c_str());
    6680           1 :                 return nullptr;
    6681             :             }
    6682             :         }
    6683             :     }
    6684             : 
    6685         752 :     if (m_apoLayers.size() == 1)
    6686             :     {
    6687             :         // Async RTree building doesn't play well with multiple layer:
    6688             :         // SQLite3 locks being hold for a long time, random failed commits,
    6689             :         // etc.
    6690          78 :         m_apoLayers[0]->FinishOrDisableThreadedRTree();
    6691             :     }
    6692             : 
    6693             :     /* Create a blank layer. */
    6694             :     auto poLayer =
    6695        1504 :         std::make_unique<OGRGeoPackageTableLayer>(this, osTableName.c_str());
    6696             : 
    6697         752 :     OGRSpatialReference *poSRS = nullptr;
    6698         752 :     if (poSpatialRef)
    6699             :     {
    6700         241 :         poSRS = poSpatialRef->Clone();
    6701         241 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    6702             :     }
    6703        1505 :     poLayer->SetCreationParameters(
    6704             :         eGType,
    6705         753 :         bLaunder ? LaunderName(pszGeomColumnName).c_str() : pszGeomColumnName,
    6706             :         bGeomNullable, poSRS, CSLFetchNameValue(papszOptions, "SRID"),
    6707        1504 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetCoordinatePrecision()
    6708             :                            : OGRGeomCoordinatePrecision(),
    6709         752 :         CPLTestBool(
    6710             :             CSLFetchNameValueDef(papszOptions, "DISCARD_COORD_LSB", "NO")),
    6711         752 :         CPLTestBool(CSLFetchNameValueDef(
    6712             :             papszOptions, "UNDO_DISCARD_COORD_LSB_ON_READING", "NO")),
    6713         753 :         bLaunder ? LaunderName(pszFIDColumnName).c_str() : pszFIDColumnName,
    6714             :         pszIdentifier, CSLFetchNameValue(papszOptions, "DESCRIPTION"));
    6715         752 :     if (poSRS)
    6716             :     {
    6717         241 :         poSRS->Release();
    6718             :     }
    6719             : 
    6720         752 :     poLayer->SetLaunder(bLaunder);
    6721             : 
    6722             :     /* Should we create a spatial index ? */
    6723         752 :     const char *pszSI = CSLFetchNameValue(papszOptions, "SPATIAL_INDEX");
    6724         752 :     int bCreateSpatialIndex = (pszSI == nullptr || CPLTestBool(pszSI));
    6725         752 :     if (eGType != wkbNone && bCreateSpatialIndex)
    6726             :     {
    6727         678 :         poLayer->SetDeferredSpatialIndexCreation(true);
    6728             :     }
    6729             : 
    6730         752 :     poLayer->SetPrecisionFlag(CPLFetchBool(papszOptions, "PRECISION", true));
    6731         752 :     poLayer->SetTruncateFieldsFlag(
    6732         752 :         CPLFetchBool(papszOptions, "TRUNCATE_FIELDS", false));
    6733         752 :     if (eGType == wkbNone)
    6734             :     {
    6735          52 :         const char *pszASpatialVariant = CSLFetchNameValueDef(
    6736             :             papszOptions, "ASPATIAL_VARIANT",
    6737          52 :             m_bNonSpatialTablesNonRegisteredInGpkgContentsFound
    6738             :                 ? "NOT_REGISTERED"
    6739             :                 : "GPKG_ATTRIBUTES");
    6740          52 :         GPKGASpatialVariant eASpatialVariant = GPKG_ATTRIBUTES;
    6741          52 :         if (EQUAL(pszASpatialVariant, "GPKG_ATTRIBUTES"))
    6742          40 :             eASpatialVariant = GPKG_ATTRIBUTES;
    6743          12 :         else if (EQUAL(pszASpatialVariant, "OGR_ASPATIAL"))
    6744             :         {
    6745           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6746             :                      "ASPATIAL_VARIANT=OGR_ASPATIAL is no longer supported");
    6747           0 :             return nullptr;
    6748             :         }
    6749          12 :         else if (EQUAL(pszASpatialVariant, "NOT_REGISTERED"))
    6750          12 :             eASpatialVariant = NOT_REGISTERED;
    6751             :         else
    6752             :         {
    6753           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6754             :                      "Unsupported value for ASPATIAL_VARIANT: %s",
    6755             :                      pszASpatialVariant);
    6756           0 :             return nullptr;
    6757             :         }
    6758          52 :         poLayer->SetASpatialVariant(eASpatialVariant);
    6759             :     }
    6760             : 
    6761             :     const char *pszDateTimePrecision =
    6762         752 :         CSLFetchNameValueDef(papszOptions, "DATETIME_PRECISION", "AUTO");
    6763         752 :     if (EQUAL(pszDateTimePrecision, "MILLISECOND"))
    6764             :     {
    6765           2 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6766             :     }
    6767         750 :     else if (EQUAL(pszDateTimePrecision, "SECOND"))
    6768             :     {
    6769           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6770           0 :             CPLError(
    6771             :                 CE_Warning, CPLE_AppDefined,
    6772             :                 "DATETIME_PRECISION=SECOND is only valid since GeoPackage 1.4");
    6773           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::SECOND);
    6774             :     }
    6775         749 :     else if (EQUAL(pszDateTimePrecision, "MINUTE"))
    6776             :     {
    6777           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6778           0 :             CPLError(
    6779             :                 CE_Warning, CPLE_AppDefined,
    6780             :                 "DATETIME_PRECISION=MINUTE is only valid since GeoPackage 1.4");
    6781           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MINUTE);
    6782             :     }
    6783         748 :     else if (EQUAL(pszDateTimePrecision, "AUTO"))
    6784             :     {
    6785         747 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6786          13 :             poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6787             :     }
    6788             :     else
    6789             :     {
    6790           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    6791             :                  "Unsupported value for DATETIME_PRECISION: %s",
    6792             :                  pszDateTimePrecision);
    6793           1 :         return nullptr;
    6794             :     }
    6795             : 
    6796             :     // If there was an ogr_empty_table table, we can remove it
    6797             :     // But do it at dataset closing, otherwise locking performance issues
    6798             :     // can arise (probably when transactions are used).
    6799         751 :     m_bRemoveOGREmptyTable = true;
    6800             : 
    6801         751 :     m_apoLayers.emplace_back(std::move(poLayer));
    6802         751 :     return m_apoLayers.back().get();
    6803             : }
    6804             : 
    6805             : /************************************************************************/
    6806             : /*                          FindLayerIndex()                            */
    6807             : /************************************************************************/
    6808             : 
    6809          27 : int GDALGeoPackageDataset::FindLayerIndex(const char *pszLayerName)
    6810             : 
    6811             : {
    6812          42 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6813             :          iLayer++)
    6814             :     {
    6815          28 :         if (EQUAL(pszLayerName, m_apoLayers[iLayer]->GetName()))
    6816          13 :             return iLayer;
    6817             :     }
    6818          14 :     return -1;
    6819             : }
    6820             : 
    6821             : /************************************************************************/
    6822             : /*                       DeleteLayerCommon()                            */
    6823             : /************************************************************************/
    6824             : 
    6825          40 : OGRErr GDALGeoPackageDataset::DeleteLayerCommon(const char *pszLayerName)
    6826             : {
    6827             :     // Temporary remove foreign key checks
    6828             :     const GPKGTemporaryForeignKeyCheckDisabler
    6829          40 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6830             : 
    6831          40 :     char *pszSQL = sqlite3_mprintf(
    6832             :         "DELETE FROM gpkg_contents WHERE lower(table_name) = lower('%q')",
    6833             :         pszLayerName);
    6834          40 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    6835          40 :     sqlite3_free(pszSQL);
    6836             : 
    6837          40 :     if (eErr == OGRERR_NONE && HasExtensionsTable())
    6838             :     {
    6839          38 :         pszSQL = sqlite3_mprintf(
    6840             :             "DELETE FROM gpkg_extensions WHERE lower(table_name) = lower('%q')",
    6841             :             pszLayerName);
    6842          38 :         eErr = SQLCommand(hDB, pszSQL);
    6843          38 :         sqlite3_free(pszSQL);
    6844             :     }
    6845             : 
    6846          40 :     if (eErr == OGRERR_NONE && HasMetadataTables())
    6847             :     {
    6848             :         // Delete from gpkg_metadata metadata records that are only referenced
    6849             :         // by the table we are about to drop
    6850          11 :         pszSQL = sqlite3_mprintf(
    6851             :             "DELETE FROM gpkg_metadata WHERE id IN ("
    6852             :             "SELECT DISTINCT md_file_id FROM "
    6853             :             "gpkg_metadata_reference WHERE "
    6854             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6855             :             "AND id NOT IN ("
    6856             :             "SELECT DISTINCT md_file_id FROM gpkg_metadata_reference WHERE "
    6857             :             "md_file_id IN (SELECT DISTINCT md_file_id FROM "
    6858             :             "gpkg_metadata_reference WHERE "
    6859             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6860             :             "AND lower(table_name) <> lower('%q'))",
    6861             :             pszLayerName, pszLayerName, pszLayerName);
    6862          11 :         eErr = SQLCommand(hDB, pszSQL);
    6863          11 :         sqlite3_free(pszSQL);
    6864             : 
    6865          11 :         if (eErr == OGRERR_NONE)
    6866             :         {
    6867             :             pszSQL =
    6868          11 :                 sqlite3_mprintf("DELETE FROM gpkg_metadata_reference WHERE "
    6869             :                                 "lower(table_name) = lower('%q')",
    6870             :                                 pszLayerName);
    6871          11 :             eErr = SQLCommand(hDB, pszSQL);
    6872          11 :             sqlite3_free(pszSQL);
    6873             :         }
    6874             :     }
    6875             : 
    6876          40 :     if (eErr == OGRERR_NONE && HasGpkgextRelationsTable())
    6877             :     {
    6878             :         // Remove reference to potential corresponding mapping table in
    6879             :         // gpkg_extensions
    6880           4 :         pszSQL = sqlite3_mprintf(
    6881             :             "DELETE FROM gpkg_extensions WHERE "
    6882             :             "extension_name IN ('related_tables', "
    6883             :             "'gpkg_related_tables') AND lower(table_name) = "
    6884             :             "(SELECT lower(mapping_table_name) FROM gpkgext_relations WHERE "
    6885             :             "lower(base_table_name) = lower('%q') OR "
    6886             :             "lower(related_table_name) = lower('%q') OR "
    6887             :             "lower(mapping_table_name) = lower('%q'))",
    6888             :             pszLayerName, pszLayerName, pszLayerName);
    6889           4 :         eErr = SQLCommand(hDB, pszSQL);
    6890           4 :         sqlite3_free(pszSQL);
    6891             : 
    6892           4 :         if (eErr == OGRERR_NONE)
    6893             :         {
    6894             :             // Remove reference to potential corresponding mapping table in
    6895             :             // gpkgext_relations
    6896             :             pszSQL =
    6897           4 :                 sqlite3_mprintf("DELETE FROM gpkgext_relations WHERE "
    6898             :                                 "lower(base_table_name) = lower('%q') OR "
    6899             :                                 "lower(related_table_name) = lower('%q') OR "
    6900             :                                 "lower(mapping_table_name) = lower('%q')",
    6901             :                                 pszLayerName, pszLayerName, pszLayerName);
    6902           4 :             eErr = SQLCommand(hDB, pszSQL);
    6903           4 :             sqlite3_free(pszSQL);
    6904             :         }
    6905             : 
    6906           4 :         if (eErr == OGRERR_NONE && HasExtensionsTable())
    6907             :         {
    6908             :             // If there is no longer any mapping table, then completely
    6909             :             // remove any reference to the extension in gpkg_extensions
    6910             :             // as mandated per the related table specification.
    6911             :             OGRErr err;
    6912           4 :             if (SQLGetInteger(hDB,
    6913             :                               "SELECT COUNT(*) FROM gpkg_extensions WHERE "
    6914             :                               "extension_name IN ('related_tables', "
    6915             :                               "'gpkg_related_tables') AND "
    6916             :                               "lower(table_name) != 'gpkgext_relations'",
    6917           4 :                               &err) == 0)
    6918             :             {
    6919           2 :                 eErr = SQLCommand(hDB, "DELETE FROM gpkg_extensions WHERE "
    6920             :                                        "extension_name IN ('related_tables', "
    6921             :                                        "'gpkg_related_tables')");
    6922             :             }
    6923             : 
    6924           4 :             ClearCachedRelationships();
    6925             :         }
    6926             :     }
    6927             : 
    6928          40 :     if (eErr == OGRERR_NONE)
    6929             :     {
    6930          40 :         pszSQL = sqlite3_mprintf("DROP TABLE \"%w\"", pszLayerName);
    6931          40 :         eErr = SQLCommand(hDB, pszSQL);
    6932          40 :         sqlite3_free(pszSQL);
    6933             :     }
    6934             : 
    6935             :     // Check foreign key integrity
    6936          40 :     if (eErr == OGRERR_NONE)
    6937             :     {
    6938          40 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    6939             :     }
    6940             : 
    6941          80 :     return eErr;
    6942             : }
    6943             : 
    6944             : /************************************************************************/
    6945             : /*                            DeleteLayer()                             */
    6946             : /************************************************************************/
    6947             : 
    6948          37 : OGRErr GDALGeoPackageDataset::DeleteLayer(int iLayer)
    6949             : {
    6950          73 :     if (!GetUpdate() || iLayer < 0 ||
    6951          36 :         iLayer >= static_cast<int>(m_apoLayers.size()))
    6952           2 :         return OGRERR_FAILURE;
    6953             : 
    6954          35 :     m_apoLayers[iLayer]->ResetReading();
    6955          35 :     m_apoLayers[iLayer]->SyncToDisk();
    6956             : 
    6957          70 :     CPLString osLayerName = m_apoLayers[iLayer]->GetName();
    6958             : 
    6959          35 :     CPLDebug("GPKG", "DeleteLayer(%s)", osLayerName.c_str());
    6960             : 
    6961             :     // Temporary remove foreign key checks
    6962             :     const GPKGTemporaryForeignKeyCheckDisabler
    6963          35 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6964             : 
    6965          35 :     OGRErr eErr = SoftStartTransaction();
    6966             : 
    6967          35 :     if (eErr == OGRERR_NONE)
    6968             :     {
    6969          35 :         if (m_apoLayers[iLayer]->HasSpatialIndex())
    6970          32 :             m_apoLayers[iLayer]->DropSpatialIndex();
    6971             : 
    6972             :         char *pszSQL =
    6973          35 :             sqlite3_mprintf("DELETE FROM gpkg_geometry_columns WHERE "
    6974             :                             "lower(table_name) = lower('%q')",
    6975             :                             osLayerName.c_str());
    6976          35 :         eErr = SQLCommand(hDB, pszSQL);
    6977          35 :         sqlite3_free(pszSQL);
    6978             :     }
    6979             : 
    6980          35 :     if (eErr == OGRERR_NONE && HasDataColumnsTable())
    6981             :     {
    6982           1 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_data_columns WHERE "
    6983             :                                        "lower(table_name) = lower('%q')",
    6984             :                                        osLayerName.c_str());
    6985           1 :         eErr = SQLCommand(hDB, pszSQL);
    6986           1 :         sqlite3_free(pszSQL);
    6987             :     }
    6988             : 
    6989             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    6990          35 :     if (eErr == OGRERR_NONE && m_bHasGPKGOGRContents)
    6991             :     {
    6992          35 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_ogr_contents WHERE "
    6993             :                                        "lower(table_name) = lower('%q')",
    6994             :                                        osLayerName.c_str());
    6995          35 :         eErr = SQLCommand(hDB, pszSQL);
    6996          35 :         sqlite3_free(pszSQL);
    6997             :     }
    6998             : #endif
    6999             : 
    7000          35 :     if (eErr == OGRERR_NONE)
    7001             :     {
    7002          35 :         eErr = DeleteLayerCommon(osLayerName.c_str());
    7003             :     }
    7004             : 
    7005          35 :     if (eErr == OGRERR_NONE)
    7006             :     {
    7007          35 :         eErr = SoftCommitTransaction();
    7008          35 :         if (eErr == OGRERR_NONE)
    7009             :         {
    7010             :             /* Delete the layer object */
    7011          35 :             m_apoLayers.erase(m_apoLayers.begin() + iLayer);
    7012             :         }
    7013             :     }
    7014             :     else
    7015             :     {
    7016           0 :         SoftRollbackTransaction();
    7017             :     }
    7018             : 
    7019          35 :     return eErr;
    7020             : }
    7021             : 
    7022             : /************************************************************************/
    7023             : /*                       DeleteRasterLayer()                            */
    7024             : /************************************************************************/
    7025             : 
    7026           2 : OGRErr GDALGeoPackageDataset::DeleteRasterLayer(const char *pszLayerName)
    7027             : {
    7028             :     // Temporary remove foreign key checks
    7029             :     const GPKGTemporaryForeignKeyCheckDisabler
    7030           2 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7031             : 
    7032           2 :     OGRErr eErr = SoftStartTransaction();
    7033             : 
    7034           2 :     if (eErr == OGRERR_NONE)
    7035             :     {
    7036           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix WHERE "
    7037             :                                        "lower(table_name) = lower('%q')",
    7038             :                                        pszLayerName);
    7039           2 :         eErr = SQLCommand(hDB, pszSQL);
    7040           2 :         sqlite3_free(pszSQL);
    7041             :     }
    7042             : 
    7043           2 :     if (eErr == OGRERR_NONE)
    7044             :     {
    7045           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix_set WHERE "
    7046             :                                        "lower(table_name) = lower('%q')",
    7047             :                                        pszLayerName);
    7048           2 :         eErr = SQLCommand(hDB, pszSQL);
    7049           2 :         sqlite3_free(pszSQL);
    7050             :     }
    7051             : 
    7052           2 :     if (eErr == OGRERR_NONE && HasGriddedCoverageAncillaryTable())
    7053             :     {
    7054             :         char *pszSQL =
    7055           1 :             sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_coverage_ancillary "
    7056             :                             "WHERE lower(tile_matrix_set_name) = lower('%q')",
    7057             :                             pszLayerName);
    7058           1 :         eErr = SQLCommand(hDB, pszSQL);
    7059           1 :         sqlite3_free(pszSQL);
    7060             : 
    7061           1 :         if (eErr == OGRERR_NONE)
    7062             :         {
    7063             :             pszSQL =
    7064           1 :                 sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_tile_ancillary "
    7065             :                                 "WHERE lower(tpudt_name) = lower('%q')",
    7066             :                                 pszLayerName);
    7067           1 :             eErr = SQLCommand(hDB, pszSQL);
    7068           1 :             sqlite3_free(pszSQL);
    7069             :         }
    7070             :     }
    7071             : 
    7072           2 :     if (eErr == OGRERR_NONE)
    7073             :     {
    7074           2 :         eErr = DeleteLayerCommon(pszLayerName);
    7075             :     }
    7076             : 
    7077           2 :     if (eErr == OGRERR_NONE)
    7078             :     {
    7079           2 :         eErr = SoftCommitTransaction();
    7080             :     }
    7081             :     else
    7082             :     {
    7083           0 :         SoftRollbackTransaction();
    7084             :     }
    7085             : 
    7086           4 :     return eErr;
    7087             : }
    7088             : 
    7089             : /************************************************************************/
    7090             : /*                    DeleteVectorOrRasterLayer()                       */
    7091             : /************************************************************************/
    7092             : 
    7093          13 : bool GDALGeoPackageDataset::DeleteVectorOrRasterLayer(const char *pszLayerName)
    7094             : {
    7095             : 
    7096          13 :     int idx = FindLayerIndex(pszLayerName);
    7097          13 :     if (idx >= 0)
    7098             :     {
    7099           5 :         DeleteLayer(idx);
    7100           5 :         return true;
    7101             :     }
    7102             : 
    7103             :     char *pszSQL =
    7104           8 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7105             :                         "lower(table_name) = lower('%q') "
    7106             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7107             :                         pszLayerName);
    7108           8 :     bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7109           8 :     sqlite3_free(pszSQL);
    7110           8 :     if (bIsRasterTable)
    7111             :     {
    7112           2 :         DeleteRasterLayer(pszLayerName);
    7113           2 :         return true;
    7114             :     }
    7115           6 :     return false;
    7116             : }
    7117             : 
    7118           7 : bool GDALGeoPackageDataset::RenameVectorOrRasterLayer(
    7119             :     const char *pszLayerName, const char *pszNewLayerName)
    7120             : {
    7121           7 :     int idx = FindLayerIndex(pszLayerName);
    7122           7 :     if (idx >= 0)
    7123             :     {
    7124           4 :         m_apoLayers[idx]->Rename(pszNewLayerName);
    7125           4 :         return true;
    7126             :     }
    7127             : 
    7128             :     char *pszSQL =
    7129           3 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7130             :                         "lower(table_name) = lower('%q') "
    7131             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7132             :                         pszLayerName);
    7133           3 :     const bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7134           3 :     sqlite3_free(pszSQL);
    7135             : 
    7136           3 :     if (bIsRasterTable)
    7137             :     {
    7138           2 :         return RenameRasterLayer(pszLayerName, pszNewLayerName);
    7139             :     }
    7140             : 
    7141           1 :     return false;
    7142             : }
    7143             : 
    7144           2 : bool GDALGeoPackageDataset::RenameRasterLayer(const char *pszLayerName,
    7145             :                                               const char *pszNewLayerName)
    7146             : {
    7147           4 :     std::string osSQL;
    7148             : 
    7149           2 :     char *pszSQL = sqlite3_mprintf(
    7150             :         "SELECT 1 FROM sqlite_master WHERE lower(name) = lower('%q') "
    7151             :         "AND type IN ('table', 'view')",
    7152             :         pszNewLayerName);
    7153           2 :     const bool bAlreadyExists = SQLGetInteger(GetDB(), pszSQL, nullptr) == 1;
    7154           2 :     sqlite3_free(pszSQL);
    7155           2 :     if (bAlreadyExists)
    7156             :     {
    7157           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Table %s already exists",
    7158             :                  pszNewLayerName);
    7159           0 :         return false;
    7160             :     }
    7161             : 
    7162             :     // Temporary remove foreign key checks
    7163             :     const GPKGTemporaryForeignKeyCheckDisabler
    7164           4 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7165             : 
    7166           2 :     if (SoftStartTransaction() != OGRERR_NONE)
    7167             :     {
    7168           0 :         return false;
    7169             :     }
    7170             : 
    7171           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET table_name = '%q' WHERE "
    7172             :                              "lower(table_name) = lower('%q');",
    7173             :                              pszNewLayerName, pszLayerName);
    7174           2 :     osSQL = pszSQL;
    7175           2 :     sqlite3_free(pszSQL);
    7176             : 
    7177           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' WHERE "
    7178             :                              "lower(identifier) = lower('%q');",
    7179             :                              pszNewLayerName, pszLayerName);
    7180           2 :     osSQL += pszSQL;
    7181           2 :     sqlite3_free(pszSQL);
    7182             : 
    7183             :     pszSQL =
    7184           2 :         sqlite3_mprintf("UPDATE gpkg_tile_matrix SET table_name = '%q' WHERE "
    7185             :                         "lower(table_name) = lower('%q');",
    7186             :                         pszNewLayerName, pszLayerName);
    7187           2 :     osSQL += pszSQL;
    7188           2 :     sqlite3_free(pszSQL);
    7189             : 
    7190           2 :     pszSQL = sqlite3_mprintf(
    7191             :         "UPDATE gpkg_tile_matrix_set SET table_name = '%q' WHERE "
    7192             :         "lower(table_name) = lower('%q');",
    7193             :         pszNewLayerName, pszLayerName);
    7194           2 :     osSQL += pszSQL;
    7195           2 :     sqlite3_free(pszSQL);
    7196             : 
    7197           2 :     if (HasGriddedCoverageAncillaryTable())
    7198             :     {
    7199           1 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_2d_gridded_coverage_ancillary "
    7200             :                                  "SET tile_matrix_set_name = '%q' WHERE "
    7201             :                                  "lower(tile_matrix_set_name) = lower('%q');",
    7202             :                                  pszNewLayerName, pszLayerName);
    7203           1 :         osSQL += pszSQL;
    7204           1 :         sqlite3_free(pszSQL);
    7205             : 
    7206           1 :         pszSQL = sqlite3_mprintf(
    7207             :             "UPDATE gpkg_2d_gridded_tile_ancillary SET tpudt_name = '%q' WHERE "
    7208             :             "lower(tpudt_name) = lower('%q');",
    7209             :             pszNewLayerName, pszLayerName);
    7210           1 :         osSQL += pszSQL;
    7211           1 :         sqlite3_free(pszSQL);
    7212             :     }
    7213             : 
    7214           2 :     if (HasExtensionsTable())
    7215             :     {
    7216           2 :         pszSQL = sqlite3_mprintf(
    7217             :             "UPDATE gpkg_extensions SET table_name = '%q' WHERE "
    7218             :             "lower(table_name) = lower('%q');",
    7219             :             pszNewLayerName, pszLayerName);
    7220           2 :         osSQL += pszSQL;
    7221           2 :         sqlite3_free(pszSQL);
    7222             :     }
    7223             : 
    7224           2 :     if (HasMetadataTables())
    7225             :     {
    7226           1 :         pszSQL = sqlite3_mprintf(
    7227             :             "UPDATE gpkg_metadata_reference SET table_name = '%q' WHERE "
    7228             :             "lower(table_name) = lower('%q');",
    7229             :             pszNewLayerName, pszLayerName);
    7230           1 :         osSQL += pszSQL;
    7231           1 :         sqlite3_free(pszSQL);
    7232             :     }
    7233             : 
    7234           2 :     if (HasDataColumnsTable())
    7235             :     {
    7236           0 :         pszSQL = sqlite3_mprintf(
    7237             :             "UPDATE gpkg_data_columns SET table_name = '%q' WHERE "
    7238             :             "lower(table_name) = lower('%q');",
    7239             :             pszNewLayerName, pszLayerName);
    7240           0 :         osSQL += pszSQL;
    7241           0 :         sqlite3_free(pszSQL);
    7242             :     }
    7243             : 
    7244           2 :     if (HasQGISLayerStyles())
    7245             :     {
    7246             :         // Update QGIS styles
    7247             :         pszSQL =
    7248           0 :             sqlite3_mprintf("UPDATE layer_styles SET f_table_name = '%q' WHERE "
    7249             :                             "lower(f_table_name) = lower('%q');",
    7250             :                             pszNewLayerName, pszLayerName);
    7251           0 :         osSQL += pszSQL;
    7252           0 :         sqlite3_free(pszSQL);
    7253             :     }
    7254             : 
    7255             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7256           2 :     if (m_bHasGPKGOGRContents)
    7257             :     {
    7258           2 :         pszSQL = sqlite3_mprintf(
    7259             :             "UPDATE gpkg_ogr_contents SET table_name = '%q' WHERE "
    7260             :             "lower(table_name) = lower('%q');",
    7261             :             pszNewLayerName, pszLayerName);
    7262           2 :         osSQL += pszSQL;
    7263           2 :         sqlite3_free(pszSQL);
    7264             :     }
    7265             : #endif
    7266             : 
    7267           2 :     if (HasGpkgextRelationsTable())
    7268             :     {
    7269           0 :         pszSQL = sqlite3_mprintf(
    7270             :             "UPDATE gpkgext_relations SET base_table_name = '%q' WHERE "
    7271             :             "lower(base_table_name) = lower('%q');",
    7272             :             pszNewLayerName, pszLayerName);
    7273           0 :         osSQL += pszSQL;
    7274           0 :         sqlite3_free(pszSQL);
    7275             : 
    7276           0 :         pszSQL = sqlite3_mprintf(
    7277             :             "UPDATE gpkgext_relations SET related_table_name = '%q' WHERE "
    7278             :             "lower(related_table_name) = lower('%q');",
    7279             :             pszNewLayerName, pszLayerName);
    7280           0 :         osSQL += pszSQL;
    7281           0 :         sqlite3_free(pszSQL);
    7282             : 
    7283           0 :         pszSQL = sqlite3_mprintf(
    7284             :             "UPDATE gpkgext_relations SET mapping_table_name = '%q' WHERE "
    7285             :             "lower(mapping_table_name) = lower('%q');",
    7286             :             pszNewLayerName, pszLayerName);
    7287           0 :         osSQL += pszSQL;
    7288           0 :         sqlite3_free(pszSQL);
    7289             :     }
    7290             : 
    7291             :     // Drop all triggers for the layer
    7292           2 :     pszSQL = sqlite3_mprintf("SELECT name FROM sqlite_master WHERE type = "
    7293             :                              "'trigger' AND tbl_name = '%q'",
    7294             :                              pszLayerName);
    7295           2 :     auto oTriggerResult = SQLQuery(GetDB(), pszSQL);
    7296           2 :     sqlite3_free(pszSQL);
    7297           2 :     if (oTriggerResult)
    7298             :     {
    7299          14 :         for (int i = 0; i < oTriggerResult->RowCount(); i++)
    7300             :         {
    7301          12 :             const char *pszTriggerName = oTriggerResult->GetValue(0, i);
    7302          12 :             pszSQL = sqlite3_mprintf("DROP TRIGGER IF EXISTS \"%w\";",
    7303             :                                      pszTriggerName);
    7304          12 :             osSQL += pszSQL;
    7305          12 :             sqlite3_free(pszSQL);
    7306             :         }
    7307             :     }
    7308             : 
    7309           2 :     pszSQL = sqlite3_mprintf("ALTER TABLE \"%w\" RENAME TO \"%w\";",
    7310             :                              pszLayerName, pszNewLayerName);
    7311           2 :     osSQL += pszSQL;
    7312           2 :     sqlite3_free(pszSQL);
    7313             : 
    7314             :     // Recreate all zoom/tile triggers
    7315           2 :     if (oTriggerResult)
    7316             :     {
    7317           2 :         osSQL += CreateRasterTriggersSQL(pszNewLayerName);
    7318             :     }
    7319             : 
    7320           2 :     OGRErr eErr = SQLCommand(GetDB(), osSQL.c_str());
    7321             : 
    7322             :     // Check foreign key integrity
    7323           2 :     if (eErr == OGRERR_NONE)
    7324             :     {
    7325           2 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    7326             :     }
    7327             : 
    7328           2 :     if (eErr == OGRERR_NONE)
    7329             :     {
    7330           2 :         eErr = SoftCommitTransaction();
    7331             :     }
    7332             :     else
    7333             :     {
    7334           0 :         SoftRollbackTransaction();
    7335             :     }
    7336             : 
    7337           2 :     return eErr == OGRERR_NONE;
    7338             : }
    7339             : 
    7340             : /************************************************************************/
    7341             : /*                       TestCapability()                               */
    7342             : /************************************************************************/
    7343             : 
    7344         449 : int GDALGeoPackageDataset::TestCapability(const char *pszCap)
    7345             : {
    7346         449 :     if (EQUAL(pszCap, ODsCCreateLayer) || EQUAL(pszCap, ODsCDeleteLayer) ||
    7347         284 :         EQUAL(pszCap, "RenameLayer"))
    7348             :     {
    7349         165 :         return GetUpdate();
    7350             :     }
    7351         284 :     else if (EQUAL(pszCap, ODsCCurveGeometries))
    7352          12 :         return TRUE;
    7353         272 :     else if (EQUAL(pszCap, ODsCMeasuredGeometries))
    7354           8 :         return TRUE;
    7355         264 :     else if (EQUAL(pszCap, ODsCZGeometries))
    7356           8 :         return TRUE;
    7357         256 :     else if (EQUAL(pszCap, ODsCRandomLayerWrite) ||
    7358         256 :              EQUAL(pszCap, GDsCAddRelationship) ||
    7359         256 :              EQUAL(pszCap, GDsCDeleteRelationship) ||
    7360         256 :              EQUAL(pszCap, GDsCUpdateRelationship) ||
    7361         256 :              EQUAL(pszCap, ODsCAddFieldDomain))
    7362           1 :         return GetUpdate();
    7363             : 
    7364         255 :     return OGRSQLiteBaseDataSource::TestCapability(pszCap);
    7365             : }
    7366             : 
    7367             : /************************************************************************/
    7368             : /*                       ResetReadingAllLayers()                        */
    7369             : /************************************************************************/
    7370             : 
    7371         204 : void GDALGeoPackageDataset::ResetReadingAllLayers()
    7372             : {
    7373         413 :     for (auto &poLayer : m_apoLayers)
    7374             :     {
    7375         209 :         poLayer->ResetReading();
    7376             :     }
    7377         204 : }
    7378             : 
    7379             : /************************************************************************/
    7380             : /*                             ExecuteSQL()                             */
    7381             : /************************************************************************/
    7382             : 
    7383             : static const char *const apszFuncsWithSideEffects[] = {
    7384             :     "CreateSpatialIndex",
    7385             :     "DisableSpatialIndex",
    7386             :     "HasSpatialIndex",
    7387             :     "RegisterGeometryExtension",
    7388             : };
    7389             : 
    7390        5650 : OGRLayer *GDALGeoPackageDataset::ExecuteSQL(const char *pszSQLCommand,
    7391             :                                             OGRGeometry *poSpatialFilter,
    7392             :                                             const char *pszDialect)
    7393             : 
    7394             : {
    7395        5650 :     m_bHasReadMetadataFromStorage = false;
    7396             : 
    7397        5650 :     FlushMetadata();
    7398             : 
    7399        5668 :     while (*pszSQLCommand != '\0' &&
    7400        5668 :            isspace(static_cast<unsigned char>(*pszSQLCommand)))
    7401          18 :         pszSQLCommand++;
    7402             : 
    7403       11300 :     CPLString osSQLCommand(pszSQLCommand);
    7404        5650 :     if (!osSQLCommand.empty() && osSQLCommand.back() == ';')
    7405          48 :         osSQLCommand.pop_back();
    7406             : 
    7407        5650 :     if (pszDialect == nullptr || !EQUAL(pszDialect, "DEBUG"))
    7408             :     {
    7409             :         // Some SQL commands will influence the feature count behind our
    7410             :         // back, so disable it in that case.
    7411             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7412             :         const bool bInsertOrDelete =
    7413        5581 :             osSQLCommand.ifind("insert into ") != std::string::npos ||
    7414        2460 :             osSQLCommand.ifind("insert or replace into ") !=
    7415        8041 :                 std::string::npos ||
    7416        2423 :             osSQLCommand.ifind("delete from ") != std::string::npos;
    7417             :         const bool bRollback =
    7418        5581 :             osSQLCommand.ifind("rollback ") != std::string::npos;
    7419             : #endif
    7420             : 
    7421        7410 :         for (auto &poLayer : m_apoLayers)
    7422             :         {
    7423        1829 :             if (poLayer->SyncToDisk() != OGRERR_NONE)
    7424           0 :                 return nullptr;
    7425             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7426        2034 :             if (bRollback ||
    7427         205 :                 (bInsertOrDelete &&
    7428         205 :                  osSQLCommand.ifind(poLayer->GetName()) != std::string::npos))
    7429             :             {
    7430         203 :                 poLayer->DisableFeatureCount();
    7431             :             }
    7432             : #endif
    7433             :         }
    7434             :     }
    7435             : 
    7436        5650 :     if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 0") ||
    7437        5649 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=0") ||
    7438        5649 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =0") ||
    7439        5649 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 0"))
    7440             :     {
    7441           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, false);
    7442             :     }
    7443        5649 :     else if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 1") ||
    7444        5648 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=1") ||
    7445        5648 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =1") ||
    7446        5648 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 1"))
    7447             :     {
    7448           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, true);
    7449             :     }
    7450             : 
    7451             :     /* -------------------------------------------------------------------- */
    7452             :     /*      DEBUG "SELECT nolock" command.                                  */
    7453             :     /* -------------------------------------------------------------------- */
    7454        5719 :     if (pszDialect != nullptr && EQUAL(pszDialect, "DEBUG") &&
    7455          69 :         EQUAL(osSQLCommand, "SELECT nolock"))
    7456             :     {
    7457           3 :         return new OGRSQLiteSingleFeatureLayer(osSQLCommand, m_bNoLock ? 1 : 0);
    7458             :     }
    7459             : 
    7460             :     /* -------------------------------------------------------------------- */
    7461             :     /*      Special case DELLAYER: command.                                 */
    7462             :     /* -------------------------------------------------------------------- */
    7463        5647 :     if (STARTS_WITH_CI(osSQLCommand, "DELLAYER:"))
    7464             :     {
    7465           4 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DELLAYER:");
    7466             : 
    7467           4 :         while (*pszLayerName == ' ')
    7468           0 :             pszLayerName++;
    7469             : 
    7470           4 :         if (!DeleteVectorOrRasterLayer(pszLayerName))
    7471             :         {
    7472           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7473             :                      pszLayerName);
    7474             :         }
    7475           4 :         return nullptr;
    7476             :     }
    7477             : 
    7478             :     /* -------------------------------------------------------------------- */
    7479             :     /*      Special case RECOMPUTE EXTENT ON command.                       */
    7480             :     /* -------------------------------------------------------------------- */
    7481        5643 :     if (STARTS_WITH_CI(osSQLCommand, "RECOMPUTE EXTENT ON "))
    7482             :     {
    7483             :         const char *pszLayerName =
    7484           4 :             osSQLCommand.c_str() + strlen("RECOMPUTE EXTENT ON ");
    7485             : 
    7486           4 :         while (*pszLayerName == ' ')
    7487           0 :             pszLayerName++;
    7488             : 
    7489           4 :         int idx = FindLayerIndex(pszLayerName);
    7490           4 :         if (idx >= 0)
    7491             :         {
    7492           4 :             m_apoLayers[idx]->RecomputeExtent();
    7493             :         }
    7494             :         else
    7495           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7496             :                      pszLayerName);
    7497           4 :         return nullptr;
    7498             :     }
    7499             : 
    7500             :     /* -------------------------------------------------------------------- */
    7501             :     /*      Intercept DROP TABLE                                            */
    7502             :     /* -------------------------------------------------------------------- */
    7503        5639 :     if (STARTS_WITH_CI(osSQLCommand, "DROP TABLE "))
    7504             :     {
    7505           9 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DROP TABLE ");
    7506             : 
    7507           9 :         while (*pszLayerName == ' ')
    7508           0 :             pszLayerName++;
    7509             : 
    7510           9 :         if (DeleteVectorOrRasterLayer(SQLUnescape(pszLayerName)))
    7511           4 :             return nullptr;
    7512             :     }
    7513             : 
    7514             :     /* -------------------------------------------------------------------- */
    7515             :     /*      Intercept ALTER TABLE src_table RENAME TO dst_table             */
    7516             :     /*      and       ALTER TABLE table RENAME COLUMN src_name TO dst_name  */
    7517             :     /*      and       ALTER TABLE table DROP COLUMN col_name                */
    7518             :     /*                                                                      */
    7519             :     /*      We do this because SQLite mechanisms can't deal with updating   */
    7520             :     /*      literal values in gpkg_ tables that refer to table and column   */
    7521             :     /*      names.                                                          */
    7522             :     /* -------------------------------------------------------------------- */
    7523        5635 :     if (STARTS_WITH_CI(osSQLCommand, "ALTER TABLE "))
    7524             :     {
    7525           9 :         char **papszTokens = SQLTokenize(osSQLCommand);
    7526             :         /* ALTER TABLE src_table RENAME TO dst_table */
    7527          16 :         if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "RENAME") &&
    7528           7 :             EQUAL(papszTokens[4], "TO"))
    7529             :         {
    7530           7 :             const char *pszSrcTableName = papszTokens[2];
    7531           7 :             const char *pszDstTableName = papszTokens[5];
    7532           7 :             if (RenameVectorOrRasterLayer(SQLUnescape(pszSrcTableName),
    7533          14 :                                           SQLUnescape(pszDstTableName)))
    7534             :             {
    7535           6 :                 CSLDestroy(papszTokens);
    7536           6 :                 return nullptr;
    7537             :             }
    7538             :         }
    7539             :         /* ALTER TABLE table RENAME COLUMN src_name TO dst_name */
    7540           2 :         else if (CSLCount(papszTokens) == 8 &&
    7541           1 :                  EQUAL(papszTokens[3], "RENAME") &&
    7542           3 :                  EQUAL(papszTokens[4], "COLUMN") && EQUAL(papszTokens[6], "TO"))
    7543             :         {
    7544           1 :             const char *pszTableName = papszTokens[2];
    7545           1 :             const char *pszSrcColumn = papszTokens[5];
    7546           1 :             const char *pszDstColumn = papszTokens[7];
    7547             :             OGRGeoPackageTableLayer *poLayer =
    7548           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7549           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7550           1 :             if (poLayer)
    7551             :             {
    7552           2 :                 int nSrcFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7553           2 :                     SQLUnescape(pszSrcColumn));
    7554           1 :                 if (nSrcFieldIdx >= 0)
    7555             :                 {
    7556             :                     // OFTString or any type will do as we just alter the name
    7557             :                     // so it will be ignored.
    7558           1 :                     OGRFieldDefn oFieldDefn(SQLUnescape(pszDstColumn),
    7559           1 :                                             OFTString);
    7560           1 :                     poLayer->AlterFieldDefn(nSrcFieldIdx, &oFieldDefn,
    7561             :                                             ALTER_NAME_FLAG);
    7562           1 :                     CSLDestroy(papszTokens);
    7563           1 :                     return nullptr;
    7564             :                 }
    7565             :             }
    7566             :         }
    7567             :         /* ALTER TABLE table DROP COLUMN col_name */
    7568           2 :         else if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "DROP") &&
    7569           1 :                  EQUAL(papszTokens[4], "COLUMN"))
    7570             :         {
    7571           1 :             const char *pszTableName = papszTokens[2];
    7572           1 :             const char *pszColumnName = papszTokens[5];
    7573             :             OGRGeoPackageTableLayer *poLayer =
    7574           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7575           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7576           1 :             if (poLayer)
    7577             :             {
    7578           2 :                 int nFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7579           2 :                     SQLUnescape(pszColumnName));
    7580           1 :                 if (nFieldIdx >= 0)
    7581             :                 {
    7582           1 :                     poLayer->DeleteField(nFieldIdx);
    7583           1 :                     CSLDestroy(papszTokens);
    7584           1 :                     return nullptr;
    7585             :                 }
    7586             :             }
    7587             :         }
    7588           1 :         CSLDestroy(papszTokens);
    7589             :     }
    7590             : 
    7591        5627 :     if (ProcessTransactionSQL(osSQLCommand))
    7592             :     {
    7593         253 :         return nullptr;
    7594             :     }
    7595             : 
    7596        5374 :     if (EQUAL(osSQLCommand, "VACUUM"))
    7597             :     {
    7598          13 :         ResetReadingAllLayers();
    7599             :     }
    7600        5361 :     else if (STARTS_WITH_CI(osSQLCommand, "DELETE FROM "))
    7601             :     {
    7602             :         // Optimize truncation of a table, especially if it has a spatial
    7603             :         // index.
    7604          24 :         const CPLStringList aosTokens(SQLTokenize(osSQLCommand));
    7605          24 :         if (aosTokens.size() == 3)
    7606             :         {
    7607          16 :             const char *pszTableName = aosTokens[2];
    7608             :             OGRGeoPackageTableLayer *poLayer =
    7609           8 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7610          24 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7611          16 :             if (poLayer)
    7612             :             {
    7613           8 :                 poLayer->Truncate();
    7614           8 :                 return nullptr;
    7615             :             }
    7616             :         }
    7617             :     }
    7618        5337 :     else if (pszDialect != nullptr && EQUAL(pszDialect, "INDIRECT_SQLITE"))
    7619           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter, "SQLITE");
    7620        5336 :     else if (pszDialect != nullptr && !EQUAL(pszDialect, "") &&
    7621          67 :              !EQUAL(pszDialect, "NATIVE") && !EQUAL(pszDialect, "SQLITE") &&
    7622          67 :              !EQUAL(pszDialect, "DEBUG"))
    7623           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter,
    7624           1 :                                        pszDialect);
    7625             : 
    7626             :     /* -------------------------------------------------------------------- */
    7627             :     /*      Prepare statement.                                              */
    7628             :     /* -------------------------------------------------------------------- */
    7629        5364 :     sqlite3_stmt *hSQLStmt = nullptr;
    7630             : 
    7631             :     /* This will speed-up layer creation */
    7632             :     /* ORDER BY are costly to evaluate and are not necessary to establish */
    7633             :     /* the layer definition. */
    7634        5364 :     bool bUseStatementForGetNextFeature = true;
    7635        5364 :     bool bEmptyLayer = false;
    7636       10728 :     CPLString osSQLCommandTruncated(osSQLCommand);
    7637             : 
    7638       17698 :     if (osSQLCommand.ifind("SELECT ") == 0 &&
    7639        6167 :         CPLString(osSQLCommand.substr(1)).ifind("SELECT ") ==
    7640         769 :             std::string::npos &&
    7641         769 :         osSQLCommand.ifind(" UNION ") == std::string::npos &&
    7642        6936 :         osSQLCommand.ifind(" INTERSECT ") == std::string::npos &&
    7643         769 :         osSQLCommand.ifind(" EXCEPT ") == std::string::npos)
    7644             :     {
    7645         769 :         size_t nOrderByPos = osSQLCommand.ifind(" ORDER BY ");
    7646         769 :         if (nOrderByPos != std::string::npos)
    7647             :         {
    7648           9 :             osSQLCommandTruncated.resize(nOrderByPos);
    7649           9 :             bUseStatementForGetNextFeature = false;
    7650             :         }
    7651             :     }
    7652             : 
    7653        5364 :     int rc = prepareSql(hDB, osSQLCommandTruncated.c_str(),
    7654        5364 :                         static_cast<int>(osSQLCommandTruncated.size()),
    7655             :                         &hSQLStmt, nullptr);
    7656             : 
    7657        5364 :     if (rc != SQLITE_OK)
    7658             :     {
    7659           9 :         CPLError(CE_Failure, CPLE_AppDefined,
    7660             :                  "In ExecuteSQL(): sqlite3_prepare_v2(%s): %s",
    7661             :                  osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7662             : 
    7663           9 :         if (hSQLStmt != nullptr)
    7664             :         {
    7665           0 :             sqlite3_finalize(hSQLStmt);
    7666             :         }
    7667             : 
    7668           9 :         return nullptr;
    7669             :     }
    7670             : 
    7671             :     /* -------------------------------------------------------------------- */
    7672             :     /*      Do we get a resultset?                                          */
    7673             :     /* -------------------------------------------------------------------- */
    7674        5355 :     rc = sqlite3_step(hSQLStmt);
    7675             : 
    7676        6949 :     for (auto &poLayer : m_apoLayers)
    7677             :     {
    7678        1594 :         poLayer->RunDeferredDropRTreeTableIfNecessary();
    7679             :     }
    7680             : 
    7681        5355 :     if (rc != SQLITE_ROW)
    7682             :     {
    7683        4633 :         if (rc != SQLITE_DONE)
    7684             :         {
    7685           7 :             CPLError(CE_Failure, CPLE_AppDefined,
    7686             :                      "In ExecuteSQL(): sqlite3_step(%s):\n  %s",
    7687             :                      osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7688             : 
    7689           7 :             sqlite3_finalize(hSQLStmt);
    7690           7 :             return nullptr;
    7691             :         }
    7692             : 
    7693        4626 :         if (EQUAL(osSQLCommand, "VACUUM"))
    7694             :         {
    7695          13 :             sqlite3_finalize(hSQLStmt);
    7696             :             /* VACUUM rewrites the DB, so we need to reset the application id */
    7697          13 :             SetApplicationAndUserVersionId();
    7698          13 :             return nullptr;
    7699             :         }
    7700             : 
    7701        4613 :         if (!STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7702             :         {
    7703        4488 :             sqlite3_finalize(hSQLStmt);
    7704        4488 :             return nullptr;
    7705             :         }
    7706             : 
    7707         125 :         bUseStatementForGetNextFeature = false;
    7708         125 :         bEmptyLayer = true;
    7709             :     }
    7710             : 
    7711             :     /* -------------------------------------------------------------------- */
    7712             :     /*      Special case for some functions which must be run               */
    7713             :     /*      only once                                                       */
    7714             :     /* -------------------------------------------------------------------- */
    7715         847 :     if (STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7716             :     {
    7717        3859 :         for (unsigned int i = 0; i < sizeof(apszFuncsWithSideEffects) /
    7718             :                                          sizeof(apszFuncsWithSideEffects[0]);
    7719             :              i++)
    7720             :         {
    7721        3113 :             if (EQUALN(apszFuncsWithSideEffects[i], osSQLCommand.c_str() + 7,
    7722             :                        strlen(apszFuncsWithSideEffects[i])))
    7723             :             {
    7724         112 :                 if (sqlite3_column_count(hSQLStmt) == 1 &&
    7725          56 :                     sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7726             :                 {
    7727          56 :                     int ret = sqlite3_column_int(hSQLStmt, 0);
    7728             : 
    7729          56 :                     sqlite3_finalize(hSQLStmt);
    7730             : 
    7731             :                     return new OGRSQLiteSingleFeatureLayer(
    7732          56 :                         apszFuncsWithSideEffects[i], ret);
    7733             :                 }
    7734             :             }
    7735             :         }
    7736             :     }
    7737          45 :     else if (STARTS_WITH_CI(osSQLCommand, "PRAGMA "))
    7738             :     {
    7739          63 :         if (sqlite3_column_count(hSQLStmt) == 1 &&
    7740          18 :             sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7741             :         {
    7742          15 :             int ret = sqlite3_column_int(hSQLStmt, 0);
    7743             : 
    7744          15 :             sqlite3_finalize(hSQLStmt);
    7745             : 
    7746          15 :             return new OGRSQLiteSingleFeatureLayer(osSQLCommand.c_str() + 7,
    7747          15 :                                                    ret);
    7748             :         }
    7749          33 :         else if (sqlite3_column_count(hSQLStmt) == 1 &&
    7750           3 :                  sqlite3_column_type(hSQLStmt, 0) == SQLITE_TEXT)
    7751             :         {
    7752             :             const char *pszRet = reinterpret_cast<const char *>(
    7753           3 :                 sqlite3_column_text(hSQLStmt, 0));
    7754             : 
    7755             :             OGRLayer *poRet = new OGRSQLiteSingleFeatureLayer(
    7756           3 :                 osSQLCommand.c_str() + 7, pszRet);
    7757             : 
    7758           3 :             sqlite3_finalize(hSQLStmt);
    7759             : 
    7760           3 :             return poRet;
    7761             :         }
    7762             :     }
    7763             : 
    7764             :     /* -------------------------------------------------------------------- */
    7765             :     /*      Create layer.                                                   */
    7766             :     /* -------------------------------------------------------------------- */
    7767             : 
    7768             :     auto poLayer = std::make_unique<OGRGeoPackageSelectLayer>(
    7769             :         this, osSQLCommand, hSQLStmt, bUseStatementForGetNextFeature,
    7770        1546 :         bEmptyLayer);
    7771             : 
    7772         776 :     if (poSpatialFilter != nullptr &&
    7773           3 :         poLayer->GetLayerDefn()->GetGeomFieldCount() > 0)
    7774           3 :         poLayer->SetSpatialFilter(0, poSpatialFilter);
    7775             : 
    7776         773 :     return poLayer.release();
    7777             : }
    7778             : 
    7779             : /************************************************************************/
    7780             : /*                          ReleaseResultSet()                          */
    7781             : /************************************************************************/
    7782             : 
    7783         806 : void GDALGeoPackageDataset::ReleaseResultSet(OGRLayer *poLayer)
    7784             : 
    7785             : {
    7786         806 :     delete poLayer;
    7787         806 : }
    7788             : 
    7789             : /************************************************************************/
    7790             : /*                         HasExtensionsTable()                         */
    7791             : /************************************************************************/
    7792             : 
    7793        6511 : bool GDALGeoPackageDataset::HasExtensionsTable()
    7794             : {
    7795        6511 :     return SQLGetInteger(
    7796             :                hDB,
    7797             :                "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_extensions' "
    7798             :                "AND type IN ('table', 'view')",
    7799        6511 :                nullptr) == 1;
    7800             : }
    7801             : 
    7802             : /************************************************************************/
    7803             : /*                    CheckUnknownExtensions()                          */
    7804             : /************************************************************************/
    7805             : 
    7806        1477 : void GDALGeoPackageDataset::CheckUnknownExtensions(bool bCheckRasterTable)
    7807             : {
    7808        1477 :     if (!HasExtensionsTable())
    7809         197 :         return;
    7810             : 
    7811        1280 :     char *pszSQL = nullptr;
    7812        1280 :     if (!bCheckRasterTable)
    7813        1071 :         pszSQL = sqlite3_mprintf(
    7814             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7815             :             "WHERE (table_name IS NULL "
    7816             :             "AND extension_name IS NOT NULL "
    7817             :             "AND definition IS NOT NULL "
    7818             :             "AND scope IS NOT NULL "
    7819             :             "AND extension_name NOT IN ("
    7820             :             "'gdal_aspatial', "
    7821             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7822             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7823             :                                        // 17-066r1 finalization
    7824             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7825             :             "'gpkg_metadata', "
    7826             :             "'gpkg_schema', "
    7827             :             "'gpkg_crs_wkt', "
    7828             :             "'gpkg_crs_wkt_1_1', "
    7829             :             "'related_tables', 'gpkg_related_tables')) "
    7830             : #ifdef WORKAROUND_SQLITE3_BUGS
    7831             :             "OR 0 "
    7832             : #endif
    7833             :             "LIMIT 1000");
    7834             :     else
    7835         209 :         pszSQL = sqlite3_mprintf(
    7836             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7837             :             "WHERE (lower(table_name) = lower('%q') "
    7838             :             "AND extension_name IS NOT NULL "
    7839             :             "AND definition IS NOT NULL "
    7840             :             "AND scope IS NOT NULL "
    7841             :             "AND extension_name NOT IN ("
    7842             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7843             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7844             :                                        // 17-066r1 finalization
    7845             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7846             :             "'gpkg_metadata', "
    7847             :             "'gpkg_schema', "
    7848             :             "'gpkg_crs_wkt', "
    7849             :             "'gpkg_crs_wkt_1_1', "
    7850             :             "'related_tables', 'gpkg_related_tables')) "
    7851             : #ifdef WORKAROUND_SQLITE3_BUGS
    7852             :             "OR 0 "
    7853             : #endif
    7854             :             "LIMIT 1000",
    7855             :             m_osRasterTable.c_str());
    7856             : 
    7857        2560 :     auto oResultTable = SQLQuery(GetDB(), pszSQL);
    7858        1280 :     sqlite3_free(pszSQL);
    7859        1280 :     if (oResultTable && oResultTable->RowCount() > 0)
    7860             :     {
    7861          44 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    7862             :         {
    7863          22 :             const char *pszExtName = oResultTable->GetValue(0, i);
    7864          22 :             const char *pszDefinition = oResultTable->GetValue(1, i);
    7865          22 :             const char *pszScope = oResultTable->GetValue(2, i);
    7866          22 :             if (pszExtName == nullptr || pszDefinition == nullptr ||
    7867             :                 pszScope == nullptr)
    7868             :             {
    7869           0 :                 continue;
    7870             :             }
    7871             : 
    7872          22 :             if (EQUAL(pszExtName, "gpkg_webp"))
    7873             :             {
    7874          16 :                 if (GDALGetDriverByName("WEBP") == nullptr)
    7875             :                 {
    7876           1 :                     CPLError(
    7877             :                         CE_Warning, CPLE_AppDefined,
    7878             :                         "Table %s contains WEBP tiles, but GDAL configured "
    7879             :                         "without WEBP support. Data will be missing",
    7880             :                         m_osRasterTable.c_str());
    7881             :                 }
    7882          16 :                 m_eTF = GPKG_TF_WEBP;
    7883          16 :                 continue;
    7884             :             }
    7885           6 :             if (EQUAL(pszExtName, "gpkg_zoom_other"))
    7886             :             {
    7887           2 :                 m_bZoomOther = true;
    7888           2 :                 continue;
    7889             :             }
    7890             : 
    7891           4 :             if (GetUpdate() && EQUAL(pszScope, "write-only"))
    7892             :             {
    7893           1 :                 CPLError(
    7894             :                     CE_Warning, CPLE_AppDefined,
    7895             :                     "Database relies on the '%s' (%s) extension that should "
    7896             :                     "be implemented for safe write-support, but is not "
    7897             :                     "currently. "
    7898             :                     "Update of that database are strongly discouraged to avoid "
    7899             :                     "corruption.",
    7900             :                     pszExtName, pszDefinition);
    7901             :             }
    7902           3 :             else if (GetUpdate() && EQUAL(pszScope, "read-write"))
    7903             :             {
    7904           1 :                 CPLError(
    7905             :                     CE_Warning, CPLE_AppDefined,
    7906             :                     "Database relies on the '%s' (%s) extension that should "
    7907             :                     "be implemented in order to read/write it safely, but is "
    7908             :                     "not currently. "
    7909             :                     "Some data may be missing while reading that database, and "
    7910             :                     "updates are strongly discouraged.",
    7911             :                     pszExtName, pszDefinition);
    7912             :             }
    7913           2 :             else if (EQUAL(pszScope, "read-write") &&
    7914             :                      // None of the NGA extensions at
    7915             :                      // http://ngageoint.github.io/GeoPackage/docs/extensions/
    7916             :                      // affect read-only scenarios
    7917           1 :                      !STARTS_WITH(pszExtName, "nga_"))
    7918             :             {
    7919           1 :                 CPLError(
    7920             :                     CE_Warning, CPLE_AppDefined,
    7921             :                     "Database relies on the '%s' (%s) extension that should "
    7922             :                     "be implemented in order to read it safely, but is not "
    7923             :                     "currently. "
    7924             :                     "Some data may be missing while reading that database.",
    7925             :                     pszExtName, pszDefinition);
    7926             :             }
    7927             :         }
    7928             :     }
    7929             : }
    7930             : 
    7931             : /************************************************************************/
    7932             : /*                         HasGDALAspatialExtension()                       */
    7933             : /************************************************************************/
    7934             : 
    7935        1020 : bool GDALGeoPackageDataset::HasGDALAspatialExtension()
    7936             : {
    7937        1020 :     if (!HasExtensionsTable())
    7938          90 :         return false;
    7939             : 
    7940             :     auto oResultTable = SQLQuery(hDB, "SELECT * FROM gpkg_extensions "
    7941             :                                       "WHERE (extension_name = 'gdal_aspatial' "
    7942             :                                       "AND table_name IS NULL "
    7943             :                                       "AND column_name IS NULL)"
    7944             : #ifdef WORKAROUND_SQLITE3_BUGS
    7945             :                                       " OR 0"
    7946             : #endif
    7947         930 :     );
    7948         930 :     bool bHasExtension = (oResultTable && oResultTable->RowCount() == 1);
    7949         930 :     return bHasExtension;
    7950             : }
    7951             : 
    7952             : std::string
    7953         190 : GDALGeoPackageDataset::CreateRasterTriggersSQL(const std::string &osTableName)
    7954             : {
    7955             :     char *pszSQL;
    7956         190 :     std::string osSQL;
    7957             :     /* From D.5. sample_tile_pyramid Table 43. tiles table Trigger
    7958             :      * Definition SQL  */
    7959         190 :     pszSQL = sqlite3_mprintf(
    7960             :         "CREATE TRIGGER \"%w_zoom_insert\" "
    7961             :         "BEFORE INSERT ON \"%w\" "
    7962             :         "FOR EACH ROW BEGIN "
    7963             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7964             :         "constraint: zoom_level not specified for table in "
    7965             :         "gpkg_tile_matrix') "
    7966             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7967             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7968             :         "END; "
    7969             :         "CREATE TRIGGER \"%w_zoom_update\" "
    7970             :         "BEFORE UPDATE OF zoom_level ON \"%w\" "
    7971             :         "FOR EACH ROW BEGIN "
    7972             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7973             :         "constraint: zoom_level not specified for table in "
    7974             :         "gpkg_tile_matrix') "
    7975             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7976             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7977             :         "END; "
    7978             :         "CREATE TRIGGER \"%w_tile_column_insert\" "
    7979             :         "BEFORE INSERT ON \"%w\" "
    7980             :         "FOR EACH ROW BEGIN "
    7981             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7982             :         "constraint: tile_column cannot be < 0') "
    7983             :         "WHERE (NEW.tile_column < 0) ; "
    7984             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7985             :         "constraint: tile_column must by < matrix_width specified for "
    7986             :         "table and zoom level in gpkg_tile_matrix') "
    7987             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    7988             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    7989             :         "zoom_level = NEW.zoom_level)); "
    7990             :         "END; "
    7991             :         "CREATE TRIGGER \"%w_tile_column_update\" "
    7992             :         "BEFORE UPDATE OF tile_column ON \"%w\" "
    7993             :         "FOR EACH ROW BEGIN "
    7994             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7995             :         "constraint: tile_column cannot be < 0') "
    7996             :         "WHERE (NEW.tile_column < 0) ; "
    7997             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7998             :         "constraint: tile_column must by < matrix_width specified for "
    7999             :         "table and zoom level in gpkg_tile_matrix') "
    8000             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    8001             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8002             :         "zoom_level = NEW.zoom_level)); "
    8003             :         "END; "
    8004             :         "CREATE TRIGGER \"%w_tile_row_insert\" "
    8005             :         "BEFORE INSERT ON \"%w\" "
    8006             :         "FOR EACH ROW BEGIN "
    8007             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8008             :         "constraint: tile_row cannot be < 0') "
    8009             :         "WHERE (NEW.tile_row < 0) ; "
    8010             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8011             :         "constraint: tile_row must by < matrix_height specified for "
    8012             :         "table and zoom level in gpkg_tile_matrix') "
    8013             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8014             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8015             :         "zoom_level = NEW.zoom_level)); "
    8016             :         "END; "
    8017             :         "CREATE TRIGGER \"%w_tile_row_update\" "
    8018             :         "BEFORE UPDATE OF tile_row ON \"%w\" "
    8019             :         "FOR EACH ROW BEGIN "
    8020             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8021             :         "constraint: tile_row cannot be < 0') "
    8022             :         "WHERE (NEW.tile_row < 0) ; "
    8023             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8024             :         "constraint: tile_row must by < matrix_height specified for "
    8025             :         "table and zoom level in gpkg_tile_matrix') "
    8026             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8027             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8028             :         "zoom_level = NEW.zoom_level)); "
    8029             :         "END; ",
    8030             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8031             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8032             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8033             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8034             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8035             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8036             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8037             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8038             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8039             :         osTableName.c_str());
    8040         190 :     osSQL = pszSQL;
    8041         190 :     sqlite3_free(pszSQL);
    8042         190 :     return osSQL;
    8043             : }
    8044             : 
    8045             : /************************************************************************/
    8046             : /*                  CreateExtensionsTableIfNecessary()                  */
    8047             : /************************************************************************/
    8048             : 
    8049        1159 : OGRErr GDALGeoPackageDataset::CreateExtensionsTableIfNecessary()
    8050             : {
    8051             :     /* Check if the table gpkg_extensions exists */
    8052        1159 :     if (HasExtensionsTable())
    8053         410 :         return OGRERR_NONE;
    8054             : 
    8055             :     /* Requirement 79 : Every extension of a GeoPackage SHALL be registered */
    8056             :     /* in a corresponding row in the gpkg_extensions table. The absence of a */
    8057             :     /* gpkg_extensions table or the absence of rows in gpkg_extensions table */
    8058             :     /* SHALL both indicate the absence of extensions to a GeoPackage. */
    8059         749 :     const char *pszCreateGpkgExtensions =
    8060             :         "CREATE TABLE gpkg_extensions ("
    8061             :         "table_name TEXT,"
    8062             :         "column_name TEXT,"
    8063             :         "extension_name TEXT NOT NULL,"
    8064             :         "definition TEXT NOT NULL,"
    8065             :         "scope TEXT NOT NULL,"
    8066             :         "CONSTRAINT ge_tce UNIQUE (table_name, column_name, extension_name)"
    8067             :         ")";
    8068             : 
    8069         749 :     return SQLCommand(hDB, pszCreateGpkgExtensions);
    8070             : }
    8071             : 
    8072             : /************************************************************************/
    8073             : /*                    OGR_GPKG_Intersects_Spatial_Filter()              */
    8074             : /************************************************************************/
    8075             : 
    8076       23135 : void OGR_GPKG_Intersects_Spatial_Filter(sqlite3_context *pContext, int argc,
    8077             :                                         sqlite3_value **argv)
    8078             : {
    8079       23135 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8080             :     {
    8081           0 :         sqlite3_result_int(pContext, 0);
    8082       23125 :         return;
    8083             :     }
    8084             : 
    8085             :     auto poLayer =
    8086       23135 :         static_cast<OGRGeoPackageTableLayer *>(sqlite3_user_data(pContext));
    8087             : 
    8088       23135 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8089             :     const GByte *pabyBLOB =
    8090       23135 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8091             : 
    8092             :     GPkgHeader sHeader;
    8093       46270 :     if (poLayer->m_bFilterIsEnvelope &&
    8094       23135 :         OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false, 0))
    8095             :     {
    8096       23135 :         if (sHeader.bExtentHasXY)
    8097             :         {
    8098          95 :             OGREnvelope sEnvelope;
    8099          95 :             sEnvelope.MinX = sHeader.MinX;
    8100          95 :             sEnvelope.MinY = sHeader.MinY;
    8101          95 :             sEnvelope.MaxX = sHeader.MaxX;
    8102          95 :             sEnvelope.MaxY = sHeader.MaxY;
    8103          95 :             if (poLayer->m_sFilterEnvelope.Contains(sEnvelope))
    8104             :             {
    8105          31 :                 sqlite3_result_int(pContext, 1);
    8106          31 :                 return;
    8107             :             }
    8108             :         }
    8109             : 
    8110             :         // Check if at least one point falls into the layer filter envelope
    8111             :         // nHeaderLen is > 0 for GeoPackage geometries
    8112       46208 :         if (sHeader.nHeaderLen > 0 &&
    8113       23104 :             OGRWKBIntersectsPessimistic(pabyBLOB + sHeader.nHeaderLen,
    8114       23104 :                                         nBLOBLen - sHeader.nHeaderLen,
    8115       23104 :                                         poLayer->m_sFilterEnvelope))
    8116             :         {
    8117       23094 :             sqlite3_result_int(pContext, 1);
    8118       23094 :             return;
    8119             :         }
    8120             :     }
    8121             : 
    8122             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8123          10 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8124          10 :     if (poGeom == nullptr)
    8125             :     {
    8126             :         // Try also spatialite geometry blobs
    8127           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8128           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8129           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8130             :         {
    8131           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8132           0 :             sqlite3_result_int(pContext, 0);
    8133           0 :             return;
    8134             :         }
    8135           0 :         poGeom.reset(poGeomSpatialite);
    8136             :     }
    8137             : 
    8138          10 :     sqlite3_result_int(pContext, poLayer->FilterGeometry(poGeom.get()));
    8139             : }
    8140             : 
    8141             : /************************************************************************/
    8142             : /*                      OGRGeoPackageSTMinX()                           */
    8143             : /************************************************************************/
    8144             : 
    8145      243781 : static void OGRGeoPackageSTMinX(sqlite3_context *pContext, int argc,
    8146             :                                 sqlite3_value **argv)
    8147             : {
    8148             :     GPkgHeader sHeader;
    8149      243781 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8150             :     {
    8151           3 :         sqlite3_result_null(pContext);
    8152           3 :         return;
    8153             :     }
    8154      243778 :     sqlite3_result_double(pContext, sHeader.MinX);
    8155             : }
    8156             : 
    8157             : /************************************************************************/
    8158             : /*                      OGRGeoPackageSTMinY()                           */
    8159             : /************************************************************************/
    8160             : 
    8161      243779 : static void OGRGeoPackageSTMinY(sqlite3_context *pContext, int argc,
    8162             :                                 sqlite3_value **argv)
    8163             : {
    8164             :     GPkgHeader sHeader;
    8165      243779 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8166             :     {
    8167           1 :         sqlite3_result_null(pContext);
    8168           1 :         return;
    8169             :     }
    8170      243778 :     sqlite3_result_double(pContext, sHeader.MinY);
    8171             : }
    8172             : 
    8173             : /************************************************************************/
    8174             : /*                      OGRGeoPackageSTMaxX()                           */
    8175             : /************************************************************************/
    8176             : 
    8177      243779 : static void OGRGeoPackageSTMaxX(sqlite3_context *pContext, int argc,
    8178             :                                 sqlite3_value **argv)
    8179             : {
    8180             :     GPkgHeader sHeader;
    8181      243779 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8182             :     {
    8183           1 :         sqlite3_result_null(pContext);
    8184           1 :         return;
    8185             :     }
    8186      243778 :     sqlite3_result_double(pContext, sHeader.MaxX);
    8187             : }
    8188             : 
    8189             : /************************************************************************/
    8190             : /*                      OGRGeoPackageSTMaxY()                           */
    8191             : /************************************************************************/
    8192             : 
    8193      243779 : static void OGRGeoPackageSTMaxY(sqlite3_context *pContext, int argc,
    8194             :                                 sqlite3_value **argv)
    8195             : {
    8196             :     GPkgHeader sHeader;
    8197      243779 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8198             :     {
    8199           1 :         sqlite3_result_null(pContext);
    8200           1 :         return;
    8201             :     }
    8202      243778 :     sqlite3_result_double(pContext, sHeader.MaxY);
    8203             : }
    8204             : 
    8205             : /************************************************************************/
    8206             : /*                     OGRGeoPackageSTIsEmpty()                         */
    8207             : /************************************************************************/
    8208             : 
    8209      245184 : static void OGRGeoPackageSTIsEmpty(sqlite3_context *pContext, int argc,
    8210             :                                    sqlite3_value **argv)
    8211             : {
    8212             :     GPkgHeader sHeader;
    8213      245184 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8214             :     {
    8215           2 :         sqlite3_result_null(pContext);
    8216           2 :         return;
    8217             :     }
    8218      245182 :     sqlite3_result_int(pContext, sHeader.bEmpty);
    8219             : }
    8220             : 
    8221             : /************************************************************************/
    8222             : /*                    OGRGeoPackageSTGeometryType()                     */
    8223             : /************************************************************************/
    8224             : 
    8225           7 : static void OGRGeoPackageSTGeometryType(sqlite3_context *pContext, int /*argc*/,
    8226             :                                         sqlite3_value **argv)
    8227             : {
    8228             :     GPkgHeader sHeader;
    8229             : 
    8230           7 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8231             :     const GByte *pabyBLOB =
    8232           7 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8233             :     OGRwkbGeometryType eGeometryType;
    8234             : 
    8235          13 :     if (nBLOBLen < 8 ||
    8236           6 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8237             :     {
    8238           2 :         if (OGRSQLiteGetSpatialiteGeometryHeader(
    8239             :                 pabyBLOB, nBLOBLen, nullptr, &eGeometryType, nullptr, nullptr,
    8240           2 :                 nullptr, nullptr, nullptr) == OGRERR_NONE)
    8241             :         {
    8242           1 :             sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8243             :                                 SQLITE_TRANSIENT);
    8244           4 :             return;
    8245             :         }
    8246             :         else
    8247             :         {
    8248           1 :             sqlite3_result_null(pContext);
    8249           1 :             return;
    8250             :         }
    8251             :     }
    8252             : 
    8253           5 :     if (static_cast<size_t>(nBLOBLen) < sHeader.nHeaderLen + 5)
    8254             :     {
    8255           2 :         sqlite3_result_null(pContext);
    8256           2 :         return;
    8257             :     }
    8258             : 
    8259           3 :     OGRErr err = OGRReadWKBGeometryType(pabyBLOB + sHeader.nHeaderLen,
    8260             :                                         wkbVariantIso, &eGeometryType);
    8261           3 :     if (err != OGRERR_NONE)
    8262           1 :         sqlite3_result_null(pContext);
    8263             :     else
    8264           2 :         sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8265             :                             SQLITE_TRANSIENT);
    8266             : }
    8267             : 
    8268             : /************************************************************************/
    8269             : /*                 OGRGeoPackageSTEnvelopesIntersects()                 */
    8270             : /************************************************************************/
    8271             : 
    8272         118 : static void OGRGeoPackageSTEnvelopesIntersects(sqlite3_context *pContext,
    8273             :                                                int argc, sqlite3_value **argv)
    8274             : {
    8275             :     GPkgHeader sHeader;
    8276         118 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8277             :     {
    8278           2 :         sqlite3_result_int(pContext, FALSE);
    8279         107 :         return;
    8280             :     }
    8281         116 :     const double dfMinX = sqlite3_value_double(argv[1]);
    8282         116 :     if (sHeader.MaxX < dfMinX)
    8283             :     {
    8284          93 :         sqlite3_result_int(pContext, FALSE);
    8285          93 :         return;
    8286             :     }
    8287          23 :     const double dfMinY = sqlite3_value_double(argv[2]);
    8288          23 :     if (sHeader.MaxY < dfMinY)
    8289             :     {
    8290          11 :         sqlite3_result_int(pContext, FALSE);
    8291          11 :         return;
    8292             :     }
    8293          12 :     const double dfMaxX = sqlite3_value_double(argv[3]);
    8294          12 :     if (sHeader.MinX > dfMaxX)
    8295             :     {
    8296           1 :         sqlite3_result_int(pContext, FALSE);
    8297           1 :         return;
    8298             :     }
    8299          11 :     const double dfMaxY = sqlite3_value_double(argv[4]);
    8300          11 :     sqlite3_result_int(pContext, sHeader.MinY <= dfMaxY);
    8301             : }
    8302             : 
    8303             : /************************************************************************/
    8304             : /*              OGRGeoPackageSTEnvelopesIntersectsTwoParams()           */
    8305             : /************************************************************************/
    8306             : 
    8307             : static void
    8308           3 : OGRGeoPackageSTEnvelopesIntersectsTwoParams(sqlite3_context *pContext, int argc,
    8309             :                                             sqlite3_value **argv)
    8310             : {
    8311             :     GPkgHeader sHeader;
    8312           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false, 0))
    8313             :     {
    8314           0 :         sqlite3_result_int(pContext, FALSE);
    8315           2 :         return;
    8316             :     }
    8317             :     GPkgHeader sHeader2;
    8318           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader2, true, false,
    8319             :                                 1))
    8320             :     {
    8321           0 :         sqlite3_result_int(pContext, FALSE);
    8322           0 :         return;
    8323             :     }
    8324           3 :     if (sHeader.MaxX < sHeader2.MinX)
    8325             :     {
    8326           1 :         sqlite3_result_int(pContext, FALSE);
    8327           1 :         return;
    8328             :     }
    8329           2 :     if (sHeader.MaxY < sHeader2.MinY)
    8330             :     {
    8331           0 :         sqlite3_result_int(pContext, FALSE);
    8332           0 :         return;
    8333             :     }
    8334           2 :     if (sHeader.MinX > sHeader2.MaxX)
    8335             :     {
    8336           1 :         sqlite3_result_int(pContext, FALSE);
    8337           1 :         return;
    8338             :     }
    8339           1 :     sqlite3_result_int(pContext, sHeader.MinY <= sHeader2.MaxY);
    8340             : }
    8341             : 
    8342             : /************************************************************************/
    8343             : /*                    OGRGeoPackageGPKGIsAssignable()                   */
    8344             : /************************************************************************/
    8345             : 
    8346           8 : static void OGRGeoPackageGPKGIsAssignable(sqlite3_context *pContext,
    8347             :                                           int /*argc*/, sqlite3_value **argv)
    8348             : {
    8349          15 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8350           7 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8351             :     {
    8352           2 :         sqlite3_result_int(pContext, 0);
    8353           2 :         return;
    8354             :     }
    8355             : 
    8356             :     const char *pszExpected =
    8357           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8358             :     const char *pszActual =
    8359           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8360           6 :     int bIsAssignable = OGR_GT_IsSubClassOf(OGRFromOGCGeomType(pszActual),
    8361             :                                             OGRFromOGCGeomType(pszExpected));
    8362           6 :     sqlite3_result_int(pContext, bIsAssignable);
    8363             : }
    8364             : 
    8365             : /************************************************************************/
    8366             : /*                     OGRGeoPackageSTSRID()                            */
    8367             : /************************************************************************/
    8368             : 
    8369          12 : static void OGRGeoPackageSTSRID(sqlite3_context *pContext, int argc,
    8370             :                                 sqlite3_value **argv)
    8371             : {
    8372             :     GPkgHeader sHeader;
    8373          12 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8374             :     {
    8375           2 :         sqlite3_result_null(pContext);
    8376           2 :         return;
    8377             :     }
    8378          10 :     sqlite3_result_int(pContext, sHeader.iSrsId);
    8379             : }
    8380             : 
    8381             : /************************************************************************/
    8382             : /*                     OGRGeoPackageSetSRID()                           */
    8383             : /************************************************************************/
    8384             : 
    8385          28 : static void OGRGeoPackageSetSRID(sqlite3_context *pContext, int /* argc */,
    8386             :                                  sqlite3_value **argv)
    8387             : {
    8388          28 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8389             :     {
    8390           1 :         sqlite3_result_null(pContext);
    8391           1 :         return;
    8392             :     }
    8393          27 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8394             :     GPkgHeader sHeader;
    8395          27 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8396             :     const GByte *pabyBLOB =
    8397          27 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8398             : 
    8399          54 :     if (nBLOBLen < 8 ||
    8400          27 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8401             :     {
    8402             :         // Try also spatialite geometry blobs
    8403           0 :         OGRGeometry *poGeom = nullptr;
    8404           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeom) !=
    8405             :             OGRERR_NONE)
    8406             :         {
    8407           0 :             sqlite3_result_null(pContext);
    8408           0 :             return;
    8409             :         }
    8410           0 :         size_t nBLOBDestLen = 0;
    8411             :         GByte *pabyDestBLOB =
    8412           0 :             GPkgGeometryFromOGR(poGeom, nDestSRID, nullptr, &nBLOBDestLen);
    8413           0 :         if (!pabyDestBLOB)
    8414             :         {
    8415           0 :             sqlite3_result_null(pContext);
    8416           0 :             return;
    8417             :         }
    8418           0 :         sqlite3_result_blob(pContext, pabyDestBLOB,
    8419             :                             static_cast<int>(nBLOBDestLen), VSIFree);
    8420           0 :         return;
    8421             :     }
    8422             : 
    8423          27 :     GByte *pabyDestBLOB = static_cast<GByte *>(CPLMalloc(nBLOBLen));
    8424          27 :     memcpy(pabyDestBLOB, pabyBLOB, nBLOBLen);
    8425          27 :     int32_t nSRIDToSerialize = nDestSRID;
    8426          27 :     if (OGR_SWAP(sHeader.eByteOrder))
    8427           0 :         nSRIDToSerialize = CPL_SWAP32(nSRIDToSerialize);
    8428          27 :     memcpy(pabyDestBLOB + 4, &nSRIDToSerialize, 4);
    8429          27 :     sqlite3_result_blob(pContext, pabyDestBLOB, nBLOBLen, VSIFree);
    8430             : }
    8431             : 
    8432             : /************************************************************************/
    8433             : /*                   OGRGeoPackageSTMakeValid()                         */
    8434             : /************************************************************************/
    8435             : 
    8436           3 : static void OGRGeoPackageSTMakeValid(sqlite3_context *pContext, int argc,
    8437             :                                      sqlite3_value **argv)
    8438             : {
    8439           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8440             :     {
    8441           2 :         sqlite3_result_null(pContext);
    8442           2 :         return;
    8443             :     }
    8444           1 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8445             :     const GByte *pabyBLOB =
    8446           1 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8447             : 
    8448             :     GPkgHeader sHeader;
    8449           1 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8450             :     {
    8451           0 :         sqlite3_result_null(pContext);
    8452           0 :         return;
    8453             :     }
    8454             : 
    8455             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8456           1 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8457           1 :     if (poGeom == nullptr)
    8458             :     {
    8459             :         // Try also spatialite geometry blobs
    8460           0 :         OGRGeometry *poGeomPtr = nullptr;
    8461           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8462             :             OGRERR_NONE)
    8463             :         {
    8464           0 :             sqlite3_result_null(pContext);
    8465           0 :             return;
    8466             :         }
    8467           0 :         poGeom.reset(poGeomPtr);
    8468             :     }
    8469           1 :     auto poValid = std::unique_ptr<OGRGeometry>(poGeom->MakeValid());
    8470           1 :     if (poValid == nullptr)
    8471             :     {
    8472           0 :         sqlite3_result_null(pContext);
    8473           0 :         return;
    8474             :     }
    8475             : 
    8476           1 :     size_t nBLOBDestLen = 0;
    8477           1 :     GByte *pabyDestBLOB = GPkgGeometryFromOGR(poValid.get(), sHeader.iSrsId,
    8478             :                                               nullptr, &nBLOBDestLen);
    8479           1 :     if (!pabyDestBLOB)
    8480             :     {
    8481           0 :         sqlite3_result_null(pContext);
    8482           0 :         return;
    8483             :     }
    8484           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8485             :                         VSIFree);
    8486             : }
    8487             : 
    8488             : /************************************************************************/
    8489             : /*                   OGRGeoPackageSTArea()                              */
    8490             : /************************************************************************/
    8491             : 
    8492          19 : static void OGRGeoPackageSTArea(sqlite3_context *pContext, int /*argc*/,
    8493             :                                 sqlite3_value **argv)
    8494             : {
    8495          19 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8496             :     {
    8497           1 :         sqlite3_result_null(pContext);
    8498          15 :         return;
    8499             :     }
    8500          18 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8501             :     const GByte *pabyBLOB =
    8502          18 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8503             : 
    8504             :     GPkgHeader sHeader;
    8505           0 :     std::unique_ptr<OGRGeometry> poGeom;
    8506          18 :     if (GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) == OGRERR_NONE)
    8507             :     {
    8508          16 :         if (sHeader.bEmpty)
    8509             :         {
    8510           3 :             sqlite3_result_double(pContext, 0);
    8511          13 :             return;
    8512             :         }
    8513          13 :         const GByte *pabyWkb = pabyBLOB + sHeader.nHeaderLen;
    8514          13 :         size_t nWKBSize = nBLOBLen - sHeader.nHeaderLen;
    8515             :         bool bNeedSwap;
    8516             :         uint32_t nType;
    8517          13 :         if (OGRWKBGetGeomType(pabyWkb, nWKBSize, bNeedSwap, nType))
    8518             :         {
    8519          13 :             if (nType == wkbPolygon || nType == wkbPolygon25D ||
    8520          11 :                 nType == wkbPolygon + 1000 ||  // wkbPolygonZ
    8521          10 :                 nType == wkbPolygonM || nType == wkbPolygonZM)
    8522             :             {
    8523             :                 double dfArea;
    8524           5 :                 if (OGRWKBPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8525             :                 {
    8526           5 :                     sqlite3_result_double(pContext, dfArea);
    8527           5 :                     return;
    8528           0 :                 }
    8529             :             }
    8530           8 :             else if (nType == wkbMultiPolygon || nType == wkbMultiPolygon25D ||
    8531           6 :                      nType == wkbMultiPolygon + 1000 ||  // wkbMultiPolygonZ
    8532           5 :                      nType == wkbMultiPolygonM || nType == wkbMultiPolygonZM)
    8533             :             {
    8534             :                 double dfArea;
    8535           5 :                 if (OGRWKBMultiPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8536             :                 {
    8537           5 :                     sqlite3_result_double(pContext, dfArea);
    8538           5 :                     return;
    8539             :                 }
    8540             :             }
    8541             :         }
    8542             : 
    8543             :         // For curve geometries, fallback to OGRGeometry methods
    8544           3 :         poGeom.reset(GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8545             :     }
    8546             :     else
    8547             :     {
    8548             :         // Try also spatialite geometry blobs
    8549           2 :         OGRGeometry *poGeomPtr = nullptr;
    8550           2 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8551             :             OGRERR_NONE)
    8552             :         {
    8553           1 :             sqlite3_result_null(pContext);
    8554           1 :             return;
    8555             :         }
    8556           1 :         poGeom.reset(poGeomPtr);
    8557             :     }
    8558           4 :     auto poSurface = dynamic_cast<OGRSurface *>(poGeom.get());
    8559           4 :     if (poSurface == nullptr)
    8560             :     {
    8561           2 :         auto poMultiSurface = dynamic_cast<OGRMultiSurface *>(poGeom.get());
    8562           2 :         if (poMultiSurface == nullptr)
    8563             :         {
    8564           1 :             sqlite3_result_double(pContext, 0);
    8565             :         }
    8566             :         else
    8567             :         {
    8568           1 :             sqlite3_result_double(pContext, poMultiSurface->get_Area());
    8569             :         }
    8570             :     }
    8571             :     else
    8572             :     {
    8573           2 :         sqlite3_result_double(pContext, poSurface->get_Area());
    8574             :     }
    8575             : }
    8576             : 
    8577             : /************************************************************************/
    8578             : /*                     OGRGeoPackageGeodesicArea()                      */
    8579             : /************************************************************************/
    8580             : 
    8581           5 : static void OGRGeoPackageGeodesicArea(sqlite3_context *pContext, int argc,
    8582             :                                       sqlite3_value **argv)
    8583             : {
    8584           5 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8585             :     {
    8586           1 :         sqlite3_result_null(pContext);
    8587           3 :         return;
    8588             :     }
    8589           4 :     if (sqlite3_value_int(argv[1]) != 1)
    8590             :     {
    8591           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8592             :                  "ST_Area(geom, use_ellipsoid) is only supported for "
    8593             :                  "use_ellipsoid = 1");
    8594             :     }
    8595             : 
    8596           4 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8597             :     const GByte *pabyBLOB =
    8598           4 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8599             :     GPkgHeader sHeader;
    8600           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8601             :     {
    8602           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8603           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8604           1 :         return;
    8605             :     }
    8606             : 
    8607             :     GDALGeoPackageDataset *poDS =
    8608           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8609             : 
    8610             :     std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSrcSRS(
    8611           3 :         poDS->GetSpatialRef(sHeader.iSrsId, true));
    8612           3 :     if (poSrcSRS == nullptr)
    8613             :     {
    8614           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    8615             :                  "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8616           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8617           1 :         return;
    8618             :     }
    8619             : 
    8620             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8621           2 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8622           2 :     if (poGeom == nullptr)
    8623             :     {
    8624             :         // Try also spatialite geometry blobs
    8625           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8626           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8627           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8628             :         {
    8629           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8630           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8631           0 :             return;
    8632             :         }
    8633           0 :         poGeom.reset(poGeomSpatialite);
    8634             :     }
    8635             : 
    8636           2 :     poGeom->assignSpatialReference(poSrcSRS.get());
    8637           2 :     sqlite3_result_double(
    8638             :         pContext, OGR_G_GeodesicArea(OGRGeometry::ToHandle(poGeom.get())));
    8639             : }
    8640             : 
    8641             : /************************************************************************/
    8642             : /*                   OGRGeoPackageLengthOrGeodesicLength()              */
    8643             : /************************************************************************/
    8644             : 
    8645           8 : static void OGRGeoPackageLengthOrGeodesicLength(sqlite3_context *pContext,
    8646             :                                                 int argc, sqlite3_value **argv)
    8647             : {
    8648           8 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8649             :     {
    8650           2 :         sqlite3_result_null(pContext);
    8651           5 :         return;
    8652             :     }
    8653           6 :     if (argc == 2 && sqlite3_value_int(argv[1]) != 1)
    8654             :     {
    8655           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8656             :                  "ST_Length(geom, use_ellipsoid) is only supported for "
    8657             :                  "use_ellipsoid = 1");
    8658             :     }
    8659             : 
    8660           6 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8661             :     const GByte *pabyBLOB =
    8662           6 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8663             :     GPkgHeader sHeader;
    8664           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8665             :     {
    8666           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8667           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8668           2 :         return;
    8669             :     }
    8670             : 
    8671             :     GDALGeoPackageDataset *poDS =
    8672           4 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8673             : 
    8674           0 :     std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSrcSRS;
    8675           4 :     if (argc == 2)
    8676             :     {
    8677           3 :         poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8678           3 :         if (!poSrcSRS)
    8679             :         {
    8680           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    8681             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8682           1 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8683           1 :             return;
    8684             :         }
    8685             :     }
    8686             : 
    8687             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8688           3 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8689           3 :     if (poGeom == nullptr)
    8690             :     {
    8691             :         // Try also spatialite geometry blobs
    8692           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8693           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8694           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8695             :         {
    8696           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8697           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8698           0 :             return;
    8699             :         }
    8700           0 :         poGeom.reset(poGeomSpatialite);
    8701             :     }
    8702             : 
    8703           3 :     if (argc == 2)
    8704           2 :         poGeom->assignSpatialReference(poSrcSRS.get());
    8705             : 
    8706           6 :     sqlite3_result_double(
    8707             :         pContext,
    8708           1 :         argc == 1 ? OGR_G_Length(OGRGeometry::ToHandle(poGeom.get()))
    8709           2 :                   : OGR_G_GeodesicLength(OGRGeometry::ToHandle(poGeom.get())));
    8710             : }
    8711             : 
    8712             : /************************************************************************/
    8713             : /*                      OGRGeoPackageTransform()                        */
    8714             : /************************************************************************/
    8715             : 
    8716             : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8717             :                             sqlite3_value **argv);
    8718             : 
    8719          32 : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8720             :                             sqlite3_value **argv)
    8721             : {
    8722          63 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB ||
    8723          31 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8724             :     {
    8725           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8726          32 :         return;
    8727             :     }
    8728             : 
    8729          30 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8730             :     const GByte *pabyBLOB =
    8731          30 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8732             :     GPkgHeader sHeader;
    8733          30 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8734             :     {
    8735           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8736           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8737           1 :         return;
    8738             :     }
    8739             : 
    8740          29 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8741          29 :     if (sHeader.iSrsId == nDestSRID)
    8742             :     {
    8743             :         // Return blob unmodified
    8744           3 :         sqlite3_result_blob(pContext, pabyBLOB, nBLOBLen, SQLITE_TRANSIENT);
    8745           3 :         return;
    8746             :     }
    8747             : 
    8748             :     GDALGeoPackageDataset *poDS =
    8749          26 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8750             : 
    8751             :     // Try to get the cached coordinate transformation
    8752             :     OGRCoordinateTransformation *poCT;
    8753          26 :     if (poDS->m_nLastCachedCTSrcSRId == sHeader.iSrsId &&
    8754          20 :         poDS->m_nLastCachedCTDstSRId == nDestSRID)
    8755             :     {
    8756          20 :         poCT = poDS->m_poLastCachedCT.get();
    8757             :     }
    8758             :     else
    8759             :     {
    8760             :         std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
    8761           6 :             poSrcSRS(poDS->GetSpatialRef(sHeader.iSrsId, true));
    8762           6 :         if (poSrcSRS == nullptr)
    8763             :         {
    8764           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    8765             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8766           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8767           0 :             return;
    8768             :         }
    8769             : 
    8770             :         std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
    8771           6 :             poDstSRS(poDS->GetSpatialRef(nDestSRID, true));
    8772           6 :         if (poDstSRS == nullptr)
    8773             :         {
    8774           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Target SRID (%d) is invalid",
    8775             :                      nDestSRID);
    8776           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8777           0 :             return;
    8778             :         }
    8779             :         poCT =
    8780           6 :             OGRCreateCoordinateTransformation(poSrcSRS.get(), poDstSRS.get());
    8781           6 :         if (poCT == nullptr)
    8782             :         {
    8783           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8784           0 :             return;
    8785             :         }
    8786             : 
    8787             :         // Cache coordinate transformation for potential later reuse
    8788           6 :         poDS->m_nLastCachedCTSrcSRId = sHeader.iSrsId;
    8789           6 :         poDS->m_nLastCachedCTDstSRId = nDestSRID;
    8790           6 :         poDS->m_poLastCachedCT.reset(poCT);
    8791           6 :         poCT = poDS->m_poLastCachedCT.get();
    8792             :     }
    8793             : 
    8794          26 :     if (sHeader.nHeaderLen >= 8)
    8795             :     {
    8796          26 :         std::vector<GByte> &abyNewBLOB = poDS->m_abyWKBTransformCache;
    8797          26 :         abyNewBLOB.resize(nBLOBLen);
    8798          26 :         memcpy(abyNewBLOB.data(), pabyBLOB, nBLOBLen);
    8799             : 
    8800          26 :         OGREnvelope3D oEnv3d;
    8801          26 :         if (!OGRWKBTransform(abyNewBLOB.data() + sHeader.nHeaderLen,
    8802          26 :                              nBLOBLen - sHeader.nHeaderLen, poCT,
    8803          78 :                              poDS->m_oWKBTransformCache, oEnv3d) ||
    8804          26 :             !GPkgUpdateHeader(abyNewBLOB.data(), nBLOBLen, nDestSRID,
    8805             :                               oEnv3d.MinX, oEnv3d.MaxX, oEnv3d.MinY,
    8806             :                               oEnv3d.MaxY, oEnv3d.MinZ, oEnv3d.MaxZ))
    8807             :         {
    8808           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8809           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8810           0 :             return;
    8811             :         }
    8812             : 
    8813          26 :         sqlite3_result_blob(pContext, abyNewBLOB.data(), nBLOBLen,
    8814             :                             SQLITE_TRANSIENT);
    8815          26 :         return;
    8816             :     }
    8817             : 
    8818             :     // Try also spatialite geometry blobs
    8819           0 :     OGRGeometry *poGeomSpatialite = nullptr;
    8820           0 :     if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8821           0 :                                           &poGeomSpatialite) != OGRERR_NONE)
    8822             :     {
    8823           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8824           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8825           0 :         return;
    8826             :     }
    8827           0 :     auto poGeom = std::unique_ptr<OGRGeometry>(poGeomSpatialite);
    8828             : 
    8829           0 :     if (poGeom->transform(poCT) != OGRERR_NONE)
    8830             :     {
    8831           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8832           0 :         return;
    8833             :     }
    8834             : 
    8835           0 :     size_t nBLOBDestLen = 0;
    8836             :     GByte *pabyDestBLOB =
    8837           0 :         GPkgGeometryFromOGR(poGeom.get(), nDestSRID, nullptr, &nBLOBDestLen);
    8838           0 :     if (!pabyDestBLOB)
    8839             :     {
    8840           0 :         sqlite3_result_null(pContext);
    8841           0 :         return;
    8842             :     }
    8843           0 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8844             :                         VSIFree);
    8845             : }
    8846             : 
    8847             : /************************************************************************/
    8848             : /*                      OGRGeoPackageSridFromAuthCRS()                  */
    8849             : /************************************************************************/
    8850             : 
    8851           4 : static void OGRGeoPackageSridFromAuthCRS(sqlite3_context *pContext,
    8852             :                                          int /*argc*/, sqlite3_value **argv)
    8853             : {
    8854           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8855           3 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8856             :     {
    8857           2 :         sqlite3_result_int(pContext, -1);
    8858           2 :         return;
    8859             :     }
    8860             : 
    8861             :     GDALGeoPackageDataset *poDS =
    8862           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8863             : 
    8864           2 :     char *pszSQL = sqlite3_mprintf(
    8865             :         "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
    8866             :         "lower(organization) = lower('%q') AND organization_coordsys_id = %d",
    8867           2 :         sqlite3_value_text(argv[0]), sqlite3_value_int(argv[1]));
    8868           2 :     OGRErr err = OGRERR_NONE;
    8869           2 :     int nSRSId = SQLGetInteger(poDS->GetDB(), pszSQL, &err);
    8870           2 :     sqlite3_free(pszSQL);
    8871           2 :     if (err != OGRERR_NONE)
    8872           1 :         nSRSId = -1;
    8873           2 :     sqlite3_result_int(pContext, nSRSId);
    8874             : }
    8875             : 
    8876             : /************************************************************************/
    8877             : /*                    OGRGeoPackageImportFromEPSG()                     */
    8878             : /************************************************************************/
    8879             : 
    8880           4 : static void OGRGeoPackageImportFromEPSG(sqlite3_context *pContext, int /*argc*/,
    8881             :                                         sqlite3_value **argv)
    8882             : {
    8883           4 :     if (sqlite3_value_type(argv[0]) != SQLITE_INTEGER)
    8884             :     {
    8885           1 :         sqlite3_result_int(pContext, -1);
    8886           2 :         return;
    8887             :     }
    8888             : 
    8889             :     GDALGeoPackageDataset *poDS =
    8890           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8891           3 :     OGRSpatialReference oSRS;
    8892           3 :     if (oSRS.importFromEPSG(sqlite3_value_int(argv[0])) != OGRERR_NONE)
    8893             :     {
    8894           1 :         sqlite3_result_int(pContext, -1);
    8895           1 :         return;
    8896             :     }
    8897             : 
    8898           2 :     sqlite3_result_int(pContext, poDS->GetSrsId(&oSRS));
    8899             : }
    8900             : 
    8901             : /************************************************************************/
    8902             : /*               OGRGeoPackageRegisterGeometryExtension()               */
    8903             : /************************************************************************/
    8904             : 
    8905           1 : static void OGRGeoPackageRegisterGeometryExtension(sqlite3_context *pContext,
    8906             :                                                    int /*argc*/,
    8907             :                                                    sqlite3_value **argv)
    8908             : {
    8909           1 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8910           2 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT ||
    8911           1 :         sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    8912             :     {
    8913           0 :         sqlite3_result_int(pContext, 0);
    8914           0 :         return;
    8915             :     }
    8916             : 
    8917             :     const char *pszTableName =
    8918           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8919             :     const char *pszGeomName =
    8920           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8921             :     const char *pszGeomType =
    8922           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    8923             : 
    8924             :     GDALGeoPackageDataset *poDS =
    8925           1 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8926             : 
    8927           1 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8928           1 :         poDS->GetLayerByName(pszTableName));
    8929           1 :     if (poLyr == nullptr)
    8930             :     {
    8931           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8932           0 :         sqlite3_result_int(pContext, 0);
    8933           0 :         return;
    8934             :     }
    8935           1 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8936             :     {
    8937           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8938           0 :         sqlite3_result_int(pContext, 0);
    8939           0 :         return;
    8940             :     }
    8941           1 :     const OGRwkbGeometryType eGeomType = OGRFromOGCGeomType(pszGeomType);
    8942           1 :     if (eGeomType == wkbUnknown)
    8943             :     {
    8944           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry type name");
    8945           0 :         sqlite3_result_int(pContext, 0);
    8946           0 :         return;
    8947             :     }
    8948             : 
    8949           1 :     sqlite3_result_int(
    8950             :         pContext,
    8951           1 :         static_cast<int>(poLyr->CreateGeometryExtensionIfNecessary(eGeomType)));
    8952             : }
    8953             : 
    8954             : /************************************************************************/
    8955             : /*                  OGRGeoPackageCreateSpatialIndex()                   */
    8956             : /************************************************************************/
    8957             : 
    8958          14 : static void OGRGeoPackageCreateSpatialIndex(sqlite3_context *pContext,
    8959             :                                             int /*argc*/, sqlite3_value **argv)
    8960             : {
    8961          27 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8962          13 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8963             :     {
    8964           2 :         sqlite3_result_int(pContext, 0);
    8965           2 :         return;
    8966             :     }
    8967             : 
    8968             :     const char *pszTableName =
    8969          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8970             :     const char *pszGeomName =
    8971          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8972             :     GDALGeoPackageDataset *poDS =
    8973          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8974             : 
    8975          12 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8976          12 :         poDS->GetLayerByName(pszTableName));
    8977          12 :     if (poLyr == nullptr)
    8978             :     {
    8979           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8980           1 :         sqlite3_result_int(pContext, 0);
    8981           1 :         return;
    8982             :     }
    8983          11 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8984             :     {
    8985           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8986           1 :         sqlite3_result_int(pContext, 0);
    8987           1 :         return;
    8988             :     }
    8989             : 
    8990          10 :     sqlite3_result_int(pContext, poLyr->CreateSpatialIndex());
    8991             : }
    8992             : 
    8993             : /************************************************************************/
    8994             : /*                  OGRGeoPackageDisableSpatialIndex()                  */
    8995             : /************************************************************************/
    8996             : 
    8997          12 : static void OGRGeoPackageDisableSpatialIndex(sqlite3_context *pContext,
    8998             :                                              int /*argc*/, sqlite3_value **argv)
    8999             : {
    9000          23 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9001          11 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9002             :     {
    9003           2 :         sqlite3_result_int(pContext, 0);
    9004           2 :         return;
    9005             :     }
    9006             : 
    9007             :     const char *pszTableName =
    9008          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9009             :     const char *pszGeomName =
    9010          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9011             :     GDALGeoPackageDataset *poDS =
    9012          10 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9013             : 
    9014          10 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9015          10 :         poDS->GetLayerByName(pszTableName));
    9016          10 :     if (poLyr == nullptr)
    9017             :     {
    9018           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9019           1 :         sqlite3_result_int(pContext, 0);
    9020           1 :         return;
    9021             :     }
    9022           9 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9023             :     {
    9024           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9025           1 :         sqlite3_result_int(pContext, 0);
    9026           1 :         return;
    9027             :     }
    9028             : 
    9029           8 :     sqlite3_result_int(pContext, poLyr->DropSpatialIndex(true));
    9030             : }
    9031             : 
    9032             : /************************************************************************/
    9033             : /*                  OGRGeoPackageHasSpatialIndex()                      */
    9034             : /************************************************************************/
    9035             : 
    9036          29 : static void OGRGeoPackageHasSpatialIndex(sqlite3_context *pContext,
    9037             :                                          int /*argc*/, sqlite3_value **argv)
    9038             : {
    9039          57 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9040          28 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9041             :     {
    9042           2 :         sqlite3_result_int(pContext, 0);
    9043           2 :         return;
    9044             :     }
    9045             : 
    9046             :     const char *pszTableName =
    9047          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9048             :     const char *pszGeomName =
    9049          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9050             :     GDALGeoPackageDataset *poDS =
    9051          27 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9052             : 
    9053          27 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9054          27 :         poDS->GetLayerByName(pszTableName));
    9055          27 :     if (poLyr == nullptr)
    9056             :     {
    9057           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9058           1 :         sqlite3_result_int(pContext, 0);
    9059           1 :         return;
    9060             :     }
    9061          26 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9062             :     {
    9063           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9064           1 :         sqlite3_result_int(pContext, 0);
    9065           1 :         return;
    9066             :     }
    9067             : 
    9068          25 :     poLyr->RunDeferredCreationIfNecessary();
    9069          25 :     poLyr->CreateSpatialIndexIfNecessary();
    9070             : 
    9071          25 :     sqlite3_result_int(pContext, poLyr->HasSpatialIndex());
    9072             : }
    9073             : 
    9074             : /************************************************************************/
    9075             : /*                       GPKG_hstore_get_value()                        */
    9076             : /************************************************************************/
    9077             : 
    9078           4 : static void GPKG_hstore_get_value(sqlite3_context *pContext, int /*argc*/,
    9079             :                                   sqlite3_value **argv)
    9080             : {
    9081           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9082           3 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9083             :     {
    9084           2 :         sqlite3_result_null(pContext);
    9085           2 :         return;
    9086             :     }
    9087             : 
    9088             :     const char *pszHStore =
    9089           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9090             :     const char *pszSearchedKey =
    9091           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9092           2 :     char *pszValue = OGRHStoreGetValue(pszHStore, pszSearchedKey);
    9093           2 :     if (pszValue != nullptr)
    9094           1 :         sqlite3_result_text(pContext, pszValue, -1, CPLFree);
    9095             :     else
    9096           1 :         sqlite3_result_null(pContext);
    9097             : }
    9098             : 
    9099             : /************************************************************************/
    9100             : /*                      GPKG_GDAL_GetMemFileFromBlob()                  */
    9101             : /************************************************************************/
    9102             : 
    9103         105 : static CPLString GPKG_GDAL_GetMemFileFromBlob(sqlite3_value **argv)
    9104             : {
    9105         105 :     int nBytes = sqlite3_value_bytes(argv[0]);
    9106             :     const GByte *pabyBLOB =
    9107         105 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    9108             :     CPLString osMemFileName(
    9109         105 :         VSIMemGenerateHiddenFilename("GPKG_GDAL_GetMemFileFromBlob"));
    9110         105 :     VSILFILE *fp = VSIFileFromMemBuffer(
    9111             :         osMemFileName.c_str(), const_cast<GByte *>(pabyBLOB), nBytes, FALSE);
    9112         105 :     VSIFCloseL(fp);
    9113         105 :     return osMemFileName;
    9114             : }
    9115             : 
    9116             : /************************************************************************/
    9117             : /*                       GPKG_GDAL_GetMimeType()                        */
    9118             : /************************************************************************/
    9119             : 
    9120          35 : static void GPKG_GDAL_GetMimeType(sqlite3_context *pContext, int /*argc*/,
    9121             :                                   sqlite3_value **argv)
    9122             : {
    9123          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9124             :     {
    9125           0 :         sqlite3_result_null(pContext);
    9126           0 :         return;
    9127             :     }
    9128             : 
    9129          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9130             :     GDALDriver *poDriver =
    9131          35 :         GDALDriver::FromHandle(GDALIdentifyDriver(osMemFileName, nullptr));
    9132          35 :     if (poDriver != nullptr)
    9133             :     {
    9134          35 :         const char *pszRes = nullptr;
    9135          35 :         if (EQUAL(poDriver->GetDescription(), "PNG"))
    9136          23 :             pszRes = "image/png";
    9137          12 :         else if (EQUAL(poDriver->GetDescription(), "JPEG"))
    9138           6 :             pszRes = "image/jpeg";
    9139           6 :         else if (EQUAL(poDriver->GetDescription(), "WEBP"))
    9140           6 :             pszRes = "image/x-webp";
    9141           0 :         else if (EQUAL(poDriver->GetDescription(), "GTIFF"))
    9142           0 :             pszRes = "image/tiff";
    9143             :         else
    9144           0 :             pszRes = CPLSPrintf("gdal/%s", poDriver->GetDescription());
    9145          35 :         sqlite3_result_text(pContext, pszRes, -1, SQLITE_TRANSIENT);
    9146             :     }
    9147             :     else
    9148           0 :         sqlite3_result_null(pContext);
    9149          35 :     VSIUnlink(osMemFileName);
    9150             : }
    9151             : 
    9152             : /************************************************************************/
    9153             : /*                       GPKG_GDAL_GetBandCount()                       */
    9154             : /************************************************************************/
    9155             : 
    9156          35 : static void GPKG_GDAL_GetBandCount(sqlite3_context *pContext, int /*argc*/,
    9157             :                                    sqlite3_value **argv)
    9158             : {
    9159          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9160             :     {
    9161           0 :         sqlite3_result_null(pContext);
    9162           0 :         return;
    9163             :     }
    9164             : 
    9165          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9166             :     auto poDS = std::unique_ptr<GDALDataset>(
    9167             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9168          70 :                           nullptr, nullptr, nullptr));
    9169          35 :     if (poDS != nullptr)
    9170             :     {
    9171          35 :         sqlite3_result_int(pContext, poDS->GetRasterCount());
    9172             :     }
    9173             :     else
    9174           0 :         sqlite3_result_null(pContext);
    9175          35 :     VSIUnlink(osMemFileName);
    9176             : }
    9177             : 
    9178             : /************************************************************************/
    9179             : /*                       GPKG_GDAL_HasColorTable()                      */
    9180             : /************************************************************************/
    9181             : 
    9182          35 : static void GPKG_GDAL_HasColorTable(sqlite3_context *pContext, int /*argc*/,
    9183             :                                     sqlite3_value **argv)
    9184             : {
    9185          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9186             :     {
    9187           0 :         sqlite3_result_null(pContext);
    9188           0 :         return;
    9189             :     }
    9190             : 
    9191          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9192             :     auto poDS = std::unique_ptr<GDALDataset>(
    9193             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9194          70 :                           nullptr, nullptr, nullptr));
    9195          35 :     if (poDS != nullptr)
    9196             :     {
    9197          35 :         sqlite3_result_int(
    9198          46 :             pContext, poDS->GetRasterCount() == 1 &&
    9199          11 :                           poDS->GetRasterBand(1)->GetColorTable() != nullptr);
    9200             :     }
    9201             :     else
    9202           0 :         sqlite3_result_null(pContext);
    9203          35 :     VSIUnlink(osMemFileName);
    9204             : }
    9205             : 
    9206             : /************************************************************************/
    9207             : /*                      GetRasterLayerDataset()                         */
    9208             : /************************************************************************/
    9209             : 
    9210             : GDALDataset *
    9211          12 : GDALGeoPackageDataset::GetRasterLayerDataset(const char *pszLayerName)
    9212             : {
    9213          12 :     const auto oIter = m_oCachedRasterDS.find(pszLayerName);
    9214          12 :     if (oIter != m_oCachedRasterDS.end())
    9215          10 :         return oIter->second.get();
    9216             : 
    9217             :     auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
    9218           4 :         (std::string("GPKG:\"") + m_pszFilename + "\":" + pszLayerName).c_str(),
    9219           4 :         GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR));
    9220           2 :     if (!poDS)
    9221             :     {
    9222           0 :         return nullptr;
    9223             :     }
    9224           2 :     m_oCachedRasterDS[pszLayerName] = std::move(poDS);
    9225           2 :     return m_oCachedRasterDS[pszLayerName].get();
    9226             : }
    9227             : 
    9228             : /************************************************************************/
    9229             : /*                   GPKG_gdal_get_layer_pixel_value()                  */
    9230             : /************************************************************************/
    9231             : 
    9232             : // NOTE: keep in sync implementations in ogrsqlitesqlfunctionscommon.cpp
    9233             : // and ogrgeopackagedatasource.cpp
    9234          13 : static void GPKG_gdal_get_layer_pixel_value(sqlite3_context *pContext, int argc,
    9235             :                                             sqlite3_value **argv)
    9236             : {
    9237          13 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9238             :     {
    9239           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9240             :                  "Invalid arguments to gdal_get_layer_pixel_value()");
    9241           1 :         sqlite3_result_null(pContext);
    9242           1 :         return;
    9243             :     }
    9244             : 
    9245             :     const char *pszLayerName =
    9246          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9247             : 
    9248             :     GDALGeoPackageDataset *poGlobalDS =
    9249          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9250          12 :     auto poDS = poGlobalDS->GetRasterLayerDataset(pszLayerName);
    9251          12 :     if (!poDS)
    9252             :     {
    9253           0 :         sqlite3_result_null(pContext);
    9254           0 :         return;
    9255             :     }
    9256             : 
    9257          12 :     OGRSQLite_gdal_get_pixel_value_common("gdal_get_layer_pixel_value",
    9258             :                                           pContext, argc, argv, poDS);
    9259             : }
    9260             : 
    9261             : /************************************************************************/
    9262             : /*                       GPKG_ogr_layer_Extent()                        */
    9263             : /************************************************************************/
    9264             : 
    9265           3 : static void GPKG_ogr_layer_Extent(sqlite3_context *pContext, int /*argc*/,
    9266             :                                   sqlite3_value **argv)
    9267             : {
    9268           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9269             :     {
    9270           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Invalid argument type",
    9271             :                  "ogr_layer_Extent");
    9272           1 :         sqlite3_result_null(pContext);
    9273           2 :         return;
    9274             :     }
    9275             : 
    9276             :     const char *pszLayerName =
    9277           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9278             :     GDALGeoPackageDataset *poDS =
    9279           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9280           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9281           2 :     if (!poLayer)
    9282             :     {
    9283           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer",
    9284             :                  "ogr_layer_Extent");
    9285           1 :         sqlite3_result_null(pContext);
    9286           1 :         return;
    9287             :     }
    9288             : 
    9289           1 :     if (poLayer->GetGeomType() == wkbNone)
    9290             :     {
    9291           0 :         sqlite3_result_null(pContext);
    9292           0 :         return;
    9293             :     }
    9294             : 
    9295           1 :     OGREnvelope sExtent;
    9296           1 :     if (poLayer->GetExtent(&sExtent) != OGRERR_NONE)
    9297             :     {
    9298           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9299             :                  "ogr_layer_Extent");
    9300           0 :         sqlite3_result_null(pContext);
    9301           0 :         return;
    9302             :     }
    9303             : 
    9304           1 :     OGRPolygon oPoly;
    9305           1 :     auto poRing = std::make_unique<OGRLinearRing>();
    9306           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9307           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MinY);
    9308           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MaxY);
    9309           1 :     poRing->addPoint(sExtent.MinX, sExtent.MaxY);
    9310           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9311           1 :     oPoly.addRing(std::move(poRing));
    9312             : 
    9313           1 :     const auto poSRS = poLayer->GetSpatialRef();
    9314           1 :     const int nSRID = poDS->GetSrsId(poSRS);
    9315           1 :     size_t nBLOBDestLen = 0;
    9316             :     GByte *pabyDestBLOB =
    9317           1 :         GPkgGeometryFromOGR(&oPoly, nSRID, nullptr, &nBLOBDestLen);
    9318           1 :     if (!pabyDestBLOB)
    9319             :     {
    9320           0 :         sqlite3_result_null(pContext);
    9321           0 :         return;
    9322             :     }
    9323           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    9324             :                         VSIFree);
    9325             : }
    9326             : 
    9327             : /************************************************************************/
    9328             : /*                      InstallSQLFunctions()                           */
    9329             : /************************************************************************/
    9330             : 
    9331             : #ifndef SQLITE_DETERMINISTIC
    9332             : #define SQLITE_DETERMINISTIC 0
    9333             : #endif
    9334             : 
    9335             : #ifndef SQLITE_INNOCUOUS
    9336             : #define SQLITE_INNOCUOUS 0
    9337             : #endif
    9338             : 
    9339             : #ifndef UTF8_INNOCUOUS
    9340             : #define UTF8_INNOCUOUS (SQLITE_UTF8 | SQLITE_DETERMINISTIC | SQLITE_INNOCUOUS)
    9341             : #endif
    9342             : 
    9343        2073 : void GDALGeoPackageDataset::InstallSQLFunctions()
    9344             : {
    9345        2073 :     InitSpatialite();
    9346             : 
    9347             :     // Enable SpatiaLite 4.3 "amphibious" mode, i.e. that SpatiaLite functions
    9348             :     // that take geometries will accept GPKG encoded geometries without
    9349             :     // explicit conversion.
    9350             :     // Use sqlite3_exec() instead of SQLCommand() since we don't want verbose
    9351             :     // error.
    9352        2073 :     sqlite3_exec(hDB, "SELECT EnableGpkgAmphibiousMode()", nullptr, nullptr,
    9353             :                  nullptr);
    9354             : 
    9355             :     /* Used by RTree Spatial Index Extension */
    9356        2073 :     sqlite3_create_function(hDB, "ST_MinX", 1, UTF8_INNOCUOUS, nullptr,
    9357             :                             OGRGeoPackageSTMinX, nullptr, nullptr);
    9358        2073 :     sqlite3_create_function(hDB, "ST_MinY", 1, UTF8_INNOCUOUS, nullptr,
    9359             :                             OGRGeoPackageSTMinY, nullptr, nullptr);
    9360        2073 :     sqlite3_create_function(hDB, "ST_MaxX", 1, UTF8_INNOCUOUS, nullptr,
    9361             :                             OGRGeoPackageSTMaxX, nullptr, nullptr);
    9362        2073 :     sqlite3_create_function(hDB, "ST_MaxY", 1, UTF8_INNOCUOUS, nullptr,
    9363             :                             OGRGeoPackageSTMaxY, nullptr, nullptr);
    9364        2073 :     sqlite3_create_function(hDB, "ST_IsEmpty", 1, UTF8_INNOCUOUS, nullptr,
    9365             :                             OGRGeoPackageSTIsEmpty, nullptr, nullptr);
    9366             : 
    9367             :     /* Used by Geometry Type Triggers Extension */
    9368        2073 :     sqlite3_create_function(hDB, "ST_GeometryType", 1, UTF8_INNOCUOUS, nullptr,
    9369             :                             OGRGeoPackageSTGeometryType, nullptr, nullptr);
    9370        2073 :     sqlite3_create_function(hDB, "GPKG_IsAssignable", 2, UTF8_INNOCUOUS,
    9371             :                             nullptr, OGRGeoPackageGPKGIsAssignable, nullptr,
    9372             :                             nullptr);
    9373             : 
    9374             :     /* Used by Geometry SRS ID Triggers Extension */
    9375        2073 :     sqlite3_create_function(hDB, "ST_SRID", 1, UTF8_INNOCUOUS, nullptr,
    9376             :                             OGRGeoPackageSTSRID, nullptr, nullptr);
    9377             : 
    9378             :     /* Spatialite-like functions */
    9379        2073 :     sqlite3_create_function(hDB, "CreateSpatialIndex", 2, SQLITE_UTF8, this,
    9380             :                             OGRGeoPackageCreateSpatialIndex, nullptr, nullptr);
    9381        2073 :     sqlite3_create_function(hDB, "DisableSpatialIndex", 2, SQLITE_UTF8, this,
    9382             :                             OGRGeoPackageDisableSpatialIndex, nullptr, nullptr);
    9383        2073 :     sqlite3_create_function(hDB, "HasSpatialIndex", 2, SQLITE_UTF8, this,
    9384             :                             OGRGeoPackageHasSpatialIndex, nullptr, nullptr);
    9385             : 
    9386             :     // HSTORE functions
    9387        2073 :     sqlite3_create_function(hDB, "hstore_get_value", 2, UTF8_INNOCUOUS, nullptr,
    9388             :                             GPKG_hstore_get_value, nullptr, nullptr);
    9389             : 
    9390             :     // Override a few Spatialite functions to work with gpkg_spatial_ref_sys
    9391        2073 :     sqlite3_create_function(hDB, "ST_Transform", 2, UTF8_INNOCUOUS, this,
    9392             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9393        2073 :     sqlite3_create_function(hDB, "Transform", 2, UTF8_INNOCUOUS, this,
    9394             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9395        2073 :     sqlite3_create_function(hDB, "SridFromAuthCRS", 2, SQLITE_UTF8, this,
    9396             :                             OGRGeoPackageSridFromAuthCRS, nullptr, nullptr);
    9397             : 
    9398        2073 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9399             :                             OGRGeoPackageSTEnvelopesIntersectsTwoParams,
    9400             :                             nullptr, nullptr);
    9401        2073 :     sqlite3_create_function(
    9402             :         hDB, "ST_EnvelopesIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9403             :         OGRGeoPackageSTEnvelopesIntersectsTwoParams, nullptr, nullptr);
    9404             : 
    9405        2073 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 5, UTF8_INNOCUOUS, nullptr,
    9406             :                             OGRGeoPackageSTEnvelopesIntersects, nullptr,
    9407             :                             nullptr);
    9408        2073 :     sqlite3_create_function(hDB, "ST_EnvelopesIntersects", 5, UTF8_INNOCUOUS,
    9409             :                             nullptr, OGRGeoPackageSTEnvelopesIntersects,
    9410             :                             nullptr, nullptr);
    9411             : 
    9412             :     // Implementation that directly hacks the GeoPackage geometry blob header
    9413        2073 :     sqlite3_create_function(hDB, "SetSRID", 2, UTF8_INNOCUOUS, nullptr,
    9414             :                             OGRGeoPackageSetSRID, nullptr, nullptr);
    9415             : 
    9416             :     // GDAL specific function
    9417        2073 :     sqlite3_create_function(hDB, "ImportFromEPSG", 1, SQLITE_UTF8, this,
    9418             :                             OGRGeoPackageImportFromEPSG, nullptr, nullptr);
    9419             : 
    9420             :     // May be used by ogrmerge.py
    9421        2073 :     sqlite3_create_function(hDB, "RegisterGeometryExtension", 3, SQLITE_UTF8,
    9422             :                             this, OGRGeoPackageRegisterGeometryExtension,
    9423             :                             nullptr, nullptr);
    9424             : 
    9425        2073 :     if (OGRGeometryFactory::haveGEOS())
    9426             :     {
    9427        2073 :         sqlite3_create_function(hDB, "ST_MakeValid", 1, UTF8_INNOCUOUS, nullptr,
    9428             :                                 OGRGeoPackageSTMakeValid, nullptr, nullptr);
    9429             :     }
    9430             : 
    9431        2073 :     sqlite3_create_function(hDB, "ST_Length", 1, UTF8_INNOCUOUS, nullptr,
    9432             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9433             :                             nullptr);
    9434        2073 :     sqlite3_create_function(hDB, "ST_Length", 2, UTF8_INNOCUOUS, this,
    9435             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9436             :                             nullptr);
    9437             : 
    9438        2073 :     sqlite3_create_function(hDB, "ST_Area", 1, UTF8_INNOCUOUS, nullptr,
    9439             :                             OGRGeoPackageSTArea, nullptr, nullptr);
    9440        2073 :     sqlite3_create_function(hDB, "ST_Area", 2, UTF8_INNOCUOUS, this,
    9441             :                             OGRGeoPackageGeodesicArea, nullptr, nullptr);
    9442             : 
    9443             :     // Debug functions
    9444        2073 :     if (CPLTestBool(CPLGetConfigOption("GPKG_DEBUG", "FALSE")))
    9445             :     {
    9446         423 :         sqlite3_create_function(hDB, "GDAL_GetMimeType", 1,
    9447             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9448             :                                 GPKG_GDAL_GetMimeType, nullptr, nullptr);
    9449         423 :         sqlite3_create_function(hDB, "GDAL_GetBandCount", 1,
    9450             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9451             :                                 GPKG_GDAL_GetBandCount, nullptr, nullptr);
    9452         423 :         sqlite3_create_function(hDB, "GDAL_HasColorTable", 1,
    9453             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9454             :                                 GPKG_GDAL_HasColorTable, nullptr, nullptr);
    9455             :     }
    9456             : 
    9457        2073 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 5, SQLITE_UTF8,
    9458             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9459             :                             nullptr);
    9460        2073 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 6, SQLITE_UTF8,
    9461             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9462             :                             nullptr);
    9463             : 
    9464             :     // Function from VirtualOGR
    9465        2073 :     sqlite3_create_function(hDB, "ogr_layer_Extent", 1, SQLITE_UTF8, this,
    9466             :                             GPKG_ogr_layer_Extent, nullptr, nullptr);
    9467             : 
    9468        2073 :     m_pSQLFunctionData = OGRSQLiteRegisterSQLFunctionsCommon(hDB);
    9469        2073 : }
    9470             : 
    9471             : /************************************************************************/
    9472             : /*                         OpenOrCreateDB()                             */
    9473             : /************************************************************************/
    9474             : 
    9475        2077 : bool GDALGeoPackageDataset::OpenOrCreateDB(int flags)
    9476             : {
    9477        2077 :     const bool bSuccess = OGRSQLiteBaseDataSource::OpenOrCreateDB(
    9478             :         flags, /*bRegisterOGR2SQLiteExtensions=*/false,
    9479             :         /*bLoadExtensions=*/true);
    9480        2077 :     if (!bSuccess)
    9481           9 :         return false;
    9482             : 
    9483             :     // Turning on recursive_triggers is needed so that DELETE triggers fire
    9484             :     // in a INSERT OR REPLACE statement. In particular this is needed to
    9485             :     // make sure gpkg_ogr_contents.feature_count is properly updated.
    9486        2068 :     SQLCommand(hDB, "PRAGMA recursive_triggers = 1");
    9487             : 
    9488        2068 :     InstallSQLFunctions();
    9489             : 
    9490             :     const char *pszSqlitePragma =
    9491        2068 :         CPLGetConfigOption("OGR_SQLITE_PRAGMA", nullptr);
    9492        2068 :     OGRErr eErr = OGRERR_NONE;
    9493           6 :     if ((!pszSqlitePragma || !strstr(pszSqlitePragma, "trusted_schema")) &&
    9494             :         // Older sqlite versions don't have this pragma
    9495        4142 :         SQLGetInteger(hDB, "PRAGMA trusted_schema", &eErr) == 0 &&
    9496        2068 :         eErr == OGRERR_NONE)
    9497             :     {
    9498        2068 :         bool bNeedsTrustedSchema = false;
    9499             : 
    9500             :         // Current SQLite versions require PRAGMA trusted_schema = 1 to be
    9501             :         // able to use the RTree from triggers, which is only needed when
    9502             :         // modifying the RTree.
    9503        5094 :         if (((flags & SQLITE_OPEN_READWRITE) != 0 ||
    9504        3178 :              (flags & SQLITE_OPEN_CREATE) != 0) &&
    9505        1110 :             OGRSQLiteRTreeRequiresTrustedSchemaOn())
    9506             :         {
    9507        1110 :             bNeedsTrustedSchema = true;
    9508             :         }
    9509             : 
    9510             : #ifdef HAVE_SPATIALITE
    9511             :         // Spatialite <= 5.1.0 doesn't declare its functions as SQLITE_INNOCUOUS
    9512         958 :         if (!bNeedsTrustedSchema && HasExtensionsTable() &&
    9513         877 :             SQLGetInteger(
    9514             :                 hDB,
    9515             :                 "SELECT 1 FROM gpkg_extensions WHERE "
    9516             :                 "extension_name ='gdal_spatialite_computed_geom_column'",
    9517           1 :                 nullptr) == 1 &&
    9518        3026 :             SpatialiteRequiresTrustedSchemaOn() && AreSpatialiteTriggersSafe())
    9519             :         {
    9520           1 :             bNeedsTrustedSchema = true;
    9521             :         }
    9522             : #endif
    9523             : 
    9524        2068 :         if (bNeedsTrustedSchema)
    9525             :         {
    9526        1111 :             CPLDebug("GPKG", "Setting PRAGMA trusted_schema = 1");
    9527        1111 :             SQLCommand(hDB, "PRAGMA trusted_schema = 1");
    9528             :         }
    9529             :     }
    9530             : 
    9531             :     const char *pszPreludeStatements =
    9532        2068 :         CSLFetchNameValue(papszOpenOptions, "PRELUDE_STATEMENTS");
    9533        2068 :     if (pszPreludeStatements)
    9534             :     {
    9535           2 :         if (SQLCommand(hDB, pszPreludeStatements) != OGRERR_NONE)
    9536           0 :             return false;
    9537             :     }
    9538             : 
    9539        2068 :     return true;
    9540             : }
    9541             : 
    9542             : /************************************************************************/
    9543             : /*                   GetLayerWithGetSpatialWhereByName()                */
    9544             : /************************************************************************/
    9545             : 
    9546             : std::pair<OGRLayer *, IOGRSQLiteGetSpatialWhere *>
    9547          90 : GDALGeoPackageDataset::GetLayerWithGetSpatialWhereByName(const char *pszName)
    9548             : {
    9549             :     OGRGeoPackageLayer *poRet =
    9550          90 :         cpl::down_cast<OGRGeoPackageLayer *>(GetLayerByName(pszName));
    9551          90 :     return std::pair(poRet, poRet);
    9552             : }
    9553             : 
    9554             : /************************************************************************/
    9555             : /*                       CommitTransaction()                            */
    9556             : /************************************************************************/
    9557             : 
    9558         208 : OGRErr GDALGeoPackageDataset::CommitTransaction()
    9559             : 
    9560             : {
    9561         208 :     if (m_nSoftTransactionLevel == 1)
    9562             :     {
    9563         207 :         FlushMetadata();
    9564         463 :         for (auto &poLayer : m_apoLayers)
    9565             :         {
    9566         256 :             poLayer->DoJobAtTransactionCommit();
    9567             :         }
    9568             :     }
    9569             : 
    9570         208 :     return OGRSQLiteBaseDataSource::CommitTransaction();
    9571             : }
    9572             : 
    9573             : /************************************************************************/
    9574             : /*                     RollbackTransaction()                            */
    9575             : /************************************************************************/
    9576             : 
    9577          35 : OGRErr GDALGeoPackageDataset::RollbackTransaction()
    9578             : 
    9579             : {
    9580             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9581          70 :     std::vector<bool> abAddTriggers;
    9582          35 :     std::vector<bool> abTriggersDeletedInTransaction;
    9583             : #endif
    9584          35 :     if (m_nSoftTransactionLevel == 1)
    9585             :     {
    9586          34 :         FlushMetadata();
    9587          70 :         for (auto &poLayer : m_apoLayers)
    9588             :         {
    9589             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9590          36 :             abAddTriggers.push_back(poLayer->GetAddOGRFeatureCountTriggers());
    9591          36 :             abTriggersDeletedInTransaction.push_back(
    9592          36 :                 poLayer->GetOGRFeatureCountTriggersDeletedInTransaction());
    9593          36 :             poLayer->SetAddOGRFeatureCountTriggers(false);
    9594             : #endif
    9595          36 :             poLayer->DoJobAtTransactionRollback();
    9596             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9597          36 :             poLayer->DisableFeatureCount();
    9598             : #endif
    9599             :         }
    9600             :     }
    9601             : 
    9602          35 :     const OGRErr eErr = OGRSQLiteBaseDataSource::RollbackTransaction();
    9603             : 
    9604             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9605          35 :     if (!abAddTriggers.empty())
    9606             :     {
    9607          68 :         for (size_t i = 0; i < m_apoLayers.size(); ++i)
    9608             :         {
    9609          36 :             auto &poLayer = m_apoLayers[i];
    9610          36 :             if (abTriggersDeletedInTransaction[i])
    9611             :             {
    9612           7 :                 poLayer->SetOGRFeatureCountTriggersEnabled(true);
    9613             :             }
    9614             :             else
    9615             :             {
    9616          29 :                 poLayer->SetAddOGRFeatureCountTriggers(abAddTriggers[i]);
    9617             :             }
    9618             :         }
    9619             :     }
    9620             : #endif
    9621          70 :     return eErr;
    9622             : }
    9623             : 
    9624             : /************************************************************************/
    9625             : /*                       GetGeometryTypeString()                        */
    9626             : /************************************************************************/
    9627             : 
    9628             : const char *
    9629        1447 : GDALGeoPackageDataset::GetGeometryTypeString(OGRwkbGeometryType eType)
    9630             : {
    9631        1447 :     const char *pszGPKGGeomType = OGRToOGCGeomType(eType);
    9632        1459 :     if (EQUAL(pszGPKGGeomType, "GEOMETRYCOLLECTION") &&
    9633          12 :         CPLTestBool(CPLGetConfigOption("OGR_GPKG_GEOMCOLLECTION", "NO")))
    9634             :     {
    9635           0 :         pszGPKGGeomType = "GEOMCOLLECTION";
    9636             :     }
    9637        1447 :     return pszGPKGGeomType;
    9638             : }
    9639             : 
    9640             : /************************************************************************/
    9641             : /*                           GetFieldDomainNames()                      */
    9642             : /************************************************************************/
    9643             : 
    9644             : std::vector<std::string>
    9645          11 : GDALGeoPackageDataset::GetFieldDomainNames(CSLConstList) const
    9646             : {
    9647          11 :     if (!HasDataColumnConstraintsTable())
    9648           4 :         return std::vector<std::string>();
    9649             : 
    9650          14 :     std::vector<std::string> oDomainNamesList;
    9651             : 
    9652           7 :     std::unique_ptr<SQLResult> oResultTable;
    9653             :     {
    9654             :         std::string osSQL =
    9655             :             "SELECT DISTINCT constraint_name "
    9656             :             "FROM gpkg_data_column_constraints "
    9657             :             "WHERE constraint_name NOT LIKE '_%_domain_description' "
    9658             :             "ORDER BY constraint_name "
    9659           7 :             "LIMIT 10000"  // to avoid denial of service
    9660             :             ;
    9661           7 :         oResultTable = SQLQuery(hDB, osSQL.c_str());
    9662           7 :         if (!oResultTable)
    9663           0 :             return oDomainNamesList;
    9664             :     }
    9665             : 
    9666           7 :     if (oResultTable->RowCount() == 10000)
    9667             :     {
    9668           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9669             :                  "Number of rows returned for field domain names has been "
    9670             :                  "truncated.");
    9671             :     }
    9672           7 :     else if (oResultTable->RowCount() > 0)
    9673             :     {
    9674           7 :         oDomainNamesList.reserve(oResultTable->RowCount());
    9675          89 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    9676             :         {
    9677          82 :             const char *pszConstraintName = oResultTable->GetValue(0, i);
    9678          82 :             if (!pszConstraintName)
    9679           0 :                 continue;
    9680             : 
    9681          82 :             oDomainNamesList.emplace_back(pszConstraintName);
    9682             :         }
    9683             :     }
    9684             : 
    9685           7 :     return oDomainNamesList;
    9686             : }
    9687             : 
    9688             : /************************************************************************/
    9689             : /*                           GetFieldDomain()                           */
    9690             : /************************************************************************/
    9691             : 
    9692             : const OGRFieldDomain *
    9693         102 : GDALGeoPackageDataset::GetFieldDomain(const std::string &name) const
    9694             : {
    9695         102 :     const auto baseRet = GDALDataset::GetFieldDomain(name);
    9696         102 :     if (baseRet)
    9697          42 :         return baseRet;
    9698             : 
    9699          60 :     if (!HasDataColumnConstraintsTable())
    9700           4 :         return nullptr;
    9701             : 
    9702          56 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
    9703          56 :     const char *min_is_inclusive =
    9704          56 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
    9705          56 :     const char *max_is_inclusive =
    9706          56 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
    9707             : 
    9708          56 :     std::unique_ptr<SQLResult> oResultTable;
    9709             :     // Note: for coded domains, we use a little trick by using a dummy
    9710             :     // _{domainname}_domain_description enum that has a single entry whose
    9711             :     // description is the description of the main domain.
    9712             :     {
    9713          56 :         char *pszSQL = sqlite3_mprintf(
    9714             :             "SELECT constraint_type, value, min, %s, "
    9715             :             "max, %s, description, constraint_name "
    9716             :             "FROM gpkg_data_column_constraints "
    9717             :             "WHERE constraint_name IN ('%q', "
    9718             :             "'_%q_domain_description') "
    9719             :             "AND length(constraint_type) < 100 "  // to
    9720             :                                                   // avoid
    9721             :                                                   // denial
    9722             :                                                   // of
    9723             :                                                   // service
    9724             :             "AND (value IS NULL OR length(value) < "
    9725             :             "10000) "  // to avoid denial
    9726             :                        // of service
    9727             :             "AND (description IS NULL OR "
    9728             :             "length(description) < 10000) "  // to
    9729             :                                              // avoid
    9730             :                                              // denial
    9731             :                                              // of
    9732             :                                              // service
    9733             :             "ORDER BY value "
    9734             :             "LIMIT 10000",  // to avoid denial of
    9735             :                             // service
    9736             :             min_is_inclusive, max_is_inclusive, name.c_str(), name.c_str());
    9737          56 :         oResultTable = SQLQuery(hDB, pszSQL);
    9738          56 :         sqlite3_free(pszSQL);
    9739          56 :         if (!oResultTable)
    9740           0 :             return nullptr;
    9741             :     }
    9742          56 :     if (oResultTable->RowCount() == 0)
    9743             :     {
    9744          15 :         return nullptr;
    9745             :     }
    9746          41 :     if (oResultTable->RowCount() == 10000)
    9747             :     {
    9748           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9749             :                  "Number of rows returned for field domain %s has been "
    9750             :                  "truncated.",
    9751             :                  name.c_str());
    9752             :     }
    9753             : 
    9754             :     // Try to find the field domain data type from fields that implement it
    9755          41 :     int nFieldType = -1;
    9756          41 :     OGRFieldSubType eSubType = OFSTNone;
    9757          41 :     if (HasDataColumnsTable())
    9758             :     {
    9759          36 :         char *pszSQL = sqlite3_mprintf(
    9760             :             "SELECT table_name, column_name FROM gpkg_data_columns WHERE "
    9761             :             "constraint_name = '%q' LIMIT 10",
    9762             :             name.c_str());
    9763          72 :         auto oResultTable2 = SQLQuery(hDB, pszSQL);
    9764          36 :         sqlite3_free(pszSQL);
    9765          36 :         if (oResultTable2 && oResultTable2->RowCount() >= 1)
    9766             :         {
    9767          46 :             for (int iRecord = 0; iRecord < oResultTable2->RowCount();
    9768             :                  iRecord++)
    9769             :             {
    9770          23 :                 const char *pszTableName = oResultTable2->GetValue(0, iRecord);
    9771          23 :                 const char *pszColumnName = oResultTable2->GetValue(1, iRecord);
    9772          23 :                 if (pszTableName == nullptr || pszColumnName == nullptr)
    9773           0 :                     continue;
    9774             :                 OGRLayer *poLayer =
    9775          46 :                     const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    9776          23 :                         pszTableName);
    9777          23 :                 if (poLayer)
    9778             :                 {
    9779          23 :                     const auto poFDefn = poLayer->GetLayerDefn();
    9780          23 :                     int nIdx = poFDefn->GetFieldIndex(pszColumnName);
    9781          23 :                     if (nIdx >= 0)
    9782             :                     {
    9783          23 :                         const auto poFieldDefn = poFDefn->GetFieldDefn(nIdx);
    9784          23 :                         const auto eType = poFieldDefn->GetType();
    9785          23 :                         if (nFieldType < 0)
    9786             :                         {
    9787          23 :                             nFieldType = eType;
    9788          23 :                             eSubType = poFieldDefn->GetSubType();
    9789             :                         }
    9790           0 :                         else if ((eType == OFTInteger64 || eType == OFTReal) &&
    9791             :                                  nFieldType == OFTInteger)
    9792             :                         {
    9793             :                             // ok
    9794             :                         }
    9795           0 :                         else if (eType == OFTInteger &&
    9796           0 :                                  (nFieldType == OFTInteger64 ||
    9797             :                                   nFieldType == OFTReal))
    9798             :                         {
    9799           0 :                             nFieldType = OFTInteger;
    9800           0 :                             eSubType = OFSTNone;
    9801             :                         }
    9802           0 :                         else if (nFieldType != eType)
    9803             :                         {
    9804           0 :                             nFieldType = -1;
    9805           0 :                             eSubType = OFSTNone;
    9806           0 :                             break;
    9807             :                         }
    9808             :                     }
    9809             :                 }
    9810             :             }
    9811             :         }
    9812             :     }
    9813             : 
    9814          41 :     std::unique_ptr<OGRFieldDomain> poDomain;
    9815          82 :     std::vector<OGRCodedValue> asValues;
    9816          41 :     bool error = false;
    9817          82 :     CPLString osLastConstraintType;
    9818          41 :     int nFieldTypeFromEnumCode = -1;
    9819          82 :     std::string osConstraintDescription;
    9820          82 :     std::string osDescrConstraintName("_");
    9821          41 :     osDescrConstraintName += name;
    9822          41 :     osDescrConstraintName += "_domain_description";
    9823         100 :     for (int iRecord = 0; iRecord < oResultTable->RowCount(); iRecord++)
    9824             :     {
    9825          63 :         const char *pszConstraintType = oResultTable->GetValue(0, iRecord);
    9826          63 :         if (pszConstraintType == nullptr)
    9827           1 :             continue;
    9828          63 :         const char *pszValue = oResultTable->GetValue(1, iRecord);
    9829          63 :         const char *pszMin = oResultTable->GetValue(2, iRecord);
    9830             :         const bool bIsMinIncluded =
    9831          63 :             oResultTable->GetValueAsInteger(3, iRecord) == 1;
    9832          63 :         const char *pszMax = oResultTable->GetValue(4, iRecord);
    9833             :         const bool bIsMaxIncluded =
    9834          63 :             oResultTable->GetValueAsInteger(5, iRecord) == 1;
    9835          63 :         const char *pszDescription = oResultTable->GetValue(6, iRecord);
    9836          63 :         const char *pszConstraintName = oResultTable->GetValue(7, iRecord);
    9837             : 
    9838          63 :         if (!osLastConstraintType.empty() && osLastConstraintType != "enum")
    9839             :         {
    9840           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    9841             :                      "Only constraint of type 'enum' can have multiple rows");
    9842           1 :             error = true;
    9843           4 :             break;
    9844             :         }
    9845             : 
    9846          62 :         if (strcmp(pszConstraintType, "enum") == 0)
    9847             :         {
    9848          42 :             if (pszValue == nullptr)
    9849             :             {
    9850           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    9851             :                          "NULL in 'value' column of enumeration");
    9852           1 :                 error = true;
    9853           1 :                 break;
    9854             :             }
    9855          41 :             if (osDescrConstraintName == pszConstraintName)
    9856             :             {
    9857           1 :                 if (pszDescription)
    9858             :                 {
    9859           1 :                     osConstraintDescription = pszDescription;
    9860             :                 }
    9861           1 :                 continue;
    9862             :             }
    9863          40 :             if (asValues.empty())
    9864             :             {
    9865          20 :                 asValues.reserve(oResultTable->RowCount() + 1);
    9866             :             }
    9867             :             OGRCodedValue cv;
    9868             :             // intended: the 'value' column in GPKG is actually the code
    9869          40 :             cv.pszCode = VSI_STRDUP_VERBOSE(pszValue);
    9870          40 :             if (cv.pszCode == nullptr)
    9871             :             {
    9872           0 :                 error = true;
    9873           0 :                 break;
    9874             :             }
    9875          40 :             if (pszDescription)
    9876             :             {
    9877          29 :                 cv.pszValue = VSI_STRDUP_VERBOSE(pszDescription);
    9878          29 :                 if (cv.pszValue == nullptr)
    9879             :                 {
    9880           0 :                     VSIFree(cv.pszCode);
    9881           0 :                     error = true;
    9882           0 :                     break;
    9883             :                 }
    9884             :             }
    9885             :             else
    9886             :             {
    9887          11 :                 cv.pszValue = nullptr;
    9888             :             }
    9889             : 
    9890             :             // If we can't get the data type from field definition, guess it
    9891             :             // from code.
    9892          40 :             if (nFieldType < 0 && nFieldTypeFromEnumCode != OFTString)
    9893             :             {
    9894          18 :                 switch (CPLGetValueType(cv.pszCode))
    9895             :                 {
    9896          13 :                     case CPL_VALUE_INTEGER:
    9897             :                     {
    9898          13 :                         if (nFieldTypeFromEnumCode != OFTReal &&
    9899             :                             nFieldTypeFromEnumCode != OFTInteger64)
    9900             :                         {
    9901           9 :                             const auto nVal = CPLAtoGIntBig(cv.pszCode);
    9902          17 :                             if (nVal < std::numeric_limits<int>::min() ||
    9903           8 :                                 nVal > std::numeric_limits<int>::max())
    9904             :                             {
    9905           3 :                                 nFieldTypeFromEnumCode = OFTInteger64;
    9906             :                             }
    9907             :                             else
    9908             :                             {
    9909           6 :                                 nFieldTypeFromEnumCode = OFTInteger;
    9910             :                             }
    9911             :                         }
    9912          13 :                         break;
    9913             :                     }
    9914             : 
    9915           3 :                     case CPL_VALUE_REAL:
    9916           3 :                         nFieldTypeFromEnumCode = OFTReal;
    9917           3 :                         break;
    9918             : 
    9919           2 :                     case CPL_VALUE_STRING:
    9920           2 :                         nFieldTypeFromEnumCode = OFTString;
    9921           2 :                         break;
    9922             :                 }
    9923             :             }
    9924             : 
    9925          40 :             asValues.emplace_back(cv);
    9926             :         }
    9927          20 :         else if (strcmp(pszConstraintType, "range") == 0)
    9928             :         {
    9929             :             OGRField sMin;
    9930             :             OGRField sMax;
    9931          14 :             OGR_RawField_SetUnset(&sMin);
    9932          14 :             OGR_RawField_SetUnset(&sMax);
    9933          14 :             if (nFieldType != OFTInteger && nFieldType != OFTInteger64)
    9934           8 :                 nFieldType = OFTReal;
    9935          27 :             if (pszMin != nullptr &&
    9936          13 :                 CPLAtof(pszMin) != -std::numeric_limits<double>::infinity())
    9937             :             {
    9938          10 :                 if (nFieldType == OFTInteger)
    9939           3 :                     sMin.Integer = atoi(pszMin);
    9940           7 :                 else if (nFieldType == OFTInteger64)
    9941           3 :                     sMin.Integer64 = CPLAtoGIntBig(pszMin);
    9942             :                 else /* if( nFieldType == OFTReal ) */
    9943           4 :                     sMin.Real = CPLAtof(pszMin);
    9944             :             }
    9945          27 :             if (pszMax != nullptr &&
    9946          13 :                 CPLAtof(pszMax) != std::numeric_limits<double>::infinity())
    9947             :             {
    9948          10 :                 if (nFieldType == OFTInteger)
    9949           3 :                     sMax.Integer = atoi(pszMax);
    9950           7 :                 else if (nFieldType == OFTInteger64)
    9951           3 :                     sMax.Integer64 = CPLAtoGIntBig(pszMax);
    9952             :                 else /* if( nFieldType == OFTReal ) */
    9953           4 :                     sMax.Real = CPLAtof(pszMax);
    9954             :             }
    9955          14 :             poDomain = std::make_unique<OGRRangeFieldDomain>(
    9956          14 :                 name, pszDescription ? pszDescription : "",
    9957          28 :                 static_cast<OGRFieldType>(nFieldType), eSubType, sMin,
    9958          14 :                 bIsMinIncluded, sMax, bIsMaxIncluded);
    9959             :         }
    9960           6 :         else if (strcmp(pszConstraintType, "glob") == 0)
    9961             :         {
    9962           5 :             if (pszValue == nullptr)
    9963             :             {
    9964           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    9965             :                          "NULL in 'value' column of glob");
    9966           1 :                 error = true;
    9967           1 :                 break;
    9968             :             }
    9969           4 :             if (nFieldType < 0)
    9970           1 :                 nFieldType = OFTString;
    9971           4 :             poDomain = std::make_unique<OGRGlobFieldDomain>(
    9972           4 :                 name, pszDescription ? pszDescription : "",
    9973          12 :                 static_cast<OGRFieldType>(nFieldType), eSubType, pszValue);
    9974             :         }
    9975             :         else
    9976             :         {
    9977           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    9978             :                      "Unhandled constraint_type: %s", pszConstraintType);
    9979           1 :             error = true;
    9980           1 :             break;
    9981             :         }
    9982             : 
    9983          58 :         osLastConstraintType = pszConstraintType;
    9984             :     }
    9985             : 
    9986          41 :     if (!asValues.empty())
    9987             :     {
    9988          20 :         if (nFieldType < 0)
    9989           9 :             nFieldType = nFieldTypeFromEnumCode;
    9990          20 :         poDomain = std::make_unique<OGRCodedFieldDomain>(
    9991             :             name, osConstraintDescription,
    9992          40 :             static_cast<OGRFieldType>(nFieldType), eSubType,
    9993          40 :             std::move(asValues));
    9994             :     }
    9995             : 
    9996          41 :     if (error)
    9997             :     {
    9998           4 :         return nullptr;
    9999             :     }
   10000             : 
   10001          37 :     m_oMapFieldDomains[name] = std::move(poDomain);
   10002          37 :     return GDALDataset::GetFieldDomain(name);
   10003             : }
   10004             : 
   10005             : /************************************************************************/
   10006             : /*                           AddFieldDomain()                           */
   10007             : /************************************************************************/
   10008             : 
   10009          18 : bool GDALGeoPackageDataset::AddFieldDomain(
   10010             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10011             : {
   10012          36 :     const std::string domainName(domain->GetName());
   10013          18 :     if (!GetUpdate())
   10014             :     {
   10015           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10016             :                  "AddFieldDomain() not supported on read-only dataset");
   10017           0 :         return false;
   10018             :     }
   10019          18 :     if (GetFieldDomain(domainName) != nullptr)
   10020             :     {
   10021           1 :         failureReason = "A domain of identical name already exists";
   10022           1 :         return false;
   10023             :     }
   10024          17 :     if (!CreateColumnsTableAndColumnConstraintsTablesIfNecessary())
   10025           0 :         return false;
   10026             : 
   10027          17 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
   10028          17 :     const char *min_is_inclusive =
   10029          17 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
   10030          17 :     const char *max_is_inclusive =
   10031          17 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
   10032             : 
   10033          17 :     const auto &osDescription = domain->GetDescription();
   10034          17 :     switch (domain->GetDomainType())
   10035             :     {
   10036          11 :         case OFDT_CODED:
   10037             :         {
   10038             :             const auto poCodedDomain =
   10039          11 :                 cpl::down_cast<const OGRCodedFieldDomain *>(domain.get());
   10040          11 :             if (!osDescription.empty())
   10041             :             {
   10042             :                 // We use a little trick by using a dummy
   10043             :                 // _{domainname}_domain_description enum that has a single
   10044             :                 // entry whose description is the description of the main
   10045             :                 // domain.
   10046           1 :                 char *pszSQL = sqlite3_mprintf(
   10047             :                     "INSERT INTO gpkg_data_column_constraints ("
   10048             :                     "constraint_name, constraint_type, value, "
   10049             :                     "min, %s, max, %s, "
   10050             :                     "description) VALUES ("
   10051             :                     "'_%q_domain_description', 'enum', '', NULL, NULL, NULL, "
   10052             :                     "NULL, %Q)",
   10053             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10054             :                     osDescription.c_str());
   10055           1 :                 CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
   10056           1 :                 sqlite3_free(pszSQL);
   10057             :             }
   10058          11 :             const auto &enumeration = poCodedDomain->GetEnumeration();
   10059          33 :             for (int i = 0; enumeration[i].pszCode != nullptr; ++i)
   10060             :             {
   10061          22 :                 char *pszSQL = sqlite3_mprintf(
   10062             :                     "INSERT INTO gpkg_data_column_constraints ("
   10063             :                     "constraint_name, constraint_type, value, "
   10064             :                     "min, %s, max, %s, "
   10065             :                     "description) VALUES ("
   10066             :                     "'%q', 'enum', '%q', NULL, NULL, NULL, NULL, %Q)",
   10067             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10068          22 :                     enumeration[i].pszCode, enumeration[i].pszValue);
   10069          22 :                 bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10070          22 :                 sqlite3_free(pszSQL);
   10071          22 :                 if (!ok)
   10072           0 :                     return false;
   10073             :             }
   10074          11 :             break;
   10075             :         }
   10076             : 
   10077           5 :         case OFDT_RANGE:
   10078             :         {
   10079             :             const auto poRangeDomain =
   10080           5 :                 cpl::down_cast<const OGRRangeFieldDomain *>(domain.get());
   10081           5 :             const auto eFieldType = poRangeDomain->GetFieldType();
   10082           5 :             if (eFieldType != OFTInteger && eFieldType != OFTInteger64 &&
   10083             :                 eFieldType != OFTReal)
   10084             :             {
   10085             :                 failureReason = "Only range domains of numeric type are "
   10086           0 :                                 "supported in GeoPackage";
   10087           0 :                 return false;
   10088             :             }
   10089             : 
   10090           5 :             double dfMin = -std::numeric_limits<double>::infinity();
   10091           5 :             double dfMax = std::numeric_limits<double>::infinity();
   10092           5 :             bool bMinIsInclusive = true;
   10093           5 :             const auto &sMin = poRangeDomain->GetMin(bMinIsInclusive);
   10094           5 :             bool bMaxIsInclusive = true;
   10095           5 :             const auto &sMax = poRangeDomain->GetMax(bMaxIsInclusive);
   10096           5 :             if (eFieldType == OFTInteger)
   10097             :             {
   10098           1 :                 if (!OGR_RawField_IsUnset(&sMin))
   10099           1 :                     dfMin = sMin.Integer;
   10100           1 :                 if (!OGR_RawField_IsUnset(&sMax))
   10101           1 :                     dfMax = sMax.Integer;
   10102             :             }
   10103           4 :             else if (eFieldType == OFTInteger64)
   10104             :             {
   10105           1 :                 if (!OGR_RawField_IsUnset(&sMin))
   10106           1 :                     dfMin = static_cast<double>(sMin.Integer64);
   10107           1 :                 if (!OGR_RawField_IsUnset(&sMax))
   10108           1 :                     dfMax = static_cast<double>(sMax.Integer64);
   10109             :             }
   10110             :             else /* if( eFieldType == OFTReal ) */
   10111             :             {
   10112           3 :                 if (!OGR_RawField_IsUnset(&sMin))
   10113           3 :                     dfMin = sMin.Real;
   10114           3 :                 if (!OGR_RawField_IsUnset(&sMax))
   10115           3 :                     dfMax = sMax.Real;
   10116             :             }
   10117             : 
   10118           5 :             sqlite3_stmt *hInsertStmt = nullptr;
   10119             :             const char *pszSQL =
   10120           5 :                 CPLSPrintf("INSERT INTO gpkg_data_column_constraints ("
   10121             :                            "constraint_name, constraint_type, value, "
   10122             :                            "min, %s, max, %s, "
   10123             :                            "description) VALUES ("
   10124             :                            "?, 'range', NULL, ?, ?, ?, ?, ?)",
   10125             :                            min_is_inclusive, max_is_inclusive);
   10126           5 :             if (SQLPrepareWithError(hDB, pszSQL, -1, &hInsertStmt, nullptr) !=
   10127             :                 SQLITE_OK)
   10128             :             {
   10129           0 :                 return false;
   10130             :             }
   10131           5 :             sqlite3_bind_text(hInsertStmt, 1, domainName.c_str(),
   10132           5 :                               static_cast<int>(domainName.size()),
   10133             :                               SQLITE_TRANSIENT);
   10134           5 :             sqlite3_bind_double(hInsertStmt, 2, dfMin);
   10135           5 :             sqlite3_bind_int(hInsertStmt, 3, bMinIsInclusive ? 1 : 0);
   10136           5 :             sqlite3_bind_double(hInsertStmt, 4, dfMax);
   10137           5 :             sqlite3_bind_int(hInsertStmt, 5, bMaxIsInclusive ? 1 : 0);
   10138           5 :             if (osDescription.empty())
   10139             :             {
   10140           3 :                 sqlite3_bind_null(hInsertStmt, 6);
   10141             :             }
   10142             :             else
   10143             :             {
   10144           2 :                 sqlite3_bind_text(hInsertStmt, 6, osDescription.c_str(),
   10145           2 :                                   static_cast<int>(osDescription.size()),
   10146             :                                   SQLITE_TRANSIENT);
   10147             :             }
   10148           5 :             const int sqlite_err = sqlite3_step(hInsertStmt);
   10149           5 :             sqlite3_finalize(hInsertStmt);
   10150           5 :             if (sqlite_err != SQLITE_OK && sqlite_err != SQLITE_DONE)
   10151             :             {
   10152           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10153             :                          "failed to execute insertion '%s': %s", pszSQL,
   10154             :                          sqlite3_errmsg(hDB));
   10155           0 :                 return false;
   10156             :             }
   10157             : 
   10158           5 :             break;
   10159             :         }
   10160             : 
   10161           1 :         case OFDT_GLOB:
   10162             :         {
   10163             :             const auto poGlobDomain =
   10164           1 :                 cpl::down_cast<const OGRGlobFieldDomain *>(domain.get());
   10165           2 :             char *pszSQL = sqlite3_mprintf(
   10166             :                 "INSERT INTO gpkg_data_column_constraints ("
   10167             :                 "constraint_name, constraint_type, value, "
   10168             :                 "min, %s, max, %s, "
   10169             :                 "description) VALUES ("
   10170             :                 "'%q', 'glob', '%q', NULL, NULL, NULL, NULL, %Q)",
   10171             :                 min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10172           1 :                 poGlobDomain->GetGlob().c_str(),
   10173           2 :                 osDescription.empty() ? nullptr : osDescription.c_str());
   10174           1 :             bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10175           1 :             sqlite3_free(pszSQL);
   10176           1 :             if (!ok)
   10177           0 :                 return false;
   10178             : 
   10179           1 :             break;
   10180             :         }
   10181             :     }
   10182             : 
   10183          17 :     m_oMapFieldDomains[domainName] = std::move(domain);
   10184          17 :     return true;
   10185             : }
   10186             : 
   10187             : /************************************************************************/
   10188             : /*                          AddRelationship()                           */
   10189             : /************************************************************************/
   10190             : 
   10191          24 : bool GDALGeoPackageDataset::AddRelationship(
   10192             :     std::unique_ptr<GDALRelationship> &&relationship,
   10193             :     std::string &failureReason)
   10194             : {
   10195          24 :     if (!GetUpdate())
   10196             :     {
   10197           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10198             :                  "AddRelationship() not supported on read-only dataset");
   10199           0 :         return false;
   10200             :     }
   10201             : 
   10202             :     const std::string osRelationshipName = GenerateNameForRelationship(
   10203          24 :         relationship->GetLeftTableName().c_str(),
   10204          24 :         relationship->GetRightTableName().c_str(),
   10205          96 :         relationship->GetRelatedTableType().c_str());
   10206             :     // sanity checks
   10207          24 :     if (GetRelationship(osRelationshipName) != nullptr)
   10208             :     {
   10209           1 :         failureReason = "A relationship of identical name already exists";
   10210           1 :         return false;
   10211             :     }
   10212             : 
   10213          23 :     if (!ValidateRelationship(relationship.get(), failureReason))
   10214             :     {
   10215          14 :         return false;
   10216             :     }
   10217             : 
   10218           9 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
   10219             :     {
   10220           0 :         return false;
   10221             :     }
   10222           9 :     if (!CreateRelationsTableIfNecessary())
   10223             :     {
   10224           0 :         failureReason = "Could not create gpkgext_relations table";
   10225           0 :         return false;
   10226             :     }
   10227           9 :     if (SQLGetInteger(GetDB(),
   10228             :                       "SELECT 1 FROM gpkg_extensions WHERE "
   10229             :                       "table_name = 'gpkgext_relations'",
   10230           9 :                       nullptr) != 1)
   10231             :     {
   10232           4 :         if (OGRERR_NONE !=
   10233           4 :             SQLCommand(
   10234             :                 GetDB(),
   10235             :                 "INSERT INTO gpkg_extensions "
   10236             :                 "(table_name,column_name,extension_name,definition,scope) "
   10237             :                 "VALUES ('gpkgext_relations', NULL, 'gpkg_related_tables', "
   10238             :                 "'http://www.geopackage.org/18-000.html', "
   10239             :                 "'read-write')"))
   10240             :         {
   10241             :             failureReason =
   10242           0 :                 "Could not create gpkg_extensions entry for gpkgext_relations";
   10243           0 :             return false;
   10244             :         }
   10245             :     }
   10246             : 
   10247           9 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10248           9 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10249           9 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10250           9 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10251             : 
   10252          18 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10253           9 :     if (osRelatedTableType.empty())
   10254             :     {
   10255           5 :         osRelatedTableType = "features";
   10256             :     }
   10257             : 
   10258             :     // generate mapping table if not set
   10259          18 :     CPLString osMappingTableName = relationship->GetMappingTableName();
   10260           9 :     if (osMappingTableName.empty())
   10261             :     {
   10262           3 :         int nIndex = 1;
   10263           3 :         osMappingTableName = osLeftTableName + "_" + osRightTableName;
   10264           3 :         while (FindLayerIndex(osMappingTableName.c_str()) >= 0)
   10265             :         {
   10266           0 :             nIndex += 1;
   10267             :             osMappingTableName.Printf("%s_%s_%d", osLeftTableName.c_str(),
   10268           0 :                                       osRightTableName.c_str(), nIndex);
   10269             :         }
   10270             : 
   10271             :         // determine whether base/related keys are unique
   10272           3 :         bool bBaseKeyIsUnique = false;
   10273             :         {
   10274             :             const std::set<std::string> uniqueBaseFieldsUC =
   10275             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10276           6 :                                                osLeftTableName.c_str());
   10277           6 :             if (uniqueBaseFieldsUC.find(
   10278           3 :                     CPLString(aosLeftTableFields[0]).toupper()) !=
   10279           6 :                 uniqueBaseFieldsUC.end())
   10280             :             {
   10281           2 :                 bBaseKeyIsUnique = true;
   10282             :             }
   10283             :         }
   10284           3 :         bool bRelatedKeyIsUnique = false;
   10285             :         {
   10286             :             const std::set<std::string> uniqueRelatedFieldsUC =
   10287             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10288           6 :                                                osRightTableName.c_str());
   10289           6 :             if (uniqueRelatedFieldsUC.find(
   10290           3 :                     CPLString(aosRightTableFields[0]).toupper()) !=
   10291           6 :                 uniqueRelatedFieldsUC.end())
   10292             :             {
   10293           2 :                 bRelatedKeyIsUnique = true;
   10294             :             }
   10295             :         }
   10296             : 
   10297             :         // create mapping table
   10298             : 
   10299           3 :         std::string osBaseIdDefinition = "base_id INTEGER";
   10300           3 :         if (bBaseKeyIsUnique)
   10301             :         {
   10302           2 :             char *pszSQL = sqlite3_mprintf(
   10303             :                 " CONSTRAINT 'fk_base_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10304             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10305             :                 "DEFERRED",
   10306             :                 osMappingTableName.c_str(), osLeftTableName.c_str(),
   10307           2 :                 aosLeftTableFields[0].c_str());
   10308           2 :             osBaseIdDefinition += pszSQL;
   10309           2 :             sqlite3_free(pszSQL);
   10310             :         }
   10311             : 
   10312           3 :         std::string osRelatedIdDefinition = "related_id INTEGER";
   10313           3 :         if (bRelatedKeyIsUnique)
   10314             :         {
   10315           2 :             char *pszSQL = sqlite3_mprintf(
   10316             :                 " CONSTRAINT 'fk_related_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10317             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10318             :                 "DEFERRED",
   10319             :                 osMappingTableName.c_str(), osRightTableName.c_str(),
   10320           2 :                 aosRightTableFields[0].c_str());
   10321           2 :             osRelatedIdDefinition += pszSQL;
   10322           2 :             sqlite3_free(pszSQL);
   10323             :         }
   10324             : 
   10325           3 :         char *pszSQL = sqlite3_mprintf("CREATE TABLE \"%w\" ("
   10326             :                                        "id INTEGER PRIMARY KEY AUTOINCREMENT, "
   10327             :                                        "%s, %s);",
   10328             :                                        osMappingTableName.c_str(),
   10329             :                                        osBaseIdDefinition.c_str(),
   10330             :                                        osRelatedIdDefinition.c_str());
   10331           3 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
   10332           3 :         sqlite3_free(pszSQL);
   10333           3 :         if (eErr != OGRERR_NONE)
   10334             :         {
   10335             :             failureReason =
   10336           0 :                 ("Could not create mapping table " + osMappingTableName)
   10337           0 :                     .c_str();
   10338           0 :             return false;
   10339             :         }
   10340             : 
   10341             :         /*
   10342             :          * Strictly speaking we should NOT be inserting the mapping table into gpkg_contents.
   10343             :          * The related tables extension explicitly states that the mapping table should only be
   10344             :          * in the gpkgext_relations table and not in gpkg_contents. (See also discussion at
   10345             :          * https://github.com/opengeospatial/geopackage/issues/679).
   10346             :          *
   10347             :          * However, if we don't insert the mapping table into gpkg_contents then it is no longer
   10348             :          * visible to some clients (eg ESRI software only allows opening tables that are present
   10349             :          * in gpkg_contents). So we'll do this anyway, for maximum compatibility and flexibility.
   10350             :          *
   10351             :          * More related discussion is at https://github.com/OSGeo/gdal/pull/9258
   10352             :          */
   10353           3 :         pszSQL = sqlite3_mprintf(
   10354             :             "INSERT INTO gpkg_contents "
   10355             :             "(table_name,data_type,identifier,description,last_change,srs_id) "
   10356             :             "VALUES "
   10357             :             "('%q','attributes','%q','Mapping table for relationship between "
   10358             :             "%q and %q',%s,0)",
   10359             :             osMappingTableName.c_str(), /*table_name*/
   10360             :             osMappingTableName.c_str(), /*identifier*/
   10361             :             osLeftTableName.c_str(),    /*description left table name*/
   10362             :             osRightTableName.c_str(),   /*description right table name*/
   10363           6 :             GDALGeoPackageDataset::GetCurrentDateEscapedSQL().c_str());
   10364             : 
   10365             :         // Note -- we explicitly ignore failures here, because hey, we aren't really
   10366             :         // supposed to be adding this table to gpkg_contents anyway!
   10367           3 :         (void)SQLCommand(hDB, pszSQL);
   10368           3 :         sqlite3_free(pszSQL);
   10369             : 
   10370           3 :         pszSQL = sqlite3_mprintf(
   10371             :             "CREATE INDEX \"idx_%w_base_id\" ON \"%w\" (base_id);",
   10372             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10373           3 :         eErr = SQLCommand(hDB, pszSQL);
   10374           3 :         sqlite3_free(pszSQL);
   10375           3 :         if (eErr != OGRERR_NONE)
   10376             :         {
   10377           0 :             failureReason = ("Could not create index for " +
   10378           0 :                              osMappingTableName + " (base_id)")
   10379           0 :                                 .c_str();
   10380           0 :             return false;
   10381             :         }
   10382             : 
   10383           3 :         pszSQL = sqlite3_mprintf(
   10384             :             "CREATE INDEX \"idx_%qw_related_id\" ON \"%w\" (related_id);",
   10385             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10386           3 :         eErr = SQLCommand(hDB, pszSQL);
   10387           3 :         sqlite3_free(pszSQL);
   10388           3 :         if (eErr != OGRERR_NONE)
   10389             :         {
   10390           0 :             failureReason = ("Could not create index for " +
   10391           0 :                              osMappingTableName + " (related_id)")
   10392           0 :                                 .c_str();
   10393           0 :             return false;
   10394             :         }
   10395             :     }
   10396             :     else
   10397             :     {
   10398             :         // validate mapping table structure
   10399           6 :         if (OGRGeoPackageTableLayer *poLayer =
   10400           6 :                 cpl::down_cast<OGRGeoPackageTableLayer *>(
   10401           6 :                     GetLayerByName(osMappingTableName)))
   10402             :         {
   10403           4 :             if (poLayer->GetLayerDefn()->GetFieldIndex("base_id") < 0)
   10404             :             {
   10405             :                 failureReason =
   10406           2 :                     ("Field base_id must exist in " + osMappingTableName)
   10407           1 :                         .c_str();
   10408           1 :                 return false;
   10409             :             }
   10410           3 :             if (poLayer->GetLayerDefn()->GetFieldIndex("related_id") < 0)
   10411             :             {
   10412             :                 failureReason =
   10413           2 :                     ("Field related_id must exist in " + osMappingTableName)
   10414           1 :                         .c_str();
   10415           1 :                 return false;
   10416             :             }
   10417             :         }
   10418             :         else
   10419             :         {
   10420             :             failureReason =
   10421           2 :                 ("Could not retrieve table " + osMappingTableName).c_str();
   10422           2 :             return false;
   10423             :         }
   10424             :     }
   10425             : 
   10426           5 :     char *pszSQL = sqlite3_mprintf(
   10427             :         "INSERT INTO gpkg_extensions "
   10428             :         "(table_name,column_name,extension_name,definition,scope) "
   10429             :         "VALUES ('%q', NULL, 'gpkg_related_tables', "
   10430             :         "'http://www.geopackage.org/18-000.html', "
   10431             :         "'read-write')",
   10432             :         osMappingTableName.c_str());
   10433           5 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10434           5 :     sqlite3_free(pszSQL);
   10435           5 :     if (eErr != OGRERR_NONE)
   10436             :     {
   10437           0 :         failureReason = ("Could not insert mapping table " +
   10438           0 :                          osMappingTableName + " into gpkg_extensions")
   10439           0 :                             .c_str();
   10440           0 :         return false;
   10441             :     }
   10442             : 
   10443          15 :     pszSQL = sqlite3_mprintf(
   10444             :         "INSERT INTO gpkgext_relations "
   10445             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10446             :         "primary_column,relation_name,mapping_table_name) "
   10447             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10448           5 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10449           5 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10450             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10451           5 :     eErr = SQLCommand(hDB, pszSQL);
   10452           5 :     sqlite3_free(pszSQL);
   10453           5 :     if (eErr != OGRERR_NONE)
   10454             :     {
   10455           0 :         failureReason = "Could not insert relationship into gpkgext_relations";
   10456           0 :         return false;
   10457             :     }
   10458             : 
   10459           5 :     ClearCachedRelationships();
   10460           5 :     LoadRelationships();
   10461           5 :     return true;
   10462             : }
   10463             : 
   10464             : /************************************************************************/
   10465             : /*                         DeleteRelationship()                         */
   10466             : /************************************************************************/
   10467             : 
   10468           4 : bool GDALGeoPackageDataset::DeleteRelationship(const std::string &name,
   10469             :                                                std::string &failureReason)
   10470             : {
   10471           4 :     if (eAccess != GA_Update)
   10472             :     {
   10473           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10474             :                  "DeleteRelationship() not supported on read-only dataset");
   10475           0 :         return false;
   10476             :     }
   10477             : 
   10478             :     // ensure relationships are up to date before we try to remove one
   10479           4 :     ClearCachedRelationships();
   10480           4 :     LoadRelationships();
   10481             : 
   10482           8 :     std::string osMappingTableName;
   10483             :     {
   10484           4 :         const GDALRelationship *poRelationship = GetRelationship(name);
   10485           4 :         if (poRelationship == nullptr)
   10486             :         {
   10487           1 :             failureReason = "Could not find relationship with name " + name;
   10488           1 :             return false;
   10489             :         }
   10490             : 
   10491           3 :         osMappingTableName = poRelationship->GetMappingTableName();
   10492             :     }
   10493             : 
   10494             :     // DeleteLayerCommon will delete existing relationship objects, so we can't
   10495             :     // refer to poRelationship or any of its members previously obtained here
   10496           3 :     if (DeleteLayerCommon(osMappingTableName.c_str()) != OGRERR_NONE)
   10497             :     {
   10498             :         failureReason =
   10499           0 :             "Could not remove mapping layer name " + osMappingTableName;
   10500             : 
   10501             :         // relationships may have been left in an inconsistent state -- reload
   10502             :         // them now
   10503           0 :         ClearCachedRelationships();
   10504           0 :         LoadRelationships();
   10505           0 :         return false;
   10506             :     }
   10507             : 
   10508           3 :     ClearCachedRelationships();
   10509           3 :     LoadRelationships();
   10510           3 :     return true;
   10511             : }
   10512             : 
   10513             : /************************************************************************/
   10514             : /*                        UpdateRelationship()                          */
   10515             : /************************************************************************/
   10516             : 
   10517           6 : bool GDALGeoPackageDataset::UpdateRelationship(
   10518             :     std::unique_ptr<GDALRelationship> &&relationship,
   10519             :     std::string &failureReason)
   10520             : {
   10521           6 :     if (eAccess != GA_Update)
   10522             :     {
   10523           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10524             :                  "UpdateRelationship() not supported on read-only dataset");
   10525           0 :         return false;
   10526             :     }
   10527             : 
   10528             :     // ensure relationships are up to date before we try to update one
   10529           6 :     ClearCachedRelationships();
   10530           6 :     LoadRelationships();
   10531             : 
   10532           6 :     const std::string &osRelationshipName = relationship->GetName();
   10533           6 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10534           6 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10535           6 :     const std::string &osMappingTableName = relationship->GetMappingTableName();
   10536           6 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10537           6 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10538             : 
   10539             :     // sanity checks
   10540             :     {
   10541             :         const GDALRelationship *poExistingRelationship =
   10542           6 :             GetRelationship(osRelationshipName);
   10543           6 :         if (poExistingRelationship == nullptr)
   10544             :         {
   10545             :             failureReason =
   10546           1 :                 "The relationship should already exist to be updated";
   10547           1 :             return false;
   10548             :         }
   10549             : 
   10550           5 :         if (!ValidateRelationship(relationship.get(), failureReason))
   10551             :         {
   10552           2 :             return false;
   10553             :         }
   10554             : 
   10555             :         // we don't permit changes to the participating tables
   10556           3 :         if (osLeftTableName != poExistingRelationship->GetLeftTableName())
   10557             :         {
   10558           0 :             failureReason = ("Cannot change base table from " +
   10559           0 :                              poExistingRelationship->GetLeftTableName() +
   10560           0 :                              " to " + osLeftTableName)
   10561           0 :                                 .c_str();
   10562           0 :             return false;
   10563             :         }
   10564           3 :         if (osRightTableName != poExistingRelationship->GetRightTableName())
   10565             :         {
   10566           0 :             failureReason = ("Cannot change related table from " +
   10567           0 :                              poExistingRelationship->GetRightTableName() +
   10568           0 :                              " to " + osRightTableName)
   10569           0 :                                 .c_str();
   10570           0 :             return false;
   10571             :         }
   10572           3 :         if (osMappingTableName != poExistingRelationship->GetMappingTableName())
   10573             :         {
   10574           0 :             failureReason = ("Cannot change mapping table from " +
   10575           0 :                              poExistingRelationship->GetMappingTableName() +
   10576           0 :                              " to " + osMappingTableName)
   10577           0 :                                 .c_str();
   10578           0 :             return false;
   10579             :         }
   10580             :     }
   10581             : 
   10582           6 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10583           3 :     if (osRelatedTableType.empty())
   10584             :     {
   10585           0 :         osRelatedTableType = "features";
   10586             :     }
   10587             : 
   10588           3 :     char *pszSQL = sqlite3_mprintf(
   10589             :         "DELETE FROM gpkgext_relations WHERE mapping_table_name='%q'",
   10590             :         osMappingTableName.c_str());
   10591           3 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10592           3 :     sqlite3_free(pszSQL);
   10593           3 :     if (eErr != OGRERR_NONE)
   10594             :     {
   10595             :         failureReason =
   10596           0 :             "Could not delete old relationship from gpkgext_relations";
   10597           0 :         return false;
   10598             :     }
   10599             : 
   10600           9 :     pszSQL = sqlite3_mprintf(
   10601             :         "INSERT INTO gpkgext_relations "
   10602             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10603             :         "primary_column,relation_name,mapping_table_name) "
   10604             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10605           3 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10606           3 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10607             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10608           3 :     eErr = SQLCommand(hDB, pszSQL);
   10609           3 :     sqlite3_free(pszSQL);
   10610           3 :     if (eErr != OGRERR_NONE)
   10611             :     {
   10612             :         failureReason =
   10613           0 :             "Could not insert updated relationship into gpkgext_relations";
   10614           0 :         return false;
   10615             :     }
   10616             : 
   10617           3 :     ClearCachedRelationships();
   10618           3 :     LoadRelationships();
   10619           3 :     return true;
   10620             : }
   10621             : 
   10622             : /************************************************************************/
   10623             : /*                    GetSqliteMasterContent()                          */
   10624             : /************************************************************************/
   10625             : 
   10626             : const std::vector<SQLSqliteMasterContent> &
   10627           2 : GDALGeoPackageDataset::GetSqliteMasterContent()
   10628             : {
   10629           2 :     if (m_aoSqliteMasterContent.empty())
   10630             :     {
   10631             :         auto oResultTable =
   10632           2 :             SQLQuery(hDB, "SELECT sql, type, tbl_name FROM sqlite_master");
   10633           1 :         if (oResultTable)
   10634             :         {
   10635          58 :             for (int rowCnt = 0; rowCnt < oResultTable->RowCount(); ++rowCnt)
   10636             :             {
   10637         114 :                 SQLSqliteMasterContent row;
   10638          57 :                 const char *pszSQL = oResultTable->GetValue(0, rowCnt);
   10639          57 :                 row.osSQL = pszSQL ? pszSQL : "";
   10640          57 :                 const char *pszType = oResultTable->GetValue(1, rowCnt);
   10641          57 :                 row.osType = pszType ? pszType : "";
   10642          57 :                 const char *pszTableName = oResultTable->GetValue(2, rowCnt);
   10643          57 :                 row.osTableName = pszTableName ? pszTableName : "";
   10644          57 :                 m_aoSqliteMasterContent.emplace_back(std::move(row));
   10645             :             }
   10646             :         }
   10647             :     }
   10648           2 :     return m_aoSqliteMasterContent;
   10649             : }

Generated by: LCOV version 1.14