Debian Codegraph @

ogr/ogrsf_frmts/oci/ogrocidatasource.cpp

raw
1 /******************************************************************************
2 *
3 * Project: Oracle Spatial Driver
4 * Purpose: Implementation of the OGROCIDataSource class.
5 * Author: Frank Warmerdam, [email protected]
6 *
7 ******************************************************************************
8 * Copyright (c) 2002, Frank Warmerdam <[email protected]>
9 *
10 * SPDX-License-Identifier: MIT
11 ****************************************************************************/
12
13 #include "ogr_oci.h"
14 #include "cpl_conv.h"
15 #include "cpl_string.h"
16
17 constexpr int anEPSGOracleMapping[] = {
18 /* Oracle SRID, EPSG GCS/PCS Code */
19
20 8192, 4326, // WGS84
21 8306, 4322, // WGS72
22 8267, 4269, // NAD83
23 8274,
24 4277, // OSGB 36
25 // NAD27 isn't easily mapped since there are many Oracle NAD27 codes.
26
27 81989, 27700, // UK National Grid
28
29 0, 0 // end marker
30 };
31
32 /************************************************************************/
33 /* OGROCIDataSource() */
34 /************************************************************************/
35
36 OGROCIDataSource::OGROCIDataSource()
37
38 {
39 pszDBName = nullptr;
40 papoLayers = nullptr;
41 nLayers = 0;
42 bDSUpdate = FALSE;
43 bNoLogging = FALSE;
44 poSession = nullptr;
45 }
46
47 /************************************************************************/
48 /* ~OGROCIDataSource() */
49 /************************************************************************/
50
51 OGROCIDataSource::~OGROCIDataSource()
52
53 {
54 int i;
55
56 CPLFree(pszDBName);
57
58 for (i = 0; i < nLayers; i++)
59 delete papoLayers[i];
60
61 CPLFree(papoLayers);
62
63 if (poSession != nullptr)
64 delete poSession;
65 }
66
67 /************************************************************************/
68 /* Open() */
69 /************************************************************************/
70
71 int OGROCIDataSource::Open(const char *pszNewName, char **papszOpenOptionsIn,
72 int bUpdate, int bTestOpen)
73
74 {
75 CPLAssert(nLayers == 0 && poSession == nullptr);
76
77 /* -------------------------------------------------------------------- */
78 /* Verify Oracle prefix. */
79 /* -------------------------------------------------------------------- */
80 if (!STARTS_WITH_CI(pszNewName, "OCI:"))
81 {
82 if (!bTestOpen)
83 {
84 CPLError(
85 CE_Failure, CPLE_AppDefined,
86 "%s does not conform to Oracle OCI driver naming convention,"
87 " OCI:*\n",
88 pszNewName);
89 }
90 return FALSE;
91 }
92
93 /* -------------------------------------------------------------------- */
94 /* Try to parse out name, password and database name. */
95 /* -------------------------------------------------------------------- */
96 char *pszUserid;
97 const char *pszPassword = "";
98 const char *pszDatabase = "";
99 char **papszTableList = nullptr;
100 const char *pszWorkspace = "";
101
102 int i;
103
104 if (pszNewName[4] == '\0')
105 {
106 pszUserid =
107 CPLStrdup(CSLFetchNameValueDef(papszOpenOptionsIn, "USER", ""));
108 pszPassword = CSLFetchNameValueDef(papszOpenOptionsIn, "PASSWORD", "");
109 pszDatabase = CSLFetchNameValueDef(papszOpenOptionsIn, "DBNAME", "");
110 const char *pszTables = CSLFetchNameValue(papszOpenOptionsIn, "TABLES");
111 if (pszTables)
112 papszTableList =
113 CSLTokenizeStringComplex(pszTables, ",", TRUE, FALSE);
114 pszWorkspace =
115 CSLFetchNameValueDef(papszOpenOptionsIn, "WORKSPACE", "");
116 }
117 else
118 {
119 pszUserid = CPLStrdup(pszNewName + 4);
120
121 // Is there a table list?
122 for (i = static_cast<int>(strlen(pszUserid)) - 1; i > 1; i--)
123 {
124 if (pszUserid[i] == ':')
125 {
126 papszTableList = CSLTokenizeStringComplex(pszUserid + i + 1,
127 ",", TRUE, FALSE);
128 pszUserid[i] = '\0';
129 break;
130 }
131
132 if (pszUserid[i] == '/' || pszUserid[i] == '@')
133 break;
134 }
135
136 for (i = 0;
137 pszUserid[i] != '\0' && pszUserid[i] != '/' && pszUserid[i] != '@';
138 i++)
139 {
140 }
141
142 if (pszUserid[i] == '/')
143 {
144 pszUserid[i++] = '\0';
145 pszPassword = pszUserid + i;
146 for (; pszUserid[i] != '\0' && pszUserid[i] != '@'; i++)
147 {
148 }
149 }
150
151 if (pszUserid[i] == '@')
152 {
153 pszUserid[i++] = '\0';
154 pszDatabase = pszUserid + i;
155 }
156 }
157
158 /* -------------------------------------------------------------------- */
159 /* Try to establish connection. */
160 /* -------------------------------------------------------------------- */
161
162 poSession = OGRGetOCISession(pszUserid, pszPassword, pszDatabase);
163
164 if (poSession == nullptr)
165 {
166 CPLFree(pszUserid);
167 CSLDestroy(papszTableList);
168 return FALSE;
169 }
170
171 if (!EQUAL(pszWorkspace, ""))
172 {
173 OGROCIStringBuf oValidateCmd;
174 OGROCIStatement oValidateStmt(GetSession());
175
176 oValidateCmd.Append("call DBMS_WM.GotoWorkspace('");
177 oValidateCmd.Append(pszWorkspace);
178 oValidateCmd.Append("')");
179
180 oValidateStmt.Execute(oValidateCmd.GetString());
181 }
182
183 bDSUpdate = bUpdate;
184
185 /* -------------------------------------------------------------------- */
186 /* If no list of target tables was provided, collect a list of */
187 /* spatial tables now. */
188 /* -------------------------------------------------------------------- */
189 if (papszTableList == nullptr)
190 {
191 OGROCIStatement oGetTables(poSession);
192
193 if (oGetTables.Execute(
194 "SELECT TABLE_NAME, OWNER FROM ALL_SDO_GEOM_METADATA") ==
195 CE_None)
196 {
197 char **papszRow;
198
199 while ((papszRow = oGetTables.SimpleFetchRow()) != nullptr)
200 {
201 char szFullTableName[100];
202
203 if (EQUAL(papszRow[1], pszUserid))
204 strcpy(szFullTableName, papszRow[0]);
205 else
206 snprintf(szFullTableName, sizeof(szFullTableName), "%s.%s",
207 papszRow[1], papszRow[0]);
208
209 if (CSLFindString(papszTableList, szFullTableName) == -1)
210 papszTableList =
211 CSLAddString(papszTableList, szFullTableName);
212 }
213 }
214 }
215 CPLFree(pszUserid);
216
217 /* -------------------------------------------------------------------- */
218 /* Open all the selected tables or views. */
219 /* -------------------------------------------------------------------- */
220 for (i = 0; papszTableList != nullptr && papszTableList[i] != nullptr; i++)
221 {
222 OpenTable(papszTableList[i], -1, bUpdate, FALSE, papszOpenOptionsIn);
223 }
224
225 CSLDestroy(papszTableList);
226
227 return TRUE;
228 }
229
230 /************************************************************************/
231 /* OpenTable() */
232 /************************************************************************/
233
234 int OGROCIDataSource::OpenTable(const char *pszNewName, int nSRID, int bUpdate,
235 CPL_UNUSED int bTestOpen,
236 char **papszOpenOptionsIn)
237
238 {
239 /* -------------------------------------------------------------------- */
240 /* Create the layer object. */
241 /* -------------------------------------------------------------------- */
242 OGROCITableLayer *poLayer;
243
244 poLayer = new OGROCITableLayer(this, pszNewName, wkbUnknown, nSRID, bUpdate,
245 FALSE);
246
247 if (!poLayer->IsValid())
248 {
249 delete poLayer;
250 return FALSE;
251 }
252
253 /* -------------------------------------------------------------------- */
254 /* Add layer to data source layer list. */
255 /* -------------------------------------------------------------------- */
256 papoLayers = (OGROCILayer **)CPLRealloc(papoLayers, sizeof(OGROCILayer *) *
257 (nLayers + 1));
258 papoLayers[nLayers++] = poLayer;
259
260 poLayer->SetOptions(papszOpenOptionsIn);
261
262 return TRUE;
263 }
264
265 /************************************************************************/
266 /* ValidateLayer() */
267 /************************************************************************/
268
269 void OGROCIDataSource::ValidateLayer(const char *pszLayerName)
270
271 {
272 int iLayer;
273
274 /* -------------------------------------------------------------------- */
275 /* Try to find layer. */
276 /* -------------------------------------------------------------------- */
277 for (iLayer = 0; iLayer < nLayers; iLayer++)
278 {
279 if (EQUAL(pszLayerName, papoLayers[iLayer]->GetLayerDefn()->GetName()))
280 break;
281 }
282
283 if (iLayer == nLayers)
284 {
285 CPLError(CE_Failure, CPLE_AppDefined,
286 "ValidateLayer(): %s is not a recognised layer.",
287 pszLayerName);
288 return;
289 }
290
291 /* -------------------------------------------------------------------- */
292 /* Verify we have an FID and geometry column for this table. */
293 /* -------------------------------------------------------------------- */
294 OGROCITableLayer *poLayer =
295 cpl::down_cast<OGROCITableLayer *>(papoLayers[iLayer]);
296
297 if (strlen(poLayer->GetFIDColumn()) == 0)
298 {
299 CPLError(CE_Failure, CPLE_AppDefined,
300 "ValidateLayer(): %s lacks a fid column.", pszLayerName);
301
302 return;
303 }
304
305 /* -------------------------------------------------------------------- */
306 /* Prepare and execute the geometry validation. */
307 /* -------------------------------------------------------------------- */
308
309 if (strlen(poLayer->GetGeometryColumn()) != 0)
310 {
311 OGROCIStringBuf oValidateCmd;
312 OGROCIStatement oValidateStmt(GetSession());
313
314 oValidateCmd.Append("SELECT c.");
315 oValidateCmd.Append(poLayer->GetFIDColumn());
316 oValidateCmd.Append(", SDO_GEOM.VALIDATE_GEOMETRY(c.");
317 oValidateCmd.Append(poLayer->GetGeometryColumn());
318 oValidateCmd.Append(", m.diminfo) from ");
319 oValidateCmd.Append(poLayer->GetLayerDefn()->GetName());
320 oValidateCmd.Append(
321 " c, user_sdo_geom_metadata m WHERE m.table_name= '");
322 oValidateCmd.Append(poLayer->GetLayerDefn()->GetName());
323 oValidateCmd.Append("' AND m.column_name = '");
324 oValidateCmd.Append(poLayer->GetGeometryColumn());
325 oValidateCmd.Append("' AND SDO_GEOM.VALIDATE_GEOMETRY(c.");
326 oValidateCmd.Append(poLayer->GetGeometryColumn());
327 oValidateCmd.Append(", m.diminfo ) <> 'TRUE'");
328
329 oValidateStmt.Execute(oValidateCmd.GetString());
330
331 /* --------------------------------------------------------------------
332 */
333 /* Report results to debug stream. */
334 /* --------------------------------------------------------------------
335 */
336 char **papszRow;
337
338 while ((papszRow = oValidateStmt.SimpleFetchRow()) != nullptr)
339 {
340 const char *pszReason = papszRow[1];
341
342 if (EQUAL(pszReason, "13011"))
343 pszReason = "13011: value is out of range";
344 else if (EQUAL(pszReason, "13050"))
345 pszReason = "13050: unable to construct spatial object";
346 else if (EQUAL(pszReason, "13349"))
347 pszReason = "13349: polygon boundary crosses itself";
348
349 CPLDebug("OCI", "Validation failure for FID=%s: %s", papszRow[0],
350 pszReason);
351 }
352 }
353 }
354
355 /************************************************************************/
356 /* DeleteLayer(int) */
357 /************************************************************************/
358
359 OGRErr OGROCIDataSource::DeleteLayer(int iLayer)
360
361 {
362 /* -------------------------------------------------------------------- */
363 /* Blow away our OGR structures related to the layer. This is */
364 /* pretty dangerous if anything has a reference to this layer! */
365 /* -------------------------------------------------------------------- */
366 CPLString osLayerName = papoLayers[iLayer]->GetLayerDefn()->GetName();
367
368 CPLDebug("OCI", "DeleteLayer(%s)", osLayerName.c_str());
369
370 delete papoLayers[iLayer];
371 memmove(papoLayers + iLayer, papoLayers + iLayer + 1,
372 sizeof(void *) * (nLayers - iLayer - 1));
373 nLayers--;
374
375 /* -------------------------------------------------------------------- */
376 /* Remove from the database. */
377 /* -------------------------------------------------------------------- */
378 OGROCIStatement oCommand(poSession);
379 CPLString osCommand;
380 int nFailures = 0;
381
382 osCommand.Printf("DROP TABLE \"%s\"", osLayerName.c_str());
383 if (oCommand.Execute(osCommand) != CE_None)
384 nFailures++;
385
386 osCommand.Printf(
387 "DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = UPPER('%s')",
388 osLayerName.c_str());
389
390 if (oCommand.Execute(osCommand) != CE_None)
391 nFailures++;
392
393 if (nFailures == 0)
394 return OGRERR_NONE;
395 else
396 return OGRERR_FAILURE;
397 }
398
399 /************************************************************************/
400 /* DeleteLayer(const char *) */
401 /************************************************************************/
402
403 void OGROCIDataSource::DeleteLayer(const char *pszLayerName)
404
405 {
406 int iLayer;
407
408 /* -------------------------------------------------------------------- */
409 /* Try to find layer. */
410 /* -------------------------------------------------------------------- */
411 for (iLayer = 0; iLayer < nLayers; iLayer++)
412 {
413 if (EQUAL(pszLayerName, papoLayers[iLayer]->GetLayerDefn()->GetName()))
414 {
415 break;
416 }
417 }
418
419 if (iLayer == nLayers)
420 {
421 CPLDebug("OCI",
422 "DeleteLayer: %s not found in layer list."
423 " Layer *not* deleted.",
424 pszLayerName);
425 return;
426 }
427
428 DeleteLayer(iLayer);
429 }
430
431 /************************************************************************/
432 /* TruncateLayer() */
433 /************************************************************************/
434
435 void OGROCIDataSource::TruncateLayer(const char *pszLayerName)
436
437 {
438
439 /* -------------------------------------------------------------------- */
440 /* Set OGR Debug statement explaining what is happening */
441 /* -------------------------------------------------------------------- */
442 CPLDebug("OCI", "Truncate TABLE %s", pszLayerName);
443
444 /* -------------------------------------------------------------------- */
445 /* Truncate the layer in the database. */
446 /* -------------------------------------------------------------------- */
447 OGROCIStatement oCommand(poSession);
448 CPLString osCommand;
449
450 osCommand.Printf("TRUNCATE TABLE \"%s\"", pszLayerName);
451 oCommand.Execute(osCommand);
452 }
453
454 /************************************************************************/
455 /* ICreateLayer() */
456 /************************************************************************/
457
458 OGRLayer *
459 OGROCIDataSource::ICreateLayer(const char *pszLayerName,
460 const OGRGeomFieldDefn *poGeomFieldDefn,
461 CSLConstList papszOptions)
462
463 {
464 const auto eType = poGeomFieldDefn ? poGeomFieldDefn->GetType() : wkbNone;
465 const auto poSRS =
466 poGeomFieldDefn ? poGeomFieldDefn->GetSpatialRef() : nullptr;
467
468 char *pszSafeLayerName = CPLStrdup(pszLayerName);
469
470 poSession->CleanName(pszSafeLayerName);
471 CPLDebug("OCI", "In Create Layer ...");
472
473 bNoLogging = CPLFetchBool(papszOptions, "NO_LOGGING", false);
474
475 /* -------------------------------------------------------------------- */
476 /* Get the default string size */
477 /* -------------------------------------------------------------------- */
478
479 int nDefaultStringSize = DEFAULT_STRING_SIZE;
480
481 if (CSLFetchNameValue(papszOptions, "DEFAULT_STRING_SIZE") != nullptr)
482 {
483 nDefaultStringSize =
484 atoi(CSLFetchNameValue(papszOptions, "DEFAULT_STRING_SIZE"));
485 }
486
487 /* -------------------------------------------------------------------- */
488 /* Do we already have this layer? If so, should we blow it */
489 /* away? */
490 /* -------------------------------------------------------------------- */
491 int iLayer;
492 bool bIsNewLayer = TRUE;
493
494 if (CPLFetchBool(papszOptions, "TRUNCATE", false))
495 {
496 CPLDebug("OCI", "Calling TruncateLayer for %s", pszLayerName);
497 TruncateLayer(pszSafeLayerName);
498 bIsNewLayer = false; // Oracle table already exists
499 }
500 else
501 {
502 for (iLayer = 0; iLayer < nLayers; iLayer++)
503 {
504 if (EQUAL(pszSafeLayerName,
505 papoLayers[iLayer]->GetLayerDefn()->GetName()))
506 {
507 if (CSLFetchNameValue(papszOptions, "OVERWRITE") != nullptr &&
508 !EQUAL(CSLFetchNameValue(papszOptions, "OVERWRITE"), "NO"))
509 {
510 DeleteLayer(pszSafeLayerName);
511 }
512 else
513 {
514 CPLError(CE_Failure, CPLE_AppDefined,
515 "Layer %s already exists, CreateLayer failed.\n"
516 "Use the layer creation option OVERWRITE=YES to "
517 "replace it.",
518 pszSafeLayerName);
519 CPLFree(pszSafeLayerName);
520 return nullptr;
521 }
522 }
523 }
524 }
525
526 /* -------------------------------------------------------------------- */
527 /* Try to get the SRS Id of this spatial reference system, */
528 /* adding tot the srs table if needed. */
529 /* -------------------------------------------------------------------- */
530 char szSRSId[100];
531
532 const char *pszSRID = CSLFetchNameValue(papszOptions, "SRID");
533 if (pszSRID != nullptr)
534 snprintf(szSRSId, sizeof(szSRSId), "%s", pszSRID);
535 else if (poSRS != nullptr)
536 snprintf(szSRSId, sizeof(szSRSId), "%d", FetchSRSId(poSRS));
537 else
538 strcpy(szSRSId, "NULL");
539
540 /* -------------------------------------------------------------------- */
541 /* Determine name of geometry column to use. */
542 /* -------------------------------------------------------------------- */
543 const char *pszGeometryName =
544 CSLFetchNameValue(papszOptions, "GEOMETRY_NAME");
545 if (pszGeometryName == nullptr)
546 pszGeometryName = "ORA_GEOMETRY";
547 const bool bGeomNullable =
548 CPLFetchBool(papszOptions, "GEOMETRY_NULLABLE", true);
549
550 /* -------------------------------------------------------------------- */
551 /* Create a basic table with the FID. Also include the */
552 /* geometry if this is not a PostGIS enabled table. */
553 /* -------------------------------------------------------------------- */
554 const char *pszExpectedFIDName = CPLGetConfigOption("OCI_FID", "OGR_FID");
555
556 OGROCIStatement oStatement(poSession);
557
558 /* -------------------------------------------------------------------- */
559 /* If geometry type is wkbNone, do not create a geometry column. */
560 /* -------------------------------------------------------------------- */
561
562 CPLString osCommand;
563 if (CSLFetchNameValue(papszOptions, "TRUNCATE") == nullptr)
564 {
565 if (eType == wkbNone)
566 {
567 osCommand.Printf("CREATE TABLE \"%s\" ( "
568 "%s INTEGER PRIMARY KEY)",
569 pszSafeLayerName, pszExpectedFIDName);
570 }
571 else
572 {
573 osCommand.Printf("CREATE TABLE \"%s\" ( "
574 "%s INTEGER PRIMARY KEY, "
575 "%s %s%s )",
576 pszSafeLayerName, pszExpectedFIDName,
577 pszGeometryName, SDO_GEOMETRY,
578 (!bGeomNullable) ? " NOT NULL" : "");
579 }
580
581 if (bNoLogging)
582 {
583 osCommand += CPLSPrintf(" NOLOGGING "
584 "VARRAY %s.SDO_ELEM_INFO STORE AS "
585 "SECUREFILE LOB (NOCACHE NOLOGGING) "
586 "VARRAY %s.SDO_ORDINATES STORE AS "
587 "SECUREFILE LOB (NOCACHE NOLOGGING) ",
588 pszGeometryName, pszGeometryName);
589 }
590
591 if (oStatement.Execute(osCommand) != CE_None)
592 {
593 CPLFree(pszSafeLayerName);
594 return nullptr;
595 }
596 }
597
598 /* -------------------------------------------------------------------- */
599 /* Create the layer object. */
600 /* -------------------------------------------------------------------- */
601 const char *pszLoaderFile = CSLFetchNameValue(papszOptions, "LOADER_FILE");
602 OGROCIWritableLayer *poLayer;
603
604 if (pszLoaderFile == nullptr)
605 poLayer = new OGROCITableLayer(
606 this, pszSafeLayerName, eType,
607 EQUAL(szSRSId, "NULL") ? -1 : atoi(szSRSId), TRUE, bIsNewLayer);
608 else
609 poLayer = new OGROCILoaderLayer(
610 this, pszSafeLayerName, pszGeometryName,
611 EQUAL(szSRSId, "NULL") ? -1 : atoi(szSRSId), pszLoaderFile);
612
613 /* -------------------------------------------------------------------- */
614 /* Set various options on the layer. */
615 /* -------------------------------------------------------------------- */
616 poLayer->SetLaunderFlag(CPLFetchBool(papszOptions, "LAUNDER", false));
617 poLayer->SetPrecisionFlag(CPLFetchBool(papszOptions, "PRECISION", true));
618 poLayer->SetDefaultStringSize(nDefaultStringSize);
619
620 const char *pszDIM = CSLFetchNameValue(papszOptions, "DIM");
621 if (pszDIM != nullptr)
622 poLayer->SetDimension(atoi(pszDIM));
623 else if (eType != wkbNone)
624 poLayer->SetDimension((wkbFlatten(eType) == eType) ? 2 : 3);
625
626 poLayer->SetOptions(papszOptions);
627 if (eType != wkbNone && !bGeomNullable)
628 poLayer->GetLayerDefn()->GetGeomFieldDefn(0)->SetNullable(FALSE);
629
630 /* -------------------------------------------------------------------- */
631 /* Add layer to data source layer list. */
632 /* -------------------------------------------------------------------- */
633 papoLayers = (OGROCILayer **)CPLRealloc(papoLayers, sizeof(OGROCILayer *) *
634 (nLayers + 1));
635
636 papoLayers[nLayers++] = poLayer;
637
638 CPLFree(pszSafeLayerName);
639
640 return poLayer;
641 }
642
643 /************************************************************************/
644 /* TestCapability() */
645 /************************************************************************/
646
647 int OGROCIDataSource::TestCapability(const char *pszCap) const
648
649 {
650 if (EQUAL(pszCap, ODsCCreateLayer) && bDSUpdate)
651 return TRUE;
652 else if (EQUAL(pszCap, ODsCDeleteLayer) && bDSUpdate)
653 return TRUE;
654 else if (EQUAL(pszCap, ODsCRandomLayerWrite))
655 return bDSUpdate;
656 else if (EQUAL(pszCap, ODsCZGeometries))
657 return TRUE;
658 else
659 return FALSE;
660 }
661
662 /************************************************************************/
663 /* GetLayer() */
664 /************************************************************************/
665
666 const OGRLayer *OGROCIDataSource::GetLayer(int iLayer) const
667
668 {
669 if (iLayer < 0 || iLayer >= nLayers)
670 return nullptr;
671 else
672 return papoLayers[iLayer];
673 }
674
675 /************************************************************************/
676 /* ExecuteSQL() */
677 /************************************************************************/
678
679 OGRLayer *OGROCIDataSource::ExecuteSQL(const char *pszSQLCommand,
680 OGRGeometry *poSpatialFilter,
681 const char *pszDialect)
682
683 {
684 /* -------------------------------------------------------------------- */
685 /* Use generic implementation for recognized dialects */
686 /* -------------------------------------------------------------------- */
687 if (IsGenericSQLDialect(pszDialect))
688 return GDALDataset::ExecuteSQL(pszSQLCommand, poSpatialFilter,
689 pszDialect);
690
691 /* -------------------------------------------------------------------- */
692 /* Ensure any pending stuff is flushed to the database. */
693 /* -------------------------------------------------------------------- */
694 FlushCache();
695
696 CPLDebug("OCI", "ExecuteSQL(%s)", pszSQLCommand);
697
698 /* -------------------------------------------------------------------- */
699 /* Special case DELLAYER: command. */
700 /* -------------------------------------------------------------------- */
701 if (STARTS_WITH_CI(pszSQLCommand, "DELLAYER:"))
702 {
703 const char *pszLayerName = pszSQLCommand + 9;
704
705 while (*pszLayerName == ' ')
706 pszLayerName++;
707
708 DeleteLayer(pszLayerName);
709 return nullptr;
710 }
711
712 /* -------------------------------------------------------------------- */
713 /* Special case VALLAYER: command. */
714 /* -------------------------------------------------------------------- */
715 if (STARTS_WITH_CI(pszSQLCommand, "VALLAYER:"))
716 {
717 const char *pszLayerName = pszSQLCommand + 9;
718
719 while (*pszLayerName == ' ')
720 pszLayerName++;
721
722 ValidateLayer(pszLayerName);
723 return nullptr;
724 }
725
726 /* -------------------------------------------------------------------- */
727 /* Just execute simple command. */
728 /* -------------------------------------------------------------------- */
729 if (!STARTS_WITH_CI(pszSQLCommand, "SELECT"))
730 {
731 OGROCIStatement oCommand(poSession);
732
733 oCommand.Execute(pszSQLCommand, OCI_COMMIT_ON_SUCCESS);
734
735 return nullptr;
736 }
737
738 /* -------------------------------------------------------------------- */
739 /* Otherwise instantiate a layer. */
740 /* -------------------------------------------------------------------- */
741 else
742 {
743 OGROCIStatement oCommand(poSession);
744
745 if (oCommand.Execute(pszSQLCommand, OCI_DESCRIBE_ONLY) == CE_None)
746 return new OGROCISelectLayer(this, pszSQLCommand, &oCommand);
747 else
748 return nullptr;
749 }
750 }
751
752 /************************************************************************/
753 /* ReleaseResultSet() */
754 /************************************************************************/
755
756 void OGROCIDataSource::ReleaseResultSet(OGRLayer *poLayer)
757
758 {
759 delete poLayer;
760 }
761
762 /************************************************************************/
763 /* FetchSRS() */
764 /* */
765 /* Return a SRS corresponding to a particular id. Note that */
766 /* reference counting should be honoured on the returned */
767 /* OGRSpatialReference, as handles may be cached. */
768 /************************************************************************/
769
770 OGRSpatialReferenceRefCountedPtr OGROCIDataSource::FetchSRS(int nId)
771
772 {
773 if (nId < 0)
774 return nullptr;
775
776 /* -------------------------------------------------------------------- */
777 /* First, we look through our SRID cache, is it there? */
778 /* -------------------------------------------------------------------- */
779 auto oIter = m_oSRSCache.find(nId);
780 if (oIter != m_oSRSCache.end())
781 {
782 return oIter->second;
783 }
784
785 /* -------------------------------------------------------------------- */
786 /* Try looking up in MDSYS.CS_SRS table. */
787 /* -------------------------------------------------------------------- */
788 OGROCIStatement oStatement(GetSession());
789 char szSelect[200], **papszResult;
790
791 snprintf(szSelect, sizeof(szSelect),
792 "SELECT WKTEXT, AUTH_SRID, AUTH_NAME FROM MDSYS.CS_SRS "
793 "WHERE SRID = %d AND WKTEXT IS NOT NULL",
794 nId);
795
796 if (oStatement.Execute(szSelect) != CE_None)
797 return nullptr;
798
799 papszResult = oStatement.SimpleFetchRow();
800 if (CSLCount(papszResult) < 1)
801 return nullptr;
802
803 /* -------------------------------------------------------------------- */
804 /* Turn into a spatial reference. */
805 /* -------------------------------------------------------------------- */
806 auto poSRS = OGRSpatialReferenceRefCountedPtr::makeInstance();
807 poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
808 if (poSRS->importFromWkt(papszResult[0]) != OGRERR_NONE)
809 {
810 return nullptr;
811 }
812
813 /* -------------------------------------------------------------------- */
814 /* If the WKTEXT definition is equivalent to the EPSG SRS of code */
815 /* nId, return that EPSG SRS. */
816 /* -------------------------------------------------------------------- */
817 constexpr int LARGEST_EPSG_CRS_CODE = 32767;
818 if (nId < LARGEST_EPSG_CRS_CODE && papszResult[1] != nullptr &&
819 atoi(papszResult[1]) == nId)
820 {
821 CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
822 OGRSpatialReference oSRS_EPSG;
823 oSRS_EPSG.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
824 const char *const apszOptions[] = {
825 "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES", nullptr};
826 if (oSRS_EPSG.importFromEPSG(nId) == OGRERR_NONE &&
827 oSRS_EPSG.IsSame(poSRS.get(), apszOptions))
828 {
829 *poSRS = oSRS_EPSG;
830 return poSRS;
831 }
832 }
833
834 /* -------------------------------------------------------------------- */
835 /* If we have a corresponding EPSG code for this SRID, use that */
836 /* authority. */
837 /* -------------------------------------------------------------------- */
838 int bGotEPSGMapping = FALSE;
839 for (int i = 0; anEPSGOracleMapping[i] != 0; i += 2)
840 {
841 if (anEPSGOracleMapping[i] == nId)
842 {
843 poSRS->SetAuthority(poSRS->GetRoot()->GetValue(), "EPSG",
844 anEPSGOracleMapping[i + 1]);
845 bGotEPSGMapping = TRUE;
846 break;
847 }
848 }
849
850 /* -------------------------------------------------------------------- */
851 /* Insert authority information, if it is available. */
852 /* -------------------------------------------------------------------- */
853 if (papszResult[1] != nullptr && atoi(papszResult[1]) != 0 &&
854 papszResult[2] != nullptr && strlen(papszResult[1]) != 0 &&
855 poSRS->GetRoot() != nullptr && !bGotEPSGMapping)
856 {
857 poSRS->SetAuthority(poSRS->GetRoot()->GetValue(), papszResult[2],
858 atoi(papszResult[1]));
859 }
860
861 /* -------------------------------------------------------------------- */
862 /* Add to the cache. */
863 /* -------------------------------------------------------------------- */
864 oIter = m_oSRSCache.emplace(nId, std::move(poSRS)).first;
865 return oIter->second;
866 }
867
868 /************************************************************************/
869 /* FetchSRSId() */
870 /* */
871 /* Fetch the id corresponding to an SRS, and if not found, add */
872 /* it to the table. */
873 /************************************************************************/
874
875 int OGROCIDataSource::FetchSRSId(const OGRSpatialReference *poSRS)
876
877 {
878 char *pszWKT = nullptr;
879 int nSRSId;
880
881 if (poSRS == nullptr)
882 return -1;
883
884 if (!poSRS->IsProjected() && !poSRS->IsGeographic())
885 return -1;
886
887 /* ==================================================================== */
888 /* The first strategy is to see if we can identify it by */
889 /* authority information within the SRS. */
890 /* ==================================================================== */
891 const char *pszAuthName = nullptr, *pszAuthCode = nullptr;
892
893 if (poSRS->IsGeographic() || poSRS->IsProjected())
894 {
895 pszAuthName = poSRS->GetAuthorityName();
896 pszAuthCode = poSRS->GetAuthorityCode();
897 }
898
899 OGROCIStatement oCmdStatement(GetSession());
900
901 if (pszAuthName != nullptr && pszAuthCode != nullptr)
902 {
903 // If the authority is Oracle, use the code as the SRID
904 if (EQUAL(pszAuthName, "Oracle") && atoi(pszAuthCode) != 0)
905 return atoi(pszAuthCode);
906
907 // If the authority is EPSG, try to retrieve the record of CS_SRS
908 // whose SRID is the EPSG code. And if the WKT definition from the
909 // CS_SRS record is equivalent to the one of poSRS, use the EPSG code
910 // as the SRID. This works for a number of EPSG CRS (4326, 3857, etc.)
911 if (EQUAL(pszAuthName, "EPSG"))
912 {
913 const int nEPSGCode = atoi(pszAuthCode);
914 char szSelect[100];
915 snprintf(szSelect, sizeof(szSelect),
916 "SELECT WKTEXT FROM MDSYS.CS_SRS WHERE SRID = %d "
917 "AND WKTEXT IS NOT NULL AND SRID = AUTH_SRID",
918 nEPSGCode);
919 if (oCmdStatement.Execute(szSelect) == CE_None)
920 {
921 CSLConstList papszResult = oCmdStatement.SimpleFetchRow();
922 if (papszResult != nullptr && papszResult[0] != nullptr &&
923 papszResult[1] == nullptr)
924 {
925 OGRSpatialReference oSRS;
926 const char *const apszOptions[] = {
927 "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES", nullptr};
928 if (oSRS.importFromWkt(papszResult[0]) == OGRERR_NONE &&
929 oSRS.IsSame(poSRS, apszOptions))
930 {
931 return nEPSGCode;
932 }
933 }
934 }
935
936 // Otherwise try to fallback to a hard-coded table that maps
937 // EPSG code to Oracle SRID. This is probably somewhat be legacy.
938 for (int i = 0; anEPSGOracleMapping[i] != 0; i += 2)
939 {
940 if (nEPSGCode == anEPSGOracleMapping[i + 1])
941 return anEPSGOracleMapping[i];
942 }
943 }
944 }
945
946 /* ==================================================================== */
947 /* We need to lookup the SRS in the existing Oracle CS_SRS */
948 /* table. */
949 /* ==================================================================== */
950
951 /* -------------------------------------------------------------------- */
952 /* Convert SRS into old style format (SF-SQL 1.0). */
953 /* -------------------------------------------------------------------- */
954 OGRSpatialReference *poSRS2 = poSRS->Clone();
955
956 /* -------------------------------------------------------------------- */
957 /* Convert any degree type unit names to "Decimal Degree". */
958 /* -------------------------------------------------------------------- */
959 double dfAngularUnits = poSRS2->GetAngularUnits(nullptr);
960 if (fabs(dfAngularUnits - 0.0174532925199433) < 0.0000000000000010)
961 poSRS2->SetAngularUnits("Decimal Degree", 0.0174532925199433);
962
963 /* -------------------------------------------------------------------- */
964 /* Translate SRS to WKT. */
965 /* -------------------------------------------------------------------- */
966 const char *const apszOptions[] = {"FORMAT=SFSQL", nullptr};
967 if (poSRS2->exportToWkt(&pszWKT, apszOptions) != OGRERR_NONE)
968 {
969 delete poSRS2;
970 CPLFree(pszWKT);
971 return -1;
972 }
973
974 delete poSRS2;
975
976 /* -------------------------------------------------------------------- */
977 /* Try to find in the existing table. */
978 /* -------------------------------------------------------------------- */
979 OGROCIStringBuf oCmdText;
980 char **papszResult = nullptr;
981
982 oCmdText.Append("SELECT SRID FROM MDSYS.CS_SRS WHERE WKTEXT = '");
983 oCmdText.Append(pszWKT);
984 oCmdText.Append("'");
985
986 if (oCmdStatement.Execute(oCmdText.GetString()) == CE_None)
987 papszResult = oCmdStatement.SimpleFetchRow();
988
989 /* -------------------------------------------------------------------- */
990 /* We got it! Return it. */
991 /* -------------------------------------------------------------------- */
992 if (papszResult != nullptr && papszResult[0] != nullptr &&
993 papszResult[1] == nullptr)
994 {
995 CPLFree(pszWKT);
996 return atoi(papszResult[0]);
997 }
998
999 /* ==================================================================== */
1000 /* We didn't find it, so we need to define it as a new SRID at */
1001 /* the end of the list of known values. */
1002 /* ==================================================================== */
1003
1004 /* -------------------------------------------------------------------- */
1005 /* Get the current maximum srid in the srs table. */
1006 /* -------------------------------------------------------------------- */
1007 if (oCmdStatement.Execute("SELECT MAX(SRID) FROM MDSYS.CS_SRS") == CE_None)
1008 papszResult = oCmdStatement.SimpleFetchRow();
1009 else
1010 papszResult = nullptr;
1011
1012 if (papszResult != nullptr && papszResult[0] != nullptr &&
1013 papszResult[1] == nullptr)
1014 nSRSId = atoi(papszResult[0]) + 1;
1015 else
1016 nSRSId = 1;
1017
1018 /* -------------------------------------------------------------------- */
1019 /* Try adding the SRS to the SRS table. */
1020 /* -------------------------------------------------------------------- */
1021 oCmdText.Clear();
1022 oCmdText.Append("INSERT INTO MDSYS.CS_SRS (SRID, WKTEXT, CS_NAME) ");
1023 oCmdText.Appendf(100, " VALUES (%d,'", nSRSId);
1024 oCmdText.Append(pszWKT);
1025 oCmdText.Append("', '");
1026 oCmdText.Append(poSRS->GetName());
1027 oCmdText.Append("' )");
1028
1029 CPLFree(pszWKT);
1030
1031 if (oCmdStatement.Execute(oCmdText.GetString()) != CE_None)
1032 return -1;
1033 else
1034 return nSRSId;
1035 }
1036
1037 /************************************************************************/
1038 /* GetLayerByName() */
1039 /************************************************************************/
1040
1041 OGRLayer *OGROCIDataSource::GetLayerByName(const char *pszNameIn)
1042
1043 {
1044 OGROCILayer *poLayer = nullptr;
1045 int i, count;
1046
1047 if (!pszNameIn)
1048 return nullptr;
1049
1050 count = GetLayerCount();
1051
1052 /* first a case sensitive check */
1053 for (i = 0; i < count; i++)
1054 {
1055 poLayer = papoLayers[i];
1056
1057 if (strcmp(pszNameIn, poLayer->GetName()) == 0)
1058 {
1059 return poLayer;
1060 }
1061 }
1062
1063 char *pszSafeLayerName = CPLStrdup(pszNameIn);
1064 poSession->CleanName(pszSafeLayerName);
1065
1066 /* then case insensitive and laundered */
1067 for (i = 0; i < count; i++)
1068 {
1069 poLayer = papoLayers[i];
1070
1071 if (EQUAL(pszSafeLayerName, poLayer->GetName()))
1072 {
1073 break;
1074 }
1075 }
1076
1077 CPLFree(pszSafeLayerName);
1078
1079 return i < count ? poLayer : nullptr;
1080 }