Debian Codegraph @

ogr/ogrsf_frmts/filegdb/FGdbLayer.cpp

raw
1 /******************************************************************************
2 *
3 * Project: OpenGIS Simple Features Reference Implementation
4 * Purpose: Implements FileGDB OGR layer.
5 * Author: Ragi Yaser Burhum, [email protected]
6 * Paul Ramsey, pramsey at cleverelephant.ca
7 *
8 ******************************************************************************
9 * Copyright (c) 2010, Ragi Yaser Burhum
10 * Copyright (c) 2011, Paul Ramsey <pramsey at cleverelephant.ca>
11 * Copyright (c) 2011-2014, Even Rouault <even dot rouault at spatialys.com>
12 *
13 * SPDX-License-Identifier: MIT
14 ****************************************************************************/
15
16 #include <cassert>
17 #include <cmath>
18
19 #include "ogr_fgdb.h"
20 #include "ogrpgeogeometry.h"
21 #include "cpl_conv.h"
22 #include "cpl_string.h"
23 #include "FGdbUtils.h"
24 #include "cpl_minixml.h" // the only way right now to extract schema information
25 #include "filegdb_gdbtoogrfieldtype.h"
26 #include "filegdb_fielddomain.h"
27 #include "filegdb_coordprec_read.h"
28
29 // See https://github.com/Esri/file-geodatabase-api/issues/46
30 // On certain FileGDB datasets with binary fields, iterating over a result set
31 // where the binary field is requested crashes in EnumRows::Next() at the
32 // second iteration.
33 // The workaround consists in iterating only over OBJECTID in the main loop,
34 // and requesting each feature in a separate request.
35 #define WORKAROUND_CRASH_ON_CDF_WITH_BINARY_FIELD
36
37 using std::string;
38 using std::wstring;
39
40 /************************************************************************/
41 /* FGdbBaseLayer() */
42 /************************************************************************/
43 FGdbBaseLayer::FGdbBaseLayer()
44 : m_pFeatureDefn(nullptr), m_pSRS(nullptr), m_pEnumRows(nullptr),
45 m_suppressColumnMappingError(false), m_forceMulti(false)
46 {
47 }
48
49 /************************************************************************/
50 /* ~FGdbBaseLayer() */
51 /************************************************************************/
52 FGdbBaseLayer::~FGdbBaseLayer()
53 {
54 if (m_pFeatureDefn)
55 {
56 m_pFeatureDefn->Release();
57 m_pFeatureDefn = nullptr;
58 }
59
60 FGdbBaseLayer::CloseGDBObjects();
61
62 if (m_pSRS)
63 {
64 m_pSRS->Release();
65 m_pSRS = nullptr;
66 }
67 }
68
69 /************************************************************************/
70 /* CloseGDBObjects() */
71 /************************************************************************/
72
73 void FGdbBaseLayer::CloseGDBObjects()
74 {
75 if (m_pEnumRows)
76 {
77 delete m_pEnumRows;
78 m_pEnumRows = nullptr;
79 }
80 }
81
82 /************************************************************************/
83 /* GetNextFeature() */
84 /************************************************************************/
85
86 OGRFeature *FGdbBaseLayer::GetNextFeature()
87 {
88 while (true) // want to skip errors
89 {
90 if (m_pEnumRows == nullptr)
91 return nullptr;
92
93 long hr;
94
95 Row row;
96
97 if (FAILED(hr = m_pEnumRows->Next(row)))
98 {
99 GDBErr(hr, "Failed fetching features");
100 return nullptr;
101 }
102
103 if (hr != S_OK)
104 {
105 // It's OK, we are done fetching - failure is caught by FAILED macro
106 return nullptr;
107 }
108
109 OGRFeature *pOGRFeature = nullptr;
110
111 if (!OGRFeatureFromGdbRow(&row, &pOGRFeature) || !pOGRFeature)
112 {
113 int32 oid = -1;
114 CPL_IGNORE_RET_VAL(row.GetOID(oid));
115
116 GDBErr(hr,
117 CPLSPrintf("Failed translating FGDB row [%d] to OGR Feature",
118 oid));
119
120 // return NULL;
121 continue; // skip feature
122 }
123
124 if ((m_poFilterGeom == nullptr ||
125 FilterGeometry(pOGRFeature->GetGeometryRef())))
126 {
127 return pOGRFeature;
128 }
129 delete pOGRFeature;
130 }
131 }
132
133 /************************************************************************/
134 /* FGdbLayer() */
135 /************************************************************************/
136 FGdbLayer::FGdbLayer()
137 : m_pDS(nullptr), m_pTable(nullptr), m_wstrSubfields(L"*"),
138 m_bFilterDirty(true), m_bLaunderReservedKeywords(true)
139 {
140 m_pEnumRows = new EnumRows;
141
142 #ifdef EXTENT_WORKAROUND
143 m_bLayerEnvelopeValid = false;
144 #endif
145 }
146
147 /************************************************************************/
148 /* ~FGdbLayer() */
149 /************************************************************************/
150
151 FGdbLayer::~FGdbLayer()
152 {
153 FGdbLayer::CloseGDBObjects();
154
155 for (size_t i = 0; i < m_apoByteArrays.size(); i++)
156 delete m_apoByteArrays[i];
157 m_apoByteArrays.resize(0);
158 }
159
160 /************************************************************************/
161 /* CloseGDBObjects() */
162 /************************************************************************/
163
164 void FGdbLayer::CloseGDBObjects()
165 {
166 #ifdef EXTENT_WORKAROUND
167 WorkAroundExtentProblem();
168 #endif
169
170 if (m_pTable)
171 {
172 delete m_pTable;
173 m_pTable = nullptr;
174 }
175
176 FGdbBaseLayer::CloseGDBObjects();
177 }
178
179 #ifdef EXTENT_WORKAROUND
180
181 /************************************************************************/
182 /* UpdateRowWithGeometry() */
183 /************************************************************************/
184
185 bool FGdbLayer::UpdateRowWithGeometry(Row &row, OGRGeometry *poGeom)
186 {
187 ShapeBuffer shape;
188 long hr;
189
190 /* Write geometry to a buffer */
191 GByte *pabyShape = nullptr;
192 int nShapeSize = 0;
193 if (OGRWriteToShapeBin(poGeom, &pabyShape, &nShapeSize) != OGRERR_NONE)
194 {
195 CPLFree(pabyShape);
196 return false;
197 }
198
199 /* Copy it into a ShapeBuffer */
200 if (nShapeSize > 0)
201 {
202 shape.Allocate(nShapeSize);
203 memcpy(shape.shapeBuffer, pabyShape, nShapeSize);
204 shape.inUseLength = nShapeSize;
205 }
206
207 /* Free the shape buffer */
208 CPLFree(pabyShape);
209
210 /* Write ShapeBuffer into the Row */
211 hr = row.SetGeometry(shape);
212 if (FAILED(hr))
213 {
214 return false;
215 }
216
217 /* Update row */
218 hr = m_pTable->Update(row);
219 if (FAILED(hr))
220 {
221 return false;
222 }
223
224 return true;
225 }
226
227 /************************************************************************/
228 /* WorkAroundExtentProblem() */
229 /* */
230 /* Work-around problem with FileGDB API 1.1 on Linux 64bit. See #4455 */
231 /************************************************************************/
232
233 void FGdbLayer::WorkAroundExtentProblem()
234 {
235 if (!m_bLayerEnvelopeValid)
236 return;
237
238 OGREnvelope sEnvelope;
239 if (FGdbLayer::GetExtent(&sEnvelope, TRUE) != OGRERR_NONE)
240 return;
241
242 /* The characteristic of the bug is that the reported extent */
243 /* is the real extent truncated incorrectly to integer values */
244 /* We work around that by temporary updating one feature with a geometry */
245 /* whose coordinates are integer values but ceil'ed and floor'ed */
246 /* such that they include the real layer extent. */
247 if (((double)(int)sEnvelope.MinX == sEnvelope.MinX &&
248 (double)(int)sEnvelope.MinY == sEnvelope.MinY &&
249 (double)(int)sEnvelope.MaxX == sEnvelope.MaxX &&
250 (double)(int)sEnvelope.MaxY == sEnvelope.MaxY) &&
251 (fabs(sEnvelope.MinX - sLayerEnvelope.MinX) > 1e-5 ||
252 fabs(sEnvelope.MinY - sLayerEnvelope.MinY) > 1e-5 ||
253 fabs(sEnvelope.MaxX - sLayerEnvelope.MaxX) > 1e-5 ||
254 fabs(sEnvelope.MaxY - sLayerEnvelope.MaxY) > 1e-5))
255 {
256 long hr;
257 Row row;
258 EnumRows enumRows;
259
260 if (FAILED(hr = m_pTable->Search(StringToWString("*"),
261 StringToWString(""), true, enumRows)))
262 return;
263
264 if (FAILED(hr = enumRows.Next(row)))
265 return;
266
267 if (hr != S_OK)
268 return;
269
270 /* Backup original shape buffer */
271 ShapeBuffer originalGdbGeometry;
272 if (FAILED(hr = row.GetGeometry(originalGdbGeometry)))
273 return;
274
275 OGRGeometry *pOGRGeo = nullptr;
276 if ((!GDBGeometryToOGRGeometry(m_forceMulti, &originalGdbGeometry,
277 m_pSRS, &pOGRGeo)) ||
278 pOGRGeo == nullptr)
279 {
280 delete pOGRGeo;
281 return;
282 }
283
284 OGRwkbGeometryType eType = wkbFlatten(pOGRGeo->getGeometryType());
285
286 delete pOGRGeo;
287 pOGRGeo = nullptr;
288
289 OGRPoint oP1(floor(sLayerEnvelope.MinX), floor(sLayerEnvelope.MinY));
290 OGRPoint oP2(ceil(sLayerEnvelope.MaxX), ceil(sLayerEnvelope.MaxY));
291
292 OGRLinearRing oLR;
293 oLR.addPoint(&oP1);
294 oLR.addPoint(&oP2);
295 oLR.addPoint(&oP1);
296
297 if (eType == wkbPoint)
298 {
299 UpdateRowWithGeometry(row, &oP1);
300 UpdateRowWithGeometry(row, &oP2);
301 }
302 else if (eType == wkbLineString)
303 {
304 UpdateRowWithGeometry(row, &oLR);
305 }
306 else if (eType == wkbPolygon)
307 {
308 OGRPolygon oPoly;
309 oPoly.addRing(&oLR);
310
311 UpdateRowWithGeometry(row, &oPoly);
312 }
313 else if (eType == wkbMultiPoint)
314 {
315 OGRMultiPoint oColl;
316 oColl.addGeometry(&oP1);
317 oColl.addGeometry(&oP2);
318
319 UpdateRowWithGeometry(row, &oColl);
320 }
321 else if (eType == wkbMultiLineString)
322 {
323 OGRMultiLineString oColl;
324 oColl.addGeometry(&oLR);
325
326 UpdateRowWithGeometry(row, &oColl);
327 }
328 else if (eType == wkbMultiPolygon)
329 {
330 OGRMultiPolygon oColl;
331 OGRPolygon oPoly;
332 oPoly.addRing(&oLR);
333 oColl.addGeometry(&oPoly);
334
335 UpdateRowWithGeometry(row, &oColl);
336 }
337 else
338 return;
339
340 /* Restore original ShapeBuffer */
341 hr = row.SetGeometry(originalGdbGeometry);
342 if (FAILED(hr))
343 return;
344
345 /* Update Row */
346 hr = m_pTable->Update(row);
347 if (FAILED(hr))
348 return;
349
350 CPLDebug("FGDB",
351 "Workaround extent problem with Linux 64bit FGDB SDK 1.1");
352 }
353 }
354 #endif // EXTENT_WORKAROUND
355
356 /************************************************************************/
357 /* GetRow() */
358 /************************************************************************/
359
360 OGRErr FGdbLayer::GetRow(EnumRows &enumRows, Row &row, GIntBig nFID)
361 {
362 long hr;
363 CPLString osQuery;
364
365 /* Querying a 64bit FID causes a runtime exception in FileGDB... */
366 if (!CPL_INT64_FITS_ON_INT32(nFID))
367 {
368 return OGRERR_FAILURE;
369 }
370
371 osQuery.Printf("%s = " CPL_FRMT_GIB, m_strOIDFieldName.c_str(), nFID);
372
373 if (FAILED(hr = m_pTable->Search(m_wstrSubfields,
374 StringToWString(osQuery.c_str()), true,
375 enumRows)))
376 {
377 GDBErr(hr, "Failed fetching row ");
378 return OGRERR_FAILURE;
379 }
380
381 if (FAILED(hr = enumRows.Next(row)))
382 {
383 GDBErr(hr, "Failed fetching row ");
384 return OGRERR_FAILURE;
385 }
386
387 if (hr != S_OK)
388 return OGRERR_NON_EXISTING_FEATURE; // none found - but no failure
389
390 return OGRERR_NONE;
391 }
392
393 /*************************************************************************/
394 /* Initialize() */
395 /* Has ownership of the table as soon as it is called. */
396 /************************************************************************/
397
398 bool FGdbLayer::Initialize(FGdbDataSource *pParentDataSource, Table *pTable,
399 const std::wstring &wstrTablePath,
400 const std::wstring &wstrType)
401 {
402 long hr;
403
404 m_pDS = pParentDataSource; // we never assume ownership of the parent - so
405 // our destructor should not delete
406
407 m_pTable = pTable;
408
409 m_wstrTablePath = wstrTablePath;
410 m_wstrType = wstrType;
411
412 wstring wstrQueryName;
413 if (FAILED(hr = pParentDataSource->GetGDB()->GetQueryName(wstrTablePath,
414 wstrQueryName)))
415 return GDBErr(hr, "Failed at getting underlying table name for " +
416 WStringToString(wstrTablePath));
417
418 m_strName = WStringToString(wstrQueryName);
419
420 m_pFeatureDefn = new OGRFeatureDefn(
421 m_strName.c_str()); // TODO: Should I "new" an OGR smart pointer -
422 // sample says so, but it doesn't seem right
423 SetDescription(m_pFeatureDefn->GetName());
424 // as long as we use the same compiler & settings in both the ogr build and
425 // this driver, we should be OK
426 m_pFeatureDefn->Reference();
427
428 string tableDef;
429 if (FAILED(hr = m_pTable->GetDefinition(tableDef)))
430 return GDBErr(hr, "Failed at getting table definition for " +
431 WStringToString(wstrTablePath));
432
433 // CPLDebug("FGDB", "tableDef = %s", tableDef.c_str());
434
435 bool abort = false;
436
437 // extract schema information from table
438 CPLXMLNode *psRoot = CPLParseXMLString(tableDef.c_str());
439
440 if (psRoot == nullptr)
441 {
442 CPLError(
443 CE_Failure, CPLE_AppDefined, "%s",
444 ("Failed parsing GDB Table Schema XML for " + m_strName).c_str());
445 return false;
446 }
447
448 CPLXMLNode *pDataElementNode =
449 psRoot->psNext; // Move to next field which should be DataElement
450
451 if (pDataElementNode != nullptr && pDataElementNode->psChild != nullptr &&
452 pDataElementNode->eType == CXT_Element &&
453 EQUAL(pDataElementNode->pszValue, "esri:DataElement"))
454 {
455 CPLXMLNode *psNode;
456
457 m_bTimeInUTC = CPLTestBool(
458 CPLGetXMLValue(pDataElementNode, "IsTimeInUTC", "false"));
459
460 std::string osAreaFieldName;
461 std::string osLengthFieldName;
462 for (psNode = pDataElementNode->psChild; psNode != nullptr;
463 psNode = psNode->psNext)
464 {
465 if (psNode->eType == CXT_Element && psNode->psChild != nullptr)
466 {
467 if (EQUAL(psNode->pszValue, "OIDFieldName"))
468 {
469 m_strOIDFieldName = CPLGetXMLValue(psNode, nullptr, "");
470 }
471 else if (EQUAL(psNode->pszValue, "ShapeFieldName"))
472 {
473 m_strShapeFieldName = CPLGetXMLValue(psNode, nullptr, "");
474 }
475 else if (EQUAL(psNode->pszValue, "AreaFieldName"))
476 {
477 osAreaFieldName = CPLGetXMLValue(psNode, nullptr, "");
478 }
479 else if (EQUAL(psNode->pszValue, "LengthFieldName"))
480 {
481 osLengthFieldName = CPLGetXMLValue(psNode, nullptr, "");
482 }
483 else if (EQUAL(psNode->pszValue, "Fields"))
484 {
485 if (!GDBToOGRFields(psNode))
486 {
487 abort = true;
488 break;
489 }
490 }
491 }
492 }
493
494 if (!osAreaFieldName.empty())
495 {
496 const int nIdx =
497 m_pFeatureDefn->GetFieldIndex(osAreaFieldName.c_str());
498 if (nIdx >= 0)
499 {
500 m_pFeatureDefn->GetFieldDefn(nIdx)->SetDefault(
501 "FILEGEODATABASE_SHAPE_AREA");
502 }
503 }
504
505 if (!osLengthFieldName.empty())
506 {
507 const int nIdx =
508 m_pFeatureDefn->GetFieldIndex(osLengthFieldName.c_str());
509 if (nIdx >= 0)
510 {
511 m_pFeatureDefn->GetFieldDefn(nIdx)->SetDefault(
512 "FILEGEODATABASE_SHAPE_LENGTH");
513 }
514 }
515
516 if (m_strShapeFieldName.empty())
517 m_pFeatureDefn->SetGeomType(wkbNone);
518 }
519 else
520 {
521 CPLError(CE_Failure, CPLE_AppDefined, "%s",
522 ("Failed parsing GDB Table Schema XML (DataElement) for " +
523 m_strName)
524 .c_str());
525 return false;
526 }
527 CPLDestroyXMLNode(psRoot);
528
529 if (m_pFeatureDefn->GetGeomFieldCount() != 0)
530 {
531 m_pFeatureDefn->GetGeomFieldDefn(0)->SetName(
532 m_strShapeFieldName.c_str());
533 m_pFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(m_pSRS);
534 }
535
536 if (abort)
537 return false;
538
539 return true; // AOToOGRFields(ipFields, m_pFeatureDefn,
540 // m_vOGRFieldToESRIField);
541 }
542
543 /************************************************************************/
544 /* ParseGeometryDef() */
545 /************************************************************************/
546
547 bool FGdbLayer::ParseGeometryDef(const CPLXMLNode *psRoot)
548 {
549 string geometryType;
550 bool hasZ = false, hasM = false;
551 string wkt, wkid, latestwkid;
552
553 OGRGeomCoordinatePrecision oCoordPrec;
554 for (const CPLXMLNode *psGeometryDefItem = psRoot->psChild;
555 psGeometryDefItem; psGeometryDefItem = psGeometryDefItem->psNext)
556 {
557 // loop through all "GeometryDef" elements
558 //
559
560 if (psGeometryDefItem->eType == CXT_Element &&
561 psGeometryDefItem->psChild != nullptr)
562 {
563 if (EQUAL(psGeometryDefItem->pszValue, "GeometryType"))
564 {
565 geometryType = CPLGetXMLValue(psGeometryDefItem, nullptr, "");
566 }
567 else if (EQUAL(psGeometryDefItem->pszValue, "SpatialReference"))
568 {
569 ParseSpatialReference(
570 psGeometryDefItem, &wkt, &wkid,
571 &latestwkid); // we don't check for success because it
572 // may not be there
573 oCoordPrec = GDBGridSettingsToOGR(psGeometryDefItem);
574 }
575 else if (EQUAL(psGeometryDefItem->pszValue, "HasM"))
576 {
577 if (!strcmp(CPLGetXMLValue(psGeometryDefItem, nullptr, ""),
578 "true"))
579 hasM = true;
580 }
581 else if (EQUAL(psGeometryDefItem->pszValue, "HasZ"))
582 {
583 if (!strcmp(CPLGetXMLValue(psGeometryDefItem, nullptr, ""),
584 "true"))
585 hasZ = true;
586 }
587 }
588 }
589
590 OGRwkbGeometryType ogrGeoType;
591 if (!GDBToOGRGeometry(geometryType, hasZ, hasM, &ogrGeoType))
592 return false;
593
594 m_pFeatureDefn->SetGeomType(ogrGeoType);
595
596 if (m_pFeatureDefn->GetGeomFieldCount() != 0)
597 m_pFeatureDefn->GetGeomFieldDefn(0)->SetCoordinatePrecision(oCoordPrec);
598
599 if (wkbFlatten(ogrGeoType) == wkbMultiLineString ||
600 wkbFlatten(ogrGeoType) == wkbMultiPoint)
601 m_forceMulti = true;
602
603 if (latestwkid.length() > 0 || wkid.length() > 0)
604 {
605 int bSuccess = FALSE;
606 m_pSRS = new OGRSpatialReference();
607 m_pSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
608 CPLPushErrorHandler(CPLQuietErrorHandler);
609 if (latestwkid.length() > 0)
610 {
611 if (m_pSRS->importFromEPSG(atoi(latestwkid.c_str())) == OGRERR_NONE)
612 {
613 bSuccess = TRUE;
614 }
615 else
616 {
617 CPLDebug("FGDB", "Cannot import SRID %s", latestwkid.c_str());
618 }
619 }
620 if (!bSuccess && wkid.length() > 0)
621 {
622 if (m_pSRS->importFromEPSG(atoi(wkid.c_str())) == OGRERR_NONE)
623 {
624 bSuccess = TRUE;
625 }
626 else
627 {
628 CPLDebug("FGDB", "Cannot import SRID %s", wkid.c_str());
629 }
630 }
631 CPLPopErrorHandler();
632 CPLErrorReset();
633 if (!bSuccess)
634 {
635 delete m_pSRS;
636 m_pSRS = nullptr;
637 }
638 else
639 return true;
640 }
641
642 if (wkt.length() > 0)
643 {
644 if (!GDBToOGRSpatialReference(wkt, &m_pSRS))
645 {
646 // report error, but be passive about it
647 CPLError(CE_Warning, CPLE_AppDefined,
648 "Failed Mapping ESRI Spatial Reference");
649 }
650 }
651
652 return true;
653 }
654
655 /************************************************************************/
656 /* ParseSpatialReference() */
657 /************************************************************************/
658
659 bool FGdbLayer::ParseSpatialReference(const CPLXMLNode *psSpatialRefNode,
660 string *pOutWkt, string *pOutWKID,
661 string *pOutLatestWKID)
662 {
663 *pOutWkt = "";
664 *pOutWKID = "";
665 *pOutLatestWKID = "";
666
667 /* Loop through all the SRS elements we want to store */
668 for (const CPLXMLNode *psSRItemNode = psSpatialRefNode->psChild;
669 psSRItemNode; psSRItemNode = psSRItemNode->psNext)
670 {
671 /* The WKID maps (mostly) to an EPSG code */
672 if (psSRItemNode->eType == CXT_Element &&
673 psSRItemNode->psChild != nullptr &&
674 EQUAL(psSRItemNode->pszValue, "WKID"))
675 {
676 *pOutWKID = CPLGetXMLValue(psSRItemNode, nullptr, "");
677
678 // Needed with FileGDB v1.4 with layers with empty SRS
679 if (*pOutWKID == "0")
680 *pOutWKID = "";
681 }
682 /* The concept of LatestWKID is explained in
683 * http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#//02r3000000n1000000
684 */
685 else if (psSRItemNode->eType == CXT_Element &&
686 psSRItemNode->psChild != nullptr &&
687 EQUAL(psSRItemNode->pszValue, "LatestWKID"))
688 {
689 *pOutLatestWKID = CPLGetXMLValue(psSRItemNode, nullptr, "");
690 }
691 /* The WKT well-known text can be converted by OGR */
692 else if (psSRItemNode->eType == CXT_Element &&
693 psSRItemNode->psChild != nullptr &&
694 EQUAL(psSRItemNode->pszValue, "WKT"))
695 {
696 *pOutWkt = CPLGetXMLValue(psSRItemNode, nullptr, "");
697 }
698 }
699 return *pOutWkt != "" || *pOutWKID != "";
700 }
701
702 /************************************************************************/
703 /* GDBToOGRFields() */
704 /************************************************************************/
705
706 bool FGdbLayer::GDBToOGRFields(CPLXMLNode *psRoot)
707 {
708 m_vOGRFieldToESRIField.clear();
709
710 if (psRoot->psChild == nullptr || psRoot->psChild->psNext == nullptr)
711 {
712 CPLError(CE_Failure, CPLE_AppDefined, "Unrecognized GDB XML Schema");
713
714 return false;
715 }
716
717 psRoot = psRoot->psChild->psNext; // change root to "FieldArray"
718
719 // CPLAssert(ogrToESRIFieldMapping.size() ==
720 // pOGRFeatureDef->GetFieldCount());
721
722 CPLXMLNode *psFieldNode;
723
724 for (psFieldNode = psRoot->psChild; psFieldNode != nullptr;
725 psFieldNode = psFieldNode->psNext)
726 {
727 // loop through all "Field" elements
728 //
729
730 if (psFieldNode->eType == CXT_Element &&
731 psFieldNode->psChild != nullptr &&
732 EQUAL(psFieldNode->pszValue, "Field"))
733 {
734
735 CPLXMLNode *psFieldItemNode;
736 std::string fieldName;
737 std::string fieldAlias;
738 std::string fieldType;
739 int nLength = 0;
740 int bNullable = TRUE;
741 std::string osDefault;
742 std::string osDomainName;
743
744 // loop through all items in Field element
745 //
746
747 for (psFieldItemNode = psFieldNode->psChild;
748 psFieldItemNode != nullptr;
749 psFieldItemNode = psFieldItemNode->psNext)
750 {
751 if (psFieldItemNode->eType == CXT_Element)
752 {
753 const char *pszValue =
754 CPLGetXMLValue(psFieldItemNode, nullptr, "");
755 if (EQUAL(psFieldItemNode->pszValue, "Name"))
756 {
757 fieldName = pszValue;
758 }
759 else if (EQUAL(psFieldItemNode->pszValue, "AliasName"))
760 {
761 fieldAlias = pszValue;
762 }
763 else if (EQUAL(psFieldItemNode->pszValue, "Type"))
764 {
765 fieldType = pszValue;
766 }
767 else if (EQUAL(psFieldItemNode->pszValue, "GeometryDef"))
768 {
769 if (!ParseGeometryDef(psFieldItemNode))
770 return false; // if we failed parsing the
771 // GeometryDef, we are done!
772 }
773 else if (EQUAL(psFieldItemNode->pszValue, "Length"))
774 {
775 nLength = atoi(pszValue);
776 }
777 else if (EQUAL(psFieldItemNode->pszValue, "IsNullable"))
778 {
779 bNullable = EQUAL(pszValue, "true");
780 }
781 else if (EQUAL(psFieldItemNode->pszValue, "DefaultValue"))
782 {
783 osDefault = pszValue;
784 }
785 // NOTE: when using the GetDefinition() API, the domain name
786 // is set in <Domain><DomainName>, whereas the raw XML is
787 // just <DomainName>
788 else if (EQUAL(psFieldItemNode->pszValue, "Domain"))
789 {
790 osDomainName =
791 CPLGetXMLValue(psFieldItemNode, "DomainName", "");
792 }
793 }
794 }
795
796 ///////////////////////////////////////////////////////////////////
797 // At this point we have parsed everything about the current field
798
799 if (fieldType == "esriFieldTypeGeometry")
800 {
801 m_strShapeFieldName = std::move(fieldName);
802 m_pFeatureDefn->GetGeomFieldDefn(0)->SetNullable(bNullable);
803
804 continue; // finish here for special field - don't add as OGR
805 // fielddef
806 }
807 else if (fieldType == "esriFieldTypeOID")
808 {
809 // m_strOIDFieldName = fieldName; // already set by this point
810
811 continue; // finish here for special field - don't add as OGR
812 // fielddef
813 }
814
815 OGRFieldType ogrType;
816 OGRFieldSubType eSubType;
817 // CPLDebug("FGDB", "name = %s, type = %s", fieldName.c_str(),
818 // fieldType.c_str() );
819 if (!GDBToOGRFieldType(fieldType, &ogrType, &eSubType))
820 {
821 // field cannot be mapped, skipping further processing
822 CPLError(CE_Warning, CPLE_AppDefined,
823 "Skipping field: [%s] type: [%s] ", fieldName.c_str(),
824 fieldType.c_str());
825 continue;
826 }
827
828 // TODO: Optimization - modify m_wstrSubFields so it only fetches
829 // fields that are mapped
830
831 OGRFieldDefn fieldTemplate(fieldName.c_str(), ogrType);
832 if (fieldAlias != fieldName)
833 {
834 // The SDK generates an alias even with it is not explicitly
835 // written
836 fieldTemplate.SetAlternativeName(fieldAlias.c_str());
837 }
838 fieldTemplate.SetSubType(eSubType);
839 /* On creation (GDBFieldTypeToLengthInBytes) if string width is 0,
840 * we pick up */
841 /* 65536 by default to mean unlimited string length, but we don't
842 * want */
843 /* to advertise such a big number */
844 if (ogrType == OFTString && nLength < 65536)
845 fieldTemplate.SetWidth(nLength);
846 fieldTemplate.SetNullable(bNullable);
847 if (!osDefault.empty())
848 {
849 if (ogrType == OFTString)
850 {
851 char *pszTmp =
852 CPLEscapeString(osDefault.c_str(), -1, CPLES_SQL);
853 osDefault = "'";
854 osDefault += pszTmp;
855 CPLFree(pszTmp);
856 osDefault += "'";
857 fieldTemplate.SetDefault(osDefault.c_str());
858 }
859 else if (ogrType == OFTInteger || ogrType == OFTReal)
860 {
861 #ifdef unreliable
862 /* Disabling this as GDBs and the FileGDB SDK aren't
863 * reliable for numeric values */
864 /* It often occurs that the XML definition in
865 * a00000004.gdbtable doesn't */
866 /* match the default values (in binary) found in the field
867 * definition */
868 /* section of the .gdbtable of the layers themselves */
869 /* The Table::GetDefinition() API of FileGDB doesn't seem to
870 * use the */
871 /* XML definition, but rather the values found in the field
872 * definition */
873 /* section of the .gdbtable of the layers themselves */
874 /* It seems that the XML definition in a00000004.gdbtable is
875 * authoritative */
876 /* in ArcGIS, so we're screwed... */
877
878 fieldTemplate.SetDefault(osDefault.c_str());
879 #endif
880 }
881 else if (ogrType == OFTDateTime)
882 {
883 int nYear, nMonth, nDay, nHour, nMinute;
884 float fSecond;
885 if (sscanf(osDefault.c_str(), "%d-%d-%dT%d:%d:%fZ", &nYear,
886 &nMonth, &nDay, &nHour, &nMinute,
887 &fSecond) == 6 ||
888 sscanf(osDefault.c_str(), "'%d-%d-%d %d:%d:%fZ'",
889 &nYear, &nMonth, &nDay, &nHour, &nMinute,
890 &fSecond) == 6)
891 {
892 fieldTemplate.SetDefault(CPLSPrintf(
893 "'%04d/%02d/%02d %02d:%02d:%02d'", nYear, nMonth,
894 nDay, nHour, nMinute, (int)(fSecond + 0.5)));
895 }
896 }
897 }
898 if (!osDomainName.empty())
899 {
900 fieldTemplate.SetDomainName(osDomainName);
901 }
902
903 m_pFeatureDefn->AddFieldDefn(&fieldTemplate);
904
905 m_vOGRFieldToESRIField.push_back(StringToWString(fieldName));
906 m_vOGRFieldToESRIFieldType.push_back(std::move(fieldType));
907 if (ogrType == OFTBinary)
908 m_apoByteArrays.push_back(new ByteArray());
909 }
910 }
911
912 /* Using OpenFileGDB to get reliable default values for integer/real fields
913 */
914 /* and alias */
915 if (m_pDS->UseOpenFileGDB())
916 {
917 const char *const apszDrivers[] = {"OpenFileGDB", nullptr};
918 GDALDataset *poDS = GDALDataset::Open(
919 m_pDS->GetFSName(), GDAL_OF_VECTOR, apszDrivers, nullptr, nullptr);
920 if (poDS != nullptr)
921 {
922 OGRLayer *poLyr = poDS->GetLayerByName(GetName());
923 if (poLyr)
924 {
925 const auto poOFGBLayerDefn = poLyr->GetLayerDefn();
926 const int nOFGDBFieldCount = poOFGBLayerDefn->GetFieldCount();
927 for (int i = 0; i < nOFGDBFieldCount; i++)
928 {
929 const OGRFieldDefn *poSrcDefn =
930 poOFGBLayerDefn->GetFieldDefn(i);
931 if ((poSrcDefn->GetType() == OFTInteger ||
932 poSrcDefn->GetType() == OFTReal) &&
933 poSrcDefn->GetDefault() != nullptr)
934 {
935 int nIdxDst = m_pFeatureDefn->GetFieldIndex(
936 poSrcDefn->GetNameRef());
937 if (nIdxDst >= 0)
938 m_pFeatureDefn->GetFieldDefn(nIdxDst)->SetDefault(
939 poSrcDefn->GetDefault());
940 }
941
942 // XML parsing by the SDK fails when there are special
943 // characters, like &, so fallback to using OpenFileGDB.
944 const char *pszAlternativeName =
945 poSrcDefn->GetAlternativeNameRef();
946 if (pszAlternativeName != nullptr &&
947 pszAlternativeName[0] != '\0' &&
948 strcmp(pszAlternativeName, poSrcDefn->GetNameRef()) !=
949 0)
950 {
951 int nIdxDst = m_pFeatureDefn->GetFieldIndex(
952 poSrcDefn->GetNameRef());
953 if (nIdxDst >= 0)
954 m_pFeatureDefn->GetFieldDefn(nIdxDst)
955 ->SetAlternativeName(pszAlternativeName);
956 }
957 }
958 }
959 GDALClose(poDS);
960 }
961 }
962
963 return true;
964 }
965
966 /************************************************************************/
967 /* ResetReading() */
968 /************************************************************************/
969
970 void FGdbLayer::ResetReading()
971 {
972 long hr;
973
974 if (m_pTable == nullptr)
975 return;
976
977 #ifdef WORKAROUND_CRASH_ON_CDF_WITH_BINARY_FIELD
978 std::wstring wstrSubFieldBackup(m_wstrSubfields);
979 if (!m_apoByteArrays.empty())
980 {
981 m_bWorkaroundCrashOnCDFWithBinaryField = CPLTestBool(CPLGetConfigOption(
982 "OGR_FGDB_WORKAROUND_CRASH_ON_BINARY_FIELD", "YES"));
983 if (m_bWorkaroundCrashOnCDFWithBinaryField)
984 {
985 m_wstrSubfields = StringToWString(m_strOIDFieldName);
986 if (!m_strShapeFieldName.empty() && m_poFilterGeom &&
987 !m_poFilterGeom->IsEmpty())
988 {
989 m_wstrSubfields += StringToWString(", " + m_strShapeFieldName);
990 }
991 }
992 }
993 #endif
994
995 if (m_poFilterGeom && !m_poFilterGeom->IsEmpty())
996 {
997 // Search spatial
998 // As of beta1, FileGDB only supports bbox searched, if we have GEOS
999 // installed, we can do the rest ourselves.
1000
1001 OGREnvelope ogrEnv;
1002
1003 m_poFilterGeom->getEnvelope(&ogrEnv);
1004
1005 // spatial query
1006 FileGDBAPI::Envelope env(ogrEnv.MinX, ogrEnv.MaxX, ogrEnv.MinY,
1007 ogrEnv.MaxY);
1008
1009 if (FAILED(hr = m_pTable->Search(m_wstrSubfields, m_wstrWhereClause,
1010 env, true, *m_pEnumRows)))
1011 GDBErr(hr, "Failed Searching");
1012 }
1013 else
1014 {
1015 // Search non-spatial
1016 if (FAILED(hr = m_pTable->Search(m_wstrSubfields, m_wstrWhereClause,
1017 true, *m_pEnumRows)))
1018 GDBErr(hr, "Failed Searching");
1019 }
1020
1021 #ifdef WORKAROUND_CRASH_ON_CDF_WITH_BINARY_FIELD
1022 if (!m_apoByteArrays.empty() && m_bWorkaroundCrashOnCDFWithBinaryField)
1023 m_wstrSubfields = std::move(wstrSubFieldBackup);
1024 #endif
1025
1026 m_bFilterDirty = false;
1027 }
1028
1029 /************************************************************************/
1030 /* ISetSpatialFilter() */
1031 /************************************************************************/
1032
1033 OGRErr FGdbLayer::ISetSpatialFilter(int iGeomField, const OGRGeometry *pOGRGeom)
1034 {
1035 m_bFilterDirty = true;
1036 return OGRLayer::ISetSpatialFilter(iGeomField, pOGRGeom);
1037 }
1038
1039 /************************************************************************/
1040 /* SetAttributeFilter() */
1041 /************************************************************************/
1042
1043 OGRErr FGdbLayer::SetAttributeFilter(const char *pszQuery)
1044 {
1045 m_wstrWhereClause = StringToWString((pszQuery != nullptr) ? pszQuery : "");
1046
1047 m_bFilterDirty = true;
1048
1049 return OGRERR_NONE;
1050 }
1051
1052 /************************************************************************/
1053 /* OGRFeatureFromGdbRow() */
1054 /************************************************************************/
1055
1056 bool FGdbBaseLayer::OGRFeatureFromGdbRow(Row *pRow, OGRFeature **ppFeature)
1057 {
1058 long hr;
1059
1060 OGRFeature *pOutFeature = new OGRFeature(m_pFeatureDefn);
1061
1062 /////////////////////////////////////////////////////////
1063 // Translate OID
1064 //
1065
1066 int32 oid = -1;
1067 if (FAILED(hr = pRow->GetOID(oid)))
1068 {
1069 // this should never happen unless not selecting the OBJECTID
1070 }
1071 else
1072 {
1073 pOutFeature->SetFID(oid);
1074 }
1075
1076 /////////////////////////////////////////////////////////
1077 // Translate Geometry
1078 //
1079
1080 ShapeBuffer gdbGeometry;
1081 // Row::GetGeometry() will fail with -2147467259 for NULL geometries
1082 // Row::GetGeometry() will fail with -2147219885 for tables without a
1083 // geometry field
1084 if (!m_pFeatureDefn->IsGeometryIgnored() &&
1085 !FAILED(hr = pRow->GetGeometry(gdbGeometry)))
1086 {
1087 OGRGeometry *pOGRGeo = nullptr;
1088
1089 if ((!GDBGeometryToOGRGeometry(m_forceMulti, &gdbGeometry, m_pSRS,
1090 &pOGRGeo)))
1091 {
1092 delete pOutFeature;
1093 return GDBErr(hr, "Failed to translate FileGDB Geometry to OGR "
1094 "Geometry for row " +
1095 string(CPLSPrintf("%d", (int)oid)));
1096 }
1097
1098 pOutFeature->SetGeometryDirectly(pOGRGeo);
1099 }
1100
1101 //////////////////////////////////////////////////////////
1102 // Map fields
1103 //
1104
1105 int mappedFieldCount = static_cast<int>(m_vOGRFieldToESRIField.size());
1106
1107 bool foundBadColumn = false;
1108
1109 for (int i = 0; i < mappedFieldCount; ++i)
1110 {
1111 OGRFieldDefn *poFieldDefn = m_pFeatureDefn->GetFieldDefn(i);
1112 // The IsNull() and GetXXX() API are very slow when there are a
1113 // big number of fields, for example with Tiger database.
1114 if (poFieldDefn->IsIgnored())
1115 continue;
1116
1117 const wstring &wstrFieldName = m_vOGRFieldToESRIField[i];
1118 const std::string &strFieldType = m_vOGRFieldToESRIFieldType[i];
1119
1120 bool isNull = false;
1121
1122 if (FAILED(hr = pRow->IsNull(wstrFieldName, isNull)))
1123 {
1124 GDBErr(hr, "Failed to determine NULL status from column " +
1125 WStringToString(wstrFieldName));
1126 foundBadColumn = true;
1127 continue;
1128 }
1129
1130 if (isNull)
1131 {
1132 pOutFeature->SetFieldNull(i);
1133 continue;
1134 }
1135
1136 //
1137 // NOTE: This switch statement needs to be kept in sync with
1138 // GDBToOGRFieldType utility function
1139 // since we are only checking for types we mapped in that utility
1140 // function
1141
1142 switch (poFieldDefn->GetType())
1143 {
1144
1145 case OFTInteger:
1146 {
1147 int32 val;
1148
1149 if (FAILED(hr = pRow->GetInteger(wstrFieldName, val)))
1150 {
1151 int16 shortval;
1152 if (FAILED(hr = pRow->GetShort(wstrFieldName, shortval)))
1153 {
1154 GDBErr(hr,
1155 "Failed to determine integer value for column " +
1156 WStringToString(wstrFieldName));
1157 foundBadColumn = true;
1158 continue;
1159 }
1160 val = shortval;
1161 }
1162
1163 pOutFeature->SetField(i, (int)val);
1164 }
1165 break;
1166
1167 case OFTReal:
1168 {
1169 if (strFieldType == "esriFieldTypeSingle")
1170 {
1171 float val;
1172
1173 if (FAILED(hr = pRow->GetFloat(wstrFieldName, val)))
1174 {
1175 GDBErr(hr,
1176 "Failed to determine float value for column " +
1177 WStringToString(wstrFieldName));
1178 foundBadColumn = true;
1179 continue;
1180 }
1181
1182 pOutFeature->SetField(i, val);
1183 }
1184 else
1185 {
1186 double val;
1187
1188 if (FAILED(hr = pRow->GetDouble(wstrFieldName, val)))
1189 {
1190 GDBErr(hr,
1191 "Failed to determine real value for column " +
1192 WStringToString(wstrFieldName));
1193 foundBadColumn = true;
1194 continue;
1195 }
1196
1197 pOutFeature->SetField(i, val);
1198 }
1199 }
1200 break;
1201 case OFTString:
1202 {
1203 wstring val;
1204 std::string strValue;
1205
1206 if (strFieldType == "esriFieldTypeGlobalID")
1207 {
1208 Guid guid;
1209 if (FAILED(hr = pRow->GetGlobalID(guid)) ||
1210 FAILED(hr = guid.ToString(val)))
1211 {
1212 GDBErr(hr,
1213 "Failed to determine string value for column " +
1214 WStringToString(wstrFieldName));
1215 foundBadColumn = true;
1216 continue;
1217 }
1218 strValue = WStringToString(val);
1219 }
1220 else if (strFieldType == "esriFieldTypeGUID")
1221 {
1222 Guid guid;
1223 if (FAILED(hr = pRow->GetGUID(wstrFieldName, guid)) ||
1224 FAILED(hr = guid.ToString(val)))
1225 {
1226 GDBErr(hr,
1227 "Failed to determine string value for column " +
1228 WStringToString(wstrFieldName));
1229 foundBadColumn = true;
1230 continue;
1231 }
1232 strValue = WStringToString(val);
1233 }
1234 else if (strFieldType == "esriFieldTypeXML")
1235 {
1236 if (FAILED(hr = pRow->GetXML(wstrFieldName, strValue)))
1237 {
1238 GDBErr(hr, "Failed to determine XML value for column " +
1239 WStringToString(wstrFieldName));
1240 foundBadColumn = true;
1241 continue;
1242 }
1243 }
1244 else
1245 {
1246 if (FAILED(hr = pRow->GetString(wstrFieldName, val)))
1247 {
1248 GDBErr(hr,
1249 "Failed to determine string value for column " +
1250 WStringToString(wstrFieldName));
1251 foundBadColumn = true;
1252 continue;
1253 }
1254 strValue = WStringToString(val);
1255 }
1256
1257 pOutFeature->SetField(i, strValue.c_str());
1258 }
1259 break;
1260
1261 case OFTBinary:
1262 {
1263 ByteArray binaryBuf;
1264
1265 if (FAILED(hr = pRow->GetBinary(wstrFieldName, binaryBuf)))
1266 {
1267 GDBErr(hr, "Failed to determine binary value for column " +
1268 WStringToString(wstrFieldName));
1269 foundBadColumn = true;
1270 continue;
1271 }
1272
1273 pOutFeature->SetField(i, (int)binaryBuf.inUseLength,
1274 (GByte *)binaryBuf.byteArray);
1275 }
1276 break;
1277
1278 case OFTDateTime:
1279 {
1280 struct tm val;
1281
1282 if (FAILED(hr = pRow->GetDate(wstrFieldName, val)))
1283 {
1284 GDBErr(hr, "Failed to determine date value for column " +
1285 WStringToString(wstrFieldName));
1286 foundBadColumn = true;
1287 continue;
1288 }
1289
1290 pOutFeature->SetField(i, val.tm_year + 1900, val.tm_mon + 1,
1291 val.tm_mday, val.tm_hour, val.tm_min,
1292 (float)val.tm_sec,
1293 m_bTimeInUTC ? 100 : 0);
1294 // Examine test data to figure out how to extract that
1295 }
1296 break;
1297
1298 default:
1299 {
1300 if (!m_suppressColumnMappingError)
1301 {
1302 foundBadColumn = true;
1303 CPLError(CE_Warning, CPLE_AppDefined,
1304 "Row id: %d col:%d has unhandled col type (%d). "
1305 "Setting to NULL.",
1306 (int)oid, (int)i,
1307 m_pFeatureDefn->GetFieldDefn(i)->GetType());
1308 }
1309 }
1310 }
1311 }
1312
1313 if (foundBadColumn)
1314 m_suppressColumnMappingError = true;
1315
1316 *ppFeature = pOutFeature;
1317
1318 return true;
1319 }
1320
1321 /************************************************************************/
1322 /* GetNextFeature() */
1323 /************************************************************************/
1324
1325 OGRFeature *FGdbLayer::GetNextFeature()
1326 {
1327 if (m_bFilterDirty)
1328 ResetReading();
1329
1330 #ifdef WORKAROUND_CRASH_ON_CDF_WITH_BINARY_FIELD
1331 if (!m_apoByteArrays.empty() && m_bWorkaroundCrashOnCDFWithBinaryField)
1332 {
1333 while (true)
1334 {
1335 if (m_pEnumRows == nullptr)
1336 return nullptr;
1337
1338 long hr;
1339
1340 Row rowOnlyOid;
1341
1342 if (FAILED(hr = m_pEnumRows->Next(rowOnlyOid)))
1343 {
1344 GDBErr(hr, "Failed fetching features");
1345 return nullptr;
1346 }
1347
1348 if (hr != S_OK)
1349 {
1350 // It's OK, we are done fetching - failure is caught by FAILED
1351 // macro
1352 return nullptr;
1353 }
1354
1355 int32 oid = -1;
1356 if (FAILED(hr = rowOnlyOid.GetOID(oid)))
1357 {
1358 GDBErr(hr, "Failed to get oid");
1359 continue;
1360 }
1361
1362 EnumRows enumRows;
1363 OGRFeature *pOGRFeature = nullptr;
1364 Row rowFull;
1365 if (GetRow(enumRows, rowFull, oid) != OGRERR_NONE ||
1366 !OGRFeatureFromGdbRow(&rowFull, &pOGRFeature) || !pOGRFeature)
1367 {
1368 GDBErr(hr,
1369 CPLSPrintf(
1370 "Failed translating FGDB row [%d] to OGR Feature",
1371 oid));
1372
1373 // return NULL;
1374 continue; // skip feature
1375 }
1376
1377 if ((m_poFilterGeom == nullptr ||
1378 FilterGeometry(pOGRFeature->GetGeometryRef())))
1379 {
1380 return pOGRFeature;
1381 }
1382 delete pOGRFeature;
1383 }
1384 }
1385 #endif
1386
1387 OGRFeature *poFeature = FGdbBaseLayer::GetNextFeature();
1388 return poFeature;
1389 }
1390
1391 /************************************************************************/
1392 /* GetFeature() */
1393 /************************************************************************/
1394
1395 OGRFeature *FGdbLayer::GetFeature(GIntBig oid)
1396 {
1397 // do query to fetch individual row
1398 EnumRows enumRows;
1399 Row row;
1400 if (!CPL_INT64_FITS_ON_INT32(oid) || m_pTable == nullptr)
1401 return nullptr;
1402
1403 int nFID32 = (int)oid;
1404
1405 if (GetRow(enumRows, row, nFID32) != OGRERR_NONE)
1406 return nullptr;
1407
1408 OGRFeature *pOGRFeature = nullptr;
1409
1410 if (!OGRFeatureFromGdbRow(&row, &pOGRFeature))
1411 {
1412 return nullptr;
1413 }
1414 if (pOGRFeature)
1415 {
1416 pOGRFeature->SetFID(oid);
1417 }
1418
1419 return pOGRFeature;
1420 }
1421
1422 /************************************************************************/
1423 /* GetFeatureCount() */
1424 /************************************************************************/
1425
1426 GIntBig FGdbLayer::GetFeatureCount(CPL_UNUSED int bForce)
1427 {
1428 int32 rowCount = 0;
1429
1430 if (m_pTable == nullptr)
1431 return 0;
1432
1433 if (m_poFilterGeom != nullptr || !m_wstrWhereClause.empty())
1434 {
1435 ResetReading();
1436 if (m_pEnumRows == nullptr)
1437 return 0;
1438
1439 int nFeatures = 0;
1440 while (true)
1441 {
1442 long hr;
1443
1444 Row row;
1445
1446 if (FAILED(hr = m_pEnumRows->Next(row)))
1447 {
1448 GDBErr(hr, "Failed fetching features");
1449 return 0;
1450 }
1451
1452 if (hr != S_OK)
1453 {
1454 break;
1455 }
1456
1457 if (m_poFilterGeom == nullptr)
1458 {
1459 nFeatures++;
1460 }
1461 else
1462 {
1463 ShapeBuffer gdbGeometry;
1464 if (FAILED(hr = row.GetGeometry(gdbGeometry)))
1465 {
1466 continue;
1467 }
1468
1469 OGRGeometry *pOGRGeo = nullptr;
1470 if (!GDBGeometryToOGRGeometry(m_forceMulti, &gdbGeometry,
1471 m_pSRS, &pOGRGeo) ||
1472 pOGRGeo == nullptr)
1473 {
1474 delete pOGRGeo;
1475 continue;
1476 }
1477
1478 if (FilterGeometry(pOGRGeo))
1479 {
1480 nFeatures++;
1481 }
1482
1483 delete pOGRGeo;
1484 }
1485 }
1486 ResetReading();
1487 return nFeatures;
1488 }
1489
1490 long hr;
1491 if (FAILED(hr = m_pTable->GetRowCount(rowCount)))
1492 {
1493 GDBErr(hr, "Failed counting rows");
1494 return 0;
1495 }
1496
1497 return static_cast<int>(rowCount);
1498 }
1499
1500 /************************************************************************/
1501 /* GetMetadataItem() */
1502 /************************************************************************/
1503
1504 const char *FGdbLayer::GetMetadataItem(const char *pszName,
1505 const char *pszDomain)
1506 {
1507 return OGRLayer::GetMetadataItem(pszName, pszDomain);
1508 }
1509
1510 /************************************************************************/
1511 /* IGetExtent() */
1512 /************************************************************************/
1513
1514 OGRErr FGdbLayer::IGetExtent(int iGeomField, OGREnvelope *psExtent, bool bForce)
1515 {
1516 if (m_pTable == nullptr)
1517 return OGRERR_FAILURE;
1518
1519 if (m_poFilterGeom != nullptr || !m_wstrWhereClause.empty() ||
1520 m_strShapeFieldName.empty())
1521 {
1522 const int nFieldCount = m_pFeatureDefn->GetFieldCount();
1523 int *pabSaveFieldIgnored = new int[nFieldCount];
1524 for (int i = 0; i < nFieldCount; i++)
1525 {
1526 // cppcheck-suppress uninitdata
1527 pabSaveFieldIgnored[i] =
1528 m_pFeatureDefn->GetFieldDefn(i)->IsIgnored();
1529 m_pFeatureDefn->GetFieldDefn(i)->SetIgnored(TRUE);
1530 }
1531 OGRErr eErr = OGRLayer::IGetExtent(iGeomField, psExtent, bForce);
1532 for (int i = 0; i < nFieldCount; i++)
1533 {
1534 m_pFeatureDefn->GetFieldDefn(i)->SetIgnored(pabSaveFieldIgnored[i]);
1535 }
1536 delete[] pabSaveFieldIgnored;
1537 return eErr;
1538 }
1539
1540 long hr;
1541 Envelope envelope;
1542 if (FAILED(hr = m_pTable->GetExtent(envelope)))
1543 {
1544 GDBErr(hr, "Failed fetching extent");
1545 return OGRERR_FAILURE;
1546 }
1547
1548 psExtent->MinX = envelope.xMin;
1549 psExtent->MinY = envelope.yMin;
1550 psExtent->MaxX = envelope.xMax;
1551 psExtent->MaxY = envelope.yMax;
1552
1553 if (std::isnan(psExtent->MinX) || std::isnan(psExtent->MinY) ||
1554 std::isnan(psExtent->MaxX) || std::isnan(psExtent->MaxY))
1555 return OGRERR_FAILURE;
1556
1557 return OGRERR_NONE;
1558 }
1559
1560 /************************************************************************/
1561 /* GetLayerXML() */
1562 /* Return XML definition of the Layer as provided by FGDB. Caller must */
1563 /* free result. */
1564 /* Not currently used by the driver, but can be used by external code */
1565 /* for specific purposes. */
1566 /************************************************************************/
1567
1568 OGRErr FGdbLayer::GetLayerXML(char **ppXml)
1569 {
1570 long hr;
1571 std::string xml;
1572
1573 if (m_pTable == nullptr)
1574 return OGRERR_FAILURE;
1575
1576 if (FAILED(hr = m_pTable->GetDefinition(xml)))
1577 {
1578 GDBErr(hr, "Failed fetching XML table definition");
1579 return OGRERR_FAILURE;
1580 }
1581
1582 *ppXml = CPLStrdup(xml.c_str());
1583 return OGRERR_NONE;
1584 }
1585
1586 /************************************************************************/
1587 /* GetLayerMetadataXML() */
1588 /* Return XML metadata for the Layer as provided by FGDB. Caller must */
1589 /* free result. */
1590 /* Not currently used by the driver, but can be used by external code */
1591 /* for specific purposes. */
1592 /************************************************************************/
1593
1594 OGRErr FGdbLayer::GetLayerMetadataXML(char **ppXml)
1595 {
1596 long hr;
1597 std::string xml;
1598
1599 if (m_pTable == nullptr)
1600 return OGRERR_FAILURE;
1601
1602 if (FAILED(hr = m_pTable->GetDocumentation(xml)))
1603 {
1604 GDBErr(hr, "Failed fetching XML table metadata");
1605 return OGRERR_FAILURE;
1606 }
1607
1608 *ppXml = CPLStrdup(xml.c_str());
1609 return OGRERR_NONE;
1610 }
1611
1612 /************************************************************************/
1613 /* TestCapability() */
1614 /************************************************************************/
1615
1616 int FGdbLayer::TestCapability(const char *pszCap) const
1617 {
1618
1619 if (EQUAL(pszCap, OLCRandomRead))
1620 return TRUE;
1621
1622 else if (EQUAL(pszCap, OLCFastFeatureCount))
1623 return m_poFilterGeom == nullptr && m_wstrWhereClause.empty();
1624
1625 else if (EQUAL(pszCap, OLCFastSpatialFilter))
1626 return TRUE;
1627
1628 else if (EQUAL(pszCap, OLCFastGetExtent))
1629 return m_poFilterGeom == nullptr && m_wstrWhereClause.empty();
1630
1631 else if (EQUAL(pszCap,
1632 OLCStringsAsUTF8)) /* Native UTF16, converted to UTF8 */
1633 return TRUE;
1634
1635 else if (EQUAL(pszCap,
1636 OLCFastSetNextByIndex)) /* TBD FastSetNextByIndex() */
1637 return FALSE;
1638
1639 else if (EQUAL(pszCap, OLCIgnoreFields))
1640 return TRUE;
1641
1642 else if (EQUAL(pszCap, OLCMeasuredGeometries))
1643 return TRUE;
1644
1645 else if (EQUAL(pszCap, OLCZGeometries))
1646 return TRUE;
1647
1648 else
1649 return FALSE;
1650 }
1651
1652 /************************************************************************/
1653 /* GetDataset() */
1654 /************************************************************************/
1655
1656 GDALDataset *FGdbLayer::GetDataset()
1657 {
1658 return m_pDS;
1659 }