LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/gpkg - ogrgeopackagedatasource.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 4017 4482 89.6 %
Date: 2025-09-10 17:48:50 Functions: 136 136 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         570 : GetTilingScheme(const char *pszName)
      82             : {
      83         570 :     if (EQUAL(pszName, "CUSTOM"))
      84         442 :         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         939 : OGRErr GDALGeoPackageDataset::SetApplicationAndUserVersionId()
     191             : {
     192         939 :     CPLAssert(hDB != nullptr);
     193             : 
     194         939 :     const CPLString osPragma(CPLString().Printf("PRAGMA application_id = %u;"
     195             :                                                 "PRAGMA user_version = %u",
     196             :                                                 m_nApplicationId,
     197        1878 :                                                 m_nUserVersion));
     198        1878 :     return SQLCommand(hDB, osPragma.c_str());
     199             : }
     200             : 
     201        2563 : bool GDALGeoPackageDataset::CloseDB()
     202             : {
     203        2563 :     OGRSQLiteUnregisterSQLFunctions(m_pSQLFunctionData);
     204        2563 :     m_pSQLFunctionData = nullptr;
     205        2563 :     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         814 : static OGRErr GDALGPKGImportFromEPSG(OGRSpatialReference *poSpatialRef,
     222             :                                      int nEPSGCode)
     223             : {
     224         814 :     CPLPushErrorHandler(CPLQuietErrorHandler);
     225         814 :     const OGRErr eErr = poSpatialRef->importFromEPSG(nEPSGCode);
     226         814 :     CPLPopErrorHandler();
     227         814 :     CPLErrorReset();
     228         814 :     return eErr;
     229             : }
     230             : 
     231             : std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
     232        1250 : GDALGeoPackageDataset::GetSpatialRef(int iSrsId, bool bFallbackToEPSG,
     233             :                                      bool bEmitErrorIfNotFound)
     234             : {
     235        1250 :     const auto oIter = m_oMapSrsIdToSrs.find(iSrsId);
     236        1250 :     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        1162 :     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        2086 :     CPLString oSQL;
     270        1043 :     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        1043 :                 m_bHasDefinition12_063 ? ", definition_12_063" : "",
     275        1043 :                 m_bHasEpochColumn ? ", epoch" : "", iSrsId);
     276             : 
     277        2086 :     auto oResult = SQLQuery(hDB, oSQL.c_str());
     278             : 
     279        1043 :     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        1031 :     const char *pszName = oResult->GetValue(0, 0);
     306        1031 :     if (pszName && EQUAL(pszName, "Undefined SRS"))
     307             :     {
     308         445 :         m_oMapSrsIdToSrs[iSrsId] = nullptr;
     309         445 :         return nullptr;
     310             :     }
     311         586 :     const char *pszWkt = oResult->GetValue(1, 0);
     312         586 :     if (pszWkt == nullptr)
     313           0 :         return nullptr;
     314         586 :     const char *pszOrganization = oResult->GetValue(2, 0);
     315         586 :     const char *pszOrganizationCoordsysID = oResult->GetValue(3, 0);
     316             :     const char *pszWkt2 =
     317         586 :         m_bHasDefinition12_063 ? oResult->GetValue(4, 0) : nullptr;
     318         586 :     if (pszWkt2 && !EQUAL(pszWkt2, "undefined"))
     319          76 :         pszWkt = pszWkt2;
     320             :     const char *pszCoordinateEpoch =
     321         586 :         m_bHasEpochColumn ? oResult->GetValue(5, 0) : nullptr;
     322             :     const double dfCoordinateEpoch =
     323         586 :         pszCoordinateEpoch ? CPLAtof(pszCoordinateEpoch) : 0.0;
     324             : 
     325         586 :     OGRSpatialReference *poSpatialRef = new OGRSpatialReference();
     326         586 :     poSpatialRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     327             :     // Try to import first from EPSG code, and then from WKT
     328         586 :     if (!(pszOrganization && pszOrganizationCoordsysID &&
     329         586 :           EQUAL(pszOrganization, "EPSG") &&
     330         566 :           (atoi(pszOrganizationCoordsysID) == iSrsId ||
     331           4 :            (dfCoordinateEpoch > 0 && strstr(pszWkt, "DYNAMIC[") == nullptr)) &&
     332         566 :           GDALGPKGImportFromEPSG(
     333        1172 :               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         586 :     poSpatialRef->StripTOWGS84IfKnownDatumAndAllowed();
     345         586 :     poSpatialRef->SetCoordinateEpoch(dfCoordinateEpoch);
     346         586 :     m_oMapSrsIdToSrs[iSrsId] = poSpatialRef;
     347         586 :     poSpatialRef->Reference();
     348             :     return std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>(
     349         586 :         poSpatialRef);
     350             : }
     351             : 
     352         277 : const char *GDALGeoPackageDataset::GetSrsName(const OGRSpatialReference &oSRS)
     353             : {
     354         277 :     const char *pszName = oSRS.GetName();
     355         277 :     if (pszName)
     356         277 :         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         903 : int GDALGeoPackageDataset::GetSrsId(const OGRSpatialReference *poSRSIn)
     529             : {
     530         903 :     const char *pszName = poSRSIn ? poSRSIn->GetName() : nullptr;
     531        1304 :     if (!poSRSIn || poSRSIn->IsEmpty() ||
     532         401 :         (pszName && EQUAL(pszName, "Undefined SRS")))
     533             :     {
     534         504 :         OGRErr err = OGRERR_NONE;
     535         504 :         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         504 :         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         449 :         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         448 :             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         449 :         if (SQLCommand(hDB, pszSQL) == OGRERR_NONE)
     585         449 :             return UNDEFINED_CRS_SRS_ID;
     586             : #undef UNDEFINED_CRS_SRS_ID
     587             : #undef XSTRINGIFY
     588             : #undef STRINGIFY
     589           0 :         return -1;
     590             :     }
     591             : 
     592         798 :     std::unique_ptr<OGRSpatialReference> poSRS(poSRSIn->Clone());
     593             : 
     594         399 :     if (poSRS->IsGeographic() || poSRS->IsLocal())
     595             :     {
     596             :         // See corresponding tests in GDALGeoPackageDataset::GetSpatialRef
     597         139 :         if (pszName != nullptr && strlen(pszName) > 0)
     598             :         {
     599         139 :             if (EQUAL(pszName, "Undefined geographic SRS"))
     600           2 :                 return 0;
     601             : 
     602         137 :             if (EQUAL(pszName, "Undefined Cartesian SRS"))
     603           1 :                 return -1;
     604             :         }
     605             :     }
     606             : 
     607         396 :     const char *pszAuthorityName = poSRS->GetAuthorityName(nullptr);
     608             : 
     609         396 :     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         396 :     char *pszSQL = nullptr;
     633         396 :     int nSRSId = DEFAULT_SRID;
     634         396 :     int nAuthorityCode = 0;
     635         396 :     OGRErr err = OGRERR_NONE;
     636         396 :     bool bCanUseAuthorityCode = false;
     637         396 :     const char *const apszIsSameOptions[] = {
     638             :         "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES",
     639             :         "IGNORE_COORDINATE_EPOCH=YES", nullptr};
     640         396 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0)
     641             :     {
     642         370 :         const char *pszAuthorityCode = poSRS->GetAuthorityCode(nullptr);
     643         370 :         if (pszAuthorityCode)
     644             :         {
     645         370 :             if (CPLGetValueType(pszAuthorityCode) == CPL_VALUE_INTEGER)
     646             :             {
     647         370 :                 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         766 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     662         370 :         poSRSIn->GetCoordinateEpoch() == 0)
     663             :     {
     664             :         pszSQL =
     665         365 :             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         365 :         nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     671         365 :         sqlite3_free(pszSQL);
     672             : 
     673             :         // Got a match? Return it!
     674         365 :         if (OGRERR_NONE == err)
     675             :         {
     676         115 :             auto poRefSRS = GetSpatialRef(nSRSId);
     677             :             bool bOK =
     678         115 :                 (poRefSRS == nullptr ||
     679         116 :                  poSRS->IsSame(poRefSRS.get(), apszIsSameOptions) ||
     680           1 :                  !CPLTestBool(CPLGetConfigOption("OGR_GPKG_CHECK_SRS", "YES")));
     681         115 :             if (bOK)
     682             :             {
     683         114 :                 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         282 :     CPLCharUniquePtr pszWKT1;
     701         282 :     CPLCharUniquePtr pszWKT2_2015;
     702         282 :     CPLCharUniquePtr pszWKT2_2019;
     703         282 :     const char *const apszOptionsWkt1[] = {"FORMAT=WKT1_GDAL", nullptr};
     704         282 :     const char *const apszOptionsWkt2_2015[] = {"FORMAT=WKT2_2015", nullptr};
     705         282 :     const char *const apszOptionsWkt2_2019[] = {"FORMAT=WKT2_2019", nullptr};
     706             : 
     707         564 :     std::string osEpochTest;
     708         282 :     if (poSRSIn->GetCoordinateEpoch() > 0 && m_bHasEpochColumn)
     709             :     {
     710             :         osEpochTest =
     711           3 :             CPLSPrintf(" AND epoch = %.17g", poSRSIn->GetCoordinateEpoch());
     712             :     }
     713             : 
     714         282 :     if (!(poSRS->IsGeographic() && poSRS->GetAxesCount() == 3))
     715             :     {
     716         273 :         char *pszTmp = nullptr;
     717         273 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt1);
     718         273 :         pszWKT1.reset(pszTmp);
     719         273 :         if (pszWKT1 && pszWKT1.get()[0] == '\0')
     720             :         {
     721           0 :             pszWKT1.reset();
     722             :         }
     723             :     }
     724             :     {
     725         282 :         char *pszTmp = nullptr;
     726         282 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2015);
     727         282 :         pszWKT2_2015.reset(pszTmp);
     728         282 :         if (pszWKT2_2015 && pszWKT2_2015.get()[0] == '\0')
     729             :         {
     730           0 :             pszWKT2_2015.reset();
     731             :         }
     732             :     }
     733             :     {
     734         282 :         char *pszTmp = nullptr;
     735         282 :         poSRS->exportToWkt(&pszTmp, apszOptionsWkt2_2019);
     736         282 :         pszWKT2_2019.reset(pszTmp);
     737         282 :         if (pszWKT2_2019 && pszWKT2_2019.get()[0] == '\0')
     738             :         {
     739           0 :             pszWKT2_2019.reset();
     740             :         }
     741             :     }
     742             : 
     743         282 :     if (!pszWKT1 && !pszWKT2_2015 && !pszWKT2_2019)
     744             :     {
     745           0 :         return DEFAULT_SRID;
     746             :     }
     747             : 
     748         282 :     if (poSRSIn->GetCoordinateEpoch() == 0 || m_bHasEpochColumn)
     749             :     {
     750             :         // Search if there is already an existing entry with this WKT
     751         279 :         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         237 :         else if (pszWKT1)
     774             :         {
     775             :             pszSQL =
     776         234 :                 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         279 :         if (pszSQL)
     785             :         {
     786         276 :             nSRSId = SQLGetInteger(hDB, pszSQL, &err);
     787         276 :             sqlite3_free(pszSQL);
     788         276 :             if (OGRERR_NONE == err)
     789             :             {
     790           5 :                 return nSRSId;
     791             :             }
     792             :         }
     793             :     }
     794             : 
     795         530 :     if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0 &&
     796         253 :         poSRSIn->GetCoordinateEpoch() == 0)
     797             :     {
     798         249 :         bool bTryToReuseSRSId = true;
     799         249 :         if (EQUAL(pszAuthorityName, "EPSG"))
     800             :         {
     801         496 :             OGRSpatialReference oSRS_EPSG;
     802         248 :             if (GDALGPKGImportFromEPSG(&oSRS_EPSG, nAuthorityCode) ==
     803             :                 OGRERR_NONE)
     804             :             {
     805         249 :                 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         249 :         if (bTryToReuseSRSId)
     823             :         {
     824             :             // No match, but maybe we can use the nAuthorityCode as the nSRSId?
     825         248 :             pszSQL = sqlite3_mprintf(
     826             :                 "SELECT Count(*) FROM gpkg_spatial_ref_sys WHERE "
     827             :                 "srs_id = %d",
     828             :                 nAuthorityCode);
     829             : 
     830             :             // Yep, we can!
     831         248 :             if (SQLGetInteger(hDB, pszSQL, nullptr) == 0)
     832         247 :                 bCanUseAuthorityCode = true;
     833         248 :             sqlite3_free(pszSQL);
     834             :         }
     835             :     }
     836             : 
     837         277 :     bool bConvertGpkgSpatialRefSysToExtensionWkt2 = false;
     838         277 :     bool bForceEpoch = false;
     839         280 :     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         277 :     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         283 :     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         277 :     if (bCanUseAuthorityCode)
     892             :     {
     893         247 :         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         554 :     std::string osEpochColumn;
     905         277 :     std::string osEpochVal;
     906         277 :     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         277 :     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         232 :         if (pszAuthorityName != nullptr && nAuthorityCode > 0)
     950             :         {
     951         438 :             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         219 :                 GetSrsName(*poSRS), nSRSId, pszAuthorityName, nAuthorityCode,
     956         438 :                 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         277 :     CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
     971             : 
     972             :     // Free everything that was allocated.
     973         277 :     sqlite3_free(pszSQL);
     974             : 
     975         277 :     return nSRSId;
     976             : }
     977             : 
     978             : /************************************************************************/
     979             : /*                       ~GDALGeoPackageDataset()                       */
     980             : /************************************************************************/
     981             : 
     982        5098 : GDALGeoPackageDataset::~GDALGeoPackageDataset()
     983             : {
     984        2549 :     GDALGeoPackageDataset::Close();
     985        5098 : }
     986             : 
     987             : /************************************************************************/
     988             : /*                              Close()                                 */
     989             : /************************************************************************/
     990             : 
     991        4269 : CPLErr GDALGeoPackageDataset::Close()
     992             : {
     993        4269 :     CPLErr eErr = CE_None;
     994        4269 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     995             :     {
     996        1506 :         if (eAccess == GA_Update && m_poParentDS == nullptr &&
     997        4058 :             !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        5096 :         if (!IsMarkedSuppressOnClose() &&
    1006        2544 :             GDALGeoPackageDataset::FlushCache(true) != CE_None)
    1007             :         {
    1008           7 :             eErr = CE_Failure;
    1009             :         }
    1010             : 
    1011             :         // Destroy bands now since we don't want
    1012             :         // GDALGPKGMBTilesLikeRasterBand::FlushCache() to run after dataset
    1013             :         // destruction
    1014        4369 :         for (int i = 0; i < nBands; i++)
    1015        1817 :             delete papoBands[i];
    1016        2552 :         nBands = 0;
    1017        2552 :         CPLFree(papoBands);
    1018        2552 :         papoBands = nullptr;
    1019             : 
    1020             :         // Destroy overviews before cleaning m_hTempDB as they could still
    1021             :         // need it
    1022        2552 :         m_apoOverviewDS.clear();
    1023             : 
    1024        2552 :         if (m_poParentDS)
    1025             :         {
    1026         325 :             hDB = nullptr;
    1027             :         }
    1028             : 
    1029        2552 :         m_apoLayers.clear();
    1030             : 
    1031             :         std::map<int, OGRSpatialReference *>::iterator oIter =
    1032        2552 :             m_oMapSrsIdToSrs.begin();
    1033        3704 :         for (; oIter != m_oMapSrsIdToSrs.end(); ++oIter)
    1034             :         {
    1035        1152 :             OGRSpatialReference *poSRS = oIter->second;
    1036        1152 :             if (poSRS)
    1037         705 :                 poSRS->Release();
    1038             :         }
    1039             : 
    1040        2552 :         if (!CloseDB())
    1041           0 :             eErr = CE_Failure;
    1042             : 
    1043        2552 :         if (OGRSQLiteBaseDataSource::Close() != CE_None)
    1044           0 :             eErr = CE_Failure;
    1045             :     }
    1046        4269 :     return eErr;
    1047             : }
    1048             : 
    1049             : /************************************************************************/
    1050             : /*                         ICanIWriteBlock()                            */
    1051             : /************************************************************************/
    1052             : 
    1053        5696 : bool GDALGeoPackageDataset::ICanIWriteBlock()
    1054             : {
    1055        5696 :     if (!GetUpdate())
    1056             :     {
    1057           0 :         CPLError(
    1058             :             CE_Failure, CPLE_NotSupported,
    1059             :             "IWriteBlock() not supported on dataset opened in read-only mode");
    1060           0 :         return false;
    1061             :     }
    1062             : 
    1063        5696 :     if (m_pabyCachedTiles == nullptr)
    1064             :     {
    1065           0 :         return false;
    1066             :     }
    1067             : 
    1068        5696 :     if (!m_bGeoTransformValid || m_nSRID == UNKNOWN_SRID)
    1069             :     {
    1070           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    1071             :                  "IWriteBlock() not supported if georeferencing not set");
    1072           0 :         return false;
    1073             :     }
    1074        5696 :     return true;
    1075             : }
    1076             : 
    1077             : /************************************************************************/
    1078             : /*                            IRasterIO()                               */
    1079             : /************************************************************************/
    1080             : 
    1081         132 : CPLErr GDALGeoPackageDataset::IRasterIO(
    1082             :     GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
    1083             :     void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
    1084             :     int nBandCount, BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
    1085             :     GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg)
    1086             : 
    1087             : {
    1088         132 :     CPLErr eErr = OGRSQLiteBaseDataSource::IRasterIO(
    1089             :         eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    1090             :         eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace, nBandSpace,
    1091             :         psExtraArg);
    1092             : 
    1093             :     // If writing all bands, in non-shifted mode, flush all entirely written
    1094             :     // tiles This can avoid "stressing" the block cache with too many dirty
    1095             :     // blocks. Note: this logic would be useless with a per-dataset block cache.
    1096         132 :     if (eErr == CE_None && eRWFlag == GF_Write && nXSize == nBufXSize &&
    1097         123 :         nYSize == nBufYSize && nBandCount == nBands &&
    1098         120 :         m_nShiftXPixelsMod == 0 && m_nShiftYPixelsMod == 0)
    1099             :     {
    1100             :         auto poBand =
    1101         116 :             cpl::down_cast<GDALGPKGMBTilesLikeRasterBand *>(GetRasterBand(1));
    1102             :         int nBlockXSize, nBlockYSize;
    1103         116 :         poBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
    1104         116 :         const int nBlockXStart = DIV_ROUND_UP(nXOff, nBlockXSize);
    1105         116 :         const int nBlockYStart = DIV_ROUND_UP(nYOff, nBlockYSize);
    1106         116 :         const int nBlockXEnd = (nXOff + nXSize) / nBlockXSize;
    1107         116 :         const int nBlockYEnd = (nYOff + nYSize) / nBlockYSize;
    1108         270 :         for (int nBlockY = nBlockXStart; nBlockY < nBlockYEnd; nBlockY++)
    1109             :         {
    1110        4371 :             for (int nBlockX = nBlockYStart; nBlockX < nBlockXEnd; nBlockX++)
    1111             :             {
    1112             :                 GDALRasterBlock *poBlock =
    1113        4217 :                     poBand->AccessibleTryGetLockedBlockRef(nBlockX, nBlockY);
    1114        4217 :                 if (poBlock)
    1115             :                 {
    1116             :                     // GetDirty() should be true in most situation (otherwise
    1117             :                     // it means the block cache is under extreme pressure!)
    1118        4215 :                     if (poBlock->GetDirty())
    1119             :                     {
    1120             :                         // IWriteBlock() on one band will check the dirty state
    1121             :                         // of the corresponding blocks in other bands, to decide
    1122             :                         // if it can call WriteTile(), so we have only to do
    1123             :                         // that on one of the bands
    1124        4215 :                         if (poBlock->Write() != CE_None)
    1125         250 :                             eErr = CE_Failure;
    1126             :                     }
    1127        4215 :                     poBlock->DropLock();
    1128             :                 }
    1129             :             }
    1130             :         }
    1131             :     }
    1132             : 
    1133         132 :     return eErr;
    1134             : }
    1135             : 
    1136             : /************************************************************************/
    1137             : /*                          GetOGRTableLimit()                          */
    1138             : /************************************************************************/
    1139             : 
    1140        4147 : static int GetOGRTableLimit()
    1141             : {
    1142        4147 :     return atoi(CPLGetConfigOption("OGR_TABLE_LIMIT", "10000"));
    1143             : }
    1144             : 
    1145             : /************************************************************************/
    1146             : /*                      GetNameTypeMapFromSQliteMaster()                */
    1147             : /************************************************************************/
    1148             : 
    1149             : const std::map<CPLString, CPLString> &
    1150        1282 : GDALGeoPackageDataset::GetNameTypeMapFromSQliteMaster()
    1151             : {
    1152        1282 :     if (!m_oMapNameToType.empty())
    1153         341 :         return m_oMapNameToType;
    1154             : 
    1155             :     CPLString osSQL(
    1156             :         "SELECT name, type FROM sqlite_master WHERE "
    1157             :         "type IN ('view', 'table') OR "
    1158        1882 :         "(name LIKE 'trigger_%_feature_count_%' AND type = 'trigger')");
    1159         941 :     const int nTableLimit = GetOGRTableLimit();
    1160         941 :     if (nTableLimit > 0)
    1161             :     {
    1162         941 :         osSQL += " LIMIT ";
    1163         941 :         osSQL += CPLSPrintf("%d", 1 + 3 * nTableLimit);
    1164             :     }
    1165             : 
    1166         941 :     auto oResult = SQLQuery(hDB, osSQL);
    1167         941 :     if (oResult)
    1168             :     {
    1169       15647 :         for (int i = 0; i < oResult->RowCount(); i++)
    1170             :         {
    1171       14706 :             const char *pszName = oResult->GetValue(0, i);
    1172       14706 :             const char *pszType = oResult->GetValue(1, i);
    1173       14706 :             m_oMapNameToType[CPLString(pszName).toupper()] = pszType;
    1174             :         }
    1175             :     }
    1176             : 
    1177         941 :     return m_oMapNameToType;
    1178             : }
    1179             : 
    1180             : /************************************************************************/
    1181             : /*                    RemoveTableFromSQLiteMasterCache()                */
    1182             : /************************************************************************/
    1183             : 
    1184          56 : void GDALGeoPackageDataset::RemoveTableFromSQLiteMasterCache(
    1185             :     const char *pszTableName)
    1186             : {
    1187          56 :     m_oMapNameToType.erase(CPLString(pszTableName).toupper());
    1188          56 : }
    1189             : 
    1190             : /************************************************************************/
    1191             : /*                  GetUnknownExtensionsTableSpecific()                 */
    1192             : /************************************************************************/
    1193             : 
    1194             : const std::map<CPLString, std::vector<GPKGExtensionDesc>> &
    1195         897 : GDALGeoPackageDataset::GetUnknownExtensionsTableSpecific()
    1196             : {
    1197         897 :     if (m_bMapTableToExtensionsBuilt)
    1198          89 :         return m_oMapTableToExtensions;
    1199         808 :     m_bMapTableToExtensionsBuilt = true;
    1200             : 
    1201         808 :     if (!HasExtensionsTable())
    1202          48 :         return m_oMapTableToExtensions;
    1203             : 
    1204             :     CPLString osSQL(
    1205             :         "SELECT table_name, extension_name, definition, scope "
    1206             :         "FROM gpkg_extensions WHERE "
    1207             :         "table_name IS NOT NULL "
    1208             :         "AND extension_name IS NOT NULL "
    1209             :         "AND definition IS NOT NULL "
    1210             :         "AND scope IS NOT NULL "
    1211             :         "AND extension_name NOT IN ('gpkg_geom_CIRCULARSTRING', "
    1212             :         "'gpkg_geom_COMPOUNDCURVE', 'gpkg_geom_CURVEPOLYGON', "
    1213             :         "'gpkg_geom_MULTICURVE', "
    1214             :         "'gpkg_geom_MULTISURFACE', 'gpkg_geom_CURVE', 'gpkg_geom_SURFACE', "
    1215             :         "'gpkg_geom_POLYHEDRALSURFACE', 'gpkg_geom_TIN', 'gpkg_geom_TRIANGLE', "
    1216             :         "'gpkg_rtree_index', 'gpkg_geometry_type_trigger', "
    1217             :         "'gpkg_srs_id_trigger', "
    1218             :         "'gpkg_crs_wkt', 'gpkg_crs_wkt_1_1', 'gpkg_schema', "
    1219             :         "'gpkg_related_tables', 'related_tables'"
    1220             : #ifdef HAVE_SPATIALITE
    1221             :         ", 'gdal_spatialite_computed_geom_column'"
    1222             : #endif
    1223        1520 :         ")");
    1224         760 :     const int nTableLimit = GetOGRTableLimit();
    1225         760 :     if (nTableLimit > 0)
    1226             :     {
    1227         760 :         osSQL += " LIMIT ";
    1228         760 :         osSQL += CPLSPrintf("%d", 1 + 10 * nTableLimit);
    1229             :     }
    1230             : 
    1231         760 :     auto oResult = SQLQuery(hDB, osSQL);
    1232         760 :     if (oResult)
    1233             :     {
    1234        1417 :         for (int i = 0; i < oResult->RowCount(); i++)
    1235             :         {
    1236         657 :             const char *pszTableName = oResult->GetValue(0, i);
    1237         657 :             const char *pszExtensionName = oResult->GetValue(1, i);
    1238         657 :             const char *pszDefinition = oResult->GetValue(2, i);
    1239         657 :             const char *pszScope = oResult->GetValue(3, i);
    1240         657 :             if (pszTableName && pszExtensionName && pszDefinition && pszScope)
    1241             :             {
    1242         657 :                 GPKGExtensionDesc oDesc;
    1243         657 :                 oDesc.osExtensionName = pszExtensionName;
    1244         657 :                 oDesc.osDefinition = pszDefinition;
    1245         657 :                 oDesc.osScope = pszScope;
    1246        1314 :                 m_oMapTableToExtensions[CPLString(pszTableName).toupper()]
    1247         657 :                     .push_back(std::move(oDesc));
    1248             :             }
    1249             :         }
    1250             :     }
    1251             : 
    1252         760 :     return m_oMapTableToExtensions;
    1253             : }
    1254             : 
    1255             : /************************************************************************/
    1256             : /*                           GetContents()                              */
    1257             : /************************************************************************/
    1258             : 
    1259             : const std::map<CPLString, GPKGContentsDesc> &
    1260         879 : GDALGeoPackageDataset::GetContents()
    1261             : {
    1262         879 :     if (m_bMapTableToContentsBuilt)
    1263          73 :         return m_oMapTableToContents;
    1264         806 :     m_bMapTableToContentsBuilt = true;
    1265             : 
    1266             :     CPLString osSQL("SELECT table_name, data_type, identifier, "
    1267             :                     "description, min_x, min_y, max_x, max_y "
    1268        1612 :                     "FROM gpkg_contents");
    1269         806 :     const int nTableLimit = GetOGRTableLimit();
    1270         806 :     if (nTableLimit > 0)
    1271             :     {
    1272         806 :         osSQL += " LIMIT ";
    1273         806 :         osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1274             :     }
    1275             : 
    1276         806 :     auto oResult = SQLQuery(hDB, osSQL);
    1277         806 :     if (oResult)
    1278             :     {
    1279        1730 :         for (int i = 0; i < oResult->RowCount(); i++)
    1280             :         {
    1281         924 :             const char *pszTableName = oResult->GetValue(0, i);
    1282         924 :             if (pszTableName == nullptr)
    1283           0 :                 continue;
    1284         924 :             const char *pszDataType = oResult->GetValue(1, i);
    1285         924 :             const char *pszIdentifier = oResult->GetValue(2, i);
    1286         924 :             const char *pszDescription = oResult->GetValue(3, i);
    1287         924 :             const char *pszMinX = oResult->GetValue(4, i);
    1288         924 :             const char *pszMinY = oResult->GetValue(5, i);
    1289         924 :             const char *pszMaxX = oResult->GetValue(6, i);
    1290         924 :             const char *pszMaxY = oResult->GetValue(7, i);
    1291         924 :             GPKGContentsDesc oDesc;
    1292         924 :             if (pszDataType)
    1293         924 :                 oDesc.osDataType = pszDataType;
    1294         924 :             if (pszIdentifier)
    1295         924 :                 oDesc.osIdentifier = pszIdentifier;
    1296         924 :             if (pszDescription)
    1297         923 :                 oDesc.osDescription = pszDescription;
    1298         924 :             if (pszMinX)
    1299         622 :                 oDesc.osMinX = pszMinX;
    1300         924 :             if (pszMinY)
    1301         622 :                 oDesc.osMinY = pszMinY;
    1302         924 :             if (pszMaxX)
    1303         622 :                 oDesc.osMaxX = pszMaxX;
    1304         924 :             if (pszMaxY)
    1305         622 :                 oDesc.osMaxY = pszMaxY;
    1306        1848 :             m_oMapTableToContents[CPLString(pszTableName).toupper()] =
    1307        1848 :                 std::move(oDesc);
    1308             :         }
    1309             :     }
    1310             : 
    1311         806 :     return m_oMapTableToContents;
    1312             : }
    1313             : 
    1314             : /************************************************************************/
    1315             : /*                                Open()                                */
    1316             : /************************************************************************/
    1317             : 
    1318        1261 : int GDALGeoPackageDataset::Open(GDALOpenInfo *poOpenInfo,
    1319             :                                 const std::string &osFilenameInZip)
    1320             : {
    1321        1261 :     m_osFilenameInZip = osFilenameInZip;
    1322        1261 :     CPLAssert(m_apoLayers.empty());
    1323        1261 :     CPLAssert(hDB == nullptr);
    1324             : 
    1325        1261 :     SetDescription(poOpenInfo->pszFilename);
    1326        2522 :     CPLString osFilename(poOpenInfo->pszFilename);
    1327        2522 :     CPLString osSubdatasetTableName;
    1328             :     GByte abyHeaderLetMeHerePlease[100];
    1329        1261 :     const GByte *pabyHeader = poOpenInfo->pabyHeader;
    1330        1261 :     if (STARTS_WITH_CI(poOpenInfo->pszFilename, "GPKG:"))
    1331             :     {
    1332         246 :         char **papszTokens = CSLTokenizeString2(poOpenInfo->pszFilename, ":",
    1333             :                                                 CSLT_HONOURSTRINGS);
    1334         246 :         int nCount = CSLCount(papszTokens);
    1335         246 :         if (nCount < 2)
    1336             :         {
    1337           0 :             CSLDestroy(papszTokens);
    1338           0 :             return FALSE;
    1339             :         }
    1340             : 
    1341         246 :         if (nCount <= 3)
    1342             :         {
    1343         244 :             osFilename = papszTokens[1];
    1344             :         }
    1345             :         /* GPKG:C:\BLA.GPKG:foo */
    1346           2 :         else if (nCount == 4 && strlen(papszTokens[1]) == 1 &&
    1347           2 :                  (papszTokens[2][0] == '/' || papszTokens[2][0] == '\\'))
    1348             :         {
    1349           2 :             osFilename = CPLString(papszTokens[1]) + ":" + papszTokens[2];
    1350             :         }
    1351             :         // GPKG:/vsicurl/http[s]://[user:passwd@]example.com[:8080]/foo.gpkg:bar
    1352           0 :         else if (/*nCount >= 4 && */
    1353           0 :                  (EQUAL(papszTokens[1], "/vsicurl/http") ||
    1354           0 :                   EQUAL(papszTokens[1], "/vsicurl/https")))
    1355             :         {
    1356           0 :             osFilename = CPLString(papszTokens[1]);
    1357           0 :             for (int i = 2; i < nCount - 1; i++)
    1358             :             {
    1359           0 :                 osFilename += ':';
    1360           0 :                 osFilename += papszTokens[i];
    1361             :             }
    1362             :         }
    1363         246 :         if (nCount >= 3)
    1364          14 :             osSubdatasetTableName = papszTokens[nCount - 1];
    1365             : 
    1366         246 :         CSLDestroy(papszTokens);
    1367         246 :         VSILFILE *fp = VSIFOpenL(osFilename, "rb");
    1368         246 :         if (fp != nullptr)
    1369             :         {
    1370         246 :             VSIFReadL(abyHeaderLetMeHerePlease, 1, 100, fp);
    1371         246 :             VSIFCloseL(fp);
    1372             :         }
    1373         246 :         pabyHeader = abyHeaderLetMeHerePlease;
    1374             :     }
    1375        1015 :     else if (poOpenInfo->pabyHeader &&
    1376        1015 :              STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1377             :                          "SQLite format 3"))
    1378             :     {
    1379        1008 :         m_bCallUndeclareFileNotToOpen = true;
    1380        1008 :         GDALOpenInfoDeclareFileNotToOpen(osFilename, poOpenInfo->pabyHeader,
    1381             :                                          poOpenInfo->nHeaderBytes);
    1382             :     }
    1383             : 
    1384        1261 :     eAccess = poOpenInfo->eAccess;
    1385        1261 :     if (!m_osFilenameInZip.empty())
    1386             :     {
    1387           2 :         m_pszFilename = CPLStrdup(CPLSPrintf(
    1388             :             "/vsizip/{%s}/%s", osFilename.c_str(), m_osFilenameInZip.c_str()));
    1389             :     }
    1390             :     else
    1391             :     {
    1392        1259 :         m_pszFilename = CPLStrdup(osFilename);
    1393             :     }
    1394             : 
    1395        1261 :     if (poOpenInfo->papszOpenOptions)
    1396             :     {
    1397         100 :         CSLDestroy(papszOpenOptions);
    1398         100 :         papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
    1399             :     }
    1400             : 
    1401             : #ifdef ENABLE_SQL_GPKG_FORMAT
    1402        1261 :     if (poOpenInfo->pabyHeader &&
    1403        1015 :         STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    1404           5 :                     "-- SQL GPKG") &&
    1405           5 :         poOpenInfo->fpL != nullptr)
    1406             :     {
    1407           5 :         if (sqlite3_open_v2(":memory:", &hDB, SQLITE_OPEN_READWRITE, nullptr) !=
    1408             :             SQLITE_OK)
    1409             :         {
    1410           0 :             return FALSE;
    1411             :         }
    1412             : 
    1413           5 :         InstallSQLFunctions();
    1414             : 
    1415             :         // Ingest the lines of the dump
    1416           5 :         VSIFSeekL(poOpenInfo->fpL, 0, SEEK_SET);
    1417             :         const char *pszLine;
    1418          76 :         while ((pszLine = CPLReadLineL(poOpenInfo->fpL)) != nullptr)
    1419             :         {
    1420          71 :             if (STARTS_WITH(pszLine, "--"))
    1421           5 :                 continue;
    1422             : 
    1423          66 :             if (!SQLCheckLineIsSafe(pszLine))
    1424           0 :                 return false;
    1425             : 
    1426          66 :             char *pszErrMsg = nullptr;
    1427          66 :             if (sqlite3_exec(hDB, pszLine, nullptr, nullptr, &pszErrMsg) !=
    1428             :                 SQLITE_OK)
    1429             :             {
    1430           0 :                 if (pszErrMsg)
    1431           0 :                     CPLDebug("SQLITE", "Error %s", pszErrMsg);
    1432             :             }
    1433          66 :             sqlite3_free(pszErrMsg);
    1434           5 :         }
    1435             :     }
    1436             : 
    1437        1256 :     else if (pabyHeader != nullptr)
    1438             : #endif
    1439             :     {
    1440        1256 :         if (poOpenInfo->fpL)
    1441             :         {
    1442             :             // See above comment about -wal locking for the importance of
    1443             :             // closing that file, prior to calling sqlite3_open()
    1444         910 :             VSIFCloseL(poOpenInfo->fpL);
    1445         910 :             poOpenInfo->fpL = nullptr;
    1446             :         }
    1447             : 
    1448             :         /* See if we can open the SQLite database */
    1449        1256 :         if (!OpenOrCreateDB(GetUpdate() ? SQLITE_OPEN_READWRITE
    1450             :                                         : SQLITE_OPEN_READONLY))
    1451           2 :             return FALSE;
    1452             : 
    1453        1254 :         memcpy(&m_nApplicationId, pabyHeader + knApplicationIdPos, 4);
    1454        1254 :         m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    1455        1254 :         memcpy(&m_nUserVersion, pabyHeader + knUserVersionPos, 4);
    1456        1254 :         m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    1457        1254 :         if (m_nApplicationId == GP10_APPLICATION_ID)
    1458             :         {
    1459           7 :             CPLDebug("GPKG", "GeoPackage v1.0");
    1460             :         }
    1461        1247 :         else if (m_nApplicationId == GP11_APPLICATION_ID)
    1462             :         {
    1463           2 :             CPLDebug("GPKG", "GeoPackage v1.1");
    1464             :         }
    1465        1245 :         else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    1466        1241 :                  m_nUserVersion >= GPKG_1_2_VERSION)
    1467             :         {
    1468        1239 :             CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    1469        1239 :                      (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    1470             :         }
    1471             :     }
    1472             : 
    1473             :     /* Requirement 6: The SQLite PRAGMA integrity_check SQL command SHALL return
    1474             :      * “ok” */
    1475             :     /* http://opengis.github.io/geopackage/#_file_integrity */
    1476             :     /* Disable integrity check by default, since it is expensive on big files */
    1477        1259 :     if (CPLTestBool(CPLGetConfigOption("OGR_GPKG_INTEGRITY_CHECK", "NO")) &&
    1478           0 :         OGRERR_NONE != PragmaCheck("integrity_check", "ok", 1))
    1479             :     {
    1480           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1481             :                  "pragma integrity_check on '%s' failed", m_pszFilename);
    1482           0 :         return FALSE;
    1483             :     }
    1484             : 
    1485             :     /* Requirement 7: The SQLite PRAGMA foreign_key_check() SQL with no */
    1486             :     /* parameter value SHALL return an empty result set */
    1487             :     /* http://opengis.github.io/geopackage/#_file_integrity */
    1488             :     /* Disable the check by default, since it is to corrupt databases, and */
    1489             :     /* that causes issues to downstream software that can't open them. */
    1490        1259 :     if (CPLTestBool(CPLGetConfigOption("OGR_GPKG_FOREIGN_KEY_CHECK", "NO")) &&
    1491           0 :         OGRERR_NONE != PragmaCheck("foreign_key_check", "", 0))
    1492             :     {
    1493           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1494             :                  "pragma foreign_key_check on '%s' failed.", m_pszFilename);
    1495           0 :         return FALSE;
    1496             :     }
    1497             : 
    1498             :     /* Check for requirement metadata tables */
    1499             :     /* Requirement 10: gpkg_spatial_ref_sys must exist */
    1500             :     /* Requirement 13: gpkg_contents must exist */
    1501        1259 :     if (SQLGetInteger(hDB,
    1502             :                       "SELECT COUNT(*) FROM sqlite_master WHERE "
    1503             :                       "name IN ('gpkg_spatial_ref_sys', 'gpkg_contents') AND "
    1504             :                       "type IN ('table', 'view')",
    1505        1259 :                       nullptr) != 2)
    1506             :     {
    1507           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1508             :                  "At least one of the required GeoPackage tables, "
    1509             :                  "gpkg_spatial_ref_sys or gpkg_contents, is missing");
    1510           0 :         return FALSE;
    1511             :     }
    1512             : 
    1513        1259 :     DetectSpatialRefSysColumns();
    1514             : 
    1515             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    1516        1259 :     if (SQLGetInteger(hDB,
    1517             :                       "SELECT 1 FROM sqlite_master WHERE "
    1518             :                       "name = 'gpkg_ogr_contents' AND type = 'table'",
    1519        1259 :                       nullptr) == 1)
    1520             :     {
    1521        1251 :         m_bHasGPKGOGRContents = true;
    1522             :     }
    1523             : #endif
    1524             : 
    1525        1259 :     CheckUnknownExtensions();
    1526             : 
    1527        1259 :     int bRet = FALSE;
    1528        1259 :     bool bHasGPKGExtRelations = false;
    1529        1259 :     if (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR)
    1530             :     {
    1531        1072 :         m_bHasGPKGGeometryColumns =
    1532        1072 :             SQLGetInteger(hDB,
    1533             :                           "SELECT 1 FROM sqlite_master WHERE "
    1534             :                           "name = 'gpkg_geometry_columns' AND "
    1535             :                           "type IN ('table', 'view')",
    1536        1072 :                           nullptr) == 1;
    1537        1072 :         bHasGPKGExtRelations = HasGpkgextRelationsTable();
    1538             :     }
    1539        1259 :     if (m_bHasGPKGGeometryColumns)
    1540             :     {
    1541             :         /* Load layer definitions for all tables in gpkg_contents &
    1542             :          * gpkg_geometry_columns */
    1543             :         /* and non-spatial tables as well */
    1544             :         std::string osSQL =
    1545             :             "SELECT c.table_name, c.identifier, 1 as is_spatial, "
    1546             :             "g.column_name, g.geometry_type_name, g.z, g.m, c.min_x, c.min_y, "
    1547             :             "c.max_x, c.max_y, 1 AS is_in_gpkg_contents, "
    1548             :             "(SELECT type FROM sqlite_master WHERE lower(name) = "
    1549             :             "lower(c.table_name) AND type IN ('table', 'view')) AS object_type "
    1550             :             "  FROM gpkg_geometry_columns g "
    1551             :             "  JOIN gpkg_contents c ON (g.table_name = c.table_name)"
    1552             :             "  WHERE "
    1553             :             "  c.table_name <> 'ogr_empty_table' AND"
    1554             :             "  c.data_type = 'features' "
    1555             :             // aspatial: Was the only method available in OGR 2.0 and 2.1
    1556             :             // attributes: GPKG 1.2 or later
    1557             :             "UNION ALL "
    1558             :             "SELECT table_name, identifier, 0 as is_spatial, NULL, NULL, 0, 0, "
    1559             :             "0 AS xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 1 AS "
    1560             :             "is_in_gpkg_contents, "
    1561             :             "(SELECT type FROM sqlite_master WHERE lower(name) = "
    1562             :             "lower(table_name) AND type IN ('table', 'view')) AS object_type "
    1563             :             "  FROM gpkg_contents"
    1564        1071 :             "  WHERE data_type IN ('aspatial', 'attributes') ";
    1565             : 
    1566        2142 :         const char *pszListAllTables = CSLFetchNameValueDef(
    1567        1071 :             poOpenInfo->papszOpenOptions, "LIST_ALL_TABLES", "AUTO");
    1568        1071 :         bool bHasASpatialOrAttributes = HasGDALAspatialExtension();
    1569        1071 :         if (!bHasASpatialOrAttributes)
    1570             :         {
    1571             :             auto oResultTable =
    1572             :                 SQLQuery(hDB, "SELECT * FROM gpkg_contents WHERE "
    1573        1070 :                               "data_type = 'attributes' LIMIT 1");
    1574        1070 :             bHasASpatialOrAttributes =
    1575        1070 :                 (oResultTable && oResultTable->RowCount() == 1);
    1576             :         }
    1577        1071 :         if (bHasGPKGExtRelations)
    1578             :         {
    1579             :             osSQL += "UNION ALL "
    1580             :                      "SELECT mapping_table_name, mapping_table_name, 0 as "
    1581             :                      "is_spatial, NULL, NULL, 0, 0, 0 AS "
    1582             :                      "xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 0 AS "
    1583             :                      "is_in_gpkg_contents, 'table' AS object_type "
    1584             :                      "FROM gpkgext_relations WHERE "
    1585             :                      "lower(mapping_table_name) NOT IN (SELECT "
    1586             :                      "lower(table_name) FROM gpkg_contents) AND "
    1587             :                      "EXISTS (SELECT 1 FROM sqlite_master WHERE "
    1588             :                      "type IN ('table', 'view') AND "
    1589          18 :                      "lower(name) = lower(mapping_table_name))";
    1590             :         }
    1591        1071 :         if (EQUAL(pszListAllTables, "YES") ||
    1592        1070 :             (!bHasASpatialOrAttributes && EQUAL(pszListAllTables, "AUTO")))
    1593             :         {
    1594             :             // vgpkg_ is Spatialite virtual table
    1595             :             osSQL +=
    1596             :                 "UNION ALL "
    1597             :                 "SELECT name, name, 0 as is_spatial, NULL, NULL, 0, 0, 0 AS "
    1598             :                 "xmin, 0 AS ymin, 0 AS xmax, 0 AS ymax, 0 AS "
    1599             :                 "is_in_gpkg_contents, type AS object_type "
    1600             :                 "FROM sqlite_master WHERE type IN ('table', 'view') "
    1601             :                 "AND name NOT LIKE 'gpkg_%' "
    1602             :                 "AND name NOT LIKE 'vgpkg_%' "
    1603             :                 "AND name NOT LIKE 'rtree_%' AND name NOT LIKE 'sqlite_%' "
    1604             :                 // Avoid reading those views from simple_sewer_features.gpkg
    1605             :                 "AND name NOT IN ('st_spatial_ref_sys', 'spatial_ref_sys', "
    1606             :                 "'st_geometry_columns', 'geometry_columns') "
    1607             :                 "AND lower(name) NOT IN (SELECT lower(table_name) FROM "
    1608        1004 :                 "gpkg_contents)";
    1609        1004 :             if (bHasGPKGExtRelations)
    1610             :             {
    1611             :                 osSQL += " AND lower(name) NOT IN (SELECT "
    1612             :                          "lower(mapping_table_name) FROM "
    1613          13 :                          "gpkgext_relations)";
    1614             :             }
    1615             :         }
    1616        1071 :         const int nTableLimit = GetOGRTableLimit();
    1617        1071 :         if (nTableLimit > 0)
    1618             :         {
    1619        1071 :             osSQL += " LIMIT ";
    1620        1071 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1621             :         }
    1622             : 
    1623        1071 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1624        1071 :         if (!oResult)
    1625             :         {
    1626           0 :             return FALSE;
    1627             :         }
    1628             : 
    1629        1071 :         if (nTableLimit > 0 && oResult->RowCount() > nTableLimit)
    1630             :         {
    1631           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    1632             :                      "File has more than %d vector tables. "
    1633             :                      "Limiting to first %d (can be overridden with "
    1634             :                      "OGR_TABLE_LIMIT config option)",
    1635             :                      nTableLimit, nTableLimit);
    1636           1 :             oResult->LimitRowCount(nTableLimit);
    1637             :         }
    1638             : 
    1639        1071 :         if (oResult->RowCount() > 0)
    1640             :         {
    1641         954 :             bRet = TRUE;
    1642             : 
    1643         954 :             m_apoLayers.reserve(oResult->RowCount());
    1644             : 
    1645        1908 :             std::map<std::string, int> oMapTableRefCount;
    1646        4104 :             for (int i = 0; i < oResult->RowCount(); i++)
    1647             :             {
    1648        3150 :                 const char *pszTableName = oResult->GetValue(0, i);
    1649        3150 :                 if (pszTableName == nullptr)
    1650           0 :                     continue;
    1651        3150 :                 if (++oMapTableRefCount[pszTableName] == 2)
    1652             :                 {
    1653             :                     // This should normally not happen if all constraints are
    1654             :                     // properly set
    1655           2 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1656             :                              "Table %s appearing several times in "
    1657             :                              "gpkg_contents and/or gpkg_geometry_columns",
    1658             :                              pszTableName);
    1659             :                 }
    1660             :             }
    1661             : 
    1662        1908 :             std::set<std::string> oExistingLayers;
    1663        4104 :             for (int i = 0; i < oResult->RowCount(); i++)
    1664             :             {
    1665        3150 :                 const char *pszTableName = oResult->GetValue(0, i);
    1666        3150 :                 if (pszTableName == nullptr)
    1667           2 :                     continue;
    1668             :                 const bool bTableHasSeveralGeomColumns =
    1669        3150 :                     oMapTableRefCount[pszTableName] > 1;
    1670        3150 :                 bool bIsSpatial = CPL_TO_BOOL(oResult->GetValueAsInteger(2, i));
    1671        3150 :                 const char *pszGeomColName = oResult->GetValue(3, i);
    1672        3150 :                 const char *pszGeomType = oResult->GetValue(4, i);
    1673        3150 :                 const char *pszZ = oResult->GetValue(5, i);
    1674        3150 :                 const char *pszM = oResult->GetValue(6, i);
    1675             :                 bool bIsInGpkgContents =
    1676        3150 :                     CPL_TO_BOOL(oResult->GetValueAsInteger(11, i));
    1677        3150 :                 if (!bIsInGpkgContents)
    1678          44 :                     m_bNonSpatialTablesNonRegisteredInGpkgContentsFound = true;
    1679        3150 :                 const char *pszObjectType = oResult->GetValue(12, i);
    1680        3150 :                 if (pszObjectType == nullptr ||
    1681        3149 :                     !(EQUAL(pszObjectType, "table") ||
    1682          21 :                       EQUAL(pszObjectType, "view")))
    1683             :                 {
    1684           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    1685             :                              "Table/view %s is referenced in gpkg_contents, "
    1686             :                              "but does not exist",
    1687             :                              pszTableName);
    1688           1 :                     continue;
    1689             :                 }
    1690             :                 // Non-standard and undocumented behavior:
    1691             :                 // if the same table appears to have several geometry columns,
    1692             :                 // handle it for now as multiple layers named
    1693             :                 // "table_name (geom_col_name)"
    1694             :                 // The way we handle that might change in the future (e.g
    1695             :                 // could be a single layer with multiple geometry columns)
    1696             :                 std::string osLayerNameWithGeomColName =
    1697        6254 :                     pszGeomColName ? std::string(pszTableName) + " (" +
    1698             :                                          pszGeomColName + ')'
    1699        6298 :                                    : std::string(pszTableName);
    1700        3149 :                 if (cpl::contains(oExistingLayers, osLayerNameWithGeomColName))
    1701           1 :                     continue;
    1702        3148 :                 oExistingLayers.insert(osLayerNameWithGeomColName);
    1703             :                 const std::string osLayerName =
    1704             :                     bTableHasSeveralGeomColumns
    1705           3 :                         ? std::move(osLayerNameWithGeomColName)
    1706        6299 :                         : std::string(pszTableName);
    1707             :                 auto poLayer = std::make_unique<OGRGeoPackageTableLayer>(
    1708        6296 :                     this, osLayerName.c_str());
    1709        3148 :                 bool bHasZ = pszZ && atoi(pszZ) > 0;
    1710        3148 :                 bool bHasM = pszM && atoi(pszM) > 0;
    1711        3148 :                 if (pszGeomType && EQUAL(pszGeomType, "GEOMETRY"))
    1712             :                 {
    1713         617 :                     if (pszZ && atoi(pszZ) == 2)
    1714           7 :                         bHasZ = false;
    1715         617 :                     if (pszM && atoi(pszM) == 2)
    1716           6 :                         bHasM = false;
    1717             :                 }
    1718        3148 :                 poLayer->SetOpeningParameters(
    1719             :                     pszTableName, pszObjectType, bIsInGpkgContents, bIsSpatial,
    1720             :                     pszGeomColName, pszGeomType, bHasZ, bHasM);
    1721        3148 :                 m_apoLayers.push_back(std::move(poLayer));
    1722             :             }
    1723             :         }
    1724             :     }
    1725             : 
    1726        1259 :     bool bHasTileMatrixSet = false;
    1727        1259 :     if (poOpenInfo->nOpenFlags & GDAL_OF_RASTER)
    1728             :     {
    1729         571 :         bHasTileMatrixSet = SQLGetInteger(hDB,
    1730             :                                           "SELECT 1 FROM sqlite_master WHERE "
    1731             :                                           "name = 'gpkg_tile_matrix_set' AND "
    1732             :                                           "type IN ('table', 'view')",
    1733             :                                           nullptr) == 1;
    1734             :     }
    1735        1259 :     if (bHasTileMatrixSet)
    1736             :     {
    1737             :         std::string osSQL =
    1738             :             "SELECT c.table_name, c.identifier, c.description, c.srs_id, "
    1739             :             "c.min_x, c.min_y, c.max_x, c.max_y, "
    1740             :             "tms.min_x, tms.min_y, tms.max_x, tms.max_y, c.data_type "
    1741             :             "FROM gpkg_contents c JOIN gpkg_tile_matrix_set tms ON "
    1742             :             "c.table_name = tms.table_name WHERE "
    1743         569 :             "data_type IN ('tiles', '2d-gridded-coverage')";
    1744         569 :         if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE"))
    1745             :             osSubdatasetTableName =
    1746           2 :                 CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TABLE");
    1747         569 :         if (!osSubdatasetTableName.empty())
    1748             :         {
    1749          16 :             char *pszTmp = sqlite3_mprintf(" AND c.table_name='%q'",
    1750             :                                            osSubdatasetTableName.c_str());
    1751          16 :             osSQL += pszTmp;
    1752          16 :             sqlite3_free(pszTmp);
    1753          16 :             SetPhysicalFilename(osFilename.c_str());
    1754             :         }
    1755         569 :         const int nTableLimit = GetOGRTableLimit();
    1756         569 :         if (nTableLimit > 0)
    1757             :         {
    1758         569 :             osSQL += " LIMIT ";
    1759         569 :             osSQL += CPLSPrintf("%d", 1 + nTableLimit);
    1760             :         }
    1761             : 
    1762         569 :         auto oResult = SQLQuery(hDB, osSQL.c_str());
    1763         569 :         if (!oResult)
    1764             :         {
    1765           0 :             return FALSE;
    1766             :         }
    1767             : 
    1768         569 :         if (oResult->RowCount() == 0 && !osSubdatasetTableName.empty())
    1769             :         {
    1770           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1771             :                      "Cannot find table '%s' in GeoPackage dataset",
    1772             :                      osSubdatasetTableName.c_str());
    1773             :         }
    1774         568 :         else if (oResult->RowCount() == 1)
    1775             :         {
    1776         274 :             const char *pszTableName = oResult->GetValue(0, 0);
    1777         274 :             const char *pszIdentifier = oResult->GetValue(1, 0);
    1778         274 :             const char *pszDescription = oResult->GetValue(2, 0);
    1779         274 :             const char *pszSRSId = oResult->GetValue(3, 0);
    1780         274 :             const char *pszMinX = oResult->GetValue(4, 0);
    1781         274 :             const char *pszMinY = oResult->GetValue(5, 0);
    1782         274 :             const char *pszMaxX = oResult->GetValue(6, 0);
    1783         274 :             const char *pszMaxY = oResult->GetValue(7, 0);
    1784         274 :             const char *pszTMSMinX = oResult->GetValue(8, 0);
    1785         274 :             const char *pszTMSMinY = oResult->GetValue(9, 0);
    1786         274 :             const char *pszTMSMaxX = oResult->GetValue(10, 0);
    1787         274 :             const char *pszTMSMaxY = oResult->GetValue(11, 0);
    1788         274 :             const char *pszDataType = oResult->GetValue(12, 0);
    1789         274 :             if (pszTableName && pszTMSMinX && pszTMSMinY && pszTMSMaxX &&
    1790             :                 pszTMSMaxY)
    1791             :             {
    1792         548 :                 bRet = OpenRaster(
    1793             :                     pszTableName, pszIdentifier, pszDescription,
    1794         274 :                     pszSRSId ? atoi(pszSRSId) : 0, CPLAtof(pszTMSMinX),
    1795             :                     CPLAtof(pszTMSMinY), CPLAtof(pszTMSMaxX),
    1796             :                     CPLAtof(pszTMSMaxY), pszMinX, pszMinY, pszMaxX, pszMaxY,
    1797         274 :                     EQUAL(pszDataType, "tiles"), poOpenInfo->papszOpenOptions);
    1798             :             }
    1799             :         }
    1800         294 :         else if (oResult->RowCount() >= 1)
    1801             :         {
    1802           5 :             bRet = TRUE;
    1803             : 
    1804           5 :             if (nTableLimit > 0 && oResult->RowCount() > nTableLimit)
    1805             :             {
    1806           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1807             :                          "File has more than %d raster tables. "
    1808             :                          "Limiting to first %d (can be overridden with "
    1809             :                          "OGR_TABLE_LIMIT config option)",
    1810             :                          nTableLimit, nTableLimit);
    1811           1 :                 oResult->LimitRowCount(nTableLimit);
    1812             :             }
    1813             : 
    1814           5 :             int nSDSCount = 0;
    1815        2013 :             for (int i = 0; i < oResult->RowCount(); i++)
    1816             :             {
    1817        2008 :                 const char *pszTableName = oResult->GetValue(0, i);
    1818        2008 :                 const char *pszIdentifier = oResult->GetValue(1, i);
    1819        2008 :                 if (pszTableName == nullptr)
    1820           0 :                     continue;
    1821             :                 m_aosSubDatasets.AddNameValue(
    1822             :                     CPLSPrintf("SUBDATASET_%d_NAME", nSDSCount + 1),
    1823        2008 :                     CPLSPrintf("GPKG:%s:%s", m_pszFilename, pszTableName));
    1824             :                 m_aosSubDatasets.AddNameValue(
    1825             :                     CPLSPrintf("SUBDATASET_%d_DESC", nSDSCount + 1),
    1826             :                     pszIdentifier
    1827        2008 :                         ? CPLSPrintf("%s - %s", pszTableName, pszIdentifier)
    1828        4016 :                         : pszTableName);
    1829        2008 :                 nSDSCount++;
    1830             :             }
    1831             :         }
    1832             :     }
    1833             : 
    1834        1259 :     if (!bRet && (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR))
    1835             :     {
    1836          33 :         if ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE))
    1837             :         {
    1838          22 :             bRet = TRUE;
    1839             :         }
    1840             :         else
    1841             :         {
    1842          11 :             CPLDebug("GPKG",
    1843             :                      "This GeoPackage has no vector content and is opened "
    1844             :                      "in read-only mode. If you open it in update mode, "
    1845             :                      "opening will be successful.");
    1846             :         }
    1847             :     }
    1848             : 
    1849        1259 :     if (eAccess == GA_Update)
    1850             :     {
    1851         257 :         FixupWrongRTreeTrigger();
    1852         257 :         FixupWrongMedataReferenceColumnNameUpdate();
    1853             :     }
    1854             : 
    1855        1259 :     SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    1856             : 
    1857        1259 :     return bRet;
    1858             : }
    1859             : 
    1860             : /************************************************************************/
    1861             : /*                    DetectSpatialRefSysColumns()                      */
    1862             : /************************************************************************/
    1863             : 
    1864        1269 : void GDALGeoPackageDataset::DetectSpatialRefSysColumns()
    1865             : {
    1866             :     // Detect definition_12_063 column
    1867             :     {
    1868        1269 :         sqlite3_stmt *hSQLStmt = nullptr;
    1869        1269 :         int rc = sqlite3_prepare_v2(
    1870             :             hDB, "SELECT definition_12_063 FROM gpkg_spatial_ref_sys ", -1,
    1871             :             &hSQLStmt, nullptr);
    1872        1269 :         if (rc == SQLITE_OK)
    1873             :         {
    1874          85 :             m_bHasDefinition12_063 = true;
    1875          85 :             sqlite3_finalize(hSQLStmt);
    1876             :         }
    1877             :     }
    1878             : 
    1879             :     // Detect epoch column
    1880        1269 :     if (m_bHasDefinition12_063)
    1881             :     {
    1882          85 :         sqlite3_stmt *hSQLStmt = nullptr;
    1883             :         int rc =
    1884          85 :             sqlite3_prepare_v2(hDB, "SELECT epoch FROM gpkg_spatial_ref_sys ",
    1885             :                                -1, &hSQLStmt, nullptr);
    1886          85 :         if (rc == SQLITE_OK)
    1887             :         {
    1888          76 :             m_bHasEpochColumn = true;
    1889          76 :             sqlite3_finalize(hSQLStmt);
    1890             :         }
    1891             :     }
    1892        1269 : }
    1893             : 
    1894             : /************************************************************************/
    1895             : /*                    FixupWrongRTreeTrigger()                          */
    1896             : /************************************************************************/
    1897             : 
    1898         257 : void GDALGeoPackageDataset::FixupWrongRTreeTrigger()
    1899             : {
    1900             :     auto oResult = SQLQuery(
    1901             :         hDB,
    1902             :         "SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND "
    1903         257 :         "NAME LIKE 'rtree_%_update3' AND sql LIKE '% AFTER UPDATE OF % ON %'");
    1904         257 :     if (oResult == nullptr)
    1905           0 :         return;
    1906         257 :     if (oResult->RowCount() > 0)
    1907             :     {
    1908           1 :         CPLDebug("GPKG", "Fixing incorrect trigger(s) related to RTree");
    1909             :     }
    1910         259 :     for (int i = 0; i < oResult->RowCount(); i++)
    1911             :     {
    1912           2 :         const char *pszName = oResult->GetValue(0, i);
    1913           2 :         const char *pszSQL = oResult->GetValue(1, i);
    1914           2 :         const char *pszPtr1 = strstr(pszSQL, " AFTER UPDATE OF ");
    1915           2 :         if (pszPtr1)
    1916             :         {
    1917           2 :             const char *pszPtr = pszPtr1 + strlen(" AFTER UPDATE OF ");
    1918             :             // Skipping over geometry column name
    1919           4 :             while (*pszPtr == ' ')
    1920           2 :                 pszPtr++;
    1921           2 :             if (pszPtr[0] == '"' || pszPtr[0] == '\'')
    1922             :             {
    1923           1 :                 char chStringDelim = pszPtr[0];
    1924           1 :                 pszPtr++;
    1925           9 :                 while (*pszPtr != '\0' && *pszPtr != chStringDelim)
    1926             :                 {
    1927           8 :                     if (*pszPtr == '\\' && pszPtr[1] == chStringDelim)
    1928           0 :                         pszPtr += 2;
    1929             :                     else
    1930           8 :                         pszPtr += 1;
    1931             :                 }
    1932           1 :                 if (*pszPtr == chStringDelim)
    1933           1 :                     pszPtr++;
    1934             :             }
    1935             :             else
    1936             :             {
    1937           1 :                 pszPtr++;
    1938           8 :                 while (*pszPtr != ' ')
    1939           7 :                     pszPtr++;
    1940             :             }
    1941           2 :             if (*pszPtr == ' ')
    1942             :             {
    1943           2 :                 SQLCommand(hDB,
    1944           4 :                            ("DROP TRIGGER \"" + SQLEscapeName(pszName) + "\"")
    1945             :                                .c_str());
    1946           4 :                 CPLString newSQL;
    1947           2 :                 newSQL.assign(pszSQL, pszPtr1 - pszSQL);
    1948           2 :                 newSQL += " AFTER UPDATE";
    1949           2 :                 newSQL += pszPtr;
    1950           2 :                 SQLCommand(hDB, newSQL);
    1951             :             }
    1952             :         }
    1953             :     }
    1954             : }
    1955             : 
    1956             : /************************************************************************/
    1957             : /*             FixupWrongMedataReferenceColumnNameUpdate()              */
    1958             : /************************************************************************/
    1959             : 
    1960         257 : void GDALGeoPackageDataset::FixupWrongMedataReferenceColumnNameUpdate()
    1961             : {
    1962             :     // Fix wrong trigger that was generated by GDAL < 2.4.0
    1963             :     // See https://github.com/qgis/QGIS/issues/42768
    1964             :     auto oResult = SQLQuery(
    1965             :         hDB, "SELECT sql FROM sqlite_master WHERE type = 'trigger' AND "
    1966             :              "NAME ='gpkg_metadata_reference_column_name_update' AND "
    1967         257 :              "sql LIKE '%column_nameIS%'");
    1968         257 :     if (oResult == nullptr)
    1969           0 :         return;
    1970         257 :     if (oResult->RowCount() == 1)
    1971             :     {
    1972           1 :         CPLDebug("GPKG", "Fixing incorrect trigger "
    1973             :                          "gpkg_metadata_reference_column_name_update");
    1974           1 :         const char *pszSQL = oResult->GetValue(0, 0);
    1975             :         std::string osNewSQL(
    1976           3 :             CPLString(pszSQL).replaceAll("column_nameIS", "column_name IS"));
    1977             : 
    1978           1 :         SQLCommand(hDB,
    1979             :                    "DROP TRIGGER gpkg_metadata_reference_column_name_update");
    1980           1 :         SQLCommand(hDB, osNewSQL.c_str());
    1981             :     }
    1982             : }
    1983             : 
    1984             : /************************************************************************/
    1985             : /*                  ClearCachedRelationships()                          */
    1986             : /************************************************************************/
    1987             : 
    1988          36 : void GDALGeoPackageDataset::ClearCachedRelationships()
    1989             : {
    1990          36 :     m_bHasPopulatedRelationships = false;
    1991          36 :     m_osMapRelationships.clear();
    1992          36 : }
    1993             : 
    1994             : /************************************************************************/
    1995             : /*                           LoadRelationships()                        */
    1996             : /************************************************************************/
    1997             : 
    1998          84 : void GDALGeoPackageDataset::LoadRelationships() const
    1999             : {
    2000          84 :     m_osMapRelationships.clear();
    2001             : 
    2002          84 :     std::vector<std::string> oExcludedTables;
    2003          84 :     if (HasGpkgextRelationsTable())
    2004             :     {
    2005          37 :         LoadRelationshipsUsingRelatedTablesExtension();
    2006             : 
    2007          89 :         for (const auto &oRelationship : m_osMapRelationships)
    2008             :         {
    2009             :             oExcludedTables.emplace_back(
    2010          52 :                 oRelationship.second->GetMappingTableName());
    2011             :         }
    2012             :     }
    2013             : 
    2014             :     // Also load relationships defined using foreign keys (i.e. one-to-many
    2015             :     // relationships). Here we must exclude any relationships defined from the
    2016             :     // related tables extension, we don't want them included twice.
    2017          84 :     LoadRelationshipsFromForeignKeys(oExcludedTables);
    2018          84 :     m_bHasPopulatedRelationships = true;
    2019          84 : }
    2020             : 
    2021             : /************************************************************************/
    2022             : /*         LoadRelationshipsUsingRelatedTablesExtension()               */
    2023             : /************************************************************************/
    2024             : 
    2025          37 : void GDALGeoPackageDataset::LoadRelationshipsUsingRelatedTablesExtension() const
    2026             : {
    2027          37 :     m_osMapRelationships.clear();
    2028             : 
    2029             :     auto oResultTable = SQLQuery(
    2030          37 :         hDB, "SELECT base_table_name, base_primary_column, "
    2031             :              "related_table_name, related_primary_column, relation_name, "
    2032          74 :              "mapping_table_name FROM gpkgext_relations");
    2033          37 :     if (oResultTable && oResultTable->RowCount() > 0)
    2034             :     {
    2035          86 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    2036             :         {
    2037          53 :             const char *pszBaseTableName = oResultTable->GetValue(0, i);
    2038          53 :             if (!pszBaseTableName)
    2039             :             {
    2040           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2041             :                          "Could not retrieve base_table_name from "
    2042             :                          "gpkgext_relations");
    2043           1 :                 continue;
    2044             :             }
    2045          53 :             const char *pszBasePrimaryColumn = oResultTable->GetValue(1, i);
    2046          53 :             if (!pszBasePrimaryColumn)
    2047             :             {
    2048           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2049             :                          "Could not retrieve base_primary_column from "
    2050             :                          "gpkgext_relations");
    2051           0 :                 continue;
    2052             :             }
    2053          53 :             const char *pszRelatedTableName = oResultTable->GetValue(2, i);
    2054          53 :             if (!pszRelatedTableName)
    2055             :             {
    2056           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2057             :                          "Could not retrieve related_table_name from "
    2058             :                          "gpkgext_relations");
    2059           0 :                 continue;
    2060             :             }
    2061          53 :             const char *pszRelatedPrimaryColumn = oResultTable->GetValue(3, i);
    2062          53 :             if (!pszRelatedPrimaryColumn)
    2063             :             {
    2064           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2065             :                          "Could not retrieve related_primary_column from "
    2066             :                          "gpkgext_relations");
    2067           0 :                 continue;
    2068             :             }
    2069          53 :             const char *pszRelationName = oResultTable->GetValue(4, i);
    2070          53 :             if (!pszRelationName)
    2071             :             {
    2072           0 :                 CPLError(
    2073             :                     CE_Warning, CPLE_AppDefined,
    2074             :                     "Could not retrieve relation_name from gpkgext_relations");
    2075           0 :                 continue;
    2076             :             }
    2077          53 :             const char *pszMappingTableName = oResultTable->GetValue(5, i);
    2078          53 :             if (!pszMappingTableName)
    2079             :             {
    2080           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2081             :                          "Could not retrieve mapping_table_name from "
    2082             :                          "gpkgext_relations");
    2083           0 :                 continue;
    2084             :             }
    2085             : 
    2086             :             // confirm that mapping table exists
    2087             :             char *pszSQL =
    2088          53 :                 sqlite3_mprintf("SELECT 1 FROM sqlite_master WHERE "
    2089             :                                 "name='%q' AND type IN ('table', 'view')",
    2090             :                                 pszMappingTableName);
    2091          53 :             const int nMappingTableCount = SQLGetInteger(hDB, pszSQL, nullptr);
    2092          53 :             sqlite3_free(pszSQL);
    2093             : 
    2094          55 :             if (nMappingTableCount < 1 &&
    2095           2 :                 !const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    2096           2 :                     pszMappingTableName))
    2097             :             {
    2098           1 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2099             :                          "Relationship mapping table %s does not exist",
    2100             :                          pszMappingTableName);
    2101           1 :                 continue;
    2102             :             }
    2103             : 
    2104             :             const std::string osRelationName = GenerateNameForRelationship(
    2105         104 :                 pszBaseTableName, pszRelatedTableName, pszRelationName);
    2106             : 
    2107         104 :             std::string osType{};
    2108             :             // defined requirement classes -- for these types the relation name
    2109             :             // will be specific string value from the related tables extension.
    2110             :             // In this case we need to construct a unique relationship name
    2111             :             // based on the related tables
    2112          52 :             if (EQUAL(pszRelationName, "media") ||
    2113          40 :                 EQUAL(pszRelationName, "simple_attributes") ||
    2114          40 :                 EQUAL(pszRelationName, "features") ||
    2115          18 :                 EQUAL(pszRelationName, "attributes") ||
    2116           2 :                 EQUAL(pszRelationName, "tiles"))
    2117             :             {
    2118          50 :                 osType = pszRelationName;
    2119             :             }
    2120             :             else
    2121             :             {
    2122             :                 // user defined types default to features
    2123           2 :                 osType = "features";
    2124             :             }
    2125             : 
    2126             :             auto poRelationship = std::make_unique<GDALRelationship>(
    2127             :                 osRelationName, pszBaseTableName, pszRelatedTableName,
    2128         104 :                 GRC_MANY_TO_MANY);
    2129             : 
    2130         104 :             poRelationship->SetLeftTableFields({pszBasePrimaryColumn});
    2131         104 :             poRelationship->SetRightTableFields({pszRelatedPrimaryColumn});
    2132         104 :             poRelationship->SetLeftMappingTableFields({"base_id"});
    2133         104 :             poRelationship->SetRightMappingTableFields({"related_id"});
    2134          52 :             poRelationship->SetMappingTableName(pszMappingTableName);
    2135          52 :             poRelationship->SetRelatedTableType(osType);
    2136             : 
    2137          52 :             m_osMapRelationships[osRelationName] = std::move(poRelationship);
    2138             :         }
    2139             :     }
    2140          37 : }
    2141             : 
    2142             : /************************************************************************/
    2143             : /*                GenerateNameForRelationship()                         */
    2144             : /************************************************************************/
    2145             : 
    2146          76 : std::string GDALGeoPackageDataset::GenerateNameForRelationship(
    2147             :     const char *pszBaseTableName, const char *pszRelatedTableName,
    2148             :     const char *pszType)
    2149             : {
    2150             :     // defined requirement classes -- for these types the relation name will be
    2151             :     // specific string value from the related tables extension. In this case we
    2152             :     // need to construct a unique relationship name based on the related tables
    2153          76 :     if (EQUAL(pszType, "media") || EQUAL(pszType, "simple_attributes") ||
    2154          53 :         EQUAL(pszType, "features") || EQUAL(pszType, "attributes") ||
    2155           8 :         EQUAL(pszType, "tiles"))
    2156             :     {
    2157         136 :         std::ostringstream stream;
    2158             :         stream << pszBaseTableName << '_' << pszRelatedTableName << '_'
    2159          68 :                << pszType;
    2160          68 :         return stream.str();
    2161             :     }
    2162             :     else
    2163             :     {
    2164             :         // user defined types default to features
    2165           8 :         return pszType;
    2166             :     }
    2167             : }
    2168             : 
    2169             : /************************************************************************/
    2170             : /*                       ValidateRelationship()                         */
    2171             : /************************************************************************/
    2172             : 
    2173          28 : bool GDALGeoPackageDataset::ValidateRelationship(
    2174             :     const GDALRelationship *poRelationship, std::string &failureReason)
    2175             : {
    2176             : 
    2177          28 :     if (poRelationship->GetCardinality() !=
    2178             :         GDALRelationshipCardinality::GRC_MANY_TO_MANY)
    2179             :     {
    2180           3 :         failureReason = "Only many to many relationships are supported";
    2181           3 :         return false;
    2182             :     }
    2183             : 
    2184          50 :     std::string osRelatedTableType = poRelationship->GetRelatedTableType();
    2185          65 :     if (!osRelatedTableType.empty() && osRelatedTableType != "features" &&
    2186          30 :         osRelatedTableType != "media" &&
    2187          20 :         osRelatedTableType != "simple_attributes" &&
    2188          55 :         osRelatedTableType != "attributes" && osRelatedTableType != "tiles")
    2189             :     {
    2190             :         failureReason =
    2191           4 :             ("Related table type " + osRelatedTableType +
    2192             :              " is not a valid value for the GeoPackage specification. "
    2193             :              "Valid values are: features, media, simple_attributes, "
    2194             :              "attributes, tiles.")
    2195           2 :                 .c_str();
    2196           2 :         return false;
    2197             :     }
    2198             : 
    2199          23 :     const std::string &osLeftTableName = poRelationship->GetLeftTableName();
    2200          23 :     OGRGeoPackageLayer *poLeftTable = cpl::down_cast<OGRGeoPackageLayer *>(
    2201          23 :         GetLayerByName(osLeftTableName.c_str()));
    2202          23 :     if (!poLeftTable)
    2203             :     {
    2204           4 :         failureReason = ("Left table " + osLeftTableName +
    2205             :                          " is not an existing layer in the dataset")
    2206           2 :                             .c_str();
    2207           2 :         return false;
    2208             :     }
    2209          21 :     const std::string &osRightTableName = poRelationship->GetRightTableName();
    2210          21 :     OGRGeoPackageLayer *poRightTable = cpl::down_cast<OGRGeoPackageLayer *>(
    2211          21 :         GetLayerByName(osRightTableName.c_str()));
    2212          21 :     if (!poRightTable)
    2213             :     {
    2214           4 :         failureReason = ("Right table " + osRightTableName +
    2215             :                          " is not an existing layer in the dataset")
    2216           2 :                             .c_str();
    2217           2 :         return false;
    2218             :     }
    2219             : 
    2220          19 :     const auto &aosLeftTableFields = poRelationship->GetLeftTableFields();
    2221          19 :     if (aosLeftTableFields.empty())
    2222             :     {
    2223           1 :         failureReason = "No left table fields were specified";
    2224           1 :         return false;
    2225             :     }
    2226          18 :     else if (aosLeftTableFields.size() > 1)
    2227             :     {
    2228             :         failureReason = "Only a single left table field is permitted for the "
    2229           1 :                         "GeoPackage specification";
    2230           1 :         return false;
    2231             :     }
    2232             :     else
    2233             :     {
    2234             :         // validate left field exists
    2235          34 :         if (poLeftTable->GetLayerDefn()->GetFieldIndex(
    2236          37 :                 aosLeftTableFields[0].c_str()) < 0 &&
    2237           3 :             !EQUAL(poLeftTable->GetFIDColumn(), aosLeftTableFields[0].c_str()))
    2238             :         {
    2239           2 :             failureReason = ("Left table field " + aosLeftTableFields[0] +
    2240           2 :                              " does not exist in " + osLeftTableName)
    2241           1 :                                 .c_str();
    2242           1 :             return false;
    2243             :         }
    2244             :     }
    2245             : 
    2246          16 :     const auto &aosRightTableFields = poRelationship->GetRightTableFields();
    2247          16 :     if (aosRightTableFields.empty())
    2248             :     {
    2249           1 :         failureReason = "No right table fields were specified";
    2250           1 :         return false;
    2251             :     }
    2252          15 :     else if (aosRightTableFields.size() > 1)
    2253             :     {
    2254             :         failureReason = "Only a single right table field is permitted for the "
    2255           1 :                         "GeoPackage specification";
    2256           1 :         return false;
    2257             :     }
    2258             :     else
    2259             :     {
    2260             :         // validate right field exists
    2261          28 :         if (poRightTable->GetLayerDefn()->GetFieldIndex(
    2262          32 :                 aosRightTableFields[0].c_str()) < 0 &&
    2263           4 :             !EQUAL(poRightTable->GetFIDColumn(),
    2264             :                    aosRightTableFields[0].c_str()))
    2265             :         {
    2266           4 :             failureReason = ("Right table field " + aosRightTableFields[0] +
    2267           4 :                              " does not exist in " + osRightTableName)
    2268           2 :                                 .c_str();
    2269           2 :             return false;
    2270             :         }
    2271             :     }
    2272             : 
    2273          12 :     return true;
    2274             : }
    2275             : 
    2276             : /************************************************************************/
    2277             : /*                         InitRaster()                                 */
    2278             : /************************************************************************/
    2279             : 
    2280         358 : bool GDALGeoPackageDataset::InitRaster(
    2281             :     GDALGeoPackageDataset *poParentDS, const char *pszTableName, double dfMinX,
    2282             :     double dfMinY, double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2283             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2284             :     const char *pszContentsMaxY, char **papszOpenOptionsIn,
    2285             :     const SQLResult &oResult, int nIdxInResult)
    2286             : {
    2287         358 :     m_osRasterTable = pszTableName;
    2288         358 :     m_dfTMSMinX = dfMinX;
    2289         358 :     m_dfTMSMaxY = dfMaxY;
    2290             : 
    2291             :     // Despite prior checking, the type might be Binary and
    2292             :     // SQLResultGetValue() not working properly on it
    2293         358 :     int nZoomLevel = atoi(oResult.GetValue(0, nIdxInResult));
    2294         358 :     if (nZoomLevel < 0 || nZoomLevel > 65536)
    2295             :     {
    2296           0 :         return false;
    2297             :     }
    2298         358 :     double dfPixelXSize = CPLAtof(oResult.GetValue(1, nIdxInResult));
    2299         358 :     double dfPixelYSize = CPLAtof(oResult.GetValue(2, nIdxInResult));
    2300         358 :     if (dfPixelXSize <= 0 || dfPixelYSize <= 0)
    2301             :     {
    2302           0 :         return false;
    2303             :     }
    2304         358 :     int nTileWidth = atoi(oResult.GetValue(3, nIdxInResult));
    2305         358 :     int nTileHeight = atoi(oResult.GetValue(4, nIdxInResult));
    2306         358 :     if (nTileWidth <= 0 || nTileWidth > 65536 || nTileHeight <= 0 ||
    2307             :         nTileHeight > 65536)
    2308             :     {
    2309           0 :         return false;
    2310             :     }
    2311             :     int nTileMatrixWidth = static_cast<int>(
    2312         716 :         std::min(static_cast<GIntBig>(INT_MAX),
    2313         358 :                  CPLAtoGIntBig(oResult.GetValue(5, nIdxInResult))));
    2314             :     int nTileMatrixHeight = static_cast<int>(
    2315         716 :         std::min(static_cast<GIntBig>(INT_MAX),
    2316         358 :                  CPLAtoGIntBig(oResult.GetValue(6, nIdxInResult))));
    2317         358 :     if (nTileMatrixWidth <= 0 || nTileMatrixHeight <= 0)
    2318             :     {
    2319           0 :         return false;
    2320             :     }
    2321             : 
    2322             :     /* Use content bounds in priority over tile_matrix_set bounds */
    2323         358 :     double dfGDALMinX = dfMinX;
    2324         358 :     double dfGDALMinY = dfMinY;
    2325         358 :     double dfGDALMaxX = dfMaxX;
    2326         358 :     double dfGDALMaxY = dfMaxY;
    2327             :     pszContentsMinX =
    2328         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINX", pszContentsMinX);
    2329             :     pszContentsMinY =
    2330         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MINY", pszContentsMinY);
    2331             :     pszContentsMaxX =
    2332         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXX", pszContentsMaxX);
    2333             :     pszContentsMaxY =
    2334         358 :         CSLFetchNameValueDef(papszOpenOptionsIn, "MAXY", pszContentsMaxY);
    2335         358 :     if (pszContentsMinX != nullptr && pszContentsMinY != nullptr &&
    2336         358 :         pszContentsMaxX != nullptr && pszContentsMaxY != nullptr)
    2337             :     {
    2338         715 :         if (CPLAtof(pszContentsMinX) < CPLAtof(pszContentsMaxX) &&
    2339         357 :             CPLAtof(pszContentsMinY) < CPLAtof(pszContentsMaxY))
    2340             :         {
    2341         357 :             dfGDALMinX = CPLAtof(pszContentsMinX);
    2342         357 :             dfGDALMinY = CPLAtof(pszContentsMinY);
    2343         357 :             dfGDALMaxX = CPLAtof(pszContentsMaxX);
    2344         357 :             dfGDALMaxY = CPLAtof(pszContentsMaxY);
    2345             :         }
    2346             :         else
    2347             :         {
    2348           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    2349             :                      "Illegal min_x/min_y/max_x/max_y values for %s in open "
    2350             :                      "options and/or gpkg_contents. Using bounds of "
    2351             :                      "gpkg_tile_matrix_set instead",
    2352             :                      pszTableName);
    2353             :         }
    2354             :     }
    2355         358 :     if (dfGDALMinX >= dfGDALMaxX || dfGDALMinY >= dfGDALMaxY)
    2356             :     {
    2357           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2358             :                  "Illegal min_x/min_y/max_x/max_y values for %s", pszTableName);
    2359           0 :         return false;
    2360             :     }
    2361             : 
    2362         358 :     int nBandCount = 0;
    2363             :     const char *pszBAND_COUNT =
    2364         358 :         CSLFetchNameValue(papszOpenOptionsIn, "BAND_COUNT");
    2365         358 :     if (poParentDS)
    2366             :     {
    2367          86 :         nBandCount = poParentDS->GetRasterCount();
    2368             :     }
    2369         272 :     else if (m_eDT != GDT_Byte)
    2370             :     {
    2371          65 :         if (pszBAND_COUNT != nullptr && !EQUAL(pszBAND_COUNT, "AUTO") &&
    2372           0 :             !EQUAL(pszBAND_COUNT, "1"))
    2373             :         {
    2374           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2375             :                      "BAND_COUNT ignored for non-Byte data");
    2376             :         }
    2377          65 :         nBandCount = 1;
    2378             :     }
    2379             :     else
    2380             :     {
    2381         207 :         if (pszBAND_COUNT != nullptr && !EQUAL(pszBAND_COUNT, "AUTO"))
    2382             :         {
    2383          69 :             nBandCount = atoi(pszBAND_COUNT);
    2384          69 :             if (nBandCount == 1)
    2385           5 :                 GetMetadata("IMAGE_STRUCTURE");
    2386             :         }
    2387             :         else
    2388             :         {
    2389         138 :             GetMetadata("IMAGE_STRUCTURE");
    2390         138 :             nBandCount = m_nBandCountFromMetadata;
    2391         138 :             if (nBandCount == 1)
    2392          39 :                 m_eTF = GPKG_TF_PNG;
    2393             :         }
    2394         207 :         if (nBandCount == 1 && !m_osTFFromMetadata.empty())
    2395             :         {
    2396           2 :             m_eTF = GDALGPKGMBTilesGetTileFormat(m_osTFFromMetadata.c_str());
    2397             :         }
    2398         207 :         if (nBandCount <= 0 || nBandCount > 4)
    2399          85 :             nBandCount = 4;
    2400             :     }
    2401             : 
    2402         358 :     return InitRaster(poParentDS, pszTableName, nZoomLevel, nBandCount, dfMinX,
    2403             :                       dfMaxY, dfPixelXSize, dfPixelYSize, nTileWidth,
    2404             :                       nTileHeight, nTileMatrixWidth, nTileMatrixHeight,
    2405         358 :                       dfGDALMinX, dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    2406             : }
    2407             : 
    2408             : /************************************************************************/
    2409             : /*                      ComputeTileAndPixelShifts()                     */
    2410             : /************************************************************************/
    2411             : 
    2412         784 : bool GDALGeoPackageDataset::ComputeTileAndPixelShifts()
    2413             : {
    2414             :     int nTileWidth, nTileHeight;
    2415         784 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2416             : 
    2417             :     // Compute shift between GDAL origin and TileMatrixSet origin
    2418         784 :     const double dfShiftXPixels = (m_gt[0] - m_dfTMSMinX) / m_gt[1];
    2419         784 :     if (!(dfShiftXPixels / nTileWidth >= INT_MIN &&
    2420         781 :           dfShiftXPixels / nTileWidth < INT_MAX))
    2421             :     {
    2422           3 :         return false;
    2423             :     }
    2424         781 :     const int64_t nShiftXPixels =
    2425         781 :         static_cast<int64_t>(floor(0.5 + dfShiftXPixels));
    2426         781 :     m_nShiftXTiles = static_cast<int>(nShiftXPixels / nTileWidth);
    2427         781 :     if (nShiftXPixels < 0 && (nShiftXPixels % nTileWidth) != 0)
    2428          11 :         m_nShiftXTiles--;
    2429         781 :     m_nShiftXPixelsMod =
    2430         781 :         (static_cast<int>(nShiftXPixels % nTileWidth) + nTileWidth) %
    2431             :         nTileWidth;
    2432             : 
    2433         781 :     const double dfShiftYPixels = (m_gt[3] - m_dfTMSMaxY) / m_gt[5];
    2434         781 :     if (!(dfShiftYPixels / nTileHeight >= INT_MIN &&
    2435         781 :           dfShiftYPixels / nTileHeight < INT_MAX))
    2436             :     {
    2437           1 :         return false;
    2438             :     }
    2439         780 :     const int64_t nShiftYPixels =
    2440         780 :         static_cast<int64_t>(floor(0.5 + dfShiftYPixels));
    2441         780 :     m_nShiftYTiles = static_cast<int>(nShiftYPixels / nTileHeight);
    2442         780 :     if (nShiftYPixels < 0 && (nShiftYPixels % nTileHeight) != 0)
    2443          11 :         m_nShiftYTiles--;
    2444         780 :     m_nShiftYPixelsMod =
    2445         780 :         (static_cast<int>(nShiftYPixels % nTileHeight) + nTileHeight) %
    2446             :         nTileHeight;
    2447         780 :     return true;
    2448             : }
    2449             : 
    2450             : /************************************************************************/
    2451             : /*                            AllocCachedTiles()                        */
    2452             : /************************************************************************/
    2453             : 
    2454         780 : bool GDALGeoPackageDataset::AllocCachedTiles()
    2455             : {
    2456             :     int nTileWidth, nTileHeight;
    2457         780 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    2458             : 
    2459             :     // We currently need 4 caches because of
    2460             :     // GDALGPKGMBTilesLikePseudoDataset::ReadTile(int nRow, int nCol)
    2461         780 :     const int nCacheCount = 4;
    2462             :     /*
    2463             :             (m_nShiftXPixelsMod != 0 || m_nShiftYPixelsMod != 0) ? 4 :
    2464             :             (GetUpdate() && m_eDT == GDT_Byte) ? 2 : 1;
    2465             :     */
    2466         780 :     m_pabyCachedTiles = static_cast<GByte *>(VSI_MALLOC3_VERBOSE(
    2467             :         cpl::fits_on<int>(nCacheCount * (m_eDT == GDT_Byte ? 4 : 1) *
    2468             :                           m_nDTSize),
    2469             :         nTileWidth, nTileHeight));
    2470         780 :     if (m_pabyCachedTiles == nullptr)
    2471             :     {
    2472           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Too big tiles: %d x %d",
    2473             :                  nTileWidth, nTileHeight);
    2474           0 :         return false;
    2475             :     }
    2476             : 
    2477         780 :     return true;
    2478             : }
    2479             : 
    2480             : /************************************************************************/
    2481             : /*                         InitRaster()                                 */
    2482             : /************************************************************************/
    2483             : 
    2484         597 : bool GDALGeoPackageDataset::InitRaster(
    2485             :     GDALGeoPackageDataset *poParentDS, const char *pszTableName, int nZoomLevel,
    2486             :     int nBandCount, double dfTMSMinX, double dfTMSMaxY, double dfPixelXSize,
    2487             :     double dfPixelYSize, int nTileWidth, int nTileHeight, int nTileMatrixWidth,
    2488             :     int nTileMatrixHeight, double dfGDALMinX, double dfGDALMinY,
    2489             :     double dfGDALMaxX, double dfGDALMaxY)
    2490             : {
    2491         597 :     m_osRasterTable = pszTableName;
    2492         597 :     m_dfTMSMinX = dfTMSMinX;
    2493         597 :     m_dfTMSMaxY = dfTMSMaxY;
    2494         597 :     m_nZoomLevel = nZoomLevel;
    2495         597 :     m_nTileMatrixWidth = nTileMatrixWidth;
    2496         597 :     m_nTileMatrixHeight = nTileMatrixHeight;
    2497             : 
    2498         597 :     m_bGeoTransformValid = true;
    2499         597 :     m_gt[0] = dfGDALMinX;
    2500         597 :     m_gt[1] = dfPixelXSize;
    2501         597 :     m_gt[3] = dfGDALMaxY;
    2502         597 :     m_gt[5] = -dfPixelYSize;
    2503         597 :     double dfRasterXSize = 0.5 + (dfGDALMaxX - dfGDALMinX) / dfPixelXSize;
    2504         597 :     double dfRasterYSize = 0.5 + (dfGDALMaxY - dfGDALMinY) / dfPixelYSize;
    2505         597 :     if (dfRasterXSize > INT_MAX || dfRasterYSize > INT_MAX)
    2506             :     {
    2507           0 :         CPLError(CE_Failure, CPLE_NotSupported, "Too big raster: %f x %f",
    2508             :                  dfRasterXSize, dfRasterYSize);
    2509           0 :         return false;
    2510             :     }
    2511         597 :     nRasterXSize = std::max(1, static_cast<int>(dfRasterXSize));
    2512         597 :     nRasterYSize = std::max(1, static_cast<int>(dfRasterYSize));
    2513             : 
    2514         597 :     if (poParentDS)
    2515             :     {
    2516         325 :         m_poParentDS = poParentDS;
    2517         325 :         eAccess = poParentDS->eAccess;
    2518         325 :         hDB = poParentDS->hDB;
    2519         325 :         m_eTF = poParentDS->m_eTF;
    2520         325 :         m_eDT = poParentDS->m_eDT;
    2521         325 :         m_nDTSize = poParentDS->m_nDTSize;
    2522         325 :         m_dfScale = poParentDS->m_dfScale;
    2523         325 :         m_dfOffset = poParentDS->m_dfOffset;
    2524         325 :         m_dfPrecision = poParentDS->m_dfPrecision;
    2525         325 :         m_usGPKGNull = poParentDS->m_usGPKGNull;
    2526         325 :         m_nQuality = poParentDS->m_nQuality;
    2527         325 :         m_nZLevel = poParentDS->m_nZLevel;
    2528         325 :         m_bDither = poParentDS->m_bDither;
    2529             :         /*m_nSRID = poParentDS->m_nSRID;*/
    2530         325 :         m_osWHERE = poParentDS->m_osWHERE;
    2531         325 :         SetDescription(CPLSPrintf("%s - zoom_level=%d",
    2532         325 :                                   poParentDS->GetDescription(), m_nZoomLevel));
    2533             :     }
    2534             : 
    2535        2091 :     for (int i = 1; i <= nBandCount; i++)
    2536             :     {
    2537             :         auto poNewBand = std::make_unique<GDALGeoPackageRasterBand>(
    2538        1494 :             this, nTileWidth, nTileHeight);
    2539        1494 :         if (poParentDS)
    2540             :         {
    2541         761 :             int bHasNoData = FALSE;
    2542             :             double dfNoDataValue =
    2543         761 :                 poParentDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    2544         761 :             if (bHasNoData)
    2545          24 :                 poNewBand->SetNoDataValueInternal(dfNoDataValue);
    2546             :         }
    2547             : 
    2548        1494 :         if (nBandCount == 1 && m_poCTFromMetadata)
    2549             :         {
    2550           3 :             poNewBand->AssignColorTable(m_poCTFromMetadata.get());
    2551             :         }
    2552        1494 :         if (!m_osNodataValueFromMetadata.empty())
    2553             :         {
    2554           8 :             poNewBand->SetNoDataValueInternal(
    2555             :                 CPLAtof(m_osNodataValueFromMetadata.c_str()));
    2556             :         }
    2557             : 
    2558        1494 :         SetBand(i, std::move(poNewBand));
    2559             :     }
    2560             : 
    2561         597 :     if (!ComputeTileAndPixelShifts())
    2562             :     {
    2563           3 :         CPLError(CE_Failure, CPLE_AppDefined,
    2564             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    2565           3 :         return false;
    2566             :     }
    2567             : 
    2568         594 :     GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    2569         594 :     GDALPamDataset::SetMetadataItem("ZOOM_LEVEL",
    2570             :                                     CPLSPrintf("%d", m_nZoomLevel));
    2571             : 
    2572         594 :     return AllocCachedTiles();
    2573             : }
    2574             : 
    2575             : /************************************************************************/
    2576             : /*                 GDALGPKGMBTilesGetTileFormat()                       */
    2577             : /************************************************************************/
    2578             : 
    2579          80 : GPKGTileFormat GDALGPKGMBTilesGetTileFormat(const char *pszTF)
    2580             : {
    2581          80 :     GPKGTileFormat eTF = GPKG_TF_PNG_JPEG;
    2582          80 :     if (pszTF)
    2583             :     {
    2584          80 :         if (EQUAL(pszTF, "PNG_JPEG") || EQUAL(pszTF, "AUTO"))
    2585           1 :             eTF = GPKG_TF_PNG_JPEG;
    2586          79 :         else if (EQUAL(pszTF, "PNG"))
    2587          46 :             eTF = GPKG_TF_PNG;
    2588          33 :         else if (EQUAL(pszTF, "PNG8"))
    2589           6 :             eTF = GPKG_TF_PNG8;
    2590          27 :         else if (EQUAL(pszTF, "JPEG"))
    2591          14 :             eTF = GPKG_TF_JPEG;
    2592          13 :         else if (EQUAL(pszTF, "WEBP"))
    2593          13 :             eTF = GPKG_TF_WEBP;
    2594             :         else
    2595             :         {
    2596           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2597             :                      "Unsuppoted value for TILE_FORMAT: %s", pszTF);
    2598             :         }
    2599             :     }
    2600          80 :     return eTF;
    2601             : }
    2602             : 
    2603          28 : const char *GDALMBTilesGetTileFormatName(GPKGTileFormat eTF)
    2604             : {
    2605          28 :     switch (eTF)
    2606             :     {
    2607          26 :         case GPKG_TF_PNG:
    2608             :         case GPKG_TF_PNG8:
    2609          26 :             return "png";
    2610           1 :         case GPKG_TF_JPEG:
    2611           1 :             return "jpg";
    2612           1 :         case GPKG_TF_WEBP:
    2613           1 :             return "webp";
    2614           0 :         default:
    2615           0 :             break;
    2616             :     }
    2617           0 :     CPLError(CE_Failure, CPLE_NotSupported,
    2618             :              "Unsuppoted value for TILE_FORMAT: %d", static_cast<int>(eTF));
    2619           0 :     return nullptr;
    2620             : }
    2621             : 
    2622             : /************************************************************************/
    2623             : /*                         OpenRaster()                                 */
    2624             : /************************************************************************/
    2625             : 
    2626         274 : bool GDALGeoPackageDataset::OpenRaster(
    2627             :     const char *pszTableName, const char *pszIdentifier,
    2628             :     const char *pszDescription, int nSRSId, double dfMinX, double dfMinY,
    2629             :     double dfMaxX, double dfMaxY, const char *pszContentsMinX,
    2630             :     const char *pszContentsMinY, const char *pszContentsMaxX,
    2631             :     const char *pszContentsMaxY, bool bIsTiles, char **papszOpenOptionsIn)
    2632             : {
    2633         274 :     if (dfMinX >= dfMaxX || dfMinY >= dfMaxY)
    2634           0 :         return false;
    2635             : 
    2636             :     // Config option just for debug, and for example force set to NaN
    2637             :     // which is not supported
    2638         548 :     CPLString osDataNull = CPLGetConfigOption("GPKG_NODATA", "");
    2639         548 :     CPLString osUom;
    2640         548 :     CPLString osFieldName;
    2641         548 :     CPLString osGridCellEncoding;
    2642         274 :     if (!bIsTiles)
    2643             :     {
    2644          65 :         char *pszSQL = sqlite3_mprintf(
    2645             :             "SELECT datatype, scale, offset, data_null, precision FROM "
    2646             :             "gpkg_2d_gridded_coverage_ancillary "
    2647             :             "WHERE tile_matrix_set_name = '%q' "
    2648             :             "AND datatype IN ('integer', 'float')"
    2649             :             "AND (scale > 0 OR scale IS NULL)",
    2650             :             pszTableName);
    2651          65 :         auto oResult = SQLQuery(hDB, pszSQL);
    2652          65 :         sqlite3_free(pszSQL);
    2653          65 :         if (!oResult || oResult->RowCount() == 0)
    2654             :         {
    2655           0 :             return false;
    2656             :         }
    2657          65 :         const char *pszDataType = oResult->GetValue(0, 0);
    2658          65 :         const char *pszScale = oResult->GetValue(1, 0);
    2659          65 :         const char *pszOffset = oResult->GetValue(2, 0);
    2660          65 :         const char *pszDataNull = oResult->GetValue(3, 0);
    2661          65 :         const char *pszPrecision = oResult->GetValue(4, 0);
    2662          65 :         if (pszDataNull)
    2663          23 :             osDataNull = pszDataNull;
    2664          65 :         if (EQUAL(pszDataType, "float"))
    2665             :         {
    2666           6 :             SetDataType(GDT_Float32);
    2667           6 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    2668             :         }
    2669             :         else
    2670             :         {
    2671          59 :             SetDataType(GDT_Float32);
    2672          59 :             m_eTF = GPKG_TF_PNG_16BIT;
    2673          59 :             const double dfScale = pszScale ? CPLAtof(pszScale) : 1.0;
    2674          59 :             const double dfOffset = pszOffset ? CPLAtof(pszOffset) : 0.0;
    2675          59 :             if (dfScale == 1.0)
    2676             :             {
    2677          59 :                 if (dfOffset == 0.0)
    2678             :                 {
    2679          24 :                     SetDataType(GDT_UInt16);
    2680             :                 }
    2681          35 :                 else if (dfOffset == -32768.0)
    2682             :                 {
    2683          35 :                     SetDataType(GDT_Int16);
    2684             :                 }
    2685             :                 // coverity[tainted_data]
    2686           0 :                 else if (dfOffset == -32767.0 && !osDataNull.empty() &&
    2687           0 :                          CPLAtof(osDataNull) == 65535.0)
    2688             :                 // Given that we will map the nodata value to -32768
    2689             :                 {
    2690           0 :                     SetDataType(GDT_Int16);
    2691             :                 }
    2692             :             }
    2693             : 
    2694             :             // Check that the tile offset and scales are compatible of a
    2695             :             // final integer result.
    2696          59 :             if (m_eDT != GDT_Float32)
    2697             :             {
    2698             :                 // coverity[tainted_data]
    2699          59 :                 if (dfScale == 1.0 && dfOffset == -32768.0 &&
    2700         118 :                     !osDataNull.empty() && CPLAtof(osDataNull) == 65535.0)
    2701             :                 {
    2702             :                     // Given that we will map the nodata value to -32768
    2703           9 :                     pszSQL = sqlite3_mprintf(
    2704             :                         "SELECT 1 FROM "
    2705             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2706             :                         "tpudt_name = '%q' "
    2707             :                         "AND NOT ((offset = 0.0 or offset = 1.0) "
    2708             :                         "AND scale = 1.0) "
    2709             :                         "LIMIT 1",
    2710             :                         pszTableName);
    2711             :                 }
    2712             :                 else
    2713             :                 {
    2714          50 :                     pszSQL = sqlite3_mprintf(
    2715             :                         "SELECT 1 FROM "
    2716             :                         "gpkg_2d_gridded_tile_ancillary WHERE "
    2717             :                         "tpudt_name = '%q' "
    2718             :                         "AND NOT (offset = 0.0 AND scale = 1.0) LIMIT 1",
    2719             :                         pszTableName);
    2720             :                 }
    2721          59 :                 sqlite3_stmt *hSQLStmt = nullptr;
    2722             :                 int rc =
    2723          59 :                     SQLPrepareWithError(hDB, pszSQL, -1, &hSQLStmt, nullptr);
    2724             : 
    2725          59 :                 if (rc == SQLITE_OK)
    2726             :                 {
    2727          59 :                     if (sqlite3_step(hSQLStmt) == SQLITE_ROW)
    2728             :                     {
    2729           8 :                         SetDataType(GDT_Float32);
    2730             :                     }
    2731          59 :                     sqlite3_finalize(hSQLStmt);
    2732             :                 }
    2733          59 :                 sqlite3_free(pszSQL);
    2734             :             }
    2735             : 
    2736          59 :             SetGlobalOffsetScale(dfOffset, dfScale);
    2737             :         }
    2738          65 :         if (pszPrecision)
    2739          65 :             m_dfPrecision = CPLAtof(pszPrecision);
    2740             : 
    2741             :         // Request those columns in a separate query, so as to keep
    2742             :         // compatibility with pre OGC 17-066r1 databases
    2743             :         pszSQL =
    2744          65 :             sqlite3_mprintf("SELECT uom, field_name, grid_cell_encoding FROM "
    2745             :                             "gpkg_2d_gridded_coverage_ancillary "
    2746             :                             "WHERE tile_matrix_set_name = '%q'",
    2747             :                             pszTableName);
    2748          65 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    2749          65 :         oResult = SQLQuery(hDB, pszSQL);
    2750          65 :         CPLPopErrorHandler();
    2751          65 :         sqlite3_free(pszSQL);
    2752          65 :         if (oResult && oResult->RowCount() == 1)
    2753             :         {
    2754          64 :             const char *pszUom = oResult->GetValue(0, 0);
    2755          64 :             if (pszUom)
    2756           2 :                 osUom = pszUom;
    2757          64 :             const char *pszFieldName = oResult->GetValue(1, 0);
    2758          64 :             if (pszFieldName)
    2759          64 :                 osFieldName = pszFieldName;
    2760          64 :             const char *pszGridCellEncoding = oResult->GetValue(2, 0);
    2761          64 :             if (pszGridCellEncoding)
    2762          64 :                 osGridCellEncoding = pszGridCellEncoding;
    2763             :         }
    2764             :     }
    2765             : 
    2766         274 :     m_bRecordInsertedInGPKGContent = true;
    2767         274 :     m_nSRID = nSRSId;
    2768             : 
    2769         547 :     if (auto poSRS = GetSpatialRef(nSRSId))
    2770             :     {
    2771         273 :         m_oSRS = *(poSRS.get());
    2772             :     }
    2773             : 
    2774             :     /* Various sanity checks added in the SELECT */
    2775         274 :     char *pszQuotedTableName = sqlite3_mprintf("'%q'", pszTableName);
    2776         548 :     CPLString osQuotedTableName(pszQuotedTableName);
    2777         274 :     sqlite3_free(pszQuotedTableName);
    2778         274 :     char *pszSQL = sqlite3_mprintf(
    2779             :         "SELECT zoom_level, pixel_x_size, pixel_y_size, tile_width, "
    2780             :         "tile_height, matrix_width, matrix_height "
    2781             :         "FROM gpkg_tile_matrix tm "
    2782             :         "WHERE table_name = %s "
    2783             :         // INT_MAX would be the theoretical maximum value to avoid
    2784             :         // overflows, but that's already a insane value.
    2785             :         "AND zoom_level >= 0 AND zoom_level <= 65536 "
    2786             :         "AND pixel_x_size > 0 AND pixel_y_size > 0 "
    2787             :         "AND tile_width >= 1 AND tile_width <= 65536 "
    2788             :         "AND tile_height >= 1 AND tile_height <= 65536 "
    2789             :         "AND matrix_width >= 1 AND matrix_height >= 1",
    2790             :         osQuotedTableName.c_str());
    2791         548 :     CPLString osSQL(pszSQL);
    2792             :     const char *pszZoomLevel =
    2793         274 :         CSLFetchNameValue(papszOpenOptionsIn, "ZOOM_LEVEL");
    2794         274 :     if (pszZoomLevel)
    2795             :     {
    2796           5 :         if (GetUpdate())
    2797           1 :             osSQL += CPLSPrintf(" AND zoom_level <= %d", atoi(pszZoomLevel));
    2798             :         else
    2799             :         {
    2800             :             osSQL += CPLSPrintf(
    2801             :                 " AND (zoom_level = %d OR (zoom_level < %d AND EXISTS(SELECT 1 "
    2802             :                 "FROM %s WHERE zoom_level = tm.zoom_level LIMIT 1)))",
    2803             :                 atoi(pszZoomLevel), atoi(pszZoomLevel),
    2804           4 :                 osQuotedTableName.c_str());
    2805             :         }
    2806             :     }
    2807             :     // In read-only mode, only lists non empty zoom levels
    2808         269 :     else if (!GetUpdate())
    2809             :     {
    2810             :         osSQL += CPLSPrintf(" AND EXISTS(SELECT 1 FROM %s WHERE zoom_level = "
    2811             :                             "tm.zoom_level LIMIT 1)",
    2812         215 :                             osQuotedTableName.c_str());
    2813             :     }
    2814             :     else  // if( pszZoomLevel == nullptr )
    2815             :     {
    2816             :         osSQL +=
    2817             :             CPLSPrintf(" AND zoom_level <= (SELECT MAX(zoom_level) FROM %s)",
    2818          54 :                        osQuotedTableName.c_str());
    2819             :     }
    2820         274 :     osSQL += " ORDER BY zoom_level DESC";
    2821             :     // To avoid denial of service.
    2822         274 :     osSQL += " LIMIT 100";
    2823             : 
    2824         548 :     auto oResult = SQLQuery(hDB, osSQL.c_str());
    2825         274 :     if (!oResult || oResult->RowCount() == 0)
    2826             :     {
    2827         114 :         if (oResult && oResult->RowCount() == 0 && pszContentsMinX != nullptr &&
    2828         114 :             pszContentsMinY != nullptr && pszContentsMaxX != nullptr &&
    2829             :             pszContentsMaxY != nullptr)
    2830             :         {
    2831          56 :             osSQL = pszSQL;
    2832          56 :             osSQL += " ORDER BY zoom_level DESC";
    2833          56 :             if (!GetUpdate())
    2834          30 :                 osSQL += " LIMIT 1";
    2835          56 :             oResult = SQLQuery(hDB, osSQL.c_str());
    2836             :         }
    2837          57 :         if (!oResult || oResult->RowCount() == 0)
    2838             :         {
    2839           1 :             if (oResult && pszZoomLevel != nullptr)
    2840             :             {
    2841           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2842             :                          "ZOOM_LEVEL is probably not valid w.r.t tile "
    2843             :                          "table content");
    2844             :             }
    2845           1 :             sqlite3_free(pszSQL);
    2846           1 :             return false;
    2847             :         }
    2848             :     }
    2849         273 :     sqlite3_free(pszSQL);
    2850             : 
    2851             :     // If USE_TILE_EXTENT=YES, then query the tile table to find which tiles
    2852             :     // actually exist.
    2853             : 
    2854             :     // CAUTION: Do not move those variables inside inner scope !
    2855         546 :     CPLString osContentsMinX, osContentsMinY, osContentsMaxX, osContentsMaxY;
    2856             : 
    2857         273 :     if (CPLTestBool(
    2858             :             CSLFetchNameValueDef(papszOpenOptionsIn, "USE_TILE_EXTENT", "NO")))
    2859             :     {
    2860          13 :         pszSQL = sqlite3_mprintf(
    2861             :             "SELECT MIN(tile_column), MIN(tile_row), MAX(tile_column), "
    2862             :             "MAX(tile_row) FROM \"%w\" WHERE zoom_level = %d",
    2863             :             pszTableName, atoi(oResult->GetValue(0, 0)));
    2864          13 :         auto oResult2 = SQLQuery(hDB, pszSQL);
    2865          13 :         sqlite3_free(pszSQL);
    2866          26 :         if (!oResult2 || oResult2->RowCount() == 0 ||
    2867             :             // Can happen if table is empty
    2868          38 :             oResult2->GetValue(0, 0) == nullptr ||
    2869             :             // Can happen if table has no NOT NULL constraint on tile_row
    2870             :             // and that all tile_row are NULL
    2871          12 :             oResult2->GetValue(1, 0) == nullptr)
    2872             :         {
    2873           1 :             return false;
    2874             :         }
    2875          12 :         const double dfPixelXSize = CPLAtof(oResult->GetValue(1, 0));
    2876          12 :         const double dfPixelYSize = CPLAtof(oResult->GetValue(2, 0));
    2877          12 :         const int nTileWidth = atoi(oResult->GetValue(3, 0));
    2878          12 :         const int nTileHeight = atoi(oResult->GetValue(4, 0));
    2879             :         osContentsMinX =
    2880          24 :             CPLSPrintf("%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2881          12 :                                              atoi(oResult2->GetValue(0, 0)));
    2882             :         osContentsMaxY =
    2883          24 :             CPLSPrintf("%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2884          12 :                                              atoi(oResult2->GetValue(1, 0)));
    2885             :         osContentsMaxX = CPLSPrintf(
    2886          24 :             "%.17g", dfMinX + dfPixelXSize * nTileWidth *
    2887          12 :                                   (1 + atoi(oResult2->GetValue(2, 0))));
    2888             :         osContentsMinY = CPLSPrintf(
    2889          24 :             "%.17g", dfMaxY - dfPixelYSize * nTileHeight *
    2890          12 :                                   (1 + atoi(oResult2->GetValue(3, 0))));
    2891          12 :         pszContentsMinX = osContentsMinX.c_str();
    2892          12 :         pszContentsMinY = osContentsMinY.c_str();
    2893          12 :         pszContentsMaxX = osContentsMaxX.c_str();
    2894          12 :         pszContentsMaxY = osContentsMaxY.c_str();
    2895             :     }
    2896             : 
    2897         272 :     if (!InitRaster(nullptr, pszTableName, dfMinX, dfMinY, dfMaxX, dfMaxY,
    2898             :                     pszContentsMinX, pszContentsMinY, pszContentsMaxX,
    2899         272 :                     pszContentsMaxY, papszOpenOptionsIn, *oResult, 0))
    2900             :     {
    2901           3 :         return false;
    2902             :     }
    2903             : 
    2904         269 :     auto poBand = cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(1));
    2905         269 :     if (!osDataNull.empty())
    2906             :     {
    2907          23 :         double dfGPKGNoDataValue = CPLAtof(osDataNull);
    2908          23 :         if (m_eTF == GPKG_TF_PNG_16BIT)
    2909             :         {
    2910          21 :             if (dfGPKGNoDataValue < 0 || dfGPKGNoDataValue > 65535 ||
    2911          21 :                 static_cast<int>(dfGPKGNoDataValue) != dfGPKGNoDataValue)
    2912             :             {
    2913           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    2914             :                          "data_null = %.17g is invalid for integer data_type",
    2915             :                          dfGPKGNoDataValue);
    2916             :             }
    2917             :             else
    2918             :             {
    2919          21 :                 m_usGPKGNull = static_cast<GUInt16>(dfGPKGNoDataValue);
    2920          21 :                 if (m_eDT == GDT_Int16 && m_usGPKGNull > 32767)
    2921           9 :                     dfGPKGNoDataValue = -32768.0;
    2922          12 :                 else if (m_eDT == GDT_Float32)
    2923             :                 {
    2924             :                     // Pick a value that is unlikely to be hit with offset &
    2925             :                     // scale
    2926           4 :                     dfGPKGNoDataValue = -std::numeric_limits<float>::max();
    2927             :                 }
    2928          21 :                 poBand->SetNoDataValueInternal(dfGPKGNoDataValue);
    2929             :             }
    2930             :         }
    2931             :         else
    2932             :         {
    2933           2 :             poBand->SetNoDataValueInternal(
    2934           2 :                 static_cast<float>(dfGPKGNoDataValue));
    2935             :         }
    2936             :     }
    2937         269 :     if (!osUom.empty())
    2938             :     {
    2939           2 :         poBand->SetUnitTypeInternal(osUom);
    2940             :     }
    2941         269 :     if (!osFieldName.empty())
    2942             :     {
    2943          64 :         GetRasterBand(1)->GDALRasterBand::SetDescription(osFieldName);
    2944             :     }
    2945         269 :     if (!osGridCellEncoding.empty())
    2946             :     {
    2947          64 :         if (osGridCellEncoding == "grid-value-is-center")
    2948             :         {
    2949          15 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2950             :                                             GDALMD_AOP_POINT);
    2951             :         }
    2952          49 :         else if (osGridCellEncoding == "grid-value-is-area")
    2953             :         {
    2954          45 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2955             :                                             GDALMD_AOP_AREA);
    2956             :         }
    2957             :         else
    2958             :         {
    2959           4 :             GDALPamDataset::SetMetadataItem(GDALMD_AREA_OR_POINT,
    2960             :                                             GDALMD_AOP_POINT);
    2961           4 :             GetRasterBand(1)->GDALRasterBand::SetMetadataItem(
    2962             :                 "GRID_CELL_ENCODING", osGridCellEncoding);
    2963             :         }
    2964             :     }
    2965             : 
    2966         269 :     CheckUnknownExtensions(true);
    2967             : 
    2968             :     // Do this after CheckUnknownExtensions() so that m_eTF is set to
    2969             :     // GPKG_TF_WEBP if the table already registers the gpkg_webp extension
    2970         269 :     const char *pszTF = CSLFetchNameValue(papszOpenOptionsIn, "TILE_FORMAT");
    2971         269 :     if (pszTF)
    2972             :     {
    2973           4 :         if (!GetUpdate())
    2974             :         {
    2975           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2976             :                      "TILE_FORMAT open option ignored in read-only mode");
    2977             :         }
    2978           4 :         else if (m_eTF == GPKG_TF_PNG_16BIT ||
    2979           4 :                  m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    2980             :         {
    2981           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    2982             :                      "TILE_FORMAT open option ignored on gridded coverages");
    2983             :         }
    2984             :         else
    2985             :         {
    2986           4 :             GPKGTileFormat eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    2987           4 :             if (eTF == GPKG_TF_WEBP && m_eTF != eTF)
    2988             :             {
    2989           1 :                 if (!RegisterWebPExtension())
    2990           0 :                     return false;
    2991             :             }
    2992           4 :             m_eTF = eTF;
    2993             :         }
    2994             :     }
    2995             : 
    2996         269 :     ParseCompressionOptions(papszOpenOptionsIn);
    2997             : 
    2998         269 :     m_osWHERE = CSLFetchNameValueDef(papszOpenOptionsIn, "WHERE", "");
    2999             : 
    3000             :     // Set metadata
    3001         269 :     if (pszIdentifier && pszIdentifier[0])
    3002         269 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", pszIdentifier);
    3003         269 :     if (pszDescription && pszDescription[0])
    3004          21 :         GDALPamDataset::SetMetadataItem("DESCRIPTION", pszDescription);
    3005             : 
    3006             :     // Add overviews
    3007         354 :     for (int i = 1; i < oResult->RowCount(); i++)
    3008             :     {
    3009          86 :         auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3010          86 :         poOvrDS->ShareLockWithParentDataset(this);
    3011         172 :         if (!poOvrDS->InitRaster(this, pszTableName, dfMinX, dfMinY, dfMaxX,
    3012             :                                  dfMaxY, pszContentsMinX, pszContentsMinY,
    3013             :                                  pszContentsMaxX, pszContentsMaxY,
    3014          86 :                                  papszOpenOptionsIn, *oResult, i))
    3015             :         {
    3016           0 :             break;
    3017             :         }
    3018             : 
    3019             :         int nTileWidth, nTileHeight;
    3020          86 :         poOvrDS->GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3021             :         const bool bStop =
    3022          87 :             (eAccess == GA_ReadOnly && poOvrDS->GetRasterXSize() < nTileWidth &&
    3023           1 :              poOvrDS->GetRasterYSize() < nTileHeight);
    3024             : 
    3025          86 :         m_apoOverviewDS.push_back(std::move(poOvrDS));
    3026             : 
    3027          86 :         if (bStop)
    3028             :         {
    3029           1 :             break;
    3030             :         }
    3031             :     }
    3032             : 
    3033         269 :     return true;
    3034             : }
    3035             : 
    3036             : /************************************************************************/
    3037             : /*                           GetSpatialRef()                            */
    3038             : /************************************************************************/
    3039             : 
    3040          17 : const OGRSpatialReference *GDALGeoPackageDataset::GetSpatialRef() const
    3041             : {
    3042          17 :     if (GetLayerCount())
    3043           1 :         return GDALDataset::GetSpatialRef();
    3044          16 :     return GetSpatialRefRasterOnly();
    3045             : }
    3046             : 
    3047             : /************************************************************************/
    3048             : /*                      GetSpatialRefRasterOnly()                       */
    3049             : /************************************************************************/
    3050             : 
    3051             : const OGRSpatialReference *
    3052          17 : GDALGeoPackageDataset::GetSpatialRefRasterOnly() const
    3053             : 
    3054             : {
    3055          17 :     return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
    3056             : }
    3057             : 
    3058             : /************************************************************************/
    3059             : /*                           SetSpatialRef()                            */
    3060             : /************************************************************************/
    3061             : 
    3062         152 : CPLErr GDALGeoPackageDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    3063             : {
    3064         152 :     if (nBands == 0)
    3065             :     {
    3066           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3067             :                  "SetProjection() not supported on a dataset with 0 band");
    3068           1 :         return CE_Failure;
    3069             :     }
    3070         151 :     if (eAccess != GA_Update)
    3071             :     {
    3072           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3073             :                  "SetProjection() not supported on read-only dataset");
    3074           1 :         return CE_Failure;
    3075             :     }
    3076             : 
    3077         150 :     const int nSRID = GetSrsId(poSRS);
    3078         300 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3079         150 :     if (poTS && nSRID != poTS->nEPSGCode)
    3080             :     {
    3081           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3082             :                  "Projection should be EPSG:%d for %s tiling scheme",
    3083           1 :                  poTS->nEPSGCode, m_osTilingScheme.c_str());
    3084           1 :         return CE_Failure;
    3085             :     }
    3086             : 
    3087         149 :     m_nSRID = nSRID;
    3088         149 :     m_oSRS.Clear();
    3089         149 :     if (poSRS)
    3090         148 :         m_oSRS = *poSRS;
    3091             : 
    3092         149 :     if (m_bRecordInsertedInGPKGContent)
    3093             :     {
    3094         121 :         char *pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET srs_id = %d "
    3095             :                                        "WHERE lower(table_name) = lower('%q')",
    3096             :                                        m_nSRID, m_osRasterTable.c_str());
    3097         121 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3098         121 :         sqlite3_free(pszSQL);
    3099         121 :         if (eErr != OGRERR_NONE)
    3100           0 :             return CE_Failure;
    3101             : 
    3102         121 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_tile_matrix_set SET srs_id = %d "
    3103             :                                  "WHERE lower(table_name) = lower('%q')",
    3104             :                                  m_nSRID, m_osRasterTable.c_str());
    3105         121 :         eErr = SQLCommand(hDB, pszSQL);
    3106         121 :         sqlite3_free(pszSQL);
    3107         121 :         if (eErr != OGRERR_NONE)
    3108           0 :             return CE_Failure;
    3109             :     }
    3110             : 
    3111         149 :     return CE_None;
    3112             : }
    3113             : 
    3114             : /************************************************************************/
    3115             : /*                          GetGeoTransform()                           */
    3116             : /************************************************************************/
    3117             : 
    3118          33 : CPLErr GDALGeoPackageDataset::GetGeoTransform(GDALGeoTransform &gt) const
    3119             : {
    3120          33 :     gt = m_gt;
    3121          33 :     if (!m_bGeoTransformValid)
    3122           2 :         return CE_Failure;
    3123             :     else
    3124          31 :         return CE_None;
    3125             : }
    3126             : 
    3127             : /************************************************************************/
    3128             : /*                          SetGeoTransform()                           */
    3129             : /************************************************************************/
    3130             : 
    3131         192 : CPLErr GDALGeoPackageDataset::SetGeoTransform(const GDALGeoTransform &gt)
    3132             : {
    3133         192 :     if (nBands == 0)
    3134             :     {
    3135           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3136             :                  "SetGeoTransform() not supported on a dataset with 0 band");
    3137           2 :         return CE_Failure;
    3138             :     }
    3139         190 :     if (eAccess != GA_Update)
    3140             :     {
    3141           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3142             :                  "SetGeoTransform() not supported on read-only dataset");
    3143           1 :         return CE_Failure;
    3144             :     }
    3145         189 :     if (m_bGeoTransformValid)
    3146             :     {
    3147           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3148             :                  "Cannot modify geotransform once set");
    3149           1 :         return CE_Failure;
    3150             :     }
    3151         188 :     if (gt[2] != 0.0 || gt[4] != 0 || gt[5] > 0.0)
    3152             :     {
    3153           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3154             :                  "Only north-up non rotated geotransform supported");
    3155           0 :         return CE_Failure;
    3156             :     }
    3157             : 
    3158         188 :     if (m_nZoomLevel < 0)
    3159             :     {
    3160         187 :         const auto poTS = GetTilingScheme(m_osTilingScheme);
    3161         187 :         if (poTS)
    3162             :         {
    3163          20 :             double dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3164          20 :             double dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3165         199 :             for (m_nZoomLevel = 0; m_nZoomLevel < MAX_ZOOM_LEVEL;
    3166         179 :                  m_nZoomLevel++)
    3167             :             {
    3168         198 :                 double dfExpectedPixelXSize =
    3169         198 :                     dfPixelXSizeZoomLevel0 / (1 << m_nZoomLevel);
    3170         198 :                 double dfExpectedPixelYSize =
    3171         198 :                     dfPixelYSizeZoomLevel0 / (1 << m_nZoomLevel);
    3172         198 :                 if (fabs(gt[1] - dfExpectedPixelXSize) <
    3173         217 :                         1e-8 * dfExpectedPixelXSize &&
    3174          19 :                     fabs(fabs(gt[5]) - dfExpectedPixelYSize) <
    3175          19 :                         1e-8 * dfExpectedPixelYSize)
    3176             :                 {
    3177          19 :                     break;
    3178             :                 }
    3179             :             }
    3180          20 :             if (m_nZoomLevel == MAX_ZOOM_LEVEL)
    3181             :             {
    3182           1 :                 m_nZoomLevel = -1;
    3183           1 :                 CPLError(
    3184             :                     CE_Failure, CPLE_NotSupported,
    3185             :                     "Could not find an appropriate zoom level of %s tiling "
    3186             :                     "scheme that matches raster pixel size",
    3187             :                     m_osTilingScheme.c_str());
    3188           1 :                 return CE_Failure;
    3189             :             }
    3190             :         }
    3191             :     }
    3192             : 
    3193         187 :     m_gt = gt;
    3194         187 :     m_bGeoTransformValid = true;
    3195             : 
    3196         187 :     return FinalizeRasterRegistration();
    3197             : }
    3198             : 
    3199             : /************************************************************************/
    3200             : /*                      FinalizeRasterRegistration()                    */
    3201             : /************************************************************************/
    3202             : 
    3203         187 : CPLErr GDALGeoPackageDataset::FinalizeRasterRegistration()
    3204             : {
    3205             :     OGRErr eErr;
    3206             : 
    3207         187 :     m_dfTMSMinX = m_gt[0];
    3208         187 :     m_dfTMSMaxY = m_gt[3];
    3209             : 
    3210             :     int nTileWidth, nTileHeight;
    3211         187 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3212             : 
    3213         187 :     if (m_nZoomLevel < 0)
    3214             :     {
    3215         167 :         m_nZoomLevel = 0;
    3216         241 :         while ((nRasterXSize >> m_nZoomLevel) > nTileWidth ||
    3217         167 :                (nRasterYSize >> m_nZoomLevel) > nTileHeight)
    3218          74 :             m_nZoomLevel++;
    3219             :     }
    3220             : 
    3221         187 :     double dfPixelXSizeZoomLevel0 = m_gt[1] * (1 << m_nZoomLevel);
    3222         187 :     double dfPixelYSizeZoomLevel0 = fabs(m_gt[5]) * (1 << m_nZoomLevel);
    3223             :     int nTileXCountZoomLevel0 =
    3224         187 :         std::max(1, DIV_ROUND_UP((nRasterXSize >> m_nZoomLevel), nTileWidth));
    3225             :     int nTileYCountZoomLevel0 =
    3226         187 :         std::max(1, DIV_ROUND_UP((nRasterYSize >> m_nZoomLevel), nTileHeight));
    3227             : 
    3228         374 :     const auto poTS = GetTilingScheme(m_osTilingScheme);
    3229         187 :     if (poTS)
    3230             :     {
    3231          20 :         CPLAssert(m_nZoomLevel >= 0);
    3232          20 :         m_dfTMSMinX = poTS->dfMinX;
    3233          20 :         m_dfTMSMaxY = poTS->dfMaxY;
    3234          20 :         dfPixelXSizeZoomLevel0 = poTS->dfPixelXSizeZoomLevel0;
    3235          20 :         dfPixelYSizeZoomLevel0 = poTS->dfPixelYSizeZoomLevel0;
    3236          20 :         nTileXCountZoomLevel0 = poTS->nTileXCountZoomLevel0;
    3237          20 :         nTileYCountZoomLevel0 = poTS->nTileYCountZoomLevel0;
    3238             :     }
    3239         187 :     m_nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << m_nZoomLevel);
    3240         187 :     m_nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << m_nZoomLevel);
    3241             : 
    3242         187 :     if (!ComputeTileAndPixelShifts())
    3243             :     {
    3244           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    3245             :                  "Overflow occurred in ComputeTileAndPixelShifts()");
    3246           1 :         return CE_Failure;
    3247             :     }
    3248             : 
    3249         186 :     if (!AllocCachedTiles())
    3250             :     {
    3251           0 :         return CE_Failure;
    3252             :     }
    3253             : 
    3254         186 :     double dfGDALMinX = m_gt[0];
    3255         186 :     double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3256         186 :     double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3257         186 :     double dfGDALMaxY = m_gt[3];
    3258             : 
    3259         186 :     if (SoftStartTransaction() != OGRERR_NONE)
    3260           0 :         return CE_Failure;
    3261             : 
    3262             :     const char *pszCurrentDate =
    3263         186 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3264             :     CPLString osInsertGpkgContentsFormatting(
    3265             :         "INSERT INTO gpkg_contents "
    3266             :         "(table_name,data_type,identifier,description,min_x,min_y,max_x,max_y,"
    3267             :         "last_change,srs_id) VALUES "
    3268         372 :         "('%q','%q','%q','%q',%.17g,%.17g,%.17g,%.17g,");
    3269         186 :     osInsertGpkgContentsFormatting += (pszCurrentDate) ? "'%q'" : "%s";
    3270         186 :     osInsertGpkgContentsFormatting += ",%d)";
    3271         372 :     char *pszSQL = sqlite3_mprintf(
    3272             :         osInsertGpkgContentsFormatting.c_str(), m_osRasterTable.c_str(),
    3273         186 :         (m_eDT == GDT_Byte) ? "tiles" : "2d-gridded-coverage",
    3274             :         m_osIdentifier.c_str(), m_osDescription.c_str(), dfGDALMinX, dfGDALMinY,
    3275             :         dfGDALMaxX, dfGDALMaxY,
    3276             :         pszCurrentDate ? pszCurrentDate
    3277             :                        : "strftime('%Y-%m-%dT%H:%M:%fZ','now')",
    3278             :         m_nSRID);
    3279             : 
    3280         186 :     eErr = SQLCommand(hDB, pszSQL);
    3281         186 :     sqlite3_free(pszSQL);
    3282         186 :     if (eErr != OGRERR_NONE)
    3283             :     {
    3284           8 :         SoftRollbackTransaction();
    3285           8 :         return CE_Failure;
    3286             :     }
    3287             : 
    3288         178 :     double dfTMSMaxX = m_dfTMSMinX + nTileXCountZoomLevel0 * nTileWidth *
    3289             :                                          dfPixelXSizeZoomLevel0;
    3290         178 :     double dfTMSMinY = m_dfTMSMaxY - nTileYCountZoomLevel0 * nTileHeight *
    3291             :                                          dfPixelYSizeZoomLevel0;
    3292             : 
    3293             :     pszSQL =
    3294         178 :         sqlite3_mprintf("INSERT INTO gpkg_tile_matrix_set "
    3295             :                         "(table_name,srs_id,min_x,min_y,max_x,max_y) VALUES "
    3296             :                         "('%q',%d,%.17g,%.17g,%.17g,%.17g)",
    3297             :                         m_osRasterTable.c_str(), m_nSRID, m_dfTMSMinX,
    3298             :                         dfTMSMinY, dfTMSMaxX, m_dfTMSMaxY);
    3299         178 :     eErr = SQLCommand(hDB, pszSQL);
    3300         178 :     sqlite3_free(pszSQL);
    3301         178 :     if (eErr != OGRERR_NONE)
    3302             :     {
    3303           0 :         SoftRollbackTransaction();
    3304           0 :         return CE_Failure;
    3305             :     }
    3306             : 
    3307         178 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3308             : 
    3309         591 :     for (int i = 0; i <= m_nZoomLevel; i++)
    3310             :     {
    3311         413 :         double dfPixelXSizeZoomLevel = 0.0;
    3312         413 :         double dfPixelYSizeZoomLevel = 0.0;
    3313         413 :         int nTileMatrixWidth = 0;
    3314         413 :         int nTileMatrixHeight = 0;
    3315         413 :         if (EQUAL(m_osTilingScheme, "CUSTOM"))
    3316             :         {
    3317         232 :             dfPixelXSizeZoomLevel = m_gt[1] * (1 << (m_nZoomLevel - i));
    3318         232 :             dfPixelYSizeZoomLevel = fabs(m_gt[5]) * (1 << (m_nZoomLevel - i));
    3319             :         }
    3320             :         else
    3321             :         {
    3322         181 :             dfPixelXSizeZoomLevel = dfPixelXSizeZoomLevel0 / (1 << i);
    3323         181 :             dfPixelYSizeZoomLevel = dfPixelYSizeZoomLevel0 / (1 << i);
    3324             :         }
    3325         413 :         nTileMatrixWidth = nTileXCountZoomLevel0 * (1 << i);
    3326         413 :         nTileMatrixHeight = nTileYCountZoomLevel0 * (1 << i);
    3327             : 
    3328         413 :         pszSQL = sqlite3_mprintf(
    3329             :             "INSERT INTO gpkg_tile_matrix "
    3330             :             "(table_name,zoom_level,matrix_width,matrix_height,tile_width,tile_"
    3331             :             "height,pixel_x_size,pixel_y_size) VALUES "
    3332             :             "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3333             :             m_osRasterTable.c_str(), i, nTileMatrixWidth, nTileMatrixHeight,
    3334             :             nTileWidth, nTileHeight, dfPixelXSizeZoomLevel,
    3335             :             dfPixelYSizeZoomLevel);
    3336         413 :         eErr = SQLCommand(hDB, pszSQL);
    3337         413 :         sqlite3_free(pszSQL);
    3338         413 :         if (eErr != OGRERR_NONE)
    3339             :         {
    3340           0 :             SoftRollbackTransaction();
    3341           0 :             return CE_Failure;
    3342             :         }
    3343             : 
    3344         413 :         if (i < m_nZoomLevel)
    3345             :         {
    3346         470 :             auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3347         235 :             poOvrDS->ShareLockWithParentDataset(this);
    3348         235 :             poOvrDS->InitRaster(this, m_osRasterTable, i, nBands, m_dfTMSMinX,
    3349             :                                 m_dfTMSMaxY, dfPixelXSizeZoomLevel,
    3350             :                                 dfPixelYSizeZoomLevel, nTileWidth, nTileHeight,
    3351             :                                 nTileMatrixWidth, nTileMatrixHeight, dfGDALMinX,
    3352             :                                 dfGDALMinY, dfGDALMaxX, dfGDALMaxY);
    3353             : 
    3354         235 :             m_apoOverviewDS[m_nZoomLevel - 1 - i] = std::move(poOvrDS);
    3355             :         }
    3356             :     }
    3357             : 
    3358         178 :     if (!m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.empty())
    3359             :     {
    3360          40 :         eErr = SQLCommand(
    3361             :             hDB, m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.c_str());
    3362          40 :         m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary.clear();
    3363          40 :         if (eErr != OGRERR_NONE)
    3364             :         {
    3365           0 :             SoftRollbackTransaction();
    3366           0 :             return CE_Failure;
    3367             :         }
    3368             :     }
    3369             : 
    3370         178 :     SoftCommitTransaction();
    3371             : 
    3372         178 :     m_apoOverviewDS.resize(m_nZoomLevel);
    3373         178 :     m_bRecordInsertedInGPKGContent = true;
    3374             : 
    3375         178 :     return CE_None;
    3376             : }
    3377             : 
    3378             : /************************************************************************/
    3379             : /*                             FlushCache()                             */
    3380             : /************************************************************************/
    3381             : 
    3382        2735 : CPLErr GDALGeoPackageDataset::FlushCache(bool bAtClosing)
    3383             : {
    3384        2735 :     if (m_bInFlushCache)
    3385           0 :         return CE_None;
    3386             : 
    3387        2735 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3388             :     {
    3389        2732 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3390             :     }
    3391             : 
    3392        2735 :     if (m_bRemoveOGREmptyTable)
    3393             :     {
    3394         725 :         m_bRemoveOGREmptyTable = false;
    3395         725 :         RemoveOGREmptyTable();
    3396             :     }
    3397             : 
    3398        2735 :     CPLErr eErr = IFlushCacheWithErrCode(bAtClosing);
    3399             : 
    3400        2735 :     FlushMetadata();
    3401             : 
    3402        2735 :     if (eAccess == GA_Update || !m_bMetadataDirty)
    3403             :     {
    3404             :         // Needed again as above IFlushCacheWithErrCode()
    3405             :         // may have call GDALGeoPackageRasterBand::InvalidateStatistics()
    3406             :         // which modifies metadata
    3407        2735 :         SetPamFlags(GetPamFlags() & ~GPF_DIRTY);
    3408             :     }
    3409             : 
    3410        2735 :     return eErr;
    3411             : }
    3412             : 
    3413        4970 : CPLErr GDALGeoPackageDataset::IFlushCacheWithErrCode(bool bAtClosing)
    3414             : 
    3415             : {
    3416        4970 :     if (m_bInFlushCache)
    3417        2168 :         return CE_None;
    3418        2802 :     m_bInFlushCache = true;
    3419        2802 :     if (hDB && eAccess == GA_ReadOnly && bAtClosing)
    3420             :     {
    3421             :         // Clean-up metadata that will go to PAM by removing items that
    3422             :         // are reconstructed.
    3423        2030 :         CPLStringList aosMD;
    3424        1638 :         for (CSLConstList papszIter = GetMetadata(); papszIter && *papszIter;
    3425             :              ++papszIter)
    3426             :         {
    3427         623 :             char *pszKey = nullptr;
    3428         623 :             CPLParseNameValue(*papszIter, &pszKey);
    3429        1246 :             if (pszKey &&
    3430         623 :                 (EQUAL(pszKey, "AREA_OR_POINT") ||
    3431         477 :                  EQUAL(pszKey, "IDENTIFIER") || EQUAL(pszKey, "DESCRIPTION") ||
    3432         256 :                  EQUAL(pszKey, "ZOOM_LEVEL") ||
    3433         653 :                  STARTS_WITH(pszKey, "GPKG_METADATA_ITEM_")))
    3434             :             {
    3435             :                 // remove it
    3436             :             }
    3437             :             else
    3438             :             {
    3439          30 :                 aosMD.AddString(*papszIter);
    3440             :             }
    3441         623 :             CPLFree(pszKey);
    3442             :         }
    3443        1015 :         oMDMD.SetMetadata(aosMD.List());
    3444        1015 :         oMDMD.SetMetadata(nullptr, "IMAGE_STRUCTURE");
    3445             : 
    3446        2030 :         GDALPamDataset::FlushCache(bAtClosing);
    3447             :     }
    3448             :     else
    3449             :     {
    3450             :         // Short circuit GDALPamDataset to avoid serialization to .aux.xml
    3451        1787 :         GDALDataset::FlushCache(bAtClosing);
    3452             :     }
    3453             : 
    3454        6859 :     for (auto &poLayer : m_apoLayers)
    3455             :     {
    3456        4057 :         poLayer->RunDeferredCreationIfNecessary();
    3457        4057 :         poLayer->CreateSpatialIndexIfNecessary();
    3458             :     }
    3459             : 
    3460             :     // Update raster table last_change column in gpkg_contents if needed
    3461        2802 :     if (m_bHasModifiedTiles)
    3462             :     {
    3463         540 :         for (int i = 1; i <= nBands; ++i)
    3464             :         {
    3465             :             auto poBand =
    3466         359 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    3467         359 :             if (!poBand->HaveStatsMetadataBeenSetInThisSession())
    3468             :             {
    3469         346 :                 poBand->InvalidateStatistics();
    3470         346 :                 if (psPam && psPam->pszPamFilename)
    3471         346 :                     VSIUnlink(psPam->pszPamFilename);
    3472             :             }
    3473             :         }
    3474             : 
    3475         181 :         UpdateGpkgContentsLastChange(m_osRasterTable);
    3476             : 
    3477         181 :         m_bHasModifiedTiles = false;
    3478             :     }
    3479             : 
    3480        2802 :     CPLErr eErr = FlushTiles();
    3481             : 
    3482        2802 :     m_bInFlushCache = false;
    3483        2802 :     return eErr;
    3484             : }
    3485             : 
    3486             : /************************************************************************/
    3487             : /*                       GetCurrentDateEscapedSQL()                      */
    3488             : /************************************************************************/
    3489             : 
    3490        2051 : std::string GDALGeoPackageDataset::GetCurrentDateEscapedSQL()
    3491             : {
    3492             :     const char *pszCurrentDate =
    3493        2051 :         CPLGetConfigOption("OGR_CURRENT_DATE", nullptr);
    3494        2051 :     if (pszCurrentDate)
    3495          10 :         return '\'' + SQLEscapeLiteral(pszCurrentDate) + '\'';
    3496        2046 :     return "strftime('%Y-%m-%dT%H:%M:%fZ','now')";
    3497             : }
    3498             : 
    3499             : /************************************************************************/
    3500             : /*                    UpdateGpkgContentsLastChange()                    */
    3501             : /************************************************************************/
    3502             : 
    3503             : OGRErr
    3504         895 : GDALGeoPackageDataset::UpdateGpkgContentsLastChange(const char *pszTableName)
    3505             : {
    3506             :     char *pszSQL =
    3507         895 :         sqlite3_mprintf("UPDATE gpkg_contents SET "
    3508             :                         "last_change = %s "
    3509             :                         "WHERE lower(table_name) = lower('%q')",
    3510        1790 :                         GetCurrentDateEscapedSQL().c_str(), pszTableName);
    3511         895 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    3512         895 :     sqlite3_free(pszSQL);
    3513         895 :     return eErr;
    3514             : }
    3515             : 
    3516             : /************************************************************************/
    3517             : /*                          IBuildOverviews()                           */
    3518             : /************************************************************************/
    3519             : 
    3520          20 : CPLErr GDALGeoPackageDataset::IBuildOverviews(
    3521             :     const char *pszResampling, int nOverviews, const int *panOverviewList,
    3522             :     int nBandsIn, const int * /*panBandList*/, GDALProgressFunc pfnProgress,
    3523             :     void *pProgressData, CSLConstList papszOptions)
    3524             : {
    3525          20 :     if (GetAccess() != GA_Update)
    3526             :     {
    3527           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3528             :                  "Overview building not supported on a database opened in "
    3529             :                  "read-only mode");
    3530           1 :         return CE_Failure;
    3531             :     }
    3532          19 :     if (m_poParentDS != nullptr)
    3533             :     {
    3534           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    3535             :                  "Overview building not supported on overview dataset");
    3536           1 :         return CE_Failure;
    3537             :     }
    3538             : 
    3539          18 :     if (nOverviews == 0)
    3540             :     {
    3541           5 :         for (auto &poOvrDS : m_apoOverviewDS)
    3542           3 :             poOvrDS->FlushCache(false);
    3543             : 
    3544           2 :         SoftStartTransaction();
    3545             : 
    3546           2 :         if (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT)
    3547             :         {
    3548           1 :             char *pszSQL = sqlite3_mprintf(
    3549             :                 "DELETE FROM gpkg_2d_gridded_tile_ancillary WHERE id IN "
    3550             :                 "(SELECT y.id FROM \"%w\" x "
    3551             :                 "JOIN gpkg_2d_gridded_tile_ancillary y "
    3552             :                 "ON x.id = y.tpudt_id AND y.tpudt_name = '%q' AND "
    3553             :                 "x.zoom_level < %d)",
    3554             :                 m_osRasterTable.c_str(), m_osRasterTable.c_str(), m_nZoomLevel);
    3555           1 :             OGRErr eErr = SQLCommand(hDB, pszSQL);
    3556           1 :             sqlite3_free(pszSQL);
    3557           1 :             if (eErr != OGRERR_NONE)
    3558             :             {
    3559           0 :                 SoftRollbackTransaction();
    3560           0 :                 return CE_Failure;
    3561             :             }
    3562             :         }
    3563             : 
    3564             :         char *pszSQL =
    3565           2 :             sqlite3_mprintf("DELETE FROM \"%w\" WHERE zoom_level < %d",
    3566             :                             m_osRasterTable.c_str(), m_nZoomLevel);
    3567           2 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
    3568           2 :         sqlite3_free(pszSQL);
    3569           2 :         if (eErr != OGRERR_NONE)
    3570             :         {
    3571           0 :             SoftRollbackTransaction();
    3572           0 :             return CE_Failure;
    3573             :         }
    3574             : 
    3575           2 :         SoftCommitTransaction();
    3576             : 
    3577           2 :         return CE_None;
    3578             :     }
    3579             : 
    3580          16 :     if (nBandsIn != nBands)
    3581             :     {
    3582           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3583             :                  "Generation of overviews in GPKG only"
    3584             :                  "supported when operating on all bands.");
    3585           0 :         return CE_Failure;
    3586             :     }
    3587             : 
    3588          16 :     if (m_apoOverviewDS.empty())
    3589             :     {
    3590           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3591             :                  "Image too small to support overviews");
    3592           0 :         return CE_Failure;
    3593             :     }
    3594             : 
    3595          16 :     FlushCache(false);
    3596          60 :     for (int i = 0; i < nOverviews; i++)
    3597             :     {
    3598          47 :         if (panOverviewList[i] < 2)
    3599             :         {
    3600           1 :             CPLError(CE_Failure, CPLE_IllegalArg,
    3601             :                      "Overview factor must be >= 2");
    3602           1 :             return CE_Failure;
    3603             :         }
    3604             : 
    3605          46 :         bool bFound = false;
    3606          46 :         int jCandidate = -1;
    3607          46 :         int nMaxOvFactor = 0;
    3608         196 :         for (int j = 0; j < static_cast<int>(m_apoOverviewDS.size()); j++)
    3609             :         {
    3610         190 :             const auto poODS = m_apoOverviewDS[j].get();
    3611             :             const int nOvFactor =
    3612         190 :                 static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3613             : 
    3614         190 :             nMaxOvFactor = nOvFactor;
    3615             : 
    3616         190 :             if (nOvFactor == panOverviewList[i])
    3617             :             {
    3618          40 :                 bFound = true;
    3619          40 :                 break;
    3620             :             }
    3621             : 
    3622         150 :             if (jCandidate < 0 && nOvFactor > panOverviewList[i])
    3623           1 :                 jCandidate = j;
    3624             :         }
    3625             : 
    3626          46 :         if (!bFound)
    3627             :         {
    3628             :             /* Mostly for debug */
    3629           6 :             if (!CPLTestBool(CPLGetConfigOption(
    3630             :                     "ALLOW_GPKG_ZOOM_OTHER_EXTENSION", "YES")))
    3631             :             {
    3632           2 :                 CPLString osOvrList;
    3633           4 :                 for (const auto &poODS : m_apoOverviewDS)
    3634             :                 {
    3635             :                     const int nOvFactor =
    3636           2 :                         static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3637             : 
    3638           2 :                     if (!osOvrList.empty())
    3639           0 :                         osOvrList += ' ';
    3640           2 :                     osOvrList += CPLSPrintf("%d", nOvFactor);
    3641             :                 }
    3642           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    3643             :                          "Only overviews %s can be computed",
    3644             :                          osOvrList.c_str());
    3645           2 :                 return CE_Failure;
    3646             :             }
    3647             :             else
    3648             :             {
    3649           4 :                 int nOvFactor = panOverviewList[i];
    3650           4 :                 if (jCandidate < 0)
    3651           3 :                     jCandidate = static_cast<int>(m_apoOverviewDS.size());
    3652             : 
    3653           4 :                 int nOvXSize = std::max(1, GetRasterXSize() / nOvFactor);
    3654           4 :                 int nOvYSize = std::max(1, GetRasterYSize() / nOvFactor);
    3655           4 :                 if (!(jCandidate == static_cast<int>(m_apoOverviewDS.size()) &&
    3656           5 :                       nOvFactor == 2 * nMaxOvFactor) &&
    3657           1 :                     !m_bZoomOther)
    3658             :                 {
    3659           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    3660             :                              "Use of overview factor %d causes gpkg_zoom_other "
    3661             :                              "extension to be needed",
    3662             :                              nOvFactor);
    3663           1 :                     RegisterZoomOtherExtension();
    3664           1 :                     m_bZoomOther = true;
    3665             :                 }
    3666             : 
    3667           4 :                 SoftStartTransaction();
    3668             : 
    3669           4 :                 CPLAssert(jCandidate > 0);
    3670             :                 const int nNewZoomLevel =
    3671           4 :                     m_apoOverviewDS[jCandidate - 1]->m_nZoomLevel;
    3672             : 
    3673             :                 char *pszSQL;
    3674             :                 OGRErr eErr;
    3675          24 :                 for (int k = 0; k <= jCandidate; k++)
    3676             :                 {
    3677          60 :                     pszSQL = sqlite3_mprintf(
    3678             :                         "UPDATE gpkg_tile_matrix SET zoom_level = %d "
    3679             :                         "WHERE lower(table_name) = lower('%q') AND zoom_level "
    3680             :                         "= %d",
    3681          20 :                         m_nZoomLevel - k + 1, m_osRasterTable.c_str(),
    3682          20 :                         m_nZoomLevel - k);
    3683          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3684          20 :                     sqlite3_free(pszSQL);
    3685          20 :                     if (eErr != OGRERR_NONE)
    3686             :                     {
    3687           0 :                         SoftRollbackTransaction();
    3688           0 :                         return CE_Failure;
    3689             :                     }
    3690             : 
    3691             :                     pszSQL =
    3692          20 :                         sqlite3_mprintf("UPDATE \"%w\" SET zoom_level = %d "
    3693             :                                         "WHERE zoom_level = %d",
    3694             :                                         m_osRasterTable.c_str(),
    3695          20 :                                         m_nZoomLevel - k + 1, m_nZoomLevel - k);
    3696          20 :                     eErr = SQLCommand(hDB, pszSQL);
    3697          20 :                     sqlite3_free(pszSQL);
    3698          20 :                     if (eErr != OGRERR_NONE)
    3699             :                     {
    3700           0 :                         SoftRollbackTransaction();
    3701           0 :                         return CE_Failure;
    3702             :                     }
    3703             :                 }
    3704             : 
    3705           4 :                 double dfGDALMinX = m_gt[0];
    3706           4 :                 double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    3707           4 :                 double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    3708           4 :                 double dfGDALMaxY = m_gt[3];
    3709           4 :                 double dfPixelXSizeZoomLevel = m_gt[1] * nOvFactor;
    3710           4 :                 double dfPixelYSizeZoomLevel = fabs(m_gt[5]) * nOvFactor;
    3711             :                 int nTileWidth, nTileHeight;
    3712           4 :                 GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    3713           4 :                 int nTileMatrixWidth = DIV_ROUND_UP(nOvXSize, nTileWidth);
    3714           4 :                 int nTileMatrixHeight = DIV_ROUND_UP(nOvYSize, nTileHeight);
    3715           4 :                 pszSQL = sqlite3_mprintf(
    3716             :                     "INSERT INTO gpkg_tile_matrix "
    3717             :                     "(table_name,zoom_level,matrix_width,matrix_height,tile_"
    3718             :                     "width,tile_height,pixel_x_size,pixel_y_size) VALUES "
    3719             :                     "('%q',%d,%d,%d,%d,%d,%.17g,%.17g)",
    3720             :                     m_osRasterTable.c_str(), nNewZoomLevel, nTileMatrixWidth,
    3721             :                     nTileMatrixHeight, nTileWidth, nTileHeight,
    3722             :                     dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel);
    3723           4 :                 eErr = SQLCommand(hDB, pszSQL);
    3724           4 :                 sqlite3_free(pszSQL);
    3725           4 :                 if (eErr != OGRERR_NONE)
    3726             :                 {
    3727           0 :                     SoftRollbackTransaction();
    3728           0 :                     return CE_Failure;
    3729             :                 }
    3730             : 
    3731           4 :                 SoftCommitTransaction();
    3732             : 
    3733           4 :                 m_nZoomLevel++; /* this change our zoom level as well as
    3734             :                                    previous overviews */
    3735          20 :                 for (int k = 0; k < jCandidate; k++)
    3736          16 :                     m_apoOverviewDS[k]->m_nZoomLevel++;
    3737             : 
    3738           4 :                 auto poOvrDS = std::make_unique<GDALGeoPackageDataset>();
    3739           4 :                 poOvrDS->ShareLockWithParentDataset(this);
    3740           4 :                 poOvrDS->InitRaster(
    3741             :                     this, m_osRasterTable, nNewZoomLevel, nBands, m_dfTMSMinX,
    3742             :                     m_dfTMSMaxY, dfPixelXSizeZoomLevel, dfPixelYSizeZoomLevel,
    3743             :                     nTileWidth, nTileHeight, nTileMatrixWidth,
    3744             :                     nTileMatrixHeight, dfGDALMinX, dfGDALMinY, dfGDALMaxX,
    3745             :                     dfGDALMaxY);
    3746           4 :                 m_apoOverviewDS.insert(m_apoOverviewDS.begin() + jCandidate,
    3747           8 :                                        std::move(poOvrDS));
    3748             :             }
    3749             :         }
    3750             :     }
    3751             : 
    3752             :     GDALRasterBand ***papapoOverviewBands = static_cast<GDALRasterBand ***>(
    3753          13 :         CPLCalloc(sizeof(GDALRasterBand **), nBands));
    3754          13 :     CPLErr eErr = CE_None;
    3755          49 :     for (int iBand = 0; eErr == CE_None && iBand < nBands; iBand++)
    3756             :     {
    3757          72 :         papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
    3758          36 :             CPLCalloc(sizeof(GDALRasterBand *), nOverviews));
    3759          36 :         int iCurOverview = 0;
    3760         185 :         for (int i = 0; i < nOverviews; i++)
    3761             :         {
    3762         149 :             bool bFound = false;
    3763         724 :             for (const auto &poODS : m_apoOverviewDS)
    3764             :             {
    3765             :                 const int nOvFactor =
    3766         724 :                     static_cast<int>(0.5 + poODS->m_gt[1] / m_gt[1]);
    3767             : 
    3768         724 :                 if (nOvFactor == panOverviewList[i])
    3769             :                 {
    3770         298 :                     papapoOverviewBands[iBand][iCurOverview] =
    3771         149 :                         poODS->GetRasterBand(iBand + 1);
    3772         149 :                     iCurOverview++;
    3773         149 :                     bFound = true;
    3774         149 :                     break;
    3775             :                 }
    3776             :             }
    3777         149 :             if (!bFound)
    3778             :             {
    3779           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3780             :                          "Could not find dataset corresponding to ov factor %d",
    3781           0 :                          panOverviewList[i]);
    3782           0 :                 eErr = CE_Failure;
    3783             :             }
    3784             :         }
    3785          36 :         if (eErr == CE_None)
    3786             :         {
    3787          36 :             CPLAssert(iCurOverview == nOverviews);
    3788             :         }
    3789             :     }
    3790             : 
    3791          13 :     if (eErr == CE_None)
    3792          13 :         eErr = GDALRegenerateOverviewsMultiBand(
    3793          13 :             nBands, papoBands, nOverviews, papapoOverviewBands, pszResampling,
    3794             :             pfnProgress, pProgressData, papszOptions);
    3795             : 
    3796          49 :     for (int iBand = 0; iBand < nBands; iBand++)
    3797             :     {
    3798          36 :         CPLFree(papapoOverviewBands[iBand]);
    3799             :     }
    3800          13 :     CPLFree(papapoOverviewBands);
    3801             : 
    3802          13 :     return eErr;
    3803             : }
    3804             : 
    3805             : /************************************************************************/
    3806             : /*                            GetFileList()                             */
    3807             : /************************************************************************/
    3808             : 
    3809          38 : char **GDALGeoPackageDataset::GetFileList()
    3810             : {
    3811          38 :     TryLoadXML();
    3812          38 :     return GDALPamDataset::GetFileList();
    3813             : }
    3814             : 
    3815             : /************************************************************************/
    3816             : /*                      GetMetadataDomainList()                         */
    3817             : /************************************************************************/
    3818             : 
    3819          47 : char **GDALGeoPackageDataset::GetMetadataDomainList()
    3820             : {
    3821          47 :     GetMetadata();
    3822          47 :     if (!m_osRasterTable.empty())
    3823           5 :         GetMetadata("GEOPACKAGE");
    3824          47 :     return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
    3825          47 :                                    TRUE, "SUBDATASETS", nullptr);
    3826             : }
    3827             : 
    3828             : /************************************************************************/
    3829             : /*                        CheckMetadataDomain()                         */
    3830             : /************************************************************************/
    3831             : 
    3832        5389 : const char *GDALGeoPackageDataset::CheckMetadataDomain(const char *pszDomain)
    3833             : {
    3834        5574 :     if (pszDomain != nullptr && EQUAL(pszDomain, "GEOPACKAGE") &&
    3835         185 :         m_osRasterTable.empty())
    3836             :     {
    3837           4 :         CPLError(
    3838             :             CE_Warning, CPLE_IllegalArg,
    3839             :             "Using GEOPACKAGE for a non-raster geopackage is not supported. "
    3840             :             "Using default domain instead");
    3841           4 :         return nullptr;
    3842             :     }
    3843        5385 :     return pszDomain;
    3844             : }
    3845             : 
    3846             : /************************************************************************/
    3847             : /*                           HasMetadataTables()                        */
    3848             : /************************************************************************/
    3849             : 
    3850        5539 : bool GDALGeoPackageDataset::HasMetadataTables() const
    3851             : {
    3852        5539 :     if (m_nHasMetadataTables < 0)
    3853             :     {
    3854             :         const int nCount =
    3855        2102 :             SQLGetInteger(hDB,
    3856             :                           "SELECT COUNT(*) FROM sqlite_master WHERE name IN "
    3857             :                           "('gpkg_metadata', 'gpkg_metadata_reference') "
    3858             :                           "AND type IN ('table', 'view')",
    3859             :                           nullptr);
    3860        2102 :         m_nHasMetadataTables = nCount == 2;
    3861             :     }
    3862        5539 :     return CPL_TO_BOOL(m_nHasMetadataTables);
    3863             : }
    3864             : 
    3865             : /************************************************************************/
    3866             : /*                         HasDataColumnsTable()                        */
    3867             : /************************************************************************/
    3868             : 
    3869        1231 : bool GDALGeoPackageDataset::HasDataColumnsTable() const
    3870             : {
    3871        2462 :     const int nCount = SQLGetInteger(
    3872        1231 :         hDB,
    3873             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_data_columns'"
    3874             :         "AND type IN ('table', 'view')",
    3875             :         nullptr);
    3876        1231 :     return nCount == 1;
    3877             : }
    3878             : 
    3879             : /************************************************************************/
    3880             : /*                    HasDataColumnConstraintsTable()                   */
    3881             : /************************************************************************/
    3882             : 
    3883         120 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTable() const
    3884             : {
    3885         120 :     const int nCount = SQLGetInteger(hDB,
    3886             :                                      "SELECT 1 FROM sqlite_master WHERE name = "
    3887             :                                      "'gpkg_data_column_constraints'"
    3888             :                                      "AND type IN ('table', 'view')",
    3889             :                                      nullptr);
    3890         120 :     return nCount == 1;
    3891             : }
    3892             : 
    3893             : /************************************************************************/
    3894             : /*                  HasDataColumnConstraintsTableGPKG_1_0()             */
    3895             : /************************************************************************/
    3896             : 
    3897          73 : bool GDALGeoPackageDataset::HasDataColumnConstraintsTableGPKG_1_0() const
    3898             : {
    3899          73 :     if (m_nApplicationId != GP10_APPLICATION_ID)
    3900          71 :         return false;
    3901             :     // In GPKG 1.0, the columns were named minIsInclusive, maxIsInclusive
    3902             :     // They were changed in 1.1 to min_is_inclusive, max_is_inclusive
    3903           2 :     bool bRet = false;
    3904           2 :     sqlite3_stmt *hSQLStmt = nullptr;
    3905           2 :     int rc = sqlite3_prepare_v2(hDB,
    3906             :                                 "SELECT minIsInclusive, maxIsInclusive FROM "
    3907             :                                 "gpkg_data_column_constraints",
    3908             :                                 -1, &hSQLStmt, nullptr);
    3909           2 :     if (rc == SQLITE_OK)
    3910             :     {
    3911           2 :         bRet = true;
    3912           2 :         sqlite3_finalize(hSQLStmt);
    3913             :     }
    3914           2 :     return bRet;
    3915             : }
    3916             : 
    3917             : /************************************************************************/
    3918             : /*      CreateColumnsTableAndColumnConstraintsTablesIfNecessary()       */
    3919             : /************************************************************************/
    3920             : 
    3921          49 : bool GDALGeoPackageDataset::
    3922             :     CreateColumnsTableAndColumnConstraintsTablesIfNecessary()
    3923             : {
    3924          49 :     if (!HasDataColumnsTable())
    3925             :     {
    3926             :         // Geopackage < 1.3 had
    3927             :         // CONSTRAINT fk_gdc_tn FOREIGN KEY (table_name) REFERENCES
    3928             :         // gpkg_contents(table_name) instead of the unique constraint.
    3929          10 :         if (OGRERR_NONE !=
    3930          10 :             SQLCommand(
    3931             :                 GetDB(),
    3932             :                 "CREATE TABLE gpkg_data_columns ("
    3933             :                 "table_name TEXT NOT NULL,"
    3934             :                 "column_name TEXT NOT NULL,"
    3935             :                 "name TEXT,"
    3936             :                 "title TEXT,"
    3937             :                 "description TEXT,"
    3938             :                 "mime_type TEXT,"
    3939             :                 "constraint_name TEXT,"
    3940             :                 "CONSTRAINT pk_gdc PRIMARY KEY (table_name, column_name),"
    3941             :                 "CONSTRAINT gdc_tn UNIQUE (table_name, name));"))
    3942             :         {
    3943           0 :             return false;
    3944             :         }
    3945             :     }
    3946          49 :     if (!HasDataColumnConstraintsTable())
    3947             :     {
    3948          22 :         const char *min_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3949          11 :                                            ? "min_is_inclusive"
    3950             :                                            : "minIsInclusive";
    3951          22 :         const char *max_is_inclusive = m_nApplicationId != GP10_APPLICATION_ID
    3952          11 :                                            ? "max_is_inclusive"
    3953             :                                            : "maxIsInclusive";
    3954             : 
    3955             :         const std::string osSQL(
    3956             :             CPLSPrintf("CREATE TABLE gpkg_data_column_constraints ("
    3957             :                        "constraint_name TEXT NOT NULL,"
    3958             :                        "constraint_type TEXT NOT NULL,"
    3959             :                        "value TEXT,"
    3960             :                        "min NUMERIC,"
    3961             :                        "%s BOOLEAN,"
    3962             :                        "max NUMERIC,"
    3963             :                        "%s BOOLEAN,"
    3964             :                        "description TEXT,"
    3965             :                        "CONSTRAINT gdcc_ntv UNIQUE (constraint_name, "
    3966             :                        "constraint_type, value));",
    3967          11 :                        min_is_inclusive, max_is_inclusive));
    3968          11 :         if (OGRERR_NONE != SQLCommand(GetDB(), osSQL.c_str()))
    3969             :         {
    3970           0 :             return false;
    3971             :         }
    3972             :     }
    3973          49 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    3974             :     {
    3975           0 :         return false;
    3976             :     }
    3977          49 :     if (SQLGetInteger(GetDB(),
    3978             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3979             :                       "table_name = 'gpkg_data_columns'",
    3980          49 :                       nullptr) != 1)
    3981             :     {
    3982          11 :         if (OGRERR_NONE !=
    3983          11 :             SQLCommand(
    3984             :                 GetDB(),
    3985             :                 "INSERT INTO gpkg_extensions "
    3986             :                 "(table_name,column_name,extension_name,definition,scope) "
    3987             :                 "VALUES ('gpkg_data_columns', NULL, 'gpkg_schema', "
    3988             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    3989             :                 "'read-write')"))
    3990             :         {
    3991           0 :             return false;
    3992             :         }
    3993             :     }
    3994          49 :     if (SQLGetInteger(GetDB(),
    3995             :                       "SELECT 1 FROM gpkg_extensions WHERE "
    3996             :                       "table_name = 'gpkg_data_column_constraints'",
    3997          49 :                       nullptr) != 1)
    3998             :     {
    3999          11 :         if (OGRERR_NONE !=
    4000          11 :             SQLCommand(
    4001             :                 GetDB(),
    4002             :                 "INSERT INTO gpkg_extensions "
    4003             :                 "(table_name,column_name,extension_name,definition,scope) "
    4004             :                 "VALUES ('gpkg_data_column_constraints', NULL, 'gpkg_schema', "
    4005             :                 "'http://www.geopackage.org/spec121/#extension_schema', "
    4006             :                 "'read-write')"))
    4007             :         {
    4008           0 :             return false;
    4009             :         }
    4010             :     }
    4011             : 
    4012          49 :     return true;
    4013             : }
    4014             : 
    4015             : /************************************************************************/
    4016             : /*                        HasGpkgextRelationsTable()                    */
    4017             : /************************************************************************/
    4018             : 
    4019        1229 : bool GDALGeoPackageDataset::HasGpkgextRelationsTable() const
    4020             : {
    4021        2458 :     const int nCount = SQLGetInteger(
    4022        1229 :         hDB,
    4023             :         "SELECT 1 FROM sqlite_master WHERE name = 'gpkgext_relations'"
    4024             :         "AND type IN ('table', 'view')",
    4025             :         nullptr);
    4026        1229 :     return nCount == 1;
    4027             : }
    4028             : 
    4029             : /************************************************************************/
    4030             : /*                    CreateRelationsTableIfNecessary()                 */
    4031             : /************************************************************************/
    4032             : 
    4033           9 : bool GDALGeoPackageDataset::CreateRelationsTableIfNecessary()
    4034             : {
    4035           9 :     if (HasGpkgextRelationsTable())
    4036             :     {
    4037           5 :         return true;
    4038             :     }
    4039             : 
    4040           4 :     if (OGRERR_NONE !=
    4041           4 :         SQLCommand(GetDB(), "CREATE TABLE gpkgext_relations ("
    4042             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    4043             :                             "base_table_name TEXT NOT NULL,"
    4044             :                             "base_primary_column TEXT NOT NULL DEFAULT 'id',"
    4045             :                             "related_table_name TEXT NOT NULL,"
    4046             :                             "related_primary_column TEXT NOT NULL DEFAULT 'id',"
    4047             :                             "relation_name TEXT NOT NULL,"
    4048             :                             "mapping_table_name TEXT NOT NULL UNIQUE);"))
    4049             :     {
    4050           0 :         return false;
    4051             :     }
    4052             : 
    4053           4 :     return true;
    4054             : }
    4055             : 
    4056             : /************************************************************************/
    4057             : /*                        HasQGISLayerStyles()                          */
    4058             : /************************************************************************/
    4059             : 
    4060          11 : bool GDALGeoPackageDataset::HasQGISLayerStyles() const
    4061             : {
    4062             :     // QGIS layer_styles extension:
    4063             :     // https://github.com/pka/qgpkg/blob/master/qgis_geopackage_extension.md
    4064          11 :     bool bRet = false;
    4065             :     const int nCount =
    4066          11 :         SQLGetInteger(hDB,
    4067             :                       "SELECT 1 FROM sqlite_master WHERE name = 'layer_styles'"
    4068             :                       "AND type = 'table'",
    4069             :                       nullptr);
    4070          11 :     if (nCount == 1)
    4071             :     {
    4072           1 :         sqlite3_stmt *hSQLStmt = nullptr;
    4073           2 :         int rc = sqlite3_prepare_v2(
    4074           1 :             hDB, "SELECT f_table_name, f_geometry_column FROM layer_styles", -1,
    4075             :             &hSQLStmt, nullptr);
    4076           1 :         if (rc == SQLITE_OK)
    4077             :         {
    4078           1 :             bRet = true;
    4079           1 :             sqlite3_finalize(hSQLStmt);
    4080             :         }
    4081             :     }
    4082          11 :     return bRet;
    4083             : }
    4084             : 
    4085             : /************************************************************************/
    4086             : /*                            GetMetadata()                             */
    4087             : /************************************************************************/
    4088             : 
    4089        3613 : char **GDALGeoPackageDataset::GetMetadata(const char *pszDomain)
    4090             : 
    4091             : {
    4092        3613 :     pszDomain = CheckMetadataDomain(pszDomain);
    4093        3613 :     if (pszDomain != nullptr && EQUAL(pszDomain, "SUBDATASETS"))
    4094          67 :         return m_aosSubDatasets.List();
    4095             : 
    4096        3546 :     if (m_bHasReadMetadataFromStorage)
    4097        1517 :         return GDALPamDataset::GetMetadata(pszDomain);
    4098             : 
    4099        2029 :     m_bHasReadMetadataFromStorage = true;
    4100             : 
    4101        2029 :     TryLoadXML();
    4102             : 
    4103        2029 :     if (!HasMetadataTables())
    4104        1521 :         return GDALPamDataset::GetMetadata(pszDomain);
    4105             : 
    4106         508 :     char *pszSQL = nullptr;
    4107         508 :     if (!m_osRasterTable.empty())
    4108             :     {
    4109         170 :         pszSQL = sqlite3_mprintf(
    4110             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4111             :             "mdr.reference_scope FROM gpkg_metadata md "
    4112             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4113             :             "WHERE "
    4114             :             "(mdr.reference_scope = 'geopackage' OR "
    4115             :             "(mdr.reference_scope = 'table' AND lower(mdr.table_name) = "
    4116             :             "lower('%q'))) ORDER BY md.id "
    4117             :             "LIMIT 1000",  // to avoid denial of service
    4118             :             m_osRasterTable.c_str());
    4119             :     }
    4120             :     else
    4121             :     {
    4122         338 :         pszSQL = sqlite3_mprintf(
    4123             :             "SELECT md.metadata, md.md_standard_uri, md.mime_type, "
    4124             :             "mdr.reference_scope FROM gpkg_metadata md "
    4125             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4126             :             "WHERE "
    4127             :             "mdr.reference_scope = 'geopackage' ORDER BY md.id "
    4128             :             "LIMIT 1000"  // to avoid denial of service
    4129             :         );
    4130             :     }
    4131             : 
    4132        1016 :     auto oResult = SQLQuery(hDB, pszSQL);
    4133         508 :     sqlite3_free(pszSQL);
    4134         508 :     if (!oResult)
    4135             :     {
    4136           0 :         return GDALPamDataset::GetMetadata(pszDomain);
    4137             :     }
    4138             : 
    4139         508 :     char **papszMetadata = CSLDuplicate(GDALPamDataset::GetMetadata());
    4140             : 
    4141             :     /* GDAL metadata */
    4142         698 :     for (int i = 0; i < oResult->RowCount(); i++)
    4143             :     {
    4144         190 :         const char *pszMetadata = oResult->GetValue(0, i);
    4145         190 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4146         190 :         const char *pszMimeType = oResult->GetValue(2, i);
    4147         190 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4148         190 :         if (pszMetadata && pszMDStandardURI && pszMimeType &&
    4149         190 :             pszReferenceScope && EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4150         174 :             EQUAL(pszMimeType, "text/xml"))
    4151             :         {
    4152         174 :             CPLXMLNode *psXMLNode = CPLParseXMLString(pszMetadata);
    4153         174 :             if (psXMLNode)
    4154             :             {
    4155         348 :                 GDALMultiDomainMetadata oLocalMDMD;
    4156         174 :                 oLocalMDMD.XMLInit(psXMLNode, FALSE);
    4157         333 :                 if (!m_osRasterTable.empty() &&
    4158         159 :                     EQUAL(pszReferenceScope, "geopackage"))
    4159             :                 {
    4160           6 :                     oMDMD.SetMetadata(oLocalMDMD.GetMetadata(), "GEOPACKAGE");
    4161             :                 }
    4162             :                 else
    4163             :                 {
    4164             :                     papszMetadata =
    4165         168 :                         CSLMerge(papszMetadata, oLocalMDMD.GetMetadata());
    4166         168 :                     CSLConstList papszDomainList = oLocalMDMD.GetDomainList();
    4167         168 :                     CSLConstList papszIter = papszDomainList;
    4168         447 :                     while (papszIter && *papszIter)
    4169             :                     {
    4170         279 :                         if (EQUAL(*papszIter, "IMAGE_STRUCTURE"))
    4171             :                         {
    4172             :                             CSLConstList papszMD =
    4173         126 :                                 oLocalMDMD.GetMetadata(*papszIter);
    4174             :                             const char *pszBAND_COUNT =
    4175         126 :                                 CSLFetchNameValue(papszMD, "BAND_COUNT");
    4176         126 :                             if (pszBAND_COUNT)
    4177         124 :                                 m_nBandCountFromMetadata = atoi(pszBAND_COUNT);
    4178             : 
    4179             :                             const char *pszCOLOR_TABLE =
    4180         126 :                                 CSLFetchNameValue(papszMD, "COLOR_TABLE");
    4181         126 :                             if (pszCOLOR_TABLE)
    4182             :                             {
    4183             :                                 const CPLStringList aosTokens(
    4184             :                                     CSLTokenizeString2(pszCOLOR_TABLE, "{,",
    4185          26 :                                                        0));
    4186          13 :                                 if ((aosTokens.size() % 4) == 0)
    4187             :                                 {
    4188          13 :                                     const int nColors = aosTokens.size() / 4;
    4189             :                                     m_poCTFromMetadata =
    4190          13 :                                         std::make_unique<GDALColorTable>();
    4191        3341 :                                     for (int iColor = 0; iColor < nColors;
    4192             :                                          ++iColor)
    4193             :                                     {
    4194             :                                         GDALColorEntry sEntry;
    4195        3328 :                                         sEntry.c1 = static_cast<short>(
    4196        3328 :                                             atoi(aosTokens[4 * iColor + 0]));
    4197        3328 :                                         sEntry.c2 = static_cast<short>(
    4198        3328 :                                             atoi(aosTokens[4 * iColor + 1]));
    4199        3328 :                                         sEntry.c3 = static_cast<short>(
    4200        3328 :                                             atoi(aosTokens[4 * iColor + 2]));
    4201        3328 :                                         sEntry.c4 = static_cast<short>(
    4202        3328 :                                             atoi(aosTokens[4 * iColor + 3]));
    4203        3328 :                                         m_poCTFromMetadata->SetColorEntry(
    4204             :                                             iColor, &sEntry);
    4205             :                                     }
    4206             :                                 }
    4207             :                             }
    4208             : 
    4209             :                             const char *pszTILE_FORMAT =
    4210         126 :                                 CSLFetchNameValue(papszMD, "TILE_FORMAT");
    4211         126 :                             if (pszTILE_FORMAT)
    4212             :                             {
    4213           8 :                                 m_osTFFromMetadata = pszTILE_FORMAT;
    4214           8 :                                 oMDMD.SetMetadataItem("TILE_FORMAT",
    4215             :                                                       pszTILE_FORMAT,
    4216             :                                                       "IMAGE_STRUCTURE");
    4217             :                             }
    4218             : 
    4219             :                             const char *pszNodataValue =
    4220         126 :                                 CSLFetchNameValue(papszMD, "NODATA_VALUE");
    4221         126 :                             if (pszNodataValue)
    4222             :                             {
    4223           2 :                                 m_osNodataValueFromMetadata = pszNodataValue;
    4224             :                             }
    4225             :                         }
    4226             : 
    4227         153 :                         else if (!EQUAL(*papszIter, "") &&
    4228          16 :                                  !STARTS_WITH(*papszIter, "BAND_"))
    4229             :                         {
    4230          12 :                             oMDMD.SetMetadata(
    4231           6 :                                 oLocalMDMD.GetMetadata(*papszIter), *papszIter);
    4232             :                         }
    4233         279 :                         papszIter++;
    4234             :                     }
    4235             :                 }
    4236         174 :                 CPLDestroyXMLNode(psXMLNode);
    4237             :             }
    4238             :         }
    4239             :     }
    4240             : 
    4241         508 :     GDALPamDataset::SetMetadata(papszMetadata);
    4242         508 :     CSLDestroy(papszMetadata);
    4243         508 :     papszMetadata = nullptr;
    4244             : 
    4245             :     /* Add non-GDAL metadata now */
    4246         508 :     int nNonGDALMDILocal = 1;
    4247         508 :     int nNonGDALMDIGeopackage = 1;
    4248         698 :     for (int i = 0; i < oResult->RowCount(); i++)
    4249             :     {
    4250         190 :         const char *pszMetadata = oResult->GetValue(0, i);
    4251         190 :         const char *pszMDStandardURI = oResult->GetValue(1, i);
    4252         190 :         const char *pszMimeType = oResult->GetValue(2, i);
    4253         190 :         const char *pszReferenceScope = oResult->GetValue(3, i);
    4254         190 :         if (pszMetadata == nullptr || pszMDStandardURI == nullptr ||
    4255         190 :             pszMimeType == nullptr || pszReferenceScope == nullptr)
    4256             :         {
    4257             :             // should not happen as there are NOT NULL constraints
    4258             :             // But a database could lack such NOT NULL constraints or have
    4259             :             // large values that would cause a memory allocation failure.
    4260           0 :             continue;
    4261             :         }
    4262         190 :         int bIsGPKGScope = EQUAL(pszReferenceScope, "geopackage");
    4263         190 :         if (EQUAL(pszMDStandardURI, "http://gdal.org") &&
    4264         174 :             EQUAL(pszMimeType, "text/xml"))
    4265         174 :             continue;
    4266             : 
    4267          16 :         if (!m_osRasterTable.empty() && bIsGPKGScope)
    4268             :         {
    4269           8 :             oMDMD.SetMetadataItem(
    4270             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDIGeopackage),
    4271             :                 pszMetadata, "GEOPACKAGE");
    4272           8 :             nNonGDALMDIGeopackage++;
    4273             :         }
    4274             :         /*else if( strcmp( pszMDStandardURI, "http://www.isotc211.org/2005/gmd"
    4275             :         ) == 0 && strcmp( pszMimeType, "text/xml" ) == 0 )
    4276             :         {
    4277             :             char* apszMD[2];
    4278             :             apszMD[0] = (char*)pszMetadata;
    4279             :             apszMD[1] = NULL;
    4280             :             oMDMD.SetMetadata(apszMD, "xml:MD_Metadata");
    4281             :         }*/
    4282             :         else
    4283             :         {
    4284           8 :             oMDMD.SetMetadataItem(
    4285             :                 CPLSPrintf("GPKG_METADATA_ITEM_%d", nNonGDALMDILocal),
    4286             :                 pszMetadata);
    4287           8 :             nNonGDALMDILocal++;
    4288             :         }
    4289             :     }
    4290             : 
    4291         508 :     return GDALPamDataset::GetMetadata(pszDomain);
    4292             : }
    4293             : 
    4294             : /************************************************************************/
    4295             : /*                            WriteMetadata()                           */
    4296             : /************************************************************************/
    4297             : 
    4298         724 : void GDALGeoPackageDataset::WriteMetadata(
    4299             :     CPLXMLNode *psXMLNode, /* will be destroyed by the method */
    4300             :     const char *pszTableName)
    4301             : {
    4302         724 :     const bool bIsEmpty = (psXMLNode == nullptr);
    4303         724 :     if (!HasMetadataTables())
    4304             :     {
    4305         524 :         if (bIsEmpty || !CreateMetadataTables())
    4306             :         {
    4307         239 :             CPLDestroyXMLNode(psXMLNode);
    4308         239 :             return;
    4309             :         }
    4310             :     }
    4311             : 
    4312         485 :     char *pszXML = nullptr;
    4313         485 :     if (!bIsEmpty)
    4314             :     {
    4315             :         CPLXMLNode *psMasterXMLNode =
    4316         332 :             CPLCreateXMLNode(nullptr, CXT_Element, "GDALMultiDomainMetadata");
    4317         332 :         psMasterXMLNode->psChild = psXMLNode;
    4318         332 :         pszXML = CPLSerializeXMLTree(psMasterXMLNode);
    4319         332 :         CPLDestroyXMLNode(psMasterXMLNode);
    4320             :     }
    4321             :     // cppcheck-suppress uselessAssignmentPtrArg
    4322         485 :     psXMLNode = nullptr;
    4323             : 
    4324         485 :     char *pszSQL = nullptr;
    4325         485 :     if (pszTableName && pszTableName[0] != '\0')
    4326             :     {
    4327         340 :         pszSQL = sqlite3_mprintf(
    4328             :             "SELECT md.id FROM gpkg_metadata md "
    4329             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4330             :             "WHERE md.md_scope = 'dataset' AND "
    4331             :             "md.md_standard_uri='http://gdal.org' "
    4332             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = 'table' AND "
    4333             :             "lower(mdr.table_name) = lower('%q')",
    4334             :             pszTableName);
    4335             :     }
    4336             :     else
    4337             :     {
    4338         145 :         pszSQL = sqlite3_mprintf(
    4339             :             "SELECT md.id FROM gpkg_metadata md "
    4340             :             "JOIN gpkg_metadata_reference mdr ON (md.id = mdr.md_file_id ) "
    4341             :             "WHERE md.md_scope = 'dataset' AND "
    4342             :             "md.md_standard_uri='http://gdal.org' "
    4343             :             "AND md.mime_type='text/xml' AND mdr.reference_scope = "
    4344             :             "'geopackage'");
    4345             :     }
    4346             :     OGRErr err;
    4347         485 :     int mdId = SQLGetInteger(hDB, pszSQL, &err);
    4348         485 :     if (err != OGRERR_NONE)
    4349         453 :         mdId = -1;
    4350         485 :     sqlite3_free(pszSQL);
    4351             : 
    4352         485 :     if (bIsEmpty)
    4353             :     {
    4354         153 :         if (mdId >= 0)
    4355             :         {
    4356           6 :             SQLCommand(
    4357             :                 hDB,
    4358             :                 CPLSPrintf(
    4359             :                     "DELETE FROM gpkg_metadata_reference WHERE md_file_id = %d",
    4360             :                     mdId));
    4361           6 :             SQLCommand(
    4362             :                 hDB,
    4363             :                 CPLSPrintf("DELETE FROM gpkg_metadata WHERE id = %d", mdId));
    4364             :         }
    4365             :     }
    4366             :     else
    4367             :     {
    4368         332 :         if (mdId >= 0)
    4369             :         {
    4370          26 :             pszSQL = sqlite3_mprintf(
    4371             :                 "UPDATE gpkg_metadata SET metadata = '%q' WHERE id = %d",
    4372             :                 pszXML, mdId);
    4373             :         }
    4374             :         else
    4375             :         {
    4376             :             pszSQL =
    4377         306 :                 sqlite3_mprintf("INSERT INTO gpkg_metadata (md_scope, "
    4378             :                                 "md_standard_uri, mime_type, metadata) VALUES "
    4379             :                                 "('dataset','http://gdal.org','text/xml','%q')",
    4380             :                                 pszXML);
    4381             :         }
    4382         332 :         SQLCommand(hDB, pszSQL);
    4383         332 :         sqlite3_free(pszSQL);
    4384             : 
    4385         332 :         CPLFree(pszXML);
    4386             : 
    4387         332 :         if (mdId < 0)
    4388             :         {
    4389         306 :             const sqlite_int64 nFID = sqlite3_last_insert_rowid(hDB);
    4390         306 :             if (pszTableName != nullptr && pszTableName[0] != '\0')
    4391             :             {
    4392         294 :                 pszSQL = sqlite3_mprintf(
    4393             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4394             :                     "table_name, timestamp, md_file_id) VALUES "
    4395             :                     "('table', '%q', %s, %d)",
    4396         588 :                     pszTableName, GetCurrentDateEscapedSQL().c_str(),
    4397             :                     static_cast<int>(nFID));
    4398             :             }
    4399             :             else
    4400             :             {
    4401          12 :                 pszSQL = sqlite3_mprintf(
    4402             :                     "INSERT INTO gpkg_metadata_reference (reference_scope, "
    4403             :                     "timestamp, md_file_id) VALUES "
    4404             :                     "('geopackage', %s, %d)",
    4405          24 :                     GetCurrentDateEscapedSQL().c_str(), static_cast<int>(nFID));
    4406             :             }
    4407             :         }
    4408             :         else
    4409             :         {
    4410          26 :             pszSQL = sqlite3_mprintf("UPDATE gpkg_metadata_reference SET "
    4411             :                                      "timestamp = %s WHERE md_file_id = %d",
    4412          52 :                                      GetCurrentDateEscapedSQL().c_str(), mdId);
    4413             :         }
    4414         332 :         SQLCommand(hDB, pszSQL);
    4415         332 :         sqlite3_free(pszSQL);
    4416             :     }
    4417             : }
    4418             : 
    4419             : /************************************************************************/
    4420             : /*                        CreateMetadataTables()                        */
    4421             : /************************************************************************/
    4422             : 
    4423         303 : bool GDALGeoPackageDataset::CreateMetadataTables()
    4424             : {
    4425             :     const bool bCreateTriggers =
    4426         303 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "NO"));
    4427             : 
    4428             :     /* From C.10. gpkg_metadata Table 35. gpkg_metadata Table Definition SQL  */
    4429             :     CPLString osSQL = "CREATE TABLE gpkg_metadata ("
    4430             :                       "id INTEGER CONSTRAINT m_pk PRIMARY KEY ASC NOT NULL,"
    4431             :                       "md_scope TEXT NOT NULL DEFAULT 'dataset',"
    4432             :                       "md_standard_uri TEXT NOT NULL,"
    4433             :                       "mime_type TEXT NOT NULL DEFAULT 'text/xml',"
    4434             :                       "metadata TEXT NOT NULL DEFAULT ''"
    4435         606 :                       ")";
    4436             : 
    4437             :     /* From D.2. metadata Table 40. metadata Trigger Definition SQL  */
    4438         303 :     const char *pszMetadataTriggers =
    4439             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_insert' "
    4440             :         "BEFORE INSERT ON 'gpkg_metadata' "
    4441             :         "FOR EACH ROW BEGIN "
    4442             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata violates "
    4443             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4444             :         "collectionSession | series | dataset | featureType | feature | "
    4445             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4446             :         "taxonomy software | service | collectionHardware | "
    4447             :         "nonGeographicDataset | dimensionGroup') "
    4448             :         "WHERE NOT(NEW.md_scope IN "
    4449             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4450             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4451             :         "'catalogue','schema','taxonomy','software','service', "
    4452             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4453             :         "END; "
    4454             :         "CREATE TRIGGER 'gpkg_metadata_md_scope_update' "
    4455             :         "BEFORE UPDATE OF 'md_scope' ON 'gpkg_metadata' "
    4456             :         "FOR EACH ROW BEGIN "
    4457             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata violates "
    4458             :         "constraint: md_scope must be one of undefined | fieldSession | "
    4459             :         "collectionSession | series | dataset | featureType | feature | "
    4460             :         "attributeType | attribute | tile | model | catalogue | schema | "
    4461             :         "taxonomy software | service | collectionHardware | "
    4462             :         "nonGeographicDataset | dimensionGroup') "
    4463             :         "WHERE NOT(NEW.md_scope IN "
    4464             :         "('undefined','fieldSession','collectionSession','series','dataset', "
    4465             :         "'featureType','feature','attributeType','attribute','tile','model', "
    4466             :         "'catalogue','schema','taxonomy','software','service', "
    4467             :         "'collectionHardware','nonGeographicDataset','dimensionGroup')); "
    4468             :         "END";
    4469         303 :     if (bCreateTriggers)
    4470             :     {
    4471           0 :         osSQL += ";";
    4472           0 :         osSQL += pszMetadataTriggers;
    4473             :     }
    4474             : 
    4475             :     /* From C.11. gpkg_metadata_reference Table 36. gpkg_metadata_reference
    4476             :      * Table Definition SQL */
    4477             :     osSQL += ";"
    4478             :              "CREATE TABLE gpkg_metadata_reference ("
    4479             :              "reference_scope TEXT NOT NULL,"
    4480             :              "table_name TEXT,"
    4481             :              "column_name TEXT,"
    4482             :              "row_id_value INTEGER,"
    4483             :              "timestamp DATETIME NOT NULL DEFAULT "
    4484             :              "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    4485             :              "md_file_id INTEGER NOT NULL,"
    4486             :              "md_parent_id INTEGER,"
    4487             :              "CONSTRAINT crmr_mfi_fk FOREIGN KEY (md_file_id) REFERENCES "
    4488             :              "gpkg_metadata(id),"
    4489             :              "CONSTRAINT crmr_mpi_fk FOREIGN KEY (md_parent_id) REFERENCES "
    4490             :              "gpkg_metadata(id)"
    4491         303 :              ")";
    4492             : 
    4493             :     /* From D.3. metadata_reference Table 41. gpkg_metadata_reference Trigger
    4494             :      * Definition SQL   */
    4495         303 :     const char *pszMetadataReferenceTriggers =
    4496             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_insert' "
    4497             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4498             :         "FOR EACH ROW BEGIN "
    4499             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4500             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4501             :         "table\", \"column\", \"row\", \"row/col\"') "
    4502             :         "WHERE NOT NEW.reference_scope IN "
    4503             :         "('geopackage','table','column','row','row/col'); "
    4504             :         "END; "
    4505             :         "CREATE TRIGGER 'gpkg_metadata_reference_reference_scope_update' "
    4506             :         "BEFORE UPDATE OF 'reference_scope' ON 'gpkg_metadata_reference' "
    4507             :         "FOR EACH ROW BEGIN "
    4508             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4509             :         "violates constraint: reference_scope must be one of \"geopackage\", "
    4510             :         "\"table\", \"column\", \"row\", \"row/col\"') "
    4511             :         "WHERE NOT NEW.reference_scope IN "
    4512             :         "('geopackage','table','column','row','row/col'); "
    4513             :         "END; "
    4514             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_insert' "
    4515             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4516             :         "FOR EACH ROW BEGIN "
    4517             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4518             :         "violates constraint: column name must be NULL when reference_scope "
    4519             :         "is \"geopackage\", \"table\" or \"row\"') "
    4520             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4521             :         "AND NEW.column_name IS NOT NULL); "
    4522             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4523             :         "violates constraint: column name must be defined for the specified "
    4524             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4525             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4526             :         "AND NOT NEW.table_name IN ( "
    4527             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4528             :         "AND name = NEW.table_name "
    4529             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4530             :         "END; "
    4531             :         "CREATE TRIGGER 'gpkg_metadata_reference_column_name_update' "
    4532             :         "BEFORE UPDATE OF column_name ON 'gpkg_metadata_reference' "
    4533             :         "FOR EACH ROW BEGIN "
    4534             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4535             :         "violates constraint: column name must be NULL when reference_scope "
    4536             :         "is \"geopackage\", \"table\" or \"row\"') "
    4537             :         "WHERE (NEW.reference_scope IN ('geopackage','table','row') "
    4538             :         "AND NEW.column_name IS NOT NULL); "
    4539             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4540             :         "violates constraint: column name must be defined for the specified "
    4541             :         "table when reference_scope is \"column\" or \"row/col\"') "
    4542             :         "WHERE (NEW.reference_scope IN ('column','row/col') "
    4543             :         "AND NOT NEW.table_name IN ( "
    4544             :         "SELECT name FROM SQLITE_MASTER WHERE type = 'table' "
    4545             :         "AND name = NEW.table_name "
    4546             :         "AND sql LIKE ('%' || NEW.column_name || '%'))); "
    4547             :         "END; "
    4548             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_insert' "
    4549             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4550             :         "FOR EACH ROW BEGIN "
    4551             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4552             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4553             :         "is \"geopackage\", \"table\" or \"column\"') "
    4554             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4555             :         "AND NEW.row_id_value IS NOT NULL; "
    4556             :         "END; "
    4557             :         "CREATE TRIGGER 'gpkg_metadata_reference_row_id_value_update' "
    4558             :         "BEFORE UPDATE OF 'row_id_value' ON 'gpkg_metadata_reference' "
    4559             :         "FOR EACH ROW BEGIN "
    4560             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4561             :         "violates constraint: row_id_value must be NULL when reference_scope "
    4562             :         "is \"geopackage\", \"table\" or \"column\"') "
    4563             :         "WHERE NEW.reference_scope IN ('geopackage','table','column') "
    4564             :         "AND NEW.row_id_value IS NOT NULL; "
    4565             :         "END; "
    4566             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_insert' "
    4567             :         "BEFORE INSERT ON 'gpkg_metadata_reference' "
    4568             :         "FOR EACH ROW BEGIN "
    4569             :         "SELECT RAISE(ABORT, 'insert on table gpkg_metadata_reference "
    4570             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4571             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4572             :         "WHERE NOT (NEW.timestamp GLOB "
    4573             :         "'[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-"
    4574             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4575             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4576             :         "END; "
    4577             :         "CREATE TRIGGER 'gpkg_metadata_reference_timestamp_update' "
    4578             :         "BEFORE UPDATE OF 'timestamp' ON 'gpkg_metadata_reference' "
    4579             :         "FOR EACH ROW BEGIN "
    4580             :         "SELECT RAISE(ABORT, 'update on table gpkg_metadata_reference "
    4581             :         "violates constraint: timestamp must be a valid time in ISO 8601 "
    4582             :         "\"yyyy-mm-ddThh:mm:ss.cccZ\" form') "
    4583             :         "WHERE NOT (NEW.timestamp GLOB "
    4584             :         "'[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-"
    4585             :         "5][0-9].[0-9][0-9][0-9]Z' "
    4586             :         "AND strftime('%s',NEW.timestamp) NOT NULL); "
    4587             :         "END";
    4588         303 :     if (bCreateTriggers)
    4589             :     {
    4590           0 :         osSQL += ";";
    4591           0 :         osSQL += pszMetadataReferenceTriggers;
    4592             :     }
    4593             : 
    4594         303 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    4595           2 :         return false;
    4596             : 
    4597         301 :     osSQL += ";";
    4598             :     osSQL += "INSERT INTO gpkg_extensions "
    4599             :              "(table_name, column_name, extension_name, definition, scope) "
    4600             :              "VALUES "
    4601             :              "('gpkg_metadata', NULL, 'gpkg_metadata', "
    4602             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4603         301 :              "'read-write')";
    4604             : 
    4605         301 :     osSQL += ";";
    4606             :     osSQL += "INSERT INTO gpkg_extensions "
    4607             :              "(table_name, column_name, extension_name, definition, scope) "
    4608             :              "VALUES "
    4609             :              "('gpkg_metadata_reference', NULL, 'gpkg_metadata', "
    4610             :              "'http://www.geopackage.org/spec120/#extension_metadata', "
    4611         301 :              "'read-write')";
    4612             : 
    4613         301 :     const bool bOK = SQLCommand(hDB, osSQL) == OGRERR_NONE;
    4614         301 :     m_nHasMetadataTables = bOK;
    4615         301 :     return bOK;
    4616             : }
    4617             : 
    4618             : /************************************************************************/
    4619             : /*                            FlushMetadata()                           */
    4620             : /************************************************************************/
    4621             : 
    4622        8750 : void GDALGeoPackageDataset::FlushMetadata()
    4623             : {
    4624        8750 :     if (!m_bMetadataDirty || m_poParentDS != nullptr ||
    4625         363 :         m_nCreateMetadataTables == FALSE)
    4626        8393 :         return;
    4627         357 :     m_bMetadataDirty = false;
    4628             : 
    4629         357 :     if (eAccess == GA_ReadOnly)
    4630             :     {
    4631           3 :         return;
    4632             :     }
    4633             : 
    4634         354 :     bool bCanWriteAreaOrPoint =
    4635         706 :         !m_bGridCellEncodingAsCO &&
    4636         352 :         (m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT);
    4637         354 :     if (!m_osRasterTable.empty())
    4638             :     {
    4639             :         const char *pszIdentifier =
    4640         144 :             GDALGeoPackageDataset::GetMetadataItem("IDENTIFIER");
    4641             :         const char *pszDescription =
    4642         144 :             GDALGeoPackageDataset::GetMetadataItem("DESCRIPTION");
    4643         173 :         if (!m_bIdentifierAsCO && pszIdentifier != nullptr &&
    4644          29 :             pszIdentifier != m_osIdentifier)
    4645             :         {
    4646          14 :             m_osIdentifier = pszIdentifier;
    4647             :             char *pszSQL =
    4648          14 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4649             :                                 "WHERE lower(table_name) = lower('%q')",
    4650             :                                 pszIdentifier, m_osRasterTable.c_str());
    4651          14 :             SQLCommand(hDB, pszSQL);
    4652          14 :             sqlite3_free(pszSQL);
    4653             :         }
    4654         151 :         if (!m_bDescriptionAsCO && pszDescription != nullptr &&
    4655           7 :             pszDescription != m_osDescription)
    4656             :         {
    4657           7 :             m_osDescription = pszDescription;
    4658             :             char *pszSQL =
    4659           7 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4660             :                                 "WHERE lower(table_name) = lower('%q')",
    4661             :                                 pszDescription, m_osRasterTable.c_str());
    4662           7 :             SQLCommand(hDB, pszSQL);
    4663           7 :             sqlite3_free(pszSQL);
    4664             :         }
    4665         144 :         if (bCanWriteAreaOrPoint)
    4666             :         {
    4667             :             const char *pszAreaOrPoint =
    4668          28 :                 GDALGeoPackageDataset::GetMetadataItem(GDALMD_AREA_OR_POINT);
    4669          28 :             if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_AREA))
    4670             :             {
    4671          23 :                 bCanWriteAreaOrPoint = false;
    4672          23 :                 char *pszSQL = sqlite3_mprintf(
    4673             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4674             :                     "grid_cell_encoding = 'grid-value-is-area' WHERE "
    4675             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4676             :                     m_osRasterTable.c_str());
    4677          23 :                 SQLCommand(hDB, pszSQL);
    4678          23 :                 sqlite3_free(pszSQL);
    4679             :             }
    4680           5 :             else if (pszAreaOrPoint && EQUAL(pszAreaOrPoint, GDALMD_AOP_POINT))
    4681             :             {
    4682           1 :                 bCanWriteAreaOrPoint = false;
    4683           1 :                 char *pszSQL = sqlite3_mprintf(
    4684             :                     "UPDATE gpkg_2d_gridded_coverage_ancillary SET "
    4685             :                     "grid_cell_encoding = 'grid-value-is-center' WHERE "
    4686             :                     "lower(tile_matrix_set_name) = lower('%q')",
    4687             :                     m_osRasterTable.c_str());
    4688           1 :                 SQLCommand(hDB, pszSQL);
    4689           1 :                 sqlite3_free(pszSQL);
    4690             :             }
    4691             :         }
    4692             :     }
    4693             : 
    4694         354 :     char **papszMDDup = nullptr;
    4695         559 :     for (char **papszIter = GDALGeoPackageDataset::GetMetadata();
    4696         559 :          papszIter && *papszIter; ++papszIter)
    4697             :     {
    4698         205 :         if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4699          29 :             continue;
    4700         176 :         if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4701           8 :             continue;
    4702         168 :         if (STARTS_WITH_CI(*papszIter, "ZOOM_LEVEL="))
    4703          14 :             continue;
    4704         154 :         if (STARTS_WITH_CI(*papszIter, "GPKG_METADATA_ITEM_"))
    4705           4 :             continue;
    4706         150 :         if ((m_eTF == GPKG_TF_PNG_16BIT || m_eTF == GPKG_TF_TIFF_32BIT_FLOAT) &&
    4707          29 :             !bCanWriteAreaOrPoint &&
    4708          26 :             STARTS_WITH_CI(*papszIter, GDALMD_AREA_OR_POINT))
    4709             :         {
    4710          26 :             continue;
    4711             :         }
    4712         124 :         papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4713             :     }
    4714             : 
    4715         354 :     CPLXMLNode *psXMLNode = nullptr;
    4716             :     {
    4717         354 :         GDALMultiDomainMetadata oLocalMDMD;
    4718         354 :         CSLConstList papszDomainList = oMDMD.GetDomainList();
    4719         354 :         CSLConstList papszIter = papszDomainList;
    4720         354 :         oLocalMDMD.SetMetadata(papszMDDup);
    4721         683 :         while (papszIter && *papszIter)
    4722             :         {
    4723         329 :             if (!EQUAL(*papszIter, "") &&
    4724         159 :                 !EQUAL(*papszIter, "IMAGE_STRUCTURE") &&
    4725          15 :                 !EQUAL(*papszIter, "GEOPACKAGE"))
    4726             :             {
    4727           8 :                 oLocalMDMD.SetMetadata(oMDMD.GetMetadata(*papszIter),
    4728             :                                        *papszIter);
    4729             :             }
    4730         329 :             papszIter++;
    4731             :         }
    4732         354 :         if (m_nBandCountFromMetadata > 0)
    4733             :         {
    4734          74 :             oLocalMDMD.SetMetadataItem(
    4735             :                 "BAND_COUNT", CPLSPrintf("%d", m_nBandCountFromMetadata),
    4736             :                 "IMAGE_STRUCTURE");
    4737          74 :             if (nBands == 1)
    4738             :             {
    4739          50 :                 const auto poCT = GetRasterBand(1)->GetColorTable();
    4740          50 :                 if (poCT)
    4741             :                 {
    4742          16 :                     std::string osVal("{");
    4743           8 :                     const int nColorCount = poCT->GetColorEntryCount();
    4744        2056 :                     for (int i = 0; i < nColorCount; ++i)
    4745             :                     {
    4746        2048 :                         if (i > 0)
    4747        2040 :                             osVal += ',';
    4748        2048 :                         const GDALColorEntry *psEntry = poCT->GetColorEntry(i);
    4749             :                         osVal +=
    4750        2048 :                             CPLSPrintf("{%d,%d,%d,%d}", psEntry->c1,
    4751        2048 :                                        psEntry->c2, psEntry->c3, psEntry->c4);
    4752             :                     }
    4753           8 :                     osVal += '}';
    4754           8 :                     oLocalMDMD.SetMetadataItem("COLOR_TABLE", osVal.c_str(),
    4755             :                                                "IMAGE_STRUCTURE");
    4756             :                 }
    4757             :             }
    4758          74 :             if (nBands == 1)
    4759             :             {
    4760          50 :                 const char *pszTILE_FORMAT = nullptr;
    4761          50 :                 switch (m_eTF)
    4762             :                 {
    4763           0 :                     case GPKG_TF_PNG_JPEG:
    4764           0 :                         pszTILE_FORMAT = "JPEG_PNG";
    4765           0 :                         break;
    4766          44 :                     case GPKG_TF_PNG:
    4767          44 :                         break;
    4768           0 :                     case GPKG_TF_PNG8:
    4769           0 :                         pszTILE_FORMAT = "PNG8";
    4770           0 :                         break;
    4771           3 :                     case GPKG_TF_JPEG:
    4772           3 :                         pszTILE_FORMAT = "JPEG";
    4773           3 :                         break;
    4774           3 :                     case GPKG_TF_WEBP:
    4775           3 :                         pszTILE_FORMAT = "WEBP";
    4776           3 :                         break;
    4777           0 :                     case GPKG_TF_PNG_16BIT:
    4778           0 :                         break;
    4779           0 :                     case GPKG_TF_TIFF_32BIT_FLOAT:
    4780           0 :                         break;
    4781             :                 }
    4782          50 :                 if (pszTILE_FORMAT)
    4783           6 :                     oLocalMDMD.SetMetadataItem("TILE_FORMAT", pszTILE_FORMAT,
    4784             :                                                "IMAGE_STRUCTURE");
    4785             :             }
    4786             :         }
    4787         498 :         if (GetRasterCount() > 0 &&
    4788         144 :             GetRasterBand(1)->GetRasterDataType() == GDT_Byte)
    4789             :         {
    4790         114 :             int bHasNoData = FALSE;
    4791             :             const double dfNoDataValue =
    4792         114 :                 GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    4793         114 :             if (bHasNoData)
    4794             :             {
    4795           3 :                 oLocalMDMD.SetMetadataItem("NODATA_VALUE",
    4796             :                                            CPLSPrintf("%.17g", dfNoDataValue),
    4797             :                                            "IMAGE_STRUCTURE");
    4798             :             }
    4799             :         }
    4800         603 :         for (int i = 1; i <= GetRasterCount(); ++i)
    4801             :         {
    4802             :             auto poBand =
    4803         249 :                 cpl::down_cast<GDALGeoPackageRasterBand *>(GetRasterBand(i));
    4804         249 :             poBand->AddImplicitStatistics(false);
    4805         249 :             char **papszMD = GetRasterBand(i)->GetMetadata();
    4806         249 :             poBand->AddImplicitStatistics(true);
    4807         249 :             if (papszMD)
    4808             :             {
    4809          14 :                 oLocalMDMD.SetMetadata(papszMD, CPLSPrintf("BAND_%d", i));
    4810             :             }
    4811             :         }
    4812         354 :         psXMLNode = oLocalMDMD.Serialize();
    4813             :     }
    4814             : 
    4815         354 :     CSLDestroy(papszMDDup);
    4816         354 :     papszMDDup = nullptr;
    4817             : 
    4818         354 :     WriteMetadata(psXMLNode, m_osRasterTable.c_str());
    4819             : 
    4820         354 :     if (!m_osRasterTable.empty())
    4821             :     {
    4822             :         char **papszGeopackageMD =
    4823         144 :             GDALGeoPackageDataset::GetMetadata("GEOPACKAGE");
    4824             : 
    4825         144 :         papszMDDup = nullptr;
    4826         153 :         for (char **papszIter = papszGeopackageMD; papszIter && *papszIter;
    4827             :              ++papszIter)
    4828             :         {
    4829           9 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4830             :         }
    4831             : 
    4832         288 :         GDALMultiDomainMetadata oLocalMDMD;
    4833         144 :         oLocalMDMD.SetMetadata(papszMDDup);
    4834         144 :         CSLDestroy(papszMDDup);
    4835         144 :         papszMDDup = nullptr;
    4836         144 :         psXMLNode = oLocalMDMD.Serialize();
    4837             : 
    4838         144 :         WriteMetadata(psXMLNode, nullptr);
    4839             :     }
    4840             : 
    4841         580 :     for (auto &poLayer : m_apoLayers)
    4842             :     {
    4843         226 :         const char *pszIdentifier = poLayer->GetMetadataItem("IDENTIFIER");
    4844         226 :         const char *pszDescription = poLayer->GetMetadataItem("DESCRIPTION");
    4845         226 :         if (pszIdentifier != nullptr)
    4846             :         {
    4847             :             char *pszSQL =
    4848           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' "
    4849             :                                 "WHERE lower(table_name) = lower('%q')",
    4850             :                                 pszIdentifier, poLayer->GetName());
    4851           3 :             SQLCommand(hDB, pszSQL);
    4852           3 :             sqlite3_free(pszSQL);
    4853             :         }
    4854         226 :         if (pszDescription != nullptr)
    4855             :         {
    4856             :             char *pszSQL =
    4857           3 :                 sqlite3_mprintf("UPDATE gpkg_contents SET description = '%q' "
    4858             :                                 "WHERE lower(table_name) = lower('%q')",
    4859             :                                 pszDescription, poLayer->GetName());
    4860           3 :             SQLCommand(hDB, pszSQL);
    4861           3 :             sqlite3_free(pszSQL);
    4862             :         }
    4863             : 
    4864         226 :         papszMDDup = nullptr;
    4865         616 :         for (char **papszIter = poLayer->GetMetadata(); papszIter && *papszIter;
    4866             :              ++papszIter)
    4867             :         {
    4868         390 :             if (STARTS_WITH_CI(*papszIter, "IDENTIFIER="))
    4869           3 :                 continue;
    4870         387 :             if (STARTS_WITH_CI(*papszIter, "DESCRIPTION="))
    4871           3 :                 continue;
    4872         384 :             if (STARTS_WITH_CI(*papszIter, "OLMD_FID64="))
    4873           0 :                 continue;
    4874         384 :             papszMDDup = CSLInsertString(papszMDDup, -1, *papszIter);
    4875             :         }
    4876             : 
    4877             :         {
    4878         226 :             GDALMultiDomainMetadata oLocalMDMD;
    4879         226 :             char **papszDomainList = poLayer->GetMetadataDomainList();
    4880         226 :             char **papszIter = papszDomainList;
    4881         226 :             oLocalMDMD.SetMetadata(papszMDDup);
    4882         501 :             while (papszIter && *papszIter)
    4883             :             {
    4884         275 :                 if (!EQUAL(*papszIter, ""))
    4885          62 :                     oLocalMDMD.SetMetadata(poLayer->GetMetadata(*papszIter),
    4886             :                                            *papszIter);
    4887         275 :                 papszIter++;
    4888             :             }
    4889         226 :             CSLDestroy(papszDomainList);
    4890         226 :             psXMLNode = oLocalMDMD.Serialize();
    4891             :         }
    4892             : 
    4893         226 :         CSLDestroy(papszMDDup);
    4894         226 :         papszMDDup = nullptr;
    4895             : 
    4896         226 :         WriteMetadata(psXMLNode, poLayer->GetName());
    4897             :     }
    4898             : }
    4899             : 
    4900             : /************************************************************************/
    4901             : /*                          GetMetadataItem()                           */
    4902             : /************************************************************************/
    4903             : 
    4904        1622 : const char *GDALGeoPackageDataset::GetMetadataItem(const char *pszName,
    4905             :                                                    const char *pszDomain)
    4906             : {
    4907        1622 :     pszDomain = CheckMetadataDomain(pszDomain);
    4908        1622 :     return CSLFetchNameValue(GetMetadata(pszDomain), pszName);
    4909             : }
    4910             : 
    4911             : /************************************************************************/
    4912             : /*                            SetMetadata()                             */
    4913             : /************************************************************************/
    4914             : 
    4915         133 : CPLErr GDALGeoPackageDataset::SetMetadata(char **papszMetadata,
    4916             :                                           const char *pszDomain)
    4917             : {
    4918         133 :     pszDomain = CheckMetadataDomain(pszDomain);
    4919         133 :     m_bMetadataDirty = true;
    4920         133 :     GetMetadata(); /* force loading from storage if needed */
    4921         133 :     return GDALPamDataset::SetMetadata(papszMetadata, pszDomain);
    4922             : }
    4923             : 
    4924             : /************************************************************************/
    4925             : /*                          SetMetadataItem()                           */
    4926             : /************************************************************************/
    4927             : 
    4928          21 : CPLErr GDALGeoPackageDataset::SetMetadataItem(const char *pszName,
    4929             :                                               const char *pszValue,
    4930             :                                               const char *pszDomain)
    4931             : {
    4932          21 :     pszDomain = CheckMetadataDomain(pszDomain);
    4933          21 :     m_bMetadataDirty = true;
    4934          21 :     GetMetadata(); /* force loading from storage if needed */
    4935          21 :     return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    4936             : }
    4937             : 
    4938             : /************************************************************************/
    4939             : /*                                Create()                              */
    4940             : /************************************************************************/
    4941             : 
    4942         966 : int GDALGeoPackageDataset::Create(const char *pszFilename, int nXSize,
    4943             :                                   int nYSize, int nBandsIn, GDALDataType eDT,
    4944             :                                   char **papszOptions)
    4945             : {
    4946        1932 :     CPLString osCommand;
    4947             : 
    4948             :     /* First, ensure there isn't any such file yet. */
    4949             :     VSIStatBufL sStatBuf;
    4950             : 
    4951         966 :     if (nBandsIn != 0)
    4952             :     {
    4953         226 :         if (eDT == GDT_Byte)
    4954             :         {
    4955         156 :             if (nBandsIn != 1 && nBandsIn != 2 && nBandsIn != 3 &&
    4956             :                 nBandsIn != 4)
    4957             :             {
    4958           1 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4959             :                          "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), "
    4960             :                          "3 (RGB) or 4 (RGBA) band dataset supported for "
    4961             :                          "Byte datatype");
    4962           1 :                 return FALSE;
    4963             :             }
    4964             :         }
    4965          70 :         else if (eDT == GDT_Int16 || eDT == GDT_UInt16 || eDT == GDT_Float32)
    4966             :         {
    4967          43 :             if (nBandsIn != 1)
    4968             :             {
    4969           3 :                 CPLError(CE_Failure, CPLE_NotSupported,
    4970             :                          "Only single band dataset supported for non Byte "
    4971             :                          "datatype");
    4972           3 :                 return FALSE;
    4973             :             }
    4974             :         }
    4975             :         else
    4976             :         {
    4977          27 :             CPLError(CE_Failure, CPLE_NotSupported,
    4978             :                      "Only Byte, Int16, UInt16 or Float32 supported");
    4979          27 :             return FALSE;
    4980             :         }
    4981             :     }
    4982             : 
    4983         935 :     const size_t nFilenameLen = strlen(pszFilename);
    4984         935 :     const bool bGpkgZip =
    4985         930 :         (nFilenameLen > strlen(".gpkg.zip") &&
    4986        1865 :          !STARTS_WITH(pszFilename, "/vsizip/") &&
    4987         930 :          EQUAL(pszFilename + nFilenameLen - strlen(".gpkg.zip"), ".gpkg.zip"));
    4988             : 
    4989             :     const bool bUseTempFile =
    4990         936 :         bGpkgZip || (CPLTestBool(CPLGetConfigOption(
    4991           1 :                          "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", "NO")) &&
    4992           1 :                      (VSIHasOptimizedReadMultiRange(pszFilename) != FALSE ||
    4993           1 :                       EQUAL(CPLGetConfigOption(
    4994             :                                 "CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE", ""),
    4995         935 :                             "FORCED")));
    4996             : 
    4997         935 :     bool bFileExists = false;
    4998         935 :     if (VSIStatL(pszFilename, &sStatBuf) == 0)
    4999             :     {
    5000          10 :         bFileExists = true;
    5001          20 :         if (nBandsIn == 0 || bUseTempFile ||
    5002          10 :             !CPLTestBool(
    5003             :                 CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")))
    5004             :         {
    5005           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5006             :                      "A file system object called '%s' already exists.",
    5007             :                      pszFilename);
    5008             : 
    5009           0 :             return FALSE;
    5010             :         }
    5011             :     }
    5012             : 
    5013         935 :     if (bUseTempFile)
    5014             :     {
    5015           3 :         if (bGpkgZip)
    5016             :         {
    5017           2 :             std::string osFilenameInZip(CPLGetFilename(pszFilename));
    5018           2 :             osFilenameInZip.resize(osFilenameInZip.size() - strlen(".zip"));
    5019             :             m_osFinalFilename =
    5020           2 :                 std::string("/vsizip/{") + pszFilename + "}/" + osFilenameInZip;
    5021             :         }
    5022             :         else
    5023             :         {
    5024           1 :             m_osFinalFilename = pszFilename;
    5025             :         }
    5026           3 :         m_pszFilename = CPLStrdup(
    5027           6 :             CPLGenerateTempFilenameSafe(CPLGetFilename(pszFilename)).c_str());
    5028           3 :         CPLDebug("GPKG", "Creating temporary file %s", m_pszFilename);
    5029             :     }
    5030             :     else
    5031             :     {
    5032         932 :         m_pszFilename = CPLStrdup(pszFilename);
    5033             :     }
    5034         935 :     m_bNew = true;
    5035         935 :     eAccess = GA_Update;
    5036         935 :     m_bDateTimeWithTZ =
    5037         935 :         EQUAL(CSLFetchNameValueDef(papszOptions, "DATETIME_FORMAT", "WITH_TZ"),
    5038             :               "WITH_TZ");
    5039             : 
    5040             :     // for test/debug purposes only. true is the nominal value
    5041         935 :     m_bPNGSupports2Bands =
    5042         935 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_2BANDS", "TRUE"));
    5043         935 :     m_bPNGSupportsCT =
    5044         935 :         CPLTestBool(CPLGetConfigOption("GPKG_PNG_SUPPORTS_CT", "TRUE"));
    5045             : 
    5046         935 :     if (!OpenOrCreateDB(bFileExists
    5047             :                             ? SQLITE_OPEN_READWRITE
    5048             :                             : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE))
    5049           7 :         return FALSE;
    5050             : 
    5051             :     /* Default to synchronous=off for performance for new file */
    5052        1846 :     if (!bFileExists &&
    5053         918 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5054             :     {
    5055         419 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5056             :     }
    5057             : 
    5058             :     /* OGR UTF-8 support. If we set the UTF-8 Pragma early on, it */
    5059             :     /* will be written into the main file and supported henceforth */
    5060         928 :     SQLCommand(hDB, "PRAGMA encoding = \"UTF-8\"");
    5061             : 
    5062         928 :     if (bFileExists)
    5063             :     {
    5064          10 :         VSILFILE *fp = VSIFOpenL(pszFilename, "rb");
    5065          10 :         if (fp)
    5066             :         {
    5067             :             GByte abyHeader[100];
    5068          10 :             VSIFReadL(abyHeader, 1, sizeof(abyHeader), fp);
    5069          10 :             VSIFCloseL(fp);
    5070             : 
    5071          10 :             memcpy(&m_nApplicationId, abyHeader + knApplicationIdPos, 4);
    5072          10 :             m_nApplicationId = CPL_MSBWORD32(m_nApplicationId);
    5073          10 :             memcpy(&m_nUserVersion, abyHeader + knUserVersionPos, 4);
    5074          10 :             m_nUserVersion = CPL_MSBWORD32(m_nUserVersion);
    5075             : 
    5076          10 :             if (m_nApplicationId == GP10_APPLICATION_ID)
    5077             :             {
    5078           0 :                 CPLDebug("GPKG", "GeoPackage v1.0");
    5079             :             }
    5080          10 :             else if (m_nApplicationId == GP11_APPLICATION_ID)
    5081             :             {
    5082           0 :                 CPLDebug("GPKG", "GeoPackage v1.1");
    5083             :             }
    5084          10 :             else if (m_nApplicationId == GPKG_APPLICATION_ID &&
    5085          10 :                      m_nUserVersion >= GPKG_1_2_VERSION)
    5086             :             {
    5087          10 :                 CPLDebug("GPKG", "GeoPackage v%d.%d.%d", m_nUserVersion / 10000,
    5088          10 :                          (m_nUserVersion % 10000) / 100, m_nUserVersion % 100);
    5089             :             }
    5090             :         }
    5091             : 
    5092          10 :         DetectSpatialRefSysColumns();
    5093             :     }
    5094             : 
    5095         928 :     const char *pszVersion = CSLFetchNameValue(papszOptions, "VERSION");
    5096         928 :     if (pszVersion && !EQUAL(pszVersion, "AUTO"))
    5097             :     {
    5098          40 :         if (EQUAL(pszVersion, "1.0"))
    5099             :         {
    5100           2 :             m_nApplicationId = GP10_APPLICATION_ID;
    5101           2 :             m_nUserVersion = 0;
    5102             :         }
    5103          38 :         else if (EQUAL(pszVersion, "1.1"))
    5104             :         {
    5105           1 :             m_nApplicationId = GP11_APPLICATION_ID;
    5106           1 :             m_nUserVersion = 0;
    5107             :         }
    5108          37 :         else if (EQUAL(pszVersion, "1.2"))
    5109             :         {
    5110          15 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5111          15 :             m_nUserVersion = GPKG_1_2_VERSION;
    5112             :         }
    5113          22 :         else if (EQUAL(pszVersion, "1.3"))
    5114             :         {
    5115           3 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5116           3 :             m_nUserVersion = GPKG_1_3_VERSION;
    5117             :         }
    5118          19 :         else if (EQUAL(pszVersion, "1.4"))
    5119             :         {
    5120          19 :             m_nApplicationId = GPKG_APPLICATION_ID;
    5121          19 :             m_nUserVersion = GPKG_1_4_VERSION;
    5122             :         }
    5123             :     }
    5124             : 
    5125         928 :     SoftStartTransaction();
    5126             : 
    5127        1856 :     CPLString osSQL;
    5128         928 :     if (!bFileExists)
    5129             :     {
    5130             :         /* Requirement 10: A GeoPackage SHALL include a gpkg_spatial_ref_sys
    5131             :          * table */
    5132             :         /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5133             :         osSQL = "CREATE TABLE gpkg_spatial_ref_sys ("
    5134             :                 "srs_name TEXT NOT NULL,"
    5135             :                 "srs_id INTEGER NOT NULL PRIMARY KEY,"
    5136             :                 "organization TEXT NOT NULL,"
    5137             :                 "organization_coordsys_id INTEGER NOT NULL,"
    5138             :                 "definition  TEXT NOT NULL,"
    5139         918 :                 "description TEXT";
    5140         918 :         if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "CRS_WKT_EXTENSION",
    5141        1099 :                                              "NO")) ||
    5142         181 :             (nBandsIn != 0 && eDT != GDT_Byte))
    5143             :         {
    5144          42 :             m_bHasDefinition12_063 = true;
    5145          42 :             osSQL += ", definition_12_063 TEXT NOT NULL";
    5146          42 :             if (m_nUserVersion >= GPKG_1_4_VERSION)
    5147             :             {
    5148          40 :                 osSQL += ", epoch DOUBLE";
    5149          40 :                 m_bHasEpochColumn = true;
    5150             :             }
    5151             :         }
    5152             :         osSQL += ")"
    5153             :                  ";"
    5154             :                  /* Requirement 11: The gpkg_spatial_ref_sys table in a
    5155             :                     GeoPackage SHALL */
    5156             :                  /* contain a record for EPSG:4326, the geodetic WGS84 SRS */
    5157             :                  /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5158             : 
    5159             :                  "INSERT INTO gpkg_spatial_ref_sys ("
    5160             :                  "srs_name, srs_id, organization, organization_coordsys_id, "
    5161         918 :                  "definition, description";
    5162         918 :         if (m_bHasDefinition12_063)
    5163          42 :             osSQL += ", definition_12_063";
    5164             :         osSQL +=
    5165             :             ") VALUES ("
    5166             :             "'WGS 84 geodetic', 4326, 'EPSG', 4326, '"
    5167             :             "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS "
    5168             :             "84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],"
    5169             :             "AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY["
    5170             :             "\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY["
    5171             :             "\"EPSG\",\"9122\"]],AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\","
    5172             :             "EAST],AUTHORITY[\"EPSG\",\"4326\"]]"
    5173             :             "', 'longitude/latitude coordinates in decimal degrees on the WGS "
    5174         918 :             "84 spheroid'";
    5175         918 :         if (m_bHasDefinition12_063)
    5176             :             osSQL +=
    5177             :                 ", 'GEODCRS[\"WGS 84\", DATUM[\"World Geodetic System 1984\", "
    5178             :                 "ELLIPSOID[\"WGS 84\",6378137, 298.257223563, "
    5179             :                 "LENGTHUNIT[\"metre\", 1.0]]], PRIMEM[\"Greenwich\", 0.0, "
    5180             :                 "ANGLEUNIT[\"degree\",0.0174532925199433]], CS[ellipsoidal, "
    5181             :                 "2], AXIS[\"latitude\", north, ORDER[1]], AXIS[\"longitude\", "
    5182             :                 "east, ORDER[2]], ANGLEUNIT[\"degree\", 0.0174532925199433], "
    5183          42 :                 "ID[\"EPSG\", 4326]]'";
    5184             :         osSQL +=
    5185             :             ")"
    5186             :             ";"
    5187             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5188             :                SHALL */
    5189             :             /* contain a record with an srs_id of -1, an organization of “NONE”,
    5190             :              */
    5191             :             /* an organization_coordsys_id of -1, and definition “undefined” */
    5192             :             /* for undefined Cartesian coordinate reference systems */
    5193             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5194             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5195             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5196         918 :             "definition, description";
    5197         918 :         if (m_bHasDefinition12_063)
    5198          42 :             osSQL += ", definition_12_063";
    5199             :         osSQL += ") VALUES ("
    5200             :                  "'Undefined Cartesian SRS', -1, 'NONE', -1, 'undefined', "
    5201         918 :                  "'undefined Cartesian coordinate reference system'";
    5202         918 :         if (m_bHasDefinition12_063)
    5203          42 :             osSQL += ", 'undefined'";
    5204             :         osSQL +=
    5205             :             ")"
    5206             :             ";"
    5207             :             /* Requirement 11: The gpkg_spatial_ref_sys table in a GeoPackage
    5208             :                SHALL */
    5209             :             /* contain a record with an srs_id of 0, an organization of “NONE”,
    5210             :              */
    5211             :             /* an organization_coordsys_id of 0, and definition “undefined” */
    5212             :             /* for undefined geographic coordinate reference systems */
    5213             :             /* http://opengis.github.io/geopackage/#spatial_ref_sys */
    5214             :             "INSERT INTO gpkg_spatial_ref_sys ("
    5215             :             "srs_name, srs_id, organization, organization_coordsys_id, "
    5216         918 :             "definition, description";
    5217         918 :         if (m_bHasDefinition12_063)
    5218          42 :             osSQL += ", definition_12_063";
    5219             :         osSQL += ") VALUES ("
    5220             :                  "'Undefined geographic SRS', 0, 'NONE', 0, 'undefined', "
    5221         918 :                  "'undefined geographic coordinate reference system'";
    5222         918 :         if (m_bHasDefinition12_063)
    5223          42 :             osSQL += ", 'undefined'";
    5224             :         osSQL += ")"
    5225             :                  ";"
    5226             :                  /* Requirement 13: A GeoPackage file SHALL include a
    5227             :                     gpkg_contents table */
    5228             :                  /* http://opengis.github.io/geopackage/#_contents */
    5229             :                  "CREATE TABLE gpkg_contents ("
    5230             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5231             :                  "data_type TEXT NOT NULL,"
    5232             :                  "identifier TEXT UNIQUE,"
    5233             :                  "description TEXT DEFAULT '',"
    5234             :                  "last_change DATETIME NOT NULL DEFAULT "
    5235             :                  "(strftime('%Y-%m-%dT%H:%M:%fZ','now')),"
    5236             :                  "min_x DOUBLE, min_y DOUBLE,"
    5237             :                  "max_x DOUBLE, max_y DOUBLE,"
    5238             :                  "srs_id INTEGER,"
    5239             :                  "CONSTRAINT fk_gc_r_srs_id FOREIGN KEY (srs_id) REFERENCES "
    5240             :                  "gpkg_spatial_ref_sys(srs_id)"
    5241         918 :                  ")";
    5242             : 
    5243             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5244         918 :         if (CPLFetchBool(papszOptions, "ADD_GPKG_OGR_CONTENTS", true))
    5245             :         {
    5246         913 :             m_bHasGPKGOGRContents = true;
    5247             :             osSQL += ";"
    5248             :                      "CREATE TABLE gpkg_ogr_contents("
    5249             :                      "table_name TEXT NOT NULL PRIMARY KEY,"
    5250             :                      "feature_count INTEGER DEFAULT NULL"
    5251         913 :                      ")";
    5252             :         }
    5253             : #endif
    5254             : 
    5255             :         /* Requirement 21: A GeoPackage with a gpkg_contents table row with a
    5256             :          * “features” */
    5257             :         /* data_type SHALL contain a gpkg_geometry_columns table or updateable
    5258             :          * view */
    5259             :         /* http://opengis.github.io/geopackage/#_geometry_columns */
    5260             :         const bool bCreateGeometryColumns =
    5261         918 :             CPLTestBool(CPLGetConfigOption("CREATE_GEOMETRY_COLUMNS", "YES"));
    5262         918 :         if (bCreateGeometryColumns)
    5263             :         {
    5264         917 :             m_bHasGPKGGeometryColumns = true;
    5265         917 :             osSQL += ";";
    5266         917 :             osSQL += pszCREATE_GPKG_GEOMETRY_COLUMNS;
    5267             :         }
    5268             :     }
    5269             : 
    5270             :     const bool bCreateTriggers =
    5271         928 :         CPLTestBool(CPLGetConfigOption("CREATE_TRIGGERS", "YES"));
    5272          10 :     if ((bFileExists && nBandsIn != 0 &&
    5273          10 :          SQLGetInteger(
    5274             :              hDB,
    5275             :              "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_tile_matrix_set' "
    5276             :              "AND type in ('table', 'view')",
    5277        1856 :              nullptr) == 0) ||
    5278         927 :         (!bFileExists &&
    5279         918 :          CPLTestBool(CPLGetConfigOption("CREATE_RASTER_TABLES", "YES"))))
    5280             :     {
    5281         918 :         if (!osSQL.empty())
    5282         917 :             osSQL += ";";
    5283             : 
    5284             :         /* From C.5. gpkg_tile_matrix_set Table 28. gpkg_tile_matrix_set Table
    5285             :          * Creation SQL  */
    5286             :         osSQL += "CREATE TABLE gpkg_tile_matrix_set ("
    5287             :                  "table_name TEXT NOT NULL PRIMARY KEY,"
    5288             :                  "srs_id INTEGER NOT NULL,"
    5289             :                  "min_x DOUBLE NOT NULL,"
    5290             :                  "min_y DOUBLE NOT NULL,"
    5291             :                  "max_x DOUBLE NOT NULL,"
    5292             :                  "max_y DOUBLE NOT NULL,"
    5293             :                  "CONSTRAINT fk_gtms_table_name FOREIGN KEY (table_name) "
    5294             :                  "REFERENCES gpkg_contents(table_name),"
    5295             :                  "CONSTRAINT fk_gtms_srs FOREIGN KEY (srs_id) REFERENCES "
    5296             :                  "gpkg_spatial_ref_sys (srs_id)"
    5297             :                  ")"
    5298             :                  ";"
    5299             : 
    5300             :                  /* From C.6. gpkg_tile_matrix Table 29. gpkg_tile_matrix Table
    5301             :                     Creation SQL */
    5302             :                  "CREATE TABLE gpkg_tile_matrix ("
    5303             :                  "table_name TEXT NOT NULL,"
    5304             :                  "zoom_level INTEGER NOT NULL,"
    5305             :                  "matrix_width INTEGER NOT NULL,"
    5306             :                  "matrix_height INTEGER NOT NULL,"
    5307             :                  "tile_width INTEGER NOT NULL,"
    5308             :                  "tile_height INTEGER NOT NULL,"
    5309             :                  "pixel_x_size DOUBLE NOT NULL,"
    5310             :                  "pixel_y_size DOUBLE NOT NULL,"
    5311             :                  "CONSTRAINT pk_ttm PRIMARY KEY (table_name, zoom_level),"
    5312             :                  "CONSTRAINT fk_tmm_table_name FOREIGN KEY (table_name) "
    5313             :                  "REFERENCES gpkg_contents(table_name)"
    5314         918 :                  ")";
    5315             : 
    5316         918 :         if (bCreateTriggers)
    5317             :         {
    5318             :             /* From D.1. gpkg_tile_matrix Table 39. gpkg_tile_matrix Trigger
    5319             :              * Definition SQL */
    5320         918 :             const char *pszTileMatrixTrigger =
    5321             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_insert' "
    5322             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5323             :                 "FOR EACH ROW BEGIN "
    5324             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5325             :                 "violates constraint: zoom_level cannot be less than 0') "
    5326             :                 "WHERE (NEW.zoom_level < 0); "
    5327             :                 "END; "
    5328             :                 "CREATE TRIGGER 'gpkg_tile_matrix_zoom_level_update' "
    5329             :                 "BEFORE UPDATE of zoom_level ON 'gpkg_tile_matrix' "
    5330             :                 "FOR EACH ROW BEGIN "
    5331             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5332             :                 "violates constraint: zoom_level cannot be less than 0') "
    5333             :                 "WHERE (NEW.zoom_level < 0); "
    5334             :                 "END; "
    5335             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_insert' "
    5336             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5337             :                 "FOR EACH ROW BEGIN "
    5338             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5339             :                 "violates constraint: matrix_width cannot be less than 1') "
    5340             :                 "WHERE (NEW.matrix_width < 1); "
    5341             :                 "END; "
    5342             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_width_update' "
    5343             :                 "BEFORE UPDATE OF matrix_width ON 'gpkg_tile_matrix' "
    5344             :                 "FOR EACH ROW BEGIN "
    5345             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5346             :                 "violates constraint: matrix_width cannot be less than 1') "
    5347             :                 "WHERE (NEW.matrix_width < 1); "
    5348             :                 "END; "
    5349             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_insert' "
    5350             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5351             :                 "FOR EACH ROW BEGIN "
    5352             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5353             :                 "violates constraint: matrix_height cannot be less than 1') "
    5354             :                 "WHERE (NEW.matrix_height < 1); "
    5355             :                 "END; "
    5356             :                 "CREATE TRIGGER 'gpkg_tile_matrix_matrix_height_update' "
    5357             :                 "BEFORE UPDATE OF matrix_height ON 'gpkg_tile_matrix' "
    5358             :                 "FOR EACH ROW BEGIN "
    5359             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5360             :                 "violates constraint: matrix_height cannot be less than 1') "
    5361             :                 "WHERE (NEW.matrix_height < 1); "
    5362             :                 "END; "
    5363             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_insert' "
    5364             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5365             :                 "FOR EACH ROW BEGIN "
    5366             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5367             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5368             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5369             :                 "END; "
    5370             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_x_size_update' "
    5371             :                 "BEFORE UPDATE OF pixel_x_size ON 'gpkg_tile_matrix' "
    5372             :                 "FOR EACH ROW BEGIN "
    5373             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5374             :                 "violates constraint: pixel_x_size must be greater than 0') "
    5375             :                 "WHERE NOT (NEW.pixel_x_size > 0); "
    5376             :                 "END; "
    5377             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_insert' "
    5378             :                 "BEFORE INSERT ON 'gpkg_tile_matrix' "
    5379             :                 "FOR EACH ROW BEGIN "
    5380             :                 "SELECT RAISE(ABORT, 'insert on table ''gpkg_tile_matrix'' "
    5381             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5382             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5383             :                 "END; "
    5384             :                 "CREATE TRIGGER 'gpkg_tile_matrix_pixel_y_size_update' "
    5385             :                 "BEFORE UPDATE OF pixel_y_size ON 'gpkg_tile_matrix' "
    5386             :                 "FOR EACH ROW BEGIN "
    5387             :                 "SELECT RAISE(ABORT, 'update on table ''gpkg_tile_matrix'' "
    5388             :                 "violates constraint: pixel_y_size must be greater than 0') "
    5389             :                 "WHERE NOT (NEW.pixel_y_size > 0); "
    5390             :                 "END;";
    5391         918 :             osSQL += ";";
    5392         918 :             osSQL += pszTileMatrixTrigger;
    5393             :         }
    5394             :     }
    5395             : 
    5396         928 :     if (!osSQL.empty() && OGRERR_NONE != SQLCommand(hDB, osSQL))
    5397           1 :         return FALSE;
    5398             : 
    5399         927 :     if (!bFileExists)
    5400             :     {
    5401             :         const char *pszMetadataTables =
    5402         917 :             CSLFetchNameValue(papszOptions, "METADATA_TABLES");
    5403         917 :         if (pszMetadataTables)
    5404           9 :             m_nCreateMetadataTables = int(CPLTestBool(pszMetadataTables));
    5405             : 
    5406         917 :         if (m_nCreateMetadataTables == TRUE && !CreateMetadataTables())
    5407           0 :             return FALSE;
    5408             : 
    5409         917 :         if (m_bHasDefinition12_063)
    5410             :         {
    5411          84 :             if (OGRERR_NONE != CreateExtensionsTableIfNecessary() ||
    5412             :                 OGRERR_NONE !=
    5413          42 :                     SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5414             :                                     "(table_name, column_name, extension_name, "
    5415             :                                     "definition, scope) "
    5416             :                                     "VALUES "
    5417             :                                     "('gpkg_spatial_ref_sys', "
    5418             :                                     "'definition_12_063', 'gpkg_crs_wkt', "
    5419             :                                     "'http://www.geopackage.org/spec120/"
    5420             :                                     "#extension_crs_wkt', 'read-write')"))
    5421             :             {
    5422           0 :                 return FALSE;
    5423             :             }
    5424          42 :             if (m_bHasEpochColumn)
    5425             :             {
    5426          40 :                 if (OGRERR_NONE !=
    5427          40 :                         SQLCommand(
    5428             :                             hDB, "UPDATE gpkg_extensions SET extension_name = "
    5429             :                                  "'gpkg_crs_wkt_1_1' "
    5430          80 :                                  "WHERE extension_name = 'gpkg_crs_wkt'") ||
    5431             :                     OGRERR_NONE !=
    5432          40 :                         SQLCommand(hDB, "INSERT INTO gpkg_extensions "
    5433             :                                         "(table_name, column_name, "
    5434             :                                         "extension_name, definition, scope) "
    5435             :                                         "VALUES "
    5436             :                                         "('gpkg_spatial_ref_sys', 'epoch', "
    5437             :                                         "'gpkg_crs_wkt_1_1', "
    5438             :                                         "'http://www.geopackage.org/spec/"
    5439             :                                         "#extension_crs_wkt', "
    5440             :                                         "'read-write')"))
    5441             :                 {
    5442           0 :                     return FALSE;
    5443             :                 }
    5444             :             }
    5445             :         }
    5446             :     }
    5447             : 
    5448         927 :     if (nBandsIn != 0)
    5449             :     {
    5450         190 :         const std::string osTableName = CPLGetBasenameSafe(m_pszFilename);
    5451             :         m_osRasterTable = CSLFetchNameValueDef(papszOptions, "RASTER_TABLE",
    5452         190 :                                                osTableName.c_str());
    5453         190 :         if (m_osRasterTable.empty())
    5454             :         {
    5455           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5456             :                      "RASTER_TABLE must be set to a non empty value");
    5457           0 :             return FALSE;
    5458             :         }
    5459         190 :         m_bIdentifierAsCO =
    5460         190 :             CSLFetchNameValue(papszOptions, "RASTER_IDENTIFIER") != nullptr;
    5461             :         m_osIdentifier = CSLFetchNameValueDef(papszOptions, "RASTER_IDENTIFIER",
    5462         190 :                                               m_osRasterTable);
    5463         190 :         m_bDescriptionAsCO =
    5464         190 :             CSLFetchNameValue(papszOptions, "RASTER_DESCRIPTION") != nullptr;
    5465             :         m_osDescription =
    5466         190 :             CSLFetchNameValueDef(papszOptions, "RASTER_DESCRIPTION", "");
    5467         190 :         SetDataType(eDT);
    5468         190 :         if (eDT == GDT_Int16)
    5469          16 :             SetGlobalOffsetScale(-32768.0, 1.0);
    5470             : 
    5471             :         /* From C.7. sample_tile_pyramid (Informative) Table 31. EXAMPLE: tiles
    5472             :          * table Create Table SQL (Informative) */
    5473             :         char *pszSQL =
    5474         190 :             sqlite3_mprintf("CREATE TABLE \"%w\" ("
    5475             :                             "id INTEGER PRIMARY KEY AUTOINCREMENT,"
    5476             :                             "zoom_level INTEGER NOT NULL,"
    5477             :                             "tile_column INTEGER NOT NULL,"
    5478             :                             "tile_row INTEGER NOT NULL,"
    5479             :                             "tile_data BLOB NOT NULL,"
    5480             :                             "UNIQUE (zoom_level, tile_column, tile_row)"
    5481             :                             ")",
    5482             :                             m_osRasterTable.c_str());
    5483         190 :         osSQL = pszSQL;
    5484         190 :         sqlite3_free(pszSQL);
    5485             : 
    5486         190 :         if (bCreateTriggers)
    5487             :         {
    5488         190 :             osSQL += ";";
    5489         190 :             osSQL += CreateRasterTriggersSQL(m_osRasterTable);
    5490             :         }
    5491             : 
    5492         190 :         OGRErr eErr = SQLCommand(hDB, osSQL);
    5493         190 :         if (OGRERR_NONE != eErr)
    5494           0 :             return FALSE;
    5495             : 
    5496         190 :         const char *pszTF = CSLFetchNameValue(papszOptions, "TILE_FORMAT");
    5497         190 :         if (eDT == GDT_Int16 || eDT == GDT_UInt16)
    5498             :         {
    5499          27 :             m_eTF = GPKG_TF_PNG_16BIT;
    5500          27 :             if (pszTF)
    5501             :             {
    5502           1 :                 if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "PNG"))
    5503             :                 {
    5504           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5505             :                              "Only AUTO or PNG supported "
    5506             :                              "as tile format for Int16 / UInt16");
    5507             :                 }
    5508             :             }
    5509             :         }
    5510         163 :         else if (eDT == GDT_Float32)
    5511             :         {
    5512          13 :             m_eTF = GPKG_TF_TIFF_32BIT_FLOAT;
    5513          13 :             if (pszTF)
    5514             :             {
    5515           5 :                 if (EQUAL(pszTF, "PNG"))
    5516           5 :                     m_eTF = GPKG_TF_PNG_16BIT;
    5517           0 :                 else if (!EQUAL(pszTF, "AUTO") && !EQUAL(pszTF, "TIFF"))
    5518             :                 {
    5519           0 :                     CPLError(CE_Warning, CPLE_NotSupported,
    5520             :                              "Only AUTO, PNG or TIFF supported "
    5521             :                              "as tile format for Float32");
    5522             :                 }
    5523             :             }
    5524             :         }
    5525             :         else
    5526             :         {
    5527         150 :             if (pszTF)
    5528             :             {
    5529          71 :                 m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    5530          71 :                 if (nBandsIn == 1 && m_eTF != GPKG_TF_PNG)
    5531           7 :                     m_bMetadataDirty = true;
    5532             :             }
    5533          79 :             else if (nBandsIn == 1)
    5534          68 :                 m_eTF = GPKG_TF_PNG;
    5535             :         }
    5536             : 
    5537         190 :         if (eDT != GDT_Byte)
    5538             :         {
    5539          40 :             if (!CreateTileGriddedTable(papszOptions))
    5540           0 :                 return FALSE;
    5541             :         }
    5542             : 
    5543         190 :         nRasterXSize = nXSize;
    5544         190 :         nRasterYSize = nYSize;
    5545             : 
    5546             :         const char *pszTileSize =
    5547         190 :             CSLFetchNameValueDef(papszOptions, "BLOCKSIZE", "256");
    5548             :         const char *pszTileWidth =
    5549         190 :             CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", pszTileSize);
    5550             :         const char *pszTileHeight =
    5551         190 :             CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", pszTileSize);
    5552         190 :         int nTileWidth = atoi(pszTileWidth);
    5553         190 :         int nTileHeight = atoi(pszTileHeight);
    5554         190 :         if ((nTileWidth < 8 || nTileWidth > 4096 || nTileHeight < 8 ||
    5555         380 :              nTileHeight > 4096) &&
    5556           1 :             !CPLTestBool(CPLGetConfigOption("GPKG_ALLOW_CRAZY_SETTINGS", "NO")))
    5557             :         {
    5558           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    5559             :                      "Invalid block dimensions: %dx%d", nTileWidth,
    5560             :                      nTileHeight);
    5561           0 :             return FALSE;
    5562             :         }
    5563             : 
    5564         513 :         for (int i = 1; i <= nBandsIn; i++)
    5565             :         {
    5566         323 :             SetBand(i, std::make_unique<GDALGeoPackageRasterBand>(
    5567             :                            this, nTileWidth, nTileHeight));
    5568             :         }
    5569             : 
    5570         190 :         GDALPamDataset::SetMetadataItem("INTERLEAVE", "PIXEL",
    5571             :                                         "IMAGE_STRUCTURE");
    5572         190 :         GDALPamDataset::SetMetadataItem("IDENTIFIER", m_osIdentifier);
    5573         190 :         if (!m_osDescription.empty())
    5574           1 :             GDALPamDataset::SetMetadataItem("DESCRIPTION", m_osDescription);
    5575             : 
    5576         190 :         ParseCompressionOptions(papszOptions);
    5577             : 
    5578         190 :         if (m_eTF == GPKG_TF_WEBP)
    5579             :         {
    5580          10 :             if (!RegisterWebPExtension())
    5581           0 :                 return FALSE;
    5582             :         }
    5583             : 
    5584             :         m_osTilingScheme =
    5585         190 :             CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5586         190 :         if (!EQUAL(m_osTilingScheme, "CUSTOM"))
    5587             :         {
    5588          22 :             const auto poTS = GetTilingScheme(m_osTilingScheme);
    5589          22 :             if (!poTS)
    5590           0 :                 return FALSE;
    5591             : 
    5592          43 :             if (nTileWidth != poTS->nTileWidth ||
    5593          21 :                 nTileHeight != poTS->nTileHeight)
    5594             :             {
    5595           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
    5596             :                          "Tile dimension should be %dx%d for %s tiling scheme",
    5597           1 :                          poTS->nTileWidth, poTS->nTileHeight,
    5598             :                          m_osTilingScheme.c_str());
    5599           1 :                 return FALSE;
    5600             :             }
    5601             : 
    5602             :             const char *pszZoomLevel =
    5603          21 :                 CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    5604          21 :             if (pszZoomLevel)
    5605             :             {
    5606           1 :                 m_nZoomLevel = atoi(pszZoomLevel);
    5607           1 :                 int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    5608           1 :                 while ((1 << nMaxZoomLevelForThisTM) >
    5609           2 :                            INT_MAX / poTS->nTileXCountZoomLevel0 ||
    5610           1 :                        (1 << nMaxZoomLevelForThisTM) >
    5611           1 :                            INT_MAX / poTS->nTileYCountZoomLevel0)
    5612             :                 {
    5613           0 :                     --nMaxZoomLevelForThisTM;
    5614             :                 }
    5615             : 
    5616           1 :                 if (m_nZoomLevel < 0 || m_nZoomLevel > nMaxZoomLevelForThisTM)
    5617             :                 {
    5618           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    5619             :                              "ZOOM_LEVEL = %s is invalid. It should be in "
    5620             :                              "[0,%d] range",
    5621             :                              pszZoomLevel, nMaxZoomLevelForThisTM);
    5622           0 :                     return FALSE;
    5623             :                 }
    5624             :             }
    5625             : 
    5626             :             // Implicitly sets SRS.
    5627          21 :             OGRSpatialReference oSRS;
    5628          21 :             if (oSRS.importFromEPSG(poTS->nEPSGCode) != OGRERR_NONE)
    5629           0 :                 return FALSE;
    5630          21 :             char *pszWKT = nullptr;
    5631          21 :             oSRS.exportToWkt(&pszWKT);
    5632          21 :             SetProjection(pszWKT);
    5633          21 :             CPLFree(pszWKT);
    5634             :         }
    5635             :         else
    5636             :         {
    5637         168 :             if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5638             :             {
    5639           0 :                 CPLError(
    5640             :                     CE_Failure, CPLE_NotSupported,
    5641             :                     "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5642           0 :                 return false;
    5643             :             }
    5644             :         }
    5645             :     }
    5646             : 
    5647         926 :     if (bFileExists && nBandsIn > 0 && eDT == GDT_Byte)
    5648             :     {
    5649             :         // If there was an ogr_empty_table table, we can remove it
    5650           9 :         RemoveOGREmptyTable();
    5651             :     }
    5652             : 
    5653         926 :     SoftCommitTransaction();
    5654             : 
    5655             :     /* Requirement 2 */
    5656             :     /* We have to do this after there's some content so the database file */
    5657             :     /* is not zero length */
    5658         926 :     SetApplicationAndUserVersionId();
    5659             : 
    5660             :     /* Default to synchronous=off for performance for new file */
    5661        1842 :     if (!bFileExists &&
    5662         916 :         CPLGetConfigOption("OGR_SQLITE_SYNCHRONOUS", nullptr) == nullptr)
    5663             :     {
    5664         419 :         SQLCommand(hDB, "PRAGMA synchronous = OFF");
    5665             :     }
    5666             : 
    5667         926 :     return TRUE;
    5668             : }
    5669             : 
    5670             : /************************************************************************/
    5671             : /*                        RemoveOGREmptyTable()                         */
    5672             : /************************************************************************/
    5673             : 
    5674         734 : void GDALGeoPackageDataset::RemoveOGREmptyTable()
    5675             : {
    5676             :     // Run with sqlite3_exec since we don't want errors to be emitted
    5677         734 :     sqlite3_exec(hDB, "DROP TABLE IF EXISTS ogr_empty_table", nullptr, nullptr,
    5678             :                  nullptr);
    5679         734 :     sqlite3_exec(
    5680             :         hDB, "DELETE FROM gpkg_contents WHERE table_name = 'ogr_empty_table'",
    5681             :         nullptr, nullptr, nullptr);
    5682             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    5683         734 :     if (m_bHasGPKGOGRContents)
    5684             :     {
    5685         720 :         sqlite3_exec(hDB,
    5686             :                      "DELETE FROM gpkg_ogr_contents WHERE "
    5687             :                      "table_name = 'ogr_empty_table'",
    5688             :                      nullptr, nullptr, nullptr);
    5689             :     }
    5690             : #endif
    5691         734 :     sqlite3_exec(hDB,
    5692             :                  "DELETE FROM gpkg_geometry_columns WHERE "
    5693             :                  "table_name = 'ogr_empty_table'",
    5694             :                  nullptr, nullptr, nullptr);
    5695         734 : }
    5696             : 
    5697             : /************************************************************************/
    5698             : /*                        CreateTileGriddedTable()                      */
    5699             : /************************************************************************/
    5700             : 
    5701          40 : bool GDALGeoPackageDataset::CreateTileGriddedTable(char **papszOptions)
    5702             : {
    5703          80 :     CPLString osSQL;
    5704          40 :     if (!HasGriddedCoverageAncillaryTable())
    5705             :     {
    5706             :         // It doesn't exist. So create gpkg_extensions table if necessary, and
    5707             :         // gpkg_2d_gridded_coverage_ancillary & gpkg_2d_gridded_tile_ancillary,
    5708             :         // and register them as extensions.
    5709          40 :         if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    5710           0 :             return false;
    5711             : 
    5712             :         // Req 1 /table-defs/coverage-ancillary
    5713             :         osSQL = "CREATE TABLE gpkg_2d_gridded_coverage_ancillary ("
    5714             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5715             :                 "tile_matrix_set_name TEXT NOT NULL UNIQUE,"
    5716             :                 "datatype TEXT NOT NULL DEFAULT 'integer',"
    5717             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5718             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5719             :                 "precision REAL DEFAULT 1.0,"
    5720             :                 "data_null REAL,"
    5721             :                 "grid_cell_encoding TEXT DEFAULT 'grid-value-is-center',"
    5722             :                 "uom TEXT,"
    5723             :                 "field_name TEXT DEFAULT 'Height',"
    5724             :                 "quantity_definition TEXT DEFAULT 'Height',"
    5725             :                 "CONSTRAINT fk_g2dgtct_name FOREIGN KEY(tile_matrix_set_name) "
    5726             :                 "REFERENCES gpkg_tile_matrix_set ( table_name ) "
    5727             :                 "CHECK (datatype in ('integer','float')))"
    5728             :                 ";"
    5729             :                 // Requirement 2 /table-defs/tile-ancillary
    5730             :                 "CREATE TABLE gpkg_2d_gridded_tile_ancillary ("
    5731             :                 "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
    5732             :                 "tpudt_name TEXT NOT NULL,"
    5733             :                 "tpudt_id INTEGER NOT NULL,"
    5734             :                 "scale REAL NOT NULL DEFAULT 1.0,"
    5735             :                 "offset REAL NOT NULL DEFAULT 0.0,"
    5736             :                 "min REAL DEFAULT NULL,"
    5737             :                 "max REAL DEFAULT NULL,"
    5738             :                 "mean REAL DEFAULT NULL,"
    5739             :                 "std_dev REAL DEFAULT NULL,"
    5740             :                 "CONSTRAINT fk_g2dgtat_name FOREIGN KEY (tpudt_name) "
    5741             :                 "REFERENCES gpkg_contents(table_name),"
    5742             :                 "UNIQUE (tpudt_name, tpudt_id))"
    5743             :                 ";"
    5744             :                 // Requirement 6 /gpkg-extensions
    5745             :                 "INSERT INTO gpkg_extensions "
    5746             :                 "(table_name, column_name, extension_name, definition, scope) "
    5747             :                 "VALUES ('gpkg_2d_gridded_coverage_ancillary', NULL, "
    5748             :                 "'gpkg_2d_gridded_coverage', "
    5749             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5750             :                 "'read-write')"
    5751             :                 ";"
    5752             :                 // Requirement 6 /gpkg-extensions
    5753             :                 "INSERT INTO gpkg_extensions "
    5754             :                 "(table_name, column_name, extension_name, definition, scope) "
    5755             :                 "VALUES ('gpkg_2d_gridded_tile_ancillary', NULL, "
    5756             :                 "'gpkg_2d_gridded_coverage', "
    5757             :                 "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5758             :                 "'read-write')"
    5759          40 :                 ";";
    5760             :     }
    5761             : 
    5762             :     // Requirement 6 /gpkg-extensions
    5763          40 :     char *pszSQL = sqlite3_mprintf(
    5764             :         "INSERT INTO gpkg_extensions "
    5765             :         "(table_name, column_name, extension_name, definition, scope) "
    5766             :         "VALUES ('%q', 'tile_data', "
    5767             :         "'gpkg_2d_gridded_coverage', "
    5768             :         "'http://docs.opengeospatial.org/is/17-066r1/17-066r1.html', "
    5769             :         "'read-write')",
    5770             :         m_osRasterTable.c_str());
    5771          40 :     osSQL += pszSQL;
    5772          40 :     osSQL += ";";
    5773          40 :     sqlite3_free(pszSQL);
    5774             : 
    5775             :     // Requirement 7 /gpkg-2d-gridded-coverage-ancillary
    5776             :     // Requirement 8 /gpkg-2d-gridded-coverage-ancillary-set-name
    5777             :     // Requirement 9 /gpkg-2d-gridded-coverage-ancillary-datatype
    5778          40 :     m_dfPrecision =
    5779          40 :         CPLAtof(CSLFetchNameValueDef(papszOptions, "PRECISION", "1"));
    5780             :     CPLString osGridCellEncoding(CSLFetchNameValueDef(
    5781          80 :         papszOptions, "GRID_CELL_ENCODING", "grid-value-is-center"));
    5782          40 :     m_bGridCellEncodingAsCO =
    5783          40 :         CSLFetchNameValue(papszOptions, "GRID_CELL_ENCODING") != nullptr;
    5784          80 :     CPLString osUom(CSLFetchNameValueDef(papszOptions, "UOM", ""));
    5785             :     CPLString osFieldName(
    5786          80 :         CSLFetchNameValueDef(papszOptions, "FIELD_NAME", "Height"));
    5787             :     CPLString osQuantityDefinition(
    5788          80 :         CSLFetchNameValueDef(papszOptions, "QUANTITY_DEFINITION", "Height"));
    5789             : 
    5790         121 :     pszSQL = sqlite3_mprintf(
    5791             :         "INSERT INTO gpkg_2d_gridded_coverage_ancillary "
    5792             :         "(tile_matrix_set_name, datatype, scale, offset, precision, "
    5793             :         "grid_cell_encoding, uom, field_name, quantity_definition) "
    5794             :         "VALUES (%Q, '%s', %.17g, %.17g, %.17g, %Q, %Q, %Q, %Q)",
    5795             :         m_osRasterTable.c_str(),
    5796          40 :         (m_eTF == GPKG_TF_PNG_16BIT) ? "integer" : "float", m_dfScale,
    5797             :         m_dfOffset, m_dfPrecision, osGridCellEncoding.c_str(),
    5798          41 :         osUom.empty() ? nullptr : osUom.c_str(), osFieldName.c_str(),
    5799             :         osQuantityDefinition.c_str());
    5800          40 :     m_osSQLInsertIntoGpkg2dGriddedCoverageAncillary = pszSQL;
    5801          40 :     sqlite3_free(pszSQL);
    5802             : 
    5803             :     // Requirement 3 /gpkg-spatial-ref-sys-row
    5804             :     auto oResultTable = SQLQuery(
    5805          80 :         hDB, "SELECT * FROM gpkg_spatial_ref_sys WHERE srs_id = 4979 LIMIT 2");
    5806          40 :     bool bHasEPSG4979 = (oResultTable && oResultTable->RowCount() == 1);
    5807          40 :     if (!bHasEPSG4979)
    5808             :     {
    5809          41 :         if (!m_bHasDefinition12_063 &&
    5810           1 :             !ConvertGpkgSpatialRefSysToExtensionWkt2(/*bForceEpoch=*/false))
    5811             :         {
    5812           0 :             return false;
    5813             :         }
    5814             : 
    5815             :         // This is WKT 2...
    5816          40 :         const char *pszWKT =
    5817             :             "GEODCRS[\"WGS 84\","
    5818             :             "DATUM[\"World Geodetic System 1984\","
    5819             :             "  ELLIPSOID[\"WGS 84\",6378137,298.257223563,"
    5820             :             "LENGTHUNIT[\"metre\",1.0]]],"
    5821             :             "CS[ellipsoidal,3],"
    5822             :             "  AXIS[\"latitude\",north,ORDER[1],ANGLEUNIT[\"degree\","
    5823             :             "0.0174532925199433]],"
    5824             :             "  AXIS[\"longitude\",east,ORDER[2],ANGLEUNIT[\"degree\","
    5825             :             "0.0174532925199433]],"
    5826             :             "  AXIS[\"ellipsoidal height\",up,ORDER[3],"
    5827             :             "LENGTHUNIT[\"metre\",1.0]],"
    5828             :             "ID[\"EPSG\",4979]]";
    5829             : 
    5830          40 :         pszSQL = sqlite3_mprintf(
    5831             :             "INSERT INTO gpkg_spatial_ref_sys "
    5832             :             "(srs_name,srs_id,organization,organization_coordsys_id,"
    5833             :             "definition,definition_12_063) VALUES "
    5834             :             "('WGS 84 3D', 4979, 'EPSG', 4979, 'undefined', '%q')",
    5835             :             pszWKT);
    5836          40 :         osSQL += ";";
    5837          40 :         osSQL += pszSQL;
    5838          40 :         sqlite3_free(pszSQL);
    5839             :     }
    5840             : 
    5841          40 :     return SQLCommand(hDB, osSQL) == OGRERR_NONE;
    5842             : }
    5843             : 
    5844             : /************************************************************************/
    5845             : /*                    HasGriddedCoverageAncillaryTable()                */
    5846             : /************************************************************************/
    5847             : 
    5848          44 : bool GDALGeoPackageDataset::HasGriddedCoverageAncillaryTable()
    5849             : {
    5850             :     auto oResultTable = SQLQuery(
    5851             :         hDB, "SELECT * FROM sqlite_master WHERE type IN ('table', 'view') AND "
    5852          44 :              "name = 'gpkg_2d_gridded_coverage_ancillary'");
    5853          44 :     bool bHasTable = (oResultTable && oResultTable->RowCount() == 1);
    5854          88 :     return bHasTable;
    5855             : }
    5856             : 
    5857             : /************************************************************************/
    5858             : /*                      GetUnderlyingDataset()                          */
    5859             : /************************************************************************/
    5860             : 
    5861           3 : static GDALDataset *GetUnderlyingDataset(GDALDataset *poSrcDS)
    5862             : {
    5863           3 :     if (auto poVRTDS = dynamic_cast<VRTDataset *>(poSrcDS))
    5864             :     {
    5865           0 :         auto poTmpDS = poVRTDS->GetSingleSimpleSource();
    5866           0 :         if (poTmpDS)
    5867           0 :             return poTmpDS;
    5868             :     }
    5869             : 
    5870           3 :     return poSrcDS;
    5871             : }
    5872             : 
    5873             : /************************************************************************/
    5874             : /*                            CreateCopy()                              */
    5875             : /************************************************************************/
    5876             : 
    5877             : typedef struct
    5878             : {
    5879             :     const char *pszName;
    5880             :     GDALResampleAlg eResampleAlg;
    5881             : } WarpResamplingAlg;
    5882             : 
    5883             : static const WarpResamplingAlg asResamplingAlg[] = {
    5884             :     {"NEAREST", GRA_NearestNeighbour},
    5885             :     {"BILINEAR", GRA_Bilinear},
    5886             :     {"CUBIC", GRA_Cubic},
    5887             :     {"CUBICSPLINE", GRA_CubicSpline},
    5888             :     {"LANCZOS", GRA_Lanczos},
    5889             :     {"MODE", GRA_Mode},
    5890             :     {"AVERAGE", GRA_Average},
    5891             :     {"RMS", GRA_RMS},
    5892             : };
    5893             : 
    5894         162 : GDALDataset *GDALGeoPackageDataset::CreateCopy(const char *pszFilename,
    5895             :                                                GDALDataset *poSrcDS,
    5896             :                                                int bStrict, char **papszOptions,
    5897             :                                                GDALProgressFunc pfnProgress,
    5898             :                                                void *pProgressData)
    5899             : {
    5900         162 :     const int nBands = poSrcDS->GetRasterCount();
    5901         162 :     if (nBands == 0)
    5902             :     {
    5903           2 :         GDALDataset *poDS = nullptr;
    5904             :         GDALDriver *poThisDriver =
    5905           2 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5906           2 :         if (poThisDriver != nullptr)
    5907             :         {
    5908           2 :             poDS = poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS,
    5909             :                                                    bStrict, papszOptions,
    5910             :                                                    pfnProgress, pProgressData);
    5911             :         }
    5912           2 :         return poDS;
    5913             :     }
    5914             : 
    5915             :     const char *pszTilingScheme =
    5916         160 :         CSLFetchNameValueDef(papszOptions, "TILING_SCHEME", "CUSTOM");
    5917             : 
    5918         320 :     CPLStringList apszUpdatedOptions(CSLDuplicate(papszOptions));
    5919         160 :     if (CPLTestBool(
    5920         166 :             CSLFetchNameValueDef(papszOptions, "APPEND_SUBDATASET", "NO")) &&
    5921           6 :         CSLFetchNameValue(papszOptions, "RASTER_TABLE") == nullptr)
    5922             :     {
    5923             :         const std::string osBasename(CPLGetBasenameSafe(
    5924           6 :             GetUnderlyingDataset(poSrcDS)->GetDescription()));
    5925           3 :         apszUpdatedOptions.SetNameValue("RASTER_TABLE", osBasename.c_str());
    5926             :     }
    5927             : 
    5928         160 :     if (nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4)
    5929             :     {
    5930           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    5931             :                  "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or "
    5932             :                  "4 (RGBA) band dataset supported");
    5933           1 :         return nullptr;
    5934             :     }
    5935             : 
    5936         159 :     const char *pszUnitType = poSrcDS->GetRasterBand(1)->GetUnitType();
    5937         318 :     if (CSLFetchNameValue(papszOptions, "UOM") == nullptr && pszUnitType &&
    5938         159 :         !EQUAL(pszUnitType, ""))
    5939             :     {
    5940           1 :         apszUpdatedOptions.SetNameValue("UOM", pszUnitType);
    5941             :     }
    5942             : 
    5943         159 :     if (EQUAL(pszTilingScheme, "CUSTOM"))
    5944             :     {
    5945         135 :         if (CSLFetchNameValue(papszOptions, "ZOOM_LEVEL"))
    5946             :         {
    5947           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    5948             :                      "ZOOM_LEVEL only supported for TILING_SCHEME != CUSTOM");
    5949           0 :             return nullptr;
    5950             :         }
    5951             : 
    5952         135 :         GDALGeoPackageDataset *poDS = nullptr;
    5953             :         GDALDriver *poThisDriver =
    5954         135 :             GDALDriver::FromHandle(GDALGetDriverByName("GPKG"));
    5955         135 :         if (poThisDriver != nullptr)
    5956             :         {
    5957         135 :             apszUpdatedOptions.SetNameValue("SKIP_HOLES", "YES");
    5958         135 :             poDS = cpl::down_cast<GDALGeoPackageDataset *>(
    5959             :                 poThisDriver->DefaultCreateCopy(pszFilename, poSrcDS, bStrict,
    5960             :                                                 apszUpdatedOptions, pfnProgress,
    5961         135 :                                                 pProgressData));
    5962             : 
    5963         250 :             if (poDS != nullptr &&
    5964         135 :                 poSrcDS->GetRasterBand(1)->GetRasterDataType() == GDT_Byte &&
    5965             :                 nBands <= 3)
    5966             :             {
    5967          75 :                 poDS->m_nBandCountFromMetadata = nBands;
    5968          75 :                 poDS->m_bMetadataDirty = true;
    5969             :             }
    5970             :         }
    5971         135 :         if (poDS)
    5972         115 :             poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    5973         135 :         return poDS;
    5974             :     }
    5975             : 
    5976          48 :     const auto poTS = GetTilingScheme(pszTilingScheme);
    5977          24 :     if (!poTS)
    5978             :     {
    5979           2 :         return nullptr;
    5980             :     }
    5981          22 :     const int nEPSGCode = poTS->nEPSGCode;
    5982             : 
    5983          44 :     OGRSpatialReference oSRS;
    5984          22 :     if (oSRS.importFromEPSG(nEPSGCode) != OGRERR_NONE)
    5985             :     {
    5986           0 :         return nullptr;
    5987             :     }
    5988          22 :     char *pszWKT = nullptr;
    5989          22 :     oSRS.exportToWkt(&pszWKT);
    5990          22 :     char **papszTO = CSLSetNameValue(nullptr, "DST_SRS", pszWKT);
    5991             : 
    5992          22 :     void *hTransformArg = nullptr;
    5993             : 
    5994             :     // Hack to compensate for GDALSuggestedWarpOutput2() failure (or not
    5995             :     // ideal suggestion with PROJ 8) when reprojecting latitude = +/- 90 to
    5996             :     // EPSG:3857.
    5997          22 :     GDALGeoTransform srcGT;
    5998          22 :     std::unique_ptr<GDALDataset> poTmpDS;
    5999          22 :     bool bEPSG3857Adjust = false;
    6000           8 :     if (nEPSGCode == 3857 && poSrcDS->GetGeoTransform(srcGT) == CE_None &&
    6001          30 :         srcGT[2] == 0 && srcGT[4] == 0 && srcGT[5] < 0)
    6002             :     {
    6003           8 :         const auto poSrcSRS = poSrcDS->GetSpatialRef();
    6004           8 :         if (poSrcSRS && poSrcSRS->IsGeographic())
    6005             :         {
    6006           2 :             double maxLat = srcGT[3];
    6007           2 :             double minLat = srcGT[3] + poSrcDS->GetRasterYSize() * srcGT[5];
    6008             :             // Corresponds to the latitude of below MAX_GM
    6009           2 :             constexpr double MAX_LAT = 85.0511287798066;
    6010           2 :             bool bModified = false;
    6011           2 :             if (maxLat > MAX_LAT)
    6012             :             {
    6013           2 :                 maxLat = MAX_LAT;
    6014           2 :                 bModified = true;
    6015             :             }
    6016           2 :             if (minLat < -MAX_LAT)
    6017             :             {
    6018           2 :                 minLat = -MAX_LAT;
    6019           2 :                 bModified = true;
    6020             :             }
    6021           2 :             if (bModified)
    6022             :             {
    6023           4 :                 CPLStringList aosOptions;
    6024           2 :                 aosOptions.AddString("-of");
    6025           2 :                 aosOptions.AddString("VRT");
    6026           2 :                 aosOptions.AddString("-projwin");
    6027           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", srcGT[0]));
    6028           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", maxLat));
    6029             :                 aosOptions.AddString(CPLSPrintf(
    6030           2 :                     "%.17g", srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1]));
    6031           2 :                 aosOptions.AddString(CPLSPrintf("%.17g", minLat));
    6032             :                 auto psOptions =
    6033           2 :                     GDALTranslateOptionsNew(aosOptions.List(), nullptr);
    6034           2 :                 poTmpDS.reset(GDALDataset::FromHandle(GDALTranslate(
    6035             :                     "", GDALDataset::ToHandle(poSrcDS), psOptions, nullptr)));
    6036           2 :                 GDALTranslateOptionsFree(psOptions);
    6037           2 :                 if (poTmpDS)
    6038             :                 {
    6039           2 :                     bEPSG3857Adjust = true;
    6040           2 :                     hTransformArg = GDALCreateGenImgProjTransformer2(
    6041           2 :                         GDALDataset::FromHandle(poTmpDS.get()), nullptr,
    6042             :                         papszTO);
    6043             :                 }
    6044             :             }
    6045             :         }
    6046             :     }
    6047          22 :     if (hTransformArg == nullptr)
    6048             :     {
    6049             :         hTransformArg =
    6050          20 :             GDALCreateGenImgProjTransformer2(poSrcDS, nullptr, papszTO);
    6051             :     }
    6052             : 
    6053          22 :     if (hTransformArg == nullptr)
    6054             :     {
    6055           1 :         CPLFree(pszWKT);
    6056           1 :         CSLDestroy(papszTO);
    6057           1 :         return nullptr;
    6058             :     }
    6059             : 
    6060          21 :     GDALTransformerInfo *psInfo =
    6061             :         static_cast<GDALTransformerInfo *>(hTransformArg);
    6062          21 :     GDALGeoTransform gt;
    6063             :     double adfExtent[4];
    6064             :     int nXSize, nYSize;
    6065             : 
    6066          21 :     if (GDALSuggestedWarpOutput2(poSrcDS, psInfo->pfnTransform, hTransformArg,
    6067             :                                  gt.data(), &nXSize, &nYSize, adfExtent,
    6068          21 :                                  0) != CE_None)
    6069             :     {
    6070           0 :         CPLFree(pszWKT);
    6071           0 :         CSLDestroy(papszTO);
    6072           0 :         GDALDestroyGenImgProjTransformer(hTransformArg);
    6073           0 :         return nullptr;
    6074             :     }
    6075             : 
    6076          21 :     GDALDestroyGenImgProjTransformer(hTransformArg);
    6077          21 :     hTransformArg = nullptr;
    6078          21 :     poTmpDS.reset();
    6079             : 
    6080          21 :     if (bEPSG3857Adjust)
    6081             :     {
    6082           2 :         constexpr double SPHERICAL_RADIUS = 6378137.0;
    6083           2 :         constexpr double MAX_GM =
    6084             :             SPHERICAL_RADIUS * M_PI;  // 20037508.342789244
    6085           2 :         double maxNorthing = gt[3];
    6086           2 :         double minNorthing = gt[3] + gt[5] * nYSize;
    6087           2 :         bool bChanged = false;
    6088           2 :         if (maxNorthing > MAX_GM)
    6089             :         {
    6090           2 :             bChanged = true;
    6091           2 :             maxNorthing = MAX_GM;
    6092             :         }
    6093           2 :         if (minNorthing < -MAX_GM)
    6094             :         {
    6095           2 :             bChanged = true;
    6096           2 :             minNorthing = -MAX_GM;
    6097             :         }
    6098           2 :         if (bChanged)
    6099             :         {
    6100           2 :             gt[3] = maxNorthing;
    6101           2 :             nYSize = int((maxNorthing - minNorthing) / (-gt[5]) + 0.5);
    6102           2 :             adfExtent[1] = maxNorthing + nYSize * gt[5];
    6103           2 :             adfExtent[3] = maxNorthing;
    6104             :         }
    6105             :     }
    6106             : 
    6107          21 :     double dfComputedRes = gt[1];
    6108          21 :     double dfPrevRes = 0.0;
    6109          21 :     double dfRes = 0.0;
    6110          21 :     int nZoomLevel = 0;  // Used after for.
    6111          21 :     const char *pszZoomLevel = CSLFetchNameValue(papszOptions, "ZOOM_LEVEL");
    6112          21 :     if (pszZoomLevel)
    6113             :     {
    6114           2 :         nZoomLevel = atoi(pszZoomLevel);
    6115             : 
    6116           2 :         int nMaxZoomLevelForThisTM = MAX_ZOOM_LEVEL;
    6117           2 :         while ((1 << nMaxZoomLevelForThisTM) >
    6118           4 :                    INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6119           2 :                (1 << nMaxZoomLevelForThisTM) >
    6120           2 :                    INT_MAX / poTS->nTileYCountZoomLevel0)
    6121             :         {
    6122           0 :             --nMaxZoomLevelForThisTM;
    6123             :         }
    6124             : 
    6125           2 :         if (nZoomLevel < 0 || nZoomLevel > nMaxZoomLevelForThisTM)
    6126             :         {
    6127           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6128             :                      "ZOOM_LEVEL = %s is invalid. It should be in [0,%d] range",
    6129             :                      pszZoomLevel, nMaxZoomLevelForThisTM);
    6130           1 :             CPLFree(pszWKT);
    6131           1 :             CSLDestroy(papszTO);
    6132           1 :             return nullptr;
    6133             :         }
    6134             :     }
    6135             :     else
    6136             :     {
    6137         171 :         for (; nZoomLevel < MAX_ZOOM_LEVEL; nZoomLevel++)
    6138             :         {
    6139         171 :             dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6140         171 :             if (dfComputedRes > dfRes ||
    6141         152 :                 fabs(dfComputedRes - dfRes) / dfRes <= 1e-8)
    6142             :                 break;
    6143         152 :             dfPrevRes = dfRes;
    6144             :         }
    6145          38 :         if (nZoomLevel == MAX_ZOOM_LEVEL ||
    6146          38 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileXCountZoomLevel0 ||
    6147          19 :             (1 << nZoomLevel) > INT_MAX / poTS->nTileYCountZoomLevel0)
    6148             :         {
    6149           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6150             :                      "Could not find an appropriate zoom level");
    6151           0 :             CPLFree(pszWKT);
    6152           0 :             CSLDestroy(papszTO);
    6153           0 :             return nullptr;
    6154             :         }
    6155             : 
    6156          19 :         if (nZoomLevel > 0 && fabs(dfComputedRes - dfRes) / dfRes > 1e-8)
    6157             :         {
    6158          17 :             const char *pszZoomLevelStrategy = CSLFetchNameValueDef(
    6159             :                 papszOptions, "ZOOM_LEVEL_STRATEGY", "AUTO");
    6160          17 :             if (EQUAL(pszZoomLevelStrategy, "LOWER"))
    6161             :             {
    6162           1 :                 nZoomLevel--;
    6163             :             }
    6164          16 :             else if (EQUAL(pszZoomLevelStrategy, "UPPER"))
    6165             :             {
    6166             :                 /* do nothing */
    6167             :             }
    6168             :             else
    6169             :             {
    6170          15 :                 if (dfPrevRes / dfComputedRes < dfComputedRes / dfRes)
    6171          13 :                     nZoomLevel--;
    6172             :             }
    6173             :         }
    6174             :     }
    6175             : 
    6176          20 :     dfRes = poTS->dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    6177             : 
    6178          20 :     double dfMinX = adfExtent[0];
    6179          20 :     double dfMinY = adfExtent[1];
    6180          20 :     double dfMaxX = adfExtent[2];
    6181          20 :     double dfMaxY = adfExtent[3];
    6182             : 
    6183          20 :     nXSize = static_cast<int>(0.5 + (dfMaxX - dfMinX) / dfRes);
    6184          20 :     nYSize = static_cast<int>(0.5 + (dfMaxY - dfMinY) / dfRes);
    6185          20 :     gt[1] = dfRes;
    6186          20 :     gt[5] = -dfRes;
    6187             : 
    6188          20 :     const GDALDataType eDT = poSrcDS->GetRasterBand(1)->GetRasterDataType();
    6189          20 :     int nTargetBands = nBands;
    6190             :     /* For grey level or RGB, if there's reprojection involved, add an alpha */
    6191             :     /* channel */
    6192          37 :     if (eDT == GDT_Byte &&
    6193          13 :         ((nBands == 1 &&
    6194          17 :           poSrcDS->GetRasterBand(1)->GetColorTable() == nullptr) ||
    6195             :          nBands == 3))
    6196             :     {
    6197          30 :         OGRSpatialReference oSrcSRS;
    6198          15 :         oSrcSRS.SetFromUserInput(poSrcDS->GetProjectionRef());
    6199          15 :         oSrcSRS.AutoIdentifyEPSG();
    6200          30 :         if (oSrcSRS.GetAuthorityCode(nullptr) == nullptr ||
    6201          15 :             atoi(oSrcSRS.GetAuthorityCode(nullptr)) != nEPSGCode)
    6202             :         {
    6203          13 :             nTargetBands++;
    6204             :         }
    6205             :     }
    6206             : 
    6207          20 :     GDALResampleAlg eResampleAlg = GRA_Bilinear;
    6208          20 :     const char *pszResampling = CSLFetchNameValue(papszOptions, "RESAMPLING");
    6209          20 :     if (pszResampling)
    6210             :     {
    6211           6 :         for (size_t iAlg = 0;
    6212           6 :              iAlg < sizeof(asResamplingAlg) / sizeof(asResamplingAlg[0]);
    6213             :              iAlg++)
    6214             :         {
    6215           6 :             if (EQUAL(pszResampling, asResamplingAlg[iAlg].pszName))
    6216             :             {
    6217           3 :                 eResampleAlg = asResamplingAlg[iAlg].eResampleAlg;
    6218           3 :                 break;
    6219             :             }
    6220             :         }
    6221             :     }
    6222             : 
    6223          16 :     if (nBands == 1 && poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    6224          36 :         eResampleAlg != GRA_NearestNeighbour && eResampleAlg != GRA_Mode)
    6225             :     {
    6226           0 :         CPLError(
    6227             :             CE_Warning, CPLE_AppDefined,
    6228             :             "Input dataset has a color table, which will likely lead to "
    6229             :             "bad results when using a resampling method other than "
    6230             :             "nearest neighbour or mode. Converting the dataset to 24/32 bit "
    6231             :             "(e.g. with gdal_translate -expand rgb/rgba) is advised.");
    6232             :     }
    6233             : 
    6234          40 :     auto poDS = std::make_unique<GDALGeoPackageDataset>();
    6235          20 :     if (!(poDS->Create(pszFilename, nXSize, nYSize, nTargetBands, eDT,
    6236             :                        apszUpdatedOptions)))
    6237             :     {
    6238           1 :         CPLFree(pszWKT);
    6239           1 :         CSLDestroy(papszTO);
    6240           1 :         return nullptr;
    6241             :     }
    6242             : 
    6243             :     // Assign nodata values before the SetGeoTransform call.
    6244             :     // SetGeoTransform will trigger creation of the overview datasets for each
    6245             :     // zoom level and at that point the nodata value needs to be known.
    6246          19 :     int bHasNoData = FALSE;
    6247             :     double dfNoDataValue =
    6248          19 :         poSrcDS->GetRasterBand(1)->GetNoDataValue(&bHasNoData);
    6249          19 :     if (eDT != GDT_Byte && bHasNoData)
    6250             :     {
    6251           3 :         poDS->GetRasterBand(1)->SetNoDataValue(dfNoDataValue);
    6252             :     }
    6253             : 
    6254          19 :     poDS->SetGeoTransform(gt);
    6255          19 :     poDS->SetProjection(pszWKT);
    6256          19 :     CPLFree(pszWKT);
    6257          19 :     pszWKT = nullptr;
    6258          24 :     if (nTargetBands == 1 && nBands == 1 &&
    6259           5 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
    6260             :     {
    6261           2 :         poDS->GetRasterBand(1)->SetColorTable(
    6262           1 :             poSrcDS->GetRasterBand(1)->GetColorTable());
    6263             :     }
    6264             : 
    6265             :     hTransformArg =
    6266          19 :         GDALCreateGenImgProjTransformer2(poSrcDS, poDS.get(), papszTO);
    6267          19 :     CSLDestroy(papszTO);
    6268          19 :     if (hTransformArg == nullptr)
    6269             :     {
    6270           0 :         return nullptr;
    6271             :     }
    6272             : 
    6273          19 :     poDS->SetMetadata(poSrcDS->GetMetadata());
    6274             : 
    6275             :     /* -------------------------------------------------------------------- */
    6276             :     /*      Warp the transformer with a linear approximator                 */
    6277             :     /* -------------------------------------------------------------------- */
    6278          19 :     hTransformArg = GDALCreateApproxTransformer(GDALGenImgProjTransform,
    6279             :                                                 hTransformArg, 0.125);
    6280          19 :     GDALApproxTransformerOwnsSubtransformer(hTransformArg, TRUE);
    6281             : 
    6282             :     /* -------------------------------------------------------------------- */
    6283             :     /*      Setup warp options.                                             */
    6284             :     /* -------------------------------------------------------------------- */
    6285          19 :     GDALWarpOptions *psWO = GDALCreateWarpOptions();
    6286             : 
    6287          19 :     psWO->papszWarpOptions = CSLSetNameValue(nullptr, "OPTIMIZE_SIZE", "YES");
    6288          19 :     psWO->papszWarpOptions =
    6289          19 :         CSLSetNameValue(psWO->papszWarpOptions, "SAMPLE_GRID", "YES");
    6290          19 :     if (bHasNoData)
    6291             :     {
    6292           3 :         if (dfNoDataValue == 0.0)
    6293             :         {
    6294             :             // Do not initialize in the case where nodata != 0, since we
    6295             :             // want the GeoPackage driver to return empty tiles at the nodata
    6296             :             // value instead of 0 as GDAL core would
    6297           0 :             psWO->papszWarpOptions =
    6298           0 :                 CSLSetNameValue(psWO->papszWarpOptions, "INIT_DEST", "0");
    6299             :         }
    6300             : 
    6301           3 :         psWO->padfSrcNoDataReal =
    6302           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6303           3 :         psWO->padfSrcNoDataReal[0] = dfNoDataValue;
    6304             : 
    6305           3 :         psWO->padfDstNoDataReal =
    6306           3 :             static_cast<double *>(CPLMalloc(sizeof(double)));
    6307           3 :         psWO->padfDstNoDataReal[0] = dfNoDataValue;
    6308             :     }
    6309          19 :     psWO->eWorkingDataType = eDT;
    6310          19 :     psWO->eResampleAlg = eResampleAlg;
    6311             : 
    6312          19 :     psWO->hSrcDS = poSrcDS;
    6313          19 :     psWO->hDstDS = poDS.get();
    6314             : 
    6315          19 :     psWO->pfnTransformer = GDALApproxTransform;
    6316          19 :     psWO->pTransformerArg = hTransformArg;
    6317             : 
    6318          19 :     psWO->pfnProgress = pfnProgress;
    6319          19 :     psWO->pProgressArg = pProgressData;
    6320             : 
    6321             :     /* -------------------------------------------------------------------- */
    6322             :     /*      Setup band mapping.                                             */
    6323             :     /* -------------------------------------------------------------------- */
    6324             : 
    6325          19 :     if (nBands == 2 || nBands == 4)
    6326           1 :         psWO->nBandCount = nBands - 1;
    6327             :     else
    6328          18 :         psWO->nBandCount = nBands;
    6329             : 
    6330          19 :     psWO->panSrcBands =
    6331          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6332          19 :     psWO->panDstBands =
    6333          19 :         static_cast<int *>(CPLMalloc(psWO->nBandCount * sizeof(int)));
    6334             : 
    6335          46 :     for (int i = 0; i < psWO->nBandCount; i++)
    6336             :     {
    6337          27 :         psWO->panSrcBands[i] = i + 1;
    6338          27 :         psWO->panDstBands[i] = i + 1;
    6339             :     }
    6340             : 
    6341          19 :     if (nBands == 2 || nBands == 4)
    6342             :     {
    6343           1 :         psWO->nSrcAlphaBand = nBands;
    6344             :     }
    6345          19 :     if (nTargetBands == 2 || nTargetBands == 4)
    6346             :     {
    6347          13 :         psWO->nDstAlphaBand = nTargetBands;
    6348             :     }
    6349             : 
    6350             :     /* -------------------------------------------------------------------- */
    6351             :     /*      Initialize and execute the warp.                                */
    6352             :     /* -------------------------------------------------------------------- */
    6353          38 :     GDALWarpOperation oWO;
    6354             : 
    6355          19 :     CPLErr eErr = oWO.Initialize(psWO);
    6356          19 :     if (eErr == CE_None)
    6357             :     {
    6358             :         /*if( bMulti )
    6359             :             eErr = oWO.ChunkAndWarpMulti( 0, 0, nXSize, nYSize );
    6360             :         else*/
    6361          19 :         eErr = oWO.ChunkAndWarpImage(0, 0, nXSize, nYSize);
    6362             :     }
    6363          19 :     if (eErr != CE_None)
    6364             :     {
    6365           0 :         poDS.reset();
    6366             :     }
    6367             : 
    6368          19 :     GDALDestroyTransformer(hTransformArg);
    6369          19 :     GDALDestroyWarpOptions(psWO);
    6370             : 
    6371          19 :     if (poDS)
    6372          19 :         poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    6373             : 
    6374          19 :     return poDS.release();
    6375             : }
    6376             : 
    6377             : /************************************************************************/
    6378             : /*                        ParseCompressionOptions()                     */
    6379             : /************************************************************************/
    6380             : 
    6381         459 : void GDALGeoPackageDataset::ParseCompressionOptions(char **papszOptions)
    6382             : {
    6383         459 :     const char *pszZLevel = CSLFetchNameValue(papszOptions, "ZLEVEL");
    6384         459 :     if (pszZLevel)
    6385           0 :         m_nZLevel = atoi(pszZLevel);
    6386             : 
    6387         459 :     const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
    6388         459 :     if (pszQuality)
    6389           0 :         m_nQuality = atoi(pszQuality);
    6390             : 
    6391         459 :     const char *pszDither = CSLFetchNameValue(papszOptions, "DITHER");
    6392         459 :     if (pszDither)
    6393           0 :         m_bDither = CPLTestBool(pszDither);
    6394         459 : }
    6395             : 
    6396             : /************************************************************************/
    6397             : /*                          RegisterWebPExtension()                     */
    6398             : /************************************************************************/
    6399             : 
    6400          11 : bool GDALGeoPackageDataset::RegisterWebPExtension()
    6401             : {
    6402          11 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6403           0 :         return false;
    6404             : 
    6405          11 :     char *pszSQL = sqlite3_mprintf(
    6406             :         "INSERT INTO gpkg_extensions "
    6407             :         "(table_name, column_name, extension_name, definition, scope) "
    6408             :         "VALUES "
    6409             :         "('%q', 'tile_data', 'gpkg_webp', "
    6410             :         "'http://www.geopackage.org/spec120/#extension_tiles_webp', "
    6411             :         "'read-write')",
    6412             :         m_osRasterTable.c_str());
    6413          11 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6414          11 :     sqlite3_free(pszSQL);
    6415             : 
    6416          11 :     return OGRERR_NONE == eErr;
    6417             : }
    6418             : 
    6419             : /************************************************************************/
    6420             : /*                       RegisterZoomOtherExtension()                   */
    6421             : /************************************************************************/
    6422             : 
    6423           1 : bool GDALGeoPackageDataset::RegisterZoomOtherExtension()
    6424             : {
    6425           1 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
    6426           0 :         return false;
    6427             : 
    6428           1 :     char *pszSQL = sqlite3_mprintf(
    6429             :         "INSERT INTO gpkg_extensions "
    6430             :         "(table_name, column_name, extension_name, definition, scope) "
    6431             :         "VALUES "
    6432             :         "('%q', 'tile_data', 'gpkg_zoom_other', "
    6433             :         "'http://www.geopackage.org/spec120/#extension_zoom_other_intervals', "
    6434             :         "'read-write')",
    6435             :         m_osRasterTable.c_str());
    6436           1 :     const OGRErr eErr = SQLCommand(hDB, pszSQL);
    6437           1 :     sqlite3_free(pszSQL);
    6438           1 :     return OGRERR_NONE == eErr;
    6439             : }
    6440             : 
    6441             : /************************************************************************/
    6442             : /*                              GetLayer()                              */
    6443             : /************************************************************************/
    6444             : 
    6445       15801 : const OGRLayer *GDALGeoPackageDataset::GetLayer(int iLayer) const
    6446             : 
    6447             : {
    6448       15801 :     if (iLayer < 0 || iLayer >= static_cast<int>(m_apoLayers.size()))
    6449           7 :         return nullptr;
    6450             :     else
    6451       15794 :         return m_apoLayers[iLayer].get();
    6452             : }
    6453             : 
    6454             : /************************************************************************/
    6455             : /*                           LaunderName()                              */
    6456             : /************************************************************************/
    6457             : 
    6458             : /** Launder identifiers (table, column names) according to guidance at
    6459             :  * https://www.geopackage.org/guidance/getting-started.html:
    6460             :  * "For maximum interoperability, start your database identifiers (table names,
    6461             :  * column names, etc.) with a lowercase character and only use lowercase
    6462             :  * characters, numbers 0-9, and underscores (_)."
    6463             :  */
    6464             : 
    6465             : /* static */
    6466           5 : std::string GDALGeoPackageDataset::LaunderName(const std::string &osStr)
    6467             : {
    6468           5 :     char *pszASCII = CPLUTF8ForceToASCII(osStr.c_str(), '_');
    6469          10 :     const std::string osStrASCII(pszASCII);
    6470           5 :     CPLFree(pszASCII);
    6471             : 
    6472          10 :     std::string osRet;
    6473           5 :     osRet.reserve(osStrASCII.size());
    6474             : 
    6475          29 :     for (size_t i = 0; i < osStrASCII.size(); ++i)
    6476             :     {
    6477          24 :         if (osRet.empty())
    6478             :         {
    6479           5 :             if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6480             :             {
    6481           2 :                 osRet += (osStrASCII[i] - 'A' + 'a');
    6482             :             }
    6483           3 :             else if (osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z')
    6484             :             {
    6485           2 :                 osRet += osStrASCII[i];
    6486             :             }
    6487             :             else
    6488             :             {
    6489           1 :                 continue;
    6490             :             }
    6491             :         }
    6492          19 :         else if (osStrASCII[i] >= 'A' && osStrASCII[i] <= 'Z')
    6493             :         {
    6494          11 :             osRet += (osStrASCII[i] - 'A' + 'a');
    6495             :         }
    6496           9 :         else if ((osStrASCII[i] >= 'a' && osStrASCII[i] <= 'z') ||
    6497          14 :                  (osStrASCII[i] >= '0' && osStrASCII[i] <= '9') ||
    6498           5 :                  osStrASCII[i] == '_')
    6499             :         {
    6500           7 :             osRet += osStrASCII[i];
    6501             :         }
    6502             :         else
    6503             :         {
    6504           1 :             osRet += '_';
    6505             :         }
    6506             :     }
    6507             : 
    6508           5 :     if (osRet.empty() && !osStrASCII.empty())
    6509           2 :         return LaunderName(std::string("x").append(osStrASCII));
    6510             : 
    6511           4 :     if (osRet != osStr)
    6512             :     {
    6513           3 :         CPLDebug("PG", "LaunderName('%s') -> '%s'", osStr.c_str(),
    6514             :                  osRet.c_str());
    6515             :     }
    6516             : 
    6517           4 :     return osRet;
    6518             : }
    6519             : 
    6520             : /************************************************************************/
    6521             : /*                          ICreateLayer()                              */
    6522             : /************************************************************************/
    6523             : 
    6524             : OGRLayer *
    6525         829 : GDALGeoPackageDataset::ICreateLayer(const char *pszLayerName,
    6526             :                                     const OGRGeomFieldDefn *poSrcGeomFieldDefn,
    6527             :                                     CSLConstList papszOptions)
    6528             : {
    6529             :     /* -------------------------------------------------------------------- */
    6530             :     /*      Verify we are in update mode.                                   */
    6531             :     /* -------------------------------------------------------------------- */
    6532         829 :     if (!GetUpdate())
    6533             :     {
    6534           0 :         CPLError(CE_Failure, CPLE_NoWriteAccess,
    6535             :                  "Data source %s opened read-only.\n"
    6536             :                  "New layer %s cannot be created.\n",
    6537             :                  m_pszFilename, pszLayerName);
    6538             : 
    6539           0 :         return nullptr;
    6540             :     }
    6541             : 
    6542             :     const bool bLaunder =
    6543         829 :         CPLTestBool(CSLFetchNameValueDef(papszOptions, "LAUNDER", "NO"));
    6544             :     const std::string osTableName(bLaunder ? LaunderName(pszLayerName)
    6545        2487 :                                            : std::string(pszLayerName));
    6546             : 
    6547             :     const auto eGType =
    6548         829 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
    6549             :     const auto poSpatialRef =
    6550         829 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
    6551             : 
    6552         829 :     if (!m_bHasGPKGGeometryColumns)
    6553             :     {
    6554           1 :         if (SQLCommand(hDB, pszCREATE_GPKG_GEOMETRY_COLUMNS) != OGRERR_NONE)
    6555             :         {
    6556           0 :             return nullptr;
    6557             :         }
    6558           1 :         m_bHasGPKGGeometryColumns = true;
    6559             :     }
    6560             : 
    6561             :     // Check identifier unicity
    6562         829 :     const char *pszIdentifier = CSLFetchNameValue(papszOptions, "IDENTIFIER");
    6563         829 :     if (pszIdentifier != nullptr && pszIdentifier[0] == '\0')
    6564           0 :         pszIdentifier = nullptr;
    6565         829 :     if (pszIdentifier != nullptr)
    6566             :     {
    6567          13 :         for (auto &poLayer : m_apoLayers)
    6568             :         {
    6569             :             const char *pszOtherIdentifier =
    6570           9 :                 poLayer->GetMetadataItem("IDENTIFIER");
    6571           9 :             if (pszOtherIdentifier == nullptr)
    6572           6 :                 pszOtherIdentifier = poLayer->GetName();
    6573          18 :             if (pszOtherIdentifier != nullptr &&
    6574          12 :                 EQUAL(pszOtherIdentifier, pszIdentifier) &&
    6575           3 :                 !EQUAL(poLayer->GetName(), osTableName.c_str()))
    6576             :             {
    6577           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6578             :                          "Identifier %s is already used by table %s",
    6579             :                          pszIdentifier, poLayer->GetName());
    6580           2 :                 return nullptr;
    6581             :             }
    6582             :         }
    6583             : 
    6584             :         // In case there would be table in gpkg_contents not listed as a
    6585             :         // vector layer
    6586           4 :         char *pszSQL = sqlite3_mprintf(
    6587             :             "SELECT table_name FROM gpkg_contents WHERE identifier = '%q' "
    6588             :             "LIMIT 2",
    6589             :             pszIdentifier);
    6590           4 :         auto oResult = SQLQuery(hDB, pszSQL);
    6591           4 :         sqlite3_free(pszSQL);
    6592           8 :         if (oResult && oResult->RowCount() > 0 &&
    6593           9 :             oResult->GetValue(0, 0) != nullptr &&
    6594           1 :             !EQUAL(oResult->GetValue(0, 0), osTableName.c_str()))
    6595             :         {
    6596           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    6597             :                      "Identifier %s is already used by table %s", pszIdentifier,
    6598             :                      oResult->GetValue(0, 0));
    6599           1 :             return nullptr;
    6600             :         }
    6601             :     }
    6602             : 
    6603             :     /* Read GEOMETRY_NAME option */
    6604             :     const char *pszGeomColumnName =
    6605         826 :         CSLFetchNameValue(papszOptions, "GEOMETRY_NAME");
    6606         826 :     if (pszGeomColumnName == nullptr) /* deprecated name */
    6607         745 :         pszGeomColumnName = CSLFetchNameValue(papszOptions, "GEOMETRY_COLUMN");
    6608         826 :     if (pszGeomColumnName == nullptr && poSrcGeomFieldDefn)
    6609             :     {
    6610         677 :         pszGeomColumnName = poSrcGeomFieldDefn->GetNameRef();
    6611         677 :         if (pszGeomColumnName && pszGeomColumnName[0] == 0)
    6612         673 :             pszGeomColumnName = nullptr;
    6613             :     }
    6614         826 :     if (pszGeomColumnName == nullptr)
    6615         741 :         pszGeomColumnName = "geom";
    6616             :     const bool bGeomNullable =
    6617         826 :         CPLFetchBool(papszOptions, "GEOMETRY_NULLABLE", true);
    6618             : 
    6619             :     /* Read FID option */
    6620         826 :     const char *pszFIDColumnName = CSLFetchNameValue(papszOptions, "FID");
    6621         826 :     if (pszFIDColumnName == nullptr)
    6622         749 :         pszFIDColumnName = "fid";
    6623             : 
    6624         826 :     if (CPLTestBool(CPLGetConfigOption("GPKG_NAME_CHECK", "YES")))
    6625             :     {
    6626         826 :         if (strspn(pszFIDColumnName, "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") > 0)
    6627             :         {
    6628           2 :             CPLError(CE_Failure, CPLE_AppDefined,
    6629             :                      "The primary key (%s) name may not contain special "
    6630             :                      "characters or spaces",
    6631             :                      pszFIDColumnName);
    6632           2 :             return nullptr;
    6633             :         }
    6634             : 
    6635             :         /* Avoiding gpkg prefixes is not an official requirement, but seems wise
    6636             :          */
    6637         824 :         if (STARTS_WITH(osTableName.c_str(), "gpkg"))
    6638             :         {
    6639           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    6640             :                      "The layer name may not begin with 'gpkg' as it is a "
    6641             :                      "reserved geopackage prefix");
    6642           0 :             return nullptr;
    6643             :         }
    6644             : 
    6645             :         /* Preemptively try and avoid sqlite3 syntax errors due to  */
    6646             :         /* illegal characters. */
    6647         824 :         if (strspn(osTableName.c_str(), "`~!@#$%^&*()+-={}|[]\\:\";'<>?,./") >
    6648             :             0)
    6649             :         {
    6650           0 :             CPLError(
    6651             :                 CE_Failure, CPLE_AppDefined,
    6652             :                 "The layer name may not contain special characters or spaces");
    6653           0 :             return nullptr;
    6654             :         }
    6655             :     }
    6656             : 
    6657             :     /* Check for any existing layers that already use this name */
    6658        1028 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6659             :          iLayer++)
    6660             :     {
    6661         205 :         if (EQUAL(osTableName.c_str(), m_apoLayers[iLayer]->GetName()))
    6662             :         {
    6663             :             const char *pszOverwrite =
    6664           2 :                 CSLFetchNameValue(papszOptions, "OVERWRITE");
    6665           2 :             if (pszOverwrite != nullptr && CPLTestBool(pszOverwrite))
    6666             :             {
    6667           1 :                 DeleteLayer(iLayer);
    6668             :             }
    6669             :             else
    6670             :             {
    6671           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    6672             :                          "Layer %s already exists, CreateLayer failed.\n"
    6673             :                          "Use the layer creation option OVERWRITE=YES to "
    6674             :                          "replace it.",
    6675             :                          osTableName.c_str());
    6676           1 :                 return nullptr;
    6677             :             }
    6678             :         }
    6679             :     }
    6680             : 
    6681         823 :     if (m_apoLayers.size() == 1)
    6682             :     {
    6683             :         // Async RTree building doesn't play well with multiple layer:
    6684             :         // SQLite3 locks being hold for a long time, random failed commits,
    6685             :         // etc.
    6686          78 :         m_apoLayers[0]->FinishOrDisableThreadedRTree();
    6687             :     }
    6688             : 
    6689             :     /* Create a blank layer. */
    6690             :     auto poLayer =
    6691        1646 :         std::make_unique<OGRGeoPackageTableLayer>(this, osTableName.c_str());
    6692             : 
    6693         823 :     OGRSpatialReference *poSRS = nullptr;
    6694         823 :     if (poSpatialRef)
    6695             :     {
    6696         250 :         poSRS = poSpatialRef->Clone();
    6697         250 :         poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    6698             :     }
    6699        1647 :     poLayer->SetCreationParameters(
    6700             :         eGType,
    6701         824 :         bLaunder ? LaunderName(pszGeomColumnName).c_str() : pszGeomColumnName,
    6702             :         bGeomNullable, poSRS, CSLFetchNameValue(papszOptions, "SRID"),
    6703        1646 :         poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetCoordinatePrecision()
    6704             :                            : OGRGeomCoordinatePrecision(),
    6705         823 :         CPLTestBool(
    6706             :             CSLFetchNameValueDef(papszOptions, "DISCARD_COORD_LSB", "NO")),
    6707         823 :         CPLTestBool(CSLFetchNameValueDef(
    6708             :             papszOptions, "UNDO_DISCARD_COORD_LSB_ON_READING", "NO")),
    6709         824 :         bLaunder ? LaunderName(pszFIDColumnName).c_str() : pszFIDColumnName,
    6710             :         pszIdentifier, CSLFetchNameValue(papszOptions, "DESCRIPTION"));
    6711         823 :     if (poSRS)
    6712             :     {
    6713         250 :         poSRS->Release();
    6714             :     }
    6715             : 
    6716         823 :     poLayer->SetLaunder(bLaunder);
    6717             : 
    6718             :     /* Should we create a spatial index ? */
    6719         823 :     const char *pszSI = CSLFetchNameValue(papszOptions, "SPATIAL_INDEX");
    6720         823 :     int bCreateSpatialIndex = (pszSI == nullptr || CPLTestBool(pszSI));
    6721         823 :     if (eGType != wkbNone && bCreateSpatialIndex)
    6722             :     {
    6723         729 :         poLayer->SetDeferredSpatialIndexCreation(true);
    6724             :     }
    6725             : 
    6726         823 :     poLayer->SetPrecisionFlag(CPLFetchBool(papszOptions, "PRECISION", true));
    6727         823 :     poLayer->SetTruncateFieldsFlag(
    6728         823 :         CPLFetchBool(papszOptions, "TRUNCATE_FIELDS", false));
    6729         823 :     if (eGType == wkbNone)
    6730             :     {
    6731          72 :         const char *pszASpatialVariant = CSLFetchNameValueDef(
    6732             :             papszOptions, "ASPATIAL_VARIANT",
    6733          72 :             m_bNonSpatialTablesNonRegisteredInGpkgContentsFound
    6734             :                 ? "NOT_REGISTERED"
    6735             :                 : "GPKG_ATTRIBUTES");
    6736          72 :         GPKGASpatialVariant eASpatialVariant = GPKG_ATTRIBUTES;
    6737          72 :         if (EQUAL(pszASpatialVariant, "GPKG_ATTRIBUTES"))
    6738          60 :             eASpatialVariant = GPKG_ATTRIBUTES;
    6739          12 :         else if (EQUAL(pszASpatialVariant, "OGR_ASPATIAL"))
    6740             :         {
    6741           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6742             :                      "ASPATIAL_VARIANT=OGR_ASPATIAL is no longer supported");
    6743           0 :             return nullptr;
    6744             :         }
    6745          12 :         else if (EQUAL(pszASpatialVariant, "NOT_REGISTERED"))
    6746          12 :             eASpatialVariant = NOT_REGISTERED;
    6747             :         else
    6748             :         {
    6749           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    6750             :                      "Unsupported value for ASPATIAL_VARIANT: %s",
    6751             :                      pszASpatialVariant);
    6752           0 :             return nullptr;
    6753             :         }
    6754          72 :         poLayer->SetASpatialVariant(eASpatialVariant);
    6755             :     }
    6756             : 
    6757             :     const char *pszDateTimePrecision =
    6758         823 :         CSLFetchNameValueDef(papszOptions, "DATETIME_PRECISION", "AUTO");
    6759         823 :     if (EQUAL(pszDateTimePrecision, "MILLISECOND"))
    6760             :     {
    6761           2 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6762             :     }
    6763         821 :     else if (EQUAL(pszDateTimePrecision, "SECOND"))
    6764             :     {
    6765           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6766           0 :             CPLError(
    6767             :                 CE_Warning, CPLE_AppDefined,
    6768             :                 "DATETIME_PRECISION=SECOND is only valid since GeoPackage 1.4");
    6769           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::SECOND);
    6770             :     }
    6771         820 :     else if (EQUAL(pszDateTimePrecision, "MINUTE"))
    6772             :     {
    6773           1 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6774           0 :             CPLError(
    6775             :                 CE_Warning, CPLE_AppDefined,
    6776             :                 "DATETIME_PRECISION=MINUTE is only valid since GeoPackage 1.4");
    6777           1 :         poLayer->SetDateTimePrecision(OGRISO8601Precision::MINUTE);
    6778             :     }
    6779         819 :     else if (EQUAL(pszDateTimePrecision, "AUTO"))
    6780             :     {
    6781         818 :         if (m_nUserVersion < GPKG_1_4_VERSION)
    6782          13 :             poLayer->SetDateTimePrecision(OGRISO8601Precision::MILLISECOND);
    6783             :     }
    6784             :     else
    6785             :     {
    6786           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    6787             :                  "Unsupported value for DATETIME_PRECISION: %s",
    6788             :                  pszDateTimePrecision);
    6789           1 :         return nullptr;
    6790             :     }
    6791             : 
    6792             :     // If there was an ogr_empty_table table, we can remove it
    6793             :     // But do it at dataset closing, otherwise locking performance issues
    6794             :     // can arise (probably when transactions are used).
    6795         822 :     m_bRemoveOGREmptyTable = true;
    6796             : 
    6797         822 :     m_apoLayers.emplace_back(std::move(poLayer));
    6798         822 :     return m_apoLayers.back().get();
    6799             : }
    6800             : 
    6801             : /************************************************************************/
    6802             : /*                          FindLayerIndex()                            */
    6803             : /************************************************************************/
    6804             : 
    6805          27 : int GDALGeoPackageDataset::FindLayerIndex(const char *pszLayerName)
    6806             : 
    6807             : {
    6808          42 :     for (int iLayer = 0; iLayer < static_cast<int>(m_apoLayers.size());
    6809             :          iLayer++)
    6810             :     {
    6811          28 :         if (EQUAL(pszLayerName, m_apoLayers[iLayer]->GetName()))
    6812          13 :             return iLayer;
    6813             :     }
    6814          14 :     return -1;
    6815             : }
    6816             : 
    6817             : /************************************************************************/
    6818             : /*                       DeleteLayerCommon()                            */
    6819             : /************************************************************************/
    6820             : 
    6821          41 : OGRErr GDALGeoPackageDataset::DeleteLayerCommon(const char *pszLayerName)
    6822             : {
    6823             :     // Temporary remove foreign key checks
    6824             :     const GPKGTemporaryForeignKeyCheckDisabler
    6825          41 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6826             : 
    6827          41 :     char *pszSQL = sqlite3_mprintf(
    6828             :         "DELETE FROM gpkg_contents WHERE lower(table_name) = lower('%q')",
    6829             :         pszLayerName);
    6830          41 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
    6831          41 :     sqlite3_free(pszSQL);
    6832             : 
    6833          41 :     if (eErr == OGRERR_NONE && HasExtensionsTable())
    6834             :     {
    6835          39 :         pszSQL = sqlite3_mprintf(
    6836             :             "DELETE FROM gpkg_extensions WHERE lower(table_name) = lower('%q')",
    6837             :             pszLayerName);
    6838          39 :         eErr = SQLCommand(hDB, pszSQL);
    6839          39 :         sqlite3_free(pszSQL);
    6840             :     }
    6841             : 
    6842          41 :     if (eErr == OGRERR_NONE && HasMetadataTables())
    6843             :     {
    6844             :         // Delete from gpkg_metadata metadata records that are only referenced
    6845             :         // by the table we are about to drop
    6846          11 :         pszSQL = sqlite3_mprintf(
    6847             :             "DELETE FROM gpkg_metadata WHERE id IN ("
    6848             :             "SELECT DISTINCT md_file_id FROM "
    6849             :             "gpkg_metadata_reference WHERE "
    6850             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6851             :             "AND id NOT IN ("
    6852             :             "SELECT DISTINCT md_file_id FROM gpkg_metadata_reference WHERE "
    6853             :             "md_file_id IN (SELECT DISTINCT md_file_id FROM "
    6854             :             "gpkg_metadata_reference WHERE "
    6855             :             "lower(table_name) = lower('%q') AND md_parent_id is NULL) "
    6856             :             "AND lower(table_name) <> lower('%q'))",
    6857             :             pszLayerName, pszLayerName, pszLayerName);
    6858          11 :         eErr = SQLCommand(hDB, pszSQL);
    6859          11 :         sqlite3_free(pszSQL);
    6860             : 
    6861          11 :         if (eErr == OGRERR_NONE)
    6862             :         {
    6863             :             pszSQL =
    6864          11 :                 sqlite3_mprintf("DELETE FROM gpkg_metadata_reference WHERE "
    6865             :                                 "lower(table_name) = lower('%q')",
    6866             :                                 pszLayerName);
    6867          11 :             eErr = SQLCommand(hDB, pszSQL);
    6868          11 :             sqlite3_free(pszSQL);
    6869             :         }
    6870             :     }
    6871             : 
    6872          41 :     if (eErr == OGRERR_NONE && HasGpkgextRelationsTable())
    6873             :     {
    6874             :         // Remove reference to potential corresponding mapping table in
    6875             :         // gpkg_extensions
    6876           4 :         pszSQL = sqlite3_mprintf(
    6877             :             "DELETE FROM gpkg_extensions WHERE "
    6878             :             "extension_name IN ('related_tables', "
    6879             :             "'gpkg_related_tables') AND lower(table_name) = "
    6880             :             "(SELECT lower(mapping_table_name) FROM gpkgext_relations WHERE "
    6881             :             "lower(base_table_name) = lower('%q') OR "
    6882             :             "lower(related_table_name) = lower('%q') OR "
    6883             :             "lower(mapping_table_name) = lower('%q'))",
    6884             :             pszLayerName, pszLayerName, pszLayerName);
    6885           4 :         eErr = SQLCommand(hDB, pszSQL);
    6886           4 :         sqlite3_free(pszSQL);
    6887             : 
    6888           4 :         if (eErr == OGRERR_NONE)
    6889             :         {
    6890             :             // Remove reference to potential corresponding mapping table in
    6891             :             // gpkgext_relations
    6892             :             pszSQL =
    6893           4 :                 sqlite3_mprintf("DELETE FROM gpkgext_relations WHERE "
    6894             :                                 "lower(base_table_name) = lower('%q') OR "
    6895             :                                 "lower(related_table_name) = lower('%q') OR "
    6896             :                                 "lower(mapping_table_name) = lower('%q')",
    6897             :                                 pszLayerName, pszLayerName, pszLayerName);
    6898           4 :             eErr = SQLCommand(hDB, pszSQL);
    6899           4 :             sqlite3_free(pszSQL);
    6900             :         }
    6901             : 
    6902           4 :         if (eErr == OGRERR_NONE && HasExtensionsTable())
    6903             :         {
    6904             :             // If there is no longer any mapping table, then completely
    6905             :             // remove any reference to the extension in gpkg_extensions
    6906             :             // as mandated per the related table specification.
    6907             :             OGRErr err;
    6908           4 :             if (SQLGetInteger(hDB,
    6909             :                               "SELECT COUNT(*) FROM gpkg_extensions WHERE "
    6910             :                               "extension_name IN ('related_tables', "
    6911             :                               "'gpkg_related_tables') AND "
    6912             :                               "lower(table_name) != 'gpkgext_relations'",
    6913           4 :                               &err) == 0)
    6914             :             {
    6915           2 :                 eErr = SQLCommand(hDB, "DELETE FROM gpkg_extensions WHERE "
    6916             :                                        "extension_name IN ('related_tables', "
    6917             :                                        "'gpkg_related_tables')");
    6918             :             }
    6919             : 
    6920           4 :             ClearCachedRelationships();
    6921             :         }
    6922             :     }
    6923             : 
    6924          41 :     if (eErr == OGRERR_NONE)
    6925             :     {
    6926          41 :         pszSQL = sqlite3_mprintf("DROP TABLE \"%w\"", pszLayerName);
    6927          41 :         eErr = SQLCommand(hDB, pszSQL);
    6928          41 :         sqlite3_free(pszSQL);
    6929             :     }
    6930             : 
    6931             :     // Check foreign key integrity
    6932          41 :     if (eErr == OGRERR_NONE)
    6933             :     {
    6934          41 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    6935             :     }
    6936             : 
    6937          82 :     return eErr;
    6938             : }
    6939             : 
    6940             : /************************************************************************/
    6941             : /*                            DeleteLayer()                             */
    6942             : /************************************************************************/
    6943             : 
    6944          38 : OGRErr GDALGeoPackageDataset::DeleteLayer(int iLayer)
    6945             : {
    6946          75 :     if (!GetUpdate() || iLayer < 0 ||
    6947          37 :         iLayer >= static_cast<int>(m_apoLayers.size()))
    6948           2 :         return OGRERR_FAILURE;
    6949             : 
    6950          36 :     m_apoLayers[iLayer]->ResetReading();
    6951          36 :     m_apoLayers[iLayer]->SyncToDisk();
    6952             : 
    6953          72 :     CPLString osLayerName = m_apoLayers[iLayer]->GetName();
    6954             : 
    6955          36 :     CPLDebug("GPKG", "DeleteLayer(%s)", osLayerName.c_str());
    6956             : 
    6957             :     // Temporary remove foreign key checks
    6958             :     const GPKGTemporaryForeignKeyCheckDisabler
    6959          36 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    6960             : 
    6961          36 :     OGRErr eErr = SoftStartTransaction();
    6962             : 
    6963          36 :     if (eErr == OGRERR_NONE)
    6964             :     {
    6965          36 :         if (m_apoLayers[iLayer]->HasSpatialIndex())
    6966          33 :             m_apoLayers[iLayer]->DropSpatialIndex();
    6967             : 
    6968             :         char *pszSQL =
    6969          36 :             sqlite3_mprintf("DELETE FROM gpkg_geometry_columns WHERE "
    6970             :                             "lower(table_name) = lower('%q')",
    6971             :                             osLayerName.c_str());
    6972          36 :         eErr = SQLCommand(hDB, pszSQL);
    6973          36 :         sqlite3_free(pszSQL);
    6974             :     }
    6975             : 
    6976          36 :     if (eErr == OGRERR_NONE && HasDataColumnsTable())
    6977             :     {
    6978           1 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_data_columns WHERE "
    6979             :                                        "lower(table_name) = lower('%q')",
    6980             :                                        osLayerName.c_str());
    6981           1 :         eErr = SQLCommand(hDB, pszSQL);
    6982           1 :         sqlite3_free(pszSQL);
    6983             :     }
    6984             : 
    6985             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    6986          36 :     if (eErr == OGRERR_NONE && m_bHasGPKGOGRContents)
    6987             :     {
    6988          36 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_ogr_contents WHERE "
    6989             :                                        "lower(table_name) = lower('%q')",
    6990             :                                        osLayerName.c_str());
    6991          36 :         eErr = SQLCommand(hDB, pszSQL);
    6992          36 :         sqlite3_free(pszSQL);
    6993             :     }
    6994             : #endif
    6995             : 
    6996          36 :     if (eErr == OGRERR_NONE)
    6997             :     {
    6998          36 :         eErr = DeleteLayerCommon(osLayerName.c_str());
    6999             :     }
    7000             : 
    7001          36 :     if (eErr == OGRERR_NONE)
    7002             :     {
    7003          36 :         eErr = SoftCommitTransaction();
    7004          36 :         if (eErr == OGRERR_NONE)
    7005             :         {
    7006             :             /* Delete the layer object */
    7007          36 :             m_apoLayers.erase(m_apoLayers.begin() + iLayer);
    7008             :         }
    7009             :     }
    7010             :     else
    7011             :     {
    7012           0 :         SoftRollbackTransaction();
    7013             :     }
    7014             : 
    7015          36 :     return eErr;
    7016             : }
    7017             : 
    7018             : /************************************************************************/
    7019             : /*                       DeleteRasterLayer()                            */
    7020             : /************************************************************************/
    7021             : 
    7022           2 : OGRErr GDALGeoPackageDataset::DeleteRasterLayer(const char *pszLayerName)
    7023             : {
    7024             :     // Temporary remove foreign key checks
    7025             :     const GPKGTemporaryForeignKeyCheckDisabler
    7026           2 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7027             : 
    7028           2 :     OGRErr eErr = SoftStartTransaction();
    7029             : 
    7030           2 :     if (eErr == OGRERR_NONE)
    7031             :     {
    7032           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix WHERE "
    7033             :                                        "lower(table_name) = lower('%q')",
    7034             :                                        pszLayerName);
    7035           2 :         eErr = SQLCommand(hDB, pszSQL);
    7036           2 :         sqlite3_free(pszSQL);
    7037             :     }
    7038             : 
    7039           2 :     if (eErr == OGRERR_NONE)
    7040             :     {
    7041           2 :         char *pszSQL = sqlite3_mprintf("DELETE FROM gpkg_tile_matrix_set WHERE "
    7042             :                                        "lower(table_name) = lower('%q')",
    7043             :                                        pszLayerName);
    7044           2 :         eErr = SQLCommand(hDB, pszSQL);
    7045           2 :         sqlite3_free(pszSQL);
    7046             :     }
    7047             : 
    7048           2 :     if (eErr == OGRERR_NONE && HasGriddedCoverageAncillaryTable())
    7049             :     {
    7050             :         char *pszSQL =
    7051           1 :             sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_coverage_ancillary "
    7052             :                             "WHERE lower(tile_matrix_set_name) = lower('%q')",
    7053             :                             pszLayerName);
    7054           1 :         eErr = SQLCommand(hDB, pszSQL);
    7055           1 :         sqlite3_free(pszSQL);
    7056             : 
    7057           1 :         if (eErr == OGRERR_NONE)
    7058             :         {
    7059             :             pszSQL =
    7060           1 :                 sqlite3_mprintf("DELETE FROM gpkg_2d_gridded_tile_ancillary "
    7061             :                                 "WHERE lower(tpudt_name) = lower('%q')",
    7062             :                                 pszLayerName);
    7063           1 :             eErr = SQLCommand(hDB, pszSQL);
    7064           1 :             sqlite3_free(pszSQL);
    7065             :         }
    7066             :     }
    7067             : 
    7068           2 :     if (eErr == OGRERR_NONE)
    7069             :     {
    7070           2 :         eErr = DeleteLayerCommon(pszLayerName);
    7071             :     }
    7072             : 
    7073           2 :     if (eErr == OGRERR_NONE)
    7074             :     {
    7075           2 :         eErr = SoftCommitTransaction();
    7076             :     }
    7077             :     else
    7078             :     {
    7079           0 :         SoftRollbackTransaction();
    7080             :     }
    7081             : 
    7082           4 :     return eErr;
    7083             : }
    7084             : 
    7085             : /************************************************************************/
    7086             : /*                    DeleteVectorOrRasterLayer()                       */
    7087             : /************************************************************************/
    7088             : 
    7089          13 : bool GDALGeoPackageDataset::DeleteVectorOrRasterLayer(const char *pszLayerName)
    7090             : {
    7091             : 
    7092          13 :     int idx = FindLayerIndex(pszLayerName);
    7093          13 :     if (idx >= 0)
    7094             :     {
    7095           5 :         DeleteLayer(idx);
    7096           5 :         return true;
    7097             :     }
    7098             : 
    7099             :     char *pszSQL =
    7100           8 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7101             :                         "lower(table_name) = lower('%q') "
    7102             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7103             :                         pszLayerName);
    7104           8 :     bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7105           8 :     sqlite3_free(pszSQL);
    7106           8 :     if (bIsRasterTable)
    7107             :     {
    7108           2 :         DeleteRasterLayer(pszLayerName);
    7109           2 :         return true;
    7110             :     }
    7111           6 :     return false;
    7112             : }
    7113             : 
    7114           7 : bool GDALGeoPackageDataset::RenameVectorOrRasterLayer(
    7115             :     const char *pszLayerName, const char *pszNewLayerName)
    7116             : {
    7117           7 :     int idx = FindLayerIndex(pszLayerName);
    7118           7 :     if (idx >= 0)
    7119             :     {
    7120           4 :         m_apoLayers[idx]->Rename(pszNewLayerName);
    7121           4 :         return true;
    7122             :     }
    7123             : 
    7124             :     char *pszSQL =
    7125           3 :         sqlite3_mprintf("SELECT 1 FROM gpkg_contents WHERE "
    7126             :                         "lower(table_name) = lower('%q') "
    7127             :                         "AND data_type IN ('tiles', '2d-gridded-coverage')",
    7128             :                         pszLayerName);
    7129           3 :     const bool bIsRasterTable = SQLGetInteger(hDB, pszSQL, nullptr) == 1;
    7130           3 :     sqlite3_free(pszSQL);
    7131             : 
    7132           3 :     if (bIsRasterTable)
    7133             :     {
    7134           2 :         return RenameRasterLayer(pszLayerName, pszNewLayerName);
    7135             :     }
    7136             : 
    7137           1 :     return false;
    7138             : }
    7139             : 
    7140           2 : bool GDALGeoPackageDataset::RenameRasterLayer(const char *pszLayerName,
    7141             :                                               const char *pszNewLayerName)
    7142             : {
    7143           4 :     std::string osSQL;
    7144             : 
    7145           2 :     char *pszSQL = sqlite3_mprintf(
    7146             :         "SELECT 1 FROM sqlite_master WHERE lower(name) = lower('%q') "
    7147             :         "AND type IN ('table', 'view')",
    7148             :         pszNewLayerName);
    7149           2 :     const bool bAlreadyExists = SQLGetInteger(GetDB(), pszSQL, nullptr) == 1;
    7150           2 :     sqlite3_free(pszSQL);
    7151           2 :     if (bAlreadyExists)
    7152             :     {
    7153           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Table %s already exists",
    7154             :                  pszNewLayerName);
    7155           0 :         return false;
    7156             :     }
    7157             : 
    7158             :     // Temporary remove foreign key checks
    7159             :     const GPKGTemporaryForeignKeyCheckDisabler
    7160           4 :         oGPKGTemporaryForeignKeyCheckDisabler(this);
    7161             : 
    7162           2 :     if (SoftStartTransaction() != OGRERR_NONE)
    7163             :     {
    7164           0 :         return false;
    7165             :     }
    7166             : 
    7167           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET table_name = '%q' WHERE "
    7168             :                              "lower(table_name) = lower('%q');",
    7169             :                              pszNewLayerName, pszLayerName);
    7170           2 :     osSQL = pszSQL;
    7171           2 :     sqlite3_free(pszSQL);
    7172             : 
    7173           2 :     pszSQL = sqlite3_mprintf("UPDATE gpkg_contents SET identifier = '%q' WHERE "
    7174             :                              "lower(identifier) = lower('%q');",
    7175             :                              pszNewLayerName, pszLayerName);
    7176           2 :     osSQL += pszSQL;
    7177           2 :     sqlite3_free(pszSQL);
    7178             : 
    7179             :     pszSQL =
    7180           2 :         sqlite3_mprintf("UPDATE gpkg_tile_matrix SET table_name = '%q' WHERE "
    7181             :                         "lower(table_name) = lower('%q');",
    7182             :                         pszNewLayerName, pszLayerName);
    7183           2 :     osSQL += pszSQL;
    7184           2 :     sqlite3_free(pszSQL);
    7185             : 
    7186           2 :     pszSQL = sqlite3_mprintf(
    7187             :         "UPDATE gpkg_tile_matrix_set SET table_name = '%q' WHERE "
    7188             :         "lower(table_name) = lower('%q');",
    7189             :         pszNewLayerName, pszLayerName);
    7190           2 :     osSQL += pszSQL;
    7191           2 :     sqlite3_free(pszSQL);
    7192             : 
    7193           2 :     if (HasGriddedCoverageAncillaryTable())
    7194             :     {
    7195           1 :         pszSQL = sqlite3_mprintf("UPDATE gpkg_2d_gridded_coverage_ancillary "
    7196             :                                  "SET tile_matrix_set_name = '%q' WHERE "
    7197             :                                  "lower(tile_matrix_set_name) = lower('%q');",
    7198             :                                  pszNewLayerName, pszLayerName);
    7199           1 :         osSQL += pszSQL;
    7200           1 :         sqlite3_free(pszSQL);
    7201             : 
    7202           1 :         pszSQL = sqlite3_mprintf(
    7203             :             "UPDATE gpkg_2d_gridded_tile_ancillary SET tpudt_name = '%q' WHERE "
    7204             :             "lower(tpudt_name) = lower('%q');",
    7205             :             pszNewLayerName, pszLayerName);
    7206           1 :         osSQL += pszSQL;
    7207           1 :         sqlite3_free(pszSQL);
    7208             :     }
    7209             : 
    7210           2 :     if (HasExtensionsTable())
    7211             :     {
    7212           2 :         pszSQL = sqlite3_mprintf(
    7213             :             "UPDATE gpkg_extensions SET table_name = '%q' WHERE "
    7214             :             "lower(table_name) = lower('%q');",
    7215             :             pszNewLayerName, pszLayerName);
    7216           2 :         osSQL += pszSQL;
    7217           2 :         sqlite3_free(pszSQL);
    7218             :     }
    7219             : 
    7220           2 :     if (HasMetadataTables())
    7221             :     {
    7222           1 :         pszSQL = sqlite3_mprintf(
    7223             :             "UPDATE gpkg_metadata_reference SET table_name = '%q' WHERE "
    7224             :             "lower(table_name) = lower('%q');",
    7225             :             pszNewLayerName, pszLayerName);
    7226           1 :         osSQL += pszSQL;
    7227           1 :         sqlite3_free(pszSQL);
    7228             :     }
    7229             : 
    7230           2 :     if (HasDataColumnsTable())
    7231             :     {
    7232           0 :         pszSQL = sqlite3_mprintf(
    7233             :             "UPDATE gpkg_data_columns SET table_name = '%q' WHERE "
    7234             :             "lower(table_name) = lower('%q');",
    7235             :             pszNewLayerName, pszLayerName);
    7236           0 :         osSQL += pszSQL;
    7237           0 :         sqlite3_free(pszSQL);
    7238             :     }
    7239             : 
    7240           2 :     if (HasQGISLayerStyles())
    7241             :     {
    7242             :         // Update QGIS styles
    7243             :         pszSQL =
    7244           0 :             sqlite3_mprintf("UPDATE layer_styles SET f_table_name = '%q' WHERE "
    7245             :                             "lower(f_table_name) = lower('%q');",
    7246             :                             pszNewLayerName, pszLayerName);
    7247           0 :         osSQL += pszSQL;
    7248           0 :         sqlite3_free(pszSQL);
    7249             :     }
    7250             : 
    7251             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7252           2 :     if (m_bHasGPKGOGRContents)
    7253             :     {
    7254           2 :         pszSQL = sqlite3_mprintf(
    7255             :             "UPDATE gpkg_ogr_contents SET table_name = '%q' WHERE "
    7256             :             "lower(table_name) = lower('%q');",
    7257             :             pszNewLayerName, pszLayerName);
    7258           2 :         osSQL += pszSQL;
    7259           2 :         sqlite3_free(pszSQL);
    7260             :     }
    7261             : #endif
    7262             : 
    7263           2 :     if (HasGpkgextRelationsTable())
    7264             :     {
    7265           0 :         pszSQL = sqlite3_mprintf(
    7266             :             "UPDATE gpkgext_relations SET base_table_name = '%q' WHERE "
    7267             :             "lower(base_table_name) = lower('%q');",
    7268             :             pszNewLayerName, pszLayerName);
    7269           0 :         osSQL += pszSQL;
    7270           0 :         sqlite3_free(pszSQL);
    7271             : 
    7272           0 :         pszSQL = sqlite3_mprintf(
    7273             :             "UPDATE gpkgext_relations SET related_table_name = '%q' WHERE "
    7274             :             "lower(related_table_name) = lower('%q');",
    7275             :             pszNewLayerName, pszLayerName);
    7276           0 :         osSQL += pszSQL;
    7277           0 :         sqlite3_free(pszSQL);
    7278             : 
    7279           0 :         pszSQL = sqlite3_mprintf(
    7280             :             "UPDATE gpkgext_relations SET mapping_table_name = '%q' WHERE "
    7281             :             "lower(mapping_table_name) = lower('%q');",
    7282             :             pszNewLayerName, pszLayerName);
    7283           0 :         osSQL += pszSQL;
    7284           0 :         sqlite3_free(pszSQL);
    7285             :     }
    7286             : 
    7287             :     // Drop all triggers for the layer
    7288           2 :     pszSQL = sqlite3_mprintf("SELECT name FROM sqlite_master WHERE type = "
    7289             :                              "'trigger' AND tbl_name = '%q'",
    7290             :                              pszLayerName);
    7291           2 :     auto oTriggerResult = SQLQuery(GetDB(), pszSQL);
    7292           2 :     sqlite3_free(pszSQL);
    7293           2 :     if (oTriggerResult)
    7294             :     {
    7295          14 :         for (int i = 0; i < oTriggerResult->RowCount(); i++)
    7296             :         {
    7297          12 :             const char *pszTriggerName = oTriggerResult->GetValue(0, i);
    7298          12 :             pszSQL = sqlite3_mprintf("DROP TRIGGER IF EXISTS \"%w\";",
    7299             :                                      pszTriggerName);
    7300          12 :             osSQL += pszSQL;
    7301          12 :             sqlite3_free(pszSQL);
    7302             :         }
    7303             :     }
    7304             : 
    7305           2 :     pszSQL = sqlite3_mprintf("ALTER TABLE \"%w\" RENAME TO \"%w\";",
    7306             :                              pszLayerName, pszNewLayerName);
    7307           2 :     osSQL += pszSQL;
    7308           2 :     sqlite3_free(pszSQL);
    7309             : 
    7310             :     // Recreate all zoom/tile triggers
    7311           2 :     if (oTriggerResult)
    7312             :     {
    7313           2 :         osSQL += CreateRasterTriggersSQL(pszNewLayerName);
    7314             :     }
    7315             : 
    7316           2 :     OGRErr eErr = SQLCommand(GetDB(), osSQL.c_str());
    7317             : 
    7318             :     // Check foreign key integrity
    7319           2 :     if (eErr == OGRERR_NONE)
    7320             :     {
    7321           2 :         eErr = PragmaCheck("foreign_key_check", "", 0);
    7322             :     }
    7323             : 
    7324           2 :     if (eErr == OGRERR_NONE)
    7325             :     {
    7326           2 :         eErr = SoftCommitTransaction();
    7327             :     }
    7328             :     else
    7329             :     {
    7330           0 :         SoftRollbackTransaction();
    7331             :     }
    7332             : 
    7333           2 :     return eErr == OGRERR_NONE;
    7334             : }
    7335             : 
    7336             : /************************************************************************/
    7337             : /*                       TestCapability()                               */
    7338             : /************************************************************************/
    7339             : 
    7340         464 : int GDALGeoPackageDataset::TestCapability(const char *pszCap) const
    7341             : {
    7342         464 :     if (EQUAL(pszCap, ODsCCreateLayer) || EQUAL(pszCap, ODsCDeleteLayer) ||
    7343         290 :         EQUAL(pszCap, "RenameLayer"))
    7344             :     {
    7345         174 :         return GetUpdate();
    7346             :     }
    7347         290 :     else if (EQUAL(pszCap, ODsCCurveGeometries))
    7348          12 :         return TRUE;
    7349         278 :     else if (EQUAL(pszCap, ODsCMeasuredGeometries))
    7350           8 :         return TRUE;
    7351         270 :     else if (EQUAL(pszCap, ODsCZGeometries))
    7352           8 :         return TRUE;
    7353         262 :     else if (EQUAL(pszCap, ODsCRandomLayerWrite) ||
    7354         262 :              EQUAL(pszCap, GDsCAddRelationship) ||
    7355         262 :              EQUAL(pszCap, GDsCDeleteRelationship) ||
    7356         262 :              EQUAL(pszCap, GDsCUpdateRelationship) ||
    7357         262 :              EQUAL(pszCap, ODsCAddFieldDomain))
    7358           1 :         return GetUpdate();
    7359             : 
    7360         261 :     return OGRSQLiteBaseDataSource::TestCapability(pszCap);
    7361             : }
    7362             : 
    7363             : /************************************************************************/
    7364             : /*                       ResetReadingAllLayers()                        */
    7365             : /************************************************************************/
    7366             : 
    7367         205 : void GDALGeoPackageDataset::ResetReadingAllLayers()
    7368             : {
    7369         415 :     for (auto &poLayer : m_apoLayers)
    7370             :     {
    7371         210 :         poLayer->ResetReading();
    7372             :     }
    7373         205 : }
    7374             : 
    7375             : /************************************************************************/
    7376             : /*                             ExecuteSQL()                             */
    7377             : /************************************************************************/
    7378             : 
    7379             : static const char *const apszFuncsWithSideEffects[] = {
    7380             :     "CreateSpatialIndex",
    7381             :     "DisableSpatialIndex",
    7382             :     "HasSpatialIndex",
    7383             :     "RegisterGeometryExtension",
    7384             : };
    7385             : 
    7386        5651 : OGRLayer *GDALGeoPackageDataset::ExecuteSQL(const char *pszSQLCommand,
    7387             :                                             OGRGeometry *poSpatialFilter,
    7388             :                                             const char *pszDialect)
    7389             : 
    7390             : {
    7391        5651 :     m_bHasReadMetadataFromStorage = false;
    7392             : 
    7393        5651 :     FlushMetadata();
    7394             : 
    7395        5669 :     while (*pszSQLCommand != '\0' &&
    7396        5669 :            isspace(static_cast<unsigned char>(*pszSQLCommand)))
    7397          18 :         pszSQLCommand++;
    7398             : 
    7399       11302 :     CPLString osSQLCommand(pszSQLCommand);
    7400        5651 :     if (!osSQLCommand.empty() && osSQLCommand.back() == ';')
    7401          48 :         osSQLCommand.pop_back();
    7402             : 
    7403        5651 :     if (pszDialect == nullptr || !EQUAL(pszDialect, "DEBUG"))
    7404             :     {
    7405             :         // Some SQL commands will influence the feature count behind our
    7406             :         // back, so disable it in that case.
    7407             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7408             :         const bool bInsertOrDelete =
    7409        5582 :             osSQLCommand.ifind("insert into ") != std::string::npos ||
    7410        2461 :             osSQLCommand.ifind("insert or replace into ") !=
    7411        8043 :                 std::string::npos ||
    7412        2424 :             osSQLCommand.ifind("delete from ") != std::string::npos;
    7413             :         const bool bRollback =
    7414        5582 :             osSQLCommand.ifind("rollback ") != std::string::npos;
    7415             : #endif
    7416             : 
    7417        7412 :         for (auto &poLayer : m_apoLayers)
    7418             :         {
    7419        1830 :             if (poLayer->SyncToDisk() != OGRERR_NONE)
    7420           0 :                 return nullptr;
    7421             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    7422        2035 :             if (bRollback ||
    7423         205 :                 (bInsertOrDelete &&
    7424         205 :                  osSQLCommand.ifind(poLayer->GetName()) != std::string::npos))
    7425             :             {
    7426         203 :                 poLayer->DisableFeatureCount();
    7427             :             }
    7428             : #endif
    7429             :         }
    7430             :     }
    7431             : 
    7432        5651 :     if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 0") ||
    7433        5650 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=0") ||
    7434        5650 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =0") ||
    7435        5650 :         EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 0"))
    7436             :     {
    7437           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, false);
    7438             :     }
    7439        5650 :     else if (EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like = 1") ||
    7440        5649 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like=1") ||
    7441        5649 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like =1") ||
    7442        5649 :              EQUAL(pszSQLCommand, "PRAGMA case_sensitive_like= 1"))
    7443             :     {
    7444           1 :         OGRSQLiteSQLFunctionsSetCaseSensitiveLike(m_pSQLFunctionData, true);
    7445             :     }
    7446             : 
    7447             :     /* -------------------------------------------------------------------- */
    7448             :     /*      DEBUG "SELECT nolock" command.                                  */
    7449             :     /* -------------------------------------------------------------------- */
    7450        5720 :     if (pszDialect != nullptr && EQUAL(pszDialect, "DEBUG") &&
    7451          69 :         EQUAL(osSQLCommand, "SELECT nolock"))
    7452             :     {
    7453           3 :         return new OGRSQLiteSingleFeatureLayer(osSQLCommand, m_bNoLock ? 1 : 0);
    7454             :     }
    7455             : 
    7456             :     /* -------------------------------------------------------------------- */
    7457             :     /*      Special case DELLAYER: command.                                 */
    7458             :     /* -------------------------------------------------------------------- */
    7459        5648 :     if (STARTS_WITH_CI(osSQLCommand, "DELLAYER:"))
    7460             :     {
    7461           4 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DELLAYER:");
    7462             : 
    7463           4 :         while (*pszLayerName == ' ')
    7464           0 :             pszLayerName++;
    7465             : 
    7466           4 :         if (!DeleteVectorOrRasterLayer(pszLayerName))
    7467             :         {
    7468           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7469             :                      pszLayerName);
    7470             :         }
    7471           4 :         return nullptr;
    7472             :     }
    7473             : 
    7474             :     /* -------------------------------------------------------------------- */
    7475             :     /*      Special case RECOMPUTE EXTENT ON command.                       */
    7476             :     /* -------------------------------------------------------------------- */
    7477        5644 :     if (STARTS_WITH_CI(osSQLCommand, "RECOMPUTE EXTENT ON "))
    7478             :     {
    7479             :         const char *pszLayerName =
    7480           4 :             osSQLCommand.c_str() + strlen("RECOMPUTE EXTENT ON ");
    7481             : 
    7482           4 :         while (*pszLayerName == ' ')
    7483           0 :             pszLayerName++;
    7484             : 
    7485           4 :         int idx = FindLayerIndex(pszLayerName);
    7486           4 :         if (idx >= 0)
    7487             :         {
    7488           4 :             m_apoLayers[idx]->RecomputeExtent();
    7489             :         }
    7490             :         else
    7491           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer: %s",
    7492             :                      pszLayerName);
    7493           4 :         return nullptr;
    7494             :     }
    7495             : 
    7496             :     /* -------------------------------------------------------------------- */
    7497             :     /*      Intercept DROP TABLE                                            */
    7498             :     /* -------------------------------------------------------------------- */
    7499        5640 :     if (STARTS_WITH_CI(osSQLCommand, "DROP TABLE "))
    7500             :     {
    7501           9 :         const char *pszLayerName = osSQLCommand.c_str() + strlen("DROP TABLE ");
    7502             : 
    7503           9 :         while (*pszLayerName == ' ')
    7504           0 :             pszLayerName++;
    7505             : 
    7506           9 :         if (DeleteVectorOrRasterLayer(SQLUnescape(pszLayerName)))
    7507           4 :             return nullptr;
    7508             :     }
    7509             : 
    7510             :     /* -------------------------------------------------------------------- */
    7511             :     /*      Intercept ALTER TABLE src_table RENAME TO dst_table             */
    7512             :     /*      and       ALTER TABLE table RENAME COLUMN src_name TO dst_name  */
    7513             :     /*      and       ALTER TABLE table DROP COLUMN col_name                */
    7514             :     /*                                                                      */
    7515             :     /*      We do this because SQLite mechanisms can't deal with updating   */
    7516             :     /*      literal values in gpkg_ tables that refer to table and column   */
    7517             :     /*      names.                                                          */
    7518             :     /* -------------------------------------------------------------------- */
    7519        5636 :     if (STARTS_WITH_CI(osSQLCommand, "ALTER TABLE "))
    7520             :     {
    7521           9 :         char **papszTokens = SQLTokenize(osSQLCommand);
    7522             :         /* ALTER TABLE src_table RENAME TO dst_table */
    7523          16 :         if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "RENAME") &&
    7524           7 :             EQUAL(papszTokens[4], "TO"))
    7525             :         {
    7526           7 :             const char *pszSrcTableName = papszTokens[2];
    7527           7 :             const char *pszDstTableName = papszTokens[5];
    7528           7 :             if (RenameVectorOrRasterLayer(SQLUnescape(pszSrcTableName),
    7529          14 :                                           SQLUnescape(pszDstTableName)))
    7530             :             {
    7531           6 :                 CSLDestroy(papszTokens);
    7532           6 :                 return nullptr;
    7533             :             }
    7534             :         }
    7535             :         /* ALTER TABLE table RENAME COLUMN src_name TO dst_name */
    7536           2 :         else if (CSLCount(papszTokens) == 8 &&
    7537           1 :                  EQUAL(papszTokens[3], "RENAME") &&
    7538           3 :                  EQUAL(papszTokens[4], "COLUMN") && EQUAL(papszTokens[6], "TO"))
    7539             :         {
    7540           1 :             const char *pszTableName = papszTokens[2];
    7541           1 :             const char *pszSrcColumn = papszTokens[5];
    7542           1 :             const char *pszDstColumn = papszTokens[7];
    7543             :             OGRGeoPackageTableLayer *poLayer =
    7544           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7545           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7546           1 :             if (poLayer)
    7547             :             {
    7548           2 :                 int nSrcFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7549           2 :                     SQLUnescape(pszSrcColumn));
    7550           1 :                 if (nSrcFieldIdx >= 0)
    7551             :                 {
    7552             :                     // OFTString or any type will do as we just alter the name
    7553             :                     // so it will be ignored.
    7554           1 :                     OGRFieldDefn oFieldDefn(SQLUnescape(pszDstColumn),
    7555           1 :                                             OFTString);
    7556           1 :                     poLayer->AlterFieldDefn(nSrcFieldIdx, &oFieldDefn,
    7557             :                                             ALTER_NAME_FLAG);
    7558           1 :                     CSLDestroy(papszTokens);
    7559           1 :                     return nullptr;
    7560             :                 }
    7561             :             }
    7562             :         }
    7563             :         /* ALTER TABLE table DROP COLUMN col_name */
    7564           2 :         else if (CSLCount(papszTokens) == 6 && EQUAL(papszTokens[3], "DROP") &&
    7565           1 :                  EQUAL(papszTokens[4], "COLUMN"))
    7566             :         {
    7567           1 :             const char *pszTableName = papszTokens[2];
    7568           1 :             const char *pszColumnName = papszTokens[5];
    7569             :             OGRGeoPackageTableLayer *poLayer =
    7570           0 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7571           1 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7572           1 :             if (poLayer)
    7573             :             {
    7574           2 :                 int nFieldIdx = poLayer->GetLayerDefn()->GetFieldIndex(
    7575           2 :                     SQLUnescape(pszColumnName));
    7576           1 :                 if (nFieldIdx >= 0)
    7577             :                 {
    7578           1 :                     poLayer->DeleteField(nFieldIdx);
    7579           1 :                     CSLDestroy(papszTokens);
    7580           1 :                     return nullptr;
    7581             :                 }
    7582             :             }
    7583             :         }
    7584           1 :         CSLDestroy(papszTokens);
    7585             :     }
    7586             : 
    7587        5628 :     if (ProcessTransactionSQL(osSQLCommand))
    7588             :     {
    7589         253 :         return nullptr;
    7590             :     }
    7591             : 
    7592        5375 :     if (EQUAL(osSQLCommand, "VACUUM"))
    7593             :     {
    7594          13 :         ResetReadingAllLayers();
    7595             :     }
    7596        5362 :     else if (STARTS_WITH_CI(osSQLCommand, "DELETE FROM "))
    7597             :     {
    7598             :         // Optimize truncation of a table, especially if it has a spatial
    7599             :         // index.
    7600          24 :         const CPLStringList aosTokens(SQLTokenize(osSQLCommand));
    7601          24 :         if (aosTokens.size() == 3)
    7602             :         {
    7603          16 :             const char *pszTableName = aosTokens[2];
    7604             :             OGRGeoPackageTableLayer *poLayer =
    7605           8 :                 dynamic_cast<OGRGeoPackageTableLayer *>(
    7606          24 :                     GetLayerByName(SQLUnescape(pszTableName)));
    7607          16 :             if (poLayer)
    7608             :             {
    7609           8 :                 poLayer->Truncate();
    7610           8 :                 return nullptr;
    7611             :             }
    7612             :         }
    7613             :     }
    7614        5338 :     else if (pszDialect != nullptr && EQUAL(pszDialect, "INDIRECT_SQLITE"))
    7615           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter, "SQLITE");
    7616        5337 :     else if (pszDialect != nullptr && !EQUAL(pszDialect, "") &&
    7617          67 :              !EQUAL(pszDialect, "NATIVE") && !EQUAL(pszDialect, "SQLITE") &&
    7618          67 :              !EQUAL(pszDialect, "DEBUG"))
    7619           1 :         return GDALDataset::ExecuteSQL(osSQLCommand, poSpatialFilter,
    7620           1 :                                        pszDialect);
    7621             : 
    7622             :     /* -------------------------------------------------------------------- */
    7623             :     /*      Prepare statement.                                              */
    7624             :     /* -------------------------------------------------------------------- */
    7625        5365 :     sqlite3_stmt *hSQLStmt = nullptr;
    7626             : 
    7627             :     /* This will speed-up layer creation */
    7628             :     /* ORDER BY are costly to evaluate and are not necessary to establish */
    7629             :     /* the layer definition. */
    7630        5365 :     bool bUseStatementForGetNextFeature = true;
    7631        5365 :     bool bEmptyLayer = false;
    7632       10730 :     CPLString osSQLCommandTruncated(osSQLCommand);
    7633             : 
    7634       17703 :     if (osSQLCommand.ifind("SELECT ") == 0 &&
    7635        6169 :         CPLString(osSQLCommand.substr(1)).ifind("SELECT ") ==
    7636         770 :             std::string::npos &&
    7637         770 :         osSQLCommand.ifind(" UNION ") == std::string::npos &&
    7638        6939 :         osSQLCommand.ifind(" INTERSECT ") == std::string::npos &&
    7639         770 :         osSQLCommand.ifind(" EXCEPT ") == std::string::npos)
    7640             :     {
    7641         770 :         size_t nOrderByPos = osSQLCommand.ifind(" ORDER BY ");
    7642         770 :         if (nOrderByPos != std::string::npos)
    7643             :         {
    7644           9 :             osSQLCommandTruncated.resize(nOrderByPos);
    7645           9 :             bUseStatementForGetNextFeature = false;
    7646             :         }
    7647             :     }
    7648             : 
    7649        5365 :     int rc = prepareSql(hDB, osSQLCommandTruncated.c_str(),
    7650        5365 :                         static_cast<int>(osSQLCommandTruncated.size()),
    7651             :                         &hSQLStmt, nullptr);
    7652             : 
    7653        5365 :     if (rc != SQLITE_OK)
    7654             :     {
    7655           9 :         CPLError(CE_Failure, CPLE_AppDefined,
    7656             :                  "In ExecuteSQL(): sqlite3_prepare_v2(%s): %s",
    7657             :                  osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7658             : 
    7659           9 :         if (hSQLStmt != nullptr)
    7660             :         {
    7661           0 :             sqlite3_finalize(hSQLStmt);
    7662             :         }
    7663             : 
    7664           9 :         return nullptr;
    7665             :     }
    7666             : 
    7667             :     /* -------------------------------------------------------------------- */
    7668             :     /*      Do we get a resultset?                                          */
    7669             :     /* -------------------------------------------------------------------- */
    7670        5356 :     rc = sqlite3_step(hSQLStmt);
    7671             : 
    7672        6951 :     for (auto &poLayer : m_apoLayers)
    7673             :     {
    7674        1595 :         poLayer->RunDeferredDropRTreeTableIfNecessary();
    7675             :     }
    7676             : 
    7677        5356 :     if (rc != SQLITE_ROW)
    7678             :     {
    7679        4634 :         if (rc != SQLITE_DONE)
    7680             :         {
    7681           7 :             CPLError(CE_Failure, CPLE_AppDefined,
    7682             :                      "In ExecuteSQL(): sqlite3_step(%s):\n  %s",
    7683             :                      osSQLCommandTruncated.c_str(), sqlite3_errmsg(hDB));
    7684             : 
    7685           7 :             sqlite3_finalize(hSQLStmt);
    7686           7 :             return nullptr;
    7687             :         }
    7688             : 
    7689        4627 :         if (EQUAL(osSQLCommand, "VACUUM"))
    7690             :         {
    7691          13 :             sqlite3_finalize(hSQLStmt);
    7692             :             /* VACUUM rewrites the DB, so we need to reset the application id */
    7693          13 :             SetApplicationAndUserVersionId();
    7694          13 :             return nullptr;
    7695             :         }
    7696             : 
    7697        4614 :         if (!STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7698             :         {
    7699        4488 :             sqlite3_finalize(hSQLStmt);
    7700        4488 :             return nullptr;
    7701             :         }
    7702             : 
    7703         126 :         bUseStatementForGetNextFeature = false;
    7704         126 :         bEmptyLayer = true;
    7705             :     }
    7706             : 
    7707             :     /* -------------------------------------------------------------------- */
    7708             :     /*      Special case for some functions which must be run               */
    7709             :     /*      only once                                                       */
    7710             :     /* -------------------------------------------------------------------- */
    7711         848 :     if (STARTS_WITH_CI(osSQLCommand, "SELECT "))
    7712             :     {
    7713        3864 :         for (unsigned int i = 0; i < sizeof(apszFuncsWithSideEffects) /
    7714             :                                          sizeof(apszFuncsWithSideEffects[0]);
    7715             :              i++)
    7716             :         {
    7717        3117 :             if (EQUALN(apszFuncsWithSideEffects[i], osSQLCommand.c_str() + 7,
    7718             :                        strlen(apszFuncsWithSideEffects[i])))
    7719             :             {
    7720         112 :                 if (sqlite3_column_count(hSQLStmt) == 1 &&
    7721          56 :                     sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7722             :                 {
    7723          56 :                     int ret = sqlite3_column_int(hSQLStmt, 0);
    7724             : 
    7725          56 :                     sqlite3_finalize(hSQLStmt);
    7726             : 
    7727             :                     return new OGRSQLiteSingleFeatureLayer(
    7728          56 :                         apszFuncsWithSideEffects[i], ret);
    7729             :                 }
    7730             :             }
    7731             :         }
    7732             :     }
    7733          45 :     else if (STARTS_WITH_CI(osSQLCommand, "PRAGMA "))
    7734             :     {
    7735          63 :         if (sqlite3_column_count(hSQLStmt) == 1 &&
    7736          18 :             sqlite3_column_type(hSQLStmt, 0) == SQLITE_INTEGER)
    7737             :         {
    7738          15 :             int ret = sqlite3_column_int(hSQLStmt, 0);
    7739             : 
    7740          15 :             sqlite3_finalize(hSQLStmt);
    7741             : 
    7742          15 :             return new OGRSQLiteSingleFeatureLayer(osSQLCommand.c_str() + 7,
    7743          15 :                                                    ret);
    7744             :         }
    7745          33 :         else if (sqlite3_column_count(hSQLStmt) == 1 &&
    7746           3 :                  sqlite3_column_type(hSQLStmt, 0) == SQLITE_TEXT)
    7747             :         {
    7748             :             const char *pszRet = reinterpret_cast<const char *>(
    7749           3 :                 sqlite3_column_text(hSQLStmt, 0));
    7750             : 
    7751             :             OGRLayer *poRet = new OGRSQLiteSingleFeatureLayer(
    7752           3 :                 osSQLCommand.c_str() + 7, pszRet);
    7753             : 
    7754           3 :             sqlite3_finalize(hSQLStmt);
    7755             : 
    7756           3 :             return poRet;
    7757             :         }
    7758             :     }
    7759             : 
    7760             :     /* -------------------------------------------------------------------- */
    7761             :     /*      Create layer.                                                   */
    7762             :     /* -------------------------------------------------------------------- */
    7763             : 
    7764             :     auto poLayer = std::make_unique<OGRGeoPackageSelectLayer>(
    7765             :         this, osSQLCommand, hSQLStmt, bUseStatementForGetNextFeature,
    7766        1548 :         bEmptyLayer);
    7767             : 
    7768         777 :     if (poSpatialFilter != nullptr &&
    7769           3 :         poLayer->GetLayerDefn()->GetGeomFieldCount() > 0)
    7770           3 :         poLayer->SetSpatialFilter(0, poSpatialFilter);
    7771             : 
    7772         774 :     return poLayer.release();
    7773             : }
    7774             : 
    7775             : /************************************************************************/
    7776             : /*                          ReleaseResultSet()                          */
    7777             : /************************************************************************/
    7778             : 
    7779         807 : void GDALGeoPackageDataset::ReleaseResultSet(OGRLayer *poLayer)
    7780             : 
    7781             : {
    7782         807 :     delete poLayer;
    7783         807 : }
    7784             : 
    7785             : /************************************************************************/
    7786             : /*                         HasExtensionsTable()                         */
    7787             : /************************************************************************/
    7788             : 
    7789        6814 : bool GDALGeoPackageDataset::HasExtensionsTable()
    7790             : {
    7791        6814 :     return SQLGetInteger(
    7792             :                hDB,
    7793             :                "SELECT 1 FROM sqlite_master WHERE name = 'gpkg_extensions' "
    7794             :                "AND type IN ('table', 'view')",
    7795        6814 :                nullptr) == 1;
    7796             : }
    7797             : 
    7798             : /************************************************************************/
    7799             : /*                    CheckUnknownExtensions()                          */
    7800             : /************************************************************************/
    7801             : 
    7802        1528 : void GDALGeoPackageDataset::CheckUnknownExtensions(bool bCheckRasterTable)
    7803             : {
    7804        1528 :     if (!HasExtensionsTable())
    7805         205 :         return;
    7806             : 
    7807        1323 :     char *pszSQL = nullptr;
    7808        1323 :     if (!bCheckRasterTable)
    7809        1114 :         pszSQL = sqlite3_mprintf(
    7810             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7811             :             "WHERE (table_name IS NULL "
    7812             :             "AND extension_name IS NOT NULL "
    7813             :             "AND definition IS NOT NULL "
    7814             :             "AND scope IS NOT NULL "
    7815             :             "AND extension_name NOT IN ("
    7816             :             "'gdal_aspatial', "
    7817             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7818             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7819             :                                        // 17-066r1 finalization
    7820             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7821             :             "'gpkg_metadata', "
    7822             :             "'gpkg_schema', "
    7823             :             "'gpkg_crs_wkt', "
    7824             :             "'gpkg_crs_wkt_1_1', "
    7825             :             "'related_tables', 'gpkg_related_tables')) "
    7826             : #ifdef WORKAROUND_SQLITE3_BUGS
    7827             :             "OR 0 "
    7828             : #endif
    7829             :             "LIMIT 1000");
    7830             :     else
    7831         209 :         pszSQL = sqlite3_mprintf(
    7832             :             "SELECT extension_name, definition, scope FROM gpkg_extensions "
    7833             :             "WHERE (lower(table_name) = lower('%q') "
    7834             :             "AND extension_name IS NOT NULL "
    7835             :             "AND definition IS NOT NULL "
    7836             :             "AND scope IS NOT NULL "
    7837             :             "AND extension_name NOT IN ("
    7838             :             "'gpkg_elevation_tiles', "  // Old name before GPKG 1.2 approval
    7839             :             "'2d_gridded_coverage', "  // Old name after GPKG 1.2 and before OGC
    7840             :                                        // 17-066r1 finalization
    7841             :             "'gpkg_2d_gridded_coverage', "  // Name in OGC 17-066r1 final
    7842             :             "'gpkg_metadata', "
    7843             :             "'gpkg_schema', "
    7844             :             "'gpkg_crs_wkt', "
    7845             :             "'gpkg_crs_wkt_1_1', "
    7846             :             "'related_tables', 'gpkg_related_tables')) "
    7847             : #ifdef WORKAROUND_SQLITE3_BUGS
    7848             :             "OR 0 "
    7849             : #endif
    7850             :             "LIMIT 1000",
    7851             :             m_osRasterTable.c_str());
    7852             : 
    7853        2646 :     auto oResultTable = SQLQuery(GetDB(), pszSQL);
    7854        1323 :     sqlite3_free(pszSQL);
    7855        1323 :     if (oResultTable && oResultTable->RowCount() > 0)
    7856             :     {
    7857          42 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    7858             :         {
    7859          21 :             const char *pszExtName = oResultTable->GetValue(0, i);
    7860          21 :             const char *pszDefinition = oResultTable->GetValue(1, i);
    7861          21 :             const char *pszScope = oResultTable->GetValue(2, i);
    7862          21 :             if (pszExtName == nullptr || pszDefinition == nullptr ||
    7863             :                 pszScope == nullptr)
    7864             :             {
    7865           0 :                 continue;
    7866             :             }
    7867             : 
    7868          21 :             if (EQUAL(pszExtName, "gpkg_webp"))
    7869             :             {
    7870          15 :                 if (GDALGetDriverByName("WEBP") == nullptr)
    7871             :                 {
    7872           1 :                     CPLError(
    7873             :                         CE_Warning, CPLE_AppDefined,
    7874             :                         "Table %s contains WEBP tiles, but GDAL configured "
    7875             :                         "without WEBP support. Data will be missing",
    7876             :                         m_osRasterTable.c_str());
    7877             :                 }
    7878          15 :                 m_eTF = GPKG_TF_WEBP;
    7879          15 :                 continue;
    7880             :             }
    7881           6 :             if (EQUAL(pszExtName, "gpkg_zoom_other"))
    7882             :             {
    7883           2 :                 m_bZoomOther = true;
    7884           2 :                 continue;
    7885             :             }
    7886             : 
    7887           4 :             if (GetUpdate() && EQUAL(pszScope, "write-only"))
    7888             :             {
    7889           1 :                 CPLError(
    7890             :                     CE_Warning, CPLE_AppDefined,
    7891             :                     "Database relies on the '%s' (%s) extension that should "
    7892             :                     "be implemented for safe write-support, but is not "
    7893             :                     "currently. "
    7894             :                     "Update of that database are strongly discouraged to avoid "
    7895             :                     "corruption.",
    7896             :                     pszExtName, pszDefinition);
    7897             :             }
    7898           3 :             else if (GetUpdate() && EQUAL(pszScope, "read-write"))
    7899             :             {
    7900           1 :                 CPLError(
    7901             :                     CE_Warning, CPLE_AppDefined,
    7902             :                     "Database relies on the '%s' (%s) extension that should "
    7903             :                     "be implemented in order to read/write it safely, but is "
    7904             :                     "not currently. "
    7905             :                     "Some data may be missing while reading that database, and "
    7906             :                     "updates are strongly discouraged.",
    7907             :                     pszExtName, pszDefinition);
    7908             :             }
    7909           2 :             else if (EQUAL(pszScope, "read-write") &&
    7910             :                      // None of the NGA extensions at
    7911             :                      // http://ngageoint.github.io/GeoPackage/docs/extensions/
    7912             :                      // affect read-only scenarios
    7913           1 :                      !STARTS_WITH(pszExtName, "nga_"))
    7914             :             {
    7915           1 :                 CPLError(
    7916             :                     CE_Warning, CPLE_AppDefined,
    7917             :                     "Database relies on the '%s' (%s) extension that should "
    7918             :                     "be implemented in order to read it safely, but is not "
    7919             :                     "currently. "
    7920             :                     "Some data may be missing while reading that database.",
    7921             :                     pszExtName, pszDefinition);
    7922             :             }
    7923             :         }
    7924             :     }
    7925             : }
    7926             : 
    7927             : /************************************************************************/
    7928             : /*                         HasGDALAspatialExtension()                       */
    7929             : /************************************************************************/
    7930             : 
    7931        1071 : bool GDALGeoPackageDataset::HasGDALAspatialExtension()
    7932             : {
    7933        1071 :     if (!HasExtensionsTable())
    7934          98 :         return false;
    7935             : 
    7936             :     auto oResultTable = SQLQuery(hDB, "SELECT * FROM gpkg_extensions "
    7937             :                                       "WHERE (extension_name = 'gdal_aspatial' "
    7938             :                                       "AND table_name IS NULL "
    7939             :                                       "AND column_name IS NULL)"
    7940             : #ifdef WORKAROUND_SQLITE3_BUGS
    7941             :                                       " OR 0"
    7942             : #endif
    7943         973 :     );
    7944         973 :     bool bHasExtension = (oResultTable && oResultTable->RowCount() == 1);
    7945         973 :     return bHasExtension;
    7946             : }
    7947             : 
    7948             : std::string
    7949         192 : GDALGeoPackageDataset::CreateRasterTriggersSQL(const std::string &osTableName)
    7950             : {
    7951             :     char *pszSQL;
    7952         192 :     std::string osSQL;
    7953             :     /* From D.5. sample_tile_pyramid Table 43. tiles table Trigger
    7954             :      * Definition SQL  */
    7955         192 :     pszSQL = sqlite3_mprintf(
    7956             :         "CREATE TRIGGER \"%w_zoom_insert\" "
    7957             :         "BEFORE INSERT ON \"%w\" "
    7958             :         "FOR EACH ROW BEGIN "
    7959             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7960             :         "constraint: zoom_level not specified for table in "
    7961             :         "gpkg_tile_matrix') "
    7962             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7963             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7964             :         "END; "
    7965             :         "CREATE TRIGGER \"%w_zoom_update\" "
    7966             :         "BEFORE UPDATE OF zoom_level ON \"%w\" "
    7967             :         "FOR EACH ROW BEGIN "
    7968             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7969             :         "constraint: zoom_level not specified for table in "
    7970             :         "gpkg_tile_matrix') "
    7971             :         "WHERE NOT (NEW.zoom_level IN (SELECT zoom_level FROM "
    7972             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q'))) ; "
    7973             :         "END; "
    7974             :         "CREATE TRIGGER \"%w_tile_column_insert\" "
    7975             :         "BEFORE INSERT ON \"%w\" "
    7976             :         "FOR EACH ROW BEGIN "
    7977             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7978             :         "constraint: tile_column cannot be < 0') "
    7979             :         "WHERE (NEW.tile_column < 0) ; "
    7980             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    7981             :         "constraint: tile_column must by < matrix_width specified for "
    7982             :         "table and zoom level in gpkg_tile_matrix') "
    7983             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    7984             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    7985             :         "zoom_level = NEW.zoom_level)); "
    7986             :         "END; "
    7987             :         "CREATE TRIGGER \"%w_tile_column_update\" "
    7988             :         "BEFORE UPDATE OF tile_column ON \"%w\" "
    7989             :         "FOR EACH ROW BEGIN "
    7990             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7991             :         "constraint: tile_column cannot be < 0') "
    7992             :         "WHERE (NEW.tile_column < 0) ; "
    7993             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    7994             :         "constraint: tile_column must by < matrix_width specified for "
    7995             :         "table and zoom level in gpkg_tile_matrix') "
    7996             :         "WHERE NOT (NEW.tile_column < (SELECT matrix_width FROM "
    7997             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    7998             :         "zoom_level = NEW.zoom_level)); "
    7999             :         "END; "
    8000             :         "CREATE TRIGGER \"%w_tile_row_insert\" "
    8001             :         "BEFORE INSERT ON \"%w\" "
    8002             :         "FOR EACH ROW BEGIN "
    8003             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8004             :         "constraint: tile_row cannot be < 0') "
    8005             :         "WHERE (NEW.tile_row < 0) ; "
    8006             :         "SELECT RAISE(ABORT, 'insert on table ''%q'' violates "
    8007             :         "constraint: tile_row must by < matrix_height specified for "
    8008             :         "table and zoom level in gpkg_tile_matrix') "
    8009             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8010             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8011             :         "zoom_level = NEW.zoom_level)); "
    8012             :         "END; "
    8013             :         "CREATE TRIGGER \"%w_tile_row_update\" "
    8014             :         "BEFORE UPDATE OF tile_row ON \"%w\" "
    8015             :         "FOR EACH ROW BEGIN "
    8016             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8017             :         "constraint: tile_row cannot be < 0') "
    8018             :         "WHERE (NEW.tile_row < 0) ; "
    8019             :         "SELECT RAISE(ABORT, 'update on table ''%q'' violates "
    8020             :         "constraint: tile_row must by < matrix_height specified for "
    8021             :         "table and zoom level in gpkg_tile_matrix') "
    8022             :         "WHERE NOT (NEW.tile_row < (SELECT matrix_height FROM "
    8023             :         "gpkg_tile_matrix WHERE lower(table_name) = lower('%q') AND "
    8024             :         "zoom_level = NEW.zoom_level)); "
    8025             :         "END; ",
    8026             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8027             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8028             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8029             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8030             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8031             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8032             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8033             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8034             :         osTableName.c_str(), osTableName.c_str(), osTableName.c_str(),
    8035             :         osTableName.c_str());
    8036         192 :     osSQL = pszSQL;
    8037         192 :     sqlite3_free(pszSQL);
    8038         192 :     return osSQL;
    8039             : }
    8040             : 
    8041             : /************************************************************************/
    8042             : /*                  CreateExtensionsTableIfNecessary()                  */
    8043             : /************************************************************************/
    8044             : 
    8045        1214 : OGRErr GDALGeoPackageDataset::CreateExtensionsTableIfNecessary()
    8046             : {
    8047             :     /* Check if the table gpkg_extensions exists */
    8048        1214 :     if (HasExtensionsTable())
    8049         412 :         return OGRERR_NONE;
    8050             : 
    8051             :     /* Requirement 79 : Every extension of a GeoPackage SHALL be registered */
    8052             :     /* in a corresponding row in the gpkg_extensions table. The absence of a */
    8053             :     /* gpkg_extensions table or the absence of rows in gpkg_extensions table */
    8054             :     /* SHALL both indicate the absence of extensions to a GeoPackage. */
    8055         802 :     const char *pszCreateGpkgExtensions =
    8056             :         "CREATE TABLE gpkg_extensions ("
    8057             :         "table_name TEXT,"
    8058             :         "column_name TEXT,"
    8059             :         "extension_name TEXT NOT NULL,"
    8060             :         "definition TEXT NOT NULL,"
    8061             :         "scope TEXT NOT NULL,"
    8062             :         "CONSTRAINT ge_tce UNIQUE (table_name, column_name, extension_name)"
    8063             :         ")";
    8064             : 
    8065         802 :     return SQLCommand(hDB, pszCreateGpkgExtensions);
    8066             : }
    8067             : 
    8068             : /************************************************************************/
    8069             : /*                    OGR_GPKG_Intersects_Spatial_Filter()              */
    8070             : /************************************************************************/
    8071             : 
    8072       23135 : void OGR_GPKG_Intersects_Spatial_Filter(sqlite3_context *pContext, int argc,
    8073             :                                         sqlite3_value **argv)
    8074             : {
    8075       23135 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8076             :     {
    8077           0 :         sqlite3_result_int(pContext, 0);
    8078       23125 :         return;
    8079             :     }
    8080             : 
    8081             :     auto poLayer =
    8082       23135 :         static_cast<OGRGeoPackageTableLayer *>(sqlite3_user_data(pContext));
    8083             : 
    8084       23135 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8085             :     const GByte *pabyBLOB =
    8086       23135 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8087             : 
    8088             :     GPkgHeader sHeader;
    8089       46270 :     if (poLayer->m_bFilterIsEnvelope &&
    8090       23135 :         OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false, 0))
    8091             :     {
    8092       23135 :         if (sHeader.bExtentHasXY)
    8093             :         {
    8094          95 :             OGREnvelope sEnvelope;
    8095          95 :             sEnvelope.MinX = sHeader.MinX;
    8096          95 :             sEnvelope.MinY = sHeader.MinY;
    8097          95 :             sEnvelope.MaxX = sHeader.MaxX;
    8098          95 :             sEnvelope.MaxY = sHeader.MaxY;
    8099          95 :             if (poLayer->m_sFilterEnvelope.Contains(sEnvelope))
    8100             :             {
    8101          31 :                 sqlite3_result_int(pContext, 1);
    8102          31 :                 return;
    8103             :             }
    8104             :         }
    8105             : 
    8106             :         // Check if at least one point falls into the layer filter envelope
    8107             :         // nHeaderLen is > 0 for GeoPackage geometries
    8108       46208 :         if (sHeader.nHeaderLen > 0 &&
    8109       23104 :             OGRWKBIntersectsPessimistic(pabyBLOB + sHeader.nHeaderLen,
    8110       23104 :                                         nBLOBLen - sHeader.nHeaderLen,
    8111       23104 :                                         poLayer->m_sFilterEnvelope))
    8112             :         {
    8113       23094 :             sqlite3_result_int(pContext, 1);
    8114       23094 :             return;
    8115             :         }
    8116             :     }
    8117             : 
    8118             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8119          10 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8120          10 :     if (poGeom == nullptr)
    8121             :     {
    8122             :         // Try also spatialite geometry blobs
    8123           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8124           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8125           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8126             :         {
    8127           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8128           0 :             sqlite3_result_int(pContext, 0);
    8129           0 :             return;
    8130             :         }
    8131           0 :         poGeom.reset(poGeomSpatialite);
    8132             :     }
    8133             : 
    8134          10 :     sqlite3_result_int(pContext, poLayer->FilterGeometry(poGeom.get()));
    8135             : }
    8136             : 
    8137             : /************************************************************************/
    8138             : /*                      OGRGeoPackageSTMinX()                           */
    8139             : /************************************************************************/
    8140             : 
    8141      252130 : static void OGRGeoPackageSTMinX(sqlite3_context *pContext, int argc,
    8142             :                                 sqlite3_value **argv)
    8143             : {
    8144             :     GPkgHeader sHeader;
    8145      252130 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8146             :     {
    8147           3 :         sqlite3_result_null(pContext);
    8148           3 :         return;
    8149             :     }
    8150      252127 :     sqlite3_result_double(pContext, sHeader.MinX);
    8151             : }
    8152             : 
    8153             : /************************************************************************/
    8154             : /*                      OGRGeoPackageSTMinY()                           */
    8155             : /************************************************************************/
    8156             : 
    8157      252128 : static void OGRGeoPackageSTMinY(sqlite3_context *pContext, int argc,
    8158             :                                 sqlite3_value **argv)
    8159             : {
    8160             :     GPkgHeader sHeader;
    8161      252128 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8162             :     {
    8163           1 :         sqlite3_result_null(pContext);
    8164           1 :         return;
    8165             :     }
    8166      252127 :     sqlite3_result_double(pContext, sHeader.MinY);
    8167             : }
    8168             : 
    8169             : /************************************************************************/
    8170             : /*                      OGRGeoPackageSTMaxX()                           */
    8171             : /************************************************************************/
    8172             : 
    8173      252128 : static void OGRGeoPackageSTMaxX(sqlite3_context *pContext, int argc,
    8174             :                                 sqlite3_value **argv)
    8175             : {
    8176             :     GPkgHeader sHeader;
    8177      252128 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8178             :     {
    8179           1 :         sqlite3_result_null(pContext);
    8180           1 :         return;
    8181             :     }
    8182      252127 :     sqlite3_result_double(pContext, sHeader.MaxX);
    8183             : }
    8184             : 
    8185             : /************************************************************************/
    8186             : /*                      OGRGeoPackageSTMaxY()                           */
    8187             : /************************************************************************/
    8188             : 
    8189      252128 : static void OGRGeoPackageSTMaxY(sqlite3_context *pContext, int argc,
    8190             :                                 sqlite3_value **argv)
    8191             : {
    8192             :     GPkgHeader sHeader;
    8193      252128 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8194             :     {
    8195           1 :         sqlite3_result_null(pContext);
    8196           1 :         return;
    8197             :     }
    8198      252127 :     sqlite3_result_double(pContext, sHeader.MaxY);
    8199             : }
    8200             : 
    8201             : /************************************************************************/
    8202             : /*                     OGRGeoPackageSTIsEmpty()                         */
    8203             : /************************************************************************/
    8204             : 
    8205      253537 : static void OGRGeoPackageSTIsEmpty(sqlite3_context *pContext, int argc,
    8206             :                                    sqlite3_value **argv)
    8207             : {
    8208             :     GPkgHeader sHeader;
    8209      253537 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8210             :     {
    8211           2 :         sqlite3_result_null(pContext);
    8212           2 :         return;
    8213             :     }
    8214      253535 :     sqlite3_result_int(pContext, sHeader.bEmpty);
    8215             : }
    8216             : 
    8217             : /************************************************************************/
    8218             : /*                    OGRGeoPackageSTGeometryType()                     */
    8219             : /************************************************************************/
    8220             : 
    8221           7 : static void OGRGeoPackageSTGeometryType(sqlite3_context *pContext, int /*argc*/,
    8222             :                                         sqlite3_value **argv)
    8223             : {
    8224             :     GPkgHeader sHeader;
    8225             : 
    8226           7 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8227             :     const GByte *pabyBLOB =
    8228           7 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8229             :     OGRwkbGeometryType eGeometryType;
    8230             : 
    8231          13 :     if (nBLOBLen < 8 ||
    8232           6 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8233             :     {
    8234           2 :         if (OGRSQLiteGetSpatialiteGeometryHeader(
    8235             :                 pabyBLOB, nBLOBLen, nullptr, &eGeometryType, nullptr, nullptr,
    8236           2 :                 nullptr, nullptr, nullptr) == OGRERR_NONE)
    8237             :         {
    8238           1 :             sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8239             :                                 SQLITE_TRANSIENT);
    8240           4 :             return;
    8241             :         }
    8242             :         else
    8243             :         {
    8244           1 :             sqlite3_result_null(pContext);
    8245           1 :             return;
    8246             :         }
    8247             :     }
    8248             : 
    8249           5 :     if (static_cast<size_t>(nBLOBLen) < sHeader.nHeaderLen + 5)
    8250             :     {
    8251           2 :         sqlite3_result_null(pContext);
    8252           2 :         return;
    8253             :     }
    8254             : 
    8255           3 :     OGRErr err = OGRReadWKBGeometryType(pabyBLOB + sHeader.nHeaderLen,
    8256             :                                         wkbVariantIso, &eGeometryType);
    8257           3 :     if (err != OGRERR_NONE)
    8258           1 :         sqlite3_result_null(pContext);
    8259             :     else
    8260           2 :         sqlite3_result_text(pContext, OGRToOGCGeomType(eGeometryType), -1,
    8261             :                             SQLITE_TRANSIENT);
    8262             : }
    8263             : 
    8264             : /************************************************************************/
    8265             : /*                 OGRGeoPackageSTEnvelopesIntersects()                 */
    8266             : /************************************************************************/
    8267             : 
    8268         118 : static void OGRGeoPackageSTEnvelopesIntersects(sqlite3_context *pContext,
    8269             :                                                int argc, sqlite3_value **argv)
    8270             : {
    8271             :     GPkgHeader sHeader;
    8272         118 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false))
    8273             :     {
    8274           2 :         sqlite3_result_int(pContext, FALSE);
    8275         107 :         return;
    8276             :     }
    8277         116 :     const double dfMinX = sqlite3_value_double(argv[1]);
    8278         116 :     if (sHeader.MaxX < dfMinX)
    8279             :     {
    8280          93 :         sqlite3_result_int(pContext, FALSE);
    8281          93 :         return;
    8282             :     }
    8283          23 :     const double dfMinY = sqlite3_value_double(argv[2]);
    8284          23 :     if (sHeader.MaxY < dfMinY)
    8285             :     {
    8286          11 :         sqlite3_result_int(pContext, FALSE);
    8287          11 :         return;
    8288             :     }
    8289          12 :     const double dfMaxX = sqlite3_value_double(argv[3]);
    8290          12 :     if (sHeader.MinX > dfMaxX)
    8291             :     {
    8292           1 :         sqlite3_result_int(pContext, FALSE);
    8293           1 :         return;
    8294             :     }
    8295          11 :     const double dfMaxY = sqlite3_value_double(argv[4]);
    8296          11 :     sqlite3_result_int(pContext, sHeader.MinY <= dfMaxY);
    8297             : }
    8298             : 
    8299             : /************************************************************************/
    8300             : /*              OGRGeoPackageSTEnvelopesIntersectsTwoParams()           */
    8301             : /************************************************************************/
    8302             : 
    8303             : static void
    8304           3 : OGRGeoPackageSTEnvelopesIntersectsTwoParams(sqlite3_context *pContext, int argc,
    8305             :                                             sqlite3_value **argv)
    8306             : {
    8307             :     GPkgHeader sHeader;
    8308           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, true, false, 0))
    8309             :     {
    8310           0 :         sqlite3_result_int(pContext, FALSE);
    8311           2 :         return;
    8312             :     }
    8313             :     GPkgHeader sHeader2;
    8314           3 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader2, true, false,
    8315             :                                 1))
    8316             :     {
    8317           0 :         sqlite3_result_int(pContext, FALSE);
    8318           0 :         return;
    8319             :     }
    8320           3 :     if (sHeader.MaxX < sHeader2.MinX)
    8321             :     {
    8322           1 :         sqlite3_result_int(pContext, FALSE);
    8323           1 :         return;
    8324             :     }
    8325           2 :     if (sHeader.MaxY < sHeader2.MinY)
    8326             :     {
    8327           0 :         sqlite3_result_int(pContext, FALSE);
    8328           0 :         return;
    8329             :     }
    8330           2 :     if (sHeader.MinX > sHeader2.MaxX)
    8331             :     {
    8332           1 :         sqlite3_result_int(pContext, FALSE);
    8333           1 :         return;
    8334             :     }
    8335           1 :     sqlite3_result_int(pContext, sHeader.MinY <= sHeader2.MaxY);
    8336             : }
    8337             : 
    8338             : /************************************************************************/
    8339             : /*                    OGRGeoPackageGPKGIsAssignable()                   */
    8340             : /************************************************************************/
    8341             : 
    8342           8 : static void OGRGeoPackageGPKGIsAssignable(sqlite3_context *pContext,
    8343             :                                           int /*argc*/, sqlite3_value **argv)
    8344             : {
    8345          15 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8346           7 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8347             :     {
    8348           2 :         sqlite3_result_int(pContext, 0);
    8349           2 :         return;
    8350             :     }
    8351             : 
    8352             :     const char *pszExpected =
    8353           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8354             :     const char *pszActual =
    8355           6 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8356           6 :     int bIsAssignable = OGR_GT_IsSubClassOf(OGRFromOGCGeomType(pszActual),
    8357             :                                             OGRFromOGCGeomType(pszExpected));
    8358           6 :     sqlite3_result_int(pContext, bIsAssignable);
    8359             : }
    8360             : 
    8361             : /************************************************************************/
    8362             : /*                     OGRGeoPackageSTSRID()                            */
    8363             : /************************************************************************/
    8364             : 
    8365          12 : static void OGRGeoPackageSTSRID(sqlite3_context *pContext, int argc,
    8366             :                                 sqlite3_value **argv)
    8367             : {
    8368             :     GPkgHeader sHeader;
    8369          12 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8370             :     {
    8371           2 :         sqlite3_result_null(pContext);
    8372           2 :         return;
    8373             :     }
    8374          10 :     sqlite3_result_int(pContext, sHeader.iSrsId);
    8375             : }
    8376             : 
    8377             : /************************************************************************/
    8378             : /*                     OGRGeoPackageSetSRID()                           */
    8379             : /************************************************************************/
    8380             : 
    8381          28 : static void OGRGeoPackageSetSRID(sqlite3_context *pContext, int /* argc */,
    8382             :                                  sqlite3_value **argv)
    8383             : {
    8384          28 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8385             :     {
    8386           1 :         sqlite3_result_null(pContext);
    8387           1 :         return;
    8388             :     }
    8389          27 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8390             :     GPkgHeader sHeader;
    8391          27 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8392             :     const GByte *pabyBLOB =
    8393          27 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8394             : 
    8395          54 :     if (nBLOBLen < 8 ||
    8396          27 :         GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) != OGRERR_NONE)
    8397             :     {
    8398             :         // Try also spatialite geometry blobs
    8399           0 :         OGRGeometry *poGeom = nullptr;
    8400           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeom) !=
    8401             :             OGRERR_NONE)
    8402             :         {
    8403           0 :             sqlite3_result_null(pContext);
    8404           0 :             return;
    8405             :         }
    8406           0 :         size_t nBLOBDestLen = 0;
    8407             :         GByte *pabyDestBLOB =
    8408           0 :             GPkgGeometryFromOGR(poGeom, nDestSRID, nullptr, &nBLOBDestLen);
    8409           0 :         if (!pabyDestBLOB)
    8410             :         {
    8411           0 :             sqlite3_result_null(pContext);
    8412           0 :             return;
    8413             :         }
    8414           0 :         sqlite3_result_blob(pContext, pabyDestBLOB,
    8415             :                             static_cast<int>(nBLOBDestLen), VSIFree);
    8416           0 :         return;
    8417             :     }
    8418             : 
    8419          27 :     GByte *pabyDestBLOB = static_cast<GByte *>(CPLMalloc(nBLOBLen));
    8420          27 :     memcpy(pabyDestBLOB, pabyBLOB, nBLOBLen);
    8421          27 :     int32_t nSRIDToSerialize = nDestSRID;
    8422          27 :     if (OGR_SWAP(sHeader.eByteOrder))
    8423           0 :         nSRIDToSerialize = CPL_SWAP32(nSRIDToSerialize);
    8424          27 :     memcpy(pabyDestBLOB + 4, &nSRIDToSerialize, 4);
    8425          27 :     sqlite3_result_blob(pContext, pabyDestBLOB, nBLOBLen, VSIFree);
    8426             : }
    8427             : 
    8428             : /************************************************************************/
    8429             : /*                   OGRGeoPackageSTMakeValid()                         */
    8430             : /************************************************************************/
    8431             : 
    8432           3 : static void OGRGeoPackageSTMakeValid(sqlite3_context *pContext, int argc,
    8433             :                                      sqlite3_value **argv)
    8434             : {
    8435           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8436             :     {
    8437           2 :         sqlite3_result_null(pContext);
    8438           2 :         return;
    8439             :     }
    8440           1 :     int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8441             :     const GByte *pabyBLOB =
    8442           1 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8443             : 
    8444             :     GPkgHeader sHeader;
    8445           1 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8446             :     {
    8447           0 :         sqlite3_result_null(pContext);
    8448           0 :         return;
    8449             :     }
    8450             : 
    8451             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8452           1 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8453           1 :     if (poGeom == nullptr)
    8454             :     {
    8455             :         // Try also spatialite geometry blobs
    8456           0 :         OGRGeometry *poGeomPtr = nullptr;
    8457           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8458             :             OGRERR_NONE)
    8459             :         {
    8460           0 :             sqlite3_result_null(pContext);
    8461           0 :             return;
    8462             :         }
    8463           0 :         poGeom.reset(poGeomPtr);
    8464             :     }
    8465           1 :     auto poValid = std::unique_ptr<OGRGeometry>(poGeom->MakeValid());
    8466           1 :     if (poValid == nullptr)
    8467             :     {
    8468           0 :         sqlite3_result_null(pContext);
    8469           0 :         return;
    8470             :     }
    8471             : 
    8472           1 :     size_t nBLOBDestLen = 0;
    8473           1 :     GByte *pabyDestBLOB = GPkgGeometryFromOGR(poValid.get(), sHeader.iSrsId,
    8474             :                                               nullptr, &nBLOBDestLen);
    8475           1 :     if (!pabyDestBLOB)
    8476             :     {
    8477           0 :         sqlite3_result_null(pContext);
    8478           0 :         return;
    8479             :     }
    8480           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8481             :                         VSIFree);
    8482             : }
    8483             : 
    8484             : /************************************************************************/
    8485             : /*                   OGRGeoPackageSTArea()                              */
    8486             : /************************************************************************/
    8487             : 
    8488          19 : static void OGRGeoPackageSTArea(sqlite3_context *pContext, int /*argc*/,
    8489             :                                 sqlite3_value **argv)
    8490             : {
    8491          19 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8492             :     {
    8493           1 :         sqlite3_result_null(pContext);
    8494          15 :         return;
    8495             :     }
    8496          18 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8497             :     const GByte *pabyBLOB =
    8498          18 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8499             : 
    8500             :     GPkgHeader sHeader;
    8501           0 :     std::unique_ptr<OGRGeometry> poGeom;
    8502          18 :     if (GPkgHeaderFromWKB(pabyBLOB, nBLOBLen, &sHeader) == OGRERR_NONE)
    8503             :     {
    8504          16 :         if (sHeader.bEmpty)
    8505             :         {
    8506           3 :             sqlite3_result_double(pContext, 0);
    8507          13 :             return;
    8508             :         }
    8509          13 :         const GByte *pabyWkb = pabyBLOB + sHeader.nHeaderLen;
    8510          13 :         size_t nWKBSize = nBLOBLen - sHeader.nHeaderLen;
    8511             :         bool bNeedSwap;
    8512             :         uint32_t nType;
    8513          13 :         if (OGRWKBGetGeomType(pabyWkb, nWKBSize, bNeedSwap, nType))
    8514             :         {
    8515          13 :             if (nType == wkbPolygon || nType == wkbPolygon25D ||
    8516          11 :                 nType == wkbPolygon + 1000 ||  // wkbPolygonZ
    8517          10 :                 nType == wkbPolygonM || nType == wkbPolygonZM)
    8518             :             {
    8519             :                 double dfArea;
    8520           5 :                 if (OGRWKBPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8521             :                 {
    8522           5 :                     sqlite3_result_double(pContext, dfArea);
    8523           5 :                     return;
    8524           0 :                 }
    8525             :             }
    8526           8 :             else if (nType == wkbMultiPolygon || nType == wkbMultiPolygon25D ||
    8527           6 :                      nType == wkbMultiPolygon + 1000 ||  // wkbMultiPolygonZ
    8528           5 :                      nType == wkbMultiPolygonM || nType == wkbMultiPolygonZM)
    8529             :             {
    8530             :                 double dfArea;
    8531           5 :                 if (OGRWKBMultiPolygonGetArea(pabyWkb, nWKBSize, dfArea))
    8532             :                 {
    8533           5 :                     sqlite3_result_double(pContext, dfArea);
    8534           5 :                     return;
    8535             :                 }
    8536             :             }
    8537             :         }
    8538             : 
    8539             :         // For curve geometries, fallback to OGRGeometry methods
    8540           3 :         poGeom.reset(GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8541             :     }
    8542             :     else
    8543             :     {
    8544             :         // Try also spatialite geometry blobs
    8545           2 :         OGRGeometry *poGeomPtr = nullptr;
    8546           2 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen, &poGeomPtr) !=
    8547             :             OGRERR_NONE)
    8548             :         {
    8549           1 :             sqlite3_result_null(pContext);
    8550           1 :             return;
    8551             :         }
    8552           1 :         poGeom.reset(poGeomPtr);
    8553             :     }
    8554           4 :     auto poSurface = dynamic_cast<OGRSurface *>(poGeom.get());
    8555           4 :     if (poSurface == nullptr)
    8556             :     {
    8557           2 :         auto poMultiSurface = dynamic_cast<OGRMultiSurface *>(poGeom.get());
    8558           2 :         if (poMultiSurface == nullptr)
    8559             :         {
    8560           1 :             sqlite3_result_double(pContext, 0);
    8561             :         }
    8562             :         else
    8563             :         {
    8564           1 :             sqlite3_result_double(pContext, poMultiSurface->get_Area());
    8565             :         }
    8566             :     }
    8567             :     else
    8568             :     {
    8569           2 :         sqlite3_result_double(pContext, poSurface->get_Area());
    8570             :     }
    8571             : }
    8572             : 
    8573             : /************************************************************************/
    8574             : /*                     OGRGeoPackageGeodesicArea()                      */
    8575             : /************************************************************************/
    8576             : 
    8577           5 : static void OGRGeoPackageGeodesicArea(sqlite3_context *pContext, int argc,
    8578             :                                       sqlite3_value **argv)
    8579             : {
    8580           5 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8581             :     {
    8582           1 :         sqlite3_result_null(pContext);
    8583           3 :         return;
    8584             :     }
    8585           4 :     if (sqlite3_value_int(argv[1]) != 1)
    8586             :     {
    8587           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8588             :                  "ST_Area(geom, use_ellipsoid) is only supported for "
    8589             :                  "use_ellipsoid = 1");
    8590             :     }
    8591             : 
    8592           4 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8593             :     const GByte *pabyBLOB =
    8594           4 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8595             :     GPkgHeader sHeader;
    8596           4 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8597             :     {
    8598           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8599           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8600           1 :         return;
    8601             :     }
    8602             : 
    8603             :     GDALGeoPackageDataset *poDS =
    8604           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8605             : 
    8606             :     std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSrcSRS(
    8607           3 :         poDS->GetSpatialRef(sHeader.iSrsId, true));
    8608           3 :     if (poSrcSRS == nullptr)
    8609             :     {
    8610           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    8611             :                  "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8612           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8613           1 :         return;
    8614             :     }
    8615             : 
    8616             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8617           2 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8618           2 :     if (poGeom == nullptr)
    8619             :     {
    8620             :         // Try also spatialite geometry blobs
    8621           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8622           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8623           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8624             :         {
    8625           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8626           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8627           0 :             return;
    8628             :         }
    8629           0 :         poGeom.reset(poGeomSpatialite);
    8630             :     }
    8631             : 
    8632           2 :     poGeom->assignSpatialReference(poSrcSRS.get());
    8633           2 :     sqlite3_result_double(
    8634             :         pContext, OGR_G_GeodesicArea(OGRGeometry::ToHandle(poGeom.get())));
    8635             : }
    8636             : 
    8637             : /************************************************************************/
    8638             : /*                   OGRGeoPackageLengthOrGeodesicLength()              */
    8639             : /************************************************************************/
    8640             : 
    8641           8 : static void OGRGeoPackageLengthOrGeodesicLength(sqlite3_context *pContext,
    8642             :                                                 int argc, sqlite3_value **argv)
    8643             : {
    8644           8 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    8645             :     {
    8646           2 :         sqlite3_result_null(pContext);
    8647           5 :         return;
    8648             :     }
    8649           6 :     if (argc == 2 && sqlite3_value_int(argv[1]) != 1)
    8650             :     {
    8651           2 :         CPLError(CE_Warning, CPLE_NotSupported,
    8652             :                  "ST_Length(geom, use_ellipsoid) is only supported for "
    8653             :                  "use_ellipsoid = 1");
    8654             :     }
    8655             : 
    8656           6 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8657             :     const GByte *pabyBLOB =
    8658           6 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8659             :     GPkgHeader sHeader;
    8660           6 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8661             :     {
    8662           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8663           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8664           2 :         return;
    8665             :     }
    8666             : 
    8667             :     GDALGeoPackageDataset *poDS =
    8668           4 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8669             : 
    8670           0 :     std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser> poSrcSRS;
    8671           4 :     if (argc == 2)
    8672             :     {
    8673           3 :         poSrcSRS = poDS->GetSpatialRef(sHeader.iSrsId, true);
    8674           3 :         if (!poSrcSRS)
    8675             :         {
    8676           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    8677             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8678           1 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8679           1 :             return;
    8680             :         }
    8681             :     }
    8682             : 
    8683             :     auto poGeom = std::unique_ptr<OGRGeometry>(
    8684           3 :         GPkgGeometryToOGR(pabyBLOB, nBLOBLen, nullptr));
    8685           3 :     if (poGeom == nullptr)
    8686             :     {
    8687             :         // Try also spatialite geometry blobs
    8688           0 :         OGRGeometry *poGeomSpatialite = nullptr;
    8689           0 :         if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8690           0 :                                               &poGeomSpatialite) != OGRERR_NONE)
    8691             :         {
    8692           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8693           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8694           0 :             return;
    8695             :         }
    8696           0 :         poGeom.reset(poGeomSpatialite);
    8697             :     }
    8698             : 
    8699           3 :     if (argc == 2)
    8700           2 :         poGeom->assignSpatialReference(poSrcSRS.get());
    8701             : 
    8702           6 :     sqlite3_result_double(
    8703             :         pContext,
    8704           1 :         argc == 1 ? OGR_G_Length(OGRGeometry::ToHandle(poGeom.get()))
    8705           2 :                   : OGR_G_GeodesicLength(OGRGeometry::ToHandle(poGeom.get())));
    8706             : }
    8707             : 
    8708             : /************************************************************************/
    8709             : /*                      OGRGeoPackageTransform()                        */
    8710             : /************************************************************************/
    8711             : 
    8712             : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8713             :                             sqlite3_value **argv);
    8714             : 
    8715          32 : void OGRGeoPackageTransform(sqlite3_context *pContext, int argc,
    8716             :                             sqlite3_value **argv)
    8717             : {
    8718          63 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB ||
    8719          31 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8720             :     {
    8721           2 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8722          32 :         return;
    8723             :     }
    8724             : 
    8725          30 :     const int nBLOBLen = sqlite3_value_bytes(argv[0]);
    8726             :     const GByte *pabyBLOB =
    8727          30 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    8728             :     GPkgHeader sHeader;
    8729          30 :     if (!OGRGeoPackageGetHeader(pContext, argc, argv, &sHeader, false, false))
    8730             :     {
    8731           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8732           1 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8733           1 :         return;
    8734             :     }
    8735             : 
    8736          29 :     const int nDestSRID = sqlite3_value_int(argv[1]);
    8737          29 :     if (sHeader.iSrsId == nDestSRID)
    8738             :     {
    8739             :         // Return blob unmodified
    8740           3 :         sqlite3_result_blob(pContext, pabyBLOB, nBLOBLen, SQLITE_TRANSIENT);
    8741           3 :         return;
    8742             :     }
    8743             : 
    8744             :     GDALGeoPackageDataset *poDS =
    8745          26 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8746             : 
    8747             :     // Try to get the cached coordinate transformation
    8748             :     OGRCoordinateTransformation *poCT;
    8749          26 :     if (poDS->m_nLastCachedCTSrcSRId == sHeader.iSrsId &&
    8750          20 :         poDS->m_nLastCachedCTDstSRId == nDestSRID)
    8751             :     {
    8752          20 :         poCT = poDS->m_poLastCachedCT.get();
    8753             :     }
    8754             :     else
    8755             :     {
    8756             :         std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
    8757           6 :             poSrcSRS(poDS->GetSpatialRef(sHeader.iSrsId, true));
    8758           6 :         if (poSrcSRS == nullptr)
    8759             :         {
    8760           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    8761             :                      "SRID set on geometry (%d) is invalid", sHeader.iSrsId);
    8762           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8763           0 :             return;
    8764             :         }
    8765             : 
    8766             :         std::unique_ptr<OGRSpatialReference, OGRSpatialReferenceReleaser>
    8767           6 :             poDstSRS(poDS->GetSpatialRef(nDestSRID, true));
    8768           6 :         if (poDstSRS == nullptr)
    8769             :         {
    8770           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Target SRID (%d) is invalid",
    8771             :                      nDestSRID);
    8772           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8773           0 :             return;
    8774             :         }
    8775             :         poCT =
    8776           6 :             OGRCreateCoordinateTransformation(poSrcSRS.get(), poDstSRS.get());
    8777           6 :         if (poCT == nullptr)
    8778             :         {
    8779           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8780           0 :             return;
    8781             :         }
    8782             : 
    8783             :         // Cache coordinate transformation for potential later reuse
    8784           6 :         poDS->m_nLastCachedCTSrcSRId = sHeader.iSrsId;
    8785           6 :         poDS->m_nLastCachedCTDstSRId = nDestSRID;
    8786           6 :         poDS->m_poLastCachedCT.reset(poCT);
    8787           6 :         poCT = poDS->m_poLastCachedCT.get();
    8788             :     }
    8789             : 
    8790          26 :     if (sHeader.nHeaderLen >= 8)
    8791             :     {
    8792          26 :         std::vector<GByte> &abyNewBLOB = poDS->m_abyWKBTransformCache;
    8793          26 :         abyNewBLOB.resize(nBLOBLen);
    8794          26 :         memcpy(abyNewBLOB.data(), pabyBLOB, nBLOBLen);
    8795             : 
    8796          26 :         OGREnvelope3D oEnv3d;
    8797          26 :         if (!OGRWKBTransform(abyNewBLOB.data() + sHeader.nHeaderLen,
    8798          26 :                              nBLOBLen - sHeader.nHeaderLen, poCT,
    8799          78 :                              poDS->m_oWKBTransformCache, oEnv3d) ||
    8800          26 :             !GPkgUpdateHeader(abyNewBLOB.data(), nBLOBLen, nDestSRID,
    8801             :                               oEnv3d.MinX, oEnv3d.MaxX, oEnv3d.MinY,
    8802             :                               oEnv3d.MaxY, oEnv3d.MinZ, oEnv3d.MaxZ))
    8803             :         {
    8804           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8805           0 :             sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8806           0 :             return;
    8807             :         }
    8808             : 
    8809          26 :         sqlite3_result_blob(pContext, abyNewBLOB.data(), nBLOBLen,
    8810             :                             SQLITE_TRANSIENT);
    8811          26 :         return;
    8812             :     }
    8813             : 
    8814             :     // Try also spatialite geometry blobs
    8815           0 :     OGRGeometry *poGeomSpatialite = nullptr;
    8816           0 :     if (OGRSQLiteImportSpatiaLiteGeometry(pabyBLOB, nBLOBLen,
    8817           0 :                                           &poGeomSpatialite) != OGRERR_NONE)
    8818             :     {
    8819           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid geometry");
    8820           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8821           0 :         return;
    8822             :     }
    8823           0 :     auto poGeom = std::unique_ptr<OGRGeometry>(poGeomSpatialite);
    8824             : 
    8825           0 :     if (poGeom->transform(poCT) != OGRERR_NONE)
    8826             :     {
    8827           0 :         sqlite3_result_blob(pContext, nullptr, 0, nullptr);
    8828           0 :         return;
    8829             :     }
    8830             : 
    8831           0 :     size_t nBLOBDestLen = 0;
    8832             :     GByte *pabyDestBLOB =
    8833           0 :         GPkgGeometryFromOGR(poGeom.get(), nDestSRID, nullptr, &nBLOBDestLen);
    8834           0 :     if (!pabyDestBLOB)
    8835             :     {
    8836           0 :         sqlite3_result_null(pContext);
    8837           0 :         return;
    8838             :     }
    8839           0 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    8840             :                         VSIFree);
    8841             : }
    8842             : 
    8843             : /************************************************************************/
    8844             : /*                      OGRGeoPackageSridFromAuthCRS()                  */
    8845             : /************************************************************************/
    8846             : 
    8847           4 : static void OGRGeoPackageSridFromAuthCRS(sqlite3_context *pContext,
    8848             :                                          int /*argc*/, sqlite3_value **argv)
    8849             : {
    8850           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8851           3 :         sqlite3_value_type(argv[1]) != SQLITE_INTEGER)
    8852             :     {
    8853           2 :         sqlite3_result_int(pContext, -1);
    8854           2 :         return;
    8855             :     }
    8856             : 
    8857             :     GDALGeoPackageDataset *poDS =
    8858           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8859             : 
    8860           2 :     char *pszSQL = sqlite3_mprintf(
    8861             :         "SELECT srs_id FROM gpkg_spatial_ref_sys WHERE "
    8862             :         "lower(organization) = lower('%q') AND organization_coordsys_id = %d",
    8863           2 :         sqlite3_value_text(argv[0]), sqlite3_value_int(argv[1]));
    8864           2 :     OGRErr err = OGRERR_NONE;
    8865           2 :     int nSRSId = SQLGetInteger(poDS->GetDB(), pszSQL, &err);
    8866           2 :     sqlite3_free(pszSQL);
    8867           2 :     if (err != OGRERR_NONE)
    8868           1 :         nSRSId = -1;
    8869           2 :     sqlite3_result_int(pContext, nSRSId);
    8870             : }
    8871             : 
    8872             : /************************************************************************/
    8873             : /*                    OGRGeoPackageImportFromEPSG()                     */
    8874             : /************************************************************************/
    8875             : 
    8876           4 : static void OGRGeoPackageImportFromEPSG(sqlite3_context *pContext, int /*argc*/,
    8877             :                                         sqlite3_value **argv)
    8878             : {
    8879           4 :     if (sqlite3_value_type(argv[0]) != SQLITE_INTEGER)
    8880             :     {
    8881           1 :         sqlite3_result_int(pContext, -1);
    8882           2 :         return;
    8883             :     }
    8884             : 
    8885             :     GDALGeoPackageDataset *poDS =
    8886           3 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8887           3 :     OGRSpatialReference oSRS;
    8888           3 :     if (oSRS.importFromEPSG(sqlite3_value_int(argv[0])) != OGRERR_NONE)
    8889             :     {
    8890           1 :         sqlite3_result_int(pContext, -1);
    8891           1 :         return;
    8892             :     }
    8893             : 
    8894           2 :     sqlite3_result_int(pContext, poDS->GetSrsId(&oSRS));
    8895             : }
    8896             : 
    8897             : /************************************************************************/
    8898             : /*               OGRGeoPackageRegisterGeometryExtension()               */
    8899             : /************************************************************************/
    8900             : 
    8901           1 : static void OGRGeoPackageRegisterGeometryExtension(sqlite3_context *pContext,
    8902             :                                                    int /*argc*/,
    8903             :                                                    sqlite3_value **argv)
    8904             : {
    8905           1 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8906           2 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT ||
    8907           1 :         sqlite3_value_type(argv[2]) != SQLITE_TEXT)
    8908             :     {
    8909           0 :         sqlite3_result_int(pContext, 0);
    8910           0 :         return;
    8911             :     }
    8912             : 
    8913             :     const char *pszTableName =
    8914           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8915             :     const char *pszGeomName =
    8916           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8917             :     const char *pszGeomType =
    8918           1 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[2]));
    8919             : 
    8920             :     GDALGeoPackageDataset *poDS =
    8921           1 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8922             : 
    8923           1 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8924           1 :         poDS->GetLayerByName(pszTableName));
    8925           1 :     if (poLyr == nullptr)
    8926             :     {
    8927           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8928           0 :         sqlite3_result_int(pContext, 0);
    8929           0 :         return;
    8930             :     }
    8931           1 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8932             :     {
    8933           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8934           0 :         sqlite3_result_int(pContext, 0);
    8935           0 :         return;
    8936             :     }
    8937           1 :     const OGRwkbGeometryType eGeomType = OGRFromOGCGeomType(pszGeomType);
    8938           1 :     if (eGeomType == wkbUnknown)
    8939             :     {
    8940           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry type name");
    8941           0 :         sqlite3_result_int(pContext, 0);
    8942           0 :         return;
    8943             :     }
    8944             : 
    8945           1 :     sqlite3_result_int(
    8946             :         pContext,
    8947           1 :         static_cast<int>(poLyr->CreateGeometryExtensionIfNecessary(eGeomType)));
    8948             : }
    8949             : 
    8950             : /************************************************************************/
    8951             : /*                  OGRGeoPackageCreateSpatialIndex()                   */
    8952             : /************************************************************************/
    8953             : 
    8954          14 : static void OGRGeoPackageCreateSpatialIndex(sqlite3_context *pContext,
    8955             :                                             int /*argc*/, sqlite3_value **argv)
    8956             : {
    8957          27 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8958          13 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8959             :     {
    8960           2 :         sqlite3_result_int(pContext, 0);
    8961           2 :         return;
    8962             :     }
    8963             : 
    8964             :     const char *pszTableName =
    8965          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    8966             :     const char *pszGeomName =
    8967          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    8968             :     GDALGeoPackageDataset *poDS =
    8969          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    8970             : 
    8971          12 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    8972          12 :         poDS->GetLayerByName(pszTableName));
    8973          12 :     if (poLyr == nullptr)
    8974             :     {
    8975           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    8976           1 :         sqlite3_result_int(pContext, 0);
    8977           1 :         return;
    8978             :     }
    8979          11 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    8980             :     {
    8981           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    8982           1 :         sqlite3_result_int(pContext, 0);
    8983           1 :         return;
    8984             :     }
    8985             : 
    8986          10 :     sqlite3_result_int(pContext, poLyr->CreateSpatialIndex());
    8987             : }
    8988             : 
    8989             : /************************************************************************/
    8990             : /*                  OGRGeoPackageDisableSpatialIndex()                  */
    8991             : /************************************************************************/
    8992             : 
    8993          12 : static void OGRGeoPackageDisableSpatialIndex(sqlite3_context *pContext,
    8994             :                                              int /*argc*/, sqlite3_value **argv)
    8995             : {
    8996          23 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    8997          11 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    8998             :     {
    8999           2 :         sqlite3_result_int(pContext, 0);
    9000           2 :         return;
    9001             :     }
    9002             : 
    9003             :     const char *pszTableName =
    9004          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9005             :     const char *pszGeomName =
    9006          10 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9007             :     GDALGeoPackageDataset *poDS =
    9008          10 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9009             : 
    9010          10 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9011          10 :         poDS->GetLayerByName(pszTableName));
    9012          10 :     if (poLyr == nullptr)
    9013             :     {
    9014           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9015           1 :         sqlite3_result_int(pContext, 0);
    9016           1 :         return;
    9017             :     }
    9018           9 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9019             :     {
    9020           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9021           1 :         sqlite3_result_int(pContext, 0);
    9022           1 :         return;
    9023             :     }
    9024             : 
    9025           8 :     sqlite3_result_int(pContext, poLyr->DropSpatialIndex(true));
    9026             : }
    9027             : 
    9028             : /************************************************************************/
    9029             : /*                  OGRGeoPackageHasSpatialIndex()                      */
    9030             : /************************************************************************/
    9031             : 
    9032          29 : static void OGRGeoPackageHasSpatialIndex(sqlite3_context *pContext,
    9033             :                                          int /*argc*/, sqlite3_value **argv)
    9034             : {
    9035          57 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9036          28 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9037             :     {
    9038           2 :         sqlite3_result_int(pContext, 0);
    9039           2 :         return;
    9040             :     }
    9041             : 
    9042             :     const char *pszTableName =
    9043          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9044             :     const char *pszGeomName =
    9045          27 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9046             :     GDALGeoPackageDataset *poDS =
    9047          27 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9048             : 
    9049          27 :     OGRGeoPackageTableLayer *poLyr = cpl::down_cast<OGRGeoPackageTableLayer *>(
    9050          27 :         poDS->GetLayerByName(pszTableName));
    9051          27 :     if (poLyr == nullptr)
    9052             :     {
    9053           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown layer name");
    9054           1 :         sqlite3_result_int(pContext, 0);
    9055           1 :         return;
    9056             :     }
    9057          26 :     if (!EQUAL(poLyr->GetGeometryColumn(), pszGeomName))
    9058             :     {
    9059           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Unknown geometry column name");
    9060           1 :         sqlite3_result_int(pContext, 0);
    9061           1 :         return;
    9062             :     }
    9063             : 
    9064          25 :     poLyr->RunDeferredCreationIfNecessary();
    9065          25 :     poLyr->CreateSpatialIndexIfNecessary();
    9066             : 
    9067          25 :     sqlite3_result_int(pContext, poLyr->HasSpatialIndex());
    9068             : }
    9069             : 
    9070             : /************************************************************************/
    9071             : /*                       GPKG_hstore_get_value()                        */
    9072             : /************************************************************************/
    9073             : 
    9074           4 : static void GPKG_hstore_get_value(sqlite3_context *pContext, int /*argc*/,
    9075             :                                   sqlite3_value **argv)
    9076             : {
    9077           7 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT ||
    9078           3 :         sqlite3_value_type(argv[1]) != SQLITE_TEXT)
    9079             :     {
    9080           2 :         sqlite3_result_null(pContext);
    9081           2 :         return;
    9082             :     }
    9083             : 
    9084             :     const char *pszHStore =
    9085           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9086             :     const char *pszSearchedKey =
    9087           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[1]));
    9088           2 :     char *pszValue = OGRHStoreGetValue(pszHStore, pszSearchedKey);
    9089           2 :     if (pszValue != nullptr)
    9090           1 :         sqlite3_result_text(pContext, pszValue, -1, CPLFree);
    9091             :     else
    9092           1 :         sqlite3_result_null(pContext);
    9093             : }
    9094             : 
    9095             : /************************************************************************/
    9096             : /*                      GPKG_GDAL_GetMemFileFromBlob()                  */
    9097             : /************************************************************************/
    9098             : 
    9099         105 : static CPLString GPKG_GDAL_GetMemFileFromBlob(sqlite3_value **argv)
    9100             : {
    9101         105 :     int nBytes = sqlite3_value_bytes(argv[0]);
    9102             :     const GByte *pabyBLOB =
    9103         105 :         reinterpret_cast<const GByte *>(sqlite3_value_blob(argv[0]));
    9104             :     CPLString osMemFileName(
    9105         105 :         VSIMemGenerateHiddenFilename("GPKG_GDAL_GetMemFileFromBlob"));
    9106         105 :     VSILFILE *fp = VSIFileFromMemBuffer(
    9107             :         osMemFileName.c_str(), const_cast<GByte *>(pabyBLOB), nBytes, FALSE);
    9108         105 :     VSIFCloseL(fp);
    9109         105 :     return osMemFileName;
    9110             : }
    9111             : 
    9112             : /************************************************************************/
    9113             : /*                       GPKG_GDAL_GetMimeType()                        */
    9114             : /************************************************************************/
    9115             : 
    9116          35 : static void GPKG_GDAL_GetMimeType(sqlite3_context *pContext, int /*argc*/,
    9117             :                                   sqlite3_value **argv)
    9118             : {
    9119          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9120             :     {
    9121           0 :         sqlite3_result_null(pContext);
    9122           0 :         return;
    9123             :     }
    9124             : 
    9125          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9126             :     GDALDriver *poDriver =
    9127          35 :         GDALDriver::FromHandle(GDALIdentifyDriver(osMemFileName, nullptr));
    9128          35 :     if (poDriver != nullptr)
    9129             :     {
    9130          35 :         const char *pszRes = nullptr;
    9131          35 :         if (EQUAL(poDriver->GetDescription(), "PNG"))
    9132          23 :             pszRes = "image/png";
    9133          12 :         else if (EQUAL(poDriver->GetDescription(), "JPEG"))
    9134           6 :             pszRes = "image/jpeg";
    9135           6 :         else if (EQUAL(poDriver->GetDescription(), "WEBP"))
    9136           6 :             pszRes = "image/x-webp";
    9137           0 :         else if (EQUAL(poDriver->GetDescription(), "GTIFF"))
    9138           0 :             pszRes = "image/tiff";
    9139             :         else
    9140           0 :             pszRes = CPLSPrintf("gdal/%s", poDriver->GetDescription());
    9141          35 :         sqlite3_result_text(pContext, pszRes, -1, SQLITE_TRANSIENT);
    9142             :     }
    9143             :     else
    9144           0 :         sqlite3_result_null(pContext);
    9145          35 :     VSIUnlink(osMemFileName);
    9146             : }
    9147             : 
    9148             : /************************************************************************/
    9149             : /*                       GPKG_GDAL_GetBandCount()                       */
    9150             : /************************************************************************/
    9151             : 
    9152          35 : static void GPKG_GDAL_GetBandCount(sqlite3_context *pContext, int /*argc*/,
    9153             :                                    sqlite3_value **argv)
    9154             : {
    9155          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9156             :     {
    9157           0 :         sqlite3_result_null(pContext);
    9158           0 :         return;
    9159             :     }
    9160             : 
    9161          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9162             :     auto poDS = std::unique_ptr<GDALDataset>(
    9163             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9164          70 :                           nullptr, nullptr, nullptr));
    9165          35 :     if (poDS != nullptr)
    9166             :     {
    9167          35 :         sqlite3_result_int(pContext, poDS->GetRasterCount());
    9168             :     }
    9169             :     else
    9170           0 :         sqlite3_result_null(pContext);
    9171          35 :     VSIUnlink(osMemFileName);
    9172             : }
    9173             : 
    9174             : /************************************************************************/
    9175             : /*                       GPKG_GDAL_HasColorTable()                      */
    9176             : /************************************************************************/
    9177             : 
    9178          35 : static void GPKG_GDAL_HasColorTable(sqlite3_context *pContext, int /*argc*/,
    9179             :                                     sqlite3_value **argv)
    9180             : {
    9181          35 :     if (sqlite3_value_type(argv[0]) != SQLITE_BLOB)
    9182             :     {
    9183           0 :         sqlite3_result_null(pContext);
    9184           0 :         return;
    9185             :     }
    9186             : 
    9187          70 :     CPLString osMemFileName(GPKG_GDAL_GetMemFileFromBlob(argv));
    9188             :     auto poDS = std::unique_ptr<GDALDataset>(
    9189             :         GDALDataset::Open(osMemFileName, GDAL_OF_RASTER | GDAL_OF_INTERNAL,
    9190          70 :                           nullptr, nullptr, nullptr));
    9191          35 :     if (poDS != nullptr)
    9192             :     {
    9193          35 :         sqlite3_result_int(
    9194          46 :             pContext, poDS->GetRasterCount() == 1 &&
    9195          11 :                           poDS->GetRasterBand(1)->GetColorTable() != nullptr);
    9196             :     }
    9197             :     else
    9198           0 :         sqlite3_result_null(pContext);
    9199          35 :     VSIUnlink(osMemFileName);
    9200             : }
    9201             : 
    9202             : /************************************************************************/
    9203             : /*                      GetRasterLayerDataset()                         */
    9204             : /************************************************************************/
    9205             : 
    9206             : GDALDataset *
    9207          12 : GDALGeoPackageDataset::GetRasterLayerDataset(const char *pszLayerName)
    9208             : {
    9209          12 :     const auto oIter = m_oCachedRasterDS.find(pszLayerName);
    9210          12 :     if (oIter != m_oCachedRasterDS.end())
    9211          10 :         return oIter->second.get();
    9212             : 
    9213             :     auto poDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
    9214           4 :         (std::string("GPKG:\"") + m_pszFilename + "\":" + pszLayerName).c_str(),
    9215           4 :         GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR));
    9216           2 :     if (!poDS)
    9217             :     {
    9218           0 :         return nullptr;
    9219             :     }
    9220           2 :     m_oCachedRasterDS[pszLayerName] = std::move(poDS);
    9221           2 :     return m_oCachedRasterDS[pszLayerName].get();
    9222             : }
    9223             : 
    9224             : /************************************************************************/
    9225             : /*                   GPKG_gdal_get_layer_pixel_value()                  */
    9226             : /************************************************************************/
    9227             : 
    9228             : // NOTE: keep in sync implementations in ogrsqlitesqlfunctionscommon.cpp
    9229             : // and ogrgeopackagedatasource.cpp
    9230          13 : static void GPKG_gdal_get_layer_pixel_value(sqlite3_context *pContext, int argc,
    9231             :                                             sqlite3_value **argv)
    9232             : {
    9233          13 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9234             :     {
    9235           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    9236             :                  "Invalid arguments to gdal_get_layer_pixel_value()");
    9237           1 :         sqlite3_result_null(pContext);
    9238           1 :         return;
    9239             :     }
    9240             : 
    9241             :     const char *pszLayerName =
    9242          12 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9243             : 
    9244             :     GDALGeoPackageDataset *poGlobalDS =
    9245          12 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9246          12 :     auto poDS = poGlobalDS->GetRasterLayerDataset(pszLayerName);
    9247          12 :     if (!poDS)
    9248             :     {
    9249           0 :         sqlite3_result_null(pContext);
    9250           0 :         return;
    9251             :     }
    9252             : 
    9253          12 :     OGRSQLite_gdal_get_pixel_value_common("gdal_get_layer_pixel_value",
    9254             :                                           pContext, argc, argv, poDS);
    9255             : }
    9256             : 
    9257             : /************************************************************************/
    9258             : /*                       GPKG_ogr_layer_Extent()                        */
    9259             : /************************************************************************/
    9260             : 
    9261           3 : static void GPKG_ogr_layer_Extent(sqlite3_context *pContext, int /*argc*/,
    9262             :                                   sqlite3_value **argv)
    9263             : {
    9264           3 :     if (sqlite3_value_type(argv[0]) != SQLITE_TEXT)
    9265             :     {
    9266           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Invalid argument type",
    9267             :                  "ogr_layer_Extent");
    9268           1 :         sqlite3_result_null(pContext);
    9269           2 :         return;
    9270             :     }
    9271             : 
    9272             :     const char *pszLayerName =
    9273           2 :         reinterpret_cast<const char *>(sqlite3_value_text(argv[0]));
    9274             :     GDALGeoPackageDataset *poDS =
    9275           2 :         static_cast<GDALGeoPackageDataset *>(sqlite3_user_data(pContext));
    9276           2 :     OGRLayer *poLayer = poDS->GetLayerByName(pszLayerName);
    9277           2 :     if (!poLayer)
    9278             :     {
    9279           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: unknown layer",
    9280             :                  "ogr_layer_Extent");
    9281           1 :         sqlite3_result_null(pContext);
    9282           1 :         return;
    9283             :     }
    9284             : 
    9285           1 :     if (poLayer->GetGeomType() == wkbNone)
    9286             :     {
    9287           0 :         sqlite3_result_null(pContext);
    9288           0 :         return;
    9289             :     }
    9290             : 
    9291           1 :     OGREnvelope sExtent;
    9292           1 :     if (poLayer->GetExtent(&sExtent) != OGRERR_NONE)
    9293             :     {
    9294           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s: Cannot fetch layer extent",
    9295             :                  "ogr_layer_Extent");
    9296           0 :         sqlite3_result_null(pContext);
    9297           0 :         return;
    9298             :     }
    9299             : 
    9300           1 :     OGRPolygon oPoly;
    9301           1 :     auto poRing = std::make_unique<OGRLinearRing>();
    9302           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9303           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MinY);
    9304           1 :     poRing->addPoint(sExtent.MaxX, sExtent.MaxY);
    9305           1 :     poRing->addPoint(sExtent.MinX, sExtent.MaxY);
    9306           1 :     poRing->addPoint(sExtent.MinX, sExtent.MinY);
    9307           1 :     oPoly.addRing(std::move(poRing));
    9308             : 
    9309           1 :     const auto poSRS = poLayer->GetSpatialRef();
    9310           1 :     const int nSRID = poDS->GetSrsId(poSRS);
    9311           1 :     size_t nBLOBDestLen = 0;
    9312             :     GByte *pabyDestBLOB =
    9313           1 :         GPkgGeometryFromOGR(&oPoly, nSRID, nullptr, &nBLOBDestLen);
    9314           1 :     if (!pabyDestBLOB)
    9315             :     {
    9316           0 :         sqlite3_result_null(pContext);
    9317           0 :         return;
    9318             :     }
    9319           1 :     sqlite3_result_blob(pContext, pabyDestBLOB, static_cast<int>(nBLOBDestLen),
    9320             :                         VSIFree);
    9321             : }
    9322             : 
    9323             : /************************************************************************/
    9324             : /*                      InstallSQLFunctions()                           */
    9325             : /************************************************************************/
    9326             : 
    9327             : #ifndef SQLITE_DETERMINISTIC
    9328             : #define SQLITE_DETERMINISTIC 0
    9329             : #endif
    9330             : 
    9331             : #ifndef SQLITE_INNOCUOUS
    9332             : #define SQLITE_INNOCUOUS 0
    9333             : #endif
    9334             : 
    9335             : #ifndef UTF8_INNOCUOUS
    9336             : #define UTF8_INNOCUOUS (SQLITE_UTF8 | SQLITE_DETERMINISTIC | SQLITE_INNOCUOUS)
    9337             : #endif
    9338             : 
    9339        2198 : void GDALGeoPackageDataset::InstallSQLFunctions()
    9340             : {
    9341        2198 :     InitSpatialite();
    9342             : 
    9343             :     // Enable SpatiaLite 4.3 "amphibious" mode, i.e. that SpatiaLite functions
    9344             :     // that take geometries will accept GPKG encoded geometries without
    9345             :     // explicit conversion.
    9346             :     // Use sqlite3_exec() instead of SQLCommand() since we don't want verbose
    9347             :     // error.
    9348        2198 :     sqlite3_exec(hDB, "SELECT EnableGpkgAmphibiousMode()", nullptr, nullptr,
    9349             :                  nullptr);
    9350             : 
    9351             :     /* Used by RTree Spatial Index Extension */
    9352        2198 :     sqlite3_create_function(hDB, "ST_MinX", 1, UTF8_INNOCUOUS, nullptr,
    9353             :                             OGRGeoPackageSTMinX, nullptr, nullptr);
    9354        2198 :     sqlite3_create_function(hDB, "ST_MinY", 1, UTF8_INNOCUOUS, nullptr,
    9355             :                             OGRGeoPackageSTMinY, nullptr, nullptr);
    9356        2198 :     sqlite3_create_function(hDB, "ST_MaxX", 1, UTF8_INNOCUOUS, nullptr,
    9357             :                             OGRGeoPackageSTMaxX, nullptr, nullptr);
    9358        2198 :     sqlite3_create_function(hDB, "ST_MaxY", 1, UTF8_INNOCUOUS, nullptr,
    9359             :                             OGRGeoPackageSTMaxY, nullptr, nullptr);
    9360        2198 :     sqlite3_create_function(hDB, "ST_IsEmpty", 1, UTF8_INNOCUOUS, nullptr,
    9361             :                             OGRGeoPackageSTIsEmpty, nullptr, nullptr);
    9362             : 
    9363             :     /* Used by Geometry Type Triggers Extension */
    9364        2198 :     sqlite3_create_function(hDB, "ST_GeometryType", 1, UTF8_INNOCUOUS, nullptr,
    9365             :                             OGRGeoPackageSTGeometryType, nullptr, nullptr);
    9366        2198 :     sqlite3_create_function(hDB, "GPKG_IsAssignable", 2, UTF8_INNOCUOUS,
    9367             :                             nullptr, OGRGeoPackageGPKGIsAssignable, nullptr,
    9368             :                             nullptr);
    9369             : 
    9370             :     /* Used by Geometry SRS ID Triggers Extension */
    9371        2198 :     sqlite3_create_function(hDB, "ST_SRID", 1, UTF8_INNOCUOUS, nullptr,
    9372             :                             OGRGeoPackageSTSRID, nullptr, nullptr);
    9373             : 
    9374             :     /* Spatialite-like functions */
    9375        2198 :     sqlite3_create_function(hDB, "CreateSpatialIndex", 2, SQLITE_UTF8, this,
    9376             :                             OGRGeoPackageCreateSpatialIndex, nullptr, nullptr);
    9377        2198 :     sqlite3_create_function(hDB, "DisableSpatialIndex", 2, SQLITE_UTF8, this,
    9378             :                             OGRGeoPackageDisableSpatialIndex, nullptr, nullptr);
    9379        2198 :     sqlite3_create_function(hDB, "HasSpatialIndex", 2, SQLITE_UTF8, this,
    9380             :                             OGRGeoPackageHasSpatialIndex, nullptr, nullptr);
    9381             : 
    9382             :     // HSTORE functions
    9383        2198 :     sqlite3_create_function(hDB, "hstore_get_value", 2, UTF8_INNOCUOUS, nullptr,
    9384             :                             GPKG_hstore_get_value, nullptr, nullptr);
    9385             : 
    9386             :     // Override a few Spatialite functions to work with gpkg_spatial_ref_sys
    9387        2198 :     sqlite3_create_function(hDB, "ST_Transform", 2, UTF8_INNOCUOUS, this,
    9388             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9389        2198 :     sqlite3_create_function(hDB, "Transform", 2, UTF8_INNOCUOUS, this,
    9390             :                             OGRGeoPackageTransform, nullptr, nullptr);
    9391        2198 :     sqlite3_create_function(hDB, "SridFromAuthCRS", 2, SQLITE_UTF8, this,
    9392             :                             OGRGeoPackageSridFromAuthCRS, nullptr, nullptr);
    9393             : 
    9394        2198 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9395             :                             OGRGeoPackageSTEnvelopesIntersectsTwoParams,
    9396             :                             nullptr, nullptr);
    9397        2198 :     sqlite3_create_function(
    9398             :         hDB, "ST_EnvelopesIntersects", 2, UTF8_INNOCUOUS, nullptr,
    9399             :         OGRGeoPackageSTEnvelopesIntersectsTwoParams, nullptr, nullptr);
    9400             : 
    9401        2198 :     sqlite3_create_function(hDB, "ST_EnvIntersects", 5, UTF8_INNOCUOUS, nullptr,
    9402             :                             OGRGeoPackageSTEnvelopesIntersects, nullptr,
    9403             :                             nullptr);
    9404        2198 :     sqlite3_create_function(hDB, "ST_EnvelopesIntersects", 5, UTF8_INNOCUOUS,
    9405             :                             nullptr, OGRGeoPackageSTEnvelopesIntersects,
    9406             :                             nullptr, nullptr);
    9407             : 
    9408             :     // Implementation that directly hacks the GeoPackage geometry blob header
    9409        2198 :     sqlite3_create_function(hDB, "SetSRID", 2, UTF8_INNOCUOUS, nullptr,
    9410             :                             OGRGeoPackageSetSRID, nullptr, nullptr);
    9411             : 
    9412             :     // GDAL specific function
    9413        2198 :     sqlite3_create_function(hDB, "ImportFromEPSG", 1, SQLITE_UTF8, this,
    9414             :                             OGRGeoPackageImportFromEPSG, nullptr, nullptr);
    9415             : 
    9416             :     // May be used by ogrmerge.py
    9417        2198 :     sqlite3_create_function(hDB, "RegisterGeometryExtension", 3, SQLITE_UTF8,
    9418             :                             this, OGRGeoPackageRegisterGeometryExtension,
    9419             :                             nullptr, nullptr);
    9420             : 
    9421        2198 :     if (OGRGeometryFactory::haveGEOS())
    9422             :     {
    9423        2198 :         sqlite3_create_function(hDB, "ST_MakeValid", 1, UTF8_INNOCUOUS, nullptr,
    9424             :                                 OGRGeoPackageSTMakeValid, nullptr, nullptr);
    9425             :     }
    9426             : 
    9427        2198 :     sqlite3_create_function(hDB, "ST_Length", 1, UTF8_INNOCUOUS, nullptr,
    9428             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9429             :                             nullptr);
    9430        2198 :     sqlite3_create_function(hDB, "ST_Length", 2, UTF8_INNOCUOUS, this,
    9431             :                             OGRGeoPackageLengthOrGeodesicLength, nullptr,
    9432             :                             nullptr);
    9433             : 
    9434        2198 :     sqlite3_create_function(hDB, "ST_Area", 1, UTF8_INNOCUOUS, nullptr,
    9435             :                             OGRGeoPackageSTArea, nullptr, nullptr);
    9436        2198 :     sqlite3_create_function(hDB, "ST_Area", 2, UTF8_INNOCUOUS, this,
    9437             :                             OGRGeoPackageGeodesicArea, nullptr, nullptr);
    9438             : 
    9439             :     // Debug functions
    9440        2198 :     if (CPLTestBool(CPLGetConfigOption("GPKG_DEBUG", "FALSE")))
    9441             :     {
    9442         422 :         sqlite3_create_function(hDB, "GDAL_GetMimeType", 1,
    9443             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9444             :                                 GPKG_GDAL_GetMimeType, nullptr, nullptr);
    9445         422 :         sqlite3_create_function(hDB, "GDAL_GetBandCount", 1,
    9446             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9447             :                                 GPKG_GDAL_GetBandCount, nullptr, nullptr);
    9448         422 :         sqlite3_create_function(hDB, "GDAL_HasColorTable", 1,
    9449             :                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
    9450             :                                 GPKG_GDAL_HasColorTable, nullptr, nullptr);
    9451             :     }
    9452             : 
    9453        2198 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 5, SQLITE_UTF8,
    9454             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9455             :                             nullptr);
    9456        2198 :     sqlite3_create_function(hDB, "gdal_get_layer_pixel_value", 6, SQLITE_UTF8,
    9457             :                             this, GPKG_gdal_get_layer_pixel_value, nullptr,
    9458             :                             nullptr);
    9459             : 
    9460             :     // Function from VirtualOGR
    9461        2198 :     sqlite3_create_function(hDB, "ogr_layer_Extent", 1, SQLITE_UTF8, this,
    9462             :                             GPKG_ogr_layer_Extent, nullptr, nullptr);
    9463             : 
    9464        2198 :     m_pSQLFunctionData = OGRSQLiteRegisterSQLFunctionsCommon(hDB);
    9465        2198 : }
    9466             : 
    9467             : /************************************************************************/
    9468             : /*                         OpenOrCreateDB()                             */
    9469             : /************************************************************************/
    9470             : 
    9471        2202 : bool GDALGeoPackageDataset::OpenOrCreateDB(int flags)
    9472             : {
    9473        2202 :     const bool bSuccess = OGRSQLiteBaseDataSource::OpenOrCreateDB(
    9474             :         flags, /*bRegisterOGR2SQLiteExtensions=*/false,
    9475             :         /*bLoadExtensions=*/true);
    9476        2202 :     if (!bSuccess)
    9477           9 :         return false;
    9478             : 
    9479             :     // Turning on recursive_triggers is needed so that DELETE triggers fire
    9480             :     // in a INSERT OR REPLACE statement. In particular this is needed to
    9481             :     // make sure gpkg_ogr_contents.feature_count is properly updated.
    9482        2193 :     SQLCommand(hDB, "PRAGMA recursive_triggers = 1");
    9483             : 
    9484        2193 :     InstallSQLFunctions();
    9485             : 
    9486             :     const char *pszSqlitePragma =
    9487        2193 :         CPLGetConfigOption("OGR_SQLITE_PRAGMA", nullptr);
    9488        2193 :     OGRErr eErr = OGRERR_NONE;
    9489           6 :     if ((!pszSqlitePragma || !strstr(pszSqlitePragma, "trusted_schema")) &&
    9490             :         // Older sqlite versions don't have this pragma
    9491        4392 :         SQLGetInteger(hDB, "PRAGMA trusted_schema", &eErr) == 0 &&
    9492        2193 :         eErr == OGRERR_NONE)
    9493             :     {
    9494        2193 :         bool bNeedsTrustedSchema = false;
    9495             : 
    9496             :         // Current SQLite versions require PRAGMA trusted_schema = 1 to be
    9497             :         // able to use the RTree from triggers, which is only needed when
    9498             :         // modifying the RTree.
    9499        5384 :         if (((flags & SQLITE_OPEN_READWRITE) != 0 ||
    9500        3388 :              (flags & SQLITE_OPEN_CREATE) != 0) &&
    9501        1195 :             OGRSQLiteRTreeRequiresTrustedSchemaOn())
    9502             :         {
    9503        1195 :             bNeedsTrustedSchema = true;
    9504             :         }
    9505             : 
    9506             : #ifdef HAVE_SPATIALITE
    9507             :         // Spatialite <= 5.1.0 doesn't declare its functions as SQLITE_INNOCUOUS
    9508         998 :         if (!bNeedsTrustedSchema && HasExtensionsTable() &&
    9509         911 :             SQLGetInteger(
    9510             :                 hDB,
    9511             :                 "SELECT 1 FROM gpkg_extensions WHERE "
    9512             :                 "extension_name ='gdal_spatialite_computed_geom_column'",
    9513           1 :                 nullptr) == 1 &&
    9514        3191 :             SpatialiteRequiresTrustedSchemaOn() && AreSpatialiteTriggersSafe())
    9515             :         {
    9516           1 :             bNeedsTrustedSchema = true;
    9517             :         }
    9518             : #endif
    9519             : 
    9520        2193 :         if (bNeedsTrustedSchema)
    9521             :         {
    9522        1196 :             CPLDebug("GPKG", "Setting PRAGMA trusted_schema = 1");
    9523        1196 :             SQLCommand(hDB, "PRAGMA trusted_schema = 1");
    9524             :         }
    9525             :     }
    9526             : 
    9527             :     const char *pszPreludeStatements =
    9528        2193 :         CSLFetchNameValue(papszOpenOptions, "PRELUDE_STATEMENTS");
    9529        2193 :     if (pszPreludeStatements)
    9530             :     {
    9531           2 :         if (SQLCommand(hDB, pszPreludeStatements) != OGRERR_NONE)
    9532           0 :             return false;
    9533             :     }
    9534             : 
    9535        2193 :     return true;
    9536             : }
    9537             : 
    9538             : /************************************************************************/
    9539             : /*                   GetLayerWithGetSpatialWhereByName()                */
    9540             : /************************************************************************/
    9541             : 
    9542             : std::pair<OGRLayer *, IOGRSQLiteGetSpatialWhere *>
    9543          90 : GDALGeoPackageDataset::GetLayerWithGetSpatialWhereByName(const char *pszName)
    9544             : {
    9545             :     OGRGeoPackageLayer *poRet =
    9546          90 :         cpl::down_cast<OGRGeoPackageLayer *>(GetLayerByName(pszName));
    9547          90 :     return std::pair(poRet, poRet);
    9548             : }
    9549             : 
    9550             : /************************************************************************/
    9551             : /*                       CommitTransaction()                            */
    9552             : /************************************************************************/
    9553             : 
    9554         336 : OGRErr GDALGeoPackageDataset::CommitTransaction()
    9555             : 
    9556             : {
    9557         336 :     if (m_nSoftTransactionLevel == 1)
    9558             :     {
    9559         330 :         FlushMetadata();
    9560         709 :         for (auto &poLayer : m_apoLayers)
    9561             :         {
    9562         379 :             poLayer->DoJobAtTransactionCommit();
    9563             :         }
    9564             :     }
    9565             : 
    9566         336 :     return OGRSQLiteBaseDataSource::CommitTransaction();
    9567             : }
    9568             : 
    9569             : /************************************************************************/
    9570             : /*                     RollbackTransaction()                            */
    9571             : /************************************************************************/
    9572             : 
    9573          35 : OGRErr GDALGeoPackageDataset::RollbackTransaction()
    9574             : 
    9575             : {
    9576             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9577          70 :     std::vector<bool> abAddTriggers;
    9578          35 :     std::vector<bool> abTriggersDeletedInTransaction;
    9579             : #endif
    9580          35 :     if (m_nSoftTransactionLevel == 1)
    9581             :     {
    9582          34 :         FlushMetadata();
    9583          70 :         for (auto &poLayer : m_apoLayers)
    9584             :         {
    9585             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9586          36 :             abAddTriggers.push_back(poLayer->GetAddOGRFeatureCountTriggers());
    9587          36 :             abTriggersDeletedInTransaction.push_back(
    9588          36 :                 poLayer->GetOGRFeatureCountTriggersDeletedInTransaction());
    9589          36 :             poLayer->SetAddOGRFeatureCountTriggers(false);
    9590             : #endif
    9591          36 :             poLayer->DoJobAtTransactionRollback();
    9592             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9593          36 :             poLayer->DisableFeatureCount();
    9594             : #endif
    9595             :         }
    9596             :     }
    9597             : 
    9598          35 :     const OGRErr eErr = OGRSQLiteBaseDataSource::RollbackTransaction();
    9599             : 
    9600             : #ifdef ENABLE_GPKG_OGR_CONTENTS
    9601          35 :     if (!abAddTriggers.empty())
    9602             :     {
    9603          68 :         for (size_t i = 0; i < m_apoLayers.size(); ++i)
    9604             :         {
    9605          36 :             auto &poLayer = m_apoLayers[i];
    9606          36 :             if (abTriggersDeletedInTransaction[i])
    9607             :             {
    9608           7 :                 poLayer->SetOGRFeatureCountTriggersEnabled(true);
    9609             :             }
    9610             :             else
    9611             :             {
    9612          29 :                 poLayer->SetAddOGRFeatureCountTriggers(abAddTriggers[i]);
    9613             :             }
    9614             :         }
    9615             :     }
    9616             : #endif
    9617          70 :     return eErr;
    9618             : }
    9619             : 
    9620             : /************************************************************************/
    9621             : /*                       GetGeometryTypeString()                        */
    9622             : /************************************************************************/
    9623             : 
    9624             : const char *
    9625        1549 : GDALGeoPackageDataset::GetGeometryTypeString(OGRwkbGeometryType eType)
    9626             : {
    9627        1549 :     const char *pszGPKGGeomType = OGRToOGCGeomType(eType);
    9628        1561 :     if (EQUAL(pszGPKGGeomType, "GEOMETRYCOLLECTION") &&
    9629          12 :         CPLTestBool(CPLGetConfigOption("OGR_GPKG_GEOMCOLLECTION", "NO")))
    9630             :     {
    9631           0 :         pszGPKGGeomType = "GEOMCOLLECTION";
    9632             :     }
    9633        1549 :     return pszGPKGGeomType;
    9634             : }
    9635             : 
    9636             : /************************************************************************/
    9637             : /*                           GetFieldDomainNames()                      */
    9638             : /************************************************************************/
    9639             : 
    9640             : std::vector<std::string>
    9641          11 : GDALGeoPackageDataset::GetFieldDomainNames(CSLConstList) const
    9642             : {
    9643          11 :     if (!HasDataColumnConstraintsTable())
    9644           4 :         return std::vector<std::string>();
    9645             : 
    9646          14 :     std::vector<std::string> oDomainNamesList;
    9647             : 
    9648           7 :     std::unique_ptr<SQLResult> oResultTable;
    9649             :     {
    9650             :         std::string osSQL =
    9651             :             "SELECT DISTINCT constraint_name "
    9652             :             "FROM gpkg_data_column_constraints "
    9653             :             "WHERE constraint_name NOT LIKE '_%_domain_description' "
    9654             :             "ORDER BY constraint_name "
    9655           7 :             "LIMIT 10000"  // to avoid denial of service
    9656             :             ;
    9657           7 :         oResultTable = SQLQuery(hDB, osSQL.c_str());
    9658           7 :         if (!oResultTable)
    9659           0 :             return oDomainNamesList;
    9660             :     }
    9661             : 
    9662           7 :     if (oResultTable->RowCount() == 10000)
    9663             :     {
    9664           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9665             :                  "Number of rows returned for field domain names has been "
    9666             :                  "truncated.");
    9667             :     }
    9668           7 :     else if (oResultTable->RowCount() > 0)
    9669             :     {
    9670           7 :         oDomainNamesList.reserve(oResultTable->RowCount());
    9671          89 :         for (int i = 0; i < oResultTable->RowCount(); i++)
    9672             :         {
    9673          82 :             const char *pszConstraintName = oResultTable->GetValue(0, i);
    9674          82 :             if (!pszConstraintName)
    9675           0 :                 continue;
    9676             : 
    9677          82 :             oDomainNamesList.emplace_back(pszConstraintName);
    9678             :         }
    9679             :     }
    9680             : 
    9681           7 :     return oDomainNamesList;
    9682             : }
    9683             : 
    9684             : /************************************************************************/
    9685             : /*                           GetFieldDomain()                           */
    9686             : /************************************************************************/
    9687             : 
    9688             : const OGRFieldDomain *
    9689         102 : GDALGeoPackageDataset::GetFieldDomain(const std::string &name) const
    9690             : {
    9691         102 :     const auto baseRet = GDALDataset::GetFieldDomain(name);
    9692         102 :     if (baseRet)
    9693          42 :         return baseRet;
    9694             : 
    9695          60 :     if (!HasDataColumnConstraintsTable())
    9696           4 :         return nullptr;
    9697             : 
    9698          56 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
    9699          56 :     const char *min_is_inclusive =
    9700          56 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
    9701          56 :     const char *max_is_inclusive =
    9702          56 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
    9703             : 
    9704          56 :     std::unique_ptr<SQLResult> oResultTable;
    9705             :     // Note: for coded domains, we use a little trick by using a dummy
    9706             :     // _{domainname}_domain_description enum that has a single entry whose
    9707             :     // description is the description of the main domain.
    9708             :     {
    9709          56 :         char *pszSQL = sqlite3_mprintf(
    9710             :             "SELECT constraint_type, value, min, %s, "
    9711             :             "max, %s, description, constraint_name "
    9712             :             "FROM gpkg_data_column_constraints "
    9713             :             "WHERE constraint_name IN ('%q', "
    9714             :             "'_%q_domain_description') "
    9715             :             "AND length(constraint_type) < 100 "  // to
    9716             :                                                   // avoid
    9717             :                                                   // denial
    9718             :                                                   // of
    9719             :                                                   // service
    9720             :             "AND (value IS NULL OR length(value) < "
    9721             :             "10000) "  // to avoid denial
    9722             :                        // of service
    9723             :             "AND (description IS NULL OR "
    9724             :             "length(description) < 10000) "  // to
    9725             :                                              // avoid
    9726             :                                              // denial
    9727             :                                              // of
    9728             :                                              // service
    9729             :             "ORDER BY value "
    9730             :             "LIMIT 10000",  // to avoid denial of
    9731             :                             // service
    9732             :             min_is_inclusive, max_is_inclusive, name.c_str(), name.c_str());
    9733          56 :         oResultTable = SQLQuery(hDB, pszSQL);
    9734          56 :         sqlite3_free(pszSQL);
    9735          56 :         if (!oResultTable)
    9736           0 :             return nullptr;
    9737             :     }
    9738          56 :     if (oResultTable->RowCount() == 0)
    9739             :     {
    9740          15 :         return nullptr;
    9741             :     }
    9742          41 :     if (oResultTable->RowCount() == 10000)
    9743             :     {
    9744           0 :         CPLError(CE_Warning, CPLE_AppDefined,
    9745             :                  "Number of rows returned for field domain %s has been "
    9746             :                  "truncated.",
    9747             :                  name.c_str());
    9748             :     }
    9749             : 
    9750             :     // Try to find the field domain data type from fields that implement it
    9751          41 :     int nFieldType = -1;
    9752          41 :     OGRFieldSubType eSubType = OFSTNone;
    9753          41 :     if (HasDataColumnsTable())
    9754             :     {
    9755          36 :         char *pszSQL = sqlite3_mprintf(
    9756             :             "SELECT table_name, column_name FROM gpkg_data_columns WHERE "
    9757             :             "constraint_name = '%q' LIMIT 10",
    9758             :             name.c_str());
    9759          72 :         auto oResultTable2 = SQLQuery(hDB, pszSQL);
    9760          36 :         sqlite3_free(pszSQL);
    9761          36 :         if (oResultTable2 && oResultTable2->RowCount() >= 1)
    9762             :         {
    9763          46 :             for (int iRecord = 0; iRecord < oResultTable2->RowCount();
    9764             :                  iRecord++)
    9765             :             {
    9766          23 :                 const char *pszTableName = oResultTable2->GetValue(0, iRecord);
    9767          23 :                 const char *pszColumnName = oResultTable2->GetValue(1, iRecord);
    9768          23 :                 if (pszTableName == nullptr || pszColumnName == nullptr)
    9769           0 :                     continue;
    9770             :                 OGRLayer *poLayer =
    9771          46 :                     const_cast<GDALGeoPackageDataset *>(this)->GetLayerByName(
    9772          23 :                         pszTableName);
    9773          23 :                 if (poLayer)
    9774             :                 {
    9775          23 :                     const auto poFDefn = poLayer->GetLayerDefn();
    9776          23 :                     int nIdx = poFDefn->GetFieldIndex(pszColumnName);
    9777          23 :                     if (nIdx >= 0)
    9778             :                     {
    9779          23 :                         const auto poFieldDefn = poFDefn->GetFieldDefn(nIdx);
    9780          23 :                         const auto eType = poFieldDefn->GetType();
    9781          23 :                         if (nFieldType < 0)
    9782             :                         {
    9783          23 :                             nFieldType = eType;
    9784          23 :                             eSubType = poFieldDefn->GetSubType();
    9785             :                         }
    9786           0 :                         else if ((eType == OFTInteger64 || eType == OFTReal) &&
    9787             :                                  nFieldType == OFTInteger)
    9788             :                         {
    9789             :                             // ok
    9790             :                         }
    9791           0 :                         else if (eType == OFTInteger &&
    9792           0 :                                  (nFieldType == OFTInteger64 ||
    9793             :                                   nFieldType == OFTReal))
    9794             :                         {
    9795           0 :                             nFieldType = OFTInteger;
    9796           0 :                             eSubType = OFSTNone;
    9797             :                         }
    9798           0 :                         else if (nFieldType != eType)
    9799             :                         {
    9800           0 :                             nFieldType = -1;
    9801           0 :                             eSubType = OFSTNone;
    9802           0 :                             break;
    9803             :                         }
    9804             :                     }
    9805             :                 }
    9806             :             }
    9807             :         }
    9808             :     }
    9809             : 
    9810          41 :     std::unique_ptr<OGRFieldDomain> poDomain;
    9811          82 :     std::vector<OGRCodedValue> asValues;
    9812          41 :     bool error = false;
    9813          82 :     CPLString osLastConstraintType;
    9814          41 :     int nFieldTypeFromEnumCode = -1;
    9815          82 :     std::string osConstraintDescription;
    9816          82 :     std::string osDescrConstraintName("_");
    9817          41 :     osDescrConstraintName += name;
    9818          41 :     osDescrConstraintName += "_domain_description";
    9819         100 :     for (int iRecord = 0; iRecord < oResultTable->RowCount(); iRecord++)
    9820             :     {
    9821          63 :         const char *pszConstraintType = oResultTable->GetValue(0, iRecord);
    9822          63 :         if (pszConstraintType == nullptr)
    9823           1 :             continue;
    9824          63 :         const char *pszValue = oResultTable->GetValue(1, iRecord);
    9825          63 :         const char *pszMin = oResultTable->GetValue(2, iRecord);
    9826             :         const bool bIsMinIncluded =
    9827          63 :             oResultTable->GetValueAsInteger(3, iRecord) == 1;
    9828          63 :         const char *pszMax = oResultTable->GetValue(4, iRecord);
    9829             :         const bool bIsMaxIncluded =
    9830          63 :             oResultTable->GetValueAsInteger(5, iRecord) == 1;
    9831          63 :         const char *pszDescription = oResultTable->GetValue(6, iRecord);
    9832          63 :         const char *pszConstraintName = oResultTable->GetValue(7, iRecord);
    9833             : 
    9834          63 :         if (!osLastConstraintType.empty() && osLastConstraintType != "enum")
    9835             :         {
    9836           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    9837             :                      "Only constraint of type 'enum' can have multiple rows");
    9838           1 :             error = true;
    9839           4 :             break;
    9840             :         }
    9841             : 
    9842          62 :         if (strcmp(pszConstraintType, "enum") == 0)
    9843             :         {
    9844          42 :             if (pszValue == nullptr)
    9845             :             {
    9846           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    9847             :                          "NULL in 'value' column of enumeration");
    9848           1 :                 error = true;
    9849           1 :                 break;
    9850             :             }
    9851          41 :             if (osDescrConstraintName == pszConstraintName)
    9852             :             {
    9853           1 :                 if (pszDescription)
    9854             :                 {
    9855           1 :                     osConstraintDescription = pszDescription;
    9856             :                 }
    9857           1 :                 continue;
    9858             :             }
    9859          40 :             if (asValues.empty())
    9860             :             {
    9861          20 :                 asValues.reserve(oResultTable->RowCount() + 1);
    9862             :             }
    9863             :             OGRCodedValue cv;
    9864             :             // intended: the 'value' column in GPKG is actually the code
    9865          40 :             cv.pszCode = VSI_STRDUP_VERBOSE(pszValue);
    9866          40 :             if (cv.pszCode == nullptr)
    9867             :             {
    9868           0 :                 error = true;
    9869           0 :                 break;
    9870             :             }
    9871          40 :             if (pszDescription)
    9872             :             {
    9873          29 :                 cv.pszValue = VSI_STRDUP_VERBOSE(pszDescription);
    9874          29 :                 if (cv.pszValue == nullptr)
    9875             :                 {
    9876           0 :                     VSIFree(cv.pszCode);
    9877           0 :                     error = true;
    9878           0 :                     break;
    9879             :                 }
    9880             :             }
    9881             :             else
    9882             :             {
    9883          11 :                 cv.pszValue = nullptr;
    9884             :             }
    9885             : 
    9886             :             // If we can't get the data type from field definition, guess it
    9887             :             // from code.
    9888          40 :             if (nFieldType < 0 && nFieldTypeFromEnumCode != OFTString)
    9889             :             {
    9890          18 :                 switch (CPLGetValueType(cv.pszCode))
    9891             :                 {
    9892          13 :                     case CPL_VALUE_INTEGER:
    9893             :                     {
    9894          13 :                         if (nFieldTypeFromEnumCode != OFTReal &&
    9895             :                             nFieldTypeFromEnumCode != OFTInteger64)
    9896             :                         {
    9897           9 :                             const auto nVal = CPLAtoGIntBig(cv.pszCode);
    9898          17 :                             if (nVal < std::numeric_limits<int>::min() ||
    9899           8 :                                 nVal > std::numeric_limits<int>::max())
    9900             :                             {
    9901           3 :                                 nFieldTypeFromEnumCode = OFTInteger64;
    9902             :                             }
    9903             :                             else
    9904             :                             {
    9905           6 :                                 nFieldTypeFromEnumCode = OFTInteger;
    9906             :                             }
    9907             :                         }
    9908          13 :                         break;
    9909             :                     }
    9910             : 
    9911           3 :                     case CPL_VALUE_REAL:
    9912           3 :                         nFieldTypeFromEnumCode = OFTReal;
    9913           3 :                         break;
    9914             : 
    9915           2 :                     case CPL_VALUE_STRING:
    9916           2 :                         nFieldTypeFromEnumCode = OFTString;
    9917           2 :                         break;
    9918             :                 }
    9919             :             }
    9920             : 
    9921          40 :             asValues.emplace_back(cv);
    9922             :         }
    9923          20 :         else if (strcmp(pszConstraintType, "range") == 0)
    9924             :         {
    9925             :             OGRField sMin;
    9926             :             OGRField sMax;
    9927          14 :             OGR_RawField_SetUnset(&sMin);
    9928          14 :             OGR_RawField_SetUnset(&sMax);
    9929          14 :             if (nFieldType != OFTInteger && nFieldType != OFTInteger64)
    9930           8 :                 nFieldType = OFTReal;
    9931          27 :             if (pszMin != nullptr &&
    9932          13 :                 CPLAtof(pszMin) != -std::numeric_limits<double>::infinity())
    9933             :             {
    9934          10 :                 if (nFieldType == OFTInteger)
    9935           3 :                     sMin.Integer = atoi(pszMin);
    9936           7 :                 else if (nFieldType == OFTInteger64)
    9937           3 :                     sMin.Integer64 = CPLAtoGIntBig(pszMin);
    9938             :                 else /* if( nFieldType == OFTReal ) */
    9939           4 :                     sMin.Real = CPLAtof(pszMin);
    9940             :             }
    9941          27 :             if (pszMax != nullptr &&
    9942          13 :                 CPLAtof(pszMax) != std::numeric_limits<double>::infinity())
    9943             :             {
    9944          10 :                 if (nFieldType == OFTInteger)
    9945           3 :                     sMax.Integer = atoi(pszMax);
    9946           7 :                 else if (nFieldType == OFTInteger64)
    9947           3 :                     sMax.Integer64 = CPLAtoGIntBig(pszMax);
    9948             :                 else /* if( nFieldType == OFTReal ) */
    9949           4 :                     sMax.Real = CPLAtof(pszMax);
    9950             :             }
    9951          14 :             poDomain = std::make_unique<OGRRangeFieldDomain>(
    9952          14 :                 name, pszDescription ? pszDescription : "",
    9953          28 :                 static_cast<OGRFieldType>(nFieldType), eSubType, sMin,
    9954          14 :                 bIsMinIncluded, sMax, bIsMaxIncluded);
    9955             :         }
    9956           6 :         else if (strcmp(pszConstraintType, "glob") == 0)
    9957             :         {
    9958           5 :             if (pszValue == nullptr)
    9959             :             {
    9960           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    9961             :                          "NULL in 'value' column of glob");
    9962           1 :                 error = true;
    9963           1 :                 break;
    9964             :             }
    9965           4 :             if (nFieldType < 0)
    9966           1 :                 nFieldType = OFTString;
    9967           4 :             poDomain = std::make_unique<OGRGlobFieldDomain>(
    9968           4 :                 name, pszDescription ? pszDescription : "",
    9969          12 :                 static_cast<OGRFieldType>(nFieldType), eSubType, pszValue);
    9970             :         }
    9971             :         else
    9972             :         {
    9973           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    9974             :                      "Unhandled constraint_type: %s", pszConstraintType);
    9975           1 :             error = true;
    9976           1 :             break;
    9977             :         }
    9978             : 
    9979          58 :         osLastConstraintType = pszConstraintType;
    9980             :     }
    9981             : 
    9982          41 :     if (!asValues.empty())
    9983             :     {
    9984          20 :         if (nFieldType < 0)
    9985           9 :             nFieldType = nFieldTypeFromEnumCode;
    9986          20 :         poDomain = std::make_unique<OGRCodedFieldDomain>(
    9987             :             name, osConstraintDescription,
    9988          40 :             static_cast<OGRFieldType>(nFieldType), eSubType,
    9989          40 :             std::move(asValues));
    9990             :     }
    9991             : 
    9992          41 :     if (error)
    9993             :     {
    9994           4 :         return nullptr;
    9995             :     }
    9996             : 
    9997          37 :     m_oMapFieldDomains[name] = std::move(poDomain);
    9998          37 :     return GDALDataset::GetFieldDomain(name);
    9999             : }
   10000             : 
   10001             : /************************************************************************/
   10002             : /*                           AddFieldDomain()                           */
   10003             : /************************************************************************/
   10004             : 
   10005          18 : bool GDALGeoPackageDataset::AddFieldDomain(
   10006             :     std::unique_ptr<OGRFieldDomain> &&domain, std::string &failureReason)
   10007             : {
   10008          36 :     const std::string domainName(domain->GetName());
   10009          18 :     if (!GetUpdate())
   10010             :     {
   10011           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10012             :                  "AddFieldDomain() not supported on read-only dataset");
   10013           0 :         return false;
   10014             :     }
   10015          18 :     if (GetFieldDomain(domainName) != nullptr)
   10016             :     {
   10017           1 :         failureReason = "A domain of identical name already exists";
   10018           1 :         return false;
   10019             :     }
   10020          17 :     if (!CreateColumnsTableAndColumnConstraintsTablesIfNecessary())
   10021           0 :         return false;
   10022             : 
   10023          17 :     const bool bIsGPKG10 = HasDataColumnConstraintsTableGPKG_1_0();
   10024          17 :     const char *min_is_inclusive =
   10025          17 :         bIsGPKG10 ? "minIsInclusive" : "min_is_inclusive";
   10026          17 :     const char *max_is_inclusive =
   10027          17 :         bIsGPKG10 ? "maxIsInclusive" : "max_is_inclusive";
   10028             : 
   10029          17 :     const auto &osDescription = domain->GetDescription();
   10030          17 :     switch (domain->GetDomainType())
   10031             :     {
   10032          11 :         case OFDT_CODED:
   10033             :         {
   10034             :             const auto poCodedDomain =
   10035          11 :                 cpl::down_cast<const OGRCodedFieldDomain *>(domain.get());
   10036          11 :             if (!osDescription.empty())
   10037             :             {
   10038             :                 // We use a little trick by using a dummy
   10039             :                 // _{domainname}_domain_description enum that has a single
   10040             :                 // entry whose description is the description of the main
   10041             :                 // domain.
   10042           1 :                 char *pszSQL = sqlite3_mprintf(
   10043             :                     "INSERT INTO gpkg_data_column_constraints ("
   10044             :                     "constraint_name, constraint_type, value, "
   10045             :                     "min, %s, max, %s, "
   10046             :                     "description) VALUES ("
   10047             :                     "'_%q_domain_description', 'enum', '', NULL, NULL, NULL, "
   10048             :                     "NULL, %Q)",
   10049             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10050             :                     osDescription.c_str());
   10051           1 :                 CPL_IGNORE_RET_VAL(SQLCommand(hDB, pszSQL));
   10052           1 :                 sqlite3_free(pszSQL);
   10053             :             }
   10054          11 :             const auto &enumeration = poCodedDomain->GetEnumeration();
   10055          33 :             for (int i = 0; enumeration[i].pszCode != nullptr; ++i)
   10056             :             {
   10057          22 :                 char *pszSQL = sqlite3_mprintf(
   10058             :                     "INSERT INTO gpkg_data_column_constraints ("
   10059             :                     "constraint_name, constraint_type, value, "
   10060             :                     "min, %s, max, %s, "
   10061             :                     "description) VALUES ("
   10062             :                     "'%q', 'enum', '%q', NULL, NULL, NULL, NULL, %Q)",
   10063             :                     min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10064          22 :                     enumeration[i].pszCode, enumeration[i].pszValue);
   10065          22 :                 bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10066          22 :                 sqlite3_free(pszSQL);
   10067          22 :                 if (!ok)
   10068           0 :                     return false;
   10069             :             }
   10070          11 :             break;
   10071             :         }
   10072             : 
   10073           5 :         case OFDT_RANGE:
   10074             :         {
   10075             :             const auto poRangeDomain =
   10076           5 :                 cpl::down_cast<const OGRRangeFieldDomain *>(domain.get());
   10077           5 :             const auto eFieldType = poRangeDomain->GetFieldType();
   10078           5 :             if (eFieldType != OFTInteger && eFieldType != OFTInteger64 &&
   10079             :                 eFieldType != OFTReal)
   10080             :             {
   10081             :                 failureReason = "Only range domains of numeric type are "
   10082           0 :                                 "supported in GeoPackage";
   10083           0 :                 return false;
   10084             :             }
   10085             : 
   10086           5 :             double dfMin = -std::numeric_limits<double>::infinity();
   10087           5 :             double dfMax = std::numeric_limits<double>::infinity();
   10088           5 :             bool bMinIsInclusive = true;
   10089           5 :             const auto &sMin = poRangeDomain->GetMin(bMinIsInclusive);
   10090           5 :             bool bMaxIsInclusive = true;
   10091           5 :             const auto &sMax = poRangeDomain->GetMax(bMaxIsInclusive);
   10092           5 :             if (eFieldType == OFTInteger)
   10093             :             {
   10094           1 :                 if (!OGR_RawField_IsUnset(&sMin))
   10095           1 :                     dfMin = sMin.Integer;
   10096           1 :                 if (!OGR_RawField_IsUnset(&sMax))
   10097           1 :                     dfMax = sMax.Integer;
   10098             :             }
   10099           4 :             else if (eFieldType == OFTInteger64)
   10100             :             {
   10101           1 :                 if (!OGR_RawField_IsUnset(&sMin))
   10102           1 :                     dfMin = static_cast<double>(sMin.Integer64);
   10103           1 :                 if (!OGR_RawField_IsUnset(&sMax))
   10104           1 :                     dfMax = static_cast<double>(sMax.Integer64);
   10105             :             }
   10106             :             else /* if( eFieldType == OFTReal ) */
   10107             :             {
   10108           3 :                 if (!OGR_RawField_IsUnset(&sMin))
   10109           3 :                     dfMin = sMin.Real;
   10110           3 :                 if (!OGR_RawField_IsUnset(&sMax))
   10111           3 :                     dfMax = sMax.Real;
   10112             :             }
   10113             : 
   10114           5 :             sqlite3_stmt *hInsertStmt = nullptr;
   10115             :             const char *pszSQL =
   10116           5 :                 CPLSPrintf("INSERT INTO gpkg_data_column_constraints ("
   10117             :                            "constraint_name, constraint_type, value, "
   10118             :                            "min, %s, max, %s, "
   10119             :                            "description) VALUES ("
   10120             :                            "?, 'range', NULL, ?, ?, ?, ?, ?)",
   10121             :                            min_is_inclusive, max_is_inclusive);
   10122           5 :             if (SQLPrepareWithError(hDB, pszSQL, -1, &hInsertStmt, nullptr) !=
   10123             :                 SQLITE_OK)
   10124             :             {
   10125           0 :                 return false;
   10126             :             }
   10127           5 :             sqlite3_bind_text(hInsertStmt, 1, domainName.c_str(),
   10128           5 :                               static_cast<int>(domainName.size()),
   10129             :                               SQLITE_TRANSIENT);
   10130           5 :             sqlite3_bind_double(hInsertStmt, 2, dfMin);
   10131           5 :             sqlite3_bind_int(hInsertStmt, 3, bMinIsInclusive ? 1 : 0);
   10132           5 :             sqlite3_bind_double(hInsertStmt, 4, dfMax);
   10133           5 :             sqlite3_bind_int(hInsertStmt, 5, bMaxIsInclusive ? 1 : 0);
   10134           5 :             if (osDescription.empty())
   10135             :             {
   10136           3 :                 sqlite3_bind_null(hInsertStmt, 6);
   10137             :             }
   10138             :             else
   10139             :             {
   10140           2 :                 sqlite3_bind_text(hInsertStmt, 6, osDescription.c_str(),
   10141           2 :                                   static_cast<int>(osDescription.size()),
   10142             :                                   SQLITE_TRANSIENT);
   10143             :             }
   10144           5 :             const int sqlite_err = sqlite3_step(hInsertStmt);
   10145           5 :             sqlite3_finalize(hInsertStmt);
   10146           5 :             if (sqlite_err != SQLITE_OK && sqlite_err != SQLITE_DONE)
   10147             :             {
   10148           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
   10149             :                          "failed to execute insertion '%s': %s", pszSQL,
   10150             :                          sqlite3_errmsg(hDB));
   10151           0 :                 return false;
   10152             :             }
   10153             : 
   10154           5 :             break;
   10155             :         }
   10156             : 
   10157           1 :         case OFDT_GLOB:
   10158             :         {
   10159             :             const auto poGlobDomain =
   10160           1 :                 cpl::down_cast<const OGRGlobFieldDomain *>(domain.get());
   10161           2 :             char *pszSQL = sqlite3_mprintf(
   10162             :                 "INSERT INTO gpkg_data_column_constraints ("
   10163             :                 "constraint_name, constraint_type, value, "
   10164             :                 "min, %s, max, %s, "
   10165             :                 "description) VALUES ("
   10166             :                 "'%q', 'glob', '%q', NULL, NULL, NULL, NULL, %Q)",
   10167             :                 min_is_inclusive, max_is_inclusive, domainName.c_str(),
   10168           1 :                 poGlobDomain->GetGlob().c_str(),
   10169           2 :                 osDescription.empty() ? nullptr : osDescription.c_str());
   10170           1 :             bool ok = SQLCommand(hDB, pszSQL) == OGRERR_NONE;
   10171           1 :             sqlite3_free(pszSQL);
   10172           1 :             if (!ok)
   10173           0 :                 return false;
   10174             : 
   10175           1 :             break;
   10176             :         }
   10177             :     }
   10178             : 
   10179          17 :     m_oMapFieldDomains[domainName] = std::move(domain);
   10180          17 :     return true;
   10181             : }
   10182             : 
   10183             : /************************************************************************/
   10184             : /*                          AddRelationship()                           */
   10185             : /************************************************************************/
   10186             : 
   10187          24 : bool GDALGeoPackageDataset::AddRelationship(
   10188             :     std::unique_ptr<GDALRelationship> &&relationship,
   10189             :     std::string &failureReason)
   10190             : {
   10191          24 :     if (!GetUpdate())
   10192             :     {
   10193           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10194             :                  "AddRelationship() not supported on read-only dataset");
   10195           0 :         return false;
   10196             :     }
   10197             : 
   10198             :     const std::string osRelationshipName = GenerateNameForRelationship(
   10199          24 :         relationship->GetLeftTableName().c_str(),
   10200          24 :         relationship->GetRightTableName().c_str(),
   10201          96 :         relationship->GetRelatedTableType().c_str());
   10202             :     // sanity checks
   10203          24 :     if (GetRelationship(osRelationshipName) != nullptr)
   10204             :     {
   10205           1 :         failureReason = "A relationship of identical name already exists";
   10206           1 :         return false;
   10207             :     }
   10208             : 
   10209          23 :     if (!ValidateRelationship(relationship.get(), failureReason))
   10210             :     {
   10211          14 :         return false;
   10212             :     }
   10213             : 
   10214           9 :     if (CreateExtensionsTableIfNecessary() != OGRERR_NONE)
   10215             :     {
   10216           0 :         return false;
   10217             :     }
   10218           9 :     if (!CreateRelationsTableIfNecessary())
   10219             :     {
   10220           0 :         failureReason = "Could not create gpkgext_relations table";
   10221           0 :         return false;
   10222             :     }
   10223           9 :     if (SQLGetInteger(GetDB(),
   10224             :                       "SELECT 1 FROM gpkg_extensions WHERE "
   10225             :                       "table_name = 'gpkgext_relations'",
   10226           9 :                       nullptr) != 1)
   10227             :     {
   10228           4 :         if (OGRERR_NONE !=
   10229           4 :             SQLCommand(
   10230             :                 GetDB(),
   10231             :                 "INSERT INTO gpkg_extensions "
   10232             :                 "(table_name,column_name,extension_name,definition,scope) "
   10233             :                 "VALUES ('gpkgext_relations', NULL, 'gpkg_related_tables', "
   10234             :                 "'http://www.geopackage.org/18-000.html', "
   10235             :                 "'read-write')"))
   10236             :         {
   10237             :             failureReason =
   10238           0 :                 "Could not create gpkg_extensions entry for gpkgext_relations";
   10239           0 :             return false;
   10240             :         }
   10241             :     }
   10242             : 
   10243           9 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10244           9 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10245           9 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10246           9 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10247             : 
   10248          18 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10249           9 :     if (osRelatedTableType.empty())
   10250             :     {
   10251           5 :         osRelatedTableType = "features";
   10252             :     }
   10253             : 
   10254             :     // generate mapping table if not set
   10255          18 :     CPLString osMappingTableName = relationship->GetMappingTableName();
   10256           9 :     if (osMappingTableName.empty())
   10257             :     {
   10258           3 :         int nIndex = 1;
   10259           3 :         osMappingTableName = osLeftTableName + "_" + osRightTableName;
   10260           3 :         while (FindLayerIndex(osMappingTableName.c_str()) >= 0)
   10261             :         {
   10262           0 :             nIndex += 1;
   10263             :             osMappingTableName.Printf("%s_%s_%d", osLeftTableName.c_str(),
   10264           0 :                                       osRightTableName.c_str(), nIndex);
   10265             :         }
   10266             : 
   10267             :         // determine whether base/related keys are unique
   10268           3 :         bool bBaseKeyIsUnique = false;
   10269             :         {
   10270             :             const std::set<std::string> uniqueBaseFieldsUC =
   10271             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10272           6 :                                                osLeftTableName.c_str());
   10273           6 :             if (uniqueBaseFieldsUC.find(
   10274           3 :                     CPLString(aosLeftTableFields[0]).toupper()) !=
   10275           6 :                 uniqueBaseFieldsUC.end())
   10276             :             {
   10277           2 :                 bBaseKeyIsUnique = true;
   10278             :             }
   10279             :         }
   10280           3 :         bool bRelatedKeyIsUnique = false;
   10281             :         {
   10282             :             const std::set<std::string> uniqueRelatedFieldsUC =
   10283             :                 SQLGetUniqueFieldUCConstraints(GetDB(),
   10284           6 :                                                osRightTableName.c_str());
   10285           6 :             if (uniqueRelatedFieldsUC.find(
   10286           3 :                     CPLString(aosRightTableFields[0]).toupper()) !=
   10287           6 :                 uniqueRelatedFieldsUC.end())
   10288             :             {
   10289           2 :                 bRelatedKeyIsUnique = true;
   10290             :             }
   10291             :         }
   10292             : 
   10293             :         // create mapping table
   10294             : 
   10295           3 :         std::string osBaseIdDefinition = "base_id INTEGER";
   10296           3 :         if (bBaseKeyIsUnique)
   10297             :         {
   10298           2 :             char *pszSQL = sqlite3_mprintf(
   10299             :                 " CONSTRAINT 'fk_base_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10300             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10301             :                 "DEFERRED",
   10302             :                 osMappingTableName.c_str(), osLeftTableName.c_str(),
   10303           2 :                 aosLeftTableFields[0].c_str());
   10304           2 :             osBaseIdDefinition += pszSQL;
   10305           2 :             sqlite3_free(pszSQL);
   10306             :         }
   10307             : 
   10308           3 :         std::string osRelatedIdDefinition = "related_id INTEGER";
   10309           3 :         if (bRelatedKeyIsUnique)
   10310             :         {
   10311           2 :             char *pszSQL = sqlite3_mprintf(
   10312             :                 " CONSTRAINT 'fk_related_id_%q' REFERENCES \"%w\"(\"%w\") ON "
   10313             :                 "DELETE CASCADE ON UPDATE CASCADE DEFERRABLE INITIALLY "
   10314             :                 "DEFERRED",
   10315             :                 osMappingTableName.c_str(), osRightTableName.c_str(),
   10316           2 :                 aosRightTableFields[0].c_str());
   10317           2 :             osRelatedIdDefinition += pszSQL;
   10318           2 :             sqlite3_free(pszSQL);
   10319             :         }
   10320             : 
   10321           3 :         char *pszSQL = sqlite3_mprintf("CREATE TABLE \"%w\" ("
   10322             :                                        "id INTEGER PRIMARY KEY AUTOINCREMENT, "
   10323             :                                        "%s, %s);",
   10324             :                                        osMappingTableName.c_str(),
   10325             :                                        osBaseIdDefinition.c_str(),
   10326             :                                        osRelatedIdDefinition.c_str());
   10327           3 :         OGRErr eErr = SQLCommand(hDB, pszSQL);
   10328           3 :         sqlite3_free(pszSQL);
   10329           3 :         if (eErr != OGRERR_NONE)
   10330             :         {
   10331             :             failureReason =
   10332           0 :                 ("Could not create mapping table " + osMappingTableName)
   10333           0 :                     .c_str();
   10334           0 :             return false;
   10335             :         }
   10336             : 
   10337             :         /*
   10338             :          * Strictly speaking we should NOT be inserting the mapping table into gpkg_contents.
   10339             :          * The related tables extension explicitly states that the mapping table should only be
   10340             :          * in the gpkgext_relations table and not in gpkg_contents. (See also discussion at
   10341             :          * https://github.com/opengeospatial/geopackage/issues/679).
   10342             :          *
   10343             :          * However, if we don't insert the mapping table into gpkg_contents then it is no longer
   10344             :          * visible to some clients (eg ESRI software only allows opening tables that are present
   10345             :          * in gpkg_contents). So we'll do this anyway, for maximum compatibility and flexibility.
   10346             :          *
   10347             :          * More related discussion is at https://github.com/OSGeo/gdal/pull/9258
   10348             :          */
   10349           3 :         pszSQL = sqlite3_mprintf(
   10350             :             "INSERT INTO gpkg_contents "
   10351             :             "(table_name,data_type,identifier,description,last_change,srs_id) "
   10352             :             "VALUES "
   10353             :             "('%q','attributes','%q','Mapping table for relationship between "
   10354             :             "%q and %q',%s,0)",
   10355             :             osMappingTableName.c_str(), /*table_name*/
   10356             :             osMappingTableName.c_str(), /*identifier*/
   10357             :             osLeftTableName.c_str(),    /*description left table name*/
   10358             :             osRightTableName.c_str(),   /*description right table name*/
   10359           6 :             GDALGeoPackageDataset::GetCurrentDateEscapedSQL().c_str());
   10360             : 
   10361             :         // Note -- we explicitly ignore failures here, because hey, we aren't really
   10362             :         // supposed to be adding this table to gpkg_contents anyway!
   10363           3 :         (void)SQLCommand(hDB, pszSQL);
   10364           3 :         sqlite3_free(pszSQL);
   10365             : 
   10366           3 :         pszSQL = sqlite3_mprintf(
   10367             :             "CREATE INDEX \"idx_%w_base_id\" ON \"%w\" (base_id);",
   10368             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10369           3 :         eErr = SQLCommand(hDB, pszSQL);
   10370           3 :         sqlite3_free(pszSQL);
   10371           3 :         if (eErr != OGRERR_NONE)
   10372             :         {
   10373           0 :             failureReason = ("Could not create index for " +
   10374           0 :                              osMappingTableName + " (base_id)")
   10375           0 :                                 .c_str();
   10376           0 :             return false;
   10377             :         }
   10378             : 
   10379           3 :         pszSQL = sqlite3_mprintf(
   10380             :             "CREATE INDEX \"idx_%qw_related_id\" ON \"%w\" (related_id);",
   10381             :             osMappingTableName.c_str(), osMappingTableName.c_str());
   10382           3 :         eErr = SQLCommand(hDB, pszSQL);
   10383           3 :         sqlite3_free(pszSQL);
   10384           3 :         if (eErr != OGRERR_NONE)
   10385             :         {
   10386           0 :             failureReason = ("Could not create index for " +
   10387           0 :                              osMappingTableName + " (related_id)")
   10388           0 :                                 .c_str();
   10389           0 :             return false;
   10390             :         }
   10391             :     }
   10392             :     else
   10393             :     {
   10394             :         // validate mapping table structure
   10395           6 :         if (OGRGeoPackageTableLayer *poLayer =
   10396           6 :                 cpl::down_cast<OGRGeoPackageTableLayer *>(
   10397           6 :                     GetLayerByName(osMappingTableName)))
   10398             :         {
   10399           4 :             if (poLayer->GetLayerDefn()->GetFieldIndex("base_id") < 0)
   10400             :             {
   10401             :                 failureReason =
   10402           2 :                     ("Field base_id must exist in " + osMappingTableName)
   10403           1 :                         .c_str();
   10404           1 :                 return false;
   10405             :             }
   10406           3 :             if (poLayer->GetLayerDefn()->GetFieldIndex("related_id") < 0)
   10407             :             {
   10408             :                 failureReason =
   10409           2 :                     ("Field related_id must exist in " + osMappingTableName)
   10410           1 :                         .c_str();
   10411           1 :                 return false;
   10412             :             }
   10413             :         }
   10414             :         else
   10415             :         {
   10416             :             failureReason =
   10417           2 :                 ("Could not retrieve table " + osMappingTableName).c_str();
   10418           2 :             return false;
   10419             :         }
   10420             :     }
   10421             : 
   10422           5 :     char *pszSQL = sqlite3_mprintf(
   10423             :         "INSERT INTO gpkg_extensions "
   10424             :         "(table_name,column_name,extension_name,definition,scope) "
   10425             :         "VALUES ('%q', NULL, 'gpkg_related_tables', "
   10426             :         "'http://www.geopackage.org/18-000.html', "
   10427             :         "'read-write')",
   10428             :         osMappingTableName.c_str());
   10429           5 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10430           5 :     sqlite3_free(pszSQL);
   10431           5 :     if (eErr != OGRERR_NONE)
   10432             :     {
   10433           0 :         failureReason = ("Could not insert mapping table " +
   10434           0 :                          osMappingTableName + " into gpkg_extensions")
   10435           0 :                             .c_str();
   10436           0 :         return false;
   10437             :     }
   10438             : 
   10439          15 :     pszSQL = sqlite3_mprintf(
   10440             :         "INSERT INTO gpkgext_relations "
   10441             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10442             :         "primary_column,relation_name,mapping_table_name) "
   10443             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10444           5 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10445           5 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10446             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10447           5 :     eErr = SQLCommand(hDB, pszSQL);
   10448           5 :     sqlite3_free(pszSQL);
   10449           5 :     if (eErr != OGRERR_NONE)
   10450             :     {
   10451           0 :         failureReason = "Could not insert relationship into gpkgext_relations";
   10452           0 :         return false;
   10453             :     }
   10454             : 
   10455           5 :     ClearCachedRelationships();
   10456           5 :     LoadRelationships();
   10457           5 :     return true;
   10458             : }
   10459             : 
   10460             : /************************************************************************/
   10461             : /*                         DeleteRelationship()                         */
   10462             : /************************************************************************/
   10463             : 
   10464           4 : bool GDALGeoPackageDataset::DeleteRelationship(const std::string &name,
   10465             :                                                std::string &failureReason)
   10466             : {
   10467           4 :     if (eAccess != GA_Update)
   10468             :     {
   10469           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10470             :                  "DeleteRelationship() not supported on read-only dataset");
   10471           0 :         return false;
   10472             :     }
   10473             : 
   10474             :     // ensure relationships are up to date before we try to remove one
   10475           4 :     ClearCachedRelationships();
   10476           4 :     LoadRelationships();
   10477             : 
   10478           8 :     std::string osMappingTableName;
   10479             :     {
   10480           4 :         const GDALRelationship *poRelationship = GetRelationship(name);
   10481           4 :         if (poRelationship == nullptr)
   10482             :         {
   10483           1 :             failureReason = "Could not find relationship with name " + name;
   10484           1 :             return false;
   10485             :         }
   10486             : 
   10487           3 :         osMappingTableName = poRelationship->GetMappingTableName();
   10488             :     }
   10489             : 
   10490             :     // DeleteLayerCommon will delete existing relationship objects, so we can't
   10491             :     // refer to poRelationship or any of its members previously obtained here
   10492           3 :     if (DeleteLayerCommon(osMappingTableName.c_str()) != OGRERR_NONE)
   10493             :     {
   10494             :         failureReason =
   10495           0 :             "Could not remove mapping layer name " + osMappingTableName;
   10496             : 
   10497             :         // relationships may have been left in an inconsistent state -- reload
   10498             :         // them now
   10499           0 :         ClearCachedRelationships();
   10500           0 :         LoadRelationships();
   10501           0 :         return false;
   10502             :     }
   10503             : 
   10504           3 :     ClearCachedRelationships();
   10505           3 :     LoadRelationships();
   10506           3 :     return true;
   10507             : }
   10508             : 
   10509             : /************************************************************************/
   10510             : /*                        UpdateRelationship()                          */
   10511             : /************************************************************************/
   10512             : 
   10513           6 : bool GDALGeoPackageDataset::UpdateRelationship(
   10514             :     std::unique_ptr<GDALRelationship> &&relationship,
   10515             :     std::string &failureReason)
   10516             : {
   10517           6 :     if (eAccess != GA_Update)
   10518             :     {
   10519           0 :         CPLError(CE_Failure, CPLE_NotSupported,
   10520             :                  "UpdateRelationship() not supported on read-only dataset");
   10521           0 :         return false;
   10522             :     }
   10523             : 
   10524             :     // ensure relationships are up to date before we try to update one
   10525           6 :     ClearCachedRelationships();
   10526           6 :     LoadRelationships();
   10527             : 
   10528           6 :     const std::string &osRelationshipName = relationship->GetName();
   10529           6 :     const std::string &osLeftTableName = relationship->GetLeftTableName();
   10530           6 :     const std::string &osRightTableName = relationship->GetRightTableName();
   10531           6 :     const std::string &osMappingTableName = relationship->GetMappingTableName();
   10532           6 :     const auto &aosLeftTableFields = relationship->GetLeftTableFields();
   10533           6 :     const auto &aosRightTableFields = relationship->GetRightTableFields();
   10534             : 
   10535             :     // sanity checks
   10536             :     {
   10537             :         const GDALRelationship *poExistingRelationship =
   10538           6 :             GetRelationship(osRelationshipName);
   10539           6 :         if (poExistingRelationship == nullptr)
   10540             :         {
   10541             :             failureReason =
   10542           1 :                 "The relationship should already exist to be updated";
   10543           1 :             return false;
   10544             :         }
   10545             : 
   10546           5 :         if (!ValidateRelationship(relationship.get(), failureReason))
   10547             :         {
   10548           2 :             return false;
   10549             :         }
   10550             : 
   10551             :         // we don't permit changes to the participating tables
   10552           3 :         if (osLeftTableName != poExistingRelationship->GetLeftTableName())
   10553             :         {
   10554           0 :             failureReason = ("Cannot change base table from " +
   10555           0 :                              poExistingRelationship->GetLeftTableName() +
   10556           0 :                              " to " + osLeftTableName)
   10557           0 :                                 .c_str();
   10558           0 :             return false;
   10559             :         }
   10560           3 :         if (osRightTableName != poExistingRelationship->GetRightTableName())
   10561             :         {
   10562           0 :             failureReason = ("Cannot change related table from " +
   10563           0 :                              poExistingRelationship->GetRightTableName() +
   10564           0 :                              " to " + osRightTableName)
   10565           0 :                                 .c_str();
   10566           0 :             return false;
   10567             :         }
   10568           3 :         if (osMappingTableName != poExistingRelationship->GetMappingTableName())
   10569             :         {
   10570           0 :             failureReason = ("Cannot change mapping table from " +
   10571           0 :                              poExistingRelationship->GetMappingTableName() +
   10572           0 :                              " to " + osMappingTableName)
   10573           0 :                                 .c_str();
   10574           0 :             return false;
   10575             :         }
   10576             :     }
   10577             : 
   10578           6 :     std::string osRelatedTableType = relationship->GetRelatedTableType();
   10579           3 :     if (osRelatedTableType.empty())
   10580             :     {
   10581           0 :         osRelatedTableType = "features";
   10582             :     }
   10583             : 
   10584           3 :     char *pszSQL = sqlite3_mprintf(
   10585             :         "DELETE FROM gpkgext_relations WHERE mapping_table_name='%q'",
   10586             :         osMappingTableName.c_str());
   10587           3 :     OGRErr eErr = SQLCommand(hDB, pszSQL);
   10588           3 :     sqlite3_free(pszSQL);
   10589           3 :     if (eErr != OGRERR_NONE)
   10590             :     {
   10591             :         failureReason =
   10592           0 :             "Could not delete old relationship from gpkgext_relations";
   10593           0 :         return false;
   10594             :     }
   10595             : 
   10596           9 :     pszSQL = sqlite3_mprintf(
   10597             :         "INSERT INTO gpkgext_relations "
   10598             :         "(base_table_name,base_primary_column,related_table_name,related_"
   10599             :         "primary_column,relation_name,mapping_table_name) "
   10600             :         "VALUES ('%q', '%q', '%q', '%q', '%q', '%q')",
   10601           3 :         osLeftTableName.c_str(), aosLeftTableFields[0].c_str(),
   10602           3 :         osRightTableName.c_str(), aosRightTableFields[0].c_str(),
   10603             :         osRelatedTableType.c_str(), osMappingTableName.c_str());
   10604           3 :     eErr = SQLCommand(hDB, pszSQL);
   10605           3 :     sqlite3_free(pszSQL);
   10606           3 :     if (eErr != OGRERR_NONE)
   10607             :     {
   10608             :         failureReason =
   10609           0 :             "Could not insert updated relationship into gpkgext_relations";
   10610           0 :         return false;
   10611             :     }
   10612             : 
   10613           3 :     ClearCachedRelationships();
   10614           3 :     LoadRelationships();
   10615           3 :     return true;
   10616             : }
   10617             : 
   10618             : /************************************************************************/
   10619             : /*                    GetSqliteMasterContent()                          */
   10620             : /************************************************************************/
   10621             : 
   10622             : const std::vector<SQLSqliteMasterContent> &
   10623           2 : GDALGeoPackageDataset::GetSqliteMasterContent()
   10624             : {
   10625           2 :     if (m_aoSqliteMasterContent.empty())
   10626             :     {
   10627             :         auto oResultTable =
   10628           2 :             SQLQuery(hDB, "SELECT sql, type, tbl_name FROM sqlite_master");
   10629           1 :         if (oResultTable)
   10630             :         {
   10631          58 :             for (int rowCnt = 0; rowCnt < oResultTable->RowCount(); ++rowCnt)
   10632             :             {
   10633         114 :                 SQLSqliteMasterContent row;
   10634          57 :                 const char *pszSQL = oResultTable->GetValue(0, rowCnt);
   10635          57 :                 row.osSQL = pszSQL ? pszSQL : "";
   10636          57 :                 const char *pszType = oResultTable->GetValue(1, rowCnt);
   10637          57 :                 row.osType = pszType ? pszType : "";
   10638          57 :                 const char *pszTableName = oResultTable->GetValue(2, rowCnt);
   10639          57 :                 row.osTableName = pszTableName ? pszTableName : "";
   10640          57 :                 m_aoSqliteMasterContent.emplace_back(std::move(row));
   10641             :             }
   10642             :         }
   10643             :     }
   10644           2 :     return m_aoSqliteMasterContent;
   10645             : }

Generated by: LCOV version 1.14