LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/gpkg - ogrgeopackagedatasource.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 4012 4477 89.6 %
Date: 2025-08-01 13:10:27 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         803 : static OGRErr GDALGPKGImportFromEPSG(OGRSpatialReference *poSpatialRef,
     222             :                                      int nEPSGCode)
     223             : {
     224         803 :     CPLPushErrorHandler(CPLQuietErrorHandler);
     225         803 :     const OGRErr eErr = poSpatialRef->importFromEPSG(nEPSGCode);
     226         803 :     CPLPopErrorHandler();
     227         803 :     CPLErrorReset();
     228         803 :     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         119 :         OGRSpatialReference *poSpatialRef = new OGRSpatialReference();
     248         119 :         poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     249             : 
     250             :         // See corresponding tests in GDALGeoPackageDataset::GetSrsId
     251         119 :         if (iSrsId == 0)
     252             :         {
     253          29 :             poSpatialRef->SetGeogCS("Undefined geographic SRS", "unknown",
     254             :                                     "unknown", SRS_WGS84_SEMIMAJOR,
     255             :                                     SRS_WGS84_INVFLATTENING);
     256             :         }
     257          90 :         else if (iSrsId == -1)
     258             :         {
     259          90 :             poSpatialRef->SetLocalCS("Undefined Cartesian SRS");
     260          90 :             poSpatialRef->SetLinearUnits(SRS_UL_METER, 1.0);
     261             :         }
     262             : 
     263         119 :         m_oMapSrsIdToSrs[iSrsId] = poSpatialRef;
     264         119 :         poSpatialRef->Reference();
     265             :         return std::unique_ptr<OGRSpatialReference,
     266         119 :                                OGRSpatialReferenceReleaser>(poSpatialRef);
     267             :     }
     268             : 
     269        2002 :     CPLString oSQL;
     270        1001 :     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        1001 :                 m_bHasDefinition12_063 ? ", definition_12_063" : "",
     275        1001 :                 m_bHasEpochColumn ? ", epoch" : "", iSrsId);
     276             : 
     277        2002 :     auto oResult = SQLQuery(hDB, oSQL.c_str());
     278             : 
     279        1001 :     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         989 :     const char *pszName = oResult->GetValue(0, 0);
     306         989 :     if (pszName && EQUAL(pszName, "Undefined SRS"))
     307             :     {
     308         408 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     309         408 :         return nullptr;
     310             :     }
     311         581 :     const char *pszWkt = oResult->GetValue(1, 0);
     312         581 :     if (pszWkt == nullptr)
     313           0 :         return nullptr;
     314         581 :     const char *pszOrganization = oResult->GetValue(2, 0);
     315         581 :     const char *pszOrganizationCoordsysID = oResult->GetValue(3, 0);
     316             :     const char *pszWkt2 =
     317         581 :         m_bHasDefinition12_063 ? oResult->GetValue(4, 0) : nullptr;
     318         581 :     if (pszWkt2 && !EQUAL(pszWkt2, "undefined"))
     319          76 :         pszWkt = pszWkt2;
     320             :     const char *pszCoordinateEpoch =
     321         581 :         m_bHasEpochColumn ? oResult->GetValue(5, 0) : nullptr;
     322             :     const double dfCoordinateEpoch =
     323         581 :         pszCoordinateEpoch ? CPLAtof(pszCoordinateEpoch) : 0.0;
     324             : 
     325         581 :     OGRSpatialReference *poSpatialRef = new OGRSpatialReference();
     326         581 :     poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     327             :     // Try to import first from EPSG code, and then from WKT
     328         581 :     if (!(pszOrganization && pszOrganizationCoordsysID &&
     329         581 :           EQUAL(pszOrganization, "EPSG") &&
     330         561 :           (atoi(pszOrganizationCoordsysID) == iSrsId ||
     331           4 :            (dfCoordinateEpoch > 0 && strstr(pszWkt, "DYNAMIC[") == nullptr)) &&
     332         561 :           GDALGPKGImportFromEPSG(
     333        1162 :               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         581 :     poSpatialRef->StripTOWGS84IfKnownDatumAndAllowed();
     345         581 :     poSpatialRef->SetCoordinateEpoch(dfCoordinateEpoch);
     346         581 :     m_oMapSrsIdToSrs[iSrsId] = poSpatialRef;
     347         581 :     poSpatialRef->Reference();
     348             :     return std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>(
     349         581 :         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        4087 : CPLErr GDALGeoPackageDataset::Close()
     992             : {
     993        4087 :     CPLErr eErr = CE_None;
     994        4087 :     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        4241 :         for (int i = 0; i < nBands; i++)
    1012        1814 :             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        4087 :     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        3958 : static int GetOGRTableLimit()
    1138             : {
    1139        3958 :     return atoi(CPLGetConfigOption("OGR_TABLE_LIMIT", "10000"));
    1140             : }
    1141             : 
    1142             : /************************************************************************/
    1143             : /*                      GetNameTypeMapFromSQliteMaster()                */
    1144             : /************************************************************************/
    1145             : 
    1146             : const std::map<CPLString, CPLString> &
    1147        1229 : GDALGeoPackageDataset::GetNameTypeMapFromSQliteMaster()
    1148             : {
    1149        1229 :     if (!m_oMapNameToType.empty())
    1150         338 :         return m_oMapNameToType;
    1151             : 
    1152             :     CPLString osSQL(
    1153             :         "SELECT name, type FROM sqlite_master WHERE "
    1154             :         "type IN ('view', 'table') OR "
    1155        1782 :         "(name LIKE 'trigger_%_feature_count_%' AND type = 'trigger')");
    1156         891 :     const int nTableLimit = GetOGRTableLimit();
    1157         891 :     if (nTableLimit > 0)
    1158             :     {
    1159         891 :         osSQL += " LIMIT ";
    1160         891 :         osSQL += CPLSPrintf("%d", 1 + 3 * nTableLimit);
    1161             :     }
    1162             : 
    1163         891 :     auto oResult = SQLQuery(hDB, osSQL);
    1164         891 :     if (oResult)
    1165             :     {
    1166       14895 :         for (int i = 0; i < oResult->RowCount(); i++)
    1167             :         {
    1168       14004 :             const char *pszName = oResult->GetValue(0, i);
    1169       14004 :             const char *pszType = oResult->GetValue(1, i);
    1170       14004 :             m_oMapNameToType[CPLString(pszName).toupper()] = pszType;
    1171             :         }
    1172             :     }
    1173             : 
    1174         891 :     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         849 : GDALGeoPackageDataset::GetUnknownExtensionsTableSpecific()
    1193             : {
    1194         849 :     if (m_bMapTableToExtensionsBuilt)
    1195          89 :         return m_oMapTableToExtensions;
    1196         760 :     m_bMapTableToExtensionsBuilt = true;
    1197             : 
    1198         760 :     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        1440 :         ")");
    1221         720 :     const int nTableLimit = GetOGRTableLimit();
    1222         720 :     if (nTableLimit > 0)
    1223             :     {
    1224         720 :         osSQL += " LIMIT ";
    1225         720 :         osSQL += CPLSPrintf("%d", 1 + 10 * nTableLimit);
    1226             :     }
    1227             : 
    1228         720 :     auto oResult = SQLQuery(hDB, osSQL);
    1229         720 :     if (oResult)
    1230             :     {
    1231        1377 :         for (int i = 0; i < oResult->RowCount(); i++)
    1232             :         {
    1233         657 :             const char *pszTableName = oResult->GetValue(0, i);
    1234         657 :             const char *pszExtensionName = oResult->GetValue(1, i);
    1235         657 :             const char *pszDefinition = oResult->GetValue(2, i);
    1236         657 :             const char *pszScope = oResult->GetValue(3, i);
    1237         657 :             if (pszTableName && pszExtensionName && pszDefinition && pszScope)
    1238             :             {
    1239         657 :                 GPKGExtensionDesc oDesc;
    1240         657 :                 oDesc.osExtensionName = pszExtensionName;
    1241         657 :                 oDesc.osDefinition = pszDefinition;
    1242         657 :                 oDesc.osScope = pszScope;
    1243        1314 :                 m_oMapTableToExtensions[CPLString(pszTableName).toupper()]
    1244         657 :                     .push_back(std::move(oDesc));
    1245             :             }
    1246             :         }
    1247             :     }
    1248             : 
    1249         720 :     return m_oMapTableToExtensions;
    1250             : }
    1251             : 
    1252             : /************************************************************************/
    1253             : /*                           GetContents()                              */
    1254             : /************************************************************************/
    1255             : 
    1256             : const std::map<CPLString, GPKGContentsDesc> &
    1257         831 : GDALGeoPackageDataset::GetContents()
    1258             : {
    1259         831 :     if (m_bMapTableToContentsBuilt)
    1260          73 :         return m_oMapTableToContents;
    1261         758 :     m_bMapTableToContentsBuilt = true;
    1262             : 
    1263             :     CPLString osSQL("SELECT table_name, data_type, identifier, "
    1264             :                     "description, min_x, min_y, max_x, max_y "
    1265        1516 :                     "FROM gpkg_contents");
    1266         758 :     const int nTableLimit = GetOGRTableLimit();
    1267         758 :     if (nTableLimit > 0)
    1268             :     {
    1269         758 :         osSQL += " LIMIT ";
    1270         758 :         osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1271             :     }
    1272             : 
    1273         758 :     auto oResult = SQLQuery(hDB, osSQL);
    1274         758 :     if (oResult)
    1275             :     {
    1276        1634 :         for (int i = 0; i < oResult->RowCount(); i++)
    1277             :         {
    1278         876 :             const char *pszTableName = oResult->GetValue(0, i);
    1279         876 :             if (pszTableName == nullptr)
    1280           0 :                 continue;
    1281         876 :             const char *pszDataType = oResult->GetValue(1, i);
    1282         876 :             const char *pszIdentifier = oResult->GetValue(2, i);
    1283         876 :             const char *pszDescription = oResult->GetValue(3, i);
    1284         876 :             const char *pszMinX = oResult->GetValue(4, i);
    1285         876 :             const char *pszMinY = oResult->GetValue(5, i);
    1286         876 :             const char *pszMaxX = oResult->GetValue(6, i);
    1287         876 :             const char *pszMaxY = oResult->GetValue(7, i);
    1288         876 :             GPKGContentsDesc oDesc;
    1289         876 :             if (pszDataType)
    1290         876 :                 oDesc.osDataType = pszDataType;
    1291         876 :             if (pszIdentifier)
    1292         876 :                 oDesc.osIdentifier = pszIdentifier;
    1293         876 :             if (pszDescription)
    1294         875 :                 oDesc.osDescription = pszDescription;
    1295         876 :             if (pszMinX)
    1296         598 :                 oDesc.osMinX = pszMinX;
    1297         876 :             if (pszMinY)
    1298         598 :                 oDesc.osMinY = pszMinY;
    1299         876 :             if (pszMaxX)
    1300         598 :                 oDesc.osMaxX = pszMaxX;
    1301         876 :             if (pszMaxY)
    1302         598 :                 oDesc.osMaxY = pszMaxY;
    1303        1752 :             m_oMapTableToContents[CPLString(pszTableName).toupper()] =
    1304        1752 :                 std::move(oDesc);
    1305             :         }
    1306             :     }
    1307             : 
    1308         758 :     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         246 :         char **papszTokens = CSLTokenizeString2(poOpenInfo->pszFilename, ":",
    1330             :                                                 CSLT_HONOURSTRINGS);
    1331         246 :         int nCount = CSLCount(papszTokens);
    1332         246 :         if (nCount < 2)
    1333             :         {
    1334           0 :             CSLDestroy(papszTokens);
    1335           0 :             return FALSE;
    1336             :         }
    1337             : 
    1338         246 :         if (nCount <= 3)
    1339             :         {
    1340         244 :             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         246 :         if (nCount >= 3)
    1361          14 :             osSubdatasetTableName = papszTokens[nCount - 1];
    1362             : 
    1363         246 :         CSLDestroy(papszTokens);
    1364         246 :         VSILFILE *fp = VSIFOpenL(osFilename, "rb");
    1365         246 :         if (fp != nullptr)
    1366             :         {
    1367         246 :             VSIFReadL(abyHeaderLetMeHerePlease, 1, 100, fp);
    1368         246 :             VSIFCloseL(fp);
    1369             :         }
    1370         246 :         pabyHeader = abyHeaderLetMeHerePlease;
    1371             :     }
    1372         964 :     else if (poOpenInfo->pabyHeader &&
    1373         964 :              STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1374             :                          "SQLite format 3"))
    1375             :     {
    1376         957 :         m_bCallUndeclareFileNotToOpen = true;
    1377         957 :         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         964 :         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         859 :             VSIFCloseL(poOpenInfo->fpL);
    1442         859 :             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        1022 :         m_bHasGPKGGeometryColumns =
    1529        1022 :             SQLGetInteger(hDB,
    1530             :                           "SELECT 1 FROM sqlite_master WHERE "
    1531             :                           "name = 'gpkg_geometry_columns' AND "
    1532             :                           "type IN ('table', 'view')",
    1533        1022 :                           nullptr) == 1;
    1534        1022 :         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        1021 :             "  WHERE data_type IN ('aspatial', 'attributes') ";
    1562             : 
    1563        2042 :         const char *pszListAllTables = CSLFetchNameValueDef(
    1564        1021 :             poOpenInfo->papszOpenOptions, "LIST_ALL_TABLES", "AUTO");
    1565        1021 :         bool bHasASpatialOrAttributes = HasGDALAspatialExtension();
    1566        1021 :         if (!bHasASpatialOrAttributes)
    1567             :         {
    1568             :             auto oResultTable =
    1569             :                 SQLQuery(hDB, "SELECT * FROM gpkg_contents WHERE "
    1570        1020 :                               "data_type = 'attributes' LIMIT 1");
    1571        1020 :             bHasASpatialOrAttributes =
    1572        1020 :                 (oResultTable && oResultTable->RowCount() == 1);
    1573             :         }
    1574        1021 :         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        1021 :         if (EQUAL(pszListAllTables, "YES") ||
    1589        1020 :             (!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         962 :                 "gpkg_contents)";
    1606         962 :             if (bHasGPKGExtRelations)
    1607             :             {
    1608             :                 osSQL += " AND lower(name) NOT IN (SELECT "
    1609             :                          "lower(mapping_table_name) FROM "
    1610          13 :                          "gpkgext_relations)";
    1611             :             }
    1612             :         }
    1613        1021 :         const int nTableLimit = GetOGRTableLimit();
    1614        1021 :         if (nTableLimit > 0)
    1615             :         {
    1616        1021 :             osSQL += " LIMIT ";
    1617        1021 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1618             :         }
    1619             : 
    1620        1021 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1621        1021 :         if (!oResult)
    1622             :         {
    1623           0 :             return FALSE;
    1624             :         }
    1625             : 
    1626        1021 :         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        1021 :         if (oResult->RowCount() > 0)
    1637             :         {
    1638         905 :             bRet = TRUE;
    1639             : 
    1640         905 :             m_apoLayers.reserve(oResult->RowCount());
    1641             : 
    1642        1810 :             std::map<std::string, int> oMapTableRefCount;
    1643        4006 :             for (int i = 0; i < oResult->RowCount(); i++)
    1644             :             {
    1645        3101 :                 const char *pszTableName = oResult->GetValue(0, i);
    1646        3101 :                 if (pszTableName == nullptr)
    1647           0 :                     continue;
    1648        3101 :                 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        1810 :             std::set<std::string> oExistingLayers;
    1660        4006 :             for (int i = 0; i < oResult->RowCount(); i++)
    1661             :             {
    1662        3101 :                 const char *pszTableName = oResult->GetValue(0, i);
    1663        3101 :                 if (pszTableName == nullptr)
    1664           2 :                     continue;
    1665             :                 const bool bTableHasSeveralGeomColumns =
    1666        3101 :                     oMapTableRefCount[pszTableName] > 1;
    1667        3101 :                 bool bIsSpatial = CPL_TO_BOOL(oResult->GetValueAsInteger(2, i));
    1668        3101 :                 const char *pszGeomColName = oResult->GetValue(3, i);
    1669        3101 :                 const char *pszGeomType = oResult->GetValue(4, i);
    1670        3101 :                 const char *pszZ = oResult->GetValue(5, i);
    1671        3101 :                 const char *pszM = oResult->GetValue(6, i);
    1672             :                 bool bIsInGpkgContents =
    1673        3101 :                     CPL_TO_BOOL(oResult->GetValueAsInteger(11, i));
    1674        3101 :                 if (!bIsInGpkgContents)
    1675          44 :                     m_bNonSpatialTablesNonRegisteredInGpkgContentsFound = true;
    1676        3101 :                 const char *pszObjectType = oResult->GetValue(12, i);
    1677        3101 :                 if (pszObjectType == nullptr ||
    1678        3100 :                     !(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        6082 :                     pszGeomColName ? std::string(pszTableName) + " (" +
    1695             :                                          pszGeomColName + ')'
    1696        6200 :                                    : std::string(pszTableName);
    1697        3100 :                 if (cpl::contains(oExistingLayers, osLayerNameWithGeomColName))
    1698           1 :                     continue;
    1699        3099 :                 oExistingLayers.insert(osLayerNameWithGeomColName);
    1700             :                 const std::string osLayerName =
    1701             :                     bTableHasSeveralGeomColumns
    1702           3 :                         ? std::move(osLayerNameWithGeomColName)
    1703        6201 :                         : std::string(pszTableName);
    1704             :                 auto poLayer = std::make_unique<OGRGeoPackageTableLayer>(
    1705        6198 :                     this, osLayerName.c_str());
    1706        3099 :                 bool bHasZ = pszZ && atoi(pszZ) > 0;
    1707        3099 :                 bool bHasM = pszM && atoi(pszM) > 0;
    1708        3099 :                 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        3099 :                 poLayer->SetOpeningParameters(
    1716             :                     pszTableName, pszObjectType, bIsInGpkgContents, bIsSpatial,
    1717             :                     pszGeomColName, pszGeomType, bHasZ, bHasM);
    1718        3099 :                 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         273 :             const char *pszTableName = oResult->GetValue(0, 0);
    1774         273 :             const char *pszIdentifier = oResult->GetValue(1, 0);
    1775         273 :             const char *pszDescription = oResult->GetValue(2, 0);
    1776         273 :             const char *pszSRSId = oResult->GetValue(3, 0);
    1777         273 :             const char *pszMinX = oResult->GetValue(4, 0);
    1778         273 :             const char *pszMinY = oResult->GetValue(5, 0);
    1779         273 :             const char *pszMaxX = oResult->GetValue(6, 0);
    1780         273 :             const char *pszMaxY = oResult->GetValue(7, 0);
    1781         273 :             const char *pszTMSMinX = oResult->GetValue(8, 0);
    1782         273 :             const char *pszTMSMinY = oResult->GetValue(9, 0);
    1783         273 :             const char *pszTMSMaxX = oResult->GetValue(10, 0);
    1784         273 :             const char *pszTMSMaxY = oResult->GetValue(11, 0);
    1785         273 :             const char *pszDataType = oResult->GetValue(12, 0);
    1786         273 :             if (pszTableName && pszTMSMinX && pszTMSMinY && pszTMSMaxX &&
    1787             :                 pszTMSMaxY)
    1788             :             {
    1789         546 :                 bRet = OpenRaster(
    1790             :                     pszTableName, pszIdentifier, pszDescription,
    1791         273 :                     pszSRSId ? atoi(pszSRSId) : 0, CPLAtof(pszTMSMinX),
    1792             :                     CPLAtof(pszTMSMinY), CPLAtof(pszTMSMaxX),
    1793             :                     CPLAtof(pszTMSMaxY), pszMinX, pszMinY, pszMaxX, pszMaxY,
    1794         273 :                     EQUAL(pszDataType, "tiles"), poOpenInfo->papszOpenOptions);
    1795             :             }
    1796             :         }
    1797         294 :         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         357 : 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         357 :     m_osRasterTable = pszTableName;
    2285         357 :     m_dfTMSMinX = dfMinX;
    2286         357 :     m_dfTMSMaxY = dfMaxY;
    2287             : 
    2288             :     // Despite prior checking, the type might be Binary and
    2289             :     // SQLResultGetValue() not working properly on it
    2290         357 :     int nZoomLevel = atoi(oResult.GetValue(0, nIdxInResult));
    2291         357 :     if (nZoomLevel < 0 || nZoomLevel > 65536)
    2292             :     {
    2293           0 :         return false;
    2294             :     }
    2295         357 :     double dfPixelXSize = CPLAtof(oResult.GetValue(1, nIdxInResult));
    2296         357 :     double dfPixelYSize = CPLAtof(oResult.GetValue(2, nIdxInResult));
    2297         357 :     if (dfPixelXSize <= 0 || dfPixelYSize <= 0)
    2298             :     {
    2299           0 :         return false;
    2300             :     }
    2301         357 :     int nTileWidth = atoi(oResult.GetValue(3, nIdxInResult));
    2302         357 :     int nTileHeight = atoi(oResult.GetValue(4, nIdxInResult));
    2303         357 :     if (nTileWidth <= 0 || nTileWidth > 65536 || nTileHeight <= 0 ||
    2304             :         nTileHeight > 65536)
    2305             :     {
    2306           0 :         return false;
    2307             :     }
    2308             :     int nTileMatrixWidth = static_cast<int>(
    2309         714 :         std::min(static_cast<GIntBig>(INT_MAX),
    2310         357 :                  CPLAtoGIntBig(oResult.GetValue(5, nIdxInResult))));
    2311             :     int nTileMatrixHeight = static_cast<int>(
    2312         714 :         std::min(static_cast<GIntBig>(INT_MAX),
    2313         357 :                  CPLAtoGIntBig(oResult.GetValue(6, nIdxInResult))));
    2314         357 :     if (nTileMatrixWidth <= 0 || nTileMatrixHeight <= 0)
    2315             :     {
    2316           0 :         return false;
    2317             :     }
    2318             : 
    2319             :     /* Use content bounds in priority over tile_matrix_set bounds */
    2320         357 :     double dfGDALMinX = dfMinX;
    2321         357 :     double dfGDALMinY = dfMinY;
    2322         357 :     double dfGDALMaxX = dfMaxX;
    2323         357 :     double dfGDALMaxY = dfMaxY;
    2324             :     pszContentsMinX =
    2325         357 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINX", pszContentsMinX);
    2326             :     pszContentsMinY =
    2327         357 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINY", pszContentsMinY);
    2328             :     pszContentsMaxX =
    2329         357 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXX", pszContentsMaxX);
    2330             :     pszContentsMaxY =
    2331         357 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXY", pszContentsMaxY);
    2332         357 :     if (pszContentsMinX != nullptr && pszContentsMinY != nullptr &&
    2333         357 :         pszContentsMaxX != nullptr && pszContentsMaxY != nullptr)
    2334             :     {
    2335         713 :         if (CPLAtof(pszContentsMinX) < CPLAtof(pszContentsMaxX) &&
    2336         356 :             CPLAtof(pszContentsMinY) < CPLAtof(pszContentsMaxY))
    2337             :         {
    2338         356 :             dfGDALMinX = CPLAtof(pszContentsMinX);
    2339         356 :             dfGDALMinY = CPLAtof(pszContentsMinY);
    2340         356 :             dfGDALMaxX = CPLAtof(pszContentsMaxX);
    2341         356 :             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         357 :     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         357 :     int nBandCount = 0;
    2360             :     const char *pszBAND_COUNT =
    2361         357 :         CSLFetchNameValue(papszOpenOptionsIn, "BAND_COUNT");
    2362         357 :     if (poParentDS)
    2363             :     {
    2364          86 :         nBandCount = poParentDS->GetRasterCount();
    2365             :     }
    2366         271 :     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         206 :         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         137 :             GetMetadata("IMAGE_STRUCTURE");
    2387         137 :             nBandCount = m_nBandCountFromMetadata;
    2388         137 :             if (nBandCount == 1)
    2389          38 :                 m_eTF = GPKG_TF_PNG;
    2390             :         }
    2391         206 :         if (nBandCount == 1 && !m_osTFFromMetadata.empty())
    2392             :         {
    2393           2 :             m_eTF = GDALGPKGMBTilesGetTileFormat(m_osTFFromMetadata.c_str());
    2394             :         }
    2395         206 :         if (nBandCount <= 0 || nBandCount > 4)
    2396          85 :             nBandCount = 4;
    2397             :     }
    2398             : 
    2399         357 :     return InitRaster(poParentDS, pszTableName, nZoomLevel, nBandCount, dfMinX,
    2400             :                       dfMaxY, dfPixelXSize, dfPixelYSize, nTileWidth,
    2401             :                       nTileHeight, nTileMatrixWidth, nTileMatrixHeight,
    2402         357 :                       dfGDALMinX, dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    2403             : }
    2404             : 
    2405             : /************************************************************************/
    2406             : /*                      ComputeTileAndPixelShifts()                     */
    2407             : /************************************************************************/
    2408             : 
    2409         781 : bool GDALGeoPackageDataset::ComputeTileAndPixelShifts()
    2410             : {
    2411             :     int nTileWidth, nTileHeight;
    2412         781 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2413             : 
    2414             :     // Compute shift between GDAL origin and TileMatrixSet origin
    2415         781 :     const double dfShiftXPixels = (m_gt[0] - m_dfTMSMinX) / m_gt[1];
    2416         781 :     if (!(dfShiftXPixels / nTileWidth >= INT_MIN &&
    2417         778 :           dfShiftXPixels / nTileWidth < INT_MAX))
    2418             :     {
    2419           3 :         return false;
    2420             :     }
    2421         778 :     const int64_t nShiftXPixels =
    2422         778 :         static_cast<int64_t>(floor(0.5 + dfShiftXPixels));
    2423         778 :     m_nShiftXTiles = static_cast<int>(nShiftXPixels / nTileWidth);
    2424         778 :     if (nShiftXPixels < 0 && (nShiftXPixels % nTileWidth) != 0)
    2425          11 :         m_nShiftXTiles--;
    2426         778 :     m_nShiftXPixelsMod =
    2427         778 :         (static_cast<int>(nShiftXPixels % nTileWidth) + nTileWidth) %
    2428             :         nTileWidth;
    2429             : 
    2430         778 :     const double dfShiftYPixels = (m_gt[3] - m_dfTMSMaxY) / m_gt[5];
    2431         778 :     if (!(dfShiftYPixels / nTileHeight >= INT_MIN &&
    2432         778 :           dfShiftYPixels / nTileHeight < INT_MAX))
    2433             :     {
    2434           1 :         return false;
    2435             :     }
    2436         777 :     const int64_t nShiftYPixels =
    2437         777 :         static_cast<int64_t>(floor(0.5 + dfShiftYPixels));
    2438         777 :     m_nShiftYTiles = static_cast<int>(nShiftYPixels / nTileHeight);
    2439         777 :     if (nShiftYPixels < 0 && (nShiftYPixels % nTileHeight) != 0)
    2440          11 :         m_nShiftYTiles--;
    2441         777 :     m_nShiftYPixelsMod =
    2442         777 :         (static_cast<int>(nShiftYPixels % nTileHeight) + nTileHeight) %
    2443             :         nTileHeight;
    2444         777 :     return true;
    2445             : }
    2446             : 
    2447             : /************************************************************************/
    2448             : /*                            AllocCachedTiles()                        */
    2449             : /************************************************************************/
    2450             : 
    2451         777 : bool GDALGeoPackageDataset::AllocCachedTiles()
    2452             : {
    2453             :     int nTileWidth, nTileHeight;
    2454         777 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2455             : 
    2456             :     // We currently need 4 caches because of
    2457             :     // GDALGPKGMBTilesLikePseudoDataset::ReadTile(int nRow, int nCol)
    2458         777 :     const int nCacheCount = 4;
    2459             :     /*
    2460             :             (m_nShiftXPixelsMod != 0 || m_nShiftYPixelsMod != 0) ? 4 :
    2461             :             (GetUpdate() && m_eDT == GDT_Byte) ? 2 : 1;
    2462             :     */
    2463         777 :     m_pabyCachedTiles = static_cast<GByte *>(VSI_MALLOC3_VERBOSE(
    2464             :         cpl::fits_on<int>(nCacheCount * (m_eDT == GDT_Byte ? 4 : 1) *
    2465             :                           m_nDTSize),
    2466             :         nTileWidth, nTileHeight));
    2467         777 :     if (m_pabyCachedTiles == nullptr)
    2468             :     {
    2469           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Too big tiles: %d x %d",
    2470             :                  nTileWidth, nTileHeight);
    2471           0 :         return false;
    2472             :     }
    2473             : 
    2474         777 :     return true;
    2475             : }
    2476             : 
    2477             : /************************************************************************/
    2478             : /*                         InitRaster()                                 */
    2479             : /************************************************************************/
    2480             : 
    2481         596 : bool GDALGeoPackageDataset::InitRaster(
    2482             :     GDALGeoPackageDataset *poParentDS, const char *pszTableName, int nZoomLevel,
    2483             :     int nBandCount, double dfTMSMinX, double dfTMSMaxY, double dfPixelXSize,
    2484             :     double dfPixelYSize, int nTileWidth, int nTileHeight, int nTileMatrixWidth,
    2485             :     int nTileMatrixHeight, double dfGDALMinX, double dfGDALMinY,
    2486             :     double dfGDALMaxX, double dfGDALMaxY)
    2487             : {
    2488         596 :     m_osRasterTable = pszTableName;
    2489         596 :     m_dfTMSMinX = dfTMSMinX;
    2490         596 :     m_dfTMSMaxY = dfTMSMaxY;
    2491         596 :     m_nZoomLevel = nZoomLevel;
    2492         596 :     m_nTileMatrixWidth = nTileMatrixWidth;
    2493         596 :     m_nTileMatrixHeight = nTileMatrixHeight;
    2494             : 
    2495         596 :     m_bGeoTransformValid = true;
    2496         596 :     m_gt[0] = dfGDALMinX;
    2497         596 :     m_gt[1] = dfPixelXSize;
    2498         596 :     m_gt[3] = dfGDALMaxY;
    2499         596 :     m_gt[5] = -dfPixelYSize;
    2500         596 :     double dfRasterXSize = 0.5 + (dfGDALMaxX - dfGDALMinX) / dfPixelXSize;
    2501         596 :     double dfRasterYSize = 0.5 + (dfGDALMaxY - dfGDALMinY) / dfPixelYSize;
    2502         596 :     if (dfRasterXSize > INT_MAX || dfRasterYSize > INT_MAX)
    2503             :     {
    2504           0 :         CPLError(CE_Failure, CPLE_NotSupported, "Too big raster: %f x %f",
    2505             :                  dfRasterXSize, dfRasterYSize);
    2506           0 :         return false;
    2507             :     }
    2508         596 :     nRasterXSize = std::max(1, static_cast<int>(dfRasterXSize));
    2509         596 :     nRasterYSize = std::max(1, static_cast<int>(dfRasterYSize));
    2510             : 
    2511         596 :     if (poParentDS)
    2512             :     {
    2513         325 :         m_poParentDS = poParentDS;
    2514         325 :         eAccess = poParentDS->eAccess;
    2515         325 :         hDB = poParentDS->hDB;
    2516         325 :         m_eTF = poParentDS->m_eTF;
    2517         325 :         m_eDT = poParentDS->m_eDT;
    2518         325 :         m_nDTSize = poParentDS->m_nDTSize;
    2519         325 :         m_dfScale = poParentDS->m_dfScale;
    2520         325 :         m_dfOffset = poParentDS->m_dfOffset;
    2521         325 :         m_dfPrecision = poParentDS->m_dfPrecision;
    2522         325 :         m_usGPKGNull = poParentDS->m_usGPKGNull;
    2523         325 :         m_nQuality = poParentDS->m_nQuality;
    2524         325 :         m_nZLevel = poParentDS->m_nZLevel;
    2525         325 :         m_bDither = poParentDS->m_bDither;
    2526             :         /*m_nSRID = poParentDS->m_nSRID;*/
    2527         325 :         m_osWHERE = poParentDS->m_osWHERE;
    2528         325 :         SetDescription(CPLSPrintf("%s - zoom_level=%d",
    2529         325 :                                   poParentDS->GetDescription(), m_nZoomLevel));
    2530             :     }
    2531             : 
    2532        2089 :     for (int i = 1; i <= nBandCount; i++)
    2533             :     {
    2534             :         auto poNewBand = std::make_unique<GDALGeoPackageRasterBand>(
    2535        1493 :             this, nTileWidth, nTileHeight);
    2536        1493 :         if (poParentDS)
    2537             :         {
    2538         761 :             int bHasNoData = FALSE;
    2539             :             double dfNoDataValue =
    2540         761 :                 poParentDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    2541         761 :             if (bHasNoData)
    2542          24 :                 poNewBand->SetNoDataValueInternal(dfNoDataValue);
    2543             :         }
    2544             : 
    2545        1493 :         if (nBandCount == 1 && m_poCTFromMetadata)
    2546             :         {
    2547           3 :             poNewBand->AssignColorTable(m_poCTFromMetadata.get());
    2548             :         }
    2549        1493 :         if (!m_osNodataValueFromMetadata.empty())
    2550             :         {
    2551           8 :             poNewBand->SetNoDataValueInternal(
    2552             :                 CPLAtof(m_osNodataValueFromMetadata.c_str()));
    2553             :         }
    2554             : 
    2555        1493 :         SetBand(i, std::move(poNewBand));
    2556             :     }
    2557             : 
    2558         596 :     if (!ComputeTileAndPixelShifts())
    2559             :     {
    2560           3 :         CPLError(CE_Failure, CPLE_AppDefined,
    2561             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    2562           3 :         return false;
    2563             :     }
    2564             : 
    2565         593 :     GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    2566         593 :     GDALPamDataset::SetMetadataItem("ZOOM_LEVEL",
    2567             :                                     CPLSPrintf("%d", m_nZoomLevel));
    2568             : 
    2569         593 :     return AllocCachedTiles();
    2570             : }
    2571             : 
    2572             : /************************************************************************/
    2573             : /*                 GDALGPKGMBTilesGetTileFormat()                       */
    2574             : /************************************************************************/
    2575             : 
    2576          80 : GPKGTileFormat GDALGPKGMBTilesGetTileFormat(const char *pszTF)
    2577             : {
    2578          80 :     GPKGTileFormat eTF = GPKG_TF_PNG_JPEG;
    2579          80 :     if (pszTF)
    2580             :     {
    2581          80 :         if (EQUAL(pszTF, "PNG_JPEG") || EQUAL(pszTF, "AUTO"))
    2582           1 :             eTF = GPKG_TF_PNG_JPEG;
    2583          79 :         else if (EQUAL(pszTF, "PNG"))
    2584          46 :             eTF = GPKG_TF_PNG;
    2585          33 :         else if (EQUAL(pszTF, "PNG8"))
    2586           6 :             eTF = GPKG_TF_PNG8;
    2587          27 :         else if (EQUAL(pszTF, "JPEG"))
    2588          14 :             eTF = GPKG_TF_JPEG;
    2589          13 :         else if (EQUAL(pszTF, "WEBP"))
    2590          13 :             eTF = GPKG_TF_WEBP;
    2591             :         else
    2592             :         {
    2593           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2594             :                      "Unsuppoted value for TILE_FORMAT: %s", pszTF);
    2595             :         }
    2596             :     }
    2597          80 :     return eTF;
    2598             : }
    2599             : 
    2600          28 : const char *GDALMBTilesGetTileFormatName(GPKGTileFormat eTF)
    2601             : {
    2602          28 :     switch (eTF)
    2603             :     {
    2604          26 :         case GPKG_TF_PNG:
    2605             :         case GPKG_TF_PNG8:
    2606          26 :             return "png";
    2607           1 :         case GPKG_TF_JPEG:
    2608           1 :             return "jpg";
    2609           1 :         case GPKG_TF_WEBP:
    2610           1 :             return "webp";
    2611           0 :         default:
    2612           0 :             break;
    2613             :     }
    2614           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2615             :              "Unsuppoted value for TILE_FORMAT: %d", static_cast<int>(eTF));
    2616           0 :     return nullptr;
    2617             : }
    2618             : 
    2619             : /************************************************************************/
    2620             : /*                         OpenRaster()                                 */
    2621             : /************************************************************************/
    2622             : 
    2623         273 : bool GDALGeoPackageDataset::OpenRaster(
    2624             :     const char *pszTableName, const char *pszIdentifier,
    2625             :     const char *pszDescription, int nSRSId, double dfMinX, double dfMinY,
    2626             :     double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2627             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2628             :     const char *pszContentsMaxY, bool bIsTiles, char **papszOpenOptionsIn)
    2629             : {
    2630         273 :     if (dfMinX >= dfMaxX || dfMinY >= dfMaxY)
    2631           0 :         return false;
    2632             : 
    2633             :     // Config option just for debug, and for example force set to NaN
    2634             :     // which is not supported
    2635         546 :     CPLString osDataNull = CPLGetConfigOption("GPKG_NODATA", "");
    2636         546 :     CPLString osUom;
    2637         546 :     CPLString osFieldName;
    2638         546 :     CPLString osGridCellEncoding;
    2639         273 :     if (!bIsTiles)
    2640             :     {
    2641          65 :         char *pszSQL = sqlite3_mprintf(
    2642             :             "SELECT datatype, scale, offset, data_null, precision FROM "
    2643             :             "gpkg_2d_gridded_coverage_ancillary "
    2644             :             "WHERE tile_matrix_set_name = '%q' "
    2645             :             "AND datatype IN ('integer', 'float')"
    2646             :             "AND (scale > 0 OR scale IS NULL)",
    2647             :             pszTableName);
    2648          65 :         auto oResult = SQLQuery(hDB, pszSQL);
    2649          65 :         sqlite3_free(pszSQL);
    2650          65 :         if (!oResult || oResult->RowCount() == 0)
    2651             :         {
    2652           0 :             return false;
    2653             :         }
    2654          65 :         const char *pszDataType = oResult->GetValue(0, 0);
    2655          65 :         const char *pszScale = oResult->GetValue(1, 0);
    2656          65 :         const char *pszOffset = oResult->GetValue(2, 0);
    2657          65 :         const char *pszDataNull = oResult->GetValue(3, 0);
    2658          65 :         const char *pszPrecision = oResult->GetValue(4, 0);
    2659          65 :         if (pszDataNull)
    2660          23 :             osDataNull = pszDataNull;
    2661          65 :         if (EQUAL(pszDataType, "float"))
    2662             :         {
    2663           6 :             SetDataType(GDT_Float32);
    2664           6 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    2665             :         }
    2666             :         else
    2667             :         {
    2668          59 :             SetDataType(GDT_Float32);
    2669          59 :             m_eTF = GPKG_TF_PNG_16BIT;
    2670          59 :             const double dfScale = pszScale ? CPLAtof(pszScale) : 1.0;
    2671          59 :             const double dfOffset = pszOffset ? CPLAtof(pszOffset) : 0.0;
    2672          59 :             if (dfScale == 1.0)
    2673             :             {
    2674          59 :                 if (dfOffset == 0.0)
    2675             :                 {
    2676          24 :                     SetDataType(GDT_UInt16);
    2677             :                 }
    2678          35 :                 else if (dfOffset == -32768.0)
    2679             :                 {
    2680          35 :                     SetDataType(GDT_Int16);
    2681             :                 }
    2682             :                 // coverity[tainted_data]
    2683           0 :                 else if (dfOffset == -32767.0 && !osDataNull.empty() &&
    2684           0 :                          CPLAtof(osDataNull) == 65535.0)
    2685             :                 // Given that we will map the nodata value to -32768
    2686             :                 {
    2687           0 :                     SetDataType(GDT_Int16);
    2688             :                 }
    2689             :             }
    2690             : 
    2691             :             // Check that the tile offset and scales are compatible of a
    2692             :             // final integer result.
    2693          59 :             if (m_eDT != GDT_Float32)
    2694             :             {
    2695             :                 // coverity[tainted_data]
    2696          59 :                 if (dfScale == 1.0 && dfOffset == -32768.0 &&
    2697         118 :                     !osDataNull.empty() && CPLAtof(osDataNull) == 65535.0)
    2698             :                 {
    2699             :                     // Given that we will map the nodata value to -32768
    2700           9 :                     pszSQL = sqlite3_mprintf(
    2701             :                         "SELECT 1 FROM "
    2702             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2703             :                         "tpudt_name = '%q' "
    2704             :                         "AND NOT ((offset = 0.0 or offset = 1.0) "
    2705             :                         "AND scale = 1.0) "
    2706             :                         "LIMIT 1",
    2707             :                         pszTableName);
    2708             :                 }
    2709             :                 else
    2710             :                 {
    2711          50 :                     pszSQL = sqlite3_mprintf(
    2712             :                         "SELECT 1 FROM "
    2713             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2714             :                         "tpudt_name = '%q' "
    2715             :                         "AND NOT (offset = 0.0 AND scale = 1.0) LIMIT 1",
    2716             :                         pszTableName);
    2717             :                 }
    2718          59 :                 sqlite3_stmt *hSQLStmt = nullptr;
    2719             :                 int rc =
    2720          59 :                     SQLPrepareWithError(hDB, pszSQL, -1, &hSQLStmt, nullptr);
    2721             : 
    2722          59 :                 if (rc == SQLITE_OK)
    2723             :                 {
    2724          59 :                     if (sqlite3_step(hSQLStmt) == SQLITE_ROW)
    2725             :                     {
    2726           8 :                         SetDataType(GDT_Float32);
    2727             :                     }
    2728          59 :                     sqlite3_finalize(hSQLStmt);
    2729             :                 }
    2730          59 :                 sqlite3_free(pszSQL);
    2731             :             }
    2732             : 
    2733          59 :             SetGlobalOffsetScale(dfOffset, dfScale);
    2734             :         }
    2735          65 :         if (pszPrecision)
    2736          65 :             m_dfPrecision = CPLAtof(pszPrecision);
    2737             : 
    2738             :         // Request those columns in a separate query, so as to keep
    2739             :         // compatibility with pre OGC 17-066r1 databases
    2740             :         pszSQL =
    2741          65 :             sqlite3_mprintf("SELECT uom, field_name, grid_cell_encoding FROM "
    2742             :                             "gpkg_2d_gridded_coverage_ancillary "
    2743             :                             "WHERE tile_matrix_set_name = '%q'",
    2744             :                             pszTableName);
    2745          65 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    2746          65 :         oResult = SQLQuery(hDB, pszSQL);
    2747          65 :         CPLPopErrorHandler();
    2748          65 :         sqlite3_free(pszSQL);
    2749          65 :         if (oResult && oResult->RowCount() == 1)
    2750             :         {
    2751          64 :             const char *pszUom = oResult->GetValue(0, 0);
    2752          64 :             if (pszUom)
    2753           2 :                 osUom = pszUom;
    2754          64 :             const char *pszFieldName = oResult->GetValue(1, 0);
    2755          64 :             if (pszFieldName)
    2756          64 :                 osFieldName = pszFieldName;
    2757          64 :             const char *pszGridCellEncoding = oResult->GetValue(2, 0);
    2758          64 :             if (pszGridCellEncoding)
    2759          64 :                 osGridCellEncoding = pszGridCellEncoding;
    2760             :         }
    2761             :     }
    2762             : 
    2763         273 :     m_bRecordInsertedInGPKGContent = true;
    2764         273 :     m_nSRID = nSRSId;
    2765             : 
    2766         545 :     if (auto poSRS = GetSpatialRef(nSRSId))
    2767             :     {
    2768         272 :         m_oSRS = *(poSRS.get());
    2769             :     }
    2770             : 
    2771             :     /* Various sanity checks added in the SELECT */
    2772         273 :     char *pszQuotedTableName = sqlite3_mprintf("'%q'", pszTableName);
    2773         546 :     CPLString osQuotedTableName(pszQuotedTableName);
    2774         273 :     sqlite3_free(pszQuotedTableName);
    2775         273 :     char *pszSQL = sqlite3_mprintf(
    2776             :         "SELECT zoom_level, pixel_x_size, pixel_y_size, tile_width, "
    2777             :         "tile_height, matrix_width, matrix_height "
    2778             :         "FROM gpkg_tile_matrix tm "
    2779             :         "WHERE table_name = %s "
    2780             :         // INT_MAX would be the theoretical maximum value to avoid
    2781             :         // overflows, but that's already a insane value.
    2782             :         "AND zoom_level >= 0 AND zoom_level <= 65536 "
    2783             :         "AND pixel_x_size > 0 AND pixel_y_size > 0 "
    2784             :         "AND tile_width >= 1 AND tile_width <= 65536 "
    2785             :         "AND tile_height >= 1 AND tile_height <= 65536 "
    2786             :         "AND matrix_width >= 1 AND matrix_height >= 1",
    2787             :         osQuotedTableName.c_str());
    2788         546 :     CPLString osSQL(pszSQL);
    2789             :     const char *pszZoomLevel =
    2790         273 :         CSLFetchNameValue(papszOpenOptionsIn, "ZOOM_LEVEL");
    2791         273 :     if (pszZoomLevel)
    2792             :     {
    2793           5 :         if (GetUpdate())
    2794           1 :             osSQL += CPLSPrintf(" AND zoom_level <= %d", atoi(pszZoomLevel));
    2795             :         else
    2796             :         {
    2797             :             osSQL += CPLSPrintf(
    2798             :                 " AND (zoom_level = %d OR (zoom_level < %d AND EXISTS(SELECT 1 "
    2799             :                 "FROM %s WHERE zoom_level = tm.zoom_level LIMIT 1)))",
    2800             :                 atoi(pszZoomLevel), atoi(pszZoomLevel),
    2801           4 :                 osQuotedTableName.c_str());
    2802             :         }
    2803             :     }
    2804             :     // In read-only mode, only lists non empty zoom levels
    2805         268 :     else if (!GetUpdate())
    2806             :     {
    2807             :         osSQL += CPLSPrintf(" AND EXISTS(SELECT 1 FROM %s WHERE zoom_level = "
    2808             :                             "tm.zoom_level LIMIT 1)",
    2809         214 :                             osQuotedTableName.c_str());
    2810             :     }
    2811             :     else  // if( pszZoomLevel == nullptr )
    2812             :     {
    2813             :         osSQL +=
    2814             :             CPLSPrintf(" AND zoom_level <= (SELECT MAX(zoom_level) FROM %s)",
    2815          54 :                        osQuotedTableName.c_str());
    2816             :     }
    2817         273 :     osSQL += " ORDER BY zoom_level DESC";
    2818             :     // To avoid denial of service.
    2819         273 :     osSQL += " LIMIT 100";
    2820             : 
    2821         546 :     auto oResult = SQLQuery(hDB, osSQL.c_str());
    2822         273 :     if (!oResult || oResult->RowCount() == 0)
    2823             :     {
    2824         114 :         if (oResult && oResult->RowCount() == 0 && pszContentsMinX != nullptr &&
    2825         114 :             pszContentsMinY != nullptr && pszContentsMaxX != nullptr &&
    2826             :             pszContentsMaxY != nullptr)
    2827             :         {
    2828          56 :             osSQL = pszSQL;
    2829          56 :             osSQL += " ORDER BY zoom_level DESC";
    2830          56 :             if (!GetUpdate())
    2831          30 :                 osSQL += " LIMIT 1";
    2832          56 :             oResult = SQLQuery(hDB, osSQL.c_str());
    2833             :         }
    2834          57 :         if (!oResult || oResult->RowCount() == 0)
    2835             :         {
    2836           1 :             if (oResult && pszZoomLevel != nullptr)
    2837             :             {
    2838           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2839             :                          "ZOOM_LEVEL is probably not valid w.r.t tile "
    2840             :                          "table content");
    2841             :             }
    2842           1 :             sqlite3_free(pszSQL);
    2843           1 :             return false;
    2844             :         }
    2845             :     }
    2846         272 :     sqlite3_free(pszSQL);
    2847             : 
    2848             :     // If USE_TILE_EXTENT=YES, then query the tile table to find which tiles
    2849             :     // actually exist.
    2850             : 
    2851             :     // CAUTION: Do not move those variables inside inner scope !
    2852         544 :     CPLString osContentsMinX, osContentsMinY, osContentsMaxX, osContentsMaxY;
    2853             : 
    2854         272 :     if (CPLTestBool(
    2855             :             CSLFetchNameValueDef(papszOpenOptionsIn, "USE_TILE_EXTENT", "NO")))
    2856             :     {
    2857          13 :         pszSQL = sqlite3_mprintf(
    2858             :             "SELECT MIN(tile_column), MIN(tile_row), MAX(tile_column), "
    2859             :             "MAX(tile_row) FROM \"%w\" WHERE zoom_level = %d",
    2860             :             pszTableName, atoi(oResult->GetValue(0, 0)));
    2861          13 :         auto oResult2 = SQLQuery(hDB, pszSQL);
    2862          13 :         sqlite3_free(pszSQL);
    2863          26 :         if (!oResult2 || oResult2->RowCount() == 0 ||
    2864             :             // Can happen if table is empty
    2865          38 :             oResult2->GetValue(0, 0) == nullptr ||
    2866             :             // Can happen if table has no NOT NULL constraint on tile_row
    2867             :             // and that all tile_row are NULL
    2868          12 :             oResult2->GetValue(1, 0) == nullptr)
    2869             :         {
    2870           1 :             return false;
    2871             :         }
    2872          12 :         const double dfPixelXSize = CPLAtof(oResult->GetValue(1, 0));
    2873          12 :         const double dfPixelYSize = CPLAtof(oResult->GetValue(2, 0));
    2874          12 :         const int nTileWidth = atoi(oResult->GetValue(3, 0));
    2875          12 :         const int nTileHeight = atoi(oResult->GetValue(4, 0));
    2876             :         osContentsMinX =
    2877          24 :             CPLSPrintf("%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2878          12 :                                              atoi(oResult2->GetValue(0, 0)));
    2879             :         osContentsMaxY =
    2880          24 :             CPLSPrintf("%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2881          12 :                                              atoi(oResult2->GetValue(1, 0)));
    2882             :         osContentsMaxX = CPLSPrintf(
    2883          24 :             "%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2884          12 :                                   (1 + atoi(oResult2->GetValue(2, 0))));
    2885             :         osContentsMinY = CPLSPrintf(
    2886          24 :             "%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2887          12 :                                   (1 + atoi(oResult2->GetValue(3, 0))));
    2888          12 :         pszContentsMinX = osContentsMinX.c_str();
    2889          12 :         pszContentsMinY = osContentsMinY.c_str();
    2890          12 :         pszContentsMaxX = osContentsMaxX.c_str();
    2891          12 :         pszContentsMaxY = osContentsMaxY.c_str();
    2892             :     }
    2893             : 
    2894         271 :     if (!InitRaster(nullptr, pszTableName, dfMinX, dfMinY, dfMaxX, dfMaxY,
    2895             :                     pszContentsMinX, pszContentsMinY, pszContentsMaxX,
    2896         271 :                     pszContentsMaxY, papszOpenOptionsIn, *oResult, 0))
    2897             :     {
    2898           3 :         return false;
    2899             :     }
    2900             : 
    2901         268 :     auto poBand = cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(1));
    2902         268 :     if (!osDataNull.empty())
    2903             :     {
    2904          23 :         double dfGPKGNoDataValue = CPLAtof(osDataNull);
    2905          23 :         if (m_eTF == GPKG_TF_PNG_16BIT)
    2906             :         {
    2907          21 :             if (dfGPKGNoDataValue < 0 || dfGPKGNoDataValue > 65535 ||
    2908          21 :                 static_cast<int>(dfGPKGNoDataValue) != dfGPKGNoDataValue)
    2909             :             {
    2910           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2911             :                          "data_null = %.17g is invalid for integer data_type",
    2912             :                          dfGPKGNoDataValue);
    2913             :             }
    2914             :             else
    2915             :             {
    2916          21 :                 m_usGPKGNull = static_cast<GUInt16>(dfGPKGNoDataValue);
    2917          21 :                 if (m_eDT == GDT_Int16 && m_usGPKGNull > 32767)
    2918           9 :                     dfGPKGNoDataValue = -32768.0;
    2919          12 :                 else if (m_eDT == GDT_Float32)
    2920             :                 {
    2921             :                     // Pick a value that is unlikely to be hit with offset &
    2922             :                     // scale
    2923           4 :                     dfGPKGNoDataValue = -std::numeric_limits<float>::max();
    2924             :                 }
    2925          21 :                 poBand->SetNoDataValueInternal(dfGPKGNoDataValue);
    2926             :             }
    2927             :         }
    2928             :         else
    2929             :         {
    2930           2 :             poBand->SetNoDataValueInternal(
    2931           2 :                 static_cast<float>(dfGPKGNoDataValue));
    2932             :         }
    2933             :     }
    2934         268 :     if (!osUom.empty())
    2935             :     {
    2936           2 :         poBand->SetUnitTypeInternal(osUom);
    2937             :     }
    2938         268 :     if (!osFieldName.empty())
    2939             :     {
    2940          64 :         GetRasterBand(1)->GDALRasterBand::SetDescription(osFieldName);
    2941             :     }
    2942         268 :     if (!osGridCellEncoding.empty())
    2943             :     {
    2944          64 :         if (osGridCellEncoding == "grid-value-is-center")
    2945             :         {
    2946          15 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2947             :                                             GDALMD_AOP_POINT);
    2948             :         }
    2949          49 :         else if (osGridCellEncoding == "grid-value-is-area")
    2950             :         {
    2951          45 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2952             :                                             GDALMD_AOP_AREA);
    2953             :         }
    2954             :         else
    2955             :         {
    2956           4 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2957             :                                             GDALMD_AOP_POINT);
    2958           4 :             GetRasterBand(1)->GDALRasterBand::SetMetadataItem(
    2959             :                 "GRID_CELL_ENCODING", osGridCellEncoding);
    2960             :         }
    2961             :     }
    2962             : 
    2963         268 :     CheckUnknownExtensions(true);
    2964             : 
    2965             :     // Do this after CheckUnknownExtensions() so that m_eTF is set to
    2966             :     // GPKG_TF_WEBP if the table already registers the gpkg_webp extension
    2967         268 :     const char *pszTF = CSLFetchNameValue(papszOpenOptionsIn, "TILE_FORMAT");
    2968         268 :     if (pszTF)
    2969             :     {
    2970           4 :         if (!GetUpdate())
    2971             :         {
    2972           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2973             :                      "TILE_FORMAT open option ignored in read-only mode");
    2974             :         }
    2975           4 :         else if (m_eTF == GPKG_TF_PNG_16BIT ||
    2976           4 :                  m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    2977             :         {
    2978           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2979             :                      "TILE_FORMAT open option ignored on gridded coverages");
    2980             :         }
    2981             :         else
    2982             :         {
    2983           4 :             GPKGTileFormat eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    2984           4 :             if (eTF == GPKG_TF_WEBP && m_eTF != eTF)
    2985             :             {
    2986           1 :                 if (!RegisterWebPExtension())
    2987           0 :                     return false;
    2988             :             }
    2989           4 :             m_eTF = eTF;
    2990             :         }
    2991             :     }
    2992             : 
    2993         268 :     ParseCompressionOptions(papszOpenOptionsIn);
    2994             : 
    2995         268 :     m_osWHERE = CSLFetchNameValueDef(papszOpenOptionsIn, "WHERE", "");
    2996             : 
    2997             :     // Set metadata
    2998         268 :     if (pszIdentifier && pszIdentifier[0])
    2999         268 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", pszIdentifier);
    3000         268 :     if (pszDescription && pszDescription[0])
    3001          21 :         GDALPamDataset::SetMetadataItem("DESCRIPTION", pszDescription);
    3002             : 
    3003             :     // Add overviews
    3004         353 :     for (int i = 1; i < oResult->RowCount(); i++)
    3005             :     {
    3006          86 :         auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3007          86 :         poOvrDS->ShareLockWithParentDataset(this);
    3008         172 :         if (!poOvrDS->InitRaster(this, pszTableName, dfMinX, dfMinY, dfMaxX,
    3009             :                                  dfMaxY, pszContentsMinX, pszContentsMinY,
    3010             :                                  pszContentsMaxX, pszContentsMaxY,
    3011          86 :                                  papszOpenOptionsIn, *oResult, i))
    3012             :         {
    3013           0 :             break;
    3014             :         }
    3015             : 
    3016             :         int nTileWidth, nTileHeight;
    3017          86 :         poOvrDS->GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3018             :         const bool bStop =
    3019          87 :             (eAccess == GA_ReadOnly && poOvrDS->GetRasterXSize() < nTileWidth &&
    3020           1 :              poOvrDS->GetRasterYSize() < nTileHeight);
    3021             : 
    3022          86 :         m_apoOverviewDS.push_back(std::move(poOvrDS));
    3023             : 
    3024          86 :         if (bStop)
    3025             :         {
    3026           1 :             break;
    3027             :         }
    3028             :     }
    3029             : 
    3030         268 :     return true;
    3031             : }
    3032             : 
    3033             : /************************************************************************/
    3034             : /*                           GetSpatialRef()                            */
    3035             : /************************************************************************/
    3036             : 
    3037          17 : const OGRSpatialReference *GDALGeoPackageDataset::GetSpatialRef() const
    3038             : {
    3039          17 :     return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
    3040             : }
    3041             : 
    3042             : /************************************************************************/
    3043             : /*                           SetSpatialRef()                            */
    3044             : /************************************************************************/
    3045             : 
    3046         150 : CPLErr GDALGeoPackageDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    3047             : {
    3048         150 :     if (nBands == 0)
    3049             :     {
    3050           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3051             :                  "SetProjection() not supported on a dataset with 0 band");
    3052           1 :         return CE_Failure;
    3053             :     }
    3054         149 :     if (eAccess != GA_Update)
    3055             :     {
    3056           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3057             :                  "SetProjection() not supported on read-only dataset");
    3058           1 :         return CE_Failure;
    3059             :     }
    3060             : 
    3061         148 :     const int nSRID = GetSrsId(poSRS);
    3062         296 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3063         148 :     if (poTS && nSRID != poTS->nEPSGCode)
    3064             :     {
    3065           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3066             :                  "Projection should be EPSG:%d for %s tiling scheme",
    3067           1 :                  poTS->nEPSGCode, m_osTilingScheme.c_str());
    3068           1 :         return CE_Failure;
    3069             :     }
    3070             : 
    3071         147 :     m_nSRID = nSRID;
    3072         147 :     m_oSRS.Clear();
    3073         147 :     if (poSRS)
    3074         146 :         m_oSRS = *poSRS;
    3075             : 
    3076         147 :     if (m_bRecordInsertedInGPKGContent)
    3077             :     {
    3078         119 :         char *pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET srs_id = %d "
    3079             :                                        "WHERE lower(table_name) = lower('%q')",
    3080             :                                        m_nSRID, m_osRasterTable.c_str());
    3081         119 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3082         119 :         sqlite3_free(pszSQL);
    3083         119 :         if (eErr != OGRERR_NONE)
    3084           0 :             return CE_Failure;
    3085             : 
    3086         119 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_tile_matrix_set SET srs_id = %d "
    3087             :                                  "WHERE lower(table_name) = lower('%q')",
    3088             :                                  m_nSRID, m_osRasterTable.c_str());
    3089         119 :         eErr = SQLCommand(hDB, pszSQL);
    3090         119 :         sqlite3_free(pszSQL);
    3091         119 :         if (eErr != OGRERR_NONE)
    3092           0 :             return CE_Failure;
    3093             :     }
    3094             : 
    3095         147 :     return CE_None;
    3096             : }
    3097             : 
    3098             : /************************************************************************/
    3099             : /*                          GetGeoTransform()                           */
    3100             : /************************************************************************/
    3101             : 
    3102          33 : CPLErr GDALGeoPackageDataset::GetGeoTransform(GDALGeoTransform &gt) const
    3103             : {
    3104          33 :     gt = m_gt;
    3105          33 :     if (!m_bGeoTransformValid)
    3106           2 :         return CE_Failure;
    3107             :     else
    3108          31 :         return CE_None;
    3109             : }
    3110             : 
    3111             : /************************************************************************/
    3112             : /*                          SetGeoTransform()                           */
    3113             : /************************************************************************/
    3114             : 
    3115         190 : CPLErr GDALGeoPackageDataset::SetGeoTransform(const GDALGeoTransform &gt)
    3116             : {
    3117         190 :     if (nBands == 0)
    3118             :     {
    3119           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3120             :                  "SetGeoTransform() not supported on a dataset with 0 band");
    3121           2 :         return CE_Failure;
    3122             :     }
    3123         188 :     if (eAccess != GA_Update)
    3124             :     {
    3125           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3126             :                  "SetGeoTransform() not supported on read-only dataset");
    3127           1 :         return CE_Failure;
    3128             :     }
    3129         187 :     if (m_bGeoTransformValid)
    3130             :     {
    3131           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3132             :                  "Cannot modify geotransform once set");
    3133           1 :         return CE_Failure;
    3134             :     }
    3135         186 :     if (gt[2] != 0.0 || gt[4] != 0 || gt[5] > 0.0)
    3136             :     {
    3137           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3138             :                  "Only north-up non rotated geotransform supported");
    3139           0 :         return CE_Failure;
    3140             :     }
    3141             : 
    3142         186 :     if (m_nZoomLevel < 0)
    3143             :     {
    3144         185 :         const auto poTS = GetTilingScheme(m_osTilingScheme);
    3145         185 :         if (poTS)
    3146             :         {
    3147          20 :             double dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3148          20 :             double dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3149         199 :             for (m_nZoomLevel = 0; m_nZoomLevel < MAX_ZOOM_LEVEL;
    3150         179 :                  m_nZoomLevel++)
    3151             :             {
    3152         198 :                 double dfExpectedPixelXSize =
    3153         198 :                     dfPixelXSizeZoomLevel0 / (1 << m_nZoomLevel);
    3154         198 :                 double dfExpectedPixelYSize =
    3155         198 :                     dfPixelYSizeZoomLevel0 / (1 << m_nZoomLevel);
    3156         198 :                 if (fabs(gt[1] - dfExpectedPixelXSize) <
    3157         217 :                         1e-8 * dfExpectedPixelXSize &&
    3158          19 :                     fabs(fabs(gt[5]) - dfExpectedPixelYSize) <
    3159          19 :                         1e-8 * dfExpectedPixelYSize)
    3160             :                 {
    3161          19 :                     break;
    3162             :                 }
    3163             :             }
    3164          20 :             if (m_nZoomLevel == MAX_ZOOM_LEVEL)
    3165             :             {
    3166           1 :                 m_nZoomLevel = -1;
    3167           1 :                 CPLError(
    3168             :                     CE_Failure, CPLE_NotSupported,
    3169             :                     "Could not find an appropriate zoom level of %s tiling "
    3170             :                     "scheme that matches raster pixel size",
    3171             :                     m_osTilingScheme.c_str());
    3172           1 :                 return CE_Failure;
    3173             :             }
    3174             :         }
    3175             :     }
    3176             : 
    3177         185 :     m_gt = gt;
    3178         185 :     m_bGeoTransformValid = true;
    3179             : 
    3180         185 :     return FinalizeRasterRegistration();
    3181             : }
    3182             : 
    3183             : /************************************************************************/
    3184             : /*                      FinalizeRasterRegistration()                    */
    3185             : /************************************************************************/
    3186             : 
    3187         185 : CPLErr GDALGeoPackageDataset::FinalizeRasterRegistration()
    3188             : {
    3189             :     OGRErr eErr;
    3190             : 
    3191         185 :     m_dfTMSMinX = m_gt[0];
    3192         185 :     m_dfTMSMaxY = m_gt[3];
    3193             : 
    3194             :     int nTileWidth, nTileHeight;
    3195         185 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3196             : 
    3197         185 :     if (m_nZoomLevel < 0)
    3198             :     {
    3199         165 :         m_nZoomLevel = 0;
    3200         239 :         while ((nRasterXSize >> m_nZoomLevel) > nTileWidth ||
    3201         165 :                (nRasterYSize >> m_nZoomLevel) > nTileHeight)
    3202          74 :             m_nZoomLevel++;
    3203             :     }
    3204             : 
    3205         185 :     double dfPixelXSizeZoomLevel0 = m_gt[1] * (1 << m_nZoomLevel);
    3206         185 :     double dfPixelYSizeZoomLevel0 = fabs(m_gt[5]) * (1 << m_nZoomLevel);
    3207             :     int nTileXCountZoomLevel0 =
    3208         185 :         std::max(1, DIV_ROUND_UP((nRasterXSize >> m_nZoomLevel), nTileWidth));
    3209             :     int nTileYCountZoomLevel0 =
    3210         185 :         std::max(1, DIV_ROUND_UP((nRasterYSize >> m_nZoomLevel), nTileHeight));
    3211             : 
    3212         370 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3213         185 :     if (poTS)
    3214             :     {
    3215          20 :         CPLAssert(m_nZoomLevel >= 0);
    3216          20 :         m_dfTMSMinX = poTS->dfMinX;
    3217          20 :         m_dfTMSMaxY = poTS->dfMaxY;
    3218          20 :         dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3219          20 :         dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3220          20 :         nTileXCountZoomLevel0 = poTS->nTileXCountZoomLevel0;
    3221          20 :         nTileYCountZoomLevel0 = poTS->nTileYCountZoomLevel0;
    3222             :     }
    3223         185 :     m_nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << m_nZoomLevel);
    3224         185 :     m_nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << m_nZoomLevel);
    3225             : 
    3226         185 :     if (!ComputeTileAndPixelShifts())
    3227             :     {
    3228           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    3229             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    3230           1 :         return CE_Failure;
    3231             :     }
    3232             : 
    3233         184 :     if (!AllocCachedTiles())
    3234             :     {
    3235           0 :         return CE_Failure;
    3236             :     }
    3237             : 
    3238         184 :     double dfGDALMinX = m_gt[0];
    3239         184 :     double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3240         184 :     double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3241         184 :     double dfGDALMaxY = m_gt[3];
    3242             : 
    3243         184 :     if (SoftStartTransaction() != OGRERR_NONE)
    3244           0 :         return CE_Failure;
    3245             : 
    3246             :     const char *pszCurrentDate =
    3247         184 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3248             :     CPLString osInsertGpkgContentsFormatting(
    3249             :         "INSERT INTO gpkg_contents "
    3250             :         "(table_name,data_type,identifier,description,min_x,min_y,max_x,max_y,"
    3251             :         "last_change,srs_id) VALUES "
    3252         368 :         "('%q','%q','%q','%q',%.17g,%.17g,%.17g,%.17g,");
    3253         184 :     osInsertGpkgContentsFormatting += (pszCurrentDate) ? "'%q'" : "%s";
    3254         184 :     osInsertGpkgContentsFormatting += ",%d)";
    3255         368 :     char *pszSQL = sqlite3_mprintf(
    3256             :         osInsertGpkgContentsFormatting.c_str(), m_osRasterTable.c_str(),
    3257         184 :         (m_eDT == GDT_Byte) ? "tiles" : "2d-gridded-coverage",
    3258             :         m_osIdentifier.c_str(), m_osDescription.c_str(), dfGDALMinX, dfGDALMinY,
    3259             :         dfGDALMaxX, dfGDALMaxY,
    3260             :         pszCurrentDate ? pszCurrentDate
    3261             :                        : "strftime('%Y-%m-%dT%H:%M:%fZ','now')",
    3262             :         m_nSRID);
    3263             : 
    3264         184 :     eErr = SQLCommand(hDB, pszSQL);
    3265         184 :     sqlite3_free(pszSQL);
    3266         184 :     if (eErr != OGRERR_NONE)
    3267             :     {
    3268           8 :         SoftRollbackTransaction();
    3269           8 :         return CE_Failure;
    3270             :     }
    3271             : 
    3272         176 :     double dfTMSMaxX = m_dfTMSMinX + nTileXCountZoomLevel0 * nTileWidth *
    3273             :                                          dfPixelXSizeZoomLevel0;
    3274         176 :     double dfTMSMinY = m_dfTMSMaxY - nTileYCountZoomLevel0 * nTileHeight *
    3275             :                                          dfPixelYSizeZoomLevel0;
    3276             : 
    3277             :     pszSQL =
    3278         176 :         sqlite3_mprintf("INSERT INTO gpkg_tile_matrix_set "
    3279             :                         "(table_name,srs_id,min_x,min_y,max_x,max_y) VALUES "
    3280             :                         "('%q',%d,%.17g,%.17g,%.17g,%.17g)",
    3281             :                         m_osRasterTable.c_str(), m_nSRID, m_dfTMSMinX,
    3282             :                         dfTMSMinY, dfTMSMaxX, m_dfTMSMaxY);
    3283         176 :     eErr = SQLCommand(hDB, pszSQL);
    3284         176 :     sqlite3_free(pszSQL);
    3285         176 :     if (eErr != OGRERR_NONE)
    3286             :     {
    3287           0 :         SoftRollbackTransaction();
    3288           0 :         return CE_Failure;
    3289             :     }
    3290             : 
    3291         176 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3292             : 
    3293         587 :     for (int i = 0; i <= m_nZoomLevel; i++)
    3294             :     {
    3295         411 :         double dfPixelXSizeZoomLevel = 0.0;
    3296         411 :         double dfPixelYSizeZoomLevel = 0.0;
    3297         411 :         int nTileMatrixWidth = 0;
    3298         411 :         int nTileMatrixHeight = 0;
    3299         411 :         if (EQUAL(m_osTilingScheme, "CUSTOM"))
    3300             :         {
    3301         230 :             dfPixelXSizeZoomLevel = m_gt[1] * (1 << (m_nZoomLevel - i));
    3302         230 :             dfPixelYSizeZoomLevel = fabs(m_gt[5]) * (1 << (m_nZoomLevel - i));
    3303             :         }
    3304             :         else
    3305             :         {
    3306         181 :             dfPixelXSizeZoomLevel = dfPixelXSizeZoomLevel0 / (1 << i);
    3307         181 :             dfPixelYSizeZoomLevel = dfPixelYSizeZoomLevel0 / (1 << i);
    3308             :         }
    3309         411 :         nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << i);
    3310         411 :         nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << i);
    3311             : 
    3312         411 :         pszSQL = sqlite3_mprintf(
    3313             :             "INSERT INTO gpkg_tile_matrix "
    3314             :             "(table_name,zoom_level,matrix_width,matrix_height,tile_width,tile_"
    3315             :             "height,pixel_x_size,pixel_y_size) VALUES "
    3316             :             "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3317             :             m_osRasterTable.c_str(), i, nTileMatrixWidth, nTileMatrixHeight,
    3318             :             nTileWidth, nTileHeight, dfPixelXSizeZoomLevel,
    3319             :             dfPixelYSizeZoomLevel);
    3320         411 :         eErr = SQLCommand(hDB, pszSQL);
    3321         411 :         sqlite3_free(pszSQL);
    3322         411 :         if (eErr != OGRERR_NONE)
    3323             :         {
    3324           0 :             SoftRollbackTransaction();
    3325           0 :             return CE_Failure;
    3326             :         }
    3327             : 
    3328         411 :         if (i < m_nZoomLevel)
    3329             :         {
    3330         470 :             auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3331         235 :             poOvrDS->ShareLockWithParentDataset(this);
    3332         235 :             poOvrDS->InitRaster(this, m_osRasterTable, i, nBands, m_dfTMSMinX,
    3333             :                                 m_dfTMSMaxY, dfPixelXSizeZoomLevel,
    3334             :                                 dfPixelYSizeZoomLevel, nTileWidth, nTileHeight,
    3335             :                                 nTileMatrixWidth, nTileMatrixHeight, dfGDALMinX,
    3336             :                                 dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    3337             : 
    3338         235 :             m_apoOverviewDS[m_nZoomLevel - 1 - i] = std::move(poOvrDS);
    3339             :         }
    3340             :     }
    3341             : 
    3342         176 :     if (!m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.empty())
    3343             :     {
    3344          40 :         eErr = SQLCommand(
    3345             :             hDB, m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.c_str());
    3346          40 :         m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.clear();
    3347          40 :         if (eErr != OGRERR_NONE)
    3348             :         {
    3349           0 :             SoftRollbackTransaction();
    3350           0 :             return CE_Failure;
    3351             :         }
    3352             :     }
    3353             : 
    3354         176 :     SoftCommitTransaction();
    3355             : 
    3356         176 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3357         176 :     m_bRecordInsertedInGPKGContent = true;
    3358             : 
    3359         176 :     return CE_None;
    3360             : }
    3361             : 
    3362             : /************************************************************************/
    3363             : /*                             FlushCache()                             */
    3364             : /************************************************************************/
    3365             : 
    3366        2611 : CPLErr GDALGeoPackageDataset::FlushCache(bool bAtClosing)
    3367             : {
    3368        2611 :     if (m_bInFlushCache)
    3369           0 :         return CE_None;
    3370             : 
    3371        2611 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3372             :     {
    3373        2608 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3374             :     }
    3375             : 
    3376        2611 :     if (m_bRemoveOGREmptyTable)
    3377             :     {
    3378         656 :         m_bRemoveOGREmptyTable = false;
    3379         656 :         RemoveOGREmptyTable();
    3380             :     }
    3381             : 
    3382        2611 :     CPLErr eErr = IFlushCacheWithErrCode(bAtClosing);
    3383             : 
    3384        2611 :     FlushMetadata();
    3385             : 
    3386        2611 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3387             :     {
    3388             :         // Needed again as above IFlushCacheWithErrCode()
    3389             :         // may have call GDALGeoPackageRasterBand::InvalidateStatistics()
    3390             :         // which modifies metadata
    3391        2611 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3392             :     }
    3393             : 
    3394        2611 :     return eErr;
    3395             : }
    3396             : 
    3397        4842 : CPLErr GDALGeoPackageDataset::IFlushCacheWithErrCode(bool bAtClosing)
    3398             : 
    3399             : {
    3400        4842 :     if (m_bInFlushCache)
    3401        2164 :         return CE_None;
    3402        2678 :     m_bInFlushCache = true;
    3403        2678 :     if (hDB && eAccess == GA_ReadOnly && bAtClosing)
    3404             :     {
    3405             :         // Clean-up metadata that will go to PAM by removing items that
    3406             :         // are reconstructed.
    3407        1950 :         CPLStringList aosMD;
    3408        1595 :         for (CSLConstList papszIter = GetMetadata(); papszIter && *papszIter;
    3409             :              ++papszIter)
    3410             :         {
    3411         620 :             char *pszKey = nullptr;
    3412         620 :             CPLParseNameValue(*papszIter, &pszKey);
    3413        1240 :             if (pszKey &&
    3414         620 :                 (EQUAL(pszKey, "AREA_OR_POINT") ||
    3415         475 :                  EQUAL(pszKey, "IDENTIFIER") || EQUAL(pszKey, "DESCRIPTION") ||
    3416         255 :                  EQUAL(pszKey, "ZOOM_LEVEL") ||
    3417         650 :                  STARTS_WITH(pszKey, "GPKG_METADATA_ITEM_")))
    3418             :             {
    3419             :                 // remove it
    3420             :             }
    3421             :             else
    3422             :             {
    3423          30 :                 aosMD.AddString(*papszIter);
    3424             :             }
    3425         620 :             CPLFree(pszKey);
    3426             :         }
    3427         975 :         oMDMD.SetMetadata(aosMD.List());
    3428         975 :         oMDMD.SetMetadata(nullptr, "IMAGE_STRUCTURE");
    3429             : 
    3430        1950 :         GDALPamDataset::FlushCache(bAtClosing);
    3431             :     }
    3432             :     else
    3433             :     {
    3434             :         // Short circuit GDALPamDataset to avoid serialization to .aux.xml
    3435        1703 :         GDALDataset::FlushCache(bAtClosing);
    3436             :     }
    3437             : 
    3438        6618 :     for (auto &poLayer : m_apoLayers)
    3439             :     {
    3440        3940 :         poLayer->RunDeferredCreationIfNecessary();
    3441        3940 :         poLayer->CreateSpatialIndexIfNecessary();
    3442             :     }
    3443             : 
    3444             :     // Update raster table last_change column in gpkg_contents if needed
    3445        2678 :     if (m_bHasModifiedTiles)
    3446             :     {
    3447         536 :         for (int i = 1; i <= nBands; ++i)
    3448             :         {
    3449             :             auto poBand =
    3450         357 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    3451         357 :             if (!poBand->HaveStatsMetadataBeenSetInThisSession())
    3452             :             {
    3453         344 :                 poBand->InvalidateStatistics();
    3454         344 :                 if (psPam && psPam->pszPamFilename)
    3455         344 :                     VSIUnlink(psPam->pszPamFilename);
    3456             :             }
    3457             :         }
    3458             : 
    3459         179 :         UpdateGpkgContentsLastChange(m_osRasterTable);
    3460             : 
    3461         179 :         m_bHasModifiedTiles = false;
    3462             :     }
    3463             : 
    3464        2678 :     CPLErr eErr = FlushTiles();
    3465             : 
    3466        2678 :     m_bInFlushCache = false;
    3467        2678 :     return eErr;
    3468             : }
    3469             : 
    3470             : /************************************************************************/
    3471             : /*                       GetCurrentDateEscapedSQL()                      */
    3472             : /************************************************************************/
    3473             : 
    3474        1901 : std::string GDALGeoPackageDataset::GetCurrentDateEscapedSQL()
    3475             : {
    3476             :     const char *pszCurrentDate =
    3477        1901 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3478        1901 :     if (pszCurrentDate)
    3479          10 :         return '\'' + SQLEscapeLiteral(pszCurrentDate) + '\'';
    3480        1896 :     return "strftime('%Y-%m-%dT%H:%M:%fZ','now')";
    3481             : }
    3482             : 
    3483             : /************************************************************************/
    3484             : /*                    UpdateGpkgContentsLastChange()                    */
    3485             : /************************************************************************/
    3486             : 
    3487             : OGRErr
    3488         820 : GDALGeoPackageDataset::UpdateGpkgContentsLastChange(const char *pszTableName)
    3489             : {
    3490             :     char *pszSQL =
    3491         820 :         sqlite3_mprintf("UPDATE gpkg_contents SET "
    3492             :                         "last_change = %s "
    3493             :                         "WHERE lower(table_name) = lower('%q')",
    3494        1640 :                         GetCurrentDateEscapedSQL().c_str(), pszTableName);
    3495         820 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    3496         820 :     sqlite3_free(pszSQL);
    3497         820 :     return eErr;
    3498             : }
    3499             : 
    3500             : /************************************************************************/
    3501             : /*                          IBuildOverviews()                           */
    3502             : /************************************************************************/
    3503             : 
    3504          20 : CPLErr GDALGeoPackageDataset::IBuildOverviews(
    3505             :     const char *pszResampling, int nOverviews, const int *panOverviewList,
    3506             :     int nBandsIn, const int * /*panBandList*/, GDALProgressFunc pfnProgress,
    3507             :     void *pProgressData, CSLConstList papszOptions)
    3508             : {
    3509          20 :     if (GetAccess() != GA_Update)
    3510             :     {
    3511           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3512             :                  "Overview building not supported on a database opened in "
    3513             :                  "read-only mode");
    3514           1 :         return CE_Failure;
    3515             :     }
    3516          19 :     if (m_poParentDS != nullptr)
    3517             :     {
    3518           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3519             :                  "Overview building not supported on overview dataset");
    3520           1 :         return CE_Failure;
    3521             :     }
    3522             : 
    3523          18 :     if (nOverviews == 0)
    3524             :     {
    3525           5 :         for (auto &poOvrDS : m_apoOverviewDS)
    3526           3 :             poOvrDS->FlushCache(false);
    3527             : 
    3528           2 :         SoftStartTransaction();
    3529             : 
    3530           2 :         if (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    3531             :         {
    3532           1 :             char *pszSQL = sqlite3_mprintf(
    3533             :                 "DELETE FROM gpkg_2d_gridded_tile_ancillary WHERE id IN "
    3534             :                 "(SELECT y.id FROM \"%w\" x "
    3535             :                 "JOIN gpkg_2d_gridded_tile_ancillary y "
    3536             :                 "ON x.id = y.tpudt_id AND y.tpudt_name = '%q' AND "
    3537             :                 "x.zoom_level < %d)",
    3538             :                 m_osRasterTable.c_str(), m_osRasterTable.c_str(), m_nZoomLevel);
    3539           1 :             OGRErr eErr = SQLCommand(hDB, pszSQL);
    3540           1 :             sqlite3_free(pszSQL);
    3541           1 :             if (eErr != OGRERR_NONE)
    3542             :             {
    3543           0 :                 SoftRollbackTransaction();
    3544           0 :                 return CE_Failure;
    3545             :             }
    3546             :         }
    3547             : 
    3548             :         char *pszSQL =
    3549           2 :             sqlite3_mprintf("DELETE FROM \"%w\" WHERE zoom_level < %d",
    3550             :                             m_osRasterTable.c_str(), m_nZoomLevel);
    3551           2 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3552           2 :         sqlite3_free(pszSQL);
    3553           2 :         if (eErr != OGRERR_NONE)
    3554             :         {
    3555           0 :             SoftRollbackTransaction();
    3556           0 :             return CE_Failure;
    3557             :         }
    3558             : 
    3559           2 :         SoftCommitTransaction();
    3560             : 
    3561           2 :         return CE_None;
    3562             :     }
    3563             : 
    3564          16 :     if (nBandsIn != nBands)
    3565             :     {
    3566           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3567             :                  "Generation of overviews in GPKG only"
    3568             :                  "supported when operating on all bands.");
    3569           0 :         return CE_Failure;
    3570             :     }
    3571             : 
    3572          16 :     if (m_apoOverviewDS.empty())
    3573             :     {
    3574           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3575             :                  "Image too small to support overviews");
    3576           0 :         return CE_Failure;
    3577             :     }
    3578             : 
    3579          16 :     FlushCache(false);
    3580          60 :     for (int i = 0; i < nOverviews; i++)
    3581             :     {
    3582          47 :         if (panOverviewList[i] < 2)
    3583             :         {
    3584           1 :             CPLError(CE_Failure, CPLE_IllegalArg,
    3585             :                      "Overview factor must be >= 2");
    3586           1 :             return CE_Failure;
    3587             :         }
    3588             : 
    3589          46 :         bool bFound = false;
    3590          46 :         int jCandidate = -1;
    3591          46 :         int nMaxOvFactor = 0;
    3592         196 :         for (int j = 0; j < static_cast<int>(m_apoOverviewDS.size()); j++)
    3593             :         {
    3594         190 :             const auto poODS = m_apoOverviewDS[j].get();
    3595             :             const int nOvFactor =
    3596         190 :                 static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3597             : 
    3598         190 :             nMaxOvFactor = nOvFactor;
    3599             : 
    3600         190 :             if (nOvFactor == panOverviewList[i])
    3601             :             {
    3602          40 :                 bFound = true;
    3603          40 :                 break;
    3604             :             }
    3605             : 
    3606         150 :             if (jCandidate < 0 && nOvFactor > panOverviewList[i])
    3607           1 :                 jCandidate = j;
    3608             :         }
    3609             : 
    3610          46 :         if (!bFound)
    3611             :         {
    3612             :             /* Mostly for debug */
    3613           6 :             if (!CPLTestBool(CPLGetConfigOption(
    3614             :                     "ALLOW_GPKG_ZOOM_OTHER_EXTENSION", "YES")))
    3615             :             {
    3616           2 :                 CPLString osOvrList;
    3617           4 :                 for (const auto &poODS : m_apoOverviewDS)
    3618             :                 {
    3619             :                     const int nOvFactor =
    3620           2 :                         static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3621             : 
    3622           2 :                     if (!osOvrList.empty())
    3623           0 :                         osOvrList += ' ';
    3624           2 :                     osOvrList += CPLSPrintf("%d", nOvFactor);
    3625             :                 }
    3626           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    3627             :                          "Only overviews %s can be computed",
    3628             :                          osOvrList.c_str());
    3629           2 :                 return CE_Failure;
    3630             :             }
    3631             :             else
    3632             :             {
    3633           4 :                 int nOvFactor = panOverviewList[i];
    3634           4 :                 if (jCandidate < 0)
    3635           3 :                     jCandidate = static_cast<int>(m_apoOverviewDS.size());
    3636             : 
    3637           4 :                 int nOvXSize = std::max(1, GetRasterXSize() / nOvFactor);
    3638           4 :                 int nOvYSize = std::max(1, GetRasterYSize() / nOvFactor);
    3639           4 :                 if (!(jCandidate == static_cast<int>(m_apoOverviewDS.size()) &&
    3640           5 :                       nOvFactor == 2 * nMaxOvFactor) &&
    3641           1 :                     !m_bZoomOther)
    3642             :                 {
    3643           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    3644             :                              "Use of overview factor %d causes gpkg_zoom_other "
    3645             :                              "extension to be needed",
    3646             :                              nOvFactor);
    3647           1 :                     RegisterZoomOtherExtension();
    3648           1 :                     m_bZoomOther = true;
    3649             :                 }
    3650             : 
    3651           4 :                 SoftStartTransaction();
    3652             : 
    3653           4 :                 CPLAssert(jCandidate > 0);
    3654             :                 const int nNewZoomLevel =
    3655           4 :                     m_apoOverviewDS[jCandidate - 1]->m_nZoomLevel;
    3656             : 
    3657             :                 char *pszSQL;
    3658             :                 OGRErr eErr;
    3659          24 :                 for (int k = 0; k <= jCandidate; k++)
    3660             :                 {
    3661          60 :                     pszSQL = sqlite3_mprintf(
    3662             :                         "UPDATE gpkg_tile_matrix SET zoom_level = %d "
    3663             :                         "WHERE lower(table_name) = lower('%q') AND zoom_level "
    3664             :                         "= %d",
    3665          20 :                         m_nZoomLevel - k + 1, m_osRasterTable.c_str(),
    3666          20 :                         m_nZoomLevel - k);
    3667          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3668          20 :                     sqlite3_free(pszSQL);
    3669          20 :                     if (eErr != OGRERR_NONE)
    3670             :                     {
    3671           0 :                         SoftRollbackTransaction();
    3672           0 :                         return CE_Failure;
    3673             :                     }
    3674             : 
    3675             :                     pszSQL =
    3676          20 :                         sqlite3_mprintf("UPDATE \"%w\" SET zoom_level = %d "
    3677             :                                         "WHERE zoom_level = %d",
    3678             :                                         m_osRasterTable.c_str(),
    3679          20 :                                         m_nZoomLevel - k + 1, m_nZoomLevel - k);
    3680          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3681          20 :                     sqlite3_free(pszSQL);
    3682          20 :                     if (eErr != OGRERR_NONE)
    3683             :                     {
    3684           0 :                         SoftRollbackTransaction();
    3685           0 :                         return CE_Failure;
    3686             :                     }
    3687             :                 }
    3688             : 
    3689           4 :                 double dfGDALMinX = m_gt[0];
    3690           4 :                 double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3691           4 :                 double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3692           4 :                 double dfGDALMaxY = m_gt[3];
    3693           4 :                 double dfPixelXSizeZoomLevel = m_gt[1] * nOvFactor;
    3694           4 :                 double dfPixelYSizeZoomLevel = fabs(m_gt[5]) * nOvFactor;
    3695             :                 int nTileWidth, nTileHeight;
    3696           4 :                 GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3697           4 :                 int nTileMatrixWidth = DIV_ROUND_UP(nOvXSize, nTileWidth);
    3698           4 :                 int nTileMatrixHeight = DIV_ROUND_UP(nOvYSize, nTileHeight);
    3699           4 :                 pszSQL = sqlite3_mprintf(
    3700             :                     "INSERT INTO gpkg_tile_matrix "
    3701             :                     "(table_name,zoom_level,matrix_width,matrix_height,tile_"
    3702             :                     "width,tile_height,pixel_x_size,pixel_y_size) VALUES "
    3703             :                     "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3704             :                     m_osRasterTable.c_str(), nNewZoomLevel, nTileMatrixWidth,
    3705             :                     nTileMatrixHeight, nTileWidth, nTileHeight,
    3706             :                     dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel);
    3707           4 :                 eErr = SQLCommand(hDB, pszSQL);
    3708           4 :                 sqlite3_free(pszSQL);
    3709           4 :                 if (eErr != OGRERR_NONE)
    3710             :                 {
    3711           0 :                     SoftRollbackTransaction();
    3712           0 :                     return CE_Failure;
    3713             :                 }
    3714             : 
    3715           4 :                 SoftCommitTransaction();
    3716             : 
    3717           4 :                 m_nZoomLevel++; /* this change our zoom level as well as
    3718             :                                    previous overviews */
    3719          20 :                 for (int k = 0; k < jCandidate; k++)
    3720          16 :                     m_apoOverviewDS[k]->m_nZoomLevel++;
    3721             : 
    3722           4 :                 auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3723           4 :                 poOvrDS->ShareLockWithParentDataset(this);
    3724           4 :                 poOvrDS->InitRaster(
    3725             :                     this, m_osRasterTable, nNewZoomLevel, nBands, m_dfTMSMinX,
    3726             :                     m_dfTMSMaxY, dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel,
    3727             :                     nTileWidth, nTileHeight, nTileMatrixWidth,
    3728             :                     nTileMatrixHeight, dfGDALMinX, dfGDALMinY, dfGDALMaxX,
    3729             :                     dfGDALMaxY);
    3730           4 :                 m_apoOverviewDS.insert(m_apoOverviewDS.begin() + jCandidate,
    3731           8 :                                        std::move(poOvrDS));
    3732             :             }
    3733             :         }
    3734             :     }
    3735             : 
    3736             :     GDALRasterBand ***papapoOverviewBands = static_cast<GDALRasterBand ***>(
    3737          13 :         CPLCalloc(sizeof(GDALRasterBand **), nBands));
    3738          13 :     CPLErr eErr = CE_None;
    3739          49 :     for (int iBand = 0; eErr == CE_None && iBand < nBands; iBand++)
    3740             :     {
    3741          72 :         papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
    3742          36 :             CPLCalloc(sizeof(GDALRasterBand *), nOverviews));
    3743          36 :         int iCurOverview = 0;
    3744         185 :         for (int i = 0; i < nOverviews; i++)
    3745             :         {
    3746         149 :             bool bFound = false;
    3747         724 :             for (const auto &poODS : m_apoOverviewDS)
    3748             :             {
    3749             :                 const int nOvFactor =
    3750         724 :                     static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3751             : 
    3752         724 :                 if (nOvFactor == panOverviewList[i])
    3753             :                 {
    3754         298 :                     papapoOverviewBands[iBand][iCurOverview] =
    3755         149 :                         poODS->GetRasterBand(iBand + 1);
    3756         149 :                     iCurOverview++;
    3757         149 :                     bFound = true;
    3758         149 :                     break;
    3759             :                 }
    3760             :             }
    3761         149 :             if (!bFound)
    3762             :             {
    3763           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3764             :                          "Could not find dataset corresponding to ov factor %d",
    3765           0 :                          panOverviewList[i]);
    3766           0 :                 eErr = CE_Failure;
    3767             :             }
    3768             :         }
    3769          36 :         if (eErr == CE_None)
    3770             :         {
    3771          36 :             CPLAssert(iCurOverview == nOverviews);
    3772             :         }
    3773             :     }
    3774             : 
    3775          13 :     if (eErr == CE_None)
    3776          13 :         eErr = GDALRegenerateOverviewsMultiBand(
    3777          13 :             nBands, papoBands, nOverviews, papapoOverviewBands, pszResampling,
    3778             :             pfnProgress, pProgressData, papszOptions);
    3779             : 
    3780          49 :     for (int iBand = 0; iBand < nBands; iBand++)
    3781             :     {
    3782          36 :         CPLFree(papapoOverviewBands[iBand]);
    3783             :     }
    3784          13 :     CPLFree(papapoOverviewBands);
    3785             : 
    3786          13 :     return eErr;
    3787             : }
    3788             : 
    3789             : /************************************************************************/
    3790             : /*                            GetFileList()                             */
    3791             : /************************************************************************/
    3792             : 
    3793          35 : char **GDALGeoPackageDataset::GetFileList()
    3794             : {
    3795          35 :     TryLoadXML();
    3796          35 :     return GDALPamDataset::GetFileList();
    3797             : }
    3798             : 
    3799             : /************************************************************************/
    3800             : /*                      GetMetadataDomainList()                         */
    3801             : /************************************************************************/
    3802             : 
    3803          47 : char **GDALGeoPackageDataset::GetMetadataDomainList()
    3804             : {
    3805          47 :     GetMetadata();
    3806          47 :     if (!m_osRasterTable.empty())
    3807           5 :         GetMetadata("GEOPACKAGE");
    3808          47 :     return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
    3809          47 :                                    TRUE, "SUBDATASETS", nullptr);
    3810             : }
    3811             : 
    3812             : /************************************************************************/
    3813             : /*                        CheckMetadataDomain()                         */
    3814             : /************************************************************************/
    3815             : 
    3816        5241 : const char *GDALGeoPackageDataset::CheckMetadataDomain(const char *pszDomain)
    3817             : {
    3818        5424 :     if (pszDomain != nullptr && EQUAL(pszDomain, "GEOPACKAGE") &&
    3819         183 :         m_osRasterTable.empty())
    3820             :     {
    3821           4 :         CPLError(
    3822             :             CE_Warning, CPLE_IllegalArg,
    3823             :             "Using GEOPACKAGE for a non-raster geopackage is not supported. "
    3824             :             "Using default domain instead");
    3825           4 :         return nullptr;
    3826             :     }
    3827        5237 :     return pszDomain;
    3828             : }
    3829             : 
    3830             : /************************************************************************/
    3831             : /*                           HasMetadataTables()                        */
    3832             : /************************************************************************/
    3833             : 
    3834        5331 : bool GDALGeoPackageDataset::HasMetadataTables() const
    3835             : {
    3836        5331 :     if (m_nHasMetadataTables < 0)
    3837             :     {
    3838             :         const int nCount =
    3839        1980 :             SQLGetInteger(hDB,
    3840             :                           "SELECT COUNT(*) FROM sqlite_master WHERE name IN "
    3841             :                           "('gpkg_metadata', 'gpkg_metadata_reference') "
    3842             :                           "AND type IN ('table', 'view')",
    3843             :                           nullptr);
    3844        1980 :         m_nHasMetadataTables = nCount == 2;
    3845             :     }
    3846        5331 :     return CPL_TO_BOOL(m_nHasMetadataTables);
    3847             : }
    3848             : 
    3849             : /************************************************************************/
    3850             : /*                         HasDataColumnsTable()                        */
    3851             : /************************************************************************/
    3852             : 
    3853        1181 : bool GDALGeoPackageDataset::HasDataColumnsTable() const
    3854             : {
    3855        2362 :     const int nCount = SQLGetInteger(
    3856        1181 :         hDB,
    3857             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_data_columns'"
    3858             :         "AND type IN ('table', 'view')",
    3859             :         nullptr);
    3860        1181 :     return nCount == 1;
    3861             : }
    3862             : 
    3863             : /************************************************************************/
    3864             : /*                    HasDataColumnConstraintsTable()                   */
    3865             : /************************************************************************/
    3866             : 
    3867         120 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTable() const
    3868             : {
    3869         120 :     const int nCount = SQLGetInteger(hDB,
    3870             :                                      "SELECT 1 FROM sqlite_master WHERE name = "
    3871             :                                      "'gpkg_data_column_constraints'"
    3872             :                                      "AND type IN ('table', 'view')",
    3873             :                                      nullptr);
    3874         120 :     return nCount == 1;
    3875             : }
    3876             : 
    3877             : /************************************************************************/
    3878             : /*                  HasDataColumnConstraintsTableGPKG_1_0()             */
    3879             : /************************************************************************/
    3880             : 
    3881          73 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTableGPKG_1_0() const
    3882             : {
    3883          73 :     if (m_nApplicationId != GP10_APPLICATION_ID)
    3884          71 :         return false;
    3885             :     // In GPKG 1.0, the columns were named minIsInclusive, maxIsInclusive
    3886             :     // They were changed in 1.1 to min_is_inclusive, max_is_inclusive
    3887           2 :     bool bRet = false;
    3888           2 :     sqlite3_stmt *hSQLStmt = nullptr;
    3889           2 :     int rc = sqlite3_prepare_v2(hDB,
    3890             :                                 "SELECT minIsInclusive, maxIsInclusive FROM "
    3891             :                                 "gpkg_data_column_constraints",
    3892             :                                 -1, &hSQLStmt, nullptr);
    3893           2 :     if (rc == SQLITE_OK)
    3894             :     {
    3895           2 :         bRet = true;
    3896           2 :         sqlite3_finalize(hSQLStmt);
    3897             :     }
    3898           2 :     return bRet;
    3899             : }
    3900             : 
    3901             : /************************************************************************/
    3902             : /*      CreateColumnsTableAndColumnConstraintsTablesIfNecessary()       */
    3903             : /************************************************************************/
    3904             : 
    3905          49 : bool GDALGeoPackageDataset::
    3906             :     CreateColumnsTableAndColumnConstraintsTablesIfNecessary()
    3907             : {
    3908          49 :     if (!HasDataColumnsTable())
    3909             :     {
    3910             :         // Geopackage < 1.3 had
    3911             :         // CONSTRAINT fk_gdc_tn FOREIGN KEY (table_name) REFERENCES
    3912             :         // gpkg_contents(table_name) instead of the unique constraint.
    3913          10 :         if (OGRERR_NONE !=
    3914          10 :             SQLCommand(
    3915             :                 GetDB(),
    3916             :                 "CREATE TABLE gpkg_data_columns ("
    3917             :                 "table_name TEXT NOT NULL,"
    3918             :                 "column_name TEXT NOT NULL,"
    3919             :                 "name TEXT,"
    3920             :                 "title TEXT,"
    3921             :                 "description TEXT,"
    3922             :                 "mime_type TEXT,"
    3923             :                 "constraint_name TEXT,"
    3924             :                 "CONSTRAINT pk_gdc PRIMARY KEY (table_name, column_name),"
    3925             :                 "CONSTRAINT gdc_tn UNIQUE (table_name, name));"))
    3926             :         {
    3927           0 :             return false;
    3928             :         }
    3929             :     }
    3930          49 :     if (!HasDataColumnConstraintsTable())
    3931             :     {
    3932          22 :         const char *min_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3933          11 :                                            ? "min_is_inclusive"
    3934             :                                            : "minIsInclusive";
    3935          22 :         const char *max_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3936          11 :                                            ? "max_is_inclusive"
    3937             :                                            : "maxIsInclusive";
    3938             : 
    3939             :         const std::string osSQL(
    3940             :             CPLSPrintf("CREATE TABLE gpkg_data_column_constraints ("
    3941             :                        "constraint_name TEXT NOT NULL,"
    3942             :                        "constraint_type TEXT NOT NULL,"
    3943             :                        "value TEXT,"
    3944             :                        "min NUMERIC,"
    3945             :                        "%s BOOLEAN,"
    3946             :                        "max NUMERIC,"
    3947             :                        "%s BOOLEAN,"
    3948             :                        "description TEXT,"
    3949             :                        "CONSTRAINT gdcc_ntv UNIQUE (constraint_name, "
    3950             :                        "constraint_type, value));",
    3951          11 :                        min_is_inclusive, max_is_inclusive));
    3952          11 :         if (OGRERR_NONE != SQLCommand(GetDB(), osSQL.c_str()))
    3953             :         {
    3954           0 :             return false;
    3955             :         }
    3956             :     }
    3957          49 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    3958             :     {
    3959           0 :         return false;
    3960             :     }
    3961          49 :     if (SQLGetInteger(GetDB(),
    3962             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3963             :                       "table_name = 'gpkg_data_columns'",
    3964          49 :                       nullptr) != 1)
    3965             :     {
    3966          11 :         if (OGRERR_NONE !=
    3967          11 :             SQLCommand(
    3968             :                 GetDB(),
    3969             :                 "INSERT INTO gpkg_extensions "
    3970             :                 "(table_name,column_name,extension_name,definition,scope) "
    3971             :                 "VALUES ('gpkg_data_columns', NULL, 'gpkg_schema', "
    3972             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    3973             :                 "'read-write')"))
    3974             :         {
    3975           0 :             return false;
    3976             :         }
    3977             :     }
    3978          49 :     if (SQLGetInteger(GetDB(),
    3979             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3980             :                       "table_name = 'gpkg_data_column_constraints'",
    3981          49 :                       nullptr) != 1)
    3982             :     {
    3983          11 :         if (OGRERR_NONE !=
    3984          11 :             SQLCommand(
    3985             :                 GetDB(),
    3986             :                 "INSERT INTO gpkg_extensions "
    3987             :                 "(table_name,column_name,extension_name,definition,scope) "
    3988             :                 "VALUES ('gpkg_data_column_constraints', NULL, 'gpkg_schema', "
    3989             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    3990             :                 "'read-write')"))
    3991             :         {
    3992           0 :             return false;
    3993             :         }
    3994             :     }
    3995             : 
    3996          49 :     return true;
    3997             : }
    3998             : 
    3999             : /************************************************************************/
    4000             : /*                        HasGpkgextRelationsTable()                    */
    4001             : /************************************************************************/
    4002             : 
    4003        1177 : bool GDALGeoPackageDataset::HasGpkgextRelationsTable() const
    4004             : {
    4005        2354 :     const int nCount = SQLGetInteger(
    4006        1177 :         hDB,
    4007             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkgext_relations'"
    4008             :         "AND type IN ('table', 'view')",
    4009             :         nullptr);
    4010        1177 :     return nCount == 1;
    4011             : }
    4012             : 
    4013             : /************************************************************************/
    4014             : /*                    CreateRelationsTableIfNecessary()                 */
    4015             : /************************************************************************/
    4016             : 
    4017           9 : bool GDALGeoPackageDataset::CreateRelationsTableIfNecessary()
    4018             : {
    4019           9 :     if (HasGpkgextRelationsTable())
    4020             :     {
    4021           5 :         return true;
    4022             :     }
    4023             : 
    4024           4 :     if (OGRERR_NONE !=
    4025           4 :         SQLCommand(GetDB(), "CREATE TABLE gpkgext_relations ("
    4026             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    4027             :                             "base_table_name TEXT NOT NULL,"
    4028             :                             "base_primary_column TEXT NOT NULL DEFAULT 'id',"
    4029             :                             "related_table_name TEXT NOT NULL,"
    4030             :                             "related_primary_column TEXT NOT NULL DEFAULT 'id',"
    4031             :                             "relation_name TEXT NOT NULL,"
    4032             :                             "mapping_table_name TEXT NOT NULL UNIQUE);"))
    4033             :     {
    4034           0 :         return false;
    4035             :     }
    4036             : 
    4037           4 :     return true;
    4038             : }
    4039             : 
    4040             : /************************************************************************/
    4041             : /*                        HasQGISLayerStyles()                          */
    4042             : /************************************************************************/
    4043             : 
    4044          11 : bool GDALGeoPackageDataset::HasQGISLayerStyles() const
    4045             : {
    4046             :     // QGIS layer_styles extension:
    4047             :     // https://github.com/pka/qgpkg/blob/master/qgis_geopackage_extension.md
    4048          11 :     bool bRet = false;
    4049             :     const int nCount =
    4050          11 :         SQLGetInteger(hDB,
    4051             :                       "SELECT 1 FROM sqlite_master WHERE name = 'layer_styles'"
    4052             :                       "AND type = 'table'",
    4053             :                       nullptr);
    4054          11 :     if (nCount == 1)
    4055             :     {
    4056           1 :         sqlite3_stmt *hSQLStmt = nullptr;
    4057           2 :         int rc = sqlite3_prepare_v2(
    4058           1 :             hDB, "SELECT f_table_name, f_geometry_column FROM layer_styles", -1,
    4059             :             &hSQLStmt, nullptr);
    4060           1 :         if (rc == SQLITE_OK)
    4061             :         {
    4062           1 :             bRet = true;
    4063           1 :             sqlite3_finalize(hSQLStmt);
    4064             :         }
    4065             :     }
    4066          11 :     return bRet;
    4067             : }
    4068             : 
    4069             : /************************************************************************/
    4070             : /*                            GetMetadata()                             */
    4071             : /************************************************************************/
    4072             : 
    4073        3523 : char **GDALGeoPackageDataset::GetMetadata(const char *pszDomain)
    4074             : 
    4075             : {
    4076        3523 :     pszDomain = CheckMetadataDomain(pszDomain);
    4077        3523 :     if (pszDomain != nullptr && EQUAL(pszDomain, "SUBDATASETS"))
    4078          67 :         return m_aosSubDatasets.List();
    4079             : 
    4080        3456 :     if (m_bHasReadMetadataFromStorage)
    4081        1532 :         return GDALPamDataset::GetMetadata(pszDomain);
    4082             : 
    4083        1924 :     m_bHasReadMetadataFromStorage = true;
    4084             : 
    4085        1924 :     TryLoadXML();
    4086             : 
    4087        1924 :     if (!HasMetadataTables())
    4088        1417 :         return GDALPamDataset::GetMetadata(pszDomain);
    4089             : 
    4090         507 :     char *pszSQL = nullptr;
    4091         507 :     if (!m_osRasterTable.empty())
    4092             :     {
    4093         169 :         pszSQL = sqlite3_mprintf(
    4094             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4095             :             "mdr.reference_scope FROM gpkg_metadata md "
    4096             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4097             :             "WHERE "
    4098             :             "(mdr.reference_scope = 'geopackage' OR "
    4099             :             "(mdr.reference_scope = 'table' AND lower(mdr.table_name) = "
    4100             :             "lower('%q'))) ORDER BY md.id "
    4101             :             "LIMIT 1000",  // to avoid denial of service
    4102             :             m_osRasterTable.c_str());
    4103             :     }
    4104             :     else
    4105             :     {
    4106         338 :         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' ORDER BY md.id "
    4112             :             "LIMIT 1000"  // to avoid denial of service
    4113             :         );
    4114             :     }
    4115             : 
    4116        1014 :     auto oResult = SQLQuery(hDB, pszSQL);
    4117         507 :     sqlite3_free(pszSQL);
    4118         507 :     if (!oResult)
    4119             :     {
    4120           0 :         return GDALPamDataset::GetMetadata(pszDomain);
    4121             :     }
    4122             : 
    4123         507 :     char **papszMetadata = CSLDuplicate(GDALPamDataset::GetMetadata());
    4124             : 
    4125             :     /* GDAL metadata */
    4126         696 :     for (int i = 0; i < oResult->RowCount(); i++)
    4127             :     {
    4128         189 :         const char *pszMetadata = oResult->GetValue(0, i);
    4129         189 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4130         189 :         const char *pszMimeType = oResult->GetValue(2, i);
    4131         189 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4132         189 :         if (pszMetadata && pszMDStandardURI && pszMimeType &&
    4133         189 :             pszReferenceScope && EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4134         173 :             EQUAL(pszMimeType, "text/xml"))
    4135             :         {
    4136         173 :             CPLXMLNode *psXMLNode = CPLParseXMLString(pszMetadata);
    4137         173 :             if (psXMLNode)
    4138             :             {
    4139         346 :                 GDALMultiDomainMetadata oLocalMDMD;
    4140         173 :                 oLocalMDMD.XMLInit(psXMLNode, FALSE);
    4141         331 :                 if (!m_osRasterTable.empty() &&
    4142         158 :                     EQUAL(pszReferenceScope, "geopackage"))
    4143             :                 {
    4144           6 :                     oMDMD.SetMetadata(oLocalMDMD.GetMetadata(), "GEOPACKAGE");
    4145             :                 }
    4146             :                 else
    4147             :                 {
    4148             :                     papszMetadata =
    4149         167 :                         CSLMerge(papszMetadata, oLocalMDMD.GetMetadata());
    4150         167 :                     CSLConstList papszDomainList = oLocalMDMD.GetDomainList();
    4151         167 :                     CSLConstList papszIter = papszDomainList;
    4152         444 :                     while (papszIter && *papszIter)
    4153             :                     {
    4154         277 :                         if (EQUAL(*papszIter, "IMAGE_STRUCTURE"))
    4155             :                         {
    4156             :                             CSLConstList papszMD =
    4157         125 :                                 oLocalMDMD.GetMetadata(*papszIter);
    4158             :                             const char *pszBAND_COUNT =
    4159         125 :                                 CSLFetchNameValue(papszMD, "BAND_COUNT");
    4160         125 :                             if (pszBAND_COUNT)
    4161         123 :                                 m_nBandCountFromMetadata = atoi(pszBAND_COUNT);
    4162             : 
    4163             :                             const char *pszCOLOR_TABLE =
    4164         125 :                                 CSLFetchNameValue(papszMD, "COLOR_TABLE");
    4165         125 :                             if (pszCOLOR_TABLE)
    4166             :                             {
    4167             :                                 const CPLStringList aosTokens(
    4168             :                                     CSLTokenizeString2(pszCOLOR_TABLE, "{,",
    4169          26 :                                                        0));
    4170          13 :                                 if ((aosTokens.size() % 4) == 0)
    4171             :                                 {
    4172          13 :                                     const int nColors = aosTokens.size() / 4;
    4173             :                                     m_poCTFromMetadata =
    4174          13 :                                         std::make_unique<GDALColorTable>();
    4175        3341 :                                     for (int iColor = 0; iColor < nColors;
    4176             :                                          ++iColor)
    4177             :                                     {
    4178             :                                         GDALColorEntry sEntry;
    4179        3328 :                                         sEntry.c1 = static_cast<short>(
    4180        3328 :                                             atoi(aosTokens[4 * iColor + 0]));
    4181        3328 :                                         sEntry.c2 = static_cast<short>(
    4182        3328 :                                             atoi(aosTokens[4 * iColor + 1]));
    4183        3328 :                                         sEntry.c3 = static_cast<short>(
    4184        3328 :                                             atoi(aosTokens[4 * iColor + 2]));
    4185        3328 :                                         sEntry.c4 = static_cast<short>(
    4186        3328 :                                             atoi(aosTokens[4 * iColor + 3]));
    4187        3328 :                                         m_poCTFromMetadata->SetColorEntry(
    4188             :                                             iColor, &sEntry);
    4189             :                                     }
    4190             :                                 }
    4191             :                             }
    4192             : 
    4193             :                             const char *pszTILE_FORMAT =
    4194         125 :                                 CSLFetchNameValue(papszMD, "TILE_FORMAT");
    4195         125 :                             if (pszTILE_FORMAT)
    4196             :                             {
    4197           8 :                                 m_osTFFromMetadata = pszTILE_FORMAT;
    4198           8 :                                 oMDMD.SetMetadataItem("TILE_FORMAT",
    4199             :                                                       pszTILE_FORMAT,
    4200             :                                                       "IMAGE_STRUCTURE");
    4201             :                             }
    4202             : 
    4203             :                             const char *pszNodataValue =
    4204         125 :                                 CSLFetchNameValue(papszMD, "NODATA_VALUE");
    4205         125 :                             if (pszNodataValue)
    4206             :                             {
    4207           2 :                                 m_osNodataValueFromMetadata = pszNodataValue;
    4208             :                             }
    4209             :                         }
    4210             : 
    4211         152 :                         else if (!EQUAL(*papszIter, "") &&
    4212          16 :                                  !STARTS_WITH(*papszIter, "BAND_"))
    4213             :                         {
    4214          12 :                             oMDMD.SetMetadata(
    4215           6 :                                 oLocalMDMD.GetMetadata(*papszIter), *papszIter);
    4216             :                         }
    4217         277 :                         papszIter++;
    4218             :                     }
    4219             :                 }
    4220         173 :                 CPLDestroyXMLNode(psXMLNode);
    4221             :             }
    4222             :         }
    4223             :     }
    4224             : 
    4225         507 :     GDALPamDataset::SetMetadata(papszMetadata);
    4226         507 :     CSLDestroy(papszMetadata);
    4227         507 :     papszMetadata = nullptr;
    4228             : 
    4229             :     /* Add non-GDAL metadata now */
    4230         507 :     int nNonGDALMDILocal = 1;
    4231         507 :     int nNonGDALMDIGeopackage = 1;
    4232         696 :     for (int i = 0; i < oResult->RowCount(); i++)
    4233             :     {
    4234         189 :         const char *pszMetadata = oResult->GetValue(0, i);
    4235         189 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4236         189 :         const char *pszMimeType = oResult->GetValue(2, i);
    4237         189 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4238         189 :         if (pszMetadata == nullptr || pszMDStandardURI == nullptr ||
    4239         189 :             pszMimeType == nullptr || pszReferenceScope == nullptr)
    4240             :         {
    4241             :             // should not happen as there are NOT NULL constraints
    4242             :             // But a database could lack such NOT NULL constraints or have
    4243             :             // large values that would cause a memory allocation failure.
    4244           0 :             continue;
    4245             :         }
    4246         189 :         int bIsGPKGScope = EQUAL(pszReferenceScope, "geopackage");
    4247         189 :         if (EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4248         173 :             EQUAL(pszMimeType, "text/xml"))
    4249         173 :             continue;
    4250             : 
    4251          16 :         if (!m_osRasterTable.empty() && bIsGPKGScope)
    4252             :         {
    4253           8 :             oMDMD.SetMetadataItem(
    4254             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDIGeopackage),
    4255             :                 pszMetadata, "GEOPACKAGE");
    4256           8 :             nNonGDALMDIGeopackage++;
    4257             :         }
    4258             :         /*else if( strcmp( pszMDStandardURI, "http://www.isotc211.org/2005/gmd"
    4259             :         ) == 0 && strcmp( pszMimeType, "text/xml" ) == 0 )
    4260             :         {
    4261             :             char* apszMD[2];
    4262             :             apszMD[0] = (char*)pszMetadata;
    4263             :             apszMD[1] = NULL;
    4264             :             oMDMD.SetMetadata(apszMD, "xml:MD_Metadata");
    4265             :         }*/
    4266             :         else
    4267             :         {
    4268           8 :             oMDMD.SetMetadataItem(
    4269             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDILocal),
    4270             :                 pszMetadata);
    4271           8 :             nNonGDALMDILocal++;
    4272             :         }
    4273             :     }
    4274             : 
    4275         507 :     return GDALPamDataset::GetMetadata(pszDomain);
    4276             : }
    4277             : 
    4278             : /************************************************************************/
    4279             : /*                            WriteMetadata()                           */
    4280             : /************************************************************************/
    4281             : 
    4282         744 : void GDALGeoPackageDataset::WriteMetadata(
    4283             :     CPLXMLNode *psXMLNode, /* will be destroyed by the method */
    4284             :     const char *pszTableName)
    4285             : {
    4286         744 :     const bool bIsEmpty = (psXMLNode == nullptr);
    4287         744 :     if (!HasMetadataTables())
    4288             :     {
    4289         536 :         if (bIsEmpty || !CreateMetadataTables())
    4290             :         {
    4291         255 :             CPLDestroyXMLNode(psXMLNode);
    4292         255 :             return;
    4293             :         }
    4294             :     }
    4295             : 
    4296         489 :     char *pszXML = nullptr;
    4297         489 :     if (!bIsEmpty)
    4298             :     {
    4299             :         CPLXMLNode *psMasterXMLNode =
    4300         328 :             CPLCreateXMLNode(nullptr, CXT_Element, "GDALMultiDomainMetadata");
    4301         328 :         psMasterXMLNode->psChild = psXMLNode;
    4302         328 :         pszXML = CPLSerializeXMLTree(psMasterXMLNode);
    4303         328 :         CPLDestroyXMLNode(psMasterXMLNode);
    4304             :     }
    4305             :     // cppcheck-suppress uselessAssignmentPtrArg
    4306         489 :     psXMLNode = nullptr;
    4307             : 
    4308         489 :     char *pszSQL = nullptr;
    4309         489 :     if (pszTableName && pszTableName[0] != '\0')
    4310             :     {
    4311         341 :         pszSQL = sqlite3_mprintf(
    4312             :             "SELECT md.id FROM gpkg_metadata md "
    4313             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4314             :             "WHERE md.md_scope = 'dataset' AND "
    4315             :             "md.md_standard_uri='http://gdal.org' "
    4316             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = 'table' AND "
    4317             :             "lower(mdr.table_name) = lower('%q')",
    4318             :             pszTableName);
    4319             :     }
    4320             :     else
    4321             :     {
    4322         148 :         pszSQL = sqlite3_mprintf(
    4323             :             "SELECT md.id FROM gpkg_metadata md "
    4324             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4325             :             "WHERE md.md_scope = 'dataset' AND "
    4326             :             "md.md_standard_uri='http://gdal.org' "
    4327             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = "
    4328             :             "'geopackage'");
    4329             :     }
    4330             :     OGRErr err;
    4331         489 :     int mdId = SQLGetInteger(hDB, pszSQL, &err);
    4332         489 :     if (err != OGRERR_NONE)
    4333         457 :         mdId = -1;
    4334         489 :     sqlite3_free(pszSQL);
    4335             : 
    4336         489 :     if (bIsEmpty)
    4337             :     {
    4338         161 :         if (mdId >= 0)
    4339             :         {
    4340           6 :             SQLCommand(
    4341             :                 hDB,
    4342             :                 CPLSPrintf(
    4343             :                     "DELETE FROM gpkg_metadata_reference WHERE md_file_id = %d",
    4344             :                     mdId));
    4345           6 :             SQLCommand(
    4346             :                 hDB,
    4347             :                 CPLSPrintf("DELETE FROM gpkg_metadata WHERE id = %d", mdId));
    4348             :         }
    4349             :     }
    4350             :     else
    4351             :     {
    4352         328 :         if (mdId >= 0)
    4353             :         {
    4354          26 :             pszSQL = sqlite3_mprintf(
    4355             :                 "UPDATE gpkg_metadata SET metadata = '%q' WHERE id = %d",
    4356             :                 pszXML, mdId);
    4357             :         }
    4358             :         else
    4359             :         {
    4360             :             pszSQL =
    4361         302 :                 sqlite3_mprintf("INSERT INTO gpkg_metadata (md_scope, "
    4362             :                                 "md_standard_uri, mime_type, metadata) VALUES "
    4363             :                                 "('dataset','http://gdal.org','text/xml','%q')",
    4364             :                                 pszXML);
    4365             :         }
    4366         328 :         SQLCommand(hDB, pszSQL);
    4367         328 :         sqlite3_free(pszSQL);
    4368             : 
    4369         328 :         CPLFree(pszXML);
    4370             : 
    4371         328 :         if (mdId < 0)
    4372             :         {
    4373         302 :             const sqlite_int64 nFID = sqlite3_last_insert_rowid(hDB);
    4374         302 :             if (pszTableName != nullptr && pszTableName[0] != '\0')
    4375             :             {
    4376         290 :                 pszSQL = sqlite3_mprintf(
    4377             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4378             :                     "table_name, timestamp, md_file_id) VALUES "
    4379             :                     "('table', '%q', %s, %d)",
    4380         580 :                     pszTableName, GetCurrentDateEscapedSQL().c_str(),
    4381             :                     static_cast<int>(nFID));
    4382             :             }
    4383             :             else
    4384             :             {
    4385          12 :                 pszSQL = sqlite3_mprintf(
    4386             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4387             :                     "timestamp, md_file_id) VALUES "
    4388             :                     "('geopackage', %s, %d)",
    4389          24 :                     GetCurrentDateEscapedSQL().c_str(), static_cast<int>(nFID));
    4390             :             }
    4391             :         }
    4392             :         else
    4393             :         {
    4394          26 :             pszSQL = sqlite3_mprintf("UPDATE gpkg_metadata_reference SET "
    4395             :                                      "timestamp = %s WHERE md_file_id = %d",
    4396          52 :                                      GetCurrentDateEscapedSQL().c_str(), mdId);
    4397             :         }
    4398         328 :         SQLCommand(hDB, pszSQL);
    4399         328 :         sqlite3_free(pszSQL);
    4400             :     }
    4401             : }
    4402             : 
    4403             : /************************************************************************/
    4404             : /*                        CreateMetadataTables()                        */
    4405             : /************************************************************************/
    4406             : 
    4407         299 : bool GDALGeoPackageDataset::CreateMetadataTables()
    4408             : {
    4409             :     const bool bCreateTriggers =
    4410         299 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "NO"));
    4411             : 
    4412             :     /* From C.10. gpkg_metadata Table 35. gpkg_metadata Table Definition SQL  */
    4413             :     CPLString osSQL = "CREATE TABLE gpkg_metadata ("
    4414             :                       "id INTEGER CONSTRAINT m_pk PRIMARY KEY ASC NOT NULL,"
    4415             :                       "md_scope TEXT NOT NULL DEFAULT 'dataset',"
    4416             :                       "md_standard_uri TEXT NOT NULL,"
    4417             :                       "mime_type TEXT NOT NULL DEFAULT 'text/xml',"
    4418             :                       "metadata TEXT NOT NULL DEFAULT ''"
    4419         598 :                       ")";
    4420             : 
    4421             :     /* From D.2. metadata Table 40. metadata Trigger Definition SQL  */
    4422         299 :     const char *pszMetadataTriggers =
    4423             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_insert' "
    4424             :         "BEFORE INSERT ON 'gpkg_metadata' "
    4425             :         "FOR EACH ROW BEGIN "
    4426             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata violates "
    4427             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4428             :         "collectionSession | series | dataset | featureType | feature | "
    4429             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4430             :         "taxonomy software | service | collectionHardware | "
    4431             :         "nonGeographicDataset | dimensionGroup') "
    4432             :         "WHERE NOT(NEW.md_scope IN "
    4433             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4434             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4435             :         "'catalogue','schema','taxonomy','software','service', "
    4436             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4437             :         "END; "
    4438             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_update' "
    4439             :         "BEFORE UPDATE OF 'md_scope' ON 'gpkg_metadata' "
    4440             :         "FOR EACH ROW BEGIN "
    4441             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata violates "
    4442             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4443             :         "collectionSession | series | dataset | featureType | feature | "
    4444             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4445             :         "taxonomy software | service | collectionHardware | "
    4446             :         "nonGeographicDataset | dimensionGroup') "
    4447             :         "WHERE NOT(NEW.md_scope IN "
    4448             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4449             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4450             :         "'catalogue','schema','taxonomy','software','service', "
    4451             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4452             :         "END";
    4453         299 :     if (bCreateTriggers)
    4454             :     {
    4455           0 :         osSQL += ";";
    4456           0 :         osSQL += pszMetadataTriggers;
    4457             :     }
    4458             : 
    4459             :     /* From C.11. gpkg_metadata_reference Table 36. gpkg_metadata_reference
    4460             :      * Table Definition SQL */
    4461             :     osSQL += ";"
    4462             :              "CREATE TABLE gpkg_metadata_reference ("
    4463             :              "reference_scope TEXT NOT NULL,"
    4464             :              "table_name TEXT,"
    4465             :              "column_name TEXT,"
    4466             :              "row_id_value INTEGER,"
    4467             :              "timestamp DATETIME NOT NULL DEFAULT "
    4468             :              "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    4469             :              "md_file_id INTEGER NOT NULL,"
    4470             :              "md_parent_id INTEGER,"
    4471             :              "CONSTRAINT crmr_mfi_fk FOREIGN KEY (md_file_id) REFERENCES "
    4472             :              "gpkg_metadata(id),"
    4473             :              "CONSTRAINT crmr_mpi_fk FOREIGN KEY (md_parent_id) REFERENCES "
    4474             :              "gpkg_metadata(id)"
    4475         299 :              ")";
    4476             : 
    4477             :     /* From D.3. metadata_reference Table 41. gpkg_metadata_reference Trigger
    4478             :      * Definition SQL   */
    4479         299 :     const char *pszMetadataReferenceTriggers =
    4480             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_insert' "
    4481             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4482             :         "FOR EACH ROW BEGIN "
    4483             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4484             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4485             :         "table\", \"column\", \"row\", \"row/col\"') "
    4486             :         "WHERE NOT NEW.reference_scope IN "
    4487             :         "('geopackage','table','column','row','row/col'); "
    4488             :         "END; "
    4489             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_update' "
    4490             :         "BEFORE UPDATE OF 'reference_scope' ON 'gpkg_metadata_reference' "
    4491             :         "FOR EACH ROW BEGIN "
    4492             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4493             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4494             :         "\"table\", \"column\", \"row\", \"row/col\"') "
    4495             :         "WHERE NOT NEW.reference_scope IN "
    4496             :         "('geopackage','table','column','row','row/col'); "
    4497             :         "END; "
    4498             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_insert' "
    4499             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4500             :         "FOR EACH ROW BEGIN "
    4501             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4502             :         "violates constraint: column name must be NULL when reference_scope "
    4503             :         "is \"geopackage\", \"table\" or \"row\"') "
    4504             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4505             :         "AND NEW.column_name IS NOT NULL); "
    4506             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4507             :         "violates constraint: column name must be defined for the specified "
    4508             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4509             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4510             :         "AND NOT NEW.table_name IN ( "
    4511             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4512             :         "AND name = NEW.table_name "
    4513             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4514             :         "END; "
    4515             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_update' "
    4516             :         "BEFORE UPDATE OF column_name ON 'gpkg_metadata_reference' "
    4517             :         "FOR EACH ROW BEGIN "
    4518             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4519             :         "violates constraint: column name must be NULL when reference_scope "
    4520             :         "is \"geopackage\", \"table\" or \"row\"') "
    4521             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4522             :         "AND NEW.column_name IS NOT NULL); "
    4523             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4524             :         "violates constraint: column name must be defined for the specified "
    4525             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4526             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4527             :         "AND NOT NEW.table_name IN ( "
    4528             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4529             :         "AND name = NEW.table_name "
    4530             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4531             :         "END; "
    4532             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_insert' "
    4533             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4534             :         "FOR EACH ROW BEGIN "
    4535             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4536             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4537             :         "is \"geopackage\", \"table\" or \"column\"') "
    4538             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4539             :         "AND NEW.row_id_value IS NOT NULL; "
    4540             :         "END; "
    4541             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_update' "
    4542             :         "BEFORE UPDATE OF 'row_id_value' ON 'gpkg_metadata_reference' "
    4543             :         "FOR EACH ROW BEGIN "
    4544             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4545             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4546             :         "is \"geopackage\", \"table\" or \"column\"') "
    4547             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4548             :         "AND NEW.row_id_value IS NOT NULL; "
    4549             :         "END; "
    4550             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_insert' "
    4551             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4552             :         "FOR EACH ROW BEGIN "
    4553             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4554             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4555             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4556             :         "WHERE NOT (NEW.timestamp GLOB "
    4557             :         "'[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-"
    4558             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4559             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4560             :         "END; "
    4561             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_update' "
    4562             :         "BEFORE UPDATE OF 'timestamp' ON 'gpkg_metadata_reference' "
    4563             :         "FOR EACH ROW BEGIN "
    4564             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4565             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4566             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4567             :         "WHERE NOT (NEW.timestamp GLOB "
    4568             :         "'[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-"
    4569             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4570             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4571             :         "END";
    4572         299 :     if (bCreateTriggers)
    4573             :     {
    4574           0 :         osSQL += ";";
    4575           0 :         osSQL += pszMetadataReferenceTriggers;
    4576             :     }
    4577             : 
    4578         299 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    4579           2 :         return false;
    4580             : 
    4581         297 :     osSQL += ";";
    4582             :     osSQL += "INSERT INTO gpkg_extensions "
    4583             :              "(table_name, column_name, extension_name, definition, scope) "
    4584             :              "VALUES "
    4585             :              "('gpkg_metadata', NULL, 'gpkg_metadata', "
    4586             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4587         297 :              "'read-write')";
    4588             : 
    4589         297 :     osSQL += ";";
    4590             :     osSQL += "INSERT INTO gpkg_extensions "
    4591             :              "(table_name, column_name, extension_name, definition, scope) "
    4592             :              "VALUES "
    4593             :              "('gpkg_metadata_reference', NULL, 'gpkg_metadata', "
    4594             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4595         297 :              "'read-write')";
    4596             : 
    4597         297 :     const bool bOK = SQLCommand(hDB, osSQL) == OGRERR_NONE;
    4598         297 :     m_nHasMetadataTables = bOK;
    4599         297 :     return bOK;
    4600             : }
    4601             : 
    4602             : /************************************************************************/
    4603             : /*                            FlushMetadata()                           */
    4604             : /************************************************************************/
    4605             : 
    4606        8502 : void GDALGeoPackageDataset::FlushMetadata()
    4607             : {
    4608        8502 :     if (!m_bMetadataDirty || m_poParentDS != nullptr ||
    4609         374 :         m_nCreateMetadataTables == FALSE)
    4610        8134 :         return;
    4611         368 :     m_bMetadataDirty = false;
    4612             : 
    4613         368 :     if (eAccess == GA_ReadOnly)
    4614             :     {
    4615           3 :         return;
    4616             :     }
    4617             : 
    4618         365 :     bool bCanWriteAreaOrPoint =
    4619         728 :         !m_bGridCellEncodingAsCO &&
    4620         363 :         (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT);
    4621         365 :     if (!m_osRasterTable.empty())
    4622             :     {
    4623             :         const char *pszIdentifier =
    4624         142 :             GDALGeoPackageDataset::GetMetadataItem("IDENTIFIER");
    4625             :         const char *pszDescription =
    4626         142 :             GDALGeoPackageDataset::GetMetadataItem("DESCRIPTION");
    4627         171 :         if (!m_bIdentifierAsCO && pszIdentifier != nullptr &&
    4628          29 :             pszIdentifier != m_osIdentifier)
    4629             :         {
    4630          14 :             m_osIdentifier = pszIdentifier;
    4631             :             char *pszSQL =
    4632          14 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4633             :                                 "WHERE lower(table_name) = lower('%q')",
    4634             :                                 pszIdentifier, m_osRasterTable.c_str());
    4635          14 :             SQLCommand(hDB, pszSQL);
    4636          14 :             sqlite3_free(pszSQL);
    4637             :         }
    4638         149 :         if (!m_bDescriptionAsCO && pszDescription != nullptr &&
    4639           7 :             pszDescription != m_osDescription)
    4640             :         {
    4641           7 :             m_osDescription = pszDescription;
    4642             :             char *pszSQL =
    4643           7 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4644             :                                 "WHERE lower(table_name) = lower('%q')",
    4645             :                                 pszDescription, m_osRasterTable.c_str());
    4646           7 :             SQLCommand(hDB, pszSQL);
    4647           7 :             sqlite3_free(pszSQL);
    4648             :         }
    4649         142 :         if (bCanWriteAreaOrPoint)
    4650             :         {
    4651             :             const char *pszAreaOrPoint =
    4652          28 :                 GDALGeoPackageDataset::GetMetadataItem(GDALMD_AREA_OR_POINT);
    4653          28 :             if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_AREA))
    4654             :             {
    4655          23 :                 bCanWriteAreaOrPoint = false;
    4656          23 :                 char *pszSQL = sqlite3_mprintf(
    4657             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4658             :                     "grid_cell_encoding = 'grid-value-is-area' WHERE "
    4659             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4660             :                     m_osRasterTable.c_str());
    4661          23 :                 SQLCommand(hDB, pszSQL);
    4662          23 :                 sqlite3_free(pszSQL);
    4663             :             }
    4664           5 :             else if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_POINT))
    4665             :             {
    4666           1 :                 bCanWriteAreaOrPoint = false;
    4667           1 :                 char *pszSQL = sqlite3_mprintf(
    4668             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4669             :                     "grid_cell_encoding = 'grid-value-is-center' WHERE "
    4670             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4671             :                     m_osRasterTable.c_str());
    4672           1 :                 SQLCommand(hDB, pszSQL);
    4673           1 :                 sqlite3_free(pszSQL);
    4674             :             }
    4675             :         }
    4676             :     }
    4677             : 
    4678         365 :     char **papszMDDup = nullptr;
    4679         568 :     for (char **papszIter = GDALGeoPackageDataset::GetMetadata();
    4680         568 :          papszIter && *papszIter; ++papszIter)
    4681             :     {
    4682         203 :         if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4683          29 :             continue;
    4684         174 :         if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4685           8 :             continue;
    4686         166 :         if (STARTS_WITH_CI(*papszIter, "ZOOM_LEVEL="))
    4687          14 :             continue;
    4688         152 :         if (STARTS_WITH_CI(*papszIter, "GPKG_METADATA_ITEM_"))
    4689           4 :             continue;
    4690         148 :         if ((m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT) &&
    4691          29 :             !bCanWriteAreaOrPoint &&
    4692          26 :             STARTS_WITH_CI(*papszIter, GDALMD_AREA_OR_POINT))
    4693             :         {
    4694          26 :             continue;
    4695             :         }
    4696         122 :         papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4697             :     }
    4698             : 
    4699         365 :     CPLXMLNode *psXMLNode = nullptr;
    4700             :     {
    4701         365 :         GDALMultiDomainMetadata oLocalMDMD;
    4702         365 :         CSLConstList papszDomainList = oMDMD.GetDomainList();
    4703         365 :         CSLConstList papszIter = papszDomainList;
    4704         365 :         oLocalMDMD.SetMetadata(papszMDDup);
    4705         705 :         while (papszIter && *papszIter)
    4706             :         {
    4707         340 :             if (!EQUAL(*papszIter, "") &&
    4708         172 :                 !EQUAL(*papszIter, "IMAGE_STRUCTURE") &&
    4709          15 :                 !EQUAL(*papszIter, "GEOPACKAGE"))
    4710             :             {
    4711           8 :                 oLocalMDMD.SetMetadata(oMDMD.GetMetadata(*papszIter),
    4712             :                                        *papszIter);
    4713             :             }
    4714         340 :             papszIter++;
    4715             :         }
    4716         365 :         if (m_nBandCountFromMetadata > 0)
    4717             :         {
    4718          72 :             oLocalMDMD.SetMetadataItem(
    4719             :                 "BAND_COUNT", CPLSPrintf("%d", m_nBandCountFromMetadata),
    4720             :                 "IMAGE_STRUCTURE");
    4721          72 :             if (nBands == 1)
    4722             :             {
    4723          48 :                 const auto poCT = GetRasterBand(1)->GetColorTable();
    4724          48 :                 if (poCT)
    4725             :                 {
    4726          16 :                     std::string osVal("{");
    4727           8 :                     const int nColorCount = poCT->GetColorEntryCount();
    4728        2056 :                     for (int i = 0; i < nColorCount; ++i)
    4729             :                     {
    4730        2048 :                         if (i > 0)
    4731        2040 :                             osVal += ',';
    4732        2048 :                         const GDALColorEntry *psEntry = poCT->GetColorEntry(i);
    4733             :                         osVal +=
    4734        2048 :                             CPLSPrintf("{%d,%d,%d,%d}", psEntry->c1,
    4735        2048 :                                        psEntry->c2, psEntry->c3, psEntry->c4);
    4736             :                     }
    4737           8 :                     osVal += '}';
    4738           8 :                     oLocalMDMD.SetMetadataItem("COLOR_TABLE", osVal.c_str(),
    4739             :                                                "IMAGE_STRUCTURE");
    4740             :                 }
    4741             :             }
    4742          72 :             if (nBands == 1)
    4743             :             {
    4744          48 :                 const char *pszTILE_FORMAT = nullptr;
    4745          48 :                 switch (m_eTF)
    4746             :                 {
    4747           0 :                     case GPKG_TF_PNG_JPEG:
    4748           0 :                         pszTILE_FORMAT = "JPEG_PNG";
    4749           0 :                         break;
    4750          42 :                     case GPKG_TF_PNG:
    4751          42 :                         break;
    4752           0 :                     case GPKG_TF_PNG8:
    4753           0 :                         pszTILE_FORMAT = "PNG8";
    4754           0 :                         break;
    4755           3 :                     case GPKG_TF_JPEG:
    4756           3 :                         pszTILE_FORMAT = "JPEG";
    4757           3 :                         break;
    4758           3 :                     case GPKG_TF_WEBP:
    4759           3 :                         pszTILE_FORMAT = "WEBP";
    4760           3 :                         break;
    4761           0 :                     case GPKG_TF_PNG_16BIT:
    4762           0 :                         break;
    4763           0 :                     case GPKG_TF_TIFF_32BIT_FLOAT:
    4764           0 :                         break;
    4765             :                 }
    4766          48 :                 if (pszTILE_FORMAT)
    4767           6 :                     oLocalMDMD.SetMetadataItem("TILE_FORMAT", pszTILE_FORMAT,
    4768             :                                                "IMAGE_STRUCTURE");
    4769             :             }
    4770             :         }
    4771         507 :         if (GetRasterCount() > 0 &&
    4772         142 :             GetRasterBand(1)->GetRasterDataType() == GDT_Byte)
    4773             :         {
    4774         112 :             int bHasNoData = FALSE;
    4775             :             const double dfNoDataValue =
    4776         112 :                 GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    4777         112 :             if (bHasNoData)
    4778             :             {
    4779           3 :                 oLocalMDMD.SetMetadataItem("NODATA_VALUE",
    4780             :                                            CPLSPrintf("%.17g", dfNoDataValue),
    4781             :                                            "IMAGE_STRUCTURE");
    4782             :             }
    4783             :         }
    4784         612 :         for (int i = 1; i <= GetRasterCount(); ++i)
    4785             :         {
    4786             :             auto poBand =
    4787         247 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    4788         247 :             poBand->AddImplicitStatistics(false);
    4789         247 :             char **papszMD = GetRasterBand(i)->GetMetadata();
    4790         247 :             poBand->AddImplicitStatistics(true);
    4791         247 :             if (papszMD)
    4792             :             {
    4793          14 :                 oLocalMDMD.SetMetadata(papszMD, CPLSPrintf("BAND_%d", i));
    4794             :             }
    4795             :         }
    4796         365 :         psXMLNode = oLocalMDMD.Serialize();
    4797             :     }
    4798             : 
    4799         365 :     CSLDestroy(papszMDDup);
    4800         365 :     papszMDDup = nullptr;
    4801             : 
    4802         365 :     WriteMetadata(psXMLNode, m_osRasterTable.c_str());
    4803             : 
    4804         365 :     if (!m_osRasterTable.empty())
    4805             :     {
    4806             :         char **papszGeopackageMD =
    4807         142 :             GDALGeoPackageDataset::GetMetadata("GEOPACKAGE");
    4808             : 
    4809         142 :         papszMDDup = nullptr;
    4810         151 :         for (char **papszIter = papszGeopackageMD; papszIter && *papszIter;
    4811             :              ++papszIter)
    4812             :         {
    4813           9 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4814             :         }
    4815             : 
    4816         284 :         GDALMultiDomainMetadata oLocalMDMD;
    4817         142 :         oLocalMDMD.SetMetadata(papszMDDup);
    4818         142 :         CSLDestroy(papszMDDup);
    4819         142 :         papszMDDup = nullptr;
    4820         142 :         psXMLNode = oLocalMDMD.Serialize();
    4821             : 
    4822         142 :         WriteMetadata(psXMLNode, nullptr);
    4823             :     }
    4824             : 
    4825         602 :     for (auto &poLayer : m_apoLayers)
    4826             :     {
    4827         237 :         const char *pszIdentifier = poLayer->GetMetadataItem("IDENTIFIER");
    4828         237 :         const char *pszDescription = poLayer->GetMetadataItem("DESCRIPTION");
    4829         237 :         if (pszIdentifier != nullptr)
    4830             :         {
    4831             :             char *pszSQL =
    4832           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4833             :                                 "WHERE lower(table_name) = lower('%q')",
    4834             :                                 pszIdentifier, poLayer->GetName());
    4835           3 :             SQLCommand(hDB, pszSQL);
    4836           3 :             sqlite3_free(pszSQL);
    4837             :         }
    4838         237 :         if (pszDescription != nullptr)
    4839             :         {
    4840             :             char *pszSQL =
    4841           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4842             :                                 "WHERE lower(table_name) = lower('%q')",
    4843             :                                 pszDescription, poLayer->GetName());
    4844           3 :             SQLCommand(hDB, pszSQL);
    4845           3 :             sqlite3_free(pszSQL);
    4846             :         }
    4847             : 
    4848         237 :         papszMDDup = nullptr;
    4849         625 :         for (char **papszIter = poLayer->GetMetadata(); papszIter && *papszIter;
    4850             :              ++papszIter)
    4851             :         {
    4852         388 :             if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4853           3 :                 continue;
    4854         385 :             if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4855           3 :                 continue;
    4856         382 :             if (STARTS_WITH_CI(*papszIter, "OLMD_FID64="))
    4857           0 :                 continue;
    4858         382 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4859             :         }
    4860             : 
    4861             :         {
    4862         237 :             GDALMultiDomainMetadata oLocalMDMD;
    4863         237 :             char **papszDomainList = poLayer->GetMetadataDomainList();
    4864         237 :             char **papszIter = papszDomainList;
    4865         237 :             oLocalMDMD.SetMetadata(papszMDDup);
    4866         513 :             while (papszIter && *papszIter)
    4867             :             {
    4868         276 :                 if (!EQUAL(*papszIter, ""))
    4869          60 :                     oLocalMDMD.SetMetadata(poLayer->GetMetadata(*papszIter),
    4870             :                                            *papszIter);
    4871         276 :                 papszIter++;
    4872             :             }
    4873         237 :             CSLDestroy(papszDomainList);
    4874         237 :             psXMLNode = oLocalMDMD.Serialize();
    4875             :         }
    4876             : 
    4877         237 :         CSLDestroy(papszMDDup);
    4878         237 :         papszMDDup = nullptr;
    4879             : 
    4880         237 :         WriteMetadata(psXMLNode, poLayer->GetName());
    4881             :     }
    4882             : }
    4883             : 
    4884             : /************************************************************************/
    4885             : /*                          GetMetadataItem()                           */
    4886             : /************************************************************************/
    4887             : 
    4888        1551 : const char *GDALGeoPackageDataset::GetMetadataItem(const char *pszName,
    4889             :                                                    const char *pszDomain)
    4890             : {
    4891        1551 :     pszDomain = CheckMetadataDomain(pszDomain);
    4892        1551 :     return CSLFetchNameValue(GetMetadata(pszDomain), pszName);
    4893             : }
    4894             : 
    4895             : /************************************************************************/
    4896             : /*                            SetMetadata()                             */
    4897             : /************************************************************************/
    4898             : 
    4899         146 : CPLErr GDALGeoPackageDataset::SetMetadata(char **papszMetadata,
    4900             :                                           const char *pszDomain)
    4901             : {
    4902         146 :     pszDomain = CheckMetadataDomain(pszDomain);
    4903         146 :     m_bMetadataDirty = true;
    4904         146 :     GetMetadata(); /* force loading from storage if needed */
    4905         146 :     return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
    4906             : }
    4907             : 
    4908             : /************************************************************************/
    4909             : /*                          SetMetadataItem()                           */
    4910             : /************************************************************************/
    4911             : 
    4912          21 : CPLErr GDALGeoPackageDataset::SetMetadataItem(const char *pszName,
    4913             :                                               const char *pszValue,
    4914             :                                               const char *pszDomain)
    4915             : {
    4916          21 :     pszDomain = CheckMetadataDomain(pszDomain);
    4917          21 :     m_bMetadataDirty = true;
    4918          21 :     GetMetadata(); /* force loading from storage if needed */
    4919          21 :     return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    4920             : }
    4921             : 
    4922             : /************************************************************************/
    4923             : /*                                Create()                              */
    4924             : /************************************************************************/
    4925             : 
    4926         892 : int GDALGeoPackageDataset::Create(const char *pszFilename, int nXSize,
    4927             :                                   int nYSize, int nBandsIn, GDALDataType eDT,
    4928             :                                   char **papszOptions)
    4929             : {
    4930        1784 :     CPLString osCommand;
    4931             : 
    4932             :     /* First, ensure there isn't any such file yet. */
    4933             :     VSIStatBufL sStatBuf;
    4934             : 
    4935         892 :     if (nBandsIn != 0)
    4936             :     {
    4937         224 :         if (eDT == GDT_Byte)
    4938             :         {
    4939         154 :             if (nBandsIn != 1 && nBandsIn != 2 && nBandsIn != 3 &&
    4940             :                 nBandsIn != 4)
    4941             :             {
    4942           1 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4943             :                          "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), "
    4944             :                          "3 (RGB) or 4 (RGBA) band dataset supported for "
    4945             :                          "Byte datatype");
    4946           1 :                 return FALSE;
    4947             :             }
    4948             :         }
    4949          70 :         else if (eDT == GDT_Int16 || eDT == GDT_UInt16 || eDT == GDT_Float32)
    4950             :         {
    4951          43 :             if (nBandsIn != 1)
    4952             :             {
    4953           3 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4954             :                          "Only single band dataset supported for non Byte "
    4955             :                          "datatype");
    4956           3 :                 return FALSE;
    4957             :             }
    4958             :         }
    4959             :         else
    4960             :         {
    4961          27 :             CPLError(CE_Failure, CPLE_NotSupported,
    4962             :                      "Only Byte, Int16, UInt16 or Float32 supported");
    4963          27 :             return FALSE;
    4964             :         }
    4965             :     }
    4966             : 
    4967         861 :     const size_t nFilenameLen = strlen(pszFilename);
    4968         861 :     const bool bGpkgZip =
    4969         856 :         (nFilenameLen > strlen(".gpkg.zip") &&
    4970        1717 :          !STARTS_WITH(pszFilename, "/vsizip/") &&
    4971         856 :          EQUAL(pszFilename + nFilenameLen - strlen(".gpkg.zip"), ".gpkg.zip"));
    4972             : 
    4973             :     const bool bUseTempFile =
    4974         862 :         bGpkgZip || (CPLTestBool(CPLGetConfigOption(
    4975           1 :                          "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", "NO")) &&
    4976           1 :                      (VSIHasOptimizedReadMultiRange(pszFilename) != FALSE ||
    4977           1 :                       EQUAL(CPLGetConfigOption(
    4978             :                                 "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", ""),
    4979         861 :                             "FORCED")));
    4980             : 
    4981         861 :     bool bFileExists = false;
    4982         861 :     if (VSIStatL(pszFilename, &sStatBuf) == 0)
    4983             :     {
    4984          10 :         bFileExists = true;
    4985          20 :         if (nBandsIn == 0 || bUseTempFile ||
    4986          10 :             !CPLTestBool(
    4987             :                 CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")))
    4988             :         {
    4989           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    4990             :                      "A file system object called '%s' already exists.",
    4991             :                      pszFilename);
    4992             : 
    4993           0 :             return FALSE;
    4994             :         }
    4995             :     }
    4996             : 
    4997         861 :     if (bUseTempFile)
    4998             :     {
    4999           3 :         if (bGpkgZip)
    5000             :         {
    5001           2 :             std::string osFilenameInZip(CPLGetFilename(pszFilename));
    5002           2 :             osFilenameInZip.resize(osFilenameInZip.size() - strlen(".zip"));
    5003             :             m_osFinalFilename =
    5004           2 :                 std::string("/vsizip/{") + pszFilename + "}/" + osFilenameInZip;
    5005             :         }
    5006             :         else
    5007             :         {
    5008           1 :             m_osFinalFilename = pszFilename;
    5009             :         }
    5010           3 :         m_pszFilename = CPLStrdup(
    5011           6 :             CPLGenerateTempFilenameSafe(CPLGetFilename(pszFilename)).c_str());
    5012           3 :         CPLDebug("GPKG", "Creating temporary file %s", m_pszFilename);
    5013             :     }
    5014             :     else
    5015             :     {
    5016         858 :         m_pszFilename = CPLStrdup(pszFilename);
    5017             :     }
    5018         861 :     m_bNew = true;
    5019         861 :     eAccess = GA_Update;
    5020         861 :     m_bDateTimeWithTZ =
    5021         861 :         EQUAL(CSLFetchNameValueDef(papszOptions, "DATETIME_FORMAT", "WITH_TZ"),
    5022             :               "WITH_TZ");
    5023             : 
    5024             :     // for test/debug purposes only. true is the nominal value
    5025         861 :     m_bPNGSupports2Bands =
    5026         861 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_2BANDS", "TRUE"));
    5027         861 :     m_bPNGSupportsCT =
    5028         861 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_CT", "TRUE"));
    5029             : 
    5030         861 :     if (!OpenOrCreateDB(bFileExists
    5031             :                             ? SQLITE_OPEN_READWRITE
    5032             :                             : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE))
    5033           7 :         return FALSE;
    5034             : 
    5035             :     /* Default to synchronous=off for performance for new file */
    5036        1698 :     if (!bFileExists &&
    5037         844 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5038             :     {
    5039         345 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5040             :     }
    5041             : 
    5042             :     /* OGR UTF-8 support. If we set the UTF-8 Pragma early on, it */
    5043             :     /* will be written into the main file and supported henceforth */
    5044         854 :     SQLCommand(hDB, "PRAGMA encoding = \"UTF-8\"");
    5045             : 
    5046         854 :     if (bFileExists)
    5047             :     {
    5048          10 :         VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
    5049          10 :         if (fp)
    5050             :         {
    5051             :             GByte abyHeader[100];
    5052          10 :             VSIFReadL(abyHeader, 1, sizeof(abyHeader), fp);
    5053          10 :             VSIFCloseL(fp);
    5054             : 
    5055          10 :             memcpy(&m_nApplicationId, abyHeader + knApplicationIdPos, 4);
    5056          10 :             m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    5057          10 :             memcpy(&m_nUserVersion, abyHeader + knUserVersionPos, 4);
    5058          10 :             m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    5059             : 
    5060          10 :             if (m_nApplicationId == GP10_APPLICATION_ID)
    5061             :             {
    5062           0 :                 CPLDebug("GPKG", "GeoPackage v1.0");
    5063             :             }
    5064          10 :             else if (m_nApplicationId == GP11_APPLICATION_ID)
    5065             :             {
    5066           0 :                 CPLDebug("GPKG", "GeoPackage v1.1");
    5067             :             }
    5068          10 :             else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    5069          10 :                      m_nUserVersion >= GPKG_1_2_VERSION)
    5070             :             {
    5071          10 :                 CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    5072          10 :                          (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    5073             :             }
    5074             :         }
    5075             : 
    5076          10 :         DetectSpatialRefSysColumns();
    5077             :     }
    5078             : 
    5079         854 :     const char *pszVersion = CSLFetchNameValue(papszOptions, "VERSION");
    5080         854 :     if (pszVersion && !EQUAL(pszVersion, "AUTO"))
    5081             :     {
    5082          40 :         if (EQUAL(pszVersion, "1.0"))
    5083             :         {
    5084           2 :             m_nApplicationId = GP10_APPLICATION_ID;
    5085           2 :             m_nUserVersion = 0;
    5086             :         }
    5087          38 :         else if (EQUAL(pszVersion, "1.1"))
    5088             :         {
    5089           1 :             m_nApplicationId = GP11_APPLICATION_ID;
    5090           1 :             m_nUserVersion = 0;
    5091             :         }
    5092          37 :         else if (EQUAL(pszVersion, "1.2"))
    5093             :         {
    5094          15 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5095          15 :             m_nUserVersion = GPKG_1_2_VERSION;
    5096             :         }
    5097          22 :         else if (EQUAL(pszVersion, "1.3"))
    5098             :         {
    5099           3 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5100           3 :             m_nUserVersion = GPKG_1_3_VERSION;
    5101             :         }
    5102          19 :         else if (EQUAL(pszVersion, "1.4"))
    5103             :         {
    5104          19 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5105          19 :             m_nUserVersion = GPKG_1_4_VERSION;
    5106             :         }
    5107             :     }
    5108             : 
    5109         854 :     SoftStartTransaction();
    5110             : 
    5111        1708 :     CPLString osSQL;
    5112         854 :     if (!bFileExists)
    5113             :     {
    5114             :         /* Requirement 10: A GeoPackage SHALL include a gpkg_spatial_ref_sys
    5115             :          * table */
    5116             :         /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5117             :         osSQL = "CREATE TABLE gpkg_spatial_ref_sys ("
    5118             :                 "srs_name TEXT NOT NULL,"
    5119             :                 "srs_id INTEGER NOT NULL PRIMARY KEY,"
    5120             :                 "organization TEXT NOT NULL,"
    5121             :                 "organization_coordsys_id INTEGER NOT NULL,"
    5122             :                 "definition  TEXT NOT NULL,"
    5123         844 :                 "description TEXT";
    5124         844 :         if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "CRS_WKT_EXTENSION",
    5125        1023 :                                              "NO")) ||
    5126         179 :             (nBandsIn != 0 && eDT != GDT_Byte))
    5127             :         {
    5128          42 :             m_bHasDefinition12_063 = true;
    5129          42 :             osSQL += ", definition_12_063 TEXT NOT NULL";
    5130          42 :             if (m_nUserVersion >= GPKG_1_4_VERSION)
    5131             :             {
    5132          40 :                 osSQL += ", epoch DOUBLE";
    5133          40 :                 m_bHasEpochColumn = true;
    5134             :             }
    5135             :         }
    5136             :         osSQL += ")"
    5137             :                  ";"
    5138             :                  /* Requirement 11: The gpkg_spatial_ref_sys table in a
    5139             :                     GeoPackage SHALL */
    5140             :                  /* contain a record for EPSG:4326, the geodetic WGS84 SRS */
    5141             :                  /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5142             : 
    5143             :                  "INSERT INTO gpkg_spatial_ref_sys ("
    5144             :                  "srs_name, srs_id, organization, organization_coordsys_id, "
    5145         844 :                  "definition, description";
    5146         844 :         if (m_bHasDefinition12_063)
    5147          42 :             osSQL += ", definition_12_063";
    5148             :         osSQL +=
    5149             :             ") VALUES ("
    5150             :             "'WGS 84 geodetic', 4326, 'EPSG', 4326, '"
    5151             :             "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS "
    5152             :             "84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],"
    5153             :             "AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY["
    5154             :             "\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY["
    5155             :             "\"EPSG\",\"9122\"]],AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\","
    5156             :             "EAST],AUTHORITY[\"EPSG\",\"4326\"]]"
    5157             :             "', 'longitude/latitude coordinates in decimal degrees on the WGS "
    5158         844 :             "84 spheroid'";
    5159         844 :         if (m_bHasDefinition12_063)
    5160             :             osSQL +=
    5161             :                 ", 'GEODCRS[\"WGS 84\", DATUM[\"World Geodetic System 1984\", "
    5162             :                 "ELLIPSOID[\"WGS 84\",6378137, 298.257223563, "
    5163             :                 "LENGTHUNIT[\"metre\", 1.0]]], PRIMEM[\"Greenwich\", 0.0, "
    5164             :                 "ANGLEUNIT[\"degree\",0.0174532925199433]], CS[ellipsoidal, "
    5165             :                 "2], AXIS[\"latitude\", north, ORDER[1]], AXIS[\"longitude\", "
    5166             :                 "east, ORDER[2]], ANGLEUNIT[\"degree\", 0.0174532925199433], "
    5167          42 :                 "ID[\"EPSG\", 4326]]'";
    5168             :         osSQL +=
    5169             :             ")"
    5170             :             ";"
    5171             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5172             :                SHALL */
    5173             :             /* contain a record with an srs_id of -1, an organization of “NONE”,
    5174             :              */
    5175             :             /* an organization_coordsys_id of -1, and definition “undefined” */
    5176             :             /* for undefined Cartesian coordinate reference systems */
    5177             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5178             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5179             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5180         844 :             "definition, description";
    5181         844 :         if (m_bHasDefinition12_063)
    5182          42 :             osSQL += ", definition_12_063";
    5183             :         osSQL += ") VALUES ("
    5184             :                  "'Undefined Cartesian SRS', -1, 'NONE', -1, 'undefined', "
    5185         844 :                  "'undefined Cartesian coordinate reference system'";
    5186         844 :         if (m_bHasDefinition12_063)
    5187          42 :             osSQL += ", 'undefined'";
    5188             :         osSQL +=
    5189             :             ")"
    5190             :             ";"
    5191             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5192             :                SHALL */
    5193             :             /* contain a record with an srs_id of 0, an organization of “NONE”,
    5194             :              */
    5195             :             /* an organization_coordsys_id of 0, and definition “undefined” */
    5196             :             /* for undefined geographic coordinate reference systems */
    5197             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5198             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5199             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5200         844 :             "definition, description";
    5201         844 :         if (m_bHasDefinition12_063)
    5202          42 :             osSQL += ", definition_12_063";
    5203             :         osSQL += ") VALUES ("
    5204             :                  "'Undefined geographic SRS', 0, 'NONE', 0, 'undefined', "
    5205         844 :                  "'undefined geographic coordinate reference system'";
    5206         844 :         if (m_bHasDefinition12_063)
    5207          42 :             osSQL += ", 'undefined'";
    5208             :         osSQL += ")"
    5209             :                  ";"
    5210             :                  /* Requirement 13: A GeoPackage file SHALL include a
    5211             :                     gpkg_contents table */
    5212             :                  /* http://opengis.github.io/geopackage/#_contents */
    5213             :                  "CREATE TABLE gpkg_contents ("
    5214             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5215             :                  "data_type TEXT NOT NULL,"
    5216             :                  "identifier TEXT UNIQUE,"
    5217             :                  "description TEXT DEFAULT '',"
    5218             :                  "last_change DATETIME NOT NULL DEFAULT "
    5219             :                  "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    5220             :                  "min_x DOUBLE, min_y DOUBLE,"
    5221             :                  "max_x DOUBLE, max_y DOUBLE,"
    5222             :                  "srs_id INTEGER,"
    5223             :                  "CONSTRAINT fk_gc_r_srs_id FOREIGN KEY (srs_id) REFERENCES "
    5224             :                  "gpkg_spatial_ref_sys(srs_id)"
    5225         844 :                  ")";
    5226             : 
    5227             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5228         844 :         if (CPLFetchBool(papszOptions, "ADD_GPKG_OGR_CONTENTS", true))
    5229             :         {
    5230         839 :             m_bHasGPKGOGRContents = true;
    5231             :             osSQL += ";"
    5232             :                      "CREATE TABLE gpkg_ogr_contents("
    5233             :                      "table_name TEXT NOT NULL PRIMARY KEY,"
    5234             :                      "feature_count INTEGER DEFAULT NULL"
    5235         839 :                      ")";
    5236             :         }
    5237             : #endif
    5238             : 
    5239             :         /* Requirement 21: A GeoPackage with a gpkg_contents table row with a
    5240             :          * “features” */
    5241             :         /* data_type SHALL contain a gpkg_geometry_columns table or updateable
    5242             :          * view */
    5243             :         /* http://opengis.github.io/geopackage/#_geometry_columns */
    5244             :         const bool bCreateGeometryColumns =
    5245         844 :             CPLTestBool(CPLGetConfigOption("CREATE_GEOMETRY_COLUMNS", "YES"));
    5246         844 :         if (bCreateGeometryColumns)
    5247             :         {
    5248         843 :             m_bHasGPKGGeometryColumns = true;
    5249         843 :             osSQL += ";";
    5250         843 :             osSQL += pszCREATE_GPKG_GEOMETRY_COLUMNS;
    5251             :         }
    5252             :     }
    5253             : 
    5254             :     const bool bCreateTriggers =
    5255         854 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "YES"));
    5256          10 :     if ((bFileExists && nBandsIn != 0 &&
    5257          10 :          SQLGetInteger(
    5258             :              hDB,
    5259             :              "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_tile_matrix_set' "
    5260             :              "AND type in ('table', 'view')",
    5261        1708 :              nullptr) == 0) ||
    5262         853 :         (!bFileExists &&
    5263         844 :          CPLTestBool(CPLGetConfigOption("CREATE_RASTER_TABLES", "YES"))))
    5264             :     {
    5265         844 :         if (!osSQL.empty())
    5266         843 :             osSQL += ";";
    5267             : 
    5268             :         /* From C.5. gpkg_tile_matrix_set Table 28. gpkg_tile_matrix_set Table
    5269             :          * Creation SQL  */
    5270             :         osSQL += "CREATE TABLE gpkg_tile_matrix_set ("
    5271             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5272             :                  "srs_id INTEGER NOT NULL,"
    5273             :                  "min_x DOUBLE NOT NULL,"
    5274             :                  "min_y DOUBLE NOT NULL,"
    5275             :                  "max_x DOUBLE NOT NULL,"
    5276             :                  "max_y DOUBLE NOT NULL,"
    5277             :                  "CONSTRAINT fk_gtms_table_name FOREIGN KEY (table_name) "
    5278             :                  "REFERENCES gpkg_contents(table_name),"
    5279             :                  "CONSTRAINT fk_gtms_srs FOREIGN KEY (srs_id) REFERENCES "
    5280             :                  "gpkg_spatial_ref_sys (srs_id)"
    5281             :                  ")"
    5282             :                  ";"
    5283             : 
    5284             :                  /* From C.6. gpkg_tile_matrix Table 29. gpkg_tile_matrix Table
    5285             :                     Creation SQL */
    5286             :                  "CREATE TABLE gpkg_tile_matrix ("
    5287             :                  "table_name TEXT NOT NULL,"
    5288             :                  "zoom_level INTEGER NOT NULL,"
    5289             :                  "matrix_width INTEGER NOT NULL,"
    5290             :                  "matrix_height INTEGER NOT NULL,"
    5291             :                  "tile_width INTEGER NOT NULL,"
    5292             :                  "tile_height INTEGER NOT NULL,"
    5293             :                  "pixel_x_size DOUBLE NOT NULL,"
    5294             :                  "pixel_y_size DOUBLE NOT NULL,"
    5295             :                  "CONSTRAINT pk_ttm PRIMARY KEY (table_name, zoom_level),"
    5296             :                  "CONSTRAINT fk_tmm_table_name FOREIGN KEY (table_name) "
    5297             :                  "REFERENCES gpkg_contents(table_name)"
    5298         844 :                  ")";
    5299             : 
    5300         844 :         if (bCreateTriggers)
    5301             :         {
    5302             :             /* From D.1. gpkg_tile_matrix Table 39. gpkg_tile_matrix Trigger
    5303             :              * Definition SQL */
    5304         844 :             const char *pszTileMatrixTrigger =
    5305             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_insert' "
    5306             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5307             :                 "FOR EACH ROW BEGIN "
    5308             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5309             :                 "violates constraint: zoom_level cannot be less than 0') "
    5310             :                 "WHERE (NEW.zoom_level < 0); "
    5311             :                 "END; "
    5312             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_update' "
    5313             :                 "BEFORE UPDATE of zoom_level ON 'gpkg_tile_matrix' "
    5314             :                 "FOR EACH ROW BEGIN "
    5315             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5316             :                 "violates constraint: zoom_level cannot be less than 0') "
    5317             :                 "WHERE (NEW.zoom_level < 0); "
    5318             :                 "END; "
    5319             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_insert' "
    5320             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5321             :                 "FOR EACH ROW BEGIN "
    5322             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5323             :                 "violates constraint: matrix_width cannot be less than 1') "
    5324             :                 "WHERE (NEW.matrix_width < 1); "
    5325             :                 "END; "
    5326             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_update' "
    5327             :                 "BEFORE UPDATE OF matrix_width ON 'gpkg_tile_matrix' "
    5328             :                 "FOR EACH ROW BEGIN "
    5329             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5330             :                 "violates constraint: matrix_width cannot be less than 1') "
    5331             :                 "WHERE (NEW.matrix_width < 1); "
    5332             :                 "END; "
    5333             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_insert' "
    5334             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5335             :                 "FOR EACH ROW BEGIN "
    5336             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5337             :                 "violates constraint: matrix_height cannot be less than 1') "
    5338             :                 "WHERE (NEW.matrix_height < 1); "
    5339             :                 "END; "
    5340             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_update' "
    5341             :                 "BEFORE UPDATE OF matrix_height ON 'gpkg_tile_matrix' "
    5342             :                 "FOR EACH ROW BEGIN "
    5343             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5344             :                 "violates constraint: matrix_height cannot be less than 1') "
    5345             :                 "WHERE (NEW.matrix_height < 1); "
    5346             :                 "END; "
    5347             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_insert' "
    5348             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5349             :                 "FOR EACH ROW BEGIN "
    5350             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5351             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5352             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5353             :                 "END; "
    5354             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_update' "
    5355             :                 "BEFORE UPDATE OF pixel_x_size ON 'gpkg_tile_matrix' "
    5356             :                 "FOR EACH ROW BEGIN "
    5357             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5358             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5359             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5360             :                 "END; "
    5361             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_insert' "
    5362             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5363             :                 "FOR EACH ROW BEGIN "
    5364             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5365             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5366             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5367             :                 "END; "
    5368             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_update' "
    5369             :                 "BEFORE UPDATE OF pixel_y_size ON 'gpkg_tile_matrix' "
    5370             :                 "FOR EACH ROW BEGIN "
    5371             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5372             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5373             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5374             :                 "END;";
    5375         844 :             osSQL += ";";
    5376         844 :             osSQL += pszTileMatrixTrigger;
    5377             :         }
    5378             :     }
    5379             : 
    5380         854 :     if (!osSQL.empty() && OGRERR_NONE != SQLCommand(hDB, osSQL))
    5381           1 :         return FALSE;
    5382             : 
    5383         853 :     if (!bFileExists)
    5384             :     {
    5385             :         const char *pszMetadataTables =
    5386         843 :             CSLFetchNameValue(papszOptions, "METADATA_TABLES");
    5387         843 :         if (pszMetadataTables)
    5388           9 :             m_nCreateMetadataTables = int(CPLTestBool(pszMetadataTables));
    5389             : 
    5390         843 :         if (m_nCreateMetadataTables == TRUE && !CreateMetadataTables())
    5391           0 :             return FALSE;
    5392             : 
    5393         843 :         if (m_bHasDefinition12_063)
    5394             :         {
    5395          84 :             if (OGRERR_NONE != CreateExtensionsTableIfNecessary() ||
    5396             :                 OGRERR_NONE !=
    5397          42 :                     SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5398             :                                     "(table_name, column_name, extension_name, "
    5399             :                                     "definition, scope) "
    5400             :                                     "VALUES "
    5401             :                                     "('gpkg_spatial_ref_sys', "
    5402             :                                     "'definition_12_063', 'gpkg_crs_wkt', "
    5403             :                                     "'http://www.geopackage.org/spec120/"
    5404             :                                     "#extension_crs_wkt', 'read-write')"))
    5405             :             {
    5406           0 :                 return FALSE;
    5407             :             }
    5408          42 :             if (m_bHasEpochColumn)
    5409             :             {
    5410          40 :                 if (OGRERR_NONE !=
    5411          40 :                         SQLCommand(
    5412             :                             hDB, "UPDATE gpkg_extensions SET extension_name = "
    5413             :                                  "'gpkg_crs_wkt_1_1' "
    5414          80 :                                  "WHERE extension_name = 'gpkg_crs_wkt'") ||
    5415             :                     OGRERR_NONE !=
    5416          40 :                         SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5417             :                                         "(table_name, column_name, "
    5418             :                                         "extension_name, definition, scope) "
    5419             :                                         "VALUES "
    5420             :                                         "('gpkg_spatial_ref_sys', 'epoch', "
    5421             :                                         "'gpkg_crs_wkt_1_1', "
    5422             :                                         "'http://www.geopackage.org/spec/"
    5423             :                                         "#extension_crs_wkt', "
    5424             :                                         "'read-write')"))
    5425             :                 {
    5426           0 :                     return FALSE;
    5427             :                 }
    5428             :             }
    5429             :         }
    5430             :     }
    5431             : 
    5432         853 :     if (nBandsIn != 0)
    5433             :     {
    5434         188 :         const std::string osTableName = CPLGetBasenameSafe(m_pszFilename);
    5435             :         m_osRasterTable = CSLFetchNameValueDef(papszOptions, "RASTER_TABLE",
    5436         188 :                                                osTableName.c_str());
    5437         188 :         if (m_osRasterTable.empty())
    5438             :         {
    5439           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5440             :                      "RASTER_TABLE must be set to a non empty value");
    5441           0 :             return FALSE;
    5442             :         }
    5443         188 :         m_bIdentifierAsCO =
    5444         188 :             CSLFetchNameValue(papszOptions, "RASTER_IDENTIFIER") != nullptr;
    5445             :         m_osIdentifier = CSLFetchNameValueDef(papszOptions, "RASTER_IDENTIFIER",
    5446         188 :                                               m_osRasterTable);
    5447         188 :         m_bDescriptionAsCO =
    5448         188 :             CSLFetchNameValue(papszOptions, "RASTER_DESCRIPTION") != nullptr;
    5449             :         m_osDescription =
    5450         188 :             CSLFetchNameValueDef(papszOptions, "RASTER_DESCRIPTION", "");
    5451         188 :         SetDataType(eDT);
    5452         188 :         if (eDT == GDT_Int16)
    5453          16 :             SetGlobalOffsetScale(-32768.0, 1.0);
    5454             : 
    5455             :         /* From C.7. sample_tile_pyramid (Informative) Table 31. EXAMPLE: tiles
    5456             :          * table Create Table SQL (Informative) */
    5457             :         char *pszSQL =
    5458         188 :             sqlite3_mprintf("CREATE TABLE \"%w\" ("
    5459             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    5460             :                             "zoom_level INTEGER NOT NULL,"
    5461             :                             "tile_column INTEGER NOT NULL,"
    5462             :                             "tile_row INTEGER NOT NULL,"
    5463             :                             "tile_data BLOB NOT NULL,"
    5464             :                             "UNIQUE (zoom_level, tile_column, tile_row)"
    5465             :                             ")",
    5466             :                             m_osRasterTable.c_str());
    5467         188 :         osSQL = pszSQL;
    5468         188 :         sqlite3_free(pszSQL);
    5469             : 
    5470         188 :         if (bCreateTriggers)
    5471             :         {
    5472         188 :             osSQL += ";";
    5473         188 :             osSQL += CreateRasterTriggersSQL(m_osRasterTable);
    5474             :         }
    5475             : 
    5476         188 :         OGRErr eErr = SQLCommand(hDB, osSQL);
    5477         188 :         if (OGRERR_NONE != eErr)
    5478           0 :             return FALSE;
    5479             : 
    5480         188 :         const char *pszTF = CSLFetchNameValue(papszOptions, "TILE_FORMAT");
    5481         188 :         if (eDT == GDT_Int16 || eDT == GDT_UInt16)
    5482             :         {
    5483          27 :             m_eTF = GPKG_TF_PNG_16BIT;
    5484          27 :             if (pszTF)
    5485             :             {
    5486           1 :                 if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "PNG"))
    5487             :                 {
    5488           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5489             :                              "Only AUTO or PNG supported "
    5490             :                              "as tile format for Int16 / UInt16");
    5491             :                 }
    5492             :             }
    5493             :         }
    5494         161 :         else if (eDT == GDT_Float32)
    5495             :         {
    5496          13 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    5497          13 :             if (pszTF)
    5498             :             {
    5499           5 :                 if (EQUAL(pszTF, "PNG"))
    5500           5 :                     m_eTF = GPKG_TF_PNG_16BIT;
    5501           0 :                 else if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "TIFF"))
    5502             :                 {
    5503           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5504             :                              "Only AUTO, PNG or TIFF supported "
    5505             :                              "as tile format for Float32");
    5506             :                 }
    5507             :             }
    5508             :         }
    5509             :         else
    5510             :         {
    5511         148 :             if (pszTF)
    5512             :             {
    5513          71 :                 m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    5514          71 :                 if (nBandsIn == 1 && m_eTF != GPKG_TF_PNG)
    5515           7 :                     m_bMetadataDirty = true;
    5516             :             }
    5517          77 :             else if (nBandsIn == 1)
    5518          66 :                 m_eTF = GPKG_TF_PNG;
    5519             :         }
    5520             : 
    5521         188 :         if (eDT != GDT_Byte)
    5522             :         {
    5523          40 :             if (!CreateTileGriddedTable(papszOptions))
    5524           0 :                 return FALSE;
    5525             :         }
    5526             : 
    5527         188 :         nRasterXSize = nXSize;
    5528         188 :         nRasterYSize = nYSize;
    5529             : 
    5530             :         const char *pszTileSize =
    5531         188 :             CSLFetchNameValueDef(papszOptions, "BLOCKSIZE", "256");
    5532             :         const char *pszTileWidth =
    5533         188 :             CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", pszTileSize);
    5534             :         const char *pszTileHeight =
    5535         188 :             CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", pszTileSize);
    5536         188 :         int nTileWidth = atoi(pszTileWidth);
    5537         188 :         int nTileHeight = atoi(pszTileHeight);
    5538         188 :         if ((nTileWidth < 8 || nTileWidth > 4096 || nTileHeight < 8 ||
    5539         376 :              nTileHeight > 4096) &&
    5540           1 :             !CPLTestBool(CPLGetConfigOption("GPKG_ALLOW_CRAZY_SETTINGS", "NO")))
    5541             :         {
    5542           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5543             :                      "Invalid block dimensions: %dx%d", nTileWidth,
    5544             :                      nTileHeight);
    5545           0 :             return FALSE;
    5546             :         }
    5547             : 
    5548         509 :         for (int i = 1; i <= nBandsIn; i++)
    5549             :         {
    5550         321 :             SetBand(i, std::make_unique<GDALGeoPackageRasterBand>(
    5551             :                            this, nTileWidth, nTileHeight));
    5552             :         }
    5553             : 
    5554         188 :         GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL",
    5555             :                                         "IMAGE_STRUCTURE");
    5556         188 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", m_osIdentifier);
    5557         188 :         if (!m_osDescription.empty())
    5558           1 :             GDALPamDataset::SetMetadataItem("DESCRIPTION", m_osDescription);
    5559             : 
    5560         188 :         ParseCompressionOptions(papszOptions);
    5561             : 
    5562         188 :         if (m_eTF == GPKG_TF_WEBP)
    5563             :         {
    5564          10 :             if (!RegisterWebPExtension())
    5565           0 :                 return FALSE;
    5566             :         }
    5567             : 
    5568             :         m_osTilingScheme =
    5569         188 :             CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5570         188 :         if (!EQUAL(m_osTilingScheme, "CUSTOM"))
    5571             :         {
    5572          22 :             const auto poTS = GetTilingScheme(m_osTilingScheme);
    5573          22 :             if (!poTS)
    5574           0 :                 return FALSE;
    5575             : 
    5576          43 :             if (nTileWidth != poTS->nTileWidth ||
    5577          21 :                 nTileHeight != poTS->nTileHeight)
    5578             :             {
    5579           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    5580             :                          "Tile dimension should be %dx%d for %s tiling scheme",
    5581           1 :                          poTS->nTileWidth, poTS->nTileHeight,
    5582             :                          m_osTilingScheme.c_str());
    5583           1 :                 return FALSE;
    5584             :             }
    5585             : 
    5586             :             const char *pszZoomLevel =
    5587          21 :                 CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    5588          21 :             if (pszZoomLevel)
    5589             :             {
    5590           1 :                 m_nZoomLevel = atoi(pszZoomLevel);
    5591           1 :                 int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    5592           1 :                 while ((1 << nMaxZoomLevelForThisTM) >
    5593           2 :                            INT_MAX / poTS->nTileXCountZoomLevel0 ||
    5594           1 :                        (1 << nMaxZoomLevelForThisTM) >
    5595           1 :                            INT_MAX / poTS->nTileYCountZoomLevel0)
    5596             :                 {
    5597           0 :                     --nMaxZoomLevelForThisTM;
    5598             :                 }
    5599             : 
    5600           1 :                 if (m_nZoomLevel < 0 || m_nZoomLevel > nMaxZoomLevelForThisTM)
    5601             :                 {
    5602           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    5603             :                              "ZOOM_LEVEL = %s is invalid. It should be in "
    5604             :                              "[0,%d] range",
    5605             :                              pszZoomLevel, nMaxZoomLevelForThisTM);
    5606           0 :                     return FALSE;
    5607             :                 }
    5608             :             }
    5609             : 
    5610             :             // Implicitly sets SRS.
    5611          21 :             OGRSpatialReference oSRS;
    5612          21 :             if (oSRS.importFromEPSG(poTS->nEPSGCode) != OGRERR_NONE)
    5613           0 :                 return FALSE;
    5614          21 :             char *pszWKT = nullptr;
    5615          21 :             oSRS.exportToWkt(&pszWKT);
    5616          21 :             SetProjection(pszWKT);
    5617          21 :             CPLFree(pszWKT);
    5618             :         }
    5619             :         else
    5620             :         {
    5621         166 :             if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5622             :             {
    5623           0 :                 CPLError(
    5624             :                     CE_Failure, CPLE_NotSupported,
    5625             :                     "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5626           0 :                 return false;
    5627             :             }
    5628             :         }
    5629             :     }
    5630             : 
    5631         852 :     if (bFileExists && nBandsIn > 0 && eDT == GDT_Byte)
    5632             :     {
    5633             :         // If there was an ogr_empty_table table, we can remove it
    5634           9 :         RemoveOGREmptyTable();
    5635             :     }
    5636             : 
    5637         852 :     SoftCommitTransaction();
    5638             : 
    5639             :     /* Requirement 2 */
    5640             :     /* We have to do this after there's some content so the database file */
    5641             :     /* is not zero length */
    5642         852 :     SetApplicationAndUserVersionId();
    5643             : 
    5644             :     /* Default to synchronous=off for performance for new file */
    5645        1694 :     if (!bFileExists &&
    5646         842 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5647             :     {
    5648         345 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5649             :     }
    5650             : 
    5651         852 :     return TRUE;
    5652             : }
    5653             : 
    5654             : /************************************************************************/
    5655             : /*                        RemoveOGREmptyTable()                         */
    5656             : /************************************************************************/
    5657             : 
    5658         665 : void GDALGeoPackageDataset::RemoveOGREmptyTable()
    5659             : {
    5660             :     // Run with sqlite3_exec since we don't want errors to be emitted
    5661         665 :     sqlite3_exec(hDB, "DROP TABLE IF EXISTS ogr_empty_table", nullptr, nullptr,
    5662             :                  nullptr);
    5663         665 :     sqlite3_exec(
    5664             :         hDB, "DELETE FROM gpkg_contents WHERE table_name = 'ogr_empty_table'",
    5665             :         nullptr, nullptr, nullptr);
    5666             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5667         665 :     if (m_bHasGPKGOGRContents)
    5668             :     {
    5669         651 :         sqlite3_exec(hDB,
    5670             :                      "DELETE FROM gpkg_ogr_contents WHERE "
    5671             :                      "table_name = 'ogr_empty_table'",
    5672             :                      nullptr, nullptr, nullptr);
    5673             :     }
    5674             : #endif
    5675         665 :     sqlite3_exec(hDB,
    5676             :                  "DELETE FROM gpkg_geometry_columns WHERE "
    5677             :                  "table_name = 'ogr_empty_table'",
    5678             :                  nullptr, nullptr, nullptr);
    5679         665 : }
    5680             : 
    5681             : /************************************************************************/
    5682             : /*                        CreateTileGriddedTable()                      */
    5683             : /************************************************************************/
    5684             : 
    5685          40 : bool GDALGeoPackageDataset::CreateTileGriddedTable(char **papszOptions)
    5686             : {
    5687          80 :     CPLString osSQL;
    5688          40 :     if (!HasGriddedCoverageAncillaryTable())
    5689             :     {
    5690             :         // It doesn't exist. So create gpkg_extensions table if necessary, and
    5691             :         // gpkg_2d_gridded_coverage_ancillary & gpkg_2d_gridded_tile_ancillary,
    5692             :         // and register them as extensions.
    5693          40 :         if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    5694           0 :             return false;
    5695             : 
    5696             :         // Req 1 /table-defs/coverage-ancillary
    5697             :         osSQL = "CREATE TABLE gpkg_2d_gridded_coverage_ancillary ("
    5698             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5699             :                 "tile_matrix_set_name TEXT NOT NULL UNIQUE,"
    5700             :                 "datatype TEXT NOT NULL DEFAULT 'integer',"
    5701             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5702             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5703             :                 "precision REAL DEFAULT 1.0,"
    5704             :                 "data_null REAL,"
    5705             :                 "grid_cell_encoding TEXT DEFAULT 'grid-value-is-center',"
    5706             :                 "uom TEXT,"
    5707             :                 "field_name TEXT DEFAULT 'Height',"
    5708             :                 "quantity_definition TEXT DEFAULT 'Height',"
    5709             :                 "CONSTRAINT fk_g2dgtct_name FOREIGN KEY(tile_matrix_set_name) "
    5710             :                 "REFERENCES gpkg_tile_matrix_set ( table_name ) "
    5711             :                 "CHECK (datatype in ('integer','float')))"
    5712             :                 ";"
    5713             :                 // Requirement 2 /table-defs/tile-ancillary
    5714             :                 "CREATE TABLE gpkg_2d_gridded_tile_ancillary ("
    5715             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5716             :                 "tpudt_name TEXT NOT NULL,"
    5717             :                 "tpudt_id INTEGER NOT NULL,"
    5718             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5719             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5720             :                 "min REAL DEFAULT NULL,"
    5721             :                 "max REAL DEFAULT NULL,"
    5722             :                 "mean REAL DEFAULT NULL,"
    5723             :                 "std_dev REAL DEFAULT NULL,"
    5724             :                 "CONSTRAINT fk_g2dgtat_name FOREIGN KEY (tpudt_name) "
    5725             :                 "REFERENCES gpkg_contents(table_name),"
    5726             :                 "UNIQUE (tpudt_name, tpudt_id))"
    5727             :                 ";"
    5728             :                 // Requirement 6 /gpkg-extensions
    5729             :                 "INSERT INTO gpkg_extensions "
    5730             :                 "(table_name, column_name, extension_name, definition, scope) "
    5731             :                 "VALUES ('gpkg_2d_gridded_coverage_ancillary', NULL, "
    5732             :                 "'gpkg_2d_gridded_coverage', "
    5733             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5734             :                 "'read-write')"
    5735             :                 ";"
    5736             :                 // Requirement 6 /gpkg-extensions
    5737             :                 "INSERT INTO gpkg_extensions "
    5738             :                 "(table_name, column_name, extension_name, definition, scope) "
    5739             :                 "VALUES ('gpkg_2d_gridded_tile_ancillary', NULL, "
    5740             :                 "'gpkg_2d_gridded_coverage', "
    5741             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5742             :                 "'read-write')"
    5743          40 :                 ";";
    5744             :     }
    5745             : 
    5746             :     // Requirement 6 /gpkg-extensions
    5747          40 :     char *pszSQL = sqlite3_mprintf(
    5748             :         "INSERT INTO gpkg_extensions "
    5749             :         "(table_name, column_name, extension_name, definition, scope) "
    5750             :         "VALUES ('%q', 'tile_data', "
    5751             :         "'gpkg_2d_gridded_coverage', "
    5752             :         "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5753             :         "'read-write')",
    5754             :         m_osRasterTable.c_str());
    5755          40 :     osSQL += pszSQL;
    5756          40 :     osSQL += ";";
    5757          40 :     sqlite3_free(pszSQL);
    5758             : 
    5759             :     // Requirement 7 /gpkg-2d-gridded-coverage-ancillary
    5760             :     // Requirement 8 /gpkg-2d-gridded-coverage-ancillary-set-name
    5761             :     // Requirement 9 /gpkg-2d-gridded-coverage-ancillary-datatype
    5762          40 :     m_dfPrecision =
    5763          40 :         CPLAtof(CSLFetchNameValueDef(papszOptions, "PRECISION", "1"));
    5764             :     CPLString osGridCellEncoding(CSLFetchNameValueDef(
    5765          80 :         papszOptions, "GRID_CELL_ENCODING", "grid-value-is-center"));
    5766          40 :     m_bGridCellEncodingAsCO =
    5767          40 :         CSLFetchNameValue(papszOptions, "GRID_CELL_ENCODING") != nullptr;
    5768          80 :     CPLString osUom(CSLFetchNameValueDef(papszOptions, "UOM", ""));
    5769             :     CPLString osFieldName(
    5770          80 :         CSLFetchNameValueDef(papszOptions, "FIELD_NAME", "Height"));
    5771             :     CPLString osQuantityDefinition(
    5772          80 :         CSLFetchNameValueDef(papszOptions, "QUANTITY_DEFINITION", "Height"));
    5773             : 
    5774         121 :     pszSQL = sqlite3_mprintf(
    5775             :         "INSERT INTO gpkg_2d_gridded_coverage_ancillary "
    5776             :         "(tile_matrix_set_name, datatype, scale, offset, precision, "
    5777             :         "grid_cell_encoding, uom, field_name, quantity_definition) "
    5778             :         "VALUES (%Q, '%s', %.17g, %.17g, %.17g, %Q, %Q, %Q, %Q)",
    5779             :         m_osRasterTable.c_str(),
    5780          40 :         (m_eTF == GPKG_TF_PNG_16BIT) ? "integer" : "float", m_dfScale,
    5781             :         m_dfOffset, m_dfPrecision, osGridCellEncoding.c_str(),
    5782          41 :         osUom.empty() ? nullptr : osUom.c_str(), osFieldName.c_str(),
    5783             :         osQuantityDefinition.c_str());
    5784          40 :     m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary = pszSQL;
    5785          40 :     sqlite3_free(pszSQL);
    5786             : 
    5787             :     // Requirement 3 /gpkg-spatial-ref-sys-row
    5788             :     auto oResultTable = SQLQuery(
    5789          80 :         hDB, "SELECT * FROM gpkg_spatial_ref_sys WHERE srs_id = 4979 LIMIT 2");
    5790          40 :     bool bHasEPSG4979 = (oResultTable && oResultTable->RowCount() == 1);
    5791          40 :     if (!bHasEPSG4979)
    5792             :     {
    5793          41 :         if (!m_bHasDefinition12_063 &&
    5794           1 :             !ConvertGpkgSpatialRefSysToExtensionWkt2(/*bForceEpoch=*/false))
    5795             :         {
    5796           0 :             return false;
    5797             :         }
    5798             : 
    5799             :         // This is WKT 2...
    5800          40 :         const char *pszWKT =
    5801             :             "GEODCRS[\"WGS 84\","
    5802             :             "DATUM[\"World Geodetic System 1984\","
    5803             :             "  ELLIPSOID[\"WGS 84\",6378137,298.257223563,"
    5804             :             "LENGTHUNIT[\"metre\",1.0]]],"
    5805             :             "CS[ellipsoidal,3],"
    5806             :             "  AXIS[\"latitude\",north,ORDER[1],ANGLEUNIT[\"degree\","
    5807             :             "0.0174532925199433]],"
    5808             :             "  AXIS[\"longitude\",east,ORDER[2],ANGLEUNIT[\"degree\","
    5809             :             "0.0174532925199433]],"
    5810             :             "  AXIS[\"ellipsoidal height\",up,ORDER[3],"
    5811             :             "LENGTHUNIT[\"metre\",1.0]],"
    5812             :             "ID[\"EPSG\",4979]]";
    5813             : 
    5814          40 :         pszSQL = sqlite3_mprintf(
    5815             :             "INSERT INTO gpkg_spatial_ref_sys "
    5816             :             "(srs_name,srs_id,organization,organization_coordsys_id,"
    5817             :             "definition,definition_12_063) VALUES "
    5818             :             "('WGS 84 3D', 4979, 'EPSG', 4979, 'undefined', '%q')",
    5819             :             pszWKT);
    5820          40 :         osSQL += ";";
    5821          40 :         osSQL += pszSQL;
    5822          40 :         sqlite3_free(pszSQL);
    5823             :     }
    5824             : 
    5825          40 :     return SQLCommand(hDB, osSQL) == OGRERR_NONE;
    5826             : }
    5827             : 
    5828             : /************************************************************************/
    5829             : /*                    HasGriddedCoverageAncillaryTable()                */
    5830             : /************************************************************************/
    5831             : 
    5832          44 : bool GDALGeoPackageDataset::HasGriddedCoverageAncillaryTable()
    5833             : {
    5834             :     auto oResultTable = SQLQuery(
    5835             :         hDB, "SELECT * FROM sqlite_master WHERE type IN ('table', 'view') AND "
    5836          44 :              "name = 'gpkg_2d_gridded_coverage_ancillary'");
    5837          44 :     bool bHasTable = (oResultTable && oResultTable->RowCount() == 1);
    5838          88 :     return bHasTable;
    5839             : }
    5840             : 
    5841             : /************************************************************************/
    5842             : /*                      GetUnderlyingDataset()                          */
    5843             : /************************************************************************/
    5844             : 
    5845           3 : static GDALDataset *GetUnderlyingDataset(GDALDataset *poSrcDS)
    5846             : {
    5847           3 :     if (auto poVRTDS = dynamic_cast<VRTDataset *>(poSrcDS))
    5848             :     {
    5849           0 :         auto poTmpDS = poVRTDS->GetSingleSimpleSource();
    5850           0 :         if (poTmpDS)
    5851           0 :             return poTmpDS;
    5852             :     }
    5853             : 
    5854           3 :     return poSrcDS;
    5855             : }
    5856             : 
    5857             : /************************************************************************/
    5858             : /*                            CreateCopy()                              */
    5859             : /************************************************************************/
    5860             : 
    5861             : typedef struct
    5862             : {
    5863             :     const char *pszName;
    5864             :     GDALResampleAlg eResampleAlg;
    5865             : } WarpResamplingAlg;
    5866             : 
    5867             : static const WarpResamplingAlg asResamplingAlg[] = {
    5868             :     {"NEAREST", GRA_NearestNeighbour},
    5869             :     {"BILINEAR", GRA_Bilinear},
    5870             :     {"CUBIC", GRA_Cubic},
    5871             :     {"CUBICSPLINE", GRA_CubicSpline},
    5872             :     {"LANCZOS", GRA_Lanczos},
    5873             :     {"MODE", GRA_Mode},
    5874             :     {"AVERAGE", GRA_Average},
    5875             :     {"RMS", GRA_RMS},
    5876             : };
    5877             : 
    5878         160 : GDALDataset *GDALGeoPackageDataset::CreateCopy(const char *pszFilename,
    5879             :                                                GDALDataset *poSrcDS,
    5880             :                                                int bStrict, char **papszOptions,
    5881             :                                                GDALProgressFunc pfnProgress,
    5882             :                                                void *pProgressData)
    5883             : {
    5884         160 :     const int nBands = poSrcDS->GetRasterCount();
    5885         160 :     if (nBands == 0)
    5886             :     {
    5887           2 :         GDALDataset *poDS = nullptr;
    5888             :         GDALDriver *poThisDriver =
    5889           2 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5890           2 :         if (poThisDriver != nullptr)
    5891             :         {
    5892           2 :             poDS = poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS,
    5893             :                                                    bStrict, papszOptions,
    5894             :                                                    pfnProgress, pProgressData);
    5895             :         }
    5896           2 :         return poDS;
    5897             :     }
    5898             : 
    5899             :     const char *pszTilingScheme =
    5900         158 :         CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5901             : 
    5902         316 :     CPLStringList apszUpdatedOptions(CSLDuplicate(papszOptions));
    5903         158 :     if (CPLTestBool(
    5904         164 :             CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")) &&
    5905           6 :         CSLFetchNameValue(papszOptions, "RASTER_TABLE") == nullptr)
    5906             :     {
    5907             :         const std::string osBasename(CPLGetBasenameSafe(
    5908           6 :             GetUnderlyingDataset(poSrcDS)->GetDescription()));
    5909           3 :         apszUpdatedOptions.SetNameValue("RASTER_TABLE", osBasename.c_str());
    5910             :     }
    5911             : 
    5912         158 :     if (nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4)
    5913             :     {
    5914           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    5915             :                  "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or "
    5916             :                  "4 (RGBA) band dataset supported");
    5917           1 :         return nullptr;
    5918             :     }
    5919             : 
    5920         157 :     const char *pszUnitType = poSrcDS->GetRasterBand(1)->GetUnitType();
    5921         314 :     if (CSLFetchNameValue(papszOptions, "UOM") == nullptr && pszUnitType &&
    5922         157 :         !EQUAL(pszUnitType, ""))
    5923             :     {
    5924           1 :         apszUpdatedOptions.SetNameValue("UOM", pszUnitType);
    5925             :     }
    5926             : 
    5927         157 :     if (EQUAL(pszTilingScheme, "CUSTOM"))
    5928             :     {
    5929         133 :         if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5930             :         {
    5931           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    5932             :                      "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5933           0 :             return nullptr;
    5934             :         }
    5935             : 
    5936         133 :         GDALGeoPackageDataset *poDS = nullptr;
    5937             :         GDALDriver *poThisDriver =
    5938         133 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5939         133 :         if (poThisDriver != nullptr)
    5940             :         {
    5941         133 :             apszUpdatedOptions.SetNameValue("SKIP_HOLES", "YES");
    5942         133 :             poDS = cpl::down_cast<GDALGeoPackageDataset *>(
    5943             :                 poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS, bStrict,
    5944             :                                                 apszUpdatedOptions, pfnProgress,
    5945         133 :                                                 pProgressData));
    5946             : 
    5947         246 :             if (poDS != nullptr &&
    5948         133 :                 poSrcDS->GetRasterBand(1)->GetRasterDataType() == GDT_Byte &&
    5949             :                 nBands <= 3)
    5950             :             {
    5951          73 :                 poDS->m_nBandCountFromMetadata = nBands;
    5952          73 :                 poDS->m_bMetadataDirty = true;
    5953             :             }
    5954             :         }
    5955         133 :         if (poDS)
    5956         113 :             poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    5957         133 :         return poDS;
    5958             :     }
    5959             : 
    5960          48 :     const auto poTS = GetTilingScheme(pszTilingScheme);
    5961          24 :     if (!poTS)
    5962             :     {
    5963           2 :         return nullptr;
    5964             :     }
    5965          22 :     const int nEPSGCode = poTS->nEPSGCode;
    5966             : 
    5967          44 :     OGRSpatialReference oSRS;
    5968          22 :     if (oSRS.importFromEPSG(nEPSGCode) != OGRERR_NONE)
    5969             :     {
    5970           0 :         return nullptr;
    5971             :     }
    5972          22 :     char *pszWKT = nullptr;
    5973          22 :     oSRS.exportToWkt(&pszWKT);
    5974          22 :     char **papszTO = CSLSetNameValue(nullptr, "DST_SRS", pszWKT);
    5975             : 
    5976          22 :     void *hTransformArg = nullptr;
    5977             : 
    5978             :     // Hack to compensate for GDALSuggestedWarpOutput2() failure (or not
    5979             :     // ideal suggestion with PROJ 8) when reprojecting latitude = +/- 90 to
    5980             :     // EPSG:3857.
    5981          22 :     GDALGeoTransform srcGT;
    5982          22 :     std::unique_ptr<GDALDataset> poTmpDS;
    5983          22 :     bool bEPSG3857Adjust = false;
    5984           8 :     if (nEPSGCode == 3857 && poSrcDS->GetGeoTransform(srcGT) == CE_None &&
    5985          30 :         srcGT[2] == 0 && srcGT[4] == 0 && srcGT[5] < 0)
    5986             :     {
    5987           8 :         const auto poSrcSRS = poSrcDS->GetSpatialRef();
    5988           8 :         if (poSrcSRS && poSrcSRS->IsGeographic())
    5989             :         {
    5990           2 :             double maxLat = srcGT[3];
    5991           2 :             double minLat = srcGT[3] + poSrcDS->GetRasterYSize() * srcGT[5];
    5992             :             // Corresponds to the latitude of below MAX_GM
    5993           2 :             constexpr double MAX_LAT = 85.0511287798066;
    5994           2 :             bool bModified = false;
    5995           2 :             if (maxLat > MAX_LAT)
    5996             :             {
    5997           2 :                 maxLat = MAX_LAT;
    5998           2 :                 bModified = true;
    5999             :             }
    6000           2 :             if (minLat < -MAX_LAT)
    6001             :             {
    6002           2 :                 minLat = -MAX_LAT;
    6003           2 :                 bModified = true;
    6004             :             }
    6005           2 :             if (bModified)
    6006             :             {
    6007           4 :                 CPLStringList aosOptions;
    6008           2 :                 aosOptions.AddString("-of");
    6009           2 :                 aosOptions.AddString("VRT");
    6010           2 :                 aosOptions.AddString("-projwin");
    6011           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", srcGT[0]));
    6012           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", maxLat));
    6013             :                 aosOptions.AddString(CPLSPrintf(
    6014           2 :                     "%.17g", srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1]));
    6015           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", minLat));
    6016             :                 auto psOptions =
    6017           2 :                     GDALTranslateOptionsNew(aosOptions.List(), nullptr);
    6018           2 :                 poTmpDS.reset(GDALDataset::FromHandle(GDALTranslate(
    6019             :                     "", GDALDataset::ToHandle(poSrcDS), psOptions, nullptr)));
    6020           2 :                 GDALTranslateOptionsFree(psOptions);
    6021           2 :                 if (poTmpDS)
    6022             :                 {
    6023           2 :                     bEPSG3857Adjust = true;
    6024           2 :                     hTransformArg = GDALCreateGenImgProjTransformer2(
    6025           2 :                         GDALDataset::FromHandle(poTmpDS.get()), nullptr,
    6026             :                         papszTO);
    6027             :                 }
    6028             :             }
    6029             :         }
    6030             :     }
    6031          22 :     if (hTransformArg == nullptr)
    6032             :     {
    6033             :         hTransformArg =
    6034          20 :             GDALCreateGenImgProjTransformer2(poSrcDS, nullptr, papszTO);
    6035             :     }
    6036             : 
    6037          22 :     if (hTransformArg == nullptr)
    6038             :     {
    6039           1 :         CPLFree(pszWKT);
    6040           1 :         CSLDestroy(papszTO);
    6041           1 :         return nullptr;
    6042             :     }
    6043             : 
    6044          21 :     GDALTransformerInfo *psInfo =
    6045             :         static_cast<GDALTransformerInfo *>(hTransformArg);
    6046          21 :     GDALGeoTransform gt;
    6047             :     double adfExtent[4];
    6048             :     int nXSize, nYSize;
    6049             : 
    6050          21 :     if (GDALSuggestedWarpOutput2(poSrcDS, psInfo->pfnTransform, hTransformArg,
    6051             :                                  gt.data(), &nXSize, &nYSize, adfExtent,
    6052          21 :                                  0) != CE_None)
    6053             :     {
    6054           0 :         CPLFree(pszWKT);
    6055           0 :         CSLDestroy(papszTO);
    6056           0 :         GDALDestroyGenImgProjTransformer(hTransformArg);
    6057           0 :         return nullptr;
    6058             :     }
    6059             : 
    6060          21 :     GDALDestroyGenImgProjTransformer(hTransformArg);
    6061          21 :     hTransformArg = nullptr;
    6062          21 :     poTmpDS.reset();
    6063             : 
    6064          21 :     if (bEPSG3857Adjust)
    6065             :     {
    6066           2 :         constexpr double SPHERICAL_RADIUS = 6378137.0;
    6067           2 :         constexpr double MAX_GM =
    6068             :             SPHERICAL_RADIUS * M_PI;  // 20037508.342789244
    6069           2 :         double maxNorthing = gt[3];
    6070           2 :         double minNorthing = gt[3] + gt[5] * nYSize;
    6071           2 :         bool bChanged = false;
    6072           2 :         if (maxNorthing > MAX_GM)
    6073             :         {
    6074           2 :             bChanged = true;
    6075           2 :             maxNorthing = MAX_GM;
    6076             :         }
    6077           2 :         if (minNorthing < -MAX_GM)
    6078             :         {
    6079           2 :             bChanged = true;
    6080           2 :             minNorthing = -MAX_GM;
    6081             :         }
    6082           2 :         if (bChanged)
    6083             :         {
    6084           2 :             gt[3] = maxNorthing;
    6085           2 :             nYSize = int((maxNorthing - minNorthing) / (-gt[5]) + 0.5);
    6086           2 :             adfExtent[1] = maxNorthing + nYSize * gt[5];
    6087           2 :             adfExtent[3] = maxNorthing;
    6088             :         }
    6089             :     }
    6090             : 
    6091          21 :     double dfComputedRes = gt[1];
    6092          21 :     double dfPrevRes = 0.0;
    6093          21 :     double dfRes = 0.0;
    6094          21 :     int nZoomLevel = 0;  // Used after for.
    6095          21 :     const char *pszZoomLevel = CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    6096          21 :     if (pszZoomLevel)
    6097             :     {
    6098           2 :         nZoomLevel = atoi(pszZoomLevel);
    6099             : 
    6100           2 :         int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    6101           2 :         while ((1 << nMaxZoomLevelForThisTM) >
    6102           4 :                    INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6103           2 :                (1 << nMaxZoomLevelForThisTM) >
    6104           2 :                    INT_MAX / poTS->nTileYCountZoomLevel0)
    6105             :         {
    6106           0 :             --nMaxZoomLevelForThisTM;
    6107             :         }
    6108             : 
    6109           2 :         if (nZoomLevel < 0 || nZoomLevel > nMaxZoomLevelForThisTM)
    6110             :         {
    6111           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6112             :                      "ZOOM_LEVEL = %s is invalid. It should be in [0,%d] range",
    6113             :                      pszZoomLevel, nMaxZoomLevelForThisTM);
    6114           1 :             CPLFree(pszWKT);
    6115           1 :             CSLDestroy(papszTO);
    6116           1 :             return nullptr;
    6117             :         }
    6118             :     }
    6119             :     else
    6120             :     {
    6121         171 :         for (; nZoomLevel < MAX_ZOOM_LEVEL; nZoomLevel++)
    6122             :         {
    6123         171 :             dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6124         171 :             if (dfComputedRes > dfRes ||
    6125         152 :                 fabs(dfComputedRes - dfRes) / dfRes <= 1e-8)
    6126             :                 break;
    6127         152 :             dfPrevRes = dfRes;
    6128             :         }
    6129          38 :         if (nZoomLevel == MAX_ZOOM_LEVEL ||
    6130          38 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6131          19 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileYCountZoomLevel0)
    6132             :         {
    6133           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6134             :                      "Could not find an appropriate zoom level");
    6135           0 :             CPLFree(pszWKT);
    6136           0 :             CSLDestroy(papszTO);
    6137           0 :             return nullptr;
    6138             :         }
    6139             : 
    6140          19 :         if (nZoomLevel > 0 && fabs(dfComputedRes - dfRes) / dfRes > 1e-8)
    6141             :         {
    6142          17 :             const char *pszZoomLevelStrategy = CSLFetchNameValueDef(
    6143             :                 papszOptions, "ZOOM_LEVEL_STRATEGY", "AUTO");
    6144          17 :             if (EQUAL(pszZoomLevelStrategy, "LOWER"))
    6145             :             {
    6146           1 :                 nZoomLevel--;
    6147             :             }
    6148          16 :             else if (EQUAL(pszZoomLevelStrategy, "UPPER"))
    6149             :             {
    6150             :                 /* do nothing */
    6151             :             }
    6152             :             else
    6153             :             {
    6154          15 :                 if (dfPrevRes / dfComputedRes < dfComputedRes / dfRes)
    6155          13 :                     nZoomLevel--;
    6156             :             }
    6157             :         }
    6158             :     }
    6159             : 
    6160          20 :     dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6161             : 
    6162          20 :     double dfMinX = adfExtent[0];
    6163          20 :     double dfMinY = adfExtent[1];
    6164          20 :     double dfMaxX = adfExtent[2];
    6165          20 :     double dfMaxY = adfExtent[3];
    6166             : 
    6167          20 :     nXSize = static_cast<int>(0.5 + (dfMaxX - dfMinX) / dfRes);
    6168          20 :     nYSize = static_cast<int>(0.5 + (dfMaxY - dfMinY) / dfRes);
    6169          20 :     gt[1] = dfRes;
    6170          20 :     gt[5] = -dfRes;
    6171             : 
    6172          20 :     const GDALDataType eDT = poSrcDS->GetRasterBand(1)->GetRasterDataType();
    6173          20 :     int nTargetBands = nBands;
    6174             :     /* For grey level or RGB, if there's reprojection involved, add an alpha */
    6175             :     /* channel */
    6176          37 :     if (eDT == GDT_Byte &&
    6177          13 :         ((nBands == 1 &&
    6178          17 :           poSrcDS->GetRasterBand(1)->GetColorTable() == nullptr) ||
    6179             :          nBands == 3))
    6180             :     {
    6181          30 :         OGRSpatialReference oSrcSRS;
    6182          15 :         oSrcSRS.SetFromUserInput(poSrcDS->GetProjectionRef());
    6183          15 :         oSrcSRS.AutoIdentifyEPSG();
    6184          30 :         if (oSrcSRS.GetAuthorityCode(nullptr) == nullptr ||
    6185          15 :             atoi(oSrcSRS.GetAuthorityCode(nullptr)) != nEPSGCode)
    6186             :         {
    6187          13 :             nTargetBands++;
    6188             :         }
    6189             :     }
    6190             : 
    6191          20 :     GDALResampleAlg eResampleAlg = GRA_Bilinear;
    6192          20 :     const char *pszResampling = CSLFetchNameValue(papszOptions, "RESAMPLING");
    6193          20 :     if (pszResampling)
    6194             :     {
    6195           6 :         for (size_t iAlg = 0;
    6196           6 :              iAlg < sizeof(asResamplingAlg) / sizeof(asResamplingAlg[0]);
    6197             :              iAlg++)
    6198             :         {
    6199           6 :             if (EQUAL(pszResampling, asResamplingAlg[iAlg].pszName))
    6200             :             {
    6201           3 :                 eResampleAlg = asResamplingAlg[iAlg].eResampleAlg;
    6202           3 :                 break;
    6203             :             }
    6204             :         }
    6205             :     }
    6206             : 
    6207          16 :     if (nBands == 1 && poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    6208          36 :         eResampleAlg != GRA_NearestNeighbour && eResampleAlg != GRA_Mode)
    6209             :     {
    6210           0 :         CPLError(
    6211             :             CE_Warning, CPLE_AppDefined,
    6212             :             "Input dataset has a color table, which will likely lead to "
    6213             :             "bad results when using a resampling method other than "
    6214             :             "nearest neighbour or mode. Converting the dataset to 24/32 bit "
    6215             :             "(e.g. with gdal_translate -expand rgb/rgba) is advised.");
    6216             :     }
    6217             : 
    6218          40 :     auto poDS = std::make_unique<GDALGeoPackageDataset>();
    6219          20 :     if (!(poDS->Create(pszFilename, nXSize, nYSize, nTargetBands, eDT,
    6220             :                        apszUpdatedOptions)))
    6221             :     {
    6222           1 :         CPLFree(pszWKT);
    6223           1 :         CSLDestroy(papszTO);
    6224           1 :         return nullptr;
    6225             :     }
    6226             : 
    6227             :     // Assign nodata values before the SetGeoTransform call.
    6228             :     // SetGeoTransform will trigger creation of the overview datasets for each
    6229             :     // zoom level and at that point the nodata value needs to be known.
    6230          19 :     int bHasNoData = FALSE;
    6231             :     double dfNoDataValue =
    6232          19 :         poSrcDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    6233          19 :     if (eDT != GDT_Byte && bHasNoData)
    6234             :     {
    6235           3 :         poDS->GetRasterBand(1)->SetNoDataValue(dfNoDataValue);
    6236             :     }
    6237             : 
    6238          19 :     poDS->SetGeoTransform(gt);
    6239          19 :     poDS->SetProjection(pszWKT);
    6240          19 :     CPLFree(pszWKT);
    6241          19 :     pszWKT = nullptr;
    6242          24 :     if (nTargetBands == 1 && nBands == 1 &&
    6243           5 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
    6244             :     {
    6245           2 :         poDS->GetRasterBand(1)->SetColorTable(
    6246           1 :             poSrcDS->GetRasterBand(1)->GetColorTable());
    6247             :     }
    6248             : 
    6249             :     hTransformArg =
    6250          19 :         GDALCreateGenImgProjTransformer2(poSrcDS, poDS.get(), papszTO);
    6251          19 :     CSLDestroy(papszTO);
    6252          19 :     if (hTransformArg == nullptr)
    6253             :     {
    6254           0 :         return nullptr;
    6255             :     }
    6256             : 
    6257          19 :     poDS->SetMetadata(poSrcDS->GetMetadata());
    6258             : 
    6259             :     /* -------------------------------------------------------------------- */
    6260             :     /*      Warp the transformer with a linear approximator                 */
    6261             :     /* -------------------------------------------------------------------- */
    6262          19 :     hTransformArg = GDALCreateApproxTransformer(GDALGenImgProjTransform,
    6263             :                                                 hTransformArg, 0.125);
    6264          19 :     GDALApproxTransformerOwnsSubtransformer(hTransformArg, TRUE);
    6265             : 
    6266             :     /* -------------------------------------------------------------------- */
    6267             :     /*      Setup warp options.                                             */
    6268             :     /* -------------------------------------------------------------------- */
    6269          19 :     GDALWarpOptions *psWO = GDALCreateWarpOptions();
    6270             : 
    6271          19 :     psWO->papszWarpOptions = CSLSetNameValue(nullptr, "OPTIMIZE_SIZE", "YES");
    6272          19 :     psWO->papszWarpOptions =
    6273          19 :         CSLSetNameValue(psWO->papszWarpOptions, "SAMPLE_GRID", "YES");
    6274          19 :     if (bHasNoData)
    6275             :     {
    6276           3 :         if (dfNoDataValue == 0.0)
    6277             :         {
    6278             :             // Do not initialize in the case where nodata != 0, since we
    6279             :             // want the GeoPackage driver to return empty tiles at the nodata
    6280             :             // value instead of 0 as GDAL core would
    6281           0 :             psWO->papszWarpOptions =
    6282           0 :                 CSLSetNameValue(psWO->papszWarpOptions, "INIT_DEST", "0");
    6283             :         }
    6284             : 
    6285           3 :         psWO->padfSrcNoDataReal =
    6286           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6287           3 :         psWO->padfSrcNoDataReal[0] = dfNoDataValue;
    6288             : 
    6289           3 :         psWO->padfDstNoDataReal =
    6290           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6291           3 :         psWO->padfDstNoDataReal[0] = dfNoDataValue;
    6292             :     }
    6293          19 :     psWO->eWorkingDataType = eDT;
    6294          19 :     psWO->eResampleAlg = eResampleAlg;
    6295             : 
    6296          19 :     psWO->hSrcDS = poSrcDS;
    6297          19 :     psWO->hDstDS = poDS.get();
    6298             : 
    6299          19 :     psWO->pfnTransformer = GDALApproxTransform;
    6300          19 :     psWO->pTransformerArg = hTransformArg;
    6301             : 
    6302          19 :     psWO->pfnProgress = pfnProgress;
    6303          19 :     psWO->pProgressArg = pProgressData;
    6304             : 
    6305             :     /* -------------------------------------------------------------------- */
    6306             :     /*      Setup band mapping.                                             */
    6307             :     /* -------------------------------------------------------------------- */
    6308             : 
    6309          19 :     if (nBands == 2 || nBands == 4)
    6310           1 :         psWO->nBandCount = nBands - 1;
    6311             :     else
    6312          18 :         psWO->nBandCount = nBands;
    6313             : 
    6314          19 :     psWO->panSrcBands =
    6315          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6316          19 :     psWO->panDstBands =
    6317          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6318             : 
    6319          46 :     for (int i = 0; i < psWO->nBandCount; i++)
    6320             :     {
    6321          27 :         psWO->panSrcBands[i] = i + 1;
    6322          27 :         psWO->panDstBands[i] = i + 1;
    6323             :     }
    6324             : 
    6325          19 :     if (nBands == 2 || nBands == 4)
    6326             :     {
    6327           1 :         psWO->nSrcAlphaBand = nBands;
    6328             :     }
    6329          19 :     if (nTargetBands == 2 || nTargetBands == 4)
    6330             :     {
    6331          13 :         psWO->nDstAlphaBand = nTargetBands;
    6332             :     }
    6333             : 
    6334             :     /* -------------------------------------------------------------------- */
    6335             :     /*      Initialize and execute the warp.                                */
    6336             :     /* -------------------------------------------------------------------- */
    6337          38 :     GDALWarpOperation oWO;
    6338             : 
    6339          19 :     CPLErr eErr = oWO.Initialize(psWO);
    6340          19 :     if (eErr == CE_None)
    6341             :     {
    6342             :         /*if( bMulti )
    6343             :             eErr = oWO.ChunkAndWarpMulti( 0, 0, nXSize, nYSize );
    6344             :         else*/
    6345          19 :         eErr = oWO.ChunkAndWarpImage(0, 0, nXSize, nYSize);
    6346             :     }
    6347          19 :     if (eErr != CE_None)
    6348             :     {
    6349           0 :         poDS.reset();
    6350             :     }
    6351             : 
    6352          19 :     GDALDestroyTransformer(hTransformArg);
    6353          19 :     GDALDestroyWarpOptions(psWO);
    6354             : 
    6355          19 :     if (poDS)
    6356          19 :         poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    6357             : 
    6358          19 :     return poDS.release();
    6359             : }
    6360             : 
    6361             : /************************************************************************/
    6362             : /*                        ParseCompressionOptions()                     */
    6363             : /************************************************************************/
    6364             : 
    6365         456 : void GDALGeoPackageDataset::ParseCompressionOptions(char **papszOptions)
    6366             : {
    6367         456 :     const char *pszZLevel = CSLFetchNameValue(papszOptions, "ZLEVEL");
    6368         456 :     if (pszZLevel)
    6369           0 :         m_nZLevel = atoi(pszZLevel);
    6370             : 
    6371         456 :     const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
    6372         456 :     if (pszQuality)
    6373           0 :         m_nQuality = atoi(pszQuality);
    6374             : 
    6375         456 :     const char *pszDither = CSLFetchNameValue(papszOptions, "DITHER");
    6376         456 :     if (pszDither)
    6377           0 :         m_bDither = CPLTestBool(pszDither);
    6378         456 : }
    6379             : 
    6380             : /************************************************************************/
    6381             : /*                          RegisterWebPExtension()                     */
    6382             : /************************************************************************/
    6383             : 
    6384          11 : bool GDALGeoPackageDataset::RegisterWebPExtension()
    6385             : {
    6386          11 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6387           0 :         return false;
    6388             : 
    6389          11 :     char *pszSQL = sqlite3_mprintf(
    6390             :         "INSERT INTO gpkg_extensions "
    6391             :         "(table_name, column_name, extension_name, definition, scope) "
    6392             :         "VALUES "
    6393             :         "('%q', 'tile_data', 'gpkg_webp', "
    6394             :         "'http://www.geopackage.org/spec120/#extension_tiles_webp', "
    6395             :         "'read-write')",
    6396             :         m_osRasterTable.c_str());
    6397          11 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6398          11 :     sqlite3_free(pszSQL);
    6399             : 
    6400          11 :     return OGRERR_NONE == eErr;
    6401             : }
    6402             : 
    6403             : /************************************************************************/
    6404             : /*                       RegisterZoomOtherExtension()                   */
    6405             : /************************************************************************/
    6406             : 
    6407           1 : bool GDALGeoPackageDataset::RegisterZoomOtherExtension()
    6408             : {
    6409           1 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6410           0 :         return false;
    6411             : 
    6412           1 :     char *pszSQL = sqlite3_mprintf(
    6413             :         "INSERT INTO gpkg_extensions "
    6414             :         "(table_name, column_name, extension_name, definition, scope) "
    6415             :         "VALUES "
    6416             :         "('%q', 'tile_data', 'gpkg_zoom_other', "
    6417             :         "'http://www.geopackage.org/spec120/#extension_zoom_other_intervals', "
    6418             :         "'read-write')",
    6419             :         m_osRasterTable.c_str());
    6420           1 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6421           1 :     sqlite3_free(pszSQL);
    6422           1 :     return OGRERR_NONE == eErr;
    6423             : }
    6424             : 
    6425             : /************************************************************************/
    6426             : /*                              GetLayer()                              */
    6427             : /************************************************************************/
    6428             : 
    6429       15432 : OGRLayer *GDALGeoPackageDataset::GetLayer(int iLayer)
    6430             : 
    6431             : {
    6432       15432 :     if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
    6433           6 :         return nullptr;
    6434             :     else
    6435       15426 :         return m_apoLayers[iLayer].get();
    6436             : }
    6437             : 
    6438             : /************************************************************************/
    6439             : /*                           LaunderName()                              */
    6440             : /************************************************************************/
    6441             : 
    6442             : /** Launder identifiers (table, column names) according to guidance at
    6443             :  * https://www.geopackage.org/guidance/getting-started.html:
    6444             :  * "For maximum interoperability, start your database identifiers (table names,
    6445             :  * column names, etc.) with a lowercase character and only use lowercase
    6446             :  * characters, numbers 0-9, and underscores (_)."
    6447             :  */
    6448             : 
    6449             : /* static */
    6450           5 : std::string GDALGeoPackageDataset::LaunderName(const std::string &osStr)
    6451             : {
    6452           5 :     char *pszASCII = CPLUTF8ForceToASCII(osStr.c_str(), '_');
    6453          10 :     const std::string osStrASCII(pszASCII);
    6454           5 :     CPLFree(pszASCII);
    6455             : 
    6456          10 :     std::string osRet;
    6457           5 :     osRet.reserve(osStrASCII.size());
    6458             : 
    6459          29 :     for (size_t i = 0; i < osStrASCII.size(); ++i)
    6460             :     {
    6461          24 :         if (osRet.empty())
    6462             :         {
    6463           5 :             if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6464             :             {
    6465           2 :                 osRet += (osStrASCII[i] - 'A' + 'a');
    6466             :             }
    6467           3 :             else if (osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z')
    6468             :             {
    6469           2 :                 osRet += osStrASCII[i];
    6470             :             }
    6471             :             else
    6472             :             {
    6473           1 :                 continue;
    6474             :             }
    6475             :         }
    6476          19 :         else if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6477             :         {
    6478          11 :             osRet += (osStrASCII[i] - 'A' + 'a');
    6479             :         }
    6480           9 :         else if ((osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z') ||
    6481          14 :                  (osStrASCII[i] >= '0' && osStrASCII[i] <= '9') ||
    6482           5 :                  osStrASCII[i] == '_')
    6483             :         {
    6484           7 :             osRet += osStrASCII[i];
    6485             :         }
    6486             :         else
    6487             :         {
    6488           1 :             osRet += '_';
    6489             :         }
    6490             :     }
    6491             : 
    6492           5 :     if (osRet.empty() && !osStrASCII.empty())
    6493           2 :         return LaunderName(std::string("x").append(osStrASCII));
    6494             : 
    6495           4 :     if (osRet != osStr)
    6496             :     {
    6497           3 :         CPLDebug("PG", "LaunderName('%s') -> '%s'", osStr.c_str(),
    6498             :                  osRet.c_str());
    6499             :     }
    6500             : 
    6501           4 :     return osRet;
    6502             : }
    6503             : 
    6504             : /************************************************************************/
    6505             : /*                          ICreateLayer()                              */
    6506             : /************************************************************************/
    6507             : 
    6508             : OGRLayer *
    6509         757 : GDALGeoPackageDataset::ICreateLayer(const char *pszLayerName,
    6510             :                                     const OGRGeomFieldDefn *poSrcGeomFieldDefn,
    6511             :                                     CSLConstList papszOptions)
    6512             : {
    6513             :     /* -------------------------------------------------------------------- */
    6514             :     /*      Verify we are in update mode.                                   */
    6515             :     /* -------------------------------------------------------------------- */
    6516         757 :     if (!GetUpdate())
    6517             :     {
    6518           0 :         CPLError(CE_Failure, CPLE_NoWriteAccess,
    6519             :                  "Data source %s opened read-only.\n"
    6520             :                  "New layer %s cannot be created.\n",
    6521             :                  m_pszFilename, pszLayerName);
    6522             : 
    6523           0 :         return nullptr;
    6524             :     }
    6525             : 
    6526             :     const bool bLaunder =
    6527         757 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "LAUNDER", "NO"));
    6528             :     const std::string osTableName(bLaunder ? LaunderName(pszLayerName)
    6529        2271 :                                            : std::string(pszLayerName));
    6530             : 
    6531             :     const auto eGType =
    6532         757 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
    6533             :     const auto poSpatialRef =
    6534         757 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
    6535             : 
    6536         757 :     if (!m_bHasGPKGGeometryColumns)
    6537             :     {
    6538           1 :         if (SQLCommand(hDB, pszCREATE_GPKG_GEOMETRY_COLUMNS) != OGRERR_NONE)
    6539             :         {
    6540           0 :             return nullptr;
    6541             :         }
    6542           1 :         m_bHasGPKGGeometryColumns = true;
    6543             :     }
    6544             : 
    6545             :     // Check identifier unicity
    6546         757 :     const char *pszIdentifier = CSLFetchNameValue(papszOptions, "IDENTIFIER");
    6547         757 :     if (pszIdentifier != nullptr && pszIdentifier[0] == '\0')
    6548           0 :         pszIdentifier = nullptr;
    6549         757 :     if (pszIdentifier != nullptr)
    6550             :     {
    6551          13 :         for (auto &poLayer : m_apoLayers)
    6552             :         {
    6553             :             const char *pszOtherIdentifier =
    6554           9 :                 poLayer->GetMetadataItem("IDENTIFIER");
    6555           9 :             if (pszOtherIdentifier == nullptr)
    6556           6 :                 pszOtherIdentifier = poLayer->GetName();
    6557          18 :             if (pszOtherIdentifier != nullptr &&
    6558          12 :                 EQUAL(pszOtherIdentifier, pszIdentifier) &&
    6559           3 :                 !EQUAL(poLayer->GetName(), osTableName.c_str()))
    6560             :             {
    6561           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6562             :                          "Identifier %s is already used by table %s",
    6563             :                          pszIdentifier, poLayer->GetName());
    6564           2 :                 return nullptr;
    6565             :             }
    6566             :         }
    6567             : 
    6568             :         // In case there would be table in gpkg_contents not listed as a
    6569             :         // vector layer
    6570           4 :         char *pszSQL = sqlite3_mprintf(
    6571             :             "SELECT table_name FROM gpkg_contents WHERE identifier = '%q' "
    6572             :             "LIMIT 2",
    6573             :             pszIdentifier);
    6574           4 :         auto oResult = SQLQuery(hDB, pszSQL);
    6575           4 :         sqlite3_free(pszSQL);
    6576           8 :         if (oResult && oResult->RowCount() > 0 &&
    6577           9 :             oResult->GetValue(0, 0) != nullptr &&
    6578           1 :             !EQUAL(oResult->GetValue(0, 0), osTableName.c_str()))
    6579             :         {
    6580           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6581             :                      "Identifier %s is already used by table %s", pszIdentifier,
    6582             :                      oResult->GetValue(0, 0));
    6583           1 :             return nullptr;
    6584             :         }
    6585             :     }
    6586             : 
    6587             :     /* Read GEOMETRY_NAME option */
    6588             :     const char *pszGeomColumnName =
    6589         754 :         CSLFetchNameValue(papszOptions, "GEOMETRY_NAME");
    6590         754 :     if (pszGeomColumnName == nullptr) /* deprecated name */
    6591         673 :         pszGeomColumnName = CSLFetchNameValue(papszOptions, "GEOMETRY_COLUMN");
    6592         754 :     if (pszGeomColumnName == nullptr && poSrcGeomFieldDefn)
    6593             :     {
    6594         621 :         pszGeomColumnName = poSrcGeomFieldDefn->GetNameRef();
    6595         621 :         if (pszGeomColumnName && pszGeomColumnName[0] == 0)
    6596         617 :             pszGeomColumnName = nullptr;
    6597             :     }
    6598         754 :     if (pszGeomColumnName == nullptr)
    6599         669 :         pszGeomColumnName = "geom";
    6600             :     const bool bGeomNullable =
    6601         754 :         CPLFetchBool(papszOptions, "GEOMETRY_NULLABLE", true);
    6602             : 
    6603             :     /* Read FID option */
    6604         754 :     const char *pszFIDColumnName = CSLFetchNameValue(papszOptions, "FID");
    6605         754 :     if (pszFIDColumnName == nullptr)
    6606         718 :         pszFIDColumnName = "fid";
    6607             : 
    6608         754 :     if (CPLTestBool(CPLGetConfigOption("GPKG_NAME_CHECK", "YES")))
    6609             :     {
    6610         754 :         if (strspn(pszFIDColumnName, "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") > 0)
    6611             :         {
    6612           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6613             :                      "The primary key (%s) name may not contain special "
    6614             :                      "characters or spaces",
    6615             :                      pszFIDColumnName);
    6616           1 :             return nullptr;
    6617             :         }
    6618             : 
    6619             :         /* Avoiding gpkg prefixes is not an official requirement, but seems wise
    6620             :          */
    6621         753 :         if (STARTS_WITH(osTableName.c_str(), "gpkg"))
    6622             :         {
    6623           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6624             :                      "The layer name may not begin with 'gpkg' as it is a "
    6625             :                      "reserved geopackage prefix");
    6626           0 :             return nullptr;
    6627             :         }
    6628             : 
    6629             :         /* Preemptively try and avoid sqlite3 syntax errors due to  */
    6630             :         /* illegal characters. */
    6631         753 :         if (strspn(osTableName.c_str(), "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") >
    6632             :             0)
    6633             :         {
    6634           0 :             CPLError(
    6635             :                 CE_Failure, CPLE_AppDefined,
    6636             :                 "The layer name may not contain special characters or spaces");
    6637           0 :             return nullptr;
    6638             :         }
    6639             :     }
    6640             : 
    6641             :     /* Check for any existing layers that already use this name */
    6642         957 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6643             :          iLayer++)
    6644             :     {
    6645         205 :         if (EQUAL(osTableName.c_str(), m_apoLayers[iLayer]->GetName()))
    6646             :         {
    6647             :             const char *pszOverwrite =
    6648           2 :                 CSLFetchNameValue(papszOptions, "OVERWRITE");
    6649           2 :             if (pszOverwrite != nullptr && CPLTestBool(pszOverwrite))
    6650             :             {
    6651           1 :                 DeleteLayer(iLayer);
    6652             :             }
    6653             :             else
    6654             :             {
    6655           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6656             :                          "Layer %s already exists, CreateLayer failed.\n"
    6657             :                          "Use the layer creation option OVERWRITE=YES to "
    6658             :                          "replace it.",
    6659             :                          osTableName.c_str());
    6660           1 :                 return nullptr;
    6661             :             }
    6662             :         }
    6663             :     }
    6664             : 
    6665         752 :     if (m_apoLayers.size() == 1)
    6666             :     {
    6667             :         // Async RTree building doesn't play well with multiple layer:
    6668             :         // SQLite3 locks being hold for a long time, random failed commits,
    6669             :         // etc.
    6670          78 :         m_apoLayers[0]->FinishOrDisableThreadedRTree();
    6671             :     }
    6672             : 
    6673             :     /* Create a blank layer. */
    6674             :     auto poLayer =
    6675        1504 :         std::make_unique<OGRGeoPackageTableLayer>(this, osTableName.c_str());
    6676             : 
    6677         752 :     OGRSpatialReference *poSRS = nullptr;
    6678         752 :     if (poSpatialRef)
    6679             :     {
    6680         241 :         poSRS = poSpatialRef->Clone();
    6681         241 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    6682             :     }
    6683        1505 :     poLayer->SetCreationParameters(
    6684             :         eGType,
    6685         753 :         bLaunder ? LaunderName(pszGeomColumnName).c_str() : pszGeomColumnName,
    6686             :         bGeomNullable, poSRS, CSLFetchNameValue(papszOptions, "SRID"),
    6687        1504 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetCoordinatePrecision()
    6688             :                            : OGRGeomCoordinatePrecision(),
    6689         752 :         CPLTestBool(
    6690             :             CSLFetchNameValueDef(papszOptions, "DISCARD_COORD_LSB", "NO")),
    6691         752 :         CPLTestBool(CSLFetchNameValueDef(
    6692             :             papszOptions, "UNDO_DISCARD_COORD_LSB_ON_READING", "NO")),
    6693         753 :         bLaunder ? LaunderName(pszFIDColumnName).c_str() : pszFIDColumnName,
    6694             :         pszIdentifier, CSLFetchNameValue(papszOptions, "DESCRIPTION"));
    6695         752 :     if (poSRS)
    6696             :     {
    6697         241 :         poSRS->Release();
    6698             :     }
    6699             : 
    6700         752 :     poLayer->SetLaunder(bLaunder);
    6701             : 
    6702             :     /* Should we create a spatial index ? */
    6703         752 :     const char *pszSI = CSLFetchNameValue(papszOptions, "SPATIAL_INDEX");
    6704         752 :     int bCreateSpatialIndex = (pszSI == nullptr || CPLTestBool(pszSI));
    6705         752 :     if (eGType != wkbNone && bCreateSpatialIndex)
    6706             :     {
    6707         678 :         poLayer->SetDeferredSpatialIndexCreation(true);
    6708             :     }
    6709             : 
    6710         752 :     poLayer->SetPrecisionFlag(CPLFetchBool(papszOptions, "PRECISION", true));
    6711         752 :     poLayer->SetTruncateFieldsFlag(
    6712         752 :         CPLFetchBool(papszOptions, "TRUNCATE_FIELDS", false));
    6713         752 :     if (eGType == wkbNone)
    6714             :     {
    6715          52 :         const char *pszASpatialVariant = CSLFetchNameValueDef(
    6716             :             papszOptions, "ASPATIAL_VARIANT",
    6717          52 :             m_bNonSpatialTablesNonRegisteredInGpkgContentsFound
    6718             :                 ? "NOT_REGISTERED"
    6719             :                 : "GPKG_ATTRIBUTES");
    6720          52 :         GPKGASpatialVariant eASpatialVariant = GPKG_ATTRIBUTES;
    6721          52 :         if (EQUAL(pszASpatialVariant, "GPKG_ATTRIBUTES"))
    6722          40 :             eASpatialVariant = GPKG_ATTRIBUTES;
    6723          12 :         else if (EQUAL(pszASpatialVariant, "OGR_ASPATIAL"))
    6724             :         {
    6725           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6726             :                      "ASPATIAL_VARIANT=OGR_ASPATIAL is no longer supported");
    6727           0 :             return nullptr;
    6728             :         }
    6729          12 :         else if (EQUAL(pszASpatialVariant, "NOT_REGISTERED"))
    6730          12 :             eASpatialVariant = NOT_REGISTERED;
    6731             :         else
    6732             :         {
    6733           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6734             :                      "Unsupported value for ASPATIAL_VARIANT: %s",
    6735             :                      pszASpatialVariant);
    6736           0 :             return nullptr;
    6737             :         }
    6738          52 :         poLayer->SetASpatialVariant(eASpatialVariant);
    6739             :     }
    6740             : 
    6741             :     const char *pszDateTimePrecision =
    6742         752 :         CSLFetchNameValueDef(papszOptions, "DATETIME_PRECISION", "AUTO");
    6743         752 :     if (EQUAL(pszDateTimePrecision, "MILLISECOND"))
    6744             :     {
    6745           2 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6746             :     }
    6747         750 :     else if (EQUAL(pszDateTimePrecision, "SECOND"))
    6748             :     {
    6749           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6750           0 :             CPLError(
    6751             :                 CE_Warning, CPLE_AppDefined,
    6752             :                 "DATETIME_PRECISION=SECOND is only valid since GeoPackage 1.4");
    6753           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::SECOND);
    6754             :     }
    6755         749 :     else if (EQUAL(pszDateTimePrecision, "MINUTE"))
    6756             :     {
    6757           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6758           0 :             CPLError(
    6759             :                 CE_Warning, CPLE_AppDefined,
    6760             :                 "DATETIME_PRECISION=MINUTE is only valid since GeoPackage 1.4");
    6761           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MINUTE);
    6762             :     }
    6763         748 :     else if (EQUAL(pszDateTimePrecision, "AUTO"))
    6764             :     {
    6765         747 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6766          13 :             poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6767             :     }
    6768             :     else
    6769             :     {
    6770           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    6771             :                  "Unsupported value for DATETIME_PRECISION: %s",
    6772             :                  pszDateTimePrecision);
    6773           1 :         return nullptr;
    6774             :     }
    6775             : 
    6776             :     // If there was an ogr_empty_table table, we can remove it
    6777             :     // But do it at dataset closing, otherwise locking performance issues
    6778             :     // can arise (probably when transactions are used).
    6779         751 :     m_bRemoveOGREmptyTable = true;
    6780             : 
    6781         751 :     m_apoLayers.emplace_back(std::move(poLayer));
    6782         751 :     return m_apoLayers.back().get();
    6783             : }
    6784             : 
    6785             : /************************************************************************/
    6786             : /*                          FindLayerIndex()                            */
    6787             : /************************************************************************/
    6788             : 
    6789          27 : int GDALGeoPackageDataset::FindLayerIndex(const char *pszLayerName)
    6790             : 
    6791             : {
    6792          42 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6793             :          iLayer++)
    6794             :     {
    6795          28 :         if (EQUAL(pszLayerName, m_apoLayers[iLayer]->GetName()))
    6796          13 :             return iLayer;
    6797             :     }
    6798          14 :     return -1;
    6799             : }
    6800             : 
    6801             : /************************************************************************/
    6802             : /*                       DeleteLayerCommon()                            */
    6803             : /************************************************************************/
    6804             : 
    6805          40 : OGRErr GDALGeoPackageDataset::DeleteLayerCommon(const char *pszLayerName)
    6806             : {
    6807             :     // Temporary remove foreign key checks
    6808             :     const GPKGTemporaryForeignKeyCheckDisabler
    6809          40 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6810             : 
    6811          40 :     char *pszSQL = sqlite3_mprintf(
    6812             :         "DELETE FROM gpkg_contents WHERE lower(table_name) = lower('%q')",
    6813             :         pszLayerName);
    6814          40 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    6815          40 :     sqlite3_free(pszSQL);
    6816             : 
    6817          40 :     if (eErr == OGRERR_NONE && HasExtensionsTable())
    6818             :     {
    6819          38 :         pszSQL = sqlite3_mprintf(
    6820             :             "DELETE FROM gpkg_extensions WHERE lower(table_name) = lower('%q')",
    6821             :             pszLayerName);
    6822          38 :         eErr = SQLCommand(hDB, pszSQL);
    6823          38 :         sqlite3_free(pszSQL);
    6824             :     }
    6825             : 
    6826          40 :     if (eErr == OGRERR_NONE && HasMetadataTables())
    6827             :     {
    6828             :         // Delete from gpkg_metadata metadata records that are only referenced
    6829             :         // by the table we are about to drop
    6830          11 :         pszSQL = sqlite3_mprintf(
    6831             :             "DELETE FROM gpkg_metadata WHERE id IN ("
    6832             :             "SELECT DISTINCT md_file_id FROM "
    6833             :             "gpkg_metadata_reference WHERE "
    6834             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6835             :             "AND id NOT IN ("
    6836             :             "SELECT DISTINCT md_file_id FROM gpkg_metadata_reference WHERE "
    6837             :             "md_file_id IN (SELECT DISTINCT md_file_id FROM "
    6838             :             "gpkg_metadata_reference WHERE "
    6839             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6840             :             "AND lower(table_name) <> lower('%q'))",
    6841             :             pszLayerName, pszLayerName, pszLayerName);
    6842          11 :         eErr = SQLCommand(hDB, pszSQL);
    6843          11 :         sqlite3_free(pszSQL);
    6844             : 
    6845          11 :         if (eErr == OGRERR_NONE)
    6846             :         {
    6847             :             pszSQL =
    6848          11 :                 sqlite3_mprintf("DELETE FROM gpkg_metadata_reference WHERE "
    6849             :                                 "lower(table_name) = lower('%q')",
    6850             :                                 pszLayerName);
    6851          11 :             eErr = SQLCommand(hDB, pszSQL);
    6852          11 :             sqlite3_free(pszSQL);
    6853             :         }
    6854             :     }
    6855             : 
    6856          40 :     if (eErr == OGRERR_NONE && HasGpkgextRelationsTable())
    6857             :     {
    6858             :         // Remove reference to potential corresponding mapping table in
    6859             :         // gpkg_extensions
    6860           4 :         pszSQL = sqlite3_mprintf(
    6861             :             "DELETE FROM gpkg_extensions WHERE "
    6862             :             "extension_name IN ('related_tables', "
    6863             :             "'gpkg_related_tables') AND lower(table_name) = "
    6864             :             "(SELECT lower(mapping_table_name) FROM gpkgext_relations WHERE "
    6865             :             "lower(base_table_name) = lower('%q') OR "
    6866             :             "lower(related_table_name) = lower('%q') OR "
    6867             :             "lower(mapping_table_name) = lower('%q'))",
    6868             :             pszLayerName, pszLayerName, pszLayerName);
    6869           4 :         eErr = SQLCommand(hDB, pszSQL);
    6870           4 :         sqlite3_free(pszSQL);
    6871             : 
    6872           4 :         if (eErr == OGRERR_NONE)
    6873             :         {
    6874             :             // Remove reference to potential corresponding mapping table in
    6875             :             // gpkgext_relations
    6876             :             pszSQL =
    6877           4 :                 sqlite3_mprintf("DELETE FROM gpkgext_relations WHERE "
    6878             :                                 "lower(base_table_name) = lower('%q') OR "
    6879             :                                 "lower(related_table_name) = lower('%q') OR "
    6880             :                                 "lower(mapping_table_name) = lower('%q')",
    6881             :                                 pszLayerName, pszLayerName, pszLayerName);
    6882           4 :             eErr = SQLCommand(hDB, pszSQL);
    6883           4 :             sqlite3_free(pszSQL);
    6884             :         }
    6885             : 
    6886           4 :         if (eErr == OGRERR_NONE && HasExtensionsTable())
    6887             :         {
    6888             :             // If there is no longer any mapping table, then completely
    6889             :             // remove any reference to the extension in gpkg_extensions
    6890             :             // as mandated per the related table specification.
    6891             :             OGRErr err;
    6892           4 :             if (SQLGetInteger(hDB,
    6893             :                               "SELECT COUNT(*) FROM gpkg_extensions WHERE "
    6894             :                               "extension_name IN ('related_tables', "
    6895             :                               "'gpkg_related_tables') AND "
    6896             :                               "lower(table_name) != 'gpkgext_relations'",
    6897           4 :                               &err) == 0)
    6898             :             {
    6899           2 :                 eErr = SQLCommand(hDB, "DELETE FROM gpkg_extensions WHERE "
    6900             :                                        "extension_name IN ('related_tables', "
    6901             :                                        "'gpkg_related_tables')");
    6902             :             }
    6903             : 
    6904           4 :             ClearCachedRelationships();
    6905             :         }
    6906             :     }
    6907             : 
    6908          40 :     if (eErr == OGRERR_NONE)
    6909             :     {
    6910          40 :         pszSQL = sqlite3_mprintf("DROP TABLE \"%w\"", pszLayerName);
    6911          40 :         eErr = SQLCommand(hDB, pszSQL);
    6912          40 :         sqlite3_free(pszSQL);
    6913             :     }
    6914             : 
    6915             :     // Check foreign key integrity
    6916          40 :     if (eErr == OGRERR_NONE)
    6917             :     {
    6918          40 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    6919             :     }
    6920             : 
    6921          80 :     return eErr;
    6922             : }
    6923             : 
    6924             : /************************************************************************/
    6925             : /*                            DeleteLayer()                             */
    6926             : /************************************************************************/
    6927             : 
    6928          37 : OGRErr GDALGeoPackageDataset::DeleteLayer(int iLayer)
    6929             : {
    6930          73 :     if (!GetUpdate() || iLayer < 0 ||
    6931          36 :         iLayer >= static_cast<int>(m_apoLayers.size()))
    6932           2 :         return OGRERR_FAILURE;
    6933             : 
    6934          35 :     m_apoLayers[iLayer]->ResetReading();
    6935          35 :     m_apoLayers[iLayer]->SyncToDisk();
    6936             : 
    6937          70 :     CPLString osLayerName = m_apoLayers[iLayer]->GetName();
    6938             : 
    6939          35 :     CPLDebug("GPKG", "DeleteLayer(%s)", osLayerName.c_str());
    6940             : 
    6941             :     // Temporary remove foreign key checks
    6942             :     const GPKGTemporaryForeignKeyCheckDisabler
    6943          35 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6944             : 
    6945          35 :     OGRErr eErr = SoftStartTransaction();
    6946             : 
    6947          35 :     if (eErr == OGRERR_NONE)
    6948             :     {
    6949          35 :         if (m_apoLayers[iLayer]->HasSpatialIndex())
    6950          32 :             m_apoLayers[iLayer]->DropSpatialIndex();
    6951             : 
    6952             :         char *pszSQL =
    6953          35 :             sqlite3_mprintf("DELETE FROM gpkg_geometry_columns WHERE "
    6954             :                             "lower(table_name) = lower('%q')",
    6955             :                             osLayerName.c_str());
    6956          35 :         eErr = SQLCommand(hDB, pszSQL);
    6957          35 :         sqlite3_free(pszSQL);
    6958             :     }
    6959             : 
    6960          35 :     if (eErr == OGRERR_NONE && HasDataColumnsTable())
    6961             :     {
    6962           1 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_data_columns WHERE "
    6963             :                                        "lower(table_name) = lower('%q')",
    6964             :                                        osLayerName.c_str());
    6965           1 :         eErr = SQLCommand(hDB, pszSQL);
    6966           1 :         sqlite3_free(pszSQL);
    6967             :     }
    6968             : 
    6969             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    6970          35 :     if (eErr == OGRERR_NONE && m_bHasGPKGOGRContents)
    6971             :     {
    6972          35 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_ogr_contents WHERE "
    6973             :                                        "lower(table_name) = lower('%q')",
    6974             :                                        osLayerName.c_str());
    6975          35 :         eErr = SQLCommand(hDB, pszSQL);
    6976          35 :         sqlite3_free(pszSQL);
    6977             :     }
    6978             : #endif
    6979             : 
    6980          35 :     if (eErr == OGRERR_NONE)
    6981             :     {
    6982          35 :         eErr = DeleteLayerCommon(osLayerName.c_str());
    6983             :     }
    6984             : 
    6985          35 :     if (eErr == OGRERR_NONE)
    6986             :     {
    6987          35 :         eErr = SoftCommitTransaction();
    6988          35 :         if (eErr == OGRERR_NONE)
    6989             :         {
    6990             :             /* Delete the layer object */
    6991          35 :             m_apoLayers.erase(m_apoLayers.begin() + iLayer);
    6992             :         }
    6993             :     }
    6994             :     else
    6995             :     {
    6996           0 :         SoftRollbackTransaction();
    6997             :     }
    6998             : 
    6999          35 :     return eErr;
    7000             : }
    7001             : 
    7002             : /************************************************************************/
    7003             : /*                       DeleteRasterLayer()                            */
    7004             : /************************************************************************/
    7005             : 
    7006           2 : OGRErr GDALGeoPackageDataset::DeleteRasterLayer(const char *pszLayerName)
    7007             : {
    7008             :     // Temporary remove foreign key checks
    7009             :     const GPKGTemporaryForeignKeyCheckDisabler
    7010           2 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7011             : 
    7012           2 :     OGRErr eErr = SoftStartTransaction();
    7013             : 
    7014           2 :     if (eErr == OGRERR_NONE)
    7015             :     {
    7016           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix WHERE "
    7017             :                                        "lower(table_name) = lower('%q')",
    7018             :                                        pszLayerName);
    7019           2 :         eErr = SQLCommand(hDB, pszSQL);
    7020           2 :         sqlite3_free(pszSQL);
    7021             :     }
    7022             : 
    7023           2 :     if (eErr == OGRERR_NONE)
    7024             :     {
    7025           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix_set WHERE "
    7026             :                                        "lower(table_name) = lower('%q')",
    7027             :                                        pszLayerName);
    7028           2 :         eErr = SQLCommand(hDB, pszSQL);
    7029           2 :         sqlite3_free(pszSQL);
    7030             :     }
    7031             : 
    7032           2 :     if (eErr == OGRERR_NONE && HasGriddedCoverageAncillaryTable())
    7033             :     {
    7034             :         char *pszSQL =
    7035           1 :             sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_coverage_ancillary "
    7036             :                             "WHERE lower(tile_matrix_set_name) = lower('%q')",
    7037             :                             pszLayerName);
    7038           1 :         eErr = SQLCommand(hDB, pszSQL);
    7039           1 :         sqlite3_free(pszSQL);
    7040             : 
    7041           1 :         if (eErr == OGRERR_NONE)
    7042             :         {
    7043             :             pszSQL =
    7044           1 :                 sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_tile_ancillary "
    7045             :                                 "WHERE lower(tpudt_name) = lower('%q')",
    7046             :                                 pszLayerName);
    7047           1 :             eErr = SQLCommand(hDB, pszSQL);
    7048           1 :             sqlite3_free(pszSQL);
    7049             :         }
    7050             :     }
    7051             : 
    7052           2 :     if (eErr == OGRERR_NONE)
    7053             :     {
    7054           2 :         eErr = DeleteLayerCommon(pszLayerName);
    7055             :     }
    7056             : 
    7057           2 :     if (eErr == OGRERR_NONE)
    7058             :     {
    7059           2 :         eErr = SoftCommitTransaction();
    7060             :     }
    7061             :     else
    7062             :     {
    7063           0 :         SoftRollbackTransaction();
    7064             :     }
    7065             : 
    7066           4 :     return eErr;
    7067             : }
    7068             : 
    7069             : /************************************************************************/
    7070             : /*                    DeleteVectorOrRasterLayer()                       */
    7071             : /************************************************************************/
    7072             : 
    7073          13 : bool GDALGeoPackageDataset::DeleteVectorOrRasterLayer(const char *pszLayerName)
    7074             : {
    7075             : 
    7076          13 :     int idx = FindLayerIndex(pszLayerName);
    7077          13 :     if (idx >= 0)
    7078             :     {
    7079           5 :         DeleteLayer(idx);
    7080           5 :         return true;
    7081             :     }
    7082             : 
    7083             :     char *pszSQL =
    7084           8 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7085             :                         "lower(table_name) = lower('%q') "
    7086             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7087             :                         pszLayerName);
    7088           8 :     bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7089           8 :     sqlite3_free(pszSQL);
    7090           8 :     if (bIsRasterTable)
    7091             :     {
    7092           2 :         DeleteRasterLayer(pszLayerName);
    7093           2 :         return true;
    7094             :     }
    7095           6 :     return false;
    7096             : }
    7097             : 
    7098           7 : bool GDALGeoPackageDataset::RenameVectorOrRasterLayer(
    7099             :     const char *pszLayerName, const char *pszNewLayerName)
    7100             : {
    7101           7 :     int idx = FindLayerIndex(pszLayerName);
    7102           7 :     if (idx >= 0)
    7103             :     {
    7104           4 :         m_apoLayers[idx]->Rename(pszNewLayerName);
    7105           4 :         return true;
    7106             :     }
    7107             : 
    7108             :     char *pszSQL =
    7109           3 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7110             :                         "lower(table_name) = lower('%q') "
    7111             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7112             :                         pszLayerName);
    7113           3 :     const bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7114           3 :     sqlite3_free(pszSQL);
    7115             : 
    7116           3 :     if (bIsRasterTable)
    7117             :     {
    7118           2 :         return RenameRasterLayer(pszLayerName, pszNewLayerName);
    7119             :     }
    7120             : 
    7121           1 :     return false;
    7122             : }
    7123             : 
    7124           2 : bool GDALGeoPackageDataset::RenameRasterLayer(const char *pszLayerName,
    7125             :                                               const char *pszNewLayerName)
    7126             : {
    7127           4 :     std::string osSQL;
    7128             : 
    7129           2 :     char *pszSQL = sqlite3_mprintf(
    7130             :         "SELECT 1 FROM sqlite_master WHERE lower(name) = lower('%q') "
    7131             :         "AND type IN ('table', 'view')",
    7132             :         pszNewLayerName);
    7133           2 :     const bool bAlreadyExists = SQLGetInteger(GetDB(), pszSQL, nullptr) == 1;
    7134           2 :     sqlite3_free(pszSQL);
    7135           2 :     if (bAlreadyExists)
    7136             :     {
    7137           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Table %s already exists",
    7138             :                  pszNewLayerName);
    7139           0 :         return false;
    7140             :     }
    7141             : 
    7142             :     // Temporary remove foreign key checks
    7143             :     const GPKGTemporaryForeignKeyCheckDisabler
    7144           4 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7145             : 
    7146           2 :     if (SoftStartTransaction() != OGRERR_NONE)
    7147             :     {
    7148           0 :         return false;
    7149             :     }
    7150             : 
    7151           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET table_name = '%q' WHERE "
    7152             :                              "lower(table_name) = lower('%q');",
    7153             :                              pszNewLayerName, pszLayerName);
    7154           2 :     osSQL = pszSQL;
    7155           2 :     sqlite3_free(pszSQL);
    7156             : 
    7157           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' WHERE "
    7158             :                              "lower(identifier) = lower('%q');",
    7159             :                              pszNewLayerName, pszLayerName);
    7160           2 :     osSQL += pszSQL;
    7161           2 :     sqlite3_free(pszSQL);
    7162             : 
    7163             :     pszSQL =
    7164           2 :         sqlite3_mprintf("UPDATE gpkg_tile_matrix SET table_name = '%q' WHERE "
    7165             :                         "lower(table_name) = lower('%q');",
    7166             :                         pszNewLayerName, pszLayerName);
    7167           2 :     osSQL += pszSQL;
    7168           2 :     sqlite3_free(pszSQL);
    7169             : 
    7170           2 :     pszSQL = sqlite3_mprintf(
    7171             :         "UPDATE gpkg_tile_matrix_set 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 :     if (HasGriddedCoverageAncillaryTable())
    7178             :     {
    7179           1 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_2d_gridded_coverage_ancillary "
    7180             :                                  "SET tile_matrix_set_name = '%q' WHERE "
    7181             :                                  "lower(tile_matrix_set_name) = lower('%q');",
    7182             :                                  pszNewLayerName, pszLayerName);
    7183           1 :         osSQL += pszSQL;
    7184           1 :         sqlite3_free(pszSQL);
    7185             : 
    7186           1 :         pszSQL = sqlite3_mprintf(
    7187             :             "UPDATE gpkg_2d_gridded_tile_ancillary SET tpudt_name = '%q' WHERE "
    7188             :             "lower(tpudt_name) = lower('%q');",
    7189             :             pszNewLayerName, pszLayerName);
    7190           1 :         osSQL += pszSQL;
    7191           1 :         sqlite3_free(pszSQL);
    7192             :     }
    7193             : 
    7194           2 :     if (HasExtensionsTable())
    7195             :     {
    7196           2 :         pszSQL = sqlite3_mprintf(
    7197             :             "UPDATE gpkg_extensions SET table_name = '%q' WHERE "
    7198             :             "lower(table_name) = lower('%q');",
    7199             :             pszNewLayerName, pszLayerName);
    7200           2 :         osSQL += pszSQL;
    7201           2 :         sqlite3_free(pszSQL);
    7202             :     }
    7203             : 
    7204           2 :     if (HasMetadataTables())
    7205             :     {
    7206           1 :         pszSQL = sqlite3_mprintf(
    7207             :             "UPDATE gpkg_metadata_reference SET table_name = '%q' WHERE "
    7208             :             "lower(table_name) = lower('%q');",
    7209             :             pszNewLayerName, pszLayerName);
    7210           1 :         osSQL += pszSQL;
    7211           1 :         sqlite3_free(pszSQL);
    7212             :     }
    7213             : 
    7214           2 :     if (HasDataColumnsTable())
    7215             :     {
    7216           0 :         pszSQL = sqlite3_mprintf(
    7217             :             "UPDATE gpkg_data_columns SET table_name = '%q' WHERE "
    7218             :             "lower(table_name) = lower('%q');",
    7219             :             pszNewLayerName, pszLayerName);
    7220           0 :         osSQL += pszSQL;
    7221           0 :         sqlite3_free(pszSQL);
    7222             :     }
    7223             : 
    7224           2 :     if (HasQGISLayerStyles())
    7225             :     {
    7226             :         // Update QGIS styles
    7227             :         pszSQL =
    7228           0 :             sqlite3_mprintf("UPDATE layer_styles SET f_table_name = '%q' WHERE "
    7229             :                             "lower(f_table_name) = lower('%q');",
    7230             :                             pszNewLayerName, pszLayerName);
    7231           0 :         osSQL += pszSQL;
    7232           0 :         sqlite3_free(pszSQL);
    7233             :     }
    7234             : 
    7235             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7236           2 :     if (m_bHasGPKGOGRContents)
    7237             :     {
    7238           2 :         pszSQL = sqlite3_mprintf(
    7239             :             "UPDATE gpkg_ogr_contents SET table_name = '%q' WHERE "
    7240             :             "lower(table_name) = lower('%q');",
    7241             :             pszNewLayerName, pszLayerName);
    7242           2 :         osSQL += pszSQL;
    7243           2 :         sqlite3_free(pszSQL);
    7244             :     }
    7245             : #endif
    7246             : 
    7247           2 :     if (HasGpkgextRelationsTable())
    7248             :     {
    7249           0 :         pszSQL = sqlite3_mprintf(
    7250             :             "UPDATE gpkgext_relations SET base_table_name = '%q' WHERE "
    7251             :             "lower(base_table_name) = lower('%q');",
    7252             :             pszNewLayerName, pszLayerName);
    7253           0 :         osSQL += pszSQL;
    7254           0 :         sqlite3_free(pszSQL);
    7255             : 
    7256           0 :         pszSQL = sqlite3_mprintf(
    7257             :             "UPDATE gpkgext_relations SET related_table_name = '%q' WHERE "
    7258             :             "lower(related_table_name) = lower('%q');",
    7259             :             pszNewLayerName, pszLayerName);
    7260           0 :         osSQL += pszSQL;
    7261           0 :         sqlite3_free(pszSQL);
    7262             : 
    7263           0 :         pszSQL = sqlite3_mprintf(
    7264             :             "UPDATE gpkgext_relations SET mapping_table_name = '%q' WHERE "
    7265             :             "lower(mapping_table_name) = lower('%q');",
    7266             :             pszNewLayerName, pszLayerName);
    7267           0 :         osSQL += pszSQL;
    7268           0 :         sqlite3_free(pszSQL);
    7269             :     }
    7270             : 
    7271             :     // Drop all triggers for the layer
    7272           2 :     pszSQL = sqlite3_mprintf("SELECT name FROM sqlite_master WHERE type = "
    7273             :                              "'trigger' AND tbl_name = '%q'",
    7274             :                              pszLayerName);
    7275           2 :     auto oTriggerResult = SQLQuery(GetDB(), pszSQL);
    7276           2 :     sqlite3_free(pszSQL);
    7277           2 :     if (oTriggerResult)
    7278             :     {
    7279          14 :         for (int i = 0; i < oTriggerResult->RowCount(); i++)
    7280             :         {
    7281          12 :             const char *pszTriggerName = oTriggerResult->GetValue(0, i);
    7282          12 :             pszSQL = sqlite3_mprintf("DROP TRIGGER IF EXISTS \"%w\";",
    7283             :                                      pszTriggerName);
    7284          12 :             osSQL += pszSQL;
    7285          12 :             sqlite3_free(pszSQL);
    7286             :         }
    7287             :     }
    7288             : 
    7289           2 :     pszSQL = sqlite3_mprintf("ALTER TABLE \"%w\" RENAME TO \"%w\";",
    7290             :                              pszLayerName, pszNewLayerName);
    7291           2 :     osSQL += pszSQL;
    7292           2 :     sqlite3_free(pszSQL);
    7293             : 
    7294             :     // Recreate all zoom/tile triggers
    7295           2 :     if (oTriggerResult)
    7296             :     {
    7297           2 :         osSQL += CreateRasterTriggersSQL(pszNewLayerName);
    7298             :     }
    7299             : 
    7300           2 :     OGRErr eErr = SQLCommand(GetDB(), osSQL.c_str());
    7301             : 
    7302             :     // Check foreign key integrity
    7303           2 :     if (eErr == OGRERR_NONE)
    7304             :     {
    7305           2 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    7306             :     }
    7307             : 
    7308           2 :     if (eErr == OGRERR_NONE)
    7309             :     {
    7310           2 :         eErr = SoftCommitTransaction();
    7311             :     }
    7312             :     else
    7313             :     {
    7314           0 :         SoftRollbackTransaction();
    7315             :     }
    7316             : 
    7317           2 :     return eErr == OGRERR_NONE;
    7318             : }
    7319             : 
    7320             : /************************************************************************/
    7321             : /*                       TestCapability()                               */
    7322             : /************************************************************************/
    7323             : 
    7324         449 : int GDALGeoPackageDataset::TestCapability(const char *pszCap)
    7325             : {
    7326         449 :     if (EQUAL(pszCap, ODsCCreateLayer) || EQUAL(pszCap, ODsCDeleteLayer) ||
    7327         284 :         EQUAL(pszCap, "RenameLayer"))
    7328             :     {
    7329         165 :         return GetUpdate();
    7330             :     }
    7331         284 :     else if (EQUAL(pszCap, ODsCCurveGeometries))
    7332          12 :         return TRUE;
    7333         272 :     else if (EQUAL(pszCap, ODsCMeasuredGeometries))
    7334           8 :         return TRUE;
    7335         264 :     else if (EQUAL(pszCap, ODsCZGeometries))
    7336           8 :         return TRUE;
    7337         256 :     else if (EQUAL(pszCap, ODsCRandomLayerWrite) ||
    7338         256 :              EQUAL(pszCap, GDsCAddRelationship) ||
    7339         256 :              EQUAL(pszCap, GDsCDeleteRelationship) ||
    7340         256 :              EQUAL(pszCap, GDsCUpdateRelationship) ||
    7341         256 :              EQUAL(pszCap, ODsCAddFieldDomain))
    7342           1 :         return GetUpdate();
    7343             : 
    7344         255 :     return OGRSQLiteBaseDataSource::TestCapability(pszCap);
    7345             : }
    7346             : 
    7347             : /************************************************************************/
    7348             : /*                       ResetReadingAllLayers()                        */
    7349             : /************************************************************************/
    7350             : 
    7351         204 : void GDALGeoPackageDataset::ResetReadingAllLayers()
    7352             : {
    7353         413 :     for (auto &poLayer : m_apoLayers)
    7354             :     {
    7355         209 :         poLayer->ResetReading();
    7356             :     }
    7357         204 : }
    7358             : 
    7359             : /************************************************************************/
    7360             : /*                             ExecuteSQL()                             */
    7361             : /************************************************************************/
    7362             : 
    7363             : static const char *const apszFuncsWithSideEffects[] = {
    7364             :     "CreateSpatialIndex",
    7365             :     "DisableSpatialIndex",
    7366             :     "HasSpatialIndex",
    7367             :     "RegisterGeometryExtension",
    7368             : };
    7369             : 
    7370        5650 : OGRLayer *GDALGeoPackageDataset::ExecuteSQL(const char *pszSQLCommand,
    7371             :                                             OGRGeometry *poSpatialFilter,
    7372             :                                             const char *pszDialect)
    7373             : 
    7374             : {
    7375        5650 :     m_bHasReadMetadataFromStorage = false;
    7376             : 
    7377        5650 :     FlushMetadata();
    7378             : 
    7379        5668 :     while (*pszSQLCommand != '\0' &&
    7380        5668 :            isspace(static_cast<unsigned char>(*pszSQLCommand)))
    7381          18 :         pszSQLCommand++;
    7382             : 
    7383       11300 :     CPLString osSQLCommand(pszSQLCommand);
    7384        5650 :     if (!osSQLCommand.empty() && osSQLCommand.back() == ';')
    7385          48 :         osSQLCommand.pop_back();
    7386             : 
    7387        5650 :     if (pszDialect == nullptr || !EQUAL(pszDialect, "DEBUG"))
    7388             :     {
    7389             :         // Some SQL commands will influence the feature count behind our
    7390             :         // back, so disable it in that case.
    7391             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7392             :         const bool bInsertOrDelete =
    7393        5581 :             osSQLCommand.ifind("insert into ") != std::string::npos ||
    7394        2460 :             osSQLCommand.ifind("insert or replace into ") !=
    7395        8041 :                 std::string::npos ||
    7396        2423 :             osSQLCommand.ifind("delete from ") != std::string::npos;
    7397             :         const bool bRollback =
    7398        5581 :             osSQLCommand.ifind("rollback ") != std::string::npos;
    7399             : #endif
    7400             : 
    7401        7410 :         for (auto &poLayer : m_apoLayers)
    7402             :         {
    7403        1829 :             if (poLayer->SyncToDisk() != OGRERR_NONE)
    7404           0 :                 return nullptr;
    7405             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7406        2034 :             if (bRollback ||
    7407         205 :                 (bInsertOrDelete &&
    7408         205 :                  osSQLCommand.ifind(poLayer->GetName()) != std::string::npos))
    7409             :             {
    7410         203 :                 poLayer->DisableFeatureCount();
    7411             :             }
    7412             : #endif
    7413             :         }
    7414             :     }
    7415             : 
    7416        5650 :     if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 0") ||
    7417        5649 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=0") ||
    7418        5649 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =0") ||
    7419        5649 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 0"))
    7420             :     {
    7421           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, false);
    7422             :     }
    7423        5649 :     else if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 1") ||
    7424        5648 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=1") ||
    7425        5648 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =1") ||
    7426        5648 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 1"))
    7427             :     {
    7428           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, true);
    7429             :     }
    7430             : 
    7431             :     /* -------------------------------------------------------------------- */
    7432             :     /*      DEBUG "SELECT nolock" command.                                  */
    7433             :     /* -------------------------------------------------------------------- */
    7434        5719 :     if (pszDialect != nullptr && EQUAL(pszDialect, "DEBUG") &&
    7435          69 :         EQUAL(osSQLCommand, "SELECT nolock"))
    7436             :     {
    7437           3 :         return new OGRSQLiteSingleFeatureLayer(osSQLCommand, m_bNoLock ? 1 : 0);
    7438             :     }
    7439             : 
    7440             :     /* -------------------------------------------------------------------- */
    7441             :     /*      Special case DELLAYER: command.                                 */
    7442             :     /* -------------------------------------------------------------------- */
    7443        5647 :     if (STARTS_WITH_CI(osSQLCommand, "DELLAYER:"))
    7444             :     {
    7445           4 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DELLAYER:");
    7446             : 
    7447           4 :         while (*pszLayerName == ' ')
    7448           0 :             pszLayerName++;
    7449             : 
    7450           4 :         if (!DeleteVectorOrRasterLayer(pszLayerName))
    7451             :         {
    7452           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7453             :                      pszLayerName);
    7454             :         }
    7455           4 :         return nullptr;
    7456             :     }
    7457             : 
    7458             :     /* -------------------------------------------------------------------- */
    7459             :     /*      Special case RECOMPUTE EXTENT ON command.                       */
    7460             :     /* -------------------------------------------------------------------- */
    7461        5643 :     if (STARTS_WITH_CI(osSQLCommand, "RECOMPUTE EXTENT ON "))
    7462             :     {
    7463             :         const char *pszLayerName =
    7464           4 :             osSQLCommand.c_str() + strlen("RECOMPUTE EXTENT ON ");
    7465             : 
    7466           4 :         while (*pszLayerName == ' ')
    7467           0 :             pszLayerName++;
    7468             : 
    7469           4 :         int idx = FindLayerIndex(pszLayerName);
    7470           4 :         if (idx >= 0)
    7471             :         {
    7472           4 :             m_apoLayers[idx]->RecomputeExtent();
    7473             :         }
    7474             :         else
    7475           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7476             :                      pszLayerName);
    7477           4 :         return nullptr;
    7478             :     }
    7479             : 
    7480             :     /* -------------------------------------------------------------------- */
    7481             :     /*      Intercept DROP TABLE                                            */
    7482             :     /* -------------------------------------------------------------------- */
    7483        5639 :     if (STARTS_WITH_CI(osSQLCommand, "DROP TABLE "))
    7484             :     {
    7485           9 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DROP TABLE ");
    7486             : 
    7487           9 :         while (*pszLayerName == ' ')
    7488           0 :             pszLayerName++;
    7489             : 
    7490           9 :         if (DeleteVectorOrRasterLayer(SQLUnescape(pszLayerName)))
    7491           4 :             return nullptr;
    7492             :     }
    7493             : 
    7494             :     /* -------------------------------------------------------------------- */
    7495             :     /*      Intercept ALTER TABLE src_table RENAME TO dst_table             */
    7496             :     /*      and       ALTER TABLE table RENAME COLUMN src_name TO dst_name  */
    7497             :     /*      and       ALTER TABLE table DROP COLUMN col_name                */
    7498             :     /*                                                                      */
    7499             :     /*      We do this because SQLite mechanisms can't deal with updating   */
    7500             :     /*      literal values in gpkg_ tables that refer to table and column   */
    7501             :     /*      names.                                                          */
    7502             :     /* -------------------------------------------------------------------- */
    7503        5635 :     if (STARTS_WITH_CI(osSQLCommand, "ALTER TABLE "))
    7504             :     {
    7505           9 :         char **papszTokens = SQLTokenize(osSQLCommand);
    7506             :         /* ALTER TABLE src_table RENAME TO dst_table */
    7507          16 :         if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "RENAME") &&
    7508           7 :             EQUAL(papszTokens[4], "TO"))
    7509             :         {
    7510           7 :             const char *pszSrcTableName = papszTokens[2];
    7511           7 :             const char *pszDstTableName = papszTokens[5];
    7512           7 :             if (RenameVectorOrRasterLayer(SQLUnescape(pszSrcTableName),
    7513          14 :                                           SQLUnescape(pszDstTableName)))
    7514             :             {
    7515           6 :                 CSLDestroy(papszTokens);
    7516           6 :                 return nullptr;
    7517             :             }
    7518             :         }
    7519             :         /* ALTER TABLE table RENAME COLUMN src_name TO dst_name */
    7520           2 :         else if (CSLCount(papszTokens) == 8 &&
    7521           1 :                  EQUAL(papszTokens[3], "RENAME") &&
    7522           3 :                  EQUAL(papszTokens[4], "COLUMN") && EQUAL(papszTokens[6], "TO"))
    7523             :         {
    7524           1 :             const char *pszTableName = papszTokens[2];
    7525           1 :             const char *pszSrcColumn = papszTokens[5];
    7526           1 :             const char *pszDstColumn = papszTokens[7];
    7527             :             OGRGeoPackageTableLayer *poLayer =
    7528           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7529           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7530           1 :             if (poLayer)
    7531             :             {
    7532           2 :                 int nSrcFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7533           2 :                     SQLUnescape(pszSrcColumn));
    7534           1 :                 if (nSrcFieldIdx >= 0)
    7535             :                 {
    7536             :                     // OFTString or any type will do as we just alter the name
    7537             :                     // so it will be ignored.
    7538           1 :                     OGRFieldDefn oFieldDefn(SQLUnescape(pszDstColumn),
    7539           1 :                                             OFTString);
    7540           1 :                     poLayer->AlterFieldDefn(nSrcFieldIdx, &oFieldDefn,
    7541             :                                             ALTER_NAME_FLAG);
    7542           1 :                     CSLDestroy(papszTokens);
    7543           1 :                     return nullptr;
    7544             :                 }
    7545             :             }
    7546             :         }
    7547             :         /* ALTER TABLE table DROP COLUMN col_name */
    7548           2 :         else if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "DROP") &&
    7549           1 :                  EQUAL(papszTokens[4], "COLUMN"))
    7550             :         {
    7551           1 :             const char *pszTableName = papszTokens[2];
    7552           1 :             const char *pszColumnName = papszTokens[5];
    7553             :             OGRGeoPackageTableLayer *poLayer =
    7554           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7555           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7556           1 :             if (poLayer)
    7557             :             {
    7558           2 :                 int nFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7559           2 :                     SQLUnescape(pszColumnName));
    7560           1 :                 if (nFieldIdx >= 0)
    7561             :                 {
    7562           1 :                     poLayer->DeleteField(nFieldIdx);
    7563           1 :                     CSLDestroy(papszTokens);
    7564           1 :                     return nullptr;
    7565             :                 }
    7566             :             }
    7567             :         }
    7568           1 :         CSLDestroy(papszTokens);
    7569             :     }
    7570             : 
    7571        5627 :     if (ProcessTransactionSQL(osSQLCommand))
    7572             :     {
    7573         253 :         return nullptr;
    7574             :     }
    7575             : 
    7576        5374 :     if (EQUAL(osSQLCommand, "VACUUM"))
    7577             :     {
    7578          13 :         ResetReadingAllLayers();
    7579             :     }
    7580        5361 :     else if (STARTS_WITH_CI(osSQLCommand, "DELETE FROM "))
    7581             :     {
    7582             :         // Optimize truncation of a table, especially if it has a spatial
    7583             :         // index.
    7584          24 :         const CPLStringList aosTokens(SQLTokenize(osSQLCommand));
    7585          24 :         if (aosTokens.size() == 3)
    7586             :         {
    7587          16 :             const char *pszTableName = aosTokens[2];
    7588             :             OGRGeoPackageTableLayer *poLayer =
    7589           8 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7590          24 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7591          16 :             if (poLayer)
    7592             :             {
    7593           8 :                 poLayer->Truncate();
    7594           8 :                 return nullptr;
    7595             :             }
    7596             :         }
    7597             :     }
    7598        5337 :     else if (pszDialect != nullptr && EQUAL(pszDialect, "INDIRECT_SQLITE"))
    7599           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter, "SQLITE");
    7600        5336 :     else if (pszDialect != nullptr && !EQUAL(pszDialect, "") &&
    7601          67 :              !EQUAL(pszDialect, "NATIVE") && !EQUAL(pszDialect, "SQLITE") &&
    7602          67 :              !EQUAL(pszDialect, "DEBUG"))
    7603           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter,
    7604           1 :                                        pszDialect);
    7605             : 
    7606             :     /* -------------------------------------------------------------------- */
    7607             :     /*      Prepare statement.                                              */
    7608             :     /* -------------------------------------------------------------------- */
    7609        5364 :     sqlite3_stmt *hSQLStmt = nullptr;
    7610             : 
    7611             :     /* This will speed-up layer creation */
    7612             :     /* ORDER BY are costly to evaluate and are not necessary to establish */
    7613             :     /* the layer definition. */
    7614        5364 :     bool bUseStatementForGetNextFeature = true;
    7615        5364 :     bool bEmptyLayer = false;
    7616       10728 :     CPLString osSQLCommandTruncated(osSQLCommand);
    7617             : 
    7618       17698 :     if (osSQLCommand.ifind("SELECT ") == 0 &&
    7619        6167 :         CPLString(osSQLCommand.substr(1)).ifind("SELECT ") ==
    7620         769 :             std::string::npos &&
    7621         769 :         osSQLCommand.ifind(" UNION ") == std::string::npos &&
    7622        6936 :         osSQLCommand.ifind(" INTERSECT ") == std::string::npos &&
    7623         769 :         osSQLCommand.ifind(" EXCEPT ") == std::string::npos)
    7624             :     {
    7625         769 :         size_t nOrderByPos = osSQLCommand.ifind(" ORDER BY ");
    7626         769 :         if (nOrderByPos != std::string::npos)
    7627             :         {
    7628           9 :             osSQLCommandTruncated.resize(nOrderByPos);
    7629           9 :             bUseStatementForGetNextFeature = false;
    7630             :         }
    7631             :     }
    7632             : 
    7633        5364 :     int rc = prepareSql(hDB, osSQLCommandTruncated.c_str(),
    7634        5364 :                         static_cast<int>(osSQLCommandTruncated.size()),
    7635             :                         &hSQLStmt, nullptr);
    7636             : 
    7637        5364 :     if (rc != SQLITE_OK)
    7638             :     {
    7639           9 :         CPLError(CE_Failure, CPLE_AppDefined,
    7640             :                  "In ExecuteSQL(): sqlite3_prepare_v2(%s): %s",
    7641             :                  osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7642             : 
    7643           9 :         if (hSQLStmt != nullptr)
    7644             :         {
    7645           0 :             sqlite3_finalize(hSQLStmt);
    7646             :         }
    7647             : 
    7648           9 :         return nullptr;
    7649             :     }
    7650             : 
    7651             :     /* -------------------------------------------------------------------- */
    7652             :     /*      Do we get a resultset?                                          */
    7653             :     /* -------------------------------------------------------------------- */
    7654        5355 :     rc = sqlite3_step(hSQLStmt);
    7655             : 
    7656        6949 :     for (auto &poLayer : m_apoLayers)
    7657             :     {
    7658        1594 :         poLayer->RunDeferredDropRTreeTableIfNecessary();
    7659             :     }
    7660             : 
    7661        5355 :     if (rc != SQLITE_ROW)
    7662             :     {
    7663        4633 :         if (rc != SQLITE_DONE)
    7664             :         {
    7665           7 :             CPLError(CE_Failure, CPLE_AppDefined,
    7666             :                      "In ExecuteSQL(): sqlite3_step(%s):\n  %s",
    7667             :                      osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7668             : 
    7669           7 :             sqlite3_finalize(hSQLStmt);
    7670           7 :             return nullptr;
    7671             :         }
    7672             : 
    7673        4626 :         if (EQUAL(osSQLCommand, "VACUUM"))
    7674             :         {
    7675          13 :             sqlite3_finalize(hSQLStmt);
    7676             :             /* VACUUM rewrites the DB, so we need to reset the application id */
    7677          13 :             SetApplicationAndUserVersionId();
    7678          13 :             return nullptr;
    7679             :         }
    7680             : 
    7681        4613 :         if (!STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7682             :         {
    7683        4488 :             sqlite3_finalize(hSQLStmt);
    7684        4488 :             return nullptr;
    7685             :         }
    7686             : 
    7687         125 :         bUseStatementForGetNextFeature = false;
    7688         125 :         bEmptyLayer = true;
    7689             :     }
    7690             : 
    7691             :     /* -------------------------------------------------------------------- */
    7692             :     /*      Special case for some functions which must be run               */
    7693             :     /*      only once                                                       */
    7694             :     /* -------------------------------------------------------------------- */
    7695         847 :     if (STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7696             :     {
    7697        3859 :         for (unsigned int i = 0; i < sizeof(apszFuncsWithSideEffects) /
    7698             :                                          sizeof(apszFuncsWithSideEffects[0]);
    7699             :              i++)
    7700             :         {
    7701        3113 :             if (EQUALN(apszFuncsWithSideEffects[i], osSQLCommand.c_str() + 7,
    7702             :                        strlen(apszFuncsWithSideEffects[i])))
    7703             :             {
    7704         112 :                 if (sqlite3_column_count(hSQLStmt) == 1 &&
    7705          56 :                     sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7706             :                 {
    7707          56 :                     int ret = sqlite3_column_int(hSQLStmt, 0);
    7708             : 
    7709          56 :                     sqlite3_finalize(hSQLStmt);
    7710             : 
    7711             :                     return new OGRSQLiteSingleFeatureLayer(
    7712          56 :                         apszFuncsWithSideEffects[i], ret);
    7713             :                 }
    7714             :             }
    7715             :         }
    7716             :     }
    7717          45 :     else if (STARTS_WITH_CI(osSQLCommand, "PRAGMA "))
    7718             :     {
    7719          63 :         if (sqlite3_column_count(hSQLStmt) == 1 &&
    7720          18 :             sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7721             :         {
    7722          15 :             int ret = sqlite3_column_int(hSQLStmt, 0);
    7723             : 
    7724          15 :             sqlite3_finalize(hSQLStmt);
    7725             : 
    7726          15 :             return new OGRSQLiteSingleFeatureLayer(osSQLCommand.c_str() + 7,
    7727          15 :                                                    ret);
    7728             :         }
    7729          33 :         else if (sqlite3_column_count(hSQLStmt) == 1 &&
    7730           3 :                  sqlite3_column_type(hSQLStmt, 0) == SQLITE_TEXT)
    7731             :         {
    7732             :             const char *pszRet = reinterpret_cast<const char *>(
    7733           3 :                 sqlite3_column_text(hSQLStmt, 0));
    7734             : 
    7735             :             OGRLayer *poRet = new OGRSQLiteSingleFeatureLayer(
    7736           3 :                 osSQLCommand.c_str() + 7, pszRet);
    7737             : 
    7738           3 :             sqlite3_finalize(hSQLStmt);
    7739             : 
    7740           3 :             return poRet;
    7741             :         }
    7742             :     }
    7743             : 
    7744             :     /* -------------------------------------------------------------------- */
    7745             :     /*      Create layer.                                                   */
    7746             :     /* -------------------------------------------------------------------- */
    7747             : 
    7748             :     auto poLayer = std::make_unique<OGRGeoPackageSelectLayer>(
    7749             :         this, osSQLCommand, hSQLStmt, bUseStatementForGetNextFeature,
    7750        1546 :         bEmptyLayer);
    7751             : 
    7752         776 :     if (poSpatialFilter != nullptr &&
    7753           3 :         poLayer->GetLayerDefn()->GetGeomFieldCount() > 0)
    7754           3 :         poLayer->SetSpatialFilter(0, poSpatialFilter);
    7755             : 
    7756         773 :     return poLayer.release();
    7757             : }
    7758             : 
    7759             : /************************************************************************/
    7760             : /*                          ReleaseResultSet()                          */
    7761             : /************************************************************************/
    7762             : 
    7763         806 : void GDALGeoPackageDataset::ReleaseResultSet(OGRLayer *poLayer)
    7764             : 
    7765             : {
    7766         806 :     delete poLayer;
    7767         806 : }
    7768             : 
    7769             : /************************************************************************/
    7770             : /*                         HasExtensionsTable()                         */
    7771             : /************************************************************************/
    7772             : 
    7773        6513 : bool GDALGeoPackageDataset::HasExtensionsTable()
    7774             : {
    7775        6513 :     return SQLGetInteger(
    7776             :                hDB,
    7777             :                "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_extensions' "
    7778             :                "AND type IN ('table', 'view')",
    7779        6513 :                nullptr) == 1;
    7780             : }
    7781             : 
    7782             : /************************************************************************/
    7783             : /*                    CheckUnknownExtensions()                          */
    7784             : /************************************************************************/
    7785             : 
    7786        1476 : void GDALGeoPackageDataset::CheckUnknownExtensions(bool bCheckRasterTable)
    7787             : {
    7788        1476 :     if (!HasExtensionsTable())
    7789         197 :         return;
    7790             : 
    7791        1279 :     char *pszSQL = nullptr;
    7792        1279 :     if (!bCheckRasterTable)
    7793        1071 :         pszSQL = sqlite3_mprintf(
    7794             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7795             :             "WHERE (table_name IS NULL "
    7796             :             "AND extension_name IS NOT NULL "
    7797             :             "AND definition IS NOT NULL "
    7798             :             "AND scope IS NOT NULL "
    7799             :             "AND extension_name NOT IN ("
    7800             :             "'gdal_aspatial', "
    7801             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7802             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7803             :                                        // 17-066r1 finalization
    7804             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7805             :             "'gpkg_metadata', "
    7806             :             "'gpkg_schema', "
    7807             :             "'gpkg_crs_wkt', "
    7808             :             "'gpkg_crs_wkt_1_1', "
    7809             :             "'related_tables', 'gpkg_related_tables')) "
    7810             : #ifdef WORKAROUND_SQLITE3_BUGS
    7811             :             "OR 0 "
    7812             : #endif
    7813             :             "LIMIT 1000");
    7814             :     else
    7815         208 :         pszSQL = sqlite3_mprintf(
    7816             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7817             :             "WHERE (lower(table_name) = lower('%q') "
    7818             :             "AND extension_name IS NOT NULL "
    7819             :             "AND definition IS NOT NULL "
    7820             :             "AND scope IS NOT NULL "
    7821             :             "AND extension_name NOT IN ("
    7822             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7823             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7824             :                                        // 17-066r1 finalization
    7825             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7826             :             "'gpkg_metadata', "
    7827             :             "'gpkg_schema', "
    7828             :             "'gpkg_crs_wkt', "
    7829             :             "'gpkg_crs_wkt_1_1', "
    7830             :             "'related_tables', 'gpkg_related_tables')) "
    7831             : #ifdef WORKAROUND_SQLITE3_BUGS
    7832             :             "OR 0 "
    7833             : #endif
    7834             :             "LIMIT 1000",
    7835             :             m_osRasterTable.c_str());
    7836             : 
    7837        2558 :     auto oResultTable = SQLQuery(GetDB(), pszSQL);
    7838        1279 :     sqlite3_free(pszSQL);
    7839        1279 :     if (oResultTable && oResultTable->RowCount() > 0)
    7840             :     {
    7841          42 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    7842             :         {
    7843          21 :             const char *pszExtName = oResultTable->GetValue(0, i);
    7844          21 :             const char *pszDefinition = oResultTable->GetValue(1, i);
    7845          21 :             const char *pszScope = oResultTable->GetValue(2, i);
    7846          21 :             if (pszExtName == nullptr || pszDefinition == nullptr ||
    7847             :                 pszScope == nullptr)
    7848             :             {
    7849           0 :                 continue;
    7850             :             }
    7851             : 
    7852          21 :             if (EQUAL(pszExtName, "gpkg_webp"))
    7853             :             {
    7854          15 :                 if (GDALGetDriverByName("WEBP") == nullptr)
    7855             :                 {
    7856           1 :                     CPLError(
    7857             :                         CE_Warning, CPLE_AppDefined,
    7858             :                         "Table %s contains WEBP tiles, but GDAL configured "
    7859             :                         "without WEBP support. Data will be missing",
    7860             :                         m_osRasterTable.c_str());
    7861             :                 }
    7862          15 :                 m_eTF = GPKG_TF_WEBP;
    7863          15 :                 continue;
    7864             :             }
    7865           6 :             if (EQUAL(pszExtName, "gpkg_zoom_other"))
    7866             :             {
    7867           2 :                 m_bZoomOther = true;
    7868           2 :                 continue;
    7869             :             }
    7870             : 
    7871           4 :             if (GetUpdate() && EQUAL(pszScope, "write-only"))
    7872             :             {
    7873           1 :                 CPLError(
    7874             :                     CE_Warning, CPLE_AppDefined,
    7875             :                     "Database relies on the '%s' (%s) extension that should "
    7876             :                     "be implemented for safe write-support, but is not "
    7877             :                     "currently. "
    7878             :                     "Update of that database are strongly discouraged to avoid "
    7879             :                     "corruption.",
    7880             :                     pszExtName, pszDefinition);
    7881             :             }
    7882           3 :             else if (GetUpdate() && EQUAL(pszScope, "read-write"))
    7883             :             {
    7884           1 :                 CPLError(
    7885             :                     CE_Warning, CPLE_AppDefined,
    7886             :                     "Database relies on the '%s' (%s) extension that should "
    7887             :                     "be implemented in order to read/write it safely, but is "
    7888             :                     "not currently. "
    7889             :                     "Some data may be missing while reading that database, and "
    7890             :                     "updates are strongly discouraged.",
    7891             :                     pszExtName, pszDefinition);
    7892             :             }
    7893           2 :             else if (EQUAL(pszScope, "read-write") &&
    7894             :                      // None of the NGA extensions at
    7895             :                      // http://ngageoint.github.io/GeoPackage/docs/extensions/
    7896             :                      // affect read-only scenarios
    7897           1 :                      !STARTS_WITH(pszExtName, "nga_"))
    7898             :             {
    7899           1 :                 CPLError(
    7900             :                     CE_Warning, CPLE_AppDefined,
    7901             :                     "Database relies on the '%s' (%s) extension that should "
    7902             :                     "be implemented in order to read it safely, but is not "
    7903             :                     "currently. "
    7904             :                     "Some data may be missing while reading that database.",
    7905             :                     pszExtName, pszDefinition);
    7906             :             }
    7907             :         }
    7908             :     }
    7909             : }
    7910             : 
    7911             : /************************************************************************/
    7912             : /*                         HasGDALAspatialExtension()                       */
    7913             : /************************************************************************/
    7914             : 
    7915        1021 : bool GDALGeoPackageDataset::HasGDALAspatialExtension()
    7916             : {
    7917        1021 :     if (!HasExtensionsTable())
    7918          90 :         return false;
    7919             : 
    7920             :     auto oResultTable = SQLQuery(hDB, "SELECT * FROM gpkg_extensions "
    7921             :                                       "WHERE (extension_name = 'gdal_aspatial' "
    7922             :                                       "AND table_name IS NULL "
    7923             :                                       "AND column_name IS NULL)"
    7924             : #ifdef WORKAROUND_SQLITE3_BUGS
    7925             :                                       " OR 0"
    7926             : #endif
    7927         931 :     );
    7928         931 :     bool bHasExtension = (oResultTable && oResultTable->RowCount() == 1);
    7929         931 :     return bHasExtension;
    7930             : }
    7931             : 
    7932             : std::string
    7933         190 : GDALGeoPackageDataset::CreateRasterTriggersSQL(const std::string &osTableName)
    7934             : {
    7935             :     char *pszSQL;
    7936         190 :     std::string osSQL;
    7937             :     /* From D.5. sample_tile_pyramid Table 43. tiles table Trigger
    7938             :      * Definition SQL  */
    7939         190 :     pszSQL = sqlite3_mprintf(
    7940             :         "CREATE TRIGGER \"%w_zoom_insert\" "
    7941             :         "BEFORE INSERT ON \"%w\" "
    7942             :         "FOR EACH ROW BEGIN "
    7943             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7944             :         "constraint: zoom_level not specified for table in "
    7945             :         "gpkg_tile_matrix') "
    7946             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7947             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7948             :         "END; "
    7949             :         "CREATE TRIGGER \"%w_zoom_update\" "
    7950             :         "BEFORE UPDATE OF zoom_level ON \"%w\" "
    7951             :         "FOR EACH ROW BEGIN "
    7952             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7953             :         "constraint: zoom_level not specified for table in "
    7954             :         "gpkg_tile_matrix') "
    7955             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7956             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7957             :         "END; "
    7958             :         "CREATE TRIGGER \"%w_tile_column_insert\" "
    7959             :         "BEFORE INSERT ON \"%w\" "
    7960             :         "FOR EACH ROW BEGIN "
    7961             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7962             :         "constraint: tile_column cannot be < 0') "
    7963             :         "WHERE (NEW.tile_column < 0) ; "
    7964             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7965             :         "constraint: tile_column must by < matrix_width specified for "
    7966             :         "table and zoom level in gpkg_tile_matrix') "
    7967             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    7968             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    7969             :         "zoom_level = NEW.zoom_level)); "
    7970             :         "END; "
    7971             :         "CREATE TRIGGER \"%w_tile_column_update\" "
    7972             :         "BEFORE UPDATE OF tile_column ON \"%w\" "
    7973             :         "FOR EACH ROW BEGIN "
    7974             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7975             :         "constraint: tile_column cannot be < 0') "
    7976             :         "WHERE (NEW.tile_column < 0) ; "
    7977             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7978             :         "constraint: tile_column must by < matrix_width specified for "
    7979             :         "table and zoom level in gpkg_tile_matrix') "
    7980             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    7981             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    7982             :         "zoom_level = NEW.zoom_level)); "
    7983             :         "END; "
    7984             :         "CREATE TRIGGER \"%w_tile_row_insert\" "
    7985             :         "BEFORE INSERT ON \"%w\" "
    7986             :         "FOR EACH ROW BEGIN "
    7987             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7988             :         "constraint: tile_row cannot be < 0') "
    7989             :         "WHERE (NEW.tile_row < 0) ; "
    7990             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7991             :         "constraint: tile_row must by < matrix_height specified for "
    7992             :         "table and zoom level in gpkg_tile_matrix') "
    7993             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    7994             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    7995             :         "zoom_level = NEW.zoom_level)); "
    7996             :         "END; "
    7997             :         "CREATE TRIGGER \"%w_tile_row_update\" "
    7998             :         "BEFORE UPDATE OF tile_row ON \"%w\" "
    7999             :         "FOR EACH ROW BEGIN "
    8000             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8001             :         "constraint: tile_row cannot be < 0') "
    8002             :         "WHERE (NEW.tile_row < 0) ; "
    8003             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8004             :         "constraint: tile_row must by < matrix_height specified for "
    8005             :         "table and zoom level in gpkg_tile_matrix') "
    8006             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8007             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8008             :         "zoom_level = NEW.zoom_level)); "
    8009             :         "END; ",
    8010             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8011             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8012             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8013             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8014             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8015             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8016             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8017             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8018             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8019             :         osTableName.c_str());
    8020         190 :     osSQL = pszSQL;
    8021         190 :     sqlite3_free(pszSQL);
    8022         190 :     return osSQL;
    8023             : }
    8024             : 
    8025             : /************************************************************************/
    8026             : /*                  CreateExtensionsTableIfNecessary()                  */
    8027             : /************************************************************************/
    8028             : 
    8029        1159 : OGRErr GDALGeoPackageDataset::CreateExtensionsTableIfNecessary()
    8030             : {
    8031             :     /* Check if the table gpkg_extensions exists */
    8032        1159 :     if (HasExtensionsTable())
    8033         410 :         return OGRERR_NONE;
    8034             : 
    8035             :     /* Requirement 79 : Every extension of a GeoPackage SHALL be registered */
    8036             :     /* in a corresponding row in the gpkg_extensions table. The absence of a */
    8037             :     /* gpkg_extensions table or the absence of rows in gpkg_extensions table */
    8038             :     /* SHALL both indicate the absence of extensions to a GeoPackage. */
    8039         749 :     const char *pszCreateGpkgExtensions =
    8040             :         "CREATE TABLE gpkg_extensions ("
    8041             :         "table_name TEXT,"
    8042             :         "column_name TEXT,"
    8043             :         "extension_name TEXT NOT NULL,"
    8044             :         "definition TEXT NOT NULL,"
    8045             :         "scope TEXT NOT NULL,"
    8046             :         "CONSTRAINT ge_tce UNIQUE (table_name, column_name, extension_name)"
    8047             :         ")";
    8048             : 
    8049         749 :     return SQLCommand(hDB, pszCreateGpkgExtensions);
    8050             : }
    8051             : 
    8052             : /************************************************************************/
    8053             : /*                    OGR_GPKG_Intersects_Spatial_Filter()              */
    8054             : /************************************************************************/
    8055             : 
    8056       23135 : void OGR_GPKG_Intersects_Spatial_Filter(sqlite3_context *pContext, int argc,
    8057             :                                         sqlite3_value **argv)
    8058             : {
    8059       23135 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8060             :     {
    8061           0 :         sqlite3_result_int(pContext, 0);
    8062       23125 :         return;
    8063             :     }
    8064             : 
    8065             :     auto poLayer =
    8066       23135 :         static_cast<OGRGeoPackageTableLayer *>(sqlite3_user_data(pContext));
    8067             : 
    8068       23135 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8069             :     const GByte *pabyBLOB =
    8070       23135 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8071             : 
    8072             :     GPkgHeader sHeader;
    8073       46270 :     if (poLayer->m_bFilterIsEnvelope &&
    8074       23135 :         OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false, 0))
    8075             :     {
    8076       23135 :         if (sHeader.bExtentHasXY)
    8077             :         {
    8078          95 :             OGREnvelope sEnvelope;
    8079          95 :             sEnvelope.MinX = sHeader.MinX;
    8080          95 :             sEnvelope.MinY = sHeader.MinY;
    8081          95 :             sEnvelope.MaxX = sHeader.MaxX;
    8082          95 :             sEnvelope.MaxY = sHeader.MaxY;
    8083          95 :             if (poLayer->m_sFilterEnvelope.Contains(sEnvelope))
    8084             :             {
    8085          31 :                 sqlite3_result_int(pContext, 1);
    8086          31 :                 return;
    8087             :             }
    8088             :         }
    8089             : 
    8090             :         // Check if at least one point falls into the layer filter envelope
    8091             :         // nHeaderLen is > 0 for GeoPackage geometries
    8092       46208 :         if (sHeader.nHeaderLen > 0 &&
    8093       23104 :             OGRWKBIntersectsPessimistic(pabyBLOB + sHeader.nHeaderLen,
    8094       23104 :                                         nBLOBLen - sHeader.nHeaderLen,
    8095       23104 :                                         poLayer->m_sFilterEnvelope))
    8096             :         {
    8097       23094 :             sqlite3_result_int(pContext, 1);
    8098       23094 :             return;
    8099             :         }
    8100             :     }
    8101             : 
    8102             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8103          10 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8104          10 :     if (poGeom == nullptr)
    8105             :     {
    8106             :         // Try also spatialite geometry blobs
    8107           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8108           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8109           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8110             :         {
    8111           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8112           0 :             sqlite3_result_int(pContext, 0);
    8113           0 :             return;
    8114             :         }
    8115           0 :         poGeom.reset(poGeomSpatialite);
    8116             :     }
    8117             : 
    8118          10 :     sqlite3_result_int(pContext, poLayer->FilterGeometry(poGeom.get()));
    8119             : }
    8120             : 
    8121             : /************************************************************************/
    8122             : /*                      OGRGeoPackageSTMinX()                           */
    8123             : /************************************************************************/
    8124             : 
    8125      243781 : static void OGRGeoPackageSTMinX(sqlite3_context *pContext, int argc,
    8126             :                                 sqlite3_value **argv)
    8127             : {
    8128             :     GPkgHeader sHeader;
    8129      243781 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8130             :     {
    8131           3 :         sqlite3_result_null(pContext);
    8132           3 :         return;
    8133             :     }
    8134      243778 :     sqlite3_result_double(pContext, sHeader.MinX);
    8135             : }
    8136             : 
    8137             : /************************************************************************/
    8138             : /*                      OGRGeoPackageSTMinY()                           */
    8139             : /************************************************************************/
    8140             : 
    8141      243779 : static void OGRGeoPackageSTMinY(sqlite3_context *pContext, int argc,
    8142             :                                 sqlite3_value **argv)
    8143             : {
    8144             :     GPkgHeader sHeader;
    8145      243779 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8146             :     {
    8147           1 :         sqlite3_result_null(pContext);
    8148           1 :         return;
    8149             :     }
    8150      243778 :     sqlite3_result_double(pContext, sHeader.MinY);
    8151             : }
    8152             : 
    8153             : /************************************************************************/
    8154             : /*                      OGRGeoPackageSTMaxX()                           */
    8155             : /************************************************************************/
    8156             : 
    8157      243779 : static void OGRGeoPackageSTMaxX(sqlite3_context *pContext, int argc,
    8158             :                                 sqlite3_value **argv)
    8159             : {
    8160             :     GPkgHeader sHeader;
    8161      243779 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8162             :     {
    8163           1 :         sqlite3_result_null(pContext);
    8164           1 :         return;
    8165             :     }
    8166      243778 :     sqlite3_result_double(pContext, sHeader.MaxX);
    8167             : }
    8168             : 
    8169             : /************************************************************************/
    8170             : /*                      OGRGeoPackageSTMaxY()                           */
    8171             : /************************************************************************/
    8172             : 
    8173      243779 : static void OGRGeoPackageSTMaxY(sqlite3_context *pContext, int argc,
    8174             :                                 sqlite3_value **argv)
    8175             : {
    8176             :     GPkgHeader sHeader;
    8177      243779 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8178             :     {
    8179           1 :         sqlite3_result_null(pContext);
    8180           1 :         return;
    8181             :     }
    8182      243778 :     sqlite3_result_double(pContext, sHeader.MaxY);
    8183             : }
    8184             : 
    8185             : /************************************************************************/
    8186             : /*                     OGRGeoPackageSTIsEmpty()                         */
    8187             : /************************************************************************/
    8188             : 
    8189      245184 : static void OGRGeoPackageSTIsEmpty(sqlite3_context *pContext, int argc,
    8190             :                                    sqlite3_value **argv)
    8191             : {
    8192             :     GPkgHeader sHeader;
    8193      245184 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8194             :     {
    8195           2 :         sqlite3_result_null(pContext);
    8196           2 :         return;
    8197             :     }
    8198      245182 :     sqlite3_result_int(pContext, sHeader.bEmpty);
    8199             : }
    8200             : 
    8201             : /************************************************************************/
    8202             : /*                    OGRGeoPackageSTGeometryType()                     */
    8203             : /************************************************************************/
    8204             : 
    8205           7 : static void OGRGeoPackageSTGeometryType(sqlite3_context *pContext, int /*argc*/,
    8206             :                                         sqlite3_value **argv)
    8207             : {
    8208             :     GPkgHeader sHeader;
    8209             : 
    8210           7 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8211             :     const GByte *pabyBLOB =
    8212           7 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8213             :     OGRwkbGeometryType eGeometryType;
    8214             : 
    8215          13 :     if (nBLOBLen < 8 ||
    8216           6 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8217             :     {
    8218           2 :         if (OGRSQLiteGetSpatialiteGeometryHeader(
    8219             :                 pabyBLOB, nBLOBLen, nullptr, &eGeometryType, nullptr, nullptr,
    8220           2 :                 nullptr, nullptr, nullptr) == OGRERR_NONE)
    8221             :         {
    8222           1 :             sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8223             :                                 SQLITE_TRANSIENT);
    8224           4 :             return;
    8225             :         }
    8226             :         else
    8227             :         {
    8228           1 :             sqlite3_result_null(pContext);
    8229           1 :             return;
    8230             :         }
    8231             :     }
    8232             : 
    8233           5 :     if (static_cast<size_t>(nBLOBLen) < sHeader.nHeaderLen + 5)
    8234             :     {
    8235           2 :         sqlite3_result_null(pContext);
    8236           2 :         return;
    8237             :     }
    8238             : 
    8239           3 :     OGRErr err = OGRReadWKBGeometryType(pabyBLOB + sHeader.nHeaderLen,
    8240             :                                         wkbVariantIso, &eGeometryType);
    8241           3 :     if (err != OGRERR_NONE)
    8242           1 :         sqlite3_result_null(pContext);
    8243             :     else
    8244           2 :         sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8245             :                             SQLITE_TRANSIENT);
    8246             : }
    8247             : 
    8248             : /************************************************************************/
    8249             : /*                 OGRGeoPackageSTEnvelopesIntersects()                 */
    8250             : /************************************************************************/
    8251             : 
    8252         118 : static void OGRGeoPackageSTEnvelopesIntersects(sqlite3_context *pContext,
    8253             :                                                int argc, sqlite3_value **argv)
    8254             : {
    8255             :     GPkgHeader sHeader;
    8256         118 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8257             :     {
    8258           2 :         sqlite3_result_int(pContext, FALSE);
    8259         107 :         return;
    8260             :     }
    8261         116 :     const double dfMinX = sqlite3_value_double(argv[1]);
    8262         116 :     if (sHeader.MaxX < dfMinX)
    8263             :     {
    8264          93 :         sqlite3_result_int(pContext, FALSE);
    8265          93 :         return;
    8266             :     }
    8267          23 :     const double dfMinY = sqlite3_value_double(argv[2]);
    8268          23 :     if (sHeader.MaxY < dfMinY)
    8269             :     {
    8270          11 :         sqlite3_result_int(pContext, FALSE);
    8271          11 :         return;
    8272             :     }
    8273          12 :     const double dfMaxX = sqlite3_value_double(argv[3]);
    8274          12 :     if (sHeader.MinX > dfMaxX)
    8275             :     {
    8276           1 :         sqlite3_result_int(pContext, FALSE);
    8277           1 :         return;
    8278             :     }
    8279          11 :     const double dfMaxY = sqlite3_value_double(argv[4]);
    8280          11 :     sqlite3_result_int(pContext, sHeader.MinY <= dfMaxY);
    8281             : }
    8282             : 
    8283             : /************************************************************************/
    8284             : /*              OGRGeoPackageSTEnvelopesIntersectsTwoParams()           */
    8285             : /************************************************************************/
    8286             : 
    8287             : static void
    8288           3 : OGRGeoPackageSTEnvelopesIntersectsTwoParams(sqlite3_context *pContext, int argc,
    8289             :                                             sqlite3_value **argv)
    8290             : {
    8291             :     GPkgHeader sHeader;
    8292           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false, 0))
    8293             :     {
    8294           0 :         sqlite3_result_int(pContext, FALSE);
    8295           2 :         return;
    8296             :     }
    8297             :     GPkgHeader sHeader2;
    8298           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader2, true, false,
    8299             :                                 1))
    8300             :     {
    8301           0 :         sqlite3_result_int(pContext, FALSE);
    8302           0 :         return;
    8303             :     }
    8304           3 :     if (sHeader.MaxX < sHeader2.MinX)
    8305             :     {
    8306           1 :         sqlite3_result_int(pContext, FALSE);
    8307           1 :         return;
    8308             :     }
    8309           2 :     if (sHeader.MaxY < sHeader2.MinY)
    8310             :     {
    8311           0 :         sqlite3_result_int(pContext, FALSE);
    8312           0 :         return;
    8313             :     }
    8314           2 :     if (sHeader.MinX > sHeader2.MaxX)
    8315             :     {
    8316           1 :         sqlite3_result_int(pContext, FALSE);
    8317           1 :         return;
    8318             :     }
    8319           1 :     sqlite3_result_int(pContext, sHeader.MinY <= sHeader2.MaxY);
    8320             : }
    8321             : 
    8322             : /************************************************************************/
    8323             : /*                    OGRGeoPackageGPKGIsAssignable()                   */
    8324             : /************************************************************************/
    8325             : 
    8326           8 : static void OGRGeoPackageGPKGIsAssignable(sqlite3_context *pContext,
    8327             :                                           int /*argc*/, sqlite3_value **argv)
    8328             : {
    8329          15 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8330           7 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8331             :     {
    8332           2 :         sqlite3_result_int(pContext, 0);
    8333           2 :         return;
    8334             :     }
    8335             : 
    8336             :     const char *pszExpected =
    8337           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8338             :     const char *pszActual =
    8339           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8340           6 :     int bIsAssignable = OGR_GT_IsSubClassOf(OGRFromOGCGeomType(pszActual),
    8341             :                                             OGRFromOGCGeomType(pszExpected));
    8342           6 :     sqlite3_result_int(pContext, bIsAssignable);
    8343             : }
    8344             : 
    8345             : /************************************************************************/
    8346             : /*                     OGRGeoPackageSTSRID()                            */
    8347             : /************************************************************************/
    8348             : 
    8349          12 : static void OGRGeoPackageSTSRID(sqlite3_context *pContext, int argc,
    8350             :                                 sqlite3_value **argv)
    8351             : {
    8352             :     GPkgHeader sHeader;
    8353          12 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8354             :     {
    8355           2 :         sqlite3_result_null(pContext);
    8356           2 :         return;
    8357             :     }
    8358          10 :     sqlite3_result_int(pContext, sHeader.iSrsId);
    8359             : }
    8360             : 
    8361             : /************************************************************************/
    8362             : /*                     OGRGeoPackageSetSRID()                           */
    8363             : /************************************************************************/
    8364             : 
    8365          28 : static void OGRGeoPackageSetSRID(sqlite3_context *pContext, int /* argc */,
    8366             :                                  sqlite3_value **argv)
    8367             : {
    8368          28 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8369             :     {
    8370           1 :         sqlite3_result_null(pContext);
    8371           1 :         return;
    8372             :     }
    8373          27 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8374             :     GPkgHeader sHeader;
    8375          27 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8376             :     const GByte *pabyBLOB =
    8377          27 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8378             : 
    8379          54 :     if (nBLOBLen < 8 ||
    8380          27 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8381             :     {
    8382             :         // Try also spatialite geometry blobs
    8383           0 :         OGRGeometry *poGeom = nullptr;
    8384           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeom) !=
    8385             :             OGRERR_NONE)
    8386             :         {
    8387           0 :             sqlite3_result_null(pContext);
    8388           0 :             return;
    8389             :         }
    8390           0 :         size_t nBLOBDestLen = 0;
    8391             :         GByte *pabyDestBLOB =
    8392           0 :             GPkgGeometryFromOGR(poGeom, nDestSRID, nullptr, &nBLOBDestLen);
    8393           0 :         if (!pabyDestBLOB)
    8394             :         {
    8395           0 :             sqlite3_result_null(pContext);
    8396           0 :             return;
    8397             :         }
    8398           0 :         sqlite3_result_blob(pContext, pabyDestBLOB,
    8399             :                             static_cast<int>(nBLOBDestLen), VSIFree);
    8400           0 :         return;
    8401             :     }
    8402             : 
    8403          27 :     GByte *pabyDestBLOB = static_cast<GByte *>(CPLMalloc(nBLOBLen));
    8404          27 :     memcpy(pabyDestBLOB, pabyBLOB, nBLOBLen);
    8405          27 :     int32_t nSRIDToSerialize = nDestSRID;
    8406          27 :     if (OGR_SWAP(sHeader.eByteOrder))
    8407           0 :         nSRIDToSerialize = CPL_SWAP32(nSRIDToSerialize);
    8408          27 :     memcpy(pabyDestBLOB + 4, &nSRIDToSerialize, 4);
    8409          27 :     sqlite3_result_blob(pContext, pabyDestBLOB, nBLOBLen, VSIFree);
    8410             : }
    8411             : 
    8412             : /************************************************************************/
    8413             : /*                   OGRGeoPackageSTMakeValid()                         */
    8414             : /************************************************************************/
    8415             : 
    8416           3 : static void OGRGeoPackageSTMakeValid(sqlite3_context *pContext, int argc,
    8417             :                                      sqlite3_value **argv)
    8418             : {
    8419           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8420             :     {
    8421           2 :         sqlite3_result_null(pContext);
    8422           2 :         return;
    8423             :     }
    8424           1 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8425             :     const GByte *pabyBLOB =
    8426           1 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8427             : 
    8428             :     GPkgHeader sHeader;
    8429           1 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8430             :     {
    8431           0 :         sqlite3_result_null(pContext);
    8432           0 :         return;
    8433             :     }
    8434             : 
    8435             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8436           1 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8437           1 :     if (poGeom == nullptr)
    8438             :     {
    8439             :         // Try also spatialite geometry blobs
    8440           0 :         OGRGeometry *poGeomPtr = nullptr;
    8441           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8442             :             OGRERR_NONE)
    8443             :         {
    8444           0 :             sqlite3_result_null(pContext);
    8445           0 :             return;
    8446             :         }
    8447           0 :         poGeom.reset(poGeomPtr);
    8448             :     }
    8449           1 :     auto poValid = std::unique_ptr<OGRGeometry>(poGeom->MakeValid());
    8450           1 :     if (poValid == nullptr)
    8451             :     {
    8452           0 :         sqlite3_result_null(pContext);
    8453           0 :         return;
    8454             :     }
    8455             : 
    8456           1 :     size_t nBLOBDestLen = 0;
    8457           1 :     GByte *pabyDestBLOB = GPkgGeometryFromOGR(poValid.get(), sHeader.iSrsId,
    8458             :                                               nullptr, &nBLOBDestLen);
    8459           1 :     if (!pabyDestBLOB)
    8460             :     {
    8461           0 :         sqlite3_result_null(pContext);
    8462           0 :         return;
    8463             :     }
    8464           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8465             :                         VSIFree);
    8466             : }
    8467             : 
    8468             : /************************************************************************/
    8469             : /*                   OGRGeoPackageSTArea()                              */
    8470             : /************************************************************************/
    8471             : 
    8472          19 : static void OGRGeoPackageSTArea(sqlite3_context *pContext, int /*argc*/,
    8473             :                                 sqlite3_value **argv)
    8474             : {
    8475          19 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8476             :     {
    8477           1 :         sqlite3_result_null(pContext);
    8478          15 :         return;
    8479             :     }
    8480          18 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8481             :     const GByte *pabyBLOB =
    8482          18 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8483             : 
    8484             :     GPkgHeader sHeader;
    8485           0 :     std::unique_ptr<OGRGeometry> poGeom;
    8486          18 :     if (GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) == OGRERR_NONE)
    8487             :     {
    8488          16 :         if (sHeader.bEmpty)
    8489             :         {
    8490           3 :             sqlite3_result_double(pContext, 0);
    8491          13 :             return;
    8492             :         }
    8493          13 :         const GByte *pabyWkb = pabyBLOB + sHeader.nHeaderLen;
    8494          13 :         size_t nWKBSize = nBLOBLen - sHeader.nHeaderLen;
    8495             :         bool bNeedSwap;
    8496             :         uint32_t nType;
    8497          13 :         if (OGRWKBGetGeomType(pabyWkb, nWKBSize, bNeedSwap, nType))
    8498             :         {
    8499          13 :             if (nType == wkbPolygon || nType == wkbPolygon25D ||
    8500          11 :                 nType == wkbPolygon + 1000 ||  // wkbPolygonZ
    8501          10 :                 nType == wkbPolygonM || nType == wkbPolygonZM)
    8502             :             {
    8503             :                 double dfArea;
    8504           5 :                 if (OGRWKBPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8505             :                 {
    8506           5 :                     sqlite3_result_double(pContext, dfArea);
    8507           5 :                     return;
    8508           0 :                 }
    8509             :             }
    8510           8 :             else if (nType == wkbMultiPolygon || nType == wkbMultiPolygon25D ||
    8511           6 :                      nType == wkbMultiPolygon + 1000 ||  // wkbMultiPolygonZ
    8512           5 :                      nType == wkbMultiPolygonM || nType == wkbMultiPolygonZM)
    8513             :             {
    8514             :                 double dfArea;
    8515           5 :                 if (OGRWKBMultiPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8516             :                 {
    8517           5 :                     sqlite3_result_double(pContext, dfArea);
    8518           5 :                     return;
    8519             :                 }
    8520             :             }
    8521             :         }
    8522             : 
    8523             :         // For curve geometries, fallback to OGRGeometry methods
    8524           3 :         poGeom.reset(GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8525             :     }
    8526             :     else
    8527             :     {
    8528             :         // Try also spatialite geometry blobs
    8529           2 :         OGRGeometry *poGeomPtr = nullptr;
    8530           2 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8531             :             OGRERR_NONE)
    8532             :         {
    8533           1 :             sqlite3_result_null(pContext);
    8534           1 :             return;
    8535             :         }
    8536           1 :         poGeom.reset(poGeomPtr);
    8537             :     }
    8538           4 :     auto poSurface = dynamic_cast<OGRSurface *>(poGeom.get());
    8539           4 :     if (poSurface == nullptr)
    8540             :     {
    8541           2 :         auto poMultiSurface = dynamic_cast<OGRMultiSurface *>(poGeom.get());
    8542           2 :         if (poMultiSurface == nullptr)
    8543             :         {
    8544           1 :             sqlite3_result_double(pContext, 0);
    8545             :         }
    8546             :         else
    8547             :         {
    8548           1 :             sqlite3_result_double(pContext, poMultiSurface->get_Area());
    8549             :         }
    8550             :     }
    8551             :     else
    8552             :     {
    8553           2 :         sqlite3_result_double(pContext, poSurface->get_Area());
    8554             :     }
    8555             : }
    8556             : 
    8557             : /************************************************************************/
    8558             : /*                     OGRGeoPackageGeodesicArea()                      */
    8559             : /************************************************************************/
    8560             : 
    8561           5 : static void OGRGeoPackageGeodesicArea(sqlite3_context *pContext, int argc,
    8562             :                                       sqlite3_value **argv)
    8563             : {
    8564           5 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8565             :     {
    8566           1 :         sqlite3_result_null(pContext);
    8567           3 :         return;
    8568             :     }
    8569           4 :     if (sqlite3_value_int(argv[1]) != 1)
    8570             :     {
    8571           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8572             :                  "ST_Area(geom, use_ellipsoid) is only supported for "
    8573             :                  "use_ellipsoid = 1");
    8574             :     }
    8575             : 
    8576           4 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8577             :     const GByte *pabyBLOB =
    8578           4 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8579             :     GPkgHeader sHeader;
    8580           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8581             :     {
    8582           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8583           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8584           1 :         return;
    8585             :     }
    8586             : 
    8587             :     GDALGeoPackageDataset *poDS =
    8588           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8589             : 
    8590             :     std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSrcSRS(
    8591           3 :         poDS->GetSpatialRef(sHeader.iSrsId, true));
    8592           3 :     if (poSrcSRS == nullptr)
    8593             :     {
    8594           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    8595             :                  "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8596           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8597           1 :         return;
    8598             :     }
    8599             : 
    8600             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8601           2 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8602           2 :     if (poGeom == nullptr)
    8603             :     {
    8604             :         // Try also spatialite geometry blobs
    8605           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8606           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8607           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8608             :         {
    8609           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8610           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8611           0 :             return;
    8612             :         }
    8613           0 :         poGeom.reset(poGeomSpatialite);
    8614             :     }
    8615             : 
    8616           2 :     poGeom->assignSpatialReference(poSrcSRS.get());
    8617           2 :     sqlite3_result_double(
    8618             :         pContext, OGR_G_GeodesicArea(OGRGeometry::ToHandle(poGeom.get())));
    8619             : }
    8620             : 
    8621             : /************************************************************************/
    8622             : /*                   OGRGeoPackageLengthOrGeodesicLength()              */
    8623             : /************************************************************************/
    8624             : 
    8625           8 : static void OGRGeoPackageLengthOrGeodesicLength(sqlite3_context *pContext,
    8626             :                                                 int argc, sqlite3_value **argv)
    8627             : {
    8628           8 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8629             :     {
    8630           2 :         sqlite3_result_null(pContext);
    8631           5 :         return;
    8632             :     }
    8633           6 :     if (argc == 2 && sqlite3_value_int(argv[1]) != 1)
    8634             :     {
    8635           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8636             :                  "ST_Length(geom, use_ellipsoid) is only supported for "
    8637             :                  "use_ellipsoid = 1");
    8638             :     }
    8639             : 
    8640           6 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8641             :     const GByte *pabyBLOB =
    8642           6 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8643             :     GPkgHeader sHeader;
    8644           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8645             :     {
    8646           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8647           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8648           2 :         return;
    8649             :     }
    8650             : 
    8651             :     GDALGeoPackageDataset *poDS =
    8652           4 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8653             : 
    8654           0 :     std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSrcSRS;
    8655           4 :     if (argc == 2)
    8656             :     {
    8657           3 :         poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8658           3 :         if (!poSrcSRS)
    8659             :         {
    8660           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    8661             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8662           1 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8663           1 :             return;
    8664             :         }
    8665             :     }
    8666             : 
    8667             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8668           3 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8669           3 :     if (poGeom == nullptr)
    8670             :     {
    8671             :         // Try also spatialite geometry blobs
    8672           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8673           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8674           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8675             :         {
    8676           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8677           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8678           0 :             return;
    8679             :         }
    8680           0 :         poGeom.reset(poGeomSpatialite);
    8681             :     }
    8682             : 
    8683           3 :     if (argc == 2)
    8684           2 :         poGeom->assignSpatialReference(poSrcSRS.get());
    8685             : 
    8686           6 :     sqlite3_result_double(
    8687             :         pContext,
    8688           1 :         argc == 1 ? OGR_G_Length(OGRGeometry::ToHandle(poGeom.get()))
    8689           2 :                   : OGR_G_GeodesicLength(OGRGeometry::ToHandle(poGeom.get())));
    8690             : }
    8691             : 
    8692             : /************************************************************************/
    8693             : /*                      OGRGeoPackageTransform()                        */
    8694             : /************************************************************************/
    8695             : 
    8696             : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8697             :                             sqlite3_value **argv);
    8698             : 
    8699          32 : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8700             :                             sqlite3_value **argv)
    8701             : {
    8702          63 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB ||
    8703          31 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8704             :     {
    8705           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8706          32 :         return;
    8707             :     }
    8708             : 
    8709          30 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8710             :     const GByte *pabyBLOB =
    8711          30 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8712             :     GPkgHeader sHeader;
    8713          30 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8714             :     {
    8715           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8716           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8717           1 :         return;
    8718             :     }
    8719             : 
    8720          29 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8721          29 :     if (sHeader.iSrsId == nDestSRID)
    8722             :     {
    8723             :         // Return blob unmodified
    8724           3 :         sqlite3_result_blob(pContext, pabyBLOB, nBLOBLen, SQLITE_TRANSIENT);
    8725           3 :         return;
    8726             :     }
    8727             : 
    8728             :     GDALGeoPackageDataset *poDS =
    8729          26 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8730             : 
    8731             :     // Try to get the cached coordinate transformation
    8732             :     OGRCoordinateTransformation *poCT;
    8733          26 :     if (poDS->m_nLastCachedCTSrcSRId == sHeader.iSrsId &&
    8734          20 :         poDS->m_nLastCachedCTDstSRId == nDestSRID)
    8735             :     {
    8736          20 :         poCT = poDS->m_poLastCachedCT.get();
    8737             :     }
    8738             :     else
    8739             :     {
    8740             :         std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
    8741           6 :             poSrcSRS(poDS->GetSpatialRef(sHeader.iSrsId, true));
    8742           6 :         if (poSrcSRS == nullptr)
    8743             :         {
    8744           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    8745             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8746           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8747           0 :             return;
    8748             :         }
    8749             : 
    8750             :         std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
    8751           6 :             poDstSRS(poDS->GetSpatialRef(nDestSRID, true));
    8752           6 :         if (poDstSRS == nullptr)
    8753             :         {
    8754           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Target SRID (%d) is invalid",
    8755             :                      nDestSRID);
    8756           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8757           0 :             return;
    8758             :         }
    8759             :         poCT =
    8760           6 :             OGRCreateCoordinateTransformation(poSrcSRS.get(), poDstSRS.get());
    8761           6 :         if (poCT == nullptr)
    8762             :         {
    8763           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8764           0 :             return;
    8765             :         }
    8766             : 
    8767             :         // Cache coordinate transformation for potential later reuse
    8768           6 :         poDS->m_nLastCachedCTSrcSRId = sHeader.iSrsId;
    8769           6 :         poDS->m_nLastCachedCTDstSRId = nDestSRID;
    8770           6 :         poDS->m_poLastCachedCT.reset(poCT);
    8771           6 :         poCT = poDS->m_poLastCachedCT.get();
    8772             :     }
    8773             : 
    8774          26 :     if (sHeader.nHeaderLen >= 8)
    8775             :     {
    8776          26 :         std::vector<GByte> &abyNewBLOB = poDS->m_abyWKBTransformCache;
    8777          26 :         abyNewBLOB.resize(nBLOBLen);
    8778          26 :         memcpy(abyNewBLOB.data(), pabyBLOB, nBLOBLen);
    8779             : 
    8780          26 :         OGREnvelope3D oEnv3d;
    8781          26 :         if (!OGRWKBTransform(abyNewBLOB.data() + sHeader.nHeaderLen,
    8782          26 :                              nBLOBLen - sHeader.nHeaderLen, poCT,
    8783          78 :                              poDS->m_oWKBTransformCache, oEnv3d) ||
    8784          26 :             !GPkgUpdateHeader(abyNewBLOB.data(), nBLOBLen, nDestSRID,
    8785             :                               oEnv3d.MinX, oEnv3d.MaxX, oEnv3d.MinY,
    8786             :                               oEnv3d.MaxY, oEnv3d.MinZ, oEnv3d.MaxZ))
    8787             :         {
    8788           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8789           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8790           0 :             return;
    8791             :         }
    8792             : 
    8793          26 :         sqlite3_result_blob(pContext, abyNewBLOB.data(), nBLOBLen,
    8794             :                             SQLITE_TRANSIENT);
    8795          26 :         return;
    8796             :     }
    8797             : 
    8798             :     // Try also spatialite geometry blobs
    8799           0 :     OGRGeometry *poGeomSpatialite = nullptr;
    8800           0 :     if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8801           0 :                                           &poGeomSpatialite) != OGRERR_NONE)
    8802             :     {
    8803           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8804           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8805           0 :         return;
    8806             :     }
    8807           0 :     auto poGeom = std::unique_ptr<OGRGeometry>(poGeomSpatialite);
    8808             : 
    8809           0 :     if (poGeom->transform(poCT) != OGRERR_NONE)
    8810             :     {
    8811           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8812           0 :         return;
    8813             :     }
    8814             : 
    8815           0 :     size_t nBLOBDestLen = 0;
    8816             :     GByte *pabyDestBLOB =
    8817           0 :         GPkgGeometryFromOGR(poGeom.get(), nDestSRID, nullptr, &nBLOBDestLen);
    8818           0 :     if (!pabyDestBLOB)
    8819             :     {
    8820           0 :         sqlite3_result_null(pContext);
    8821           0 :         return;
    8822             :     }
    8823           0 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8824             :                         VSIFree);
    8825             : }
    8826             : 
    8827             : /************************************************************************/
    8828             : /*                      OGRGeoPackageSridFromAuthCRS()                  */
    8829             : /************************************************************************/
    8830             : 
    8831           4 : static void OGRGeoPackageSridFromAuthCRS(sqlite3_context *pContext,
    8832             :                                          int /*argc*/, sqlite3_value **argv)
    8833             : {
    8834           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8835           3 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8836             :     {
    8837           2 :         sqlite3_result_int(pContext, -1);
    8838           2 :         return;
    8839             :     }
    8840             : 
    8841             :     GDALGeoPackageDataset *poDS =
    8842           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8843             : 
    8844           2 :     char *pszSQL = sqlite3_mprintf(
    8845             :         "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
    8846             :         "lower(organization) = lower('%q') AND organization_coordsys_id = %d",
    8847           2 :         sqlite3_value_text(argv[0]), sqlite3_value_int(argv[1]));
    8848           2 :     OGRErr err = OGRERR_NONE;
    8849           2 :     int nSRSId = SQLGetInteger(poDS->GetDB(), pszSQL, &err);
    8850           2 :     sqlite3_free(pszSQL);
    8851           2 :     if (err != OGRERR_NONE)
    8852           1 :         nSRSId = -1;
    8853           2 :     sqlite3_result_int(pContext, nSRSId);
    8854             : }
    8855             : 
    8856             : /************************************************************************/
    8857             : /*                    OGRGeoPackageImportFromEPSG()                     */
    8858             : /************************************************************************/
    8859             : 
    8860           4 : static void OGRGeoPackageImportFromEPSG(sqlite3_context *pContext, int /*argc*/,
    8861             :                                         sqlite3_value **argv)
    8862             : {
    8863           4 :     if (sqlite3_value_type(argv[0]) != SQLITE_INTEGER)
    8864             :     {
    8865           1 :         sqlite3_result_int(pContext, -1);
    8866           2 :         return;
    8867             :     }
    8868             : 
    8869             :     GDALGeoPackageDataset *poDS =
    8870           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8871           3 :     OGRSpatialReference oSRS;
    8872           3 :     if (oSRS.importFromEPSG(sqlite3_value_int(argv[0])) != OGRERR_NONE)
    8873             :     {
    8874           1 :         sqlite3_result_int(pContext, -1);
    8875           1 :         return;
    8876             :     }
    8877             : 
    8878           2 :     sqlite3_result_int(pContext, poDS->GetSrsId(&oSRS));
    8879             : }
    8880             : 
    8881             : /************************************************************************/
    8882             : /*               OGRGeoPackageRegisterGeometryExtension()               */
    8883             : /************************************************************************/
    8884             : 
    8885           1 : static void OGRGeoPackageRegisterGeometryExtension(sqlite3_context *pContext,
    8886             :                                                    int /*argc*/,
    8887             :                                                    sqlite3_value **argv)
    8888             : {
    8889           1 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8890           2 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT ||
    8891           1 :         sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    8892             :     {
    8893           0 :         sqlite3_result_int(pContext, 0);
    8894           0 :         return;
    8895             :     }
    8896             : 
    8897             :     const char *pszTableName =
    8898           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8899             :     const char *pszGeomName =
    8900           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8901             :     const char *pszGeomType =
    8902           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    8903             : 
    8904             :     GDALGeoPackageDataset *poDS =
    8905           1 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8906             : 
    8907           1 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8908           1 :         poDS->GetLayerByName(pszTableName));
    8909           1 :     if (poLyr == nullptr)
    8910             :     {
    8911           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8912           0 :         sqlite3_result_int(pContext, 0);
    8913           0 :         return;
    8914             :     }
    8915           1 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8916             :     {
    8917           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8918           0 :         sqlite3_result_int(pContext, 0);
    8919           0 :         return;
    8920             :     }
    8921           1 :     const OGRwkbGeometryType eGeomType = OGRFromOGCGeomType(pszGeomType);
    8922           1 :     if (eGeomType == wkbUnknown)
    8923             :     {
    8924           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry type name");
    8925           0 :         sqlite3_result_int(pContext, 0);
    8926           0 :         return;
    8927             :     }
    8928             : 
    8929           1 :     sqlite3_result_int(
    8930             :         pContext,
    8931           1 :         static_cast<int>(poLyr->CreateGeometryExtensionIfNecessary(eGeomType)));
    8932             : }
    8933             : 
    8934             : /************************************************************************/
    8935             : /*                  OGRGeoPackageCreateSpatialIndex()                   */
    8936             : /************************************************************************/
    8937             : 
    8938          14 : static void OGRGeoPackageCreateSpatialIndex(sqlite3_context *pContext,
    8939             :                                             int /*argc*/, sqlite3_value **argv)
    8940             : {
    8941          27 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8942          13 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8943             :     {
    8944           2 :         sqlite3_result_int(pContext, 0);
    8945           2 :         return;
    8946             :     }
    8947             : 
    8948             :     const char *pszTableName =
    8949          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8950             :     const char *pszGeomName =
    8951          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8952             :     GDALGeoPackageDataset *poDS =
    8953          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8954             : 
    8955          12 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8956          12 :         poDS->GetLayerByName(pszTableName));
    8957          12 :     if (poLyr == nullptr)
    8958             :     {
    8959           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8960           1 :         sqlite3_result_int(pContext, 0);
    8961           1 :         return;
    8962             :     }
    8963          11 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8964             :     {
    8965           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8966           1 :         sqlite3_result_int(pContext, 0);
    8967           1 :         return;
    8968             :     }
    8969             : 
    8970          10 :     sqlite3_result_int(pContext, poLyr->CreateSpatialIndex());
    8971             : }
    8972             : 
    8973             : /************************************************************************/
    8974             : /*                  OGRGeoPackageDisableSpatialIndex()                  */
    8975             : /************************************************************************/
    8976             : 
    8977          12 : static void OGRGeoPackageDisableSpatialIndex(sqlite3_context *pContext,
    8978             :                                              int /*argc*/, sqlite3_value **argv)
    8979             : {
    8980          23 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8981          11 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8982             :     {
    8983           2 :         sqlite3_result_int(pContext, 0);
    8984           2 :         return;
    8985             :     }
    8986             : 
    8987             :     const char *pszTableName =
    8988          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8989             :     const char *pszGeomName =
    8990          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8991             :     GDALGeoPackageDataset *poDS =
    8992          10 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8993             : 
    8994          10 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8995          10 :         poDS->GetLayerByName(pszTableName));
    8996          10 :     if (poLyr == nullptr)
    8997             :     {
    8998           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8999           1 :         sqlite3_result_int(pContext, 0);
    9000           1 :         return;
    9001             :     }
    9002           9 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9003             :     {
    9004           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9005           1 :         sqlite3_result_int(pContext, 0);
    9006           1 :         return;
    9007             :     }
    9008             : 
    9009           8 :     sqlite3_result_int(pContext, poLyr->DropSpatialIndex(true));
    9010             : }
    9011             : 
    9012             : /************************************************************************/
    9013             : /*                  OGRGeoPackageHasSpatialIndex()                      */
    9014             : /************************************************************************/
    9015             : 
    9016          29 : static void OGRGeoPackageHasSpatialIndex(sqlite3_context *pContext,
    9017             :                                          int /*argc*/, sqlite3_value **argv)
    9018             : {
    9019          57 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9020          28 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9021             :     {
    9022           2 :         sqlite3_result_int(pContext, 0);
    9023           2 :         return;
    9024             :     }
    9025             : 
    9026             :     const char *pszTableName =
    9027          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9028             :     const char *pszGeomName =
    9029          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9030             :     GDALGeoPackageDataset *poDS =
    9031          27 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9032             : 
    9033          27 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9034          27 :         poDS->GetLayerByName(pszTableName));
    9035          27 :     if (poLyr == nullptr)
    9036             :     {
    9037           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9038           1 :         sqlite3_result_int(pContext, 0);
    9039           1 :         return;
    9040             :     }
    9041          26 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9042             :     {
    9043           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9044           1 :         sqlite3_result_int(pContext, 0);
    9045           1 :         return;
    9046             :     }
    9047             : 
    9048          25 :     poLyr->RunDeferredCreationIfNecessary();
    9049          25 :     poLyr->CreateSpatialIndexIfNecessary();
    9050             : 
    9051          25 :     sqlite3_result_int(pContext, poLyr->HasSpatialIndex());
    9052             : }
    9053             : 
    9054             : /************************************************************************/
    9055             : /*                       GPKG_hstore_get_value()                        */
    9056             : /************************************************************************/
    9057             : 
    9058           4 : static void GPKG_hstore_get_value(sqlite3_context *pContext, int /*argc*/,
    9059             :                                   sqlite3_value **argv)
    9060             : {
    9061           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9062           3 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9063             :     {
    9064           2 :         sqlite3_result_null(pContext);
    9065           2 :         return;
    9066             :     }
    9067             : 
    9068             :     const char *pszHStore =
    9069           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9070             :     const char *pszSearchedKey =
    9071           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9072           2 :     char *pszValue = OGRHStoreGetValue(pszHStore, pszSearchedKey);
    9073           2 :     if (pszValue != nullptr)
    9074           1 :         sqlite3_result_text(pContext, pszValue, -1, CPLFree);
    9075             :     else
    9076           1 :         sqlite3_result_null(pContext);
    9077             : }
    9078             : 
    9079             : /************************************************************************/
    9080             : /*                      GPKG_GDAL_GetMemFileFromBlob()                  */
    9081             : /************************************************************************/
    9082             : 
    9083         105 : static CPLString GPKG_GDAL_GetMemFileFromBlob(sqlite3_value **argv)
    9084             : {
    9085         105 :     int nBytes = sqlite3_value_bytes(argv[0]);
    9086             :     const GByte *pabyBLOB =
    9087         105 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    9088             :     CPLString osMemFileName(
    9089         105 :         VSIMemGenerateHiddenFilename("GPKG_GDAL_GetMemFileFromBlob"));
    9090         105 :     VSILFILE *fp = VSIFileFromMemBuffer(
    9091             :         osMemFileName.c_str(), const_cast<GByte *>(pabyBLOB), nBytes, FALSE);
    9092         105 :     VSIFCloseL(fp);
    9093         105 :     return osMemFileName;
    9094             : }
    9095             : 
    9096             : /************************************************************************/
    9097             : /*                       GPKG_GDAL_GetMimeType()                        */
    9098             : /************************************************************************/
    9099             : 
    9100          35 : static void GPKG_GDAL_GetMimeType(sqlite3_context *pContext, int /*argc*/,
    9101             :                                   sqlite3_value **argv)
    9102             : {
    9103          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9104             :     {
    9105           0 :         sqlite3_result_null(pContext);
    9106           0 :         return;
    9107             :     }
    9108             : 
    9109          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9110             :     GDALDriver *poDriver =
    9111          35 :         GDALDriver::FromHandle(GDALIdentifyDriver(osMemFileName, nullptr));
    9112          35 :     if (poDriver != nullptr)
    9113             :     {
    9114          35 :         const char *pszRes = nullptr;
    9115          35 :         if (EQUAL(poDriver->GetDescription(), "PNG"))
    9116          23 :             pszRes = "image/png";
    9117          12 :         else if (EQUAL(poDriver->GetDescription(), "JPEG"))
    9118           6 :             pszRes = "image/jpeg";
    9119           6 :         else if (EQUAL(poDriver->GetDescription(), "WEBP"))
    9120           6 :             pszRes = "image/x-webp";
    9121           0 :         else if (EQUAL(poDriver->GetDescription(), "GTIFF"))
    9122           0 :             pszRes = "image/tiff";
    9123             :         else
    9124           0 :             pszRes = CPLSPrintf("gdal/%s", poDriver->GetDescription());
    9125          35 :         sqlite3_result_text(pContext, pszRes, -1, SQLITE_TRANSIENT);
    9126             :     }
    9127             :     else
    9128           0 :         sqlite3_result_null(pContext);
    9129          35 :     VSIUnlink(osMemFileName);
    9130             : }
    9131             : 
    9132             : /************************************************************************/
    9133             : /*                       GPKG_GDAL_GetBandCount()                       */
    9134             : /************************************************************************/
    9135             : 
    9136          35 : static void GPKG_GDAL_GetBandCount(sqlite3_context *pContext, int /*argc*/,
    9137             :                                    sqlite3_value **argv)
    9138             : {
    9139          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9140             :     {
    9141           0 :         sqlite3_result_null(pContext);
    9142           0 :         return;
    9143             :     }
    9144             : 
    9145          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9146             :     auto poDS = std::unique_ptr<GDALDataset>(
    9147             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9148          70 :                           nullptr, nullptr, nullptr));
    9149          35 :     if (poDS != nullptr)
    9150             :     {
    9151          35 :         sqlite3_result_int(pContext, poDS->GetRasterCount());
    9152             :     }
    9153             :     else
    9154           0 :         sqlite3_result_null(pContext);
    9155          35 :     VSIUnlink(osMemFileName);
    9156             : }
    9157             : 
    9158             : /************************************************************************/
    9159             : /*                       GPKG_GDAL_HasColorTable()                      */
    9160             : /************************************************************************/
    9161             : 
    9162          35 : static void GPKG_GDAL_HasColorTable(sqlite3_context *pContext, int /*argc*/,
    9163             :                                     sqlite3_value **argv)
    9164             : {
    9165          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9166             :     {
    9167           0 :         sqlite3_result_null(pContext);
    9168           0 :         return;
    9169             :     }
    9170             : 
    9171          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9172             :     auto poDS = std::unique_ptr<GDALDataset>(
    9173             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9174          70 :                           nullptr, nullptr, nullptr));
    9175          35 :     if (poDS != nullptr)
    9176             :     {
    9177          35 :         sqlite3_result_int(
    9178          46 :             pContext, poDS->GetRasterCount() == 1 &&
    9179          11 :                           poDS->GetRasterBand(1)->GetColorTable() != nullptr);
    9180             :     }
    9181             :     else
    9182           0 :         sqlite3_result_null(pContext);
    9183          35 :     VSIUnlink(osMemFileName);
    9184             : }
    9185             : 
    9186             : /************************************************************************/
    9187             : /*                      GetRasterLayerDataset()                         */
    9188             : /************************************************************************/
    9189             : 
    9190             : GDALDataset *
    9191          12 : GDALGeoPackageDataset::GetRasterLayerDataset(const char *pszLayerName)
    9192             : {
    9193          12 :     const auto oIter = m_oCachedRasterDS.find(pszLayerName);
    9194          12 :     if (oIter != m_oCachedRasterDS.end())
    9195          10 :         return oIter->second.get();
    9196             : 
    9197             :     auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
    9198           4 :         (std::string("GPKG:\"") + m_pszFilename + "\":" + pszLayerName).c_str(),
    9199           4 :         GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR));
    9200           2 :     if (!poDS)
    9201             :     {
    9202           0 :         return nullptr;
    9203             :     }
    9204           2 :     m_oCachedRasterDS[pszLayerName] = std::move(poDS);
    9205           2 :     return m_oCachedRasterDS[pszLayerName].get();
    9206             : }
    9207             : 
    9208             : /************************************************************************/
    9209             : /*                   GPKG_gdal_get_layer_pixel_value()                  */
    9210             : /************************************************************************/
    9211             : 
    9212             : // NOTE: keep in sync implementations in ogrsqlitesqlfunctionscommon.cpp
    9213             : // and ogrgeopackagedatasource.cpp
    9214          13 : static void GPKG_gdal_get_layer_pixel_value(sqlite3_context *pContext, int argc,
    9215             :                                             sqlite3_value **argv)
    9216             : {
    9217          13 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9218             :     {
    9219           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9220             :                  "Invalid arguments to gdal_get_layer_pixel_value()");
    9221           1 :         sqlite3_result_null(pContext);
    9222           1 :         return;
    9223             :     }
    9224             : 
    9225             :     const char *pszLayerName =
    9226          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9227             : 
    9228             :     GDALGeoPackageDataset *poGlobalDS =
    9229          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9230          12 :     auto poDS = poGlobalDS->GetRasterLayerDataset(pszLayerName);
    9231          12 :     if (!poDS)
    9232             :     {
    9233           0 :         sqlite3_result_null(pContext);
    9234           0 :         return;
    9235             :     }
    9236             : 
    9237          12 :     OGRSQLite_gdal_get_pixel_value_common("gdal_get_layer_pixel_value",
    9238             :                                           pContext, argc, argv, poDS);
    9239             : }
    9240             : 
    9241             : /************************************************************************/
    9242             : /*                       GPKG_ogr_layer_Extent()                        */
    9243             : /************************************************************************/
    9244             : 
    9245           3 : static void GPKG_ogr_layer_Extent(sqlite3_context *pContext, int /*argc*/,
    9246             :                                   sqlite3_value **argv)
    9247             : {
    9248           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9249             :     {
    9250           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Invalid argument type",
    9251             :                  "ogr_layer_Extent");
    9252           1 :         sqlite3_result_null(pContext);
    9253           2 :         return;
    9254             :     }
    9255             : 
    9256             :     const char *pszLayerName =
    9257           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9258             :     GDALGeoPackageDataset *poDS =
    9259           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9260           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9261           2 :     if (!poLayer)
    9262             :     {
    9263           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer",
    9264             :                  "ogr_layer_Extent");
    9265           1 :         sqlite3_result_null(pContext);
    9266           1 :         return;
    9267             :     }
    9268             : 
    9269           1 :     if (poLayer->GetGeomType() == wkbNone)
    9270             :     {
    9271           0 :         sqlite3_result_null(pContext);
    9272           0 :         return;
    9273             :     }
    9274             : 
    9275           1 :     OGREnvelope sExtent;
    9276           1 :     if (poLayer->GetExtent(&sExtent) != OGRERR_NONE)
    9277             :     {
    9278           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9279             :                  "ogr_layer_Extent");
    9280           0 :         sqlite3_result_null(pContext);
    9281           0 :         return;
    9282             :     }
    9283             : 
    9284           1 :     OGRPolygon oPoly;
    9285           1 :     auto poRing = std::make_unique<OGRLinearRing>();
    9286           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9287           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MinY);
    9288           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MaxY);
    9289           1 :     poRing->addPoint(sExtent.MinX, sExtent.MaxY);
    9290           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9291           1 :     oPoly.addRing(std::move(poRing));
    9292             : 
    9293           1 :     const auto poSRS = poLayer->GetSpatialRef();
    9294           1 :     const int nSRID = poDS->GetSrsId(poSRS);
    9295           1 :     size_t nBLOBDestLen = 0;
    9296             :     GByte *pabyDestBLOB =
    9297           1 :         GPkgGeometryFromOGR(&oPoly, nSRID, nullptr, &nBLOBDestLen);
    9298           1 :     if (!pabyDestBLOB)
    9299             :     {
    9300           0 :         sqlite3_result_null(pContext);
    9301           0 :         return;
    9302             :     }
    9303           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    9304             :                         VSIFree);
    9305             : }
    9306             : 
    9307             : /************************************************************************/
    9308             : /*                      InstallSQLFunctions()                           */
    9309             : /************************************************************************/
    9310             : 
    9311             : #ifndef SQLITE_DETERMINISTIC
    9312             : #define SQLITE_DETERMINISTIC 0
    9313             : #endif
    9314             : 
    9315             : #ifndef SQLITE_INNOCUOUS
    9316             : #define SQLITE_INNOCUOUS 0
    9317             : #endif
    9318             : 
    9319             : #ifndef UTF8_INNOCUOUS
    9320             : #define UTF8_INNOCUOUS (SQLITE_UTF8 | SQLITE_DETERMINISTIC | SQLITE_INNOCUOUS)
    9321             : #endif
    9322             : 
    9323        2073 : void GDALGeoPackageDataset::InstallSQLFunctions()
    9324             : {
    9325        2073 :     InitSpatialite();
    9326             : 
    9327             :     // Enable SpatiaLite 4.3 "amphibious" mode, i.e. that SpatiaLite functions
    9328             :     // that take geometries will accept GPKG encoded geometries without
    9329             :     // explicit conversion.
    9330             :     // Use sqlite3_exec() instead of SQLCommand() since we don't want verbose
    9331             :     // error.
    9332        2073 :     sqlite3_exec(hDB, "SELECT EnableGpkgAmphibiousMode()", nullptr, nullptr,
    9333             :                  nullptr);
    9334             : 
    9335             :     /* Used by RTree Spatial Index Extension */
    9336        2073 :     sqlite3_create_function(hDB, "ST_MinX", 1, UTF8_INNOCUOUS, nullptr,
    9337             :                             OGRGeoPackageSTMinX, nullptr, nullptr);
    9338        2073 :     sqlite3_create_function(hDB, "ST_MinY", 1, UTF8_INNOCUOUS, nullptr,
    9339             :                             OGRGeoPackageSTMinY, nullptr, nullptr);
    9340        2073 :     sqlite3_create_function(hDB, "ST_MaxX", 1, UTF8_INNOCUOUS, nullptr,
    9341             :                             OGRGeoPackageSTMaxX, nullptr, nullptr);
    9342        2073 :     sqlite3_create_function(hDB, "ST_MaxY", 1, UTF8_INNOCUOUS, nullptr,
    9343             :                             OGRGeoPackageSTMaxY, nullptr, nullptr);
    9344        2073 :     sqlite3_create_function(hDB, "ST_IsEmpty", 1, UTF8_INNOCUOUS, nullptr,
    9345             :                             OGRGeoPackageSTIsEmpty, nullptr, nullptr);
    9346             : 
    9347             :     /* Used by Geometry Type Triggers Extension */
    9348        2073 :     sqlite3_create_function(hDB, "ST_GeometryType", 1, UTF8_INNOCUOUS, nullptr,
    9349             :                             OGRGeoPackageSTGeometryType, nullptr, nullptr);
    9350        2073 :     sqlite3_create_function(hDB, "GPKG_IsAssignable", 2, UTF8_INNOCUOUS,
    9351             :                             nullptr, OGRGeoPackageGPKGIsAssignable, nullptr,
    9352             :                             nullptr);
    9353             : 
    9354             :     /* Used by Geometry SRS ID Triggers Extension */
    9355        2073 :     sqlite3_create_function(hDB, "ST_SRID", 1, UTF8_INNOCUOUS, nullptr,
    9356             :                             OGRGeoPackageSTSRID, nullptr, nullptr);
    9357             : 
    9358             :     /* Spatialite-like functions */
    9359        2073 :     sqlite3_create_function(hDB, "CreateSpatialIndex", 2, SQLITE_UTF8, this,
    9360             :                             OGRGeoPackageCreateSpatialIndex, nullptr, nullptr);
    9361        2073 :     sqlite3_create_function(hDB, "DisableSpatialIndex", 2, SQLITE_UTF8, this,
    9362             :                             OGRGeoPackageDisableSpatialIndex, nullptr, nullptr);
    9363        2073 :     sqlite3_create_function(hDB, "HasSpatialIndex", 2, SQLITE_UTF8, this,
    9364             :                             OGRGeoPackageHasSpatialIndex, nullptr, nullptr);
    9365             : 
    9366             :     // HSTORE functions
    9367        2073 :     sqlite3_create_function(hDB, "hstore_get_value", 2, UTF8_INNOCUOUS, nullptr,
    9368             :                             GPKG_hstore_get_value, nullptr, nullptr);
    9369             : 
    9370             :     // Override a few Spatialite functions to work with gpkg_spatial_ref_sys
    9371        2073 :     sqlite3_create_function(hDB, "ST_Transform", 2, UTF8_INNOCUOUS, this,
    9372             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9373        2073 :     sqlite3_create_function(hDB, "Transform", 2, UTF8_INNOCUOUS, this,
    9374             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9375        2073 :     sqlite3_create_function(hDB, "SridFromAuthCRS", 2, SQLITE_UTF8, this,
    9376             :                             OGRGeoPackageSridFromAuthCRS, nullptr, nullptr);
    9377             : 
    9378        2073 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9379             :                             OGRGeoPackageSTEnvelopesIntersectsTwoParams,
    9380             :                             nullptr, nullptr);
    9381        2073 :     sqlite3_create_function(
    9382             :         hDB, "ST_EnvelopesIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9383             :         OGRGeoPackageSTEnvelopesIntersectsTwoParams, nullptr, nullptr);
    9384             : 
    9385        2073 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 5, UTF8_INNOCUOUS, nullptr,
    9386             :                             OGRGeoPackageSTEnvelopesIntersects, nullptr,
    9387             :                             nullptr);
    9388        2073 :     sqlite3_create_function(hDB, "ST_EnvelopesIntersects", 5, UTF8_INNOCUOUS,
    9389             :                             nullptr, OGRGeoPackageSTEnvelopesIntersects,
    9390             :                             nullptr, nullptr);
    9391             : 
    9392             :     // Implementation that directly hacks the GeoPackage geometry blob header
    9393        2073 :     sqlite3_create_function(hDB, "SetSRID", 2, UTF8_INNOCUOUS, nullptr,
    9394             :                             OGRGeoPackageSetSRID, nullptr, nullptr);
    9395             : 
    9396             :     // GDAL specific function
    9397        2073 :     sqlite3_create_function(hDB, "ImportFromEPSG", 1, SQLITE_UTF8, this,
    9398             :                             OGRGeoPackageImportFromEPSG, nullptr, nullptr);
    9399             : 
    9400             :     // May be used by ogrmerge.py
    9401        2073 :     sqlite3_create_function(hDB, "RegisterGeometryExtension", 3, SQLITE_UTF8,
    9402             :                             this, OGRGeoPackageRegisterGeometryExtension,
    9403             :                             nullptr, nullptr);
    9404             : 
    9405        2073 :     if (OGRGeometryFactory::haveGEOS())
    9406             :     {
    9407        2073 :         sqlite3_create_function(hDB, "ST_MakeValid", 1, UTF8_INNOCUOUS, nullptr,
    9408             :                                 OGRGeoPackageSTMakeValid, nullptr, nullptr);
    9409             :     }
    9410             : 
    9411        2073 :     sqlite3_create_function(hDB, "ST_Length", 1, UTF8_INNOCUOUS, nullptr,
    9412             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9413             :                             nullptr);
    9414        2073 :     sqlite3_create_function(hDB, "ST_Length", 2, UTF8_INNOCUOUS, this,
    9415             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9416             :                             nullptr);
    9417             : 
    9418        2073 :     sqlite3_create_function(hDB, "ST_Area", 1, UTF8_INNOCUOUS, nullptr,
    9419             :                             OGRGeoPackageSTArea, nullptr, nullptr);
    9420        2073 :     sqlite3_create_function(hDB, "ST_Area", 2, UTF8_INNOCUOUS, this,
    9421             :                             OGRGeoPackageGeodesicArea, nullptr, nullptr);
    9422             : 
    9423             :     // Debug functions
    9424        2073 :     if (CPLTestBool(CPLGetConfigOption("GPKG_DEBUG", "FALSE")))
    9425             :     {
    9426         422 :         sqlite3_create_function(hDB, "GDAL_GetMimeType", 1,
    9427             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9428             :                                 GPKG_GDAL_GetMimeType, nullptr, nullptr);
    9429         422 :         sqlite3_create_function(hDB, "GDAL_GetBandCount", 1,
    9430             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9431             :                                 GPKG_GDAL_GetBandCount, nullptr, nullptr);
    9432         422 :         sqlite3_create_function(hDB, "GDAL_HasColorTable", 1,
    9433             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9434             :                                 GPKG_GDAL_HasColorTable, nullptr, nullptr);
    9435             :     }
    9436             : 
    9437        2073 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 5, SQLITE_UTF8,
    9438             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9439             :                             nullptr);
    9440        2073 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 6, SQLITE_UTF8,
    9441             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9442             :                             nullptr);
    9443             : 
    9444             :     // Function from VirtualOGR
    9445        2073 :     sqlite3_create_function(hDB, "ogr_layer_Extent", 1, SQLITE_UTF8, this,
    9446             :                             GPKG_ogr_layer_Extent, nullptr, nullptr);
    9447             : 
    9448        2073 :     m_pSQLFunctionData = OGRSQLiteRegisterSQLFunctionsCommon(hDB);
    9449        2073 : }
    9450             : 
    9451             : /************************************************************************/
    9452             : /*                         OpenOrCreateDB()                             */
    9453             : /************************************************************************/
    9454             : 
    9455        2077 : bool GDALGeoPackageDataset::OpenOrCreateDB(int flags)
    9456             : {
    9457        2077 :     const bool bSuccess = OGRSQLiteBaseDataSource::OpenOrCreateDB(
    9458             :         flags, /*bRegisterOGR2SQLiteExtensions=*/false,
    9459             :         /*bLoadExtensions=*/true);
    9460        2077 :     if (!bSuccess)
    9461           9 :         return false;
    9462             : 
    9463             :     // Turning on recursive_triggers is needed so that DELETE triggers fire
    9464             :     // in a INSERT OR REPLACE statement. In particular this is needed to
    9465             :     // make sure gpkg_ogr_contents.feature_count is properly updated.
    9466        2068 :     SQLCommand(hDB, "PRAGMA recursive_triggers = 1");
    9467             : 
    9468        2068 :     InstallSQLFunctions();
    9469             : 
    9470             :     const char *pszSqlitePragma =
    9471        2068 :         CPLGetConfigOption("OGR_SQLITE_PRAGMA", nullptr);
    9472        2068 :     OGRErr eErr = OGRERR_NONE;
    9473           6 :     if ((!pszSqlitePragma || !strstr(pszSqlitePragma, "trusted_schema")) &&
    9474             :         // Older sqlite versions don't have this pragma
    9475        4142 :         SQLGetInteger(hDB, "PRAGMA trusted_schema", &eErr) == 0 &&
    9476        2068 :         eErr == OGRERR_NONE)
    9477             :     {
    9478        2068 :         bool bNeedsTrustedSchema = false;
    9479             : 
    9480             :         // Current SQLite versions require PRAGMA trusted_schema = 1 to be
    9481             :         // able to use the RTree from triggers, which is only needed when
    9482             :         // modifying the RTree.
    9483        5094 :         if (((flags & SQLITE_OPEN_READWRITE) != 0 ||
    9484        3178 :              (flags & SQLITE_OPEN_CREATE) != 0) &&
    9485        1110 :             OGRSQLiteRTreeRequiresTrustedSchemaOn())
    9486             :         {
    9487        1110 :             bNeedsTrustedSchema = true;
    9488             :         }
    9489             : 
    9490             : #ifdef HAVE_SPATIALITE
    9491             :         // Spatialite <= 5.1.0 doesn't declare its functions as SQLITE_INNOCUOUS
    9492         958 :         if (!bNeedsTrustedSchema && HasExtensionsTable() &&
    9493         877 :             SQLGetInteger(
    9494             :                 hDB,
    9495             :                 "SELECT 1 FROM gpkg_extensions WHERE "
    9496             :                 "extension_name ='gdal_spatialite_computed_geom_column'",
    9497           1 :                 nullptr) == 1 &&
    9498        3026 :             SpatialiteRequiresTrustedSchemaOn() && AreSpatialiteTriggersSafe())
    9499             :         {
    9500           1 :             bNeedsTrustedSchema = true;
    9501             :         }
    9502             : #endif
    9503             : 
    9504        2068 :         if (bNeedsTrustedSchema)
    9505             :         {
    9506        1111 :             CPLDebug("GPKG", "Setting PRAGMA trusted_schema = 1");
    9507        1111 :             SQLCommand(hDB, "PRAGMA trusted_schema = 1");
    9508             :         }
    9509             :     }
    9510             : 
    9511             :     const char *pszPreludeStatements =
    9512        2068 :         CSLFetchNameValue(papszOpenOptions, "PRELUDE_STATEMENTS");
    9513        2068 :     if (pszPreludeStatements)
    9514             :     {
    9515           2 :         if (SQLCommand(hDB, pszPreludeStatements) != OGRERR_NONE)
    9516           0 :             return false;
    9517             :     }
    9518             : 
    9519        2068 :     return true;
    9520             : }
    9521             : 
    9522             : /************************************************************************/
    9523             : /*                   GetLayerWithGetSpatialWhereByName()                */
    9524             : /************************************************************************/
    9525             : 
    9526             : std::pair<OGRLayer *, IOGRSQLiteGetSpatialWhere *>
    9527          90 : GDALGeoPackageDataset::GetLayerWithGetSpatialWhereByName(const char *pszName)
    9528             : {
    9529             :     OGRGeoPackageLayer *poRet =
    9530          90 :         cpl::down_cast<OGRGeoPackageLayer *>(GetLayerByName(pszName));
    9531          90 :     return std::pair(poRet, poRet);
    9532             : }
    9533             : 
    9534             : /************************************************************************/
    9535             : /*                       CommitTransaction()                            */
    9536             : /************************************************************************/
    9537             : 
    9538         208 : OGRErr GDALGeoPackageDataset::CommitTransaction()
    9539             : 
    9540             : {
    9541         208 :     if (m_nSoftTransactionLevel == 1)
    9542             :     {
    9543         207 :         FlushMetadata();
    9544         463 :         for (auto &poLayer : m_apoLayers)
    9545             :         {
    9546         256 :             poLayer->DoJobAtTransactionCommit();
    9547             :         }
    9548             :     }
    9549             : 
    9550         208 :     return OGRSQLiteBaseDataSource::CommitTransaction();
    9551             : }
    9552             : 
    9553             : /************************************************************************/
    9554             : /*                     RollbackTransaction()                            */
    9555             : /************************************************************************/
    9556             : 
    9557          35 : OGRErr GDALGeoPackageDataset::RollbackTransaction()
    9558             : 
    9559             : {
    9560             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9561          70 :     std::vector<bool> abAddTriggers;
    9562          35 :     std::vector<bool> abTriggersDeletedInTransaction;
    9563             : #endif
    9564          35 :     if (m_nSoftTransactionLevel == 1)
    9565             :     {
    9566          34 :         FlushMetadata();
    9567          70 :         for (auto &poLayer : m_apoLayers)
    9568             :         {
    9569             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9570          36 :             abAddTriggers.push_back(poLayer->GetAddOGRFeatureCountTriggers());
    9571          36 :             abTriggersDeletedInTransaction.push_back(
    9572          36 :                 poLayer->GetOGRFeatureCountTriggersDeletedInTransaction());
    9573          36 :             poLayer->SetAddOGRFeatureCountTriggers(false);
    9574             : #endif
    9575          36 :             poLayer->DoJobAtTransactionRollback();
    9576             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9577          36 :             poLayer->DisableFeatureCount();
    9578             : #endif
    9579             :         }
    9580             :     }
    9581             : 
    9582          35 :     const OGRErr eErr = OGRSQLiteBaseDataSource::RollbackTransaction();
    9583             : 
    9584             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9585          35 :     if (!abAddTriggers.empty())
    9586             :     {
    9587          68 :         for (size_t i = 0; i < m_apoLayers.size(); ++i)
    9588             :         {
    9589          36 :             auto &poLayer = m_apoLayers[i];
    9590          36 :             if (abTriggersDeletedInTransaction[i])
    9591             :             {
    9592           7 :                 poLayer->SetOGRFeatureCountTriggersEnabled(true);
    9593             :             }
    9594             :             else
    9595             :             {
    9596          29 :                 poLayer->SetAddOGRFeatureCountTriggers(abAddTriggers[i]);
    9597             :             }
    9598             :         }
    9599             :     }
    9600             : #endif
    9601          70 :     return eErr;
    9602             : }
    9603             : 
    9604             : /************************************************************************/
    9605             : /*                       GetGeometryTypeString()                        */
    9606             : /************************************************************************/
    9607             : 
    9608             : const char *
    9609        1447 : GDALGeoPackageDataset::GetGeometryTypeString(OGRwkbGeometryType eType)
    9610             : {
    9611        1447 :     const char *pszGPKGGeomType = OGRToOGCGeomType(eType);
    9612        1459 :     if (EQUAL(pszGPKGGeomType, "GEOMETRYCOLLECTION") &&
    9613          12 :         CPLTestBool(CPLGetConfigOption("OGR_GPKG_GEOMCOLLECTION", "NO")))
    9614             :     {
    9615           0 :         pszGPKGGeomType = "GEOMCOLLECTION";
    9616             :     }
    9617        1447 :     return pszGPKGGeomType;
    9618             : }
    9619             : 
    9620             : /************************************************************************/
    9621             : /*                           GetFieldDomainNames()                      */
    9622             : /************************************************************************/
    9623             : 
    9624             : std::vector<std::string>
    9625          11 : GDALGeoPackageDataset::GetFieldDomainNames(CSLConstList) const
    9626             : {
    9627          11 :     if (!HasDataColumnConstraintsTable())
    9628           4 :         return std::vector<std::string>();
    9629             : 
    9630          14 :     std::vector<std::string> oDomainNamesList;
    9631             : 
    9632           7 :     std::unique_ptr<SQLResult> oResultTable;
    9633             :     {
    9634             :         std::string osSQL =
    9635             :             "SELECT DISTINCT constraint_name "
    9636             :             "FROM gpkg_data_column_constraints "
    9637             :             "WHERE constraint_name NOT LIKE '_%_domain_description' "
    9638             :             "ORDER BY constraint_name "
    9639           7 :             "LIMIT 10000"  // to avoid denial of service
    9640             :             ;
    9641           7 :         oResultTable = SQLQuery(hDB, osSQL.c_str());
    9642           7 :         if (!oResultTable)
    9643           0 :             return oDomainNamesList;
    9644             :     }
    9645             : 
    9646           7 :     if (oResultTable->RowCount() == 10000)
    9647             :     {
    9648           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9649             :                  "Number of rows returned for field domain names has been "
    9650             :                  "truncated.");
    9651             :     }
    9652           7 :     else if (oResultTable->RowCount() > 0)
    9653             :     {
    9654           7 :         oDomainNamesList.reserve(oResultTable->RowCount());
    9655          89 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    9656             :         {
    9657          82 :             const char *pszConstraintName = oResultTable->GetValue(0, i);
    9658          82 :             if (!pszConstraintName)
    9659           0 :                 continue;
    9660             : 
    9661          82 :             oDomainNamesList.emplace_back(pszConstraintName);
    9662             :         }
    9663             :     }
    9664             : 
    9665           7 :     return oDomainNamesList;
    9666             : }
    9667             : 
    9668             : /************************************************************************/
    9669             : /*                           GetFieldDomain()                           */
    9670             : /************************************************************************/
    9671             : 
    9672             : const OGRFieldDomain *
    9673         102 : GDALGeoPackageDataset::GetFieldDomain(const std::string &name) const
    9674             : {
    9675         102 :     const auto baseRet = GDALDataset::GetFieldDomain(name);
    9676         102 :     if (baseRet)
    9677          42 :         return baseRet;
    9678             : 
    9679          60 :     if (!HasDataColumnConstraintsTable())
    9680           4 :         return nullptr;
    9681             : 
    9682          56 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
    9683          56 :     const char *min_is_inclusive =
    9684          56 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
    9685          56 :     const char *max_is_inclusive =
    9686          56 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
    9687             : 
    9688          56 :     std::unique_ptr<SQLResult> oResultTable;
    9689             :     // Note: for coded domains, we use a little trick by using a dummy
    9690             :     // _{domainname}_domain_description enum that has a single entry whose
    9691             :     // description is the description of the main domain.
    9692             :     {
    9693          56 :         char *pszSQL = sqlite3_mprintf(
    9694             :             "SELECT constraint_type, value, min, %s, "
    9695             :             "max, %s, description, constraint_name "
    9696             :             "FROM gpkg_data_column_constraints "
    9697             :             "WHERE constraint_name IN ('%q', "
    9698             :             "'_%q_domain_description') "
    9699             :             "AND length(constraint_type) < 100 "  // to
    9700             :                                                   // avoid
    9701             :                                                   // denial
    9702             :                                                   // of
    9703             :                                                   // service
    9704             :             "AND (value IS NULL OR length(value) < "
    9705             :             "10000) "  // to avoid denial
    9706             :                        // of service
    9707             :             "AND (description IS NULL OR "
    9708             :             "length(description) < 10000) "  // to
    9709             :                                              // avoid
    9710             :                                              // denial
    9711             :                                              // of
    9712             :                                              // service
    9713             :             "ORDER BY value "
    9714             :             "LIMIT 10000",  // to avoid denial of
    9715             :                             // service
    9716             :             min_is_inclusive, max_is_inclusive, name.c_str(), name.c_str());
    9717          56 :         oResultTable = SQLQuery(hDB, pszSQL);
    9718          56 :         sqlite3_free(pszSQL);
    9719          56 :         if (!oResultTable)
    9720           0 :             return nullptr;
    9721             :     }
    9722          56 :     if (oResultTable->RowCount() == 0)
    9723             :     {
    9724          15 :         return nullptr;
    9725             :     }
    9726          41 :     if (oResultTable->RowCount() == 10000)
    9727             :     {
    9728           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9729             :                  "Number of rows returned for field domain %s has been "
    9730             :                  "truncated.",
    9731             :                  name.c_str());
    9732             :     }
    9733             : 
    9734             :     // Try to find the field domain data type from fields that implement it
    9735          41 :     int nFieldType = -1;
    9736          41 :     OGRFieldSubType eSubType = OFSTNone;
    9737          41 :     if (HasDataColumnsTable())
    9738             :     {
    9739          36 :         char *pszSQL = sqlite3_mprintf(
    9740             :             "SELECT table_name, column_name FROM gpkg_data_columns WHERE "
    9741             :             "constraint_name = '%q' LIMIT 10",
    9742             :             name.c_str());
    9743          72 :         auto oResultTable2 = SQLQuery(hDB, pszSQL);
    9744          36 :         sqlite3_free(pszSQL);
    9745          36 :         if (oResultTable2 && oResultTable2->RowCount() >= 1)
    9746             :         {
    9747          46 :             for (int iRecord = 0; iRecord < oResultTable2->RowCount();
    9748             :                  iRecord++)
    9749             :             {
    9750          23 :                 const char *pszTableName = oResultTable2->GetValue(0, iRecord);
    9751          23 :                 const char *pszColumnName = oResultTable2->GetValue(1, iRecord);
    9752          23 :                 if (pszTableName == nullptr || pszColumnName == nullptr)
    9753           0 :                     continue;
    9754             :                 OGRLayer *poLayer =
    9755          46 :                     const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    9756          23 :                         pszTableName);
    9757          23 :                 if (poLayer)
    9758             :                 {
    9759          23 :                     const auto poFDefn = poLayer->GetLayerDefn();
    9760          23 :                     int nIdx = poFDefn->GetFieldIndex(pszColumnName);
    9761          23 :                     if (nIdx >= 0)
    9762             :                     {
    9763          23 :                         const auto poFieldDefn = poFDefn->GetFieldDefn(nIdx);
    9764          23 :                         const auto eType = poFieldDefn->GetType();
    9765          23 :                         if (nFieldType < 0)
    9766             :                         {
    9767          23 :                             nFieldType = eType;
    9768          23 :                             eSubType = poFieldDefn->GetSubType();
    9769             :                         }
    9770           0 :                         else if ((eType == OFTInteger64 || eType == OFTReal) &&
    9771             :                                  nFieldType == OFTInteger)
    9772             :                         {
    9773             :                             // ok
    9774             :                         }
    9775           0 :                         else if (eType == OFTInteger &&
    9776           0 :                                  (nFieldType == OFTInteger64 ||
    9777             :                                   nFieldType == OFTReal))
    9778             :                         {
    9779           0 :                             nFieldType = OFTInteger;
    9780           0 :                             eSubType = OFSTNone;
    9781             :                         }
    9782           0 :                         else if (nFieldType != eType)
    9783             :                         {
    9784           0 :                             nFieldType = -1;
    9785           0 :                             eSubType = OFSTNone;
    9786           0 :                             break;
    9787             :                         }
    9788             :                     }
    9789             :                 }
    9790             :             }
    9791             :         }
    9792             :     }
    9793             : 
    9794          41 :     std::unique_ptr<OGRFieldDomain> poDomain;
    9795          82 :     std::vector<OGRCodedValue> asValues;
    9796          41 :     bool error = false;
    9797          82 :     CPLString osLastConstraintType;
    9798          41 :     int nFieldTypeFromEnumCode = -1;
    9799          82 :     std::string osConstraintDescription;
    9800          82 :     std::string osDescrConstraintName("_");
    9801          41 :     osDescrConstraintName += name;
    9802          41 :     osDescrConstraintName += "_domain_description";
    9803         100 :     for (int iRecord = 0; iRecord < oResultTable->RowCount(); iRecord++)
    9804             :     {
    9805          63 :         const char *pszConstraintType = oResultTable->GetValue(0, iRecord);
    9806          63 :         if (pszConstraintType == nullptr)
    9807           1 :             continue;
    9808          63 :         const char *pszValue = oResultTable->GetValue(1, iRecord);
    9809          63 :         const char *pszMin = oResultTable->GetValue(2, iRecord);
    9810             :         const bool bIsMinIncluded =
    9811          63 :             oResultTable->GetValueAsInteger(3, iRecord) == 1;
    9812          63 :         const char *pszMax = oResultTable->GetValue(4, iRecord);
    9813             :         const bool bIsMaxIncluded =
    9814          63 :             oResultTable->GetValueAsInteger(5, iRecord) == 1;
    9815          63 :         const char *pszDescription = oResultTable->GetValue(6, iRecord);
    9816          63 :         const char *pszConstraintName = oResultTable->GetValue(7, iRecord);
    9817             : 
    9818          63 :         if (!osLastConstraintType.empty() && osLastConstraintType != "enum")
    9819             :         {
    9820           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    9821             :                      "Only constraint of type 'enum' can have multiple rows");
    9822           1 :             error = true;
    9823           4 :             break;
    9824             :         }
    9825             : 
    9826          62 :         if (strcmp(pszConstraintType, "enum") == 0)
    9827             :         {
    9828          42 :             if (pszValue == nullptr)
    9829             :             {
    9830           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    9831             :                          "NULL in 'value' column of enumeration");
    9832           1 :                 error = true;
    9833           1 :                 break;
    9834             :             }
    9835          41 :             if (osDescrConstraintName == pszConstraintName)
    9836             :             {
    9837           1 :                 if (pszDescription)
    9838             :                 {
    9839           1 :                     osConstraintDescription = pszDescription;
    9840             :                 }
    9841           1 :                 continue;
    9842             :             }
    9843          40 :             if (asValues.empty())
    9844             :             {
    9845          20 :                 asValues.reserve(oResultTable->RowCount() + 1);
    9846             :             }
    9847             :             OGRCodedValue cv;
    9848             :             // intended: the 'value' column in GPKG is actually the code
    9849          40 :             cv.pszCode = VSI_STRDUP_VERBOSE(pszValue);
    9850          40 :             if (cv.pszCode == nullptr)
    9851             :             {
    9852           0 :                 error = true;
    9853           0 :                 break;
    9854             :             }
    9855          40 :             if (pszDescription)
    9856             :             {
    9857          29 :                 cv.pszValue = VSI_STRDUP_VERBOSE(pszDescription);
    9858          29 :                 if (cv.pszValue == nullptr)
    9859             :                 {
    9860           0 :                     VSIFree(cv.pszCode);
    9861           0 :                     error = true;
    9862           0 :                     break;
    9863             :                 }
    9864             :             }
    9865             :             else
    9866             :             {
    9867          11 :                 cv.pszValue = nullptr;
    9868             :             }
    9869             : 
    9870             :             // If we can't get the data type from field definition, guess it
    9871             :             // from code.
    9872          40 :             if (nFieldType < 0 && nFieldTypeFromEnumCode != OFTString)
    9873             :             {
    9874          18 :                 switch (CPLGetValueType(cv.pszCode))
    9875             :                 {
    9876          13 :                     case CPL_VALUE_INTEGER:
    9877             :                     {
    9878          13 :                         if (nFieldTypeFromEnumCode != OFTReal &&
    9879             :                             nFieldTypeFromEnumCode != OFTInteger64)
    9880             :                         {
    9881           9 :                             const auto nVal = CPLAtoGIntBig(cv.pszCode);
    9882          17 :                             if (nVal < std::numeric_limits<int>::min() ||
    9883           8 :                                 nVal > std::numeric_limits<int>::max())
    9884             :                             {
    9885           3 :                                 nFieldTypeFromEnumCode = OFTInteger64;
    9886             :                             }
    9887             :                             else
    9888             :                             {
    9889           6 :                                 nFieldTypeFromEnumCode = OFTInteger;
    9890             :                             }
    9891             :                         }
    9892          13 :                         break;
    9893             :                     }
    9894             : 
    9895           3 :                     case CPL_VALUE_REAL:
    9896           3 :                         nFieldTypeFromEnumCode = OFTReal;
    9897           3 :                         break;
    9898             : 
    9899           2 :                     case CPL_VALUE_STRING:
    9900           2 :                         nFieldTypeFromEnumCode = OFTString;
    9901           2 :                         break;
    9902             :                 }
    9903             :             }
    9904             : 
    9905          40 :             asValues.emplace_back(cv);
    9906             :         }
    9907          20 :         else if (strcmp(pszConstraintType, "range") == 0)
    9908             :         {
    9909             :             OGRField sMin;
    9910             :             OGRField sMax;
    9911          14 :             OGR_RawField_SetUnset(&sMin);
    9912          14 :             OGR_RawField_SetUnset(&sMax);
    9913          14 :             if (nFieldType != OFTInteger && nFieldType != OFTInteger64)
    9914           8 :                 nFieldType = OFTReal;
    9915          27 :             if (pszMin != nullptr &&
    9916          13 :                 CPLAtof(pszMin) != -std::numeric_limits<double>::infinity())
    9917             :             {
    9918          10 :                 if (nFieldType == OFTInteger)
    9919           3 :                     sMin.Integer = atoi(pszMin);
    9920           7 :                 else if (nFieldType == OFTInteger64)
    9921           3 :                     sMin.Integer64 = CPLAtoGIntBig(pszMin);
    9922             :                 else /* if( nFieldType == OFTReal ) */
    9923           4 :                     sMin.Real = CPLAtof(pszMin);
    9924             :             }
    9925          27 :             if (pszMax != nullptr &&
    9926          13 :                 CPLAtof(pszMax) != std::numeric_limits<double>::infinity())
    9927             :             {
    9928          10 :                 if (nFieldType == OFTInteger)
    9929           3 :                     sMax.Integer = atoi(pszMax);
    9930           7 :                 else if (nFieldType == OFTInteger64)
    9931           3 :                     sMax.Integer64 = CPLAtoGIntBig(pszMax);
    9932             :                 else /* if( nFieldType == OFTReal ) */
    9933           4 :                     sMax.Real = CPLAtof(pszMax);
    9934             :             }
    9935          14 :             poDomain = std::make_unique<OGRRangeFieldDomain>(
    9936          14 :                 name, pszDescription ? pszDescription : "",
    9937          28 :                 static_cast<OGRFieldType>(nFieldType), eSubType, sMin,
    9938          14 :                 bIsMinIncluded, sMax, bIsMaxIncluded);
    9939             :         }
    9940           6 :         else if (strcmp(pszConstraintType, "glob") == 0)
    9941             :         {
    9942           5 :             if (pszValue == nullptr)
    9943             :             {
    9944           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    9945             :                          "NULL in 'value' column of glob");
    9946           1 :                 error = true;
    9947           1 :                 break;
    9948             :             }
    9949           4 :             if (nFieldType < 0)
    9950           1 :                 nFieldType = OFTString;
    9951           4 :             poDomain = std::make_unique<OGRGlobFieldDomain>(
    9952           4 :                 name, pszDescription ? pszDescription : "",
    9953          12 :                 static_cast<OGRFieldType>(nFieldType), eSubType, pszValue);
    9954             :         }
    9955             :         else
    9956             :         {
    9957           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    9958             :                      "Unhandled constraint_type: %s", pszConstraintType);
    9959           1 :             error = true;
    9960           1 :             break;
    9961             :         }
    9962             : 
    9963          58 :         osLastConstraintType = pszConstraintType;
    9964             :     }
    9965             : 
    9966          41 :     if (!asValues.empty())
    9967             :     {
    9968          20 :         if (nFieldType < 0)
    9969           9 :             nFieldType = nFieldTypeFromEnumCode;
    9970          20 :         poDomain = std::make_unique<OGRCodedFieldDomain>(
    9971             :             name, osConstraintDescription,
    9972          40 :             static_cast<OGRFieldType>(nFieldType), eSubType,
    9973          40 :             std::move(asValues));
    9974             :     }
    9975             : 
    9976          41 :     if (error)
    9977             :     {
    9978           4 :         return nullptr;
    9979             :     }
    9980             : 
    9981          37 :     m_oMapFieldDomains[name] = std::move(poDomain);
    9982          37 :     return GDALDataset::GetFieldDomain(name);
    9983             : }
    9984             : 
    9985             : /************************************************************************/
    9986             : /*                           AddFieldDomain()                           */
    9987             : /************************************************************************/
    9988             : 
    9989          18 : bool GDALGeoPackageDataset::AddFieldDomain(
    9990             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
    9991             : {
    9992          36 :     const std::string domainName(domain->GetName());
    9993          18 :     if (!GetUpdate())
    9994             :     {
    9995           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    9996             :                  "AddFieldDomain() not supported on read-only dataset");
    9997           0 :         return false;
    9998             :     }
    9999          18 :     if (GetFieldDomain(domainName) != nullptr)
   10000             :     {
   10001           1 :         failureReason = "A domain of identical name already exists";
   10002           1 :         return false;
   10003             :     }
   10004          17 :     if (!CreateColumnsTableAndColumnConstraintsTablesIfNecessary())
   10005           0 :         return false;
   10006             : 
   10007          17 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
   10008          17 :     const char *min_is_inclusive =
   10009          17 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
   10010          17 :     const char *max_is_inclusive =
   10011          17 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
   10012             : 
   10013          17 :     const auto &osDescription = domain->GetDescription();
   10014          17 :     switch (domain->GetDomainType())
   10015             :     {
   10016          11 :         case OFDT_CODED:
   10017             :         {
   10018             :             const auto poCodedDomain =
   10019          11 :                 cpl::down_cast<const OGRCodedFieldDomain *>(domain.get());
   10020          11 :             if (!osDescription.empty())
   10021             :             {
   10022             :                 // We use a little trick by using a dummy
   10023             :                 // _{domainname}_domain_description enum that has a single
   10024             :                 // entry whose description is the description of the main
   10025             :                 // domain.
   10026           1 :                 char *pszSQL = sqlite3_mprintf(
   10027             :                     "INSERT INTO gpkg_data_column_constraints ("
   10028             :                     "constraint_name, constraint_type, value, "
   10029             :                     "min, %s, max, %s, "
   10030             :                     "description) VALUES ("
   10031             :                     "'_%q_domain_description', 'enum', '', NULL, NULL, NULL, "
   10032             :                     "NULL, %Q)",
   10033             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10034             :                     osDescription.c_str());
   10035           1 :                 CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
   10036           1 :                 sqlite3_free(pszSQL);
   10037             :             }
   10038          11 :             const auto &enumeration = poCodedDomain->GetEnumeration();
   10039          33 :             for (int i = 0; enumeration[i].pszCode != nullptr; ++i)
   10040             :             {
   10041          22 :                 char *pszSQL = sqlite3_mprintf(
   10042             :                     "INSERT INTO gpkg_data_column_constraints ("
   10043             :                     "constraint_name, constraint_type, value, "
   10044             :                     "min, %s, max, %s, "
   10045             :                     "description) VALUES ("
   10046             :                     "'%q', 'enum', '%q', NULL, NULL, NULL, NULL, %Q)",
   10047             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10048          22 :                     enumeration[i].pszCode, enumeration[i].pszValue);
   10049          22 :                 bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10050          22 :                 sqlite3_free(pszSQL);
   10051          22 :                 if (!ok)
   10052           0 :                     return false;
   10053             :             }
   10054          11 :             break;
   10055             :         }
   10056             : 
   10057           5 :         case OFDT_RANGE:
   10058             :         {
   10059             :             const auto poRangeDomain =
   10060           5 :                 cpl::down_cast<const OGRRangeFieldDomain *>(domain.get());
   10061           5 :             const auto eFieldType = poRangeDomain->GetFieldType();
   10062           5 :             if (eFieldType != OFTInteger && eFieldType != OFTInteger64 &&
   10063             :                 eFieldType != OFTReal)
   10064             :             {
   10065             :                 failureReason = "Only range domains of numeric type are "
   10066           0 :                                 "supported in GeoPackage";
   10067           0 :                 return false;
   10068             :             }
   10069             : 
   10070           5 :             double dfMin = -std::numeric_limits<double>::infinity();
   10071           5 :             double dfMax = std::numeric_limits<double>::infinity();
   10072           5 :             bool bMinIsInclusive = true;
   10073           5 :             const auto &sMin = poRangeDomain->GetMin(bMinIsInclusive);
   10074           5 :             bool bMaxIsInclusive = true;
   10075           5 :             const auto &sMax = poRangeDomain->GetMax(bMaxIsInclusive);
   10076           5 :             if (eFieldType == OFTInteger)
   10077             :             {
   10078           1 :                 if (!OGR_RawField_IsUnset(&sMin))
   10079           1 :                     dfMin = sMin.Integer;
   10080           1 :                 if (!OGR_RawField_IsUnset(&sMax))
   10081           1 :                     dfMax = sMax.Integer;
   10082             :             }
   10083           4 :             else if (eFieldType == OFTInteger64)
   10084             :             {
   10085           1 :                 if (!OGR_RawField_IsUnset(&sMin))
   10086           1 :                     dfMin = static_cast<double>(sMin.Integer64);
   10087           1 :                 if (!OGR_RawField_IsUnset(&sMax))
   10088           1 :                     dfMax = static_cast<double>(sMax.Integer64);
   10089             :             }
   10090             :             else /* if( eFieldType == OFTReal ) */
   10091             :             {
   10092           3 :                 if (!OGR_RawField_IsUnset(&sMin))
   10093           3 :                     dfMin = sMin.Real;
   10094           3 :                 if (!OGR_RawField_IsUnset(&sMax))
   10095           3 :                     dfMax = sMax.Real;
   10096             :             }
   10097             : 
   10098           5 :             sqlite3_stmt *hInsertStmt = nullptr;
   10099             :             const char *pszSQL =
   10100           5 :                 CPLSPrintf("INSERT INTO gpkg_data_column_constraints ("
   10101             :                            "constraint_name, constraint_type, value, "
   10102             :                            "min, %s, max, %s, "
   10103             :                            "description) VALUES ("
   10104             :                            "?, 'range', NULL, ?, ?, ?, ?, ?)",
   10105             :                            min_is_inclusive, max_is_inclusive);
   10106           5 :             if (SQLPrepareWithError(hDB, pszSQL, -1, &hInsertStmt, nullptr) !=
   10107             :                 SQLITE_OK)
   10108             :             {
   10109           0 :                 return false;
   10110             :             }
   10111           5 :             sqlite3_bind_text(hInsertStmt, 1, domainName.c_str(),
   10112           5 :                               static_cast<int>(domainName.size()),
   10113             :                               SQLITE_TRANSIENT);
   10114           5 :             sqlite3_bind_double(hInsertStmt, 2, dfMin);
   10115           5 :             sqlite3_bind_int(hInsertStmt, 3, bMinIsInclusive ? 1 : 0);
   10116           5 :             sqlite3_bind_double(hInsertStmt, 4, dfMax);
   10117           5 :             sqlite3_bind_int(hInsertStmt, 5, bMaxIsInclusive ? 1 : 0);
   10118           5 :             if (osDescription.empty())
   10119             :             {
   10120           3 :                 sqlite3_bind_null(hInsertStmt, 6);
   10121             :             }
   10122             :             else
   10123             :             {
   10124           2 :                 sqlite3_bind_text(hInsertStmt, 6, osDescription.c_str(),
   10125           2 :                                   static_cast<int>(osDescription.size()),
   10126             :                                   SQLITE_TRANSIENT);
   10127             :             }
   10128           5 :             const int sqlite_err = sqlite3_step(hInsertStmt);
   10129           5 :             sqlite3_finalize(hInsertStmt);
   10130           5 :             if (sqlite_err != SQLITE_OK && sqlite_err != SQLITE_DONE)
   10131             :             {
   10132           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10133             :                          "failed to execute insertion '%s': %s", pszSQL,
   10134             :                          sqlite3_errmsg(hDB));
   10135           0 :                 return false;
   10136             :             }
   10137             : 
   10138           5 :             break;
   10139             :         }
   10140             : 
   10141           1 :         case OFDT_GLOB:
   10142             :         {
   10143             :             const auto poGlobDomain =
   10144           1 :                 cpl::down_cast<const OGRGlobFieldDomain *>(domain.get());
   10145           2 :             char *pszSQL = sqlite3_mprintf(
   10146             :                 "INSERT INTO gpkg_data_column_constraints ("
   10147             :                 "constraint_name, constraint_type, value, "
   10148             :                 "min, %s, max, %s, "
   10149             :                 "description) VALUES ("
   10150             :                 "'%q', 'glob', '%q', NULL, NULL, NULL, NULL, %Q)",
   10151             :                 min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10152           1 :                 poGlobDomain->GetGlob().c_str(),
   10153           2 :                 osDescription.empty() ? nullptr : osDescription.c_str());
   10154           1 :             bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10155           1 :             sqlite3_free(pszSQL);
   10156           1 :             if (!ok)
   10157           0 :                 return false;
   10158             : 
   10159           1 :             break;
   10160             :         }
   10161             :     }
   10162             : 
   10163          17 :     m_oMapFieldDomains[domainName] = std::move(domain);
   10164          17 :     return true;
   10165             : }
   10166             : 
   10167             : /************************************************************************/
   10168             : /*                          AddRelationship()                           */
   10169             : /************************************************************************/
   10170             : 
   10171          24 : bool GDALGeoPackageDataset::AddRelationship(
   10172             :     std::unique_ptr<GDALRelationship> &&relationship,
   10173             :     std::string &failureReason)
   10174             : {
   10175          24 :     if (!GetUpdate())
   10176             :     {
   10177           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10178             :                  "AddRelationship() not supported on read-only dataset");
   10179           0 :         return false;
   10180             :     }
   10181             : 
   10182             :     const std::string osRelationshipName = GenerateNameForRelationship(
   10183          24 :         relationship->GetLeftTableName().c_str(),
   10184          24 :         relationship->GetRightTableName().c_str(),
   10185          96 :         relationship->GetRelatedTableType().c_str());
   10186             :     // sanity checks
   10187          24 :     if (GetRelationship(osRelationshipName) != nullptr)
   10188             :     {
   10189           1 :         failureReason = "A relationship of identical name already exists";
   10190           1 :         return false;
   10191             :     }
   10192             : 
   10193          23 :     if (!ValidateRelationship(relationship.get(), failureReason))
   10194             :     {
   10195          14 :         return false;
   10196             :     }
   10197             : 
   10198           9 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
   10199             :     {
   10200           0 :         return false;
   10201             :     }
   10202           9 :     if (!CreateRelationsTableIfNecessary())
   10203             :     {
   10204           0 :         failureReason = "Could not create gpkgext_relations table";
   10205           0 :         return false;
   10206             :     }
   10207           9 :     if (SQLGetInteger(GetDB(),
   10208             :                       "SELECT 1 FROM gpkg_extensions WHERE "
   10209             :                       "table_name = 'gpkgext_relations'",
   10210           9 :                       nullptr) != 1)
   10211             :     {
   10212           4 :         if (OGRERR_NONE !=
   10213           4 :             SQLCommand(
   10214             :                 GetDB(),
   10215             :                 "INSERT INTO gpkg_extensions "
   10216             :                 "(table_name,column_name,extension_name,definition,scope) "
   10217             :                 "VALUES ('gpkgext_relations', NULL, 'gpkg_related_tables', "
   10218             :                 "'http://www.geopackage.org/18-000.html', "
   10219             :                 "'read-write')"))
   10220             :         {
   10221             :             failureReason =
   10222           0 :                 "Could not create gpkg_extensions entry for gpkgext_relations";
   10223           0 :             return false;
   10224             :         }
   10225             :     }
   10226             : 
   10227           9 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10228           9 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10229           9 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10230           9 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10231             : 
   10232          18 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10233           9 :     if (osRelatedTableType.empty())
   10234             :     {
   10235           5 :         osRelatedTableType = "features";
   10236             :     }
   10237             : 
   10238             :     // generate mapping table if not set
   10239          18 :     CPLString osMappingTableName = relationship->GetMappingTableName();
   10240           9 :     if (osMappingTableName.empty())
   10241             :     {
   10242           3 :         int nIndex = 1;
   10243           3 :         osMappingTableName = osLeftTableName + "_" + osRightTableName;
   10244           3 :         while (FindLayerIndex(osMappingTableName.c_str()) >= 0)
   10245             :         {
   10246           0 :             nIndex += 1;
   10247             :             osMappingTableName.Printf("%s_%s_%d", osLeftTableName.c_str(),
   10248           0 :                                       osRightTableName.c_str(), nIndex);
   10249             :         }
   10250             : 
   10251             :         // determine whether base/related keys are unique
   10252           3 :         bool bBaseKeyIsUnique = false;
   10253             :         {
   10254             :             const std::set<std::string> uniqueBaseFieldsUC =
   10255             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10256           6 :                                                osLeftTableName.c_str());
   10257           6 :             if (uniqueBaseFieldsUC.find(
   10258           3 :                     CPLString(aosLeftTableFields[0]).toupper()) !=
   10259           6 :                 uniqueBaseFieldsUC.end())
   10260             :             {
   10261           2 :                 bBaseKeyIsUnique = true;
   10262             :             }
   10263             :         }
   10264           3 :         bool bRelatedKeyIsUnique = false;
   10265             :         {
   10266             :             const std::set<std::string> uniqueRelatedFieldsUC =
   10267             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10268           6 :                                                osRightTableName.c_str());
   10269           6 :             if (uniqueRelatedFieldsUC.find(
   10270           3 :                     CPLString(aosRightTableFields[0]).toupper()) !=
   10271           6 :                 uniqueRelatedFieldsUC.end())
   10272             :             {
   10273           2 :                 bRelatedKeyIsUnique = true;
   10274             :             }
   10275             :         }
   10276             : 
   10277             :         // create mapping table
   10278             : 
   10279           3 :         std::string osBaseIdDefinition = "base_id INTEGER";
   10280           3 :         if (bBaseKeyIsUnique)
   10281             :         {
   10282           2 :             char *pszSQL = sqlite3_mprintf(
   10283             :                 " CONSTRAINT 'fk_base_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10284             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10285             :                 "DEFERRED",
   10286             :                 osMappingTableName.c_str(), osLeftTableName.c_str(),
   10287           2 :                 aosLeftTableFields[0].c_str());
   10288           2 :             osBaseIdDefinition += pszSQL;
   10289           2 :             sqlite3_free(pszSQL);
   10290             :         }
   10291             : 
   10292           3 :         std::string osRelatedIdDefinition = "related_id INTEGER";
   10293           3 :         if (bRelatedKeyIsUnique)
   10294             :         {
   10295           2 :             char *pszSQL = sqlite3_mprintf(
   10296             :                 " CONSTRAINT 'fk_related_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10297             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10298             :                 "DEFERRED",
   10299             :                 osMappingTableName.c_str(), osRightTableName.c_str(),
   10300           2 :                 aosRightTableFields[0].c_str());
   10301           2 :             osRelatedIdDefinition += pszSQL;
   10302           2 :             sqlite3_free(pszSQL);
   10303             :         }
   10304             : 
   10305           3 :         char *pszSQL = sqlite3_mprintf("CREATE TABLE \"%w\" ("
   10306             :                                        "id INTEGER PRIMARY KEY AUTOINCREMENT, "
   10307             :                                        "%s, %s);",
   10308             :                                        osMappingTableName.c_str(),
   10309             :                                        osBaseIdDefinition.c_str(),
   10310             :                                        osRelatedIdDefinition.c_str());
   10311           3 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
   10312           3 :         sqlite3_free(pszSQL);
   10313           3 :         if (eErr != OGRERR_NONE)
   10314             :         {
   10315             :             failureReason =
   10316           0 :                 ("Could not create mapping table " + osMappingTableName)
   10317           0 :                     .c_str();
   10318           0 :             return false;
   10319             :         }
   10320             : 
   10321             :         /*
   10322             :          * Strictly speaking we should NOT be inserting the mapping table into gpkg_contents.
   10323             :          * The related tables extension explicitly states that the mapping table should only be
   10324             :          * in the gpkgext_relations table and not in gpkg_contents. (See also discussion at
   10325             :          * https://github.com/opengeospatial/geopackage/issues/679).
   10326             :          *
   10327             :          * However, if we don't insert the mapping table into gpkg_contents then it is no longer
   10328             :          * visible to some clients (eg ESRI software only allows opening tables that are present
   10329             :          * in gpkg_contents). So we'll do this anyway, for maximum compatibility and flexibility.
   10330             :          *
   10331             :          * More related discussion is at https://github.com/OSGeo/gdal/pull/9258
   10332             :          */
   10333           3 :         pszSQL = sqlite3_mprintf(
   10334             :             "INSERT INTO gpkg_contents "
   10335             :             "(table_name,data_type,identifier,description,last_change,srs_id) "
   10336             :             "VALUES "
   10337             :             "('%q','attributes','%q','Mapping table for relationship between "
   10338             :             "%q and %q',%s,0)",
   10339             :             osMappingTableName.c_str(), /*table_name*/
   10340             :             osMappingTableName.c_str(), /*identifier*/
   10341             :             osLeftTableName.c_str(),    /*description left table name*/
   10342             :             osRightTableName.c_str(),   /*description right table name*/
   10343           6 :             GDALGeoPackageDataset::GetCurrentDateEscapedSQL().c_str());
   10344             : 
   10345             :         // Note -- we explicitly ignore failures here, because hey, we aren't really
   10346             :         // supposed to be adding this table to gpkg_contents anyway!
   10347           3 :         (void)SQLCommand(hDB, pszSQL);
   10348           3 :         sqlite3_free(pszSQL);
   10349             : 
   10350           3 :         pszSQL = sqlite3_mprintf(
   10351             :             "CREATE INDEX \"idx_%w_base_id\" ON \"%w\" (base_id);",
   10352             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10353           3 :         eErr = SQLCommand(hDB, pszSQL);
   10354           3 :         sqlite3_free(pszSQL);
   10355           3 :         if (eErr != OGRERR_NONE)
   10356             :         {
   10357           0 :             failureReason = ("Could not create index for " +
   10358           0 :                              osMappingTableName + " (base_id)")
   10359           0 :                                 .c_str();
   10360           0 :             return false;
   10361             :         }
   10362             : 
   10363           3 :         pszSQL = sqlite3_mprintf(
   10364             :             "CREATE INDEX \"idx_%qw_related_id\" ON \"%w\" (related_id);",
   10365             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10366           3 :         eErr = SQLCommand(hDB, pszSQL);
   10367           3 :         sqlite3_free(pszSQL);
   10368           3 :         if (eErr != OGRERR_NONE)
   10369             :         {
   10370           0 :             failureReason = ("Could not create index for " +
   10371           0 :                              osMappingTableName + " (related_id)")
   10372           0 :                                 .c_str();
   10373           0 :             return false;
   10374             :         }
   10375             :     }
   10376             :     else
   10377             :     {
   10378             :         // validate mapping table structure
   10379           6 :         if (OGRGeoPackageTableLayer *poLayer =
   10380           6 :                 cpl::down_cast<OGRGeoPackageTableLayer *>(
   10381           6 :                     GetLayerByName(osMappingTableName)))
   10382             :         {
   10383           4 :             if (poLayer->GetLayerDefn()->GetFieldIndex("base_id") < 0)
   10384             :             {
   10385             :                 failureReason =
   10386           2 :                     ("Field base_id must exist in " + osMappingTableName)
   10387           1 :                         .c_str();
   10388           1 :                 return false;
   10389             :             }
   10390           3 :             if (poLayer->GetLayerDefn()->GetFieldIndex("related_id") < 0)
   10391             :             {
   10392             :                 failureReason =
   10393           2 :                     ("Field related_id must exist in " + osMappingTableName)
   10394           1 :                         .c_str();
   10395           1 :                 return false;
   10396             :             }
   10397             :         }
   10398             :         else
   10399             :         {
   10400             :             failureReason =
   10401           2 :                 ("Could not retrieve table " + osMappingTableName).c_str();
   10402           2 :             return false;
   10403             :         }
   10404             :     }
   10405             : 
   10406           5 :     char *pszSQL = sqlite3_mprintf(
   10407             :         "INSERT INTO gpkg_extensions "
   10408             :         "(table_name,column_name,extension_name,definition,scope) "
   10409             :         "VALUES ('%q', NULL, 'gpkg_related_tables', "
   10410             :         "'http://www.geopackage.org/18-000.html', "
   10411             :         "'read-write')",
   10412             :         osMappingTableName.c_str());
   10413           5 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10414           5 :     sqlite3_free(pszSQL);
   10415           5 :     if (eErr != OGRERR_NONE)
   10416             :     {
   10417           0 :         failureReason = ("Could not insert mapping table " +
   10418           0 :                          osMappingTableName + " into gpkg_extensions")
   10419           0 :                             .c_str();
   10420           0 :         return false;
   10421             :     }
   10422             : 
   10423          15 :     pszSQL = sqlite3_mprintf(
   10424             :         "INSERT INTO gpkgext_relations "
   10425             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10426             :         "primary_column,relation_name,mapping_table_name) "
   10427             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10428           5 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10429           5 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10430             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10431           5 :     eErr = SQLCommand(hDB, pszSQL);
   10432           5 :     sqlite3_free(pszSQL);
   10433           5 :     if (eErr != OGRERR_NONE)
   10434             :     {
   10435           0 :         failureReason = "Could not insert relationship into gpkgext_relations";
   10436           0 :         return false;
   10437             :     }
   10438             : 
   10439           5 :     ClearCachedRelationships();
   10440           5 :     LoadRelationships();
   10441           5 :     return true;
   10442             : }
   10443             : 
   10444             : /************************************************************************/
   10445             : /*                         DeleteRelationship()                         */
   10446             : /************************************************************************/
   10447             : 
   10448           4 : bool GDALGeoPackageDataset::DeleteRelationship(const std::string &name,
   10449             :                                                std::string &failureReason)
   10450             : {
   10451           4 :     if (eAccess != GA_Update)
   10452             :     {
   10453           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10454             :                  "DeleteRelationship() not supported on read-only dataset");
   10455           0 :         return false;
   10456             :     }
   10457             : 
   10458             :     // ensure relationships are up to date before we try to remove one
   10459           4 :     ClearCachedRelationships();
   10460           4 :     LoadRelationships();
   10461             : 
   10462           8 :     std::string osMappingTableName;
   10463             :     {
   10464           4 :         const GDALRelationship *poRelationship = GetRelationship(name);
   10465           4 :         if (poRelationship == nullptr)
   10466             :         {
   10467           1 :             failureReason = "Could not find relationship with name " + name;
   10468           1 :             return false;
   10469             :         }
   10470             : 
   10471           3 :         osMappingTableName = poRelationship->GetMappingTableName();
   10472             :     }
   10473             : 
   10474             :     // DeleteLayerCommon will delete existing relationship objects, so we can't
   10475             :     // refer to poRelationship or any of its members previously obtained here
   10476           3 :     if (DeleteLayerCommon(osMappingTableName.c_str()) != OGRERR_NONE)
   10477             :     {
   10478             :         failureReason =
   10479           0 :             "Could not remove mapping layer name " + osMappingTableName;
   10480             : 
   10481             :         // relationships may have been left in an inconsistent state -- reload
   10482             :         // them now
   10483           0 :         ClearCachedRelationships();
   10484           0 :         LoadRelationships();
   10485           0 :         return false;
   10486             :     }
   10487             : 
   10488           3 :     ClearCachedRelationships();
   10489           3 :     LoadRelationships();
   10490           3 :     return true;
   10491             : }
   10492             : 
   10493             : /************************************************************************/
   10494             : /*                        UpdateRelationship()                          */
   10495             : /************************************************************************/
   10496             : 
   10497           6 : bool GDALGeoPackageDataset::UpdateRelationship(
   10498             :     std::unique_ptr<GDALRelationship> &&relationship,
   10499             :     std::string &failureReason)
   10500             : {
   10501           6 :     if (eAccess != GA_Update)
   10502             :     {
   10503           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10504             :                  "UpdateRelationship() not supported on read-only dataset");
   10505           0 :         return false;
   10506             :     }
   10507             : 
   10508             :     // ensure relationships are up to date before we try to update one
   10509           6 :     ClearCachedRelationships();
   10510           6 :     LoadRelationships();
   10511             : 
   10512           6 :     const std::string &osRelationshipName = relationship->GetName();
   10513           6 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10514           6 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10515           6 :     const std::string &osMappingTableName = relationship->GetMappingTableName();
   10516           6 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10517           6 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10518             : 
   10519             :     // sanity checks
   10520             :     {
   10521             :         const GDALRelationship *poExistingRelationship =
   10522           6 :             GetRelationship(osRelationshipName);
   10523           6 :         if (poExistingRelationship == nullptr)
   10524             :         {
   10525             :             failureReason =
   10526           1 :                 "The relationship should already exist to be updated";
   10527           1 :             return false;
   10528             :         }
   10529             : 
   10530           5 :         if (!ValidateRelationship(relationship.get(), failureReason))
   10531             :         {
   10532           2 :             return false;
   10533             :         }
   10534             : 
   10535             :         // we don't permit changes to the participating tables
   10536           3 :         if (osLeftTableName != poExistingRelationship->GetLeftTableName())
   10537             :         {
   10538           0 :             failureReason = ("Cannot change base table from " +
   10539           0 :                              poExistingRelationship->GetLeftTableName() +
   10540           0 :                              " to " + osLeftTableName)
   10541           0 :                                 .c_str();
   10542           0 :             return false;
   10543             :         }
   10544           3 :         if (osRightTableName != poExistingRelationship->GetRightTableName())
   10545             :         {
   10546           0 :             failureReason = ("Cannot change related table from " +
   10547           0 :                              poExistingRelationship->GetRightTableName() +
   10548           0 :                              " to " + osRightTableName)
   10549           0 :                                 .c_str();
   10550           0 :             return false;
   10551             :         }
   10552           3 :         if (osMappingTableName != poExistingRelationship->GetMappingTableName())
   10553             :         {
   10554           0 :             failureReason = ("Cannot change mapping table from " +
   10555           0 :                              poExistingRelationship->GetMappingTableName() +
   10556           0 :                              " to " + osMappingTableName)
   10557           0 :                                 .c_str();
   10558           0 :             return false;
   10559             :         }
   10560             :     }
   10561             : 
   10562           6 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10563           3 :     if (osRelatedTableType.empty())
   10564             :     {
   10565           0 :         osRelatedTableType = "features";
   10566             :     }
   10567             : 
   10568           3 :     char *pszSQL = sqlite3_mprintf(
   10569             :         "DELETE FROM gpkgext_relations WHERE mapping_table_name='%q'",
   10570             :         osMappingTableName.c_str());
   10571           3 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10572           3 :     sqlite3_free(pszSQL);
   10573           3 :     if (eErr != OGRERR_NONE)
   10574             :     {
   10575             :         failureReason =
   10576           0 :             "Could not delete old relationship from gpkgext_relations";
   10577           0 :         return false;
   10578             :     }
   10579             : 
   10580           9 :     pszSQL = sqlite3_mprintf(
   10581             :         "INSERT INTO gpkgext_relations "
   10582             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10583             :         "primary_column,relation_name,mapping_table_name) "
   10584             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10585           3 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10586           3 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10587             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10588           3 :     eErr = SQLCommand(hDB, pszSQL);
   10589           3 :     sqlite3_free(pszSQL);
   10590           3 :     if (eErr != OGRERR_NONE)
   10591             :     {
   10592             :         failureReason =
   10593           0 :             "Could not insert updated relationship into gpkgext_relations";
   10594           0 :         return false;
   10595             :     }
   10596             : 
   10597           3 :     ClearCachedRelationships();
   10598           3 :     LoadRelationships();
   10599           3 :     return true;
   10600             : }
   10601             : 
   10602             : /************************************************************************/
   10603             : /*                    GetSqliteMasterContent()                          */
   10604             : /************************************************************************/
   10605             : 
   10606             : const std::vector<SQLSqliteMasterContent> &
   10607           2 : GDALGeoPackageDataset::GetSqliteMasterContent()
   10608             : {
   10609           2 :     if (m_aoSqliteMasterContent.empty())
   10610             :     {
   10611             :         auto oResultTable =
   10612           2 :             SQLQuery(hDB, "SELECT sql, type, tbl_name FROM sqlite_master");
   10613           1 :         if (oResultTable)
   10614             :         {
   10615          58 :             for (int rowCnt = 0; rowCnt < oResultTable->RowCount(); ++rowCnt)
   10616             :             {
   10617         114 :                 SQLSqliteMasterContent row;
   10618          57 :                 const char *pszSQL = oResultTable->GetValue(0, rowCnt);
   10619          57 :                 row.osSQL = pszSQL ? pszSQL : "";
   10620          57 :                 const char *pszType = oResultTable->GetValue(1, rowCnt);
   10621          57 :                 row.osType = pszType ? pszType : "";
   10622          57 :                 const char *pszTableName = oResultTable->GetValue(2, rowCnt);
   10623          57 :                 row.osTableName = pszTableName ? pszTableName : "";
   10624          57 :                 m_aoSqliteMasterContent.emplace_back(std::move(row));
   10625             :             }
   10626             :         }
   10627             :     }
   10628           2 :     return m_aoSqliteMasterContent;
   10629             : }

Generated by: LCOV version 1.14