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 : (OGRAmigoCloudGeomFieldDefn *)poFeatureDefn->GetGeomFieldDefn(i);
435 0 : int nSRID = poGeomFieldDefn->nSRID;
436 0 : if (nSRID == 0)
437 0 : nSRID = 4326;
438 0 : char *pszEWKB = nullptr;
439 0 : if (wkbFlatten(poGeom->getGeometryType()) == wkbPolygon &&
440 0 : wkbFlatten(GetGeomType()) == wkbMultiPolygon)
441 : {
442 0 : OGRMultiPolygon *poNewGeom = new OGRMultiPolygon();
443 0 : poNewGeom->addGeometry(poGeom);
444 0 : pszEWKB = OGRGeometryToHexEWKB(poNewGeom, nSRID, 2, 1);
445 0 : delete poNewGeom;
446 : }
447 : else
448 :
449 0 : pszEWKB = OGRGeometryToHexEWKB(poGeom, nSRID, 2, 1);
450 0 : record << "\"" << pszEWKB << "\"";
451 0 : CPLFree(pszEWKB);
452 :
453 0 : counter++;
454 : }
455 :
456 0 : std::string amigo_id_value;
457 :
458 : // Add non-geometry field
459 0 : for (int i = 0; i < poFeatureDefn->GetFieldCount(); i++)
460 : {
461 0 : std::string name = poFeatureDefn->GetFieldDefn(i)->GetNameRef();
462 0 : std::string value = poFeature->GetFieldAsString(i);
463 :
464 0 : if (name == "amigo_id")
465 : {
466 0 : amigo_id_value = value;
467 0 : continue;
468 : }
469 0 : if (!poFeature->IsFieldSet(i))
470 0 : continue;
471 :
472 0 : if (counter > 0)
473 0 : record << ",";
474 :
475 0 : record << OGRAMIGOCLOUDEscapeIdentifier(name.c_str()) << ":";
476 :
477 0 : if (!poFeature->IsFieldNull(i))
478 : {
479 0 : OGRFieldType eType = poFeatureDefn->GetFieldDefn(i)->GetType();
480 0 : if (eType == OFTString || eType == OFTDateTime ||
481 0 : eType == OFTDate || eType == OFTTime)
482 : {
483 0 : record << "\"" << OGRAMIGOCLOUDJsonEncode(value.c_str())
484 0 : << "\"";
485 : }
486 : else
487 0 : record << OGRAMIGOCLOUDJsonEncode(value.c_str());
488 : }
489 : else
490 0 : record << "null";
491 :
492 0 : counter++;
493 : }
494 :
495 0 : record << "},";
496 :
497 0 : if (!amigo_id_value.empty())
498 : {
499 0 : record << "\"amigo_id\":\"" << amigo_id_value << "\"";
500 : }
501 : else
502 : {
503 0 : record << "\"amigo_id\":null";
504 : }
505 :
506 0 : record << "}";
507 :
508 0 : vsDeferredInsertChangesets.push_back(record.str());
509 :
510 0 : return OGRERR_NONE;
511 : }
512 :
513 : /************************************************************************/
514 : /* ISetFeature() */
515 : /************************************************************************/
516 :
517 0 : OGRErr OGRAmigoCloudTableLayer::ISetFeature(OGRFeature *poFeature)
518 :
519 : {
520 0 : OGRErr eRet = OGRERR_FAILURE;
521 :
522 0 : if (bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE)
523 0 : return OGRERR_FAILURE;
524 0 : FlushDeferredInsert();
525 :
526 0 : GetLayerDefn();
527 :
528 0 : if (!poDS->IsReadWrite())
529 : {
530 0 : CPLError(CE_Failure, CPLE_AppDefined,
531 : "Operation not available in read-only mode");
532 0 : return OGRERR_FAILURE;
533 : }
534 :
535 0 : if (poFeature->GetFID() == OGRNullFID)
536 : {
537 0 : CPLError(CE_Failure, CPLE_AppDefined,
538 : "FID required on features given to SetFeature().");
539 0 : return OGRERR_FAILURE;
540 : }
541 :
542 0 : const auto it = mFIDs.find(poFeature->GetFID());
543 0 : if (it != mFIDs.end())
544 : {
545 0 : const OGRAmigoCloudFID &aFID = it->second;
546 :
547 0 : CPLString osSQL;
548 : osSQL.Printf("UPDATE %s SET ",
549 0 : OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str());
550 0 : bool bMustComma = false;
551 0 : for (int i = 0; i < poFeatureDefn->GetFieldCount(); i++)
552 : {
553 0 : if (!poFeature->IsFieldSet(i))
554 0 : continue;
555 :
556 0 : if (bMustComma)
557 0 : osSQL += ", ";
558 : else
559 0 : bMustComma = true;
560 :
561 0 : osSQL += OGRAMIGOCLOUDEscapeIdentifier(
562 0 : poFeatureDefn->GetFieldDefn(i)->GetNameRef());
563 0 : osSQL += " = ";
564 :
565 0 : if (poFeature->IsFieldNull(i))
566 : {
567 0 : osSQL += "NULL";
568 : }
569 : else
570 : {
571 0 : OGRFieldType eType = poFeatureDefn->GetFieldDefn(i)->GetType();
572 0 : if (eType == OFTString || eType == OFTDateTime ||
573 0 : eType == OFTDate || eType == OFTTime)
574 : {
575 0 : osSQL += "'";
576 : osSQL +=
577 0 : OGRAMIGOCLOUDJsonEncode(poFeature->GetFieldAsString(i));
578 0 : osSQL += "'";
579 : }
580 0 : else if ((eType == OFTInteger || eType == OFTInteger64) &&
581 0 : poFeatureDefn->GetFieldDefn(i)->GetSubType() ==
582 : OFSTBoolean)
583 : {
584 0 : osSQL += poFeature->GetFieldAsInteger(i) ? "'t'" : "'f'";
585 : }
586 : else
587 0 : osSQL += poFeature->GetFieldAsString(i);
588 : }
589 : }
590 :
591 0 : for (int i = 0; i < poFeatureDefn->GetGeomFieldCount(); i++)
592 : {
593 0 : if (bMustComma)
594 0 : osSQL += ", ";
595 : else
596 0 : bMustComma = true;
597 :
598 0 : osSQL += OGRAMIGOCLOUDEscapeIdentifier(
599 0 : poFeatureDefn->GetGeomFieldDefn(i)->GetNameRef());
600 0 : osSQL += " = ";
601 :
602 0 : OGRGeometry *poGeom = poFeature->GetGeomFieldRef(i);
603 0 : if (poGeom == nullptr)
604 : {
605 0 : osSQL += "NULL";
606 : }
607 : else
608 : {
609 : OGRAmigoCloudGeomFieldDefn *poGeomFieldDefn =
610 : (OGRAmigoCloudGeomFieldDefn *)
611 0 : poFeatureDefn->GetGeomFieldDefn(i);
612 0 : int nSRID = poGeomFieldDefn->nSRID;
613 0 : if (nSRID == 0)
614 0 : nSRID = 4326;
615 0 : char *pszEWKB = OGRGeometryToHexEWKB(poGeom, nSRID, 2, 1);
616 0 : osSQL += "'";
617 0 : osSQL += pszEWKB;
618 0 : osSQL += "'";
619 0 : CPLFree(pszEWKB);
620 : }
621 : }
622 :
623 0 : if (!bMustComma) // nothing to do
624 0 : return OGRERR_NONE;
625 :
626 : osSQL += CPLSPrintf(" WHERE %s = '%s'",
627 0 : OGRAMIGOCLOUDEscapeIdentifier(osFIDColName).c_str(),
628 0 : aFID.osAmigoId.c_str());
629 :
630 0 : std::stringstream changeset;
631 0 : changeset << "{\"query\": \"" << OGRAMIGOCLOUDJsonEncode(osSQL)
632 0 : << "\"}";
633 0 : std::stringstream url;
634 0 : url << std::string(poDS->GetAPIURL())
635 0 : << "/users/0/projects/" + std::string(poDS->GetProjectId()) +
636 0 : "/sql";
637 : json_object *poObj =
638 0 : poDS->RunPOST(url.str().c_str(), changeset.str().c_str());
639 :
640 0 : if (poObj != nullptr)
641 : {
642 : json_object *poTotalRows =
643 0 : CPL_json_object_object_get(poObj, "total_rows");
644 0 : if (poTotalRows != nullptr &&
645 0 : json_object_get_type(poTotalRows) == json_type_int)
646 : {
647 0 : int nTotalRows = json_object_get_int(poTotalRows);
648 0 : if (nTotalRows > 0)
649 : {
650 0 : eRet = OGRERR_NONE;
651 : }
652 : else
653 0 : eRet = OGRERR_NON_EXISTING_FEATURE;
654 : }
655 0 : json_object_put(poObj);
656 : }
657 : }
658 0 : return eRet;
659 : }
660 :
661 : /************************************************************************/
662 : /* DeleteFeature() */
663 : /************************************************************************/
664 :
665 0 : OGRErr OGRAmigoCloudTableLayer::DeleteFeature(GIntBig nFID)
666 :
667 : {
668 0 : OGRErr eRet = OGRERR_FAILURE;
669 :
670 0 : if (bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE)
671 0 : return OGRERR_FAILURE;
672 0 : FlushDeferredInsert();
673 :
674 0 : GetLayerDefn();
675 :
676 0 : if (!poDS->IsReadWrite())
677 : {
678 0 : CPLError(CE_Failure, CPLE_AppDefined,
679 : "Operation not available in read-only mode");
680 0 : return OGRERR_FAILURE;
681 : }
682 :
683 0 : if (osFIDColName.empty())
684 0 : return OGRERR_FAILURE;
685 :
686 0 : const auto it = mFIDs.find(nFID);
687 0 : if (it != mFIDs.end())
688 : {
689 0 : const OGRAmigoCloudFID &aFID = it->second;
690 :
691 0 : CPLString osSQL;
692 : osSQL.Printf("DELETE FROM %s WHERE %s = '%s'",
693 0 : OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str(),
694 0 : OGRAMIGOCLOUDEscapeIdentifier(osFIDColName).c_str(),
695 0 : aFID.osAmigoId.c_str());
696 :
697 0 : std::stringstream changeset;
698 0 : changeset << "{\"query\": \"" << OGRAMIGOCLOUDJsonEncode(osSQL)
699 0 : << "\"}";
700 0 : std::stringstream url;
701 0 : url << std::string(poDS->GetAPIURL())
702 0 : << "/users/0/projects/" + std::string(poDS->GetProjectId()) +
703 0 : "/sql";
704 : json_object *poObj =
705 0 : poDS->RunPOST(url.str().c_str(), changeset.str().c_str());
706 0 : if (poObj != nullptr)
707 : {
708 0 : json_object_put(poObj);
709 0 : eRet = OGRERR_NONE;
710 : }
711 : }
712 0 : return eRet;
713 : }
714 :
715 : /************************************************************************/
716 : /* GetSRS_SQL() */
717 : /************************************************************************/
718 :
719 0 : CPLString OGRAmigoCloudTableLayer::GetSRS_SQL(const char *pszGeomCol)
720 : {
721 0 : CPLString osSQL;
722 :
723 : osSQL.Printf("SELECT srid, srtext FROM spatial_ref_sys WHERE srid IN "
724 : "(SELECT Find_SRID('%s', '%s', '%s'))",
725 0 : OGRAMIGOCLOUDJsonEncode(poDS->GetCurrentSchema()).c_str(),
726 0 : OGRAMIGOCLOUDJsonEncode(osTableName).c_str(),
727 0 : OGRAMIGOCLOUDJsonEncode(pszGeomCol).c_str());
728 :
729 0 : return osSQL;
730 : }
731 :
732 : /************************************************************************/
733 : /* BuildWhere() */
734 : /* */
735 : /* Build the WHERE statement appropriate to the current set of */
736 : /* criteria (spatial and attribute queries). */
737 : /************************************************************************/
738 :
739 0 : void OGRAmigoCloudTableLayer::BuildWhere()
740 :
741 : {
742 0 : osWHERE = "";
743 :
744 0 : if (m_poFilterGeom != nullptr && m_iGeomFieldFilter >= 0 &&
745 0 : m_iGeomFieldFilter < poFeatureDefn->GetGeomFieldCount())
746 : {
747 0 : OGREnvelope sEnvelope;
748 :
749 0 : m_poFilterGeom->getEnvelope(&sEnvelope);
750 :
751 : CPLString osGeomColumn(
752 0 : poFeatureDefn->GetGeomFieldDefn(m_iGeomFieldFilter)->GetNameRef());
753 :
754 : char szBox3D_1[128];
755 : char szBox3D_2[128];
756 0 : char *pszComma = nullptr;
757 :
758 0 : CPLsnprintf(szBox3D_1, sizeof(szBox3D_1), "%.17g %.17g", sEnvelope.MinX,
759 : sEnvelope.MinY);
760 0 : while ((pszComma = strchr(szBox3D_1, ',')) != nullptr)
761 0 : *pszComma = '.';
762 0 : CPLsnprintf(szBox3D_2, sizeof(szBox3D_2), "%.17g %.17g", sEnvelope.MaxX,
763 : sEnvelope.MaxY);
764 0 : while ((pszComma = strchr(szBox3D_2, ',')) != nullptr)
765 0 : *pszComma = '.';
766 : osWHERE.Printf("(%s && 'BOX3D(%s, %s)'::box3d)",
767 0 : OGRAMIGOCLOUDEscapeIdentifier(osGeomColumn).c_str(),
768 0 : szBox3D_1, szBox3D_2);
769 : }
770 :
771 0 : if (!osQuery.empty())
772 : {
773 0 : if (!osWHERE.empty())
774 0 : osWHERE += " AND ";
775 0 : osWHERE += osQuery;
776 : }
777 :
778 0 : if (osFIDColName.empty())
779 : {
780 0 : osBaseSQL = osSELECTWithoutWHERE;
781 0 : if (!osWHERE.empty())
782 : {
783 0 : osBaseSQL += " WHERE ";
784 0 : osBaseSQL += osWHERE;
785 : }
786 : }
787 0 : }
788 :
789 : /************************************************************************/
790 : /* GetFeature() */
791 : /************************************************************************/
792 :
793 0 : OGRFeature *OGRAmigoCloudTableLayer::GetFeature(GIntBig nFeatureId)
794 : {
795 :
796 0 : if (bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE)
797 0 : return nullptr;
798 0 : FlushDeferredInsert();
799 :
800 0 : GetLayerDefn();
801 :
802 0 : if (osFIDColName.empty())
803 0 : return OGRAmigoCloudLayer::GetFeature(nFeatureId);
804 :
805 0 : const auto it = mFIDs.find(nFeatureId);
806 0 : if (it != mFIDs.end())
807 : {
808 0 : const OGRAmigoCloudFID &aFID = it->second;
809 :
810 0 : CPLString osSQL = osSELECTWithoutWHERE;
811 0 : osSQL += " WHERE ";
812 0 : osSQL += OGRAMIGOCLOUDEscapeIdentifier(osFIDColName).c_str();
813 0 : osSQL += " = ";
814 0 : osSQL += CPLSPrintf("'%s'", aFID.osAmigoId.c_str());
815 :
816 0 : json_object *poObj = poDS->RunSQL(osSQL);
817 0 : json_object *poRowObj = OGRAMIGOCLOUDGetSingleRow(poObj);
818 0 : if (poRowObj == nullptr)
819 : {
820 0 : if (poObj != nullptr)
821 0 : json_object_put(poObj);
822 0 : return OGRAmigoCloudLayer::GetFeature(nFeatureId);
823 : }
824 :
825 0 : OGRFeature *poFeature = BuildFeature(poRowObj);
826 0 : json_object_put(poObj);
827 :
828 0 : return poFeature;
829 : }
830 0 : return nullptr;
831 : }
832 :
833 : /************************************************************************/
834 : /* GetFeatureCount() */
835 : /************************************************************************/
836 :
837 0 : GIntBig OGRAmigoCloudTableLayer::GetFeatureCount(int bForce)
838 : {
839 :
840 0 : if (bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE)
841 0 : return 0;
842 0 : FlushDeferredInsert();
843 :
844 0 : GetLayerDefn();
845 :
846 : CPLString osSQL(
847 : CPLSPrintf("SELECT COUNT(*) FROM %s",
848 0 : OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str()));
849 0 : if (!osWHERE.empty())
850 : {
851 0 : osSQL += " WHERE ";
852 0 : osSQL += osWHERE;
853 : }
854 :
855 0 : json_object *poObj = poDS->RunSQL(osSQL);
856 0 : json_object *poRowObj = OGRAMIGOCLOUDGetSingleRow(poObj);
857 0 : if (poRowObj == nullptr)
858 : {
859 0 : if (poObj != nullptr)
860 0 : json_object_put(poObj);
861 0 : return OGRAmigoCloudLayer::GetFeatureCount(bForce);
862 : }
863 :
864 0 : json_object *poCount = CPL_json_object_object_get(poRowObj, "count");
865 0 : if (poCount == nullptr || json_object_get_type(poCount) != json_type_int)
866 : {
867 0 : json_object_put(poObj);
868 0 : return OGRAmigoCloudLayer::GetFeatureCount(bForce);
869 : }
870 :
871 0 : GIntBig nRet = (GIntBig)json_object_get_int64(poCount);
872 :
873 0 : json_object_put(poObj);
874 :
875 0 : return nRet;
876 : }
877 :
878 : /************************************************************************/
879 : /* IGetExtent() */
880 : /* */
881 : /* For PostGIS use internal Extend(geometry) function */
882 : /* in other cases we use standard OGRLayer::GetExtent() */
883 : /************************************************************************/
884 :
885 0 : OGRErr OGRAmigoCloudTableLayer::IGetExtent(int iGeomField,
886 : OGREnvelope *psExtent, bool bForce)
887 : {
888 0 : CPLString osSQL;
889 :
890 0 : if (bDeferredCreation && RunDeferredCreationIfNecessary() != OGRERR_NONE)
891 0 : return OGRERR_FAILURE;
892 0 : FlushDeferredInsert();
893 :
894 : OGRGeomFieldDefn *poGeomFieldDefn =
895 0 : poFeatureDefn->GetGeomFieldDefn(iGeomField);
896 :
897 : /* Do not take the spatial filter into account */
898 : osSQL.Printf(
899 : "SELECT ST_Extent(%s) FROM %s",
900 0 : OGRAMIGOCLOUDEscapeIdentifier(poGeomFieldDefn->GetNameRef()).c_str(),
901 0 : OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str());
902 :
903 0 : json_object *poObj = poDS->RunSQL(osSQL);
904 0 : json_object *poRowObj = OGRAMIGOCLOUDGetSingleRow(poObj);
905 0 : if (poRowObj != nullptr)
906 : {
907 : json_object *poExtent =
908 0 : CPL_json_object_object_get(poRowObj, "st_extent");
909 0 : if (poExtent != nullptr &&
910 0 : json_object_get_type(poExtent) == json_type_string)
911 : {
912 0 : const char *pszBox = json_object_get_string(poExtent);
913 : const char *ptr, *ptrEndParenthesis;
914 : char szVals[64 * 6 + 6];
915 :
916 0 : ptr = strchr(pszBox, '(');
917 0 : if (ptr)
918 0 : ptr++;
919 0 : if (ptr == nullptr ||
920 0 : (ptrEndParenthesis = strchr(ptr, ')')) == nullptr ||
921 0 : ptrEndParenthesis - ptr > (int)(sizeof(szVals) - 1))
922 : {
923 0 : CPLError(CE_Failure, CPLE_IllegalArg,
924 : "Bad extent representation: '%s'", pszBox);
925 :
926 0 : json_object_put(poObj);
927 0 : return OGRERR_FAILURE;
928 : }
929 :
930 0 : strncpy(szVals, ptr, ptrEndParenthesis - ptr);
931 0 : szVals[ptrEndParenthesis - ptr] = '\0';
932 :
933 : char **papszTokens =
934 0 : CSLTokenizeString2(szVals, " ,", CSLT_HONOURSTRINGS);
935 0 : int nTokenCnt = 4;
936 :
937 0 : if (CSLCount(papszTokens) != nTokenCnt)
938 : {
939 0 : CPLError(CE_Failure, CPLE_IllegalArg,
940 : "Bad extent representation: '%s'", pszBox);
941 0 : CSLDestroy(papszTokens);
942 :
943 0 : json_object_put(poObj);
944 0 : return OGRERR_FAILURE;
945 : }
946 :
947 : // Take X,Y coords
948 : // For PostGIS ver >= 1.0.0 -> Tokens: X1 Y1 X2 Y2 (nTokenCnt = 4)
949 : // For PostGIS ver < 1.0.0 -> Tokens: X1 Y1 Z1 X2 Y2 Z2 (nTokenCnt =
950 : // 6)
951 : // => X2 index calculated as nTokenCnt/2
952 : // Y2 index calculated as nTokenCnt/2+1
953 :
954 0 : psExtent->MinX = CPLAtof(papszTokens[0]);
955 0 : psExtent->MinY = CPLAtof(papszTokens[1]);
956 0 : psExtent->MaxX = CPLAtof(papszTokens[nTokenCnt / 2]);
957 0 : psExtent->MaxY = CPLAtof(papszTokens[nTokenCnt / 2 + 1]);
958 :
959 0 : CSLDestroy(papszTokens);
960 :
961 0 : json_object_put(poObj);
962 0 : return OGRERR_NONE;
963 : }
964 : }
965 :
966 0 : if (poObj != nullptr)
967 0 : json_object_put(poObj);
968 :
969 0 : return OGRLayer::IGetExtent(iGeomField, psExtent, bForce);
970 : }
971 :
972 : /************************************************************************/
973 : /* TestCapability() */
974 : /************************************************************************/
975 :
976 0 : int OGRAmigoCloudTableLayer::TestCapability(const char *pszCap)
977 :
978 : {
979 0 : if (EQUAL(pszCap, OLCFastFeatureCount))
980 0 : return TRUE;
981 0 : if (EQUAL(pszCap, OLCFastGetExtent))
982 0 : return TRUE;
983 0 : if (EQUAL(pszCap, OLCRandomRead))
984 : {
985 0 : GetLayerDefn();
986 0 : return !osFIDColName.empty();
987 : }
988 :
989 0 : if (EQUAL(pszCap, OLCSequentialWrite) || EQUAL(pszCap, OLCRandomWrite) ||
990 0 : EQUAL(pszCap, OLCDeleteFeature) || EQUAL(pszCap, ODsCCreateLayer) ||
991 0 : EQUAL(pszCap, ODsCDeleteLayer))
992 : {
993 0 : return poDS->IsReadWrite();
994 : }
995 :
996 0 : return OGRAmigoCloudLayer::TestCapability(pszCap);
997 : }
998 :
999 : /************************************************************************/
1000 : /* SetDeferredCreation() */
1001 : /************************************************************************/
1002 :
1003 0 : void OGRAmigoCloudTableLayer::SetDeferredCreation(OGRwkbGeometryType eGType,
1004 : OGRSpatialReference *poSRS,
1005 : int bGeomNullable)
1006 : {
1007 0 : bDeferredCreation = TRUE;
1008 0 : nNextFID = 1;
1009 0 : CPLAssert(poFeatureDefn == nullptr);
1010 0 : poFeatureDefn = new OGRFeatureDefn(osTableName);
1011 0 : poFeatureDefn->Reference();
1012 0 : poFeatureDefn->SetGeomType(wkbNone);
1013 0 : if (eGType == wkbPolygon)
1014 0 : eGType = wkbMultiPolygon;
1015 0 : else if (eGType == wkbPolygon25D)
1016 0 : eGType = wkbMultiPolygon25D;
1017 0 : if (eGType != wkbNone)
1018 : {
1019 : auto poFieldDefn = std::make_unique<OGRAmigoCloudGeomFieldDefn>(
1020 0 : "wkb_geometry", eGType);
1021 0 : poFieldDefn->SetNullable(bGeomNullable);
1022 0 : if (poSRS != nullptr)
1023 : {
1024 0 : poFieldDefn->nSRID = poDS->FetchSRSId(poSRS);
1025 0 : poFieldDefn->SetSpatialRef(poSRS);
1026 : }
1027 0 : poFeatureDefn->AddGeomFieldDefn(std::move(poFieldDefn));
1028 : }
1029 :
1030 : osBaseSQL.Printf("SELECT * FROM %s",
1031 0 : OGRAMIGOCLOUDEscapeIdentifier(osTableName).c_str());
1032 0 : }
1033 :
1034 0 : CPLString OGRAmigoCloudTableLayer::GetAmigoCloudType(const OGRFieldDefn &oField)
1035 : {
1036 : char szFieldType[256];
1037 :
1038 : /* -------------------------------------------------------------------- */
1039 : /* AmigoCloud supported types. */
1040 : /* -------------------------------------------------------------------- */
1041 0 : if (oField.GetType() == OFTInteger)
1042 : {
1043 0 : strcpy(szFieldType, "integer");
1044 : }
1045 0 : else if (oField.GetType() == OFTInteger64)
1046 : {
1047 0 : strcpy(szFieldType, "bigint");
1048 : }
1049 0 : else if (oField.GetType() == OFTReal)
1050 : {
1051 0 : strcpy(szFieldType, "float");
1052 : }
1053 0 : else if (oField.GetType() == OFTString)
1054 : {
1055 0 : strcpy(szFieldType, "string");
1056 : }
1057 0 : else if (oField.GetType() == OFTDate)
1058 : {
1059 0 : strcpy(szFieldType, "date");
1060 : }
1061 0 : else if (oField.GetType() == OFTTime)
1062 : {
1063 0 : strcpy(szFieldType, "time");
1064 : }
1065 0 : else if (oField.GetType() == OFTDateTime)
1066 : {
1067 0 : strcpy(szFieldType, "datetime");
1068 : }
1069 : else
1070 : {
1071 0 : CPLError(CE_Failure, CPLE_NotSupported,
1072 : "Can't create field %s with type %s on PostgreSQL layers.",
1073 : oField.GetNameRef(),
1074 : OGRFieldDefn::GetFieldTypeName(oField.GetType()));
1075 0 : strcpy(szFieldType, "");
1076 : }
1077 :
1078 0 : return szFieldType;
1079 : }
1080 :
1081 0 : bool OGRAmigoCloudTableLayer::IsDatasetExists()
1082 : {
1083 0 : std::stringstream url;
1084 0 : url << std::string(poDS->GetAPIURL())
1085 0 : << "/users/0/projects/" + std::string(poDS->GetProjectId()) +
1086 0 : "/datasets/" + osDatasetId;
1087 0 : json_object *result = poDS->RunGET(url.str().c_str());
1088 0 : if (result == nullptr)
1089 0 : return false;
1090 :
1091 : {
1092 0 : int type = json_object_get_type(result);
1093 0 : if (type == json_type_object)
1094 : {
1095 0 : json_object *poId = CPL_json_object_object_get(result, "id");
1096 0 : if (poId != nullptr)
1097 : {
1098 0 : json_object_put(result);
1099 0 : return true;
1100 : }
1101 : }
1102 0 : json_object_put(result);
1103 : }
1104 :
1105 : // Sleep 3 sec
1106 0 : CPLSleep(3);
1107 :
1108 0 : return false;
1109 : }
1110 :
1111 : /************************************************************************/
1112 : /* RunDeferredCreationIfNecessary() */
1113 : /************************************************************************/
1114 :
1115 0 : OGRErr OGRAmigoCloudTableLayer::RunDeferredCreationIfNecessary()
1116 : {
1117 0 : if (!bDeferredCreation)
1118 0 : return OGRERR_NONE;
1119 0 : bDeferredCreation = FALSE;
1120 0 : std::stringstream json;
1121 0 : json << "{ \"name\":\"" << osDatasetId << "\",";
1122 0 : json << "\"schema\": \"[";
1123 0 : int counter = 0;
1124 0 : OGRwkbGeometryType eGType = GetGeomType();
1125 0 : if (eGType != wkbNone)
1126 : {
1127 0 : CPLString osGeomType = OGRToOGCGeomType(eGType);
1128 0 : if (wkbHasZ(eGType))
1129 0 : osGeomType += "Z";
1130 :
1131 : OGRAmigoCloudGeomFieldDefn *poFieldDefn =
1132 0 : (OGRAmigoCloudGeomFieldDefn *)poFeatureDefn->GetGeomFieldDefn(0);
1133 :
1134 0 : json << "{\\\"name\\\":\\\"" << poFieldDefn->GetNameRef() << "\\\",";
1135 0 : json << "\\\"type\\\":\\\"geometry\\\",";
1136 0 : json << "\\\"geometry_type\\\":\\\"" << osGeomType << "\\\",";
1137 :
1138 0 : if (!poFieldDefn->IsNullable())
1139 0 : json << "\\\"nullable\\\":false,";
1140 : else
1141 0 : json << "\\\"nullable\\\":true,";
1142 :
1143 0 : json << "\\\"visible\\\": true}";
1144 :
1145 0 : counter++;
1146 : }
1147 :
1148 0 : for (int i = 0; i < poFeatureDefn->GetFieldCount(); i++)
1149 : {
1150 0 : OGRFieldDefn *poFieldDefn = poFeatureDefn->GetFieldDefn(i);
1151 0 : if (strcmp(poFieldDefn->GetNameRef(), osFIDColName) != 0)
1152 : {
1153 0 : if (counter > 0)
1154 0 : json << ",";
1155 :
1156 : json << "{\\\"name\\\":\\\"" << poFieldDefn->GetNameRef()
1157 0 : << "\\\",";
1158 0 : json << "\\\"type\\\":\\\"" << GetAmigoCloudType(*poFieldDefn)
1159 0 : << "\\\",";
1160 0 : if (!poFieldDefn->IsNullable())
1161 0 : json << "\\\"nullable\\\":false,";
1162 : else
1163 0 : json << "\\\"nullable\\\":true,";
1164 :
1165 0 : if (poFieldDefn->GetDefault() != nullptr &&
1166 0 : !poFieldDefn->IsDefaultDriverSpecific())
1167 : {
1168 : json << "\\\"default\\\":\\\"" << poFieldDefn->GetDefault()
1169 0 : << "\\\",";
1170 : }
1171 0 : json << "\\\"visible\\\": true}";
1172 0 : counter++;
1173 : }
1174 : }
1175 :
1176 0 : json << " ] \" }";
1177 :
1178 0 : std::stringstream url;
1179 0 : url << std::string(poDS->GetAPIURL())
1180 0 : << "/users/0/projects/" + std::string(poDS->GetProjectId()) +
1181 0 : "/datasets/create";
1182 :
1183 0 : json_object *result = poDS->RunPOST(url.str().c_str(), json.str().c_str());
1184 0 : if (result != nullptr)
1185 : {
1186 0 : if (json_object_get_type(result) == json_type_object)
1187 : {
1188 0 : json_object *poName = CPL_json_object_object_get(result, "name");
1189 0 : if (poName != nullptr)
1190 : {
1191 0 : osName = json_object_to_json_string(poName);
1192 : }
1193 :
1194 0 : json_object *poId = CPL_json_object_object_get(result, "id");
1195 0 : if (poId != nullptr)
1196 : {
1197 : osTableName =
1198 0 : CPLString("dataset_") + json_object_to_json_string(poId);
1199 0 : osDatasetId = json_object_to_json_string(poId);
1200 0 : int retry = 10;
1201 0 : while (!IsDatasetExists() && retry >= 0)
1202 : {
1203 0 : retry--;
1204 : }
1205 0 : json_object_put(result);
1206 0 : return OGRERR_NONE;
1207 : }
1208 : }
1209 : }
1210 0 : return OGRERR_FAILURE;
1211 : }
|