LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/amigocloud - ogramigocloudtablelayer.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 0 614 0.0 %
Date: 2025-05-31 00:00:17 Functions: 0 25 0.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  AmigoCloud Translator
       4             :  * Purpose:  Implements OGRAmigoCloudTableLayer class.
       5             :  * Author:   Even Rouault, <even dot rouault at spatialys.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2015, Victor Chernetsky, <victor at amigocloud dot com>
       9             :  *
      10             :  * SPDX-License-Identifier: MIT
      11             :  ****************************************************************************/
      12             : 
      13             : #include "ogr_amigocloud.h"
      14             : #include "ogr_p.h"
      15             : #include "ogr_pgdump.h"
      16             : #include "ogrlibjsonutils.h"
      17             : #include <sstream>
      18             : #include <iomanip>
      19             : 
      20             : /************************************************************************/
      21             : /*                    OGRAMIGOCLOUDEscapeIdentifier( )                     */
      22             : /************************************************************************/
      23             : 
      24           0 : CPLString OGRAMIGOCLOUDEscapeIdentifier(const char *pszStr)
      25             : {
      26           0 :     CPLString osStr;
      27             : 
      28           0 :     osStr += "\"";
      29             : 
      30           0 :     char ch = '\0';
      31           0 :     for (int i = 0; (ch = pszStr[i]) != '\0'; i++)
      32             :     {
      33           0 :         if (ch == '"')
      34           0 :             osStr.append(1, ch);
      35           0 :         osStr.append(1, ch);
      36             :     }
      37             : 
      38           0 :     osStr += "\"";
      39             : 
      40           0 :     return osStr;
      41             : }
      42             : 
      43           0 : std::string OGRAMIGOCLOUDJsonEncode(const std::string &s)
      44             : {
      45           0 :     std::ostringstream o;
      46           0 :     for (auto c = s.cbegin(); c != s.cend(); c++)
      47             :     {
      48           0 :         switch (*c)
      49             :         {
      50           0 :             case '"':
      51           0 :                 o << "\\\"";
      52           0 :                 break;
      53           0 :             case '\\':
      54           0 :                 o << "\\\\";
      55           0 :                 break;
      56           0 :             case '\b':
      57           0 :                 o << "\\b";
      58           0 :                 break;
      59           0 :             case '\f':
      60           0 :                 o << "\\f";
      61           0 :                 break;
      62           0 :             case '\n':
      63           0 :                 o << "\\n";
      64           0 :                 break;
      65           0 :             case '\r':
      66           0 :                 o << "\\r";
      67           0 :                 break;
      68           0 :             case '\t':
      69           0 :                 o << "\\t";
      70           0 :                 break;
      71           0 :             default:
      72           0 :                 if (*c <= '\x1f')
      73             :                 {
      74           0 :                     o << "\\u" << std::hex << std::setw(4) << std::setfill('0')
      75           0 :                       << (int)*c;
      76             :                 }
      77             :                 else
      78             :                 {
      79           0 :                     o << *c;
      80             :                 }
      81             :         }
      82             :     }
      83           0 :     return o.str();
      84             : }
      85             : 
      86             : /************************************************************************/
      87             : /*                        OGRAmigoCloudTableLayer()                        */
      88             : /************************************************************************/
      89             : 
      90           0 : OGRAmigoCloudTableLayer::OGRAmigoCloudTableLayer(
      91           0 :     OGRAmigoCloudDataSource *poDSIn, const char *pszName)
      92             :     : OGRAmigoCloudLayer(poDSIn), osDatasetId(CPLString(pszName)), nNextFID(-1),
      93           0 :       bDeferredCreation(FALSE)
      94             : {
      95           0 :     osTableName = CPLString("dataset_") + osDatasetId;
      96           0 :     SetDescription(osDatasetId);
      97           0 :     osName = osDatasetId;
      98           0 :     nMaxChunkSize =
      99           0 :         atoi(CPLGetConfigOption("AMIGOCLOUD_MAX_CHUNK_SIZE", "15")) * 1024 *
     100             :         1024;
     101           0 : }
     102             : 
     103             : /************************************************************************/
     104             : /*                    ~OGRAmigoCloudTableLayer()                           */
     105             : /************************************************************************/
     106             : 
     107           0 : OGRAmigoCloudTableLayer::~OGRAmigoCloudTableLayer()
     108             : 
     109             : {
     110           0 :     if (bDeferredCreation)
     111           0 :         RunDeferredCreationIfNecessary();
     112           0 :     FlushDeferredInsert();
     113           0 : }
     114             : 
     115             : /************************************************************************/
     116             : /*                        GetLayerDefnInternal()                        */
     117             : /************************************************************************/
     118             : 
     119             : OGRFeatureDefn *
     120           0 : OGRAmigoCloudTableLayer::GetLayerDefnInternal(CPL_UNUSED json_object *poObjIn)
     121             : {
     122           0 :     if (poFeatureDefn != nullptr)
     123             :     {
     124           0 :         return poFeatureDefn;
     125             :     }
     126             : 
     127             :     osBaseSQL.Printf("SELECT * FROM %s",
     128           0 :                      OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str());
     129           0 :     EstablishLayerDefn(osTableName, nullptr);
     130           0 :     osBaseSQL = "";
     131             : 
     132           0 :     if (!osFIDColName.empty())
     133             :     {
     134           0 :         CPLString sql;
     135             :         sql.Printf("SELECT %s FROM %s",
     136           0 :                    OGRAMIGOCLOUDEscapeIdentifier(osFIDColName).c_str(),
     137           0 :                    OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str());
     138           0 :         json_object *poObj = poDS->RunSQL(sql);
     139           0 :         if (poObj != nullptr && json_object_get_type(poObj) == json_type_object)
     140             :         {
     141           0 :             json_object *poRows = CPL_json_object_object_get(poObj, "data");
     142             : 
     143           0 :             if (poRows != nullptr &&
     144           0 :                 json_object_get_type(poRows) == json_type_array)
     145             :             {
     146           0 :                 mFIDs.clear();
     147           0 :                 const auto nLength = json_object_array_length(poRows);
     148           0 :                 for (auto i = decltype(nLength){0}; i < nLength; i++)
     149             :                 {
     150           0 :                     json_object *obj = json_object_array_get_idx(poRows, i);
     151             : 
     152             :                     json_object_iter it;
     153           0 :                     it.key = nullptr;
     154           0 :                     it.val = nullptr;
     155           0 :                     it.entry = nullptr;
     156           0 :                     json_object_object_foreachC(obj, it)
     157             :                     {
     158           0 :                         const char *pszColName = it.key;
     159           0 :                         if (it.val != nullptr)
     160             :                         {
     161           0 :                             if (EQUAL(pszColName, osFIDColName.c_str()))
     162             :                             {
     163             :                                 std::string amigo_id =
     164           0 :                                     json_object_get_string(it.val);
     165           0 :                                 OGRAmigoCloudFID aFID(amigo_id, iNext);
     166           0 :                                 mFIDs[aFID.iFID] = aFID;
     167             :                             }
     168             :                         }
     169             :                     }
     170             :                 }
     171             :             }
     172           0 :             json_object_put(poObj);
     173             :         }
     174             :     }
     175             : 
     176           0 :     if (!osFIDColName.empty())
     177             :     {
     178           0 :         osBaseSQL = "SELECT ";
     179           0 :         osBaseSQL += OGRAMIGOCLOUDEscapeIdentifier(osFIDColName);
     180             :     }
     181           0 :     for (int i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++)
     182             :     {
     183           0 :         if (osBaseSQL.empty())
     184           0 :             osBaseSQL = "SELECT ";
     185             :         else
     186           0 :             osBaseSQL += ", ";
     187           0 :         osBaseSQL += OGRAMIGOCLOUDEscapeIdentifier(
     188           0 :             poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef());
     189             :     }
     190           0 :     for (int i = 0; i < poFeatureDefn->GetFieldCount(); i++)
     191             :     {
     192           0 :         if (osBaseSQL.empty())
     193           0 :             osBaseSQL = "SELECT ";
     194             :         else
     195           0 :             osBaseSQL += ", ";
     196           0 :         osBaseSQL += OGRAMIGOCLOUDEscapeIdentifier(
     197           0 :             poFeatureDefn->GetFieldDefn(i)->GetNameRef());
     198             :     }
     199           0 :     if (osBaseSQL.empty())
     200           0 :         osBaseSQL = "SELECT *";
     201           0 :     osBaseSQL += " FROM ";
     202           0 :     osBaseSQL += OGRAMIGOCLOUDEscapeIdentifier(osTableName);
     203             : 
     204           0 :     osSELECTWithoutWHERE = osBaseSQL;
     205             : 
     206           0 :     return poFeatureDefn;
     207             : }
     208             : 
     209             : /************************************************************************/
     210             : /*                        FetchNewFeatures()                            */
     211             : /************************************************************************/
     212             : 
     213           0 : json_object *OGRAmigoCloudTableLayer::FetchNewFeatures(GIntBig iNextIn)
     214             : {
     215           0 :     if (!osFIDColName.empty())
     216             :     {
     217           0 :         CPLString osSQL;
     218             : 
     219           0 :         if (!osWHERE.empty())
     220             :         {
     221             :             osSQL.Printf("%s WHERE %s ", osSELECTWithoutWHERE.c_str(),
     222           0 :                          (!osWHERE.empty()) ? CPLSPrintf("%s", osWHERE.c_str())
     223           0 :                                             : "");
     224             :         }
     225             :         else
     226             :         {
     227           0 :             osSQL.Printf("%s", osSELECTWithoutWHERE.c_str());
     228             :         }
     229             : 
     230           0 :         if (osSQL.ifind("SELECT") != std::string::npos &&
     231           0 :             osSQL.ifind(" LIMIT ") == std::string::npos)
     232             :         {
     233           0 :             osSQL += " LIMIT ";
     234           0 :             osSQL += CPLSPrintf("%d", GetFeaturesToFetch());
     235           0 :             osSQL += " OFFSET ";
     236           0 :             osSQL += CPLSPrintf(CPL_FRMT_GIB, iNextIn);
     237             :         }
     238           0 :         return poDS->RunSQL(osSQL);
     239             :     }
     240             :     else
     241           0 :         return OGRAmigoCloudLayer::FetchNewFeatures(iNextIn);
     242             : }
     243             : 
     244             : /************************************************************************/
     245             : /*                           GetNextRawFeature()                        */
     246             : /************************************************************************/
     247             : 
     248           0 : OGRFeature *OGRAmigoCloudTableLayer::GetNextRawFeature()
     249             : {
     250           0 :     if (bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE)
     251           0 :         return nullptr;
     252           0 :     FlushDeferredInsert();
     253           0 :     return OGRAmigoCloudLayer::GetNextRawFeature();
     254             : }
     255             : 
     256             : /************************************************************************/
     257             : /*                         SetAttributeFilter()                         */
     258             : /************************************************************************/
     259             : 
     260           0 : OGRErr OGRAmigoCloudTableLayer::SetAttributeFilter(const char *pszQuery)
     261             : 
     262             : {
     263           0 :     GetLayerDefn();
     264             : 
     265           0 :     if (pszQuery == nullptr)
     266           0 :         osQuery = "";
     267             :     else
     268             :     {
     269           0 :         osQuery = "(";
     270           0 :         osQuery += pszQuery;
     271           0 :         osQuery += ")";
     272             :     }
     273             : 
     274           0 :     BuildWhere();
     275             : 
     276           0 :     ResetReading();
     277             : 
     278           0 :     return OGRERR_NONE;
     279             : }
     280             : 
     281             : /************************************************************************/
     282             : /*                          ISetSpatialFilter()                          */
     283             : /************************************************************************/
     284             : 
     285           0 : OGRErr OGRAmigoCloudTableLayer::ISetSpatialFilter(int iGeomField,
     286             :                                                   const OGRGeometry *poGeomIn)
     287             : 
     288             : {
     289           0 :     m_iGeomFieldFilter = iGeomField;
     290             : 
     291           0 :     if (InstallFilter(poGeomIn))
     292             :     {
     293           0 :         BuildWhere();
     294             : 
     295           0 :         ResetReading();
     296             :     }
     297           0 :     return OGRERR_NONE;
     298             : }
     299             : 
     300             : /************************************************************************/
     301             : /*                         FlushDeferredInsert()                          */
     302             : /************************************************************************/
     303             : 
     304           0 : void OGRAmigoCloudTableLayer::FlushDeferredInsert()
     305             : 
     306             : {
     307           0 :     if (vsDeferredInsertChangesets.empty())
     308           0 :         return;
     309             : 
     310           0 :     std::stringstream url;
     311           0 :     url << std::string(poDS->GetAPIURL())
     312           0 :         << "/users/0/projects/" + std::string(poDS->GetProjectId()) +
     313           0 :                "/datasets/" + osDatasetId + "/submit_change";
     314             : 
     315           0 :     std::stringstream query;
     316             : 
     317           0 :     query << "{\"type\":\"DML\",\"entity\":\"" << osTableName << "\",";
     318           0 :     query << "\"parent\":null,\"action\":\"INSERT\",\"data\":[";
     319             : 
     320           0 :     int counter = 0;
     321           0 :     for (size_t i = 0; i < vsDeferredInsertChangesets.size(); i++)
     322             :     {
     323           0 :         if (counter > 0)
     324           0 :             query << ",";
     325           0 :         query << vsDeferredInsertChangesets[i].c_str();
     326           0 :         counter++;
     327             :     }
     328           0 :     query << "]}";
     329             : 
     330           0 :     std::stringstream changeset;
     331           0 :     changeset << "{\"change\": \"" << OGRAMIGOCLOUDJsonEncode(query.str())
     332           0 :               << "\"}";
     333             : 
     334             :     json_object *poObj =
     335           0 :         poDS->RunPOST(url.str().c_str(), changeset.str().c_str());
     336           0 :     if (poObj != nullptr)
     337           0 :         json_object_put(poObj);
     338             : 
     339           0 :     vsDeferredInsertChangesets.clear();
     340           0 :     nNextFID = -1;
     341             : }
     342             : 
     343             : /************************************************************************/
     344             : /*                            CreateField()                             */
     345             : /************************************************************************/
     346             : 
     347           0 : OGRErr OGRAmigoCloudTableLayer::CreateField(const OGRFieldDefn *poFieldIn,
     348             :                                             CPL_UNUSED int bApproxOK)
     349             : {
     350           0 :     GetLayerDefn();
     351             : 
     352           0 :     if (!poDS->IsReadWrite())
     353             :     {
     354           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     355             :                  "Operation not available in read-only mode");
     356           0 :         return OGRERR_FAILURE;
     357             :     }
     358             : 
     359           0 :     OGRFieldDefn oField(poFieldIn);
     360             :     /* -------------------------------------------------------------------- */
     361             :     /*      Create the new field.                                           */
     362             :     /* -------------------------------------------------------------------- */
     363             : 
     364           0 :     if (!bDeferredCreation)
     365             :     {
     366           0 :         CPLString osSQL;
     367             :         osSQL.Printf("ALTER TABLE %s ADD COLUMN %s %s",
     368           0 :                      OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str(),
     369           0 :                      OGRAMIGOCLOUDEscapeIdentifier(oField.GetNameRef()).c_str(),
     370           0 :                      OGRPGCommonLayerGetType(oField, false, true).c_str());
     371           0 :         if (!oField.IsNullable())
     372           0 :             osSQL += " NOT NULL";
     373           0 :         if (oField.GetDefault() != nullptr && !oField.IsDefaultDriverSpecific())
     374             :         {
     375           0 :             osSQL += " DEFAULT ";
     376           0 :             osSQL += OGRPGCommonLayerGetPGDefault(&oField);
     377             :         }
     378             : 
     379           0 :         json_object *poObj = poDS->RunSQL(osSQL);
     380           0 :         if (poObj == nullptr)
     381           0 :             return OGRERR_FAILURE;
     382           0 :         json_object_put(poObj);
     383             :     }
     384             : 
     385           0 :     poFeatureDefn->AddFieldDefn(&oField);
     386             : 
     387           0 :     return OGRERR_NONE;
     388             : }
     389             : 
     390             : /************************************************************************/
     391             : /*                           ICreateFeature()                            */
     392             : /************************************************************************/
     393             : 
     394           0 : OGRErr OGRAmigoCloudTableLayer::ICreateFeature(OGRFeature *poFeature)
     395             : 
     396             : {
     397           0 :     if (bDeferredCreation)
     398             :     {
     399           0 :         if (RunDeferredCreationIfNecessary() != OGRERR_NONE)
     400           0 :             return OGRERR_FAILURE;
     401             :     }
     402             : 
     403           0 :     GetLayerDefn();
     404             : 
     405           0 :     if (!poDS->IsReadWrite())
     406             :     {
     407           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     408             :                  "Operation not available in read-only mode");
     409           0 :         return OGRERR_FAILURE;
     410             :     }
     411             : 
     412           0 :     std::stringstream record;
     413             : 
     414           0 :     record << "{\"new\":{";
     415             : 
     416           0 :     int counter = 0;
     417             : 
     418             :     // Add geometry field
     419           0 :     for (int i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++)
     420             :     {
     421           0 :         if (poFeature->GetGeomFieldRef(i) == nullptr)
     422           0 :             continue;
     423             : 
     424             :         record << "\""
     425           0 :                << OGRAMIGOCLOUDJsonEncode(
     426           0 :                       poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef())
     427           0 :                << "\":";
     428             : 
     429           0 :         OGRGeometry *poGeom = poFeature->GetGeomFieldRef(i);
     430           0 :         if (poGeom == nullptr)
     431           0 :             continue;
     432             : 
     433             :         OGRAmigoCloudGeomFieldDefn *poGeomFieldDefn =
     434           0 :             cpl::down_cast<OGRAmigoCloudGeomFieldDefn *>(
     435           0 :                 poFeatureDefn->GetGeomFieldDefn(i));
     436           0 :         int nSRID = poGeomFieldDefn->nSRID;
     437           0 :         if (nSRID == 0)
     438           0 :             nSRID = 4326;
     439           0 :         char *pszEWKB = nullptr;
     440           0 :         if (wkbFlatten(poGeom->getGeometryType()) == wkbPolygon &&
     441           0 :             wkbFlatten(GetGeomType()) == wkbMultiPolygon)
     442             :         {
     443           0 :             OGRMultiPolygon *poNewGeom = new OGRMultiPolygon();
     444           0 :             poNewGeom->addGeometry(poGeom);
     445           0 :             pszEWKB = OGRGeometryToHexEWKB(poNewGeom, nSRID, 2, 1);
     446           0 :             delete poNewGeom;
     447             :         }
     448             :         else
     449             : 
     450           0 :             pszEWKB = OGRGeometryToHexEWKB(poGeom, nSRID, 2, 1);
     451           0 :         record << "\"" << pszEWKB << "\"";
     452           0 :         CPLFree(pszEWKB);
     453             : 
     454           0 :         counter++;
     455             :     }
     456             : 
     457           0 :     std::string amigo_id_value;
     458             : 
     459             :     // Add non-geometry field
     460           0 :     for (int i = 0; i < poFeatureDefn->GetFieldCount(); i++)
     461             :     {
     462           0 :         std::string name = poFeatureDefn->GetFieldDefn(i)->GetNameRef();
     463           0 :         std::string value = poFeature->GetFieldAsString(i);
     464             : 
     465           0 :         if (name == "amigo_id")
     466             :         {
     467           0 :             amigo_id_value = std::move(value);
     468           0 :             continue;
     469             :         }
     470           0 :         if (!poFeature->IsFieldSet(i))
     471           0 :             continue;
     472             : 
     473           0 :         if (counter > 0)
     474           0 :             record << ",";
     475             : 
     476           0 :         record << OGRAMIGOCLOUDEscapeIdentifier(name.c_str()) << ":";
     477             : 
     478           0 :         if (!poFeature->IsFieldNull(i))
     479             :         {
     480           0 :             OGRFieldType eType = poFeatureDefn->GetFieldDefn(i)->GetType();
     481           0 :             if (eType == OFTString || eType == OFTDateTime ||
     482           0 :                 eType == OFTDate || eType == OFTTime)
     483             :             {
     484           0 :                 record << "\"" << OGRAMIGOCLOUDJsonEncode(value.c_str())
     485           0 :                        << "\"";
     486             :             }
     487             :             else
     488           0 :                 record << OGRAMIGOCLOUDJsonEncode(value.c_str());
     489             :         }
     490             :         else
     491           0 :             record << "null";
     492             : 
     493           0 :         counter++;
     494             :     }
     495             : 
     496           0 :     record << "},";
     497             : 
     498           0 :     if (!amigo_id_value.empty())
     499             :     {
     500           0 :         record << "\"amigo_id\":\"" << amigo_id_value << "\"";
     501             :     }
     502             :     else
     503             :     {
     504           0 :         record << "\"amigo_id\":null";
     505             :     }
     506             : 
     507           0 :     record << "}";
     508             : 
     509           0 :     vsDeferredInsertChangesets.push_back(record.str());
     510             : 
     511           0 :     return OGRERR_NONE;
     512             : }
     513             : 
     514             : /************************************************************************/
     515             : /*                            ISetFeature()                              */
     516             : /************************************************************************/
     517             : 
     518           0 : OGRErr OGRAmigoCloudTableLayer::ISetFeature(OGRFeature *poFeature)
     519             : 
     520             : {
     521           0 :     OGRErr eRet = OGRERR_FAILURE;
     522             : 
     523           0 :     if (bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE)
     524           0 :         return OGRERR_FAILURE;
     525           0 :     FlushDeferredInsert();
     526             : 
     527           0 :     GetLayerDefn();
     528             : 
     529           0 :     if (!poDS->IsReadWrite())
     530             :     {
     531           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     532             :                  "Operation not available in read-only mode");
     533           0 :         return OGRERR_FAILURE;
     534             :     }
     535             : 
     536           0 :     if (poFeature->GetFID() == OGRNullFID)
     537             :     {
     538           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     539             :                  "FID required on features given to SetFeature().");
     540           0 :         return OGRERR_FAILURE;
     541             :     }
     542             : 
     543           0 :     const auto it = mFIDs.find(poFeature->GetFID());
     544           0 :     if (it != mFIDs.end())
     545             :     {
     546           0 :         const OGRAmigoCloudFID &aFID = it->second;
     547             : 
     548           0 :         CPLString osSQL;
     549             :         osSQL.Printf("UPDATE %s SET ",
     550           0 :                      OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str());
     551           0 :         bool bMustComma = false;
     552           0 :         for (int i = 0; i < poFeatureDefn->GetFieldCount(); i++)
     553             :         {
     554           0 :             if (!poFeature->IsFieldSet(i))
     555           0 :                 continue;
     556             : 
     557           0 :             if (bMustComma)
     558           0 :                 osSQL += ", ";
     559             :             else
     560           0 :                 bMustComma = true;
     561             : 
     562           0 :             osSQL += OGRAMIGOCLOUDEscapeIdentifier(
     563           0 :                 poFeatureDefn->GetFieldDefn(i)->GetNameRef());
     564           0 :             osSQL += " = ";
     565             : 
     566           0 :             if (poFeature->IsFieldNull(i))
     567             :             {
     568           0 :                 osSQL += "NULL";
     569             :             }
     570             :             else
     571             :             {
     572           0 :                 OGRFieldType eType = poFeatureDefn->GetFieldDefn(i)->GetType();
     573           0 :                 if (eType == OFTString || eType == OFTDateTime ||
     574           0 :                     eType == OFTDate || eType == OFTTime)
     575             :                 {
     576           0 :                     osSQL += "'";
     577             :                     osSQL +=
     578           0 :                         OGRAMIGOCLOUDJsonEncode(poFeature->GetFieldAsString(i));
     579           0 :                     osSQL += "'";
     580             :                 }
     581           0 :                 else if ((eType == OFTInteger || eType == OFTInteger64) &&
     582           0 :                          poFeatureDefn->GetFieldDefn(i)->GetSubType() ==
     583             :                              OFSTBoolean)
     584             :                 {
     585           0 :                     osSQL += poFeature->GetFieldAsInteger(i) ? "'t'" : "'f'";
     586             :                 }
     587             :                 else
     588           0 :                     osSQL += poFeature->GetFieldAsString(i);
     589             :             }
     590             :         }
     591             : 
     592           0 :         for (int i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++)
     593             :         {
     594           0 :             if (bMustComma)
     595           0 :                 osSQL += ", ";
     596             :             else
     597           0 :                 bMustComma = true;
     598             : 
     599           0 :             osSQL += OGRAMIGOCLOUDEscapeIdentifier(
     600           0 :                 poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef());
     601           0 :             osSQL += " = ";
     602             : 
     603           0 :             OGRGeometry *poGeom = poFeature->GetGeomFieldRef(i);
     604           0 :             if (poGeom == nullptr)
     605             :             {
     606           0 :                 osSQL += "NULL";
     607             :             }
     608             :             else
     609             :             {
     610             :                 OGRAmigoCloudGeomFieldDefn *poGeomFieldDefn =
     611           0 :                     cpl::down_cast<OGRAmigoCloudGeomFieldDefn *>(
     612           0 :                         poFeatureDefn->GetGeomFieldDefn(i));
     613           0 :                 int nSRID = poGeomFieldDefn->nSRID;
     614           0 :                 if (nSRID == 0)
     615           0 :                     nSRID = 4326;
     616           0 :                 char *pszEWKB = OGRGeometryToHexEWKB(poGeom, nSRID, 2, 1);
     617           0 :                 osSQL += "'";
     618           0 :                 osSQL += pszEWKB;
     619           0 :                 osSQL += "'";
     620           0 :                 CPLFree(pszEWKB);
     621             :             }
     622             :         }
     623             : 
     624           0 :         if (!bMustComma)  // nothing to do
     625           0 :             return OGRERR_NONE;
     626             : 
     627             :         osSQL += CPLSPrintf(" WHERE %s = '%s'",
     628           0 :                             OGRAMIGOCLOUDEscapeIdentifier(osFIDColName).c_str(),
     629           0 :                             aFID.osAmigoId.c_str());
     630             : 
     631           0 :         std::stringstream changeset;
     632           0 :         changeset << "{\"query\": \"" << OGRAMIGOCLOUDJsonEncode(osSQL)
     633           0 :                   << "\"}";
     634           0 :         std::stringstream url;
     635           0 :         url << std::string(poDS->GetAPIURL())
     636           0 :             << "/users/0/projects/" + std::string(poDS->GetProjectId()) +
     637           0 :                    "/sql";
     638             :         json_object *poObj =
     639           0 :             poDS->RunPOST(url.str().c_str(), changeset.str().c_str());
     640             : 
     641           0 :         if (poObj != nullptr)
     642             :         {
     643             :             json_object *poTotalRows =
     644           0 :                 CPL_json_object_object_get(poObj, "total_rows");
     645           0 :             if (poTotalRows != nullptr &&
     646           0 :                 json_object_get_type(poTotalRows) == json_type_int)
     647             :             {
     648           0 :                 int nTotalRows = json_object_get_int(poTotalRows);
     649           0 :                 if (nTotalRows > 0)
     650             :                 {
     651           0 :                     eRet = OGRERR_NONE;
     652             :                 }
     653             :                 else
     654           0 :                     eRet = OGRERR_NON_EXISTING_FEATURE;
     655             :             }
     656           0 :             json_object_put(poObj);
     657             :         }
     658             :     }
     659           0 :     return eRet;
     660             : }
     661             : 
     662             : /************************************************************************/
     663             : /*                          DeleteFeature()                             */
     664             : /************************************************************************/
     665             : 
     666           0 : OGRErr OGRAmigoCloudTableLayer::DeleteFeature(GIntBig nFID)
     667             : 
     668             : {
     669           0 :     OGRErr eRet = OGRERR_FAILURE;
     670             : 
     671           0 :     if (bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE)
     672           0 :         return OGRERR_FAILURE;
     673           0 :     FlushDeferredInsert();
     674             : 
     675           0 :     GetLayerDefn();
     676             : 
     677           0 :     if (!poDS->IsReadWrite())
     678             :     {
     679           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     680             :                  "Operation not available in read-only mode");
     681           0 :         return OGRERR_FAILURE;
     682             :     }
     683             : 
     684           0 :     if (osFIDColName.empty())
     685           0 :         return OGRERR_FAILURE;
     686             : 
     687           0 :     const auto it = mFIDs.find(nFID);
     688           0 :     if (it != mFIDs.end())
     689             :     {
     690           0 :         const OGRAmigoCloudFID &aFID = it->second;
     691             : 
     692           0 :         CPLString osSQL;
     693             :         osSQL.Printf("DELETE FROM %s WHERE %s = '%s'",
     694           0 :                      OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str(),
     695           0 :                      OGRAMIGOCLOUDEscapeIdentifier(osFIDColName).c_str(),
     696           0 :                      aFID.osAmigoId.c_str());
     697             : 
     698           0 :         std::stringstream changeset;
     699           0 :         changeset << "{\"query\": \"" << OGRAMIGOCLOUDJsonEncode(osSQL)
     700           0 :                   << "\"}";
     701           0 :         std::stringstream url;
     702           0 :         url << std::string(poDS->GetAPIURL())
     703           0 :             << "/users/0/projects/" + std::string(poDS->GetProjectId()) +
     704           0 :                    "/sql";
     705             :         json_object *poObj =
     706           0 :             poDS->RunPOST(url.str().c_str(), changeset.str().c_str());
     707           0 :         if (poObj != nullptr)
     708             :         {
     709           0 :             json_object_put(poObj);
     710           0 :             eRet = OGRERR_NONE;
     711             :         }
     712             :     }
     713           0 :     return eRet;
     714             : }
     715             : 
     716             : /************************************************************************/
     717             : /*                             GetSRS_SQL()                             */
     718             : /************************************************************************/
     719             : 
     720           0 : CPLString OGRAmigoCloudTableLayer::GetSRS_SQL(const char *pszGeomCol)
     721             : {
     722           0 :     CPLString osSQL;
     723             : 
     724             :     osSQL.Printf("SELECT srid, srtext FROM spatial_ref_sys WHERE srid IN "
     725             :                  "(SELECT Find_SRID('%s', '%s', '%s'))",
     726           0 :                  OGRAMIGOCLOUDJsonEncode(poDS->GetCurrentSchema()).c_str(),
     727           0 :                  OGRAMIGOCLOUDJsonEncode(osTableName).c_str(),
     728           0 :                  OGRAMIGOCLOUDJsonEncode(pszGeomCol).c_str());
     729             : 
     730           0 :     return osSQL;
     731             : }
     732             : 
     733             : /************************************************************************/
     734             : /*                             BuildWhere()                             */
     735             : /*                                                                      */
     736             : /*      Build the WHERE statement appropriate to the current set of     */
     737             : /*      criteria (spatial and attribute queries).                       */
     738             : /************************************************************************/
     739             : 
     740           0 : void OGRAmigoCloudTableLayer::BuildWhere()
     741             : 
     742             : {
     743           0 :     osWHERE = "";
     744             : 
     745           0 :     if (m_poFilterGeom != nullptr && m_iGeomFieldFilter >= 0 &&
     746           0 :         m_iGeomFieldFilter < poFeatureDefn->GetGeomFieldCount())
     747             :     {
     748           0 :         OGREnvelope sEnvelope;
     749             : 
     750           0 :         m_poFilterGeom->getEnvelope(&sEnvelope);
     751             : 
     752             :         CPLString osGeomColumn(
     753           0 :             poFeatureDefn->GetGeomFieldDefn(m_iGeomFieldFilter)->GetNameRef());
     754             : 
     755             :         char szBox3D_1[128];
     756             :         char szBox3D_2[128];
     757           0 :         char *pszComma = nullptr;
     758             : 
     759           0 :         CPLsnprintf(szBox3D_1, sizeof(szBox3D_1), "%.17g %.17g", sEnvelope.MinX,
     760             :                     sEnvelope.MinY);
     761           0 :         while ((pszComma = strchr(szBox3D_1, ',')) != nullptr)
     762           0 :             *pszComma = '.';
     763           0 :         CPLsnprintf(szBox3D_2, sizeof(szBox3D_2), "%.17g %.17g", sEnvelope.MaxX,
     764             :                     sEnvelope.MaxY);
     765           0 :         while ((pszComma = strchr(szBox3D_2, ',')) != nullptr)
     766           0 :             *pszComma = '.';
     767             :         osWHERE.Printf("(%s && 'BOX3D(%s, %s)'::box3d)",
     768           0 :                        OGRAMIGOCLOUDEscapeIdentifier(osGeomColumn).c_str(),
     769           0 :                        szBox3D_1, szBox3D_2);
     770             :     }
     771             : 
     772           0 :     if (!osQuery.empty())
     773             :     {
     774           0 :         if (!osWHERE.empty())
     775           0 :             osWHERE += " AND ";
     776           0 :         osWHERE += osQuery;
     777             :     }
     778             : 
     779           0 :     if (osFIDColName.empty())
     780             :     {
     781           0 :         osBaseSQL = osSELECTWithoutWHERE;
     782           0 :         if (!osWHERE.empty())
     783             :         {
     784           0 :             osBaseSQL += " WHERE ";
     785           0 :             osBaseSQL += osWHERE;
     786             :         }
     787             :     }
     788           0 : }
     789             : 
     790             : /************************************************************************/
     791             : /*                              GetFeature()                            */
     792             : /************************************************************************/
     793             : 
     794           0 : OGRFeature *OGRAmigoCloudTableLayer::GetFeature(GIntBig nFeatureId)
     795             : {
     796             : 
     797           0 :     if (bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE)
     798           0 :         return nullptr;
     799           0 :     FlushDeferredInsert();
     800             : 
     801           0 :     GetLayerDefn();
     802             : 
     803           0 :     if (osFIDColName.empty())
     804           0 :         return OGRAmigoCloudLayer::GetFeature(nFeatureId);
     805             : 
     806           0 :     const auto it = mFIDs.find(nFeatureId);
     807           0 :     if (it != mFIDs.end())
     808             :     {
     809           0 :         const OGRAmigoCloudFID &aFID = it->second;
     810             : 
     811           0 :         CPLString osSQL = osSELECTWithoutWHERE;
     812           0 :         osSQL += " WHERE ";
     813           0 :         osSQL += OGRAMIGOCLOUDEscapeIdentifier(osFIDColName).c_str();
     814           0 :         osSQL += " = ";
     815           0 :         osSQL += CPLSPrintf("'%s'", aFID.osAmigoId.c_str());
     816             : 
     817           0 :         json_object *poObj = poDS->RunSQL(osSQL);
     818           0 :         json_object *poRowObj = OGRAMIGOCLOUDGetSingleRow(poObj);
     819           0 :         if (poRowObj == nullptr)
     820             :         {
     821           0 :             if (poObj != nullptr)
     822           0 :                 json_object_put(poObj);
     823           0 :             return OGRAmigoCloudLayer::GetFeature(nFeatureId);
     824             :         }
     825             : 
     826           0 :         OGRFeature *poFeature = BuildFeature(poRowObj);
     827           0 :         json_object_put(poObj);
     828             : 
     829           0 :         return poFeature;
     830             :     }
     831           0 :     return nullptr;
     832             : }
     833             : 
     834             : /************************************************************************/
     835             : /*                          GetFeatureCount()                           */
     836             : /************************************************************************/
     837             : 
     838           0 : GIntBig OGRAmigoCloudTableLayer::GetFeatureCount(int bForce)
     839             : {
     840             : 
     841           0 :     if (bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE)
     842           0 :         return 0;
     843           0 :     FlushDeferredInsert();
     844             : 
     845           0 :     GetLayerDefn();
     846             : 
     847             :     CPLString osSQL(
     848             :         CPLSPrintf("SELECT COUNT(*) FROM %s",
     849           0 :                    OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str()));
     850           0 :     if (!osWHERE.empty())
     851             :     {
     852           0 :         osSQL += " WHERE ";
     853           0 :         osSQL += osWHERE;
     854             :     }
     855             : 
     856           0 :     json_object *poObj = poDS->RunSQL(osSQL);
     857           0 :     json_object *poRowObj = OGRAMIGOCLOUDGetSingleRow(poObj);
     858           0 :     if (poRowObj == nullptr)
     859             :     {
     860           0 :         if (poObj != nullptr)
     861           0 :             json_object_put(poObj);
     862           0 :         return OGRAmigoCloudLayer::GetFeatureCount(bForce);
     863             :     }
     864             : 
     865           0 :     json_object *poCount = CPL_json_object_object_get(poRowObj, "count");
     866           0 :     if (poCount == nullptr || json_object_get_type(poCount) != json_type_int)
     867             :     {
     868           0 :         json_object_put(poObj);
     869           0 :         return OGRAmigoCloudLayer::GetFeatureCount(bForce);
     870             :     }
     871             : 
     872           0 :     GIntBig nRet = (GIntBig)json_object_get_int64(poCount);
     873             : 
     874           0 :     json_object_put(poObj);
     875             : 
     876           0 :     return nRet;
     877             : }
     878             : 
     879             : /************************************************************************/
     880             : /*                            IGetExtent()                              */
     881             : /*                                                                      */
     882             : /*      For PostGIS use internal Extend(geometry) function              */
     883             : /*      in other cases we use standard OGRLayer::GetExtent()            */
     884             : /************************************************************************/
     885             : 
     886           0 : OGRErr OGRAmigoCloudTableLayer::IGetExtent(int iGeomField,
     887             :                                            OGREnvelope *psExtent, bool bForce)
     888             : {
     889           0 :     CPLString osSQL;
     890             : 
     891           0 :     if (bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE)
     892           0 :         return OGRERR_FAILURE;
     893           0 :     FlushDeferredInsert();
     894             : 
     895             :     OGRGeomFieldDefn *poGeomFieldDefn =
     896           0 :         poFeatureDefn->GetGeomFieldDefn(iGeomField);
     897             : 
     898             :     /* Do not take the spatial filter into account */
     899             :     osSQL.Printf(
     900             :         "SELECT ST_Extent(%s) FROM %s",
     901           0 :         OGRAMIGOCLOUDEscapeIdentifier(poGeomFieldDefn->GetNameRef()).c_str(),
     902           0 :         OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str());
     903             : 
     904           0 :     json_object *poObj = poDS->RunSQL(osSQL);
     905           0 :     json_object *poRowObj = OGRAMIGOCLOUDGetSingleRow(poObj);
     906           0 :     if (poRowObj != nullptr)
     907             :     {
     908             :         json_object *poExtent =
     909           0 :             CPL_json_object_object_get(poRowObj, "st_extent");
     910           0 :         if (poExtent != nullptr &&
     911           0 :             json_object_get_type(poExtent) == json_type_string)
     912             :         {
     913           0 :             const char *pszBox = json_object_get_string(poExtent);
     914             :             const char *ptr, *ptrEndParenthesis;
     915             :             char szVals[64 * 6 + 6];
     916             : 
     917           0 :             ptr = strchr(pszBox, '(');
     918           0 :             if (ptr)
     919           0 :                 ptr++;
     920           0 :             if (ptr == nullptr ||
     921           0 :                 (ptrEndParenthesis = strchr(ptr, ')')) == nullptr ||
     922           0 :                 ptrEndParenthesis - ptr > (int)(sizeof(szVals) - 1))
     923             :             {
     924           0 :                 CPLError(CE_Failure, CPLE_IllegalArg,
     925             :                          "Bad extent representation: '%s'", pszBox);
     926             : 
     927           0 :                 json_object_put(poObj);
     928           0 :                 return OGRERR_FAILURE;
     929             :             }
     930             : 
     931           0 :             strncpy(szVals, ptr, ptrEndParenthesis - ptr);
     932           0 :             szVals[ptrEndParenthesis - ptr] = '\0';
     933             : 
     934             :             char **papszTokens =
     935           0 :                 CSLTokenizeString2(szVals, " ,", CSLT_HONOURSTRINGS);
     936           0 :             int nTokenCnt = 4;
     937             : 
     938           0 :             if (CSLCount(papszTokens) != nTokenCnt)
     939             :             {
     940           0 :                 CPLError(CE_Failure, CPLE_IllegalArg,
     941             :                          "Bad extent representation: '%s'", pszBox);
     942           0 :                 CSLDestroy(papszTokens);
     943             : 
     944           0 :                 json_object_put(poObj);
     945           0 :                 return OGRERR_FAILURE;
     946             :             }
     947             : 
     948             :             // Take X,Y coords
     949             :             // For PostGIS ver >= 1.0.0 -> Tokens: X1 Y1 X2 Y2 (nTokenCnt = 4)
     950             :             // For PostGIS ver < 1.0.0 -> Tokens: X1 Y1 Z1 X2 Y2 Z2 (nTokenCnt =
     951             :             // 6)
     952             :             // =>   X2 index calculated as nTokenCnt/2
     953             :             //      Y2 index calculated as nTokenCnt/2+1
     954             : 
     955           0 :             psExtent->MinX = CPLAtof(papszTokens[0]);
     956           0 :             psExtent->MinY = CPLAtof(papszTokens[1]);
     957           0 :             psExtent->MaxX = CPLAtof(papszTokens[nTokenCnt / 2]);
     958           0 :             psExtent->MaxY = CPLAtof(papszTokens[nTokenCnt / 2 + 1]);
     959             : 
     960           0 :             CSLDestroy(papszTokens);
     961             : 
     962           0 :             json_object_put(poObj);
     963           0 :             return OGRERR_NONE;
     964             :         }
     965             :     }
     966             : 
     967           0 :     if (poObj != nullptr)
     968           0 :         json_object_put(poObj);
     969             : 
     970           0 :     return OGRLayer::IGetExtent(iGeomField, psExtent, bForce);
     971             : }
     972             : 
     973             : /************************************************************************/
     974             : /*                           TestCapability()                           */
     975             : /************************************************************************/
     976             : 
     977           0 : int OGRAmigoCloudTableLayer::TestCapability(const char *pszCap)
     978             : 
     979             : {
     980           0 :     if (EQUAL(pszCap, OLCFastFeatureCount))
     981           0 :         return TRUE;
     982           0 :     if (EQUAL(pszCap, OLCFastGetExtent))
     983           0 :         return TRUE;
     984           0 :     if (EQUAL(pszCap, OLCRandomRead))
     985             :     {
     986           0 :         GetLayerDefn();
     987           0 :         return !osFIDColName.empty();
     988             :     }
     989             : 
     990           0 :     if (EQUAL(pszCap, OLCSequentialWrite) || EQUAL(pszCap, OLCRandomWrite) ||
     991           0 :         EQUAL(pszCap, OLCDeleteFeature) || EQUAL(pszCap, ODsCCreateLayer) ||
     992           0 :         EQUAL(pszCap, ODsCDeleteLayer))
     993             :     {
     994           0 :         return poDS->IsReadWrite();
     995             :     }
     996             : 
     997           0 :     return OGRAmigoCloudLayer::TestCapability(pszCap);
     998             : }
     999             : 
    1000             : /************************************************************************/
    1001             : /*                        SetDeferredCreation()                          */
    1002             : /************************************************************************/
    1003             : 
    1004           0 : void OGRAmigoCloudTableLayer::SetDeferredCreation(OGRwkbGeometryType eGType,
    1005             :                                                   OGRSpatialReference *poSRS,
    1006             :                                                   int bGeomNullable)
    1007             : {
    1008           0 :     bDeferredCreation = TRUE;
    1009           0 :     nNextFID = 1;
    1010           0 :     CPLAssert(poFeatureDefn == nullptr);
    1011           0 :     poFeatureDefn = new OGRFeatureDefn(osTableName);
    1012           0 :     poFeatureDefn->Reference();
    1013           0 :     poFeatureDefn->SetGeomType(wkbNone);
    1014           0 :     if (eGType == wkbPolygon)
    1015           0 :         eGType = wkbMultiPolygon;
    1016           0 :     else if (eGType == wkbPolygon25D)
    1017           0 :         eGType = wkbMultiPolygon25D;
    1018           0 :     if (eGType != wkbNone)
    1019             :     {
    1020             :         auto poFieldDefn = std::make_unique<OGRAmigoCloudGeomFieldDefn>(
    1021           0 :             "wkb_geometry", eGType);
    1022           0 :         poFieldDefn->SetNullable(bGeomNullable);
    1023           0 :         if (poSRS != nullptr)
    1024             :         {
    1025           0 :             poFieldDefn->nSRID = poDS->FetchSRSId(poSRS);
    1026           0 :             poFieldDefn->SetSpatialRef(poSRS);
    1027             :         }
    1028           0 :         poFeatureDefn->AddGeomFieldDefn(std::move(poFieldDefn));
    1029             :     }
    1030             : 
    1031             :     osBaseSQL.Printf("SELECT * FROM %s",
    1032           0 :                      OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str());
    1033           0 : }
    1034             : 
    1035           0 : CPLString OGRAmigoCloudTableLayer::GetAmigoCloudType(const OGRFieldDefn &oField)
    1036             : {
    1037             :     char szFieldType[256];
    1038             : 
    1039             :     /* -------------------------------------------------------------------- */
    1040             :     /*      AmigoCloud supported types.                                   */
    1041             :     /* -------------------------------------------------------------------- */
    1042           0 :     if (oField.GetType() == OFTInteger)
    1043             :     {
    1044           0 :         strcpy(szFieldType, "integer");
    1045             :     }
    1046           0 :     else if (oField.GetType() == OFTInteger64)
    1047             :     {
    1048           0 :         strcpy(szFieldType, "bigint");
    1049             :     }
    1050           0 :     else if (oField.GetType() == OFTReal)
    1051             :     {
    1052           0 :         strcpy(szFieldType, "float");
    1053             :     }
    1054           0 :     else if (oField.GetType() == OFTString)
    1055             :     {
    1056           0 :         strcpy(szFieldType, "string");
    1057             :     }
    1058           0 :     else if (oField.GetType() == OFTDate)
    1059             :     {
    1060           0 :         strcpy(szFieldType, "date");
    1061             :     }
    1062           0 :     else if (oField.GetType() == OFTTime)
    1063             :     {
    1064           0 :         strcpy(szFieldType, "time");
    1065             :     }
    1066           0 :     else if (oField.GetType() == OFTDateTime)
    1067             :     {
    1068           0 :         strcpy(szFieldType, "datetime");
    1069             :     }
    1070             :     else
    1071             :     {
    1072           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    1073             :                  "Can't create field %s with type %s on PostgreSQL layers.",
    1074             :                  oField.GetNameRef(),
    1075             :                  OGRFieldDefn::GetFieldTypeName(oField.GetType()));
    1076           0 :         strcpy(szFieldType, "");
    1077             :     }
    1078             : 
    1079           0 :     return szFieldType;
    1080             : }
    1081             : 
    1082           0 : bool OGRAmigoCloudTableLayer::IsDatasetExists()
    1083             : {
    1084           0 :     std::stringstream url;
    1085           0 :     url << std::string(poDS->GetAPIURL())
    1086           0 :         << "/users/0/projects/" + std::string(poDS->GetProjectId()) +
    1087           0 :                "/datasets/" + osDatasetId;
    1088           0 :     json_object *result = poDS->RunGET(url.str().c_str());
    1089           0 :     if (result == nullptr)
    1090           0 :         return false;
    1091             : 
    1092             :     {
    1093           0 :         int type = json_object_get_type(result);
    1094           0 :         if (type == json_type_object)
    1095             :         {
    1096           0 :             json_object *poId = CPL_json_object_object_get(result, "id");
    1097           0 :             if (poId != nullptr)
    1098             :             {
    1099           0 :                 json_object_put(result);
    1100           0 :                 return true;
    1101             :             }
    1102             :         }
    1103           0 :         json_object_put(result);
    1104             :     }
    1105             : 
    1106             :     // Sleep 3 sec
    1107           0 :     CPLSleep(3);
    1108             : 
    1109           0 :     return false;
    1110             : }
    1111             : 
    1112             : /************************************************************************/
    1113             : /*                      RunDeferredCreationIfNecessary()                 */
    1114             : /************************************************************************/
    1115             : 
    1116           0 : OGRErr OGRAmigoCloudTableLayer::RunDeferredCreationIfNecessary()
    1117             : {
    1118           0 :     if (!bDeferredCreation)
    1119           0 :         return OGRERR_NONE;
    1120           0 :     bDeferredCreation = FALSE;
    1121           0 :     std::stringstream json;
    1122           0 :     json << "{ \"name\":\"" << osDatasetId << "\",";
    1123           0 :     json << "\"schema\": \"[";
    1124           0 :     int counter = 0;
    1125           0 :     OGRwkbGeometryType eGType = GetGeomType();
    1126           0 :     if (eGType != wkbNone)
    1127             :     {
    1128           0 :         CPLString osGeomType = OGRToOGCGeomType(eGType);
    1129           0 :         if (wkbHasZ(eGType))
    1130           0 :             osGeomType += "Z";
    1131             : 
    1132             :         OGRAmigoCloudGeomFieldDefn *poFieldDefn =
    1133           0 :             cpl::down_cast<OGRAmigoCloudGeomFieldDefn *>(
    1134           0 :                 poFeatureDefn->GetGeomFieldDefn(0));
    1135             : 
    1136           0 :         json << "{\\\"name\\\":\\\"" << poFieldDefn->GetNameRef() << "\\\",";
    1137           0 :         json << "\\\"type\\\":\\\"geometry\\\",";
    1138           0 :         json << "\\\"geometry_type\\\":\\\"" << osGeomType << "\\\",";
    1139             : 
    1140           0 :         if (!poFieldDefn->IsNullable())
    1141           0 :             json << "\\\"nullable\\\":false,";
    1142             :         else
    1143           0 :             json << "\\\"nullable\\\":true,";
    1144             : 
    1145           0 :         json << "\\\"visible\\\": true}";
    1146             : 
    1147           0 :         counter++;
    1148             :     }
    1149             : 
    1150           0 :     for (int i = 0; i < poFeatureDefn->GetFieldCount(); i++)
    1151             :     {
    1152           0 :         OGRFieldDefn *poFieldDefn = poFeatureDefn->GetFieldDefn(i);
    1153           0 :         if (strcmp(poFieldDefn->GetNameRef(), osFIDColName) != 0)
    1154             :         {
    1155           0 :             if (counter > 0)
    1156           0 :                 json << ",";
    1157             : 
    1158             :             json << "{\\\"name\\\":\\\"" << poFieldDefn->GetNameRef()
    1159           0 :                  << "\\\",";
    1160           0 :             json << "\\\"type\\\":\\\"" << GetAmigoCloudType(*poFieldDefn)
    1161           0 :                  << "\\\",";
    1162           0 :             if (!poFieldDefn->IsNullable())
    1163           0 :                 json << "\\\"nullable\\\":false,";
    1164             :             else
    1165           0 :                 json << "\\\"nullable\\\":true,";
    1166             : 
    1167           0 :             if (poFieldDefn->GetDefault() != nullptr &&
    1168           0 :                 !poFieldDefn->IsDefaultDriverSpecific())
    1169             :             {
    1170             :                 json << "\\\"default\\\":\\\"" << poFieldDefn->GetDefault()
    1171           0 :                      << "\\\",";
    1172             :             }
    1173           0 :             json << "\\\"visible\\\": true}";
    1174           0 :             counter++;
    1175             :         }
    1176             :     }
    1177             : 
    1178           0 :     json << " ] \" }";
    1179             : 
    1180           0 :     std::stringstream url;
    1181           0 :     url << std::string(poDS->GetAPIURL())
    1182           0 :         << "/users/0/projects/" + std::string(poDS->GetProjectId()) +
    1183           0 :                "/datasets/create";
    1184             : 
    1185           0 :     json_object *result = poDS->RunPOST(url.str().c_str(), json.str().c_str());
    1186           0 :     if (result != nullptr)
    1187             :     {
    1188           0 :         if (json_object_get_type(result) == json_type_object)
    1189             :         {
    1190           0 :             json_object *poName = CPL_json_object_object_get(result, "name");
    1191           0 :             if (poName != nullptr)
    1192             :             {
    1193           0 :                 osName = json_object_to_json_string(poName);
    1194             :             }
    1195             : 
    1196           0 :             json_object *poId = CPL_json_object_object_get(result, "id");
    1197           0 :             if (poId != nullptr)
    1198             :             {
    1199             :                 osTableName =
    1200           0 :                     CPLString("dataset_") + json_object_to_json_string(poId);
    1201           0 :                 osDatasetId = json_object_to_json_string(poId);
    1202           0 :                 int retry = 10;
    1203           0 :                 while (!IsDatasetExists() && retry >= 0)
    1204             :                 {
    1205           0 :                     retry--;
    1206             :                 }
    1207           0 :                 json_object_put(result);
    1208           0 :                 return OGRERR_NONE;
    1209             :             }
    1210             :         }
    1211             :     }
    1212           0 :     return OGRERR_FAILURE;
    1213             : }

Generated by: LCOV version 1.14