Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: FlatGeobuf driver
4 : * Purpose: Implements OGRFlatGeobufLayer class.
5 : * Author: Björn Harrtell <bjorn at wololo dot org>
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2018-2020, Björn Harrtell <bjorn at wololo dot org>
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : #include "ogrsf_frmts.h"
14 : #include "cpl_vsi_virtual.h"
15 : #include "cpl_conv.h"
16 : #include "cpl_json.h"
17 : #include "cpl_http.h"
18 : #include "cpl_time.h"
19 : #include "ogr_p.h"
20 : #include "ograrrowarrayhelper.h"
21 : #include "ogrlayerarrow.h"
22 : #include "ogr_recordbatch.h"
23 :
24 : #include "ogr_flatgeobuf.h"
25 : #include "cplerrors.h"
26 : #include "geometryreader.h"
27 : #include "geometrywriter.h"
28 :
29 : #include <algorithm>
30 : #include <cmath>
31 : #include <limits>
32 : #include <new>
33 : #include <stdexcept>
34 :
35 : using namespace flatbuffers;
36 : using namespace FlatGeobuf;
37 : using namespace ogr_flatgeobuf;
38 :
39 0 : static OGRErr CPLErrorMemoryAllocation(const char *message)
40 : {
41 0 : CPLError(CE_Failure, CPLE_AppDefined, "Could not allocate memory: %s",
42 : message);
43 0 : return OGRERR_NOT_ENOUGH_MEMORY;
44 : }
45 :
46 0 : static OGRErr CPLErrorIO(const char *message)
47 : {
48 0 : CPLError(CE_Failure, CPLE_AppDefined, "Unexpected I/O failure: %s",
49 : message);
50 0 : return OGRERR_FAILURE;
51 : }
52 :
53 150 : OGRFlatGeobufLayer::OGRFlatGeobufLayer(const Header *poHeader, GByte *headerBuf,
54 : const char *pszFilename, VSILFILE *poFp,
55 150 : uint64_t offset)
56 : {
57 150 : m_poHeader = poHeader;
58 150 : CPLAssert(poHeader);
59 150 : m_headerBuf = headerBuf;
60 150 : CPLAssert(pszFilename);
61 150 : if (pszFilename)
62 150 : m_osFilename = pszFilename;
63 150 : m_poFp = poFp;
64 150 : m_offsetFeatures = offset;
65 150 : m_offset = offset;
66 150 : m_create = false;
67 :
68 150 : m_featuresCount = m_poHeader->features_count();
69 150 : m_geometryType = m_poHeader->geometry_type();
70 150 : m_indexNodeSize = m_poHeader->index_node_size();
71 150 : m_hasZ = m_poHeader->has_z();
72 150 : m_hasM = m_poHeader->has_m();
73 150 : m_hasT = m_poHeader->has_t();
74 150 : const auto envelope = m_poHeader->envelope();
75 269 : if (envelope && envelope->size() == 4 && std::isfinite((*envelope)[0]) &&
76 553 : std::isfinite((*envelope)[1]) && std::isfinite((*envelope)[2]) &&
77 134 : std::isfinite((*envelope)[3]))
78 : {
79 134 : m_sExtent.MinX = (*envelope)[0];
80 134 : m_sExtent.MinY = (*envelope)[1];
81 134 : m_sExtent.MaxX = (*envelope)[2];
82 134 : m_sExtent.MaxY = (*envelope)[3];
83 : }
84 :
85 150 : CPLDebugOnly("FlatGeobuf", "geometryType: %d, hasZ: %d, hasM: %d, hasT: %d",
86 : (int)m_geometryType, m_hasZ, m_hasM, m_hasT);
87 :
88 150 : const auto crs = m_poHeader->crs();
89 150 : if (crs != nullptr)
90 : {
91 16 : m_poSRS = new OGRSpatialReference();
92 16 : m_poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
93 16 : const auto org = crs->org();
94 16 : const auto code = crs->code();
95 16 : const auto crs_wkt = crs->wkt();
96 32 : CPLString wkt = crs_wkt ? crs_wkt->c_str() : "";
97 16 : double dfCoordEpoch = 0;
98 16 : if (STARTS_WITH_CI(wkt.c_str(), "COORDINATEMETADATA["))
99 : {
100 3 : size_t nPos = std::string::npos;
101 : // We don't want to match FRAMEEPOCH[
102 0 : for (const char *pszEpoch :
103 3 : {",EPOCH[", " EPOCH[", "\tEPOCH[", "\nEPOCH[", "\rEPOCH["})
104 : {
105 3 : nPos = wkt.ifind(pszEpoch);
106 3 : if (nPos != std::string::npos)
107 3 : break;
108 : }
109 3 : if (nPos != std::string::npos)
110 : {
111 3 : dfCoordEpoch = CPLAtof(wkt.c_str() + nPos + strlen(",EPOCH["));
112 3 : wkt.resize(nPos);
113 3 : wkt = wkt.substr(strlen("COORDINATEMETADATA["));
114 : }
115 : }
116 :
117 16 : if ((org == nullptr || EQUAL(org->c_str(), "EPSG")) && code != 0)
118 : {
119 11 : m_poSRS->importFromEPSG(code);
120 : }
121 5 : else if (org && code != 0)
122 : {
123 2 : CPLString osCode;
124 1 : osCode.Printf("%s:%d", org->c_str(), code);
125 1 : if (m_poSRS->SetFromUserInput(
126 : osCode.c_str(),
127 : OGRSpatialReference::
128 1 : SET_FROM_USER_INPUT_LIMITATIONS_get()) != OGRERR_NONE &&
129 0 : !wkt.empty())
130 : {
131 0 : m_poSRS->importFromWkt(wkt.c_str());
132 1 : }
133 : }
134 4 : else if (!wkt.empty())
135 : {
136 3 : m_poSRS->importFromWkt(wkt.c_str());
137 : }
138 :
139 16 : if (dfCoordEpoch > 0)
140 3 : m_poSRS->SetCoordinateEpoch(dfCoordEpoch);
141 : }
142 :
143 150 : m_eGType = getOGRwkbGeometryType();
144 :
145 150 : if (const auto title = poHeader->title())
146 2 : SetMetadataItem("TITLE", title->c_str());
147 :
148 150 : if (const auto description = poHeader->description())
149 2 : SetMetadataItem("DESCRIPTION", description->c_str());
150 :
151 150 : if (const auto metadata = poHeader->metadata())
152 : {
153 8 : CPLJSONDocument oDoc;
154 8 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
155 12 : if (oDoc.LoadMemory(metadata->c_str()) &&
156 8 : oDoc.GetRoot().GetType() == CPLJSONObject::Type::Object)
157 : {
158 10 : for (const auto &oItem : oDoc.GetRoot().GetChildren())
159 : {
160 6 : if (oItem.GetType() == CPLJSONObject::Type::String)
161 : {
162 6 : SetMetadataItem(oItem.GetName().c_str(),
163 12 : oItem.ToString().c_str());
164 : }
165 : }
166 : }
167 : }
168 :
169 : const char *pszName =
170 150 : m_poHeader->name() ? m_poHeader->name()->c_str() : "unknown";
171 150 : m_poFeatureDefn = new OGRFeatureDefn(pszName);
172 150 : SetDescription(m_poFeatureDefn->GetName());
173 150 : m_poFeatureDefn->SetGeomType(wkbNone);
174 : auto poGeomFieldDefn =
175 300 : std::make_unique<OGRGeomFieldDefn>(nullptr, m_eGType);
176 150 : if (m_poSRS != nullptr)
177 16 : poGeomFieldDefn->SetSpatialRef(m_poSRS);
178 150 : m_poFeatureDefn->AddGeomFieldDefn(std::move(poGeomFieldDefn));
179 150 : readColumns();
180 150 : m_poFeatureDefn->Reference();
181 150 : }
182 :
183 171 : OGRFlatGeobufLayer::OGRFlatGeobufLayer(
184 : GDALDataset *poDS, const char *pszLayerName, const char *pszFilename,
185 : const OGRSpatialReference *poSpatialRef, OGRwkbGeometryType eGType,
186 : bool bCreateSpatialIndexAtClose, VSILFILE *poFpWrite,
187 171 : std::string &osTempFile, CSLConstList papszOptions)
188 : : m_eGType(eGType), m_poDS(poDS), m_create(true),
189 : m_bCreateSpatialIndexAtClose(bCreateSpatialIndexAtClose),
190 : m_poFpWrite(poFpWrite), m_aosCreationOption(papszOptions),
191 171 : m_osTempFile(osTempFile)
192 : {
193 171 : if (pszLayerName)
194 171 : m_osLayerName = pszLayerName;
195 171 : if (pszFilename)
196 171 : m_osFilename = pszFilename;
197 171 : m_geometryType = GeometryWriter::translateOGRwkbGeometryType(eGType);
198 171 : if wkbHasZ (eGType)
199 59 : m_hasZ = true;
200 171 : if wkbHasM (eGType)
201 42 : m_hasM = true;
202 171 : if (poSpatialRef)
203 9 : m_poSRS = poSpatialRef->Clone();
204 :
205 171 : CPLDebugOnly("FlatGeobuf", "geometryType: %d, hasZ: %d, hasM: %d, hasT: %d",
206 : (int)m_geometryType, m_hasZ, m_hasM, m_hasT);
207 :
208 171 : SetMetadataItem(OLMD_FID64, "YES");
209 :
210 171 : m_poFeatureDefn = new OGRFeatureDefn(pszLayerName);
211 171 : SetDescription(m_poFeatureDefn->GetName());
212 171 : m_poFeatureDefn->SetGeomType(eGType);
213 171 : m_poFeatureDefn->Reference();
214 171 : }
215 :
216 151 : OGRwkbGeometryType OGRFlatGeobufLayer::getOGRwkbGeometryType()
217 : {
218 151 : OGRwkbGeometryType ogrType = OGRwkbGeometryType::wkbUnknown;
219 151 : if (static_cast<int>(m_geometryType) <= 17)
220 151 : ogrType = (OGRwkbGeometryType)m_geometryType;
221 151 : if (m_hasZ)
222 45 : ogrType = wkbSetZ(ogrType);
223 151 : if (m_hasM)
224 42 : ogrType = wkbSetM(ogrType);
225 151 : return ogrType;
226 : }
227 :
228 131404 : static ColumnType toColumnType(const char *pszFieldName, OGRFieldType type,
229 : OGRFieldSubType subType)
230 : {
231 131404 : switch (type)
232 : {
233 131133 : case OGRFieldType::OFTInteger:
234 262258 : return subType == OFSTBoolean ? ColumnType::Bool
235 131125 : : subType == OFSTInt16 ? ColumnType::Short
236 131133 : : ColumnType::Int;
237 21 : case OGRFieldType::OFTInteger64:
238 21 : return ColumnType::Long;
239 76 : case OGRFieldType::OFTReal:
240 76 : return subType == OFSTFloat32 ? ColumnType::Float
241 76 : : ColumnType::Double;
242 94 : case OGRFieldType::OFTString:
243 94 : return ColumnType::String;
244 33 : case OGRFieldType::OFTDate:
245 33 : return ColumnType::DateTime;
246 0 : case OGRFieldType::OFTTime:
247 0 : return ColumnType::DateTime;
248 39 : case OGRFieldType::OFTDateTime:
249 39 : return ColumnType::DateTime;
250 8 : case OGRFieldType::OFTBinary:
251 8 : return ColumnType::Binary;
252 0 : default:
253 0 : CPLError(CE_Warning, CPLE_AppDefined,
254 : "toColumnType: %s field is of type %s, which is not "
255 : "handled natively. Falling back to String.",
256 : pszFieldName, OGRFieldDefn::GetFieldTypeName(type));
257 : }
258 0 : return ColumnType::String;
259 : }
260 :
261 65666 : static OGRFieldType toOGRFieldType(ColumnType type, OGRFieldSubType &eSubType)
262 : {
263 65666 : eSubType = OFSTNone;
264 65666 : switch (type)
265 : {
266 1 : case ColumnType::Byte:
267 1 : return OGRFieldType::OFTInteger;
268 1 : case ColumnType::UByte:
269 1 : return OGRFieldType::OFTInteger;
270 5 : case ColumnType::Bool:
271 5 : eSubType = OFSTBoolean;
272 5 : return OGRFieldType::OFTInteger;
273 5 : case ColumnType::Short:
274 5 : eSubType = OFSTInt16;
275 5 : return OGRFieldType::OFTInteger;
276 1 : case ColumnType::UShort:
277 1 : return OGRFieldType::OFTInteger;
278 65546 : case ColumnType::Int:
279 65546 : return OGRFieldType::OFTInteger;
280 1 : case ColumnType::UInt:
281 1 : return OGRFieldType::OFTInteger64;
282 19 : case ColumnType::Long:
283 19 : return OGRFieldType::OFTInteger64;
284 1 : case ColumnType::ULong:
285 1 : return OGRFieldType::OFTReal;
286 5 : case ColumnType::Float:
287 5 : eSubType = OFSTFloat32;
288 5 : return OGRFieldType::OFTReal;
289 25 : case ColumnType::Double:
290 25 : return OGRFieldType::OFTReal;
291 43 : case ColumnType::String:
292 43 : return OGRFieldType::OFTString;
293 1 : case ColumnType::Json:
294 1 : return OGRFieldType::OFTString;
295 7 : case ColumnType::DateTime:
296 7 : return OGRFieldType::OFTDateTime;
297 5 : case ColumnType::Binary:
298 5 : return OGRFieldType::OFTBinary;
299 : }
300 0 : return OGRFieldType::OFTString;
301 : }
302 :
303 : const std::vector<Offset<Column>>
304 314 : OGRFlatGeobufLayer::writeColumns(FlatBufferBuilder &fbb)
305 : {
306 314 : std::vector<Offset<Column>> columns;
307 131718 : for (int i = 0; i < m_poFeatureDefn->GetFieldCount(); i++)
308 : {
309 131404 : const auto field = m_poFeatureDefn->GetFieldDefn(i);
310 131404 : const auto name = field->GetNameRef();
311 : const auto columnType =
312 131404 : toColumnType(name, field->GetType(), field->GetSubType());
313 131404 : auto title = field->GetAlternativeNameRef();
314 131404 : if (EQUAL(title, ""))
315 131402 : title = nullptr;
316 131404 : const std::string &osComment = field->GetComment();
317 : const char *description =
318 131404 : !osComment.empty() ? osComment.c_str() : nullptr;
319 131404 : auto width = -1;
320 131404 : auto precision = -1;
321 131404 : auto scale = field->GetPrecision();
322 131404 : if (scale == 0)
323 131399 : scale = -1;
324 131404 : if (columnType == ColumnType::Float || columnType == ColumnType::Double)
325 76 : precision = field->GetWidth();
326 : else
327 131328 : width = field->GetWidth();
328 131404 : auto nullable = CPL_TO_BOOL(field->IsNullable());
329 131404 : auto unique = CPL_TO_BOOL(field->IsUnique());
330 131404 : auto primaryKey = false;
331 : // CPLDebugOnly("FlatGeobuf", "Create column %s (index %d)", name, i);
332 : const auto column =
333 : CreateColumnDirect(fbb, name, columnType, title, description, width,
334 131404 : precision, scale, nullable, unique, primaryKey);
335 131404 : columns.push_back(column);
336 : // CPLDebugOnly("FlatGeobuf", "DEBUG writeColumns: Created column %s
337 : // added as index %d", name, i);
338 : }
339 314 : CPLDebugOnly("FlatGeobuf", "Created %lu columns for writing",
340 : static_cast<long unsigned int>(columns.size()));
341 314 : return columns;
342 : }
343 :
344 150 : void OGRFlatGeobufLayer::readColumns()
345 : {
346 150 : const auto columns = m_poHeader->columns();
347 150 : if (columns == nullptr)
348 3 : return;
349 65813 : for (uint32_t i = 0; i < columns->size(); i++)
350 : {
351 65666 : const auto column = columns->Get(i);
352 65666 : const auto type = column->type();
353 65666 : const auto name = column->name()->c_str();
354 : const auto title =
355 65666 : column->title() != nullptr ? column->title()->c_str() : nullptr;
356 65666 : const auto width = column->width();
357 65666 : const auto precision = column->precision();
358 65666 : const auto scale = column->scale();
359 65666 : const auto nullable = column->nullable();
360 65666 : const auto unique = column->unique();
361 65666 : OGRFieldSubType eSubType = OFSTNone;
362 65666 : const auto ogrType = toOGRFieldType(column->type(), eSubType);
363 131332 : OGRFieldDefn field(name, ogrType);
364 65666 : field.SetSubType(eSubType);
365 65666 : field.SetAlternativeName(title);
366 65666 : if (column->description())
367 1 : field.SetComment(column->description()->str());
368 65666 : if (width != -1 && type != ColumnType::Float &&
369 : type != ColumnType::Double)
370 65606 : field.SetWidth(width);
371 65666 : if (precision != -1)
372 23 : field.SetWidth(precision);
373 65666 : field.SetPrecision(scale != -1 ? scale : 0);
374 65666 : field.SetNullable(nullable);
375 65666 : field.SetUnique(unique);
376 65666 : m_poFeatureDefn->AddFieldDefn(&field);
377 : // CPLDebugOnly("FlatGeobuf", "DEBUG readColumns: Read column %s added
378 : // as index %d", name, i);
379 : }
380 147 : CPLDebugOnly("FlatGeobuf",
381 : "Read %lu columns and added to feature definition",
382 : static_cast<long unsigned int>(columns->size()));
383 : }
384 :
385 314 : void OGRFlatGeobufLayer::writeHeader(VSILFILE *poFp, uint64_t featuresCount,
386 : std::vector<double> *extentVector)
387 : {
388 : size_t c;
389 314 : c = VSIFWriteL(&magicbytes, sizeof(magicbytes), 1, poFp);
390 314 : CPLDebugOnly("FlatGeobuf", "Wrote magicbytes (%lu bytes)",
391 : static_cast<long unsigned int>(c * sizeof(magicbytes)));
392 314 : m_writeOffset += sizeof(magicbytes);
393 :
394 628 : FlatBufferBuilder fbb;
395 314 : fbb.TrackMinAlign(8);
396 628 : auto columns = writeColumns(fbb);
397 :
398 314 : flatbuffers::Offset<Crs> crs = 0;
399 314 : if (m_poSRS)
400 : {
401 11 : int nAuthorityCode = 0;
402 11 : const char *pszAuthorityName = m_poSRS->GetAuthorityName(nullptr);
403 11 : if (pszAuthorityName == nullptr || strlen(pszAuthorityName) == 0)
404 : {
405 : // Try to force identify an EPSG code.
406 2 : m_poSRS->AutoIdentifyEPSG();
407 :
408 2 : pszAuthorityName = m_poSRS->GetAuthorityName(nullptr);
409 2 : if (pszAuthorityName != nullptr && EQUAL(pszAuthorityName, "EPSG"))
410 : {
411 : const char *pszAuthorityCode =
412 0 : m_poSRS->GetAuthorityCode(nullptr);
413 0 : if (pszAuthorityCode != nullptr && strlen(pszAuthorityCode) > 0)
414 : {
415 : /* Import 'clean' SRS */
416 0 : m_poSRS->importFromEPSG(atoi(pszAuthorityCode));
417 :
418 0 : pszAuthorityName = m_poSRS->GetAuthorityName(nullptr);
419 : }
420 : }
421 : }
422 11 : if (pszAuthorityName != nullptr && strlen(pszAuthorityName) > 0)
423 : {
424 : // For the root authority name 'EPSG', the authority code
425 : // should always be integral
426 9 : nAuthorityCode = atoi(m_poSRS->GetAuthorityCode(nullptr));
427 : }
428 :
429 : // Translate SRS to WKT.
430 11 : char *pszWKT = nullptr;
431 11 : const char *const apszOptionsWkt[] = {"FORMAT=WKT2_2019", nullptr};
432 11 : m_poSRS->exportToWkt(&pszWKT, apszOptionsWkt);
433 11 : if (pszWKT && pszWKT[0] == '\0')
434 : {
435 0 : CPLFree(pszWKT);
436 0 : pszWKT = nullptr;
437 : }
438 :
439 11 : if (pszWKT && m_poSRS->GetCoordinateEpoch() > 0)
440 : {
441 : std::string osCoordinateEpoch =
442 4 : CPLSPrintf("%f", m_poSRS->GetCoordinateEpoch());
443 2 : if (osCoordinateEpoch.find('.') != std::string::npos)
444 : {
445 12 : while (osCoordinateEpoch.back() == '0')
446 10 : osCoordinateEpoch.pop_back();
447 : }
448 :
449 2 : std::string osWKT("COORDINATEMETADATA[");
450 2 : osWKT += pszWKT;
451 2 : osWKT += ",EPOCH[";
452 2 : osWKT += osCoordinateEpoch;
453 2 : osWKT += "]]";
454 2 : CPLFree(pszWKT);
455 2 : pszWKT = CPLStrdup(osWKT.c_str());
456 : }
457 :
458 11 : if (pszWKT && !CPLIsUTF8(pszWKT, -1))
459 : {
460 0 : char *pszWKTtmp = CPLForceToASCII(pszWKT, -1, '?');
461 0 : CPLFree(pszWKT);
462 0 : pszWKT = pszWKTtmp;
463 : }
464 : crs = CreateCrsDirect(fbb, pszAuthorityName, nAuthorityCode,
465 11 : m_poSRS->GetName(), nullptr, pszWKT);
466 11 : CPLFree(pszWKT);
467 : }
468 :
469 628 : std::string osTitle(m_aosCreationOption.FetchNameValueDef("TITLE", ""));
470 : std::string osDescription(
471 628 : m_aosCreationOption.FetchNameValueDef("DESCRIPTION", ""));
472 628 : std::string osMetadata;
473 314 : CPLJSONObject oMetadataJSONObj;
474 314 : bool bEmptyMetadata = true;
475 628 : for (GDALMajorObject *poContainer :
476 : {static_cast<GDALMajorObject *>(this),
477 : static_cast<GDALMajorObject *>(
478 942 : m_poDS && m_poDS->GetLayerCount() == 1 ? m_poDS : nullptr)})
479 : {
480 628 : if (poContainer)
481 : {
482 624 : if (char **papszMD = poContainer->GetMetadata())
483 : {
484 636 : for (CSLConstList papszIter = papszMD; *papszIter; ++papszIter)
485 : {
486 322 : char *pszKey = nullptr;
487 : const char *pszValue =
488 322 : CPLParseNameValue(*papszIter, &pszKey);
489 322 : if (pszKey && pszValue && !EQUAL(pszKey, OLMD_FID64))
490 : {
491 15 : if (EQUAL(pszKey, "TITLE"))
492 : {
493 2 : if (osTitle.empty())
494 2 : osTitle = pszValue;
495 : }
496 13 : else if (EQUAL(pszKey, "DESCRIPTION"))
497 : {
498 2 : if (osDescription.empty())
499 2 : osDescription = pszValue;
500 : }
501 : else
502 : {
503 11 : bEmptyMetadata = false;
504 11 : oMetadataJSONObj.Add(pszKey, pszValue);
505 : }
506 : }
507 322 : CPLFree(pszKey);
508 : }
509 : }
510 : }
511 : }
512 314 : if (!bEmptyMetadata)
513 : {
514 : osMetadata =
515 7 : oMetadataJSONObj.Format(CPLJSONObject::PrettyFormat::Plain);
516 : }
517 :
518 : const auto header = CreateHeaderDirect(
519 314 : fbb, m_osLayerName.c_str(), extentVector, m_geometryType, m_hasZ,
520 314 : m_hasM, m_hasT, m_hasTM, &columns, featuresCount, m_indexNodeSize, crs,
521 318 : osTitle.empty() ? nullptr : osTitle.c_str(),
522 318 : osDescription.empty() ? nullptr : osDescription.c_str(),
523 946 : osMetadata.empty() ? nullptr : osMetadata.c_str());
524 314 : fbb.FinishSizePrefixed(header);
525 314 : c = VSIFWriteL(fbb.GetBufferPointer(), 1, fbb.GetSize(), poFp);
526 314 : CPLDebugOnly("FlatGeobuf", "Wrote header (%lu bytes)",
527 : static_cast<long unsigned int>(c));
528 314 : m_writeOffset += c;
529 314 : }
530 :
531 170 : static bool SupportsSeekWhileWriting(const std::string &osFilename)
532 : {
533 316 : return (!STARTS_WITH(osFilename.c_str(), "/vsi")) ||
534 316 : STARTS_WITH(osFilename.c_str(), "/vsimem/");
535 : }
536 :
537 171 : bool OGRFlatGeobufLayer::CreateFinalFile()
538 : {
539 : // no spatial index requested, we are (almost) done
540 171 : if (!m_bCreateSpatialIndexAtClose)
541 : {
542 13 : if (m_poFpWrite == nullptr || !SupportsSeekWhileWriting(m_osFilename))
543 : {
544 1 : return true;
545 : }
546 :
547 : // Rewrite header
548 12 : VSIFSeekL(m_poFpWrite, 0, SEEK_SET);
549 12 : m_writeOffset = 0;
550 12 : std::vector<double> extentVector;
551 12 : if (!m_sExtent.IsInit())
552 : {
553 1 : extentVector.resize(4, std::numeric_limits<double>::quiet_NaN());
554 : }
555 : else
556 : {
557 11 : extentVector.push_back(m_sExtent.MinX);
558 11 : extentVector.push_back(m_sExtent.MinY);
559 11 : extentVector.push_back(m_sExtent.MaxX);
560 11 : extentVector.push_back(m_sExtent.MaxY);
561 : }
562 12 : writeHeader(m_poFpWrite, m_featuresCount, &extentVector);
563 : // Sanity check to verify that the dummy header and the real header
564 : // have the same size.
565 12 : if (m_featuresCount)
566 : {
567 11 : CPLAssert(m_writeOffset == m_offsetAfterHeader);
568 : }
569 12 : CPL_IGNORE_RET_VAL(m_writeOffset); // otherwise checkers might tell the
570 : // member is not used
571 12 : return true;
572 : }
573 :
574 158 : m_poFp = VSIFOpenL(m_osFilename.c_str(), "wb");
575 158 : if (m_poFp == nullptr)
576 : {
577 0 : CPLError(CE_Failure, CPLE_OpenFailed, "Failed to create %s:\n%s",
578 0 : m_osFilename.c_str(), VSIStrerror(errno));
579 0 : return false;
580 : }
581 :
582 : // check if something has been written, if not write empty layer and bail
583 158 : if (m_writeOffset == 0 || m_featuresCount == 0)
584 : {
585 41 : CPLDebugOnly("FlatGeobuf", "Writing empty layer");
586 41 : writeHeader(m_poFp, 0, nullptr);
587 41 : return true;
588 : }
589 :
590 117 : CPLDebugOnly("FlatGeobuf", "Writing second pass sorted by spatial index");
591 :
592 117 : const uint64_t nTempFileSize = m_writeOffset;
593 117 : m_writeOffset = 0;
594 117 : m_indexNodeSize = 16;
595 :
596 : size_t c;
597 :
598 117 : if (m_featuresCount >= std::numeric_limits<size_t>::max() / 8)
599 : {
600 0 : CPLError(CE_Failure, CPLE_AppDefined,
601 : "Too many features for this architecture");
602 0 : return false;
603 : }
604 :
605 117 : NodeItem extent = calcExtent(m_featureItems);
606 234 : auto extentVector = extent.toVector();
607 :
608 117 : writeHeader(m_poFp, m_featuresCount, &extentVector);
609 :
610 117 : CPLDebugOnly("FlatGeobuf", "Sorting items for Packed R-tree");
611 117 : hilbertSort(m_featureItems);
612 117 : CPLDebugOnly("FlatGeobuf", "Calc new feature offsets");
613 117 : uint64_t featureOffset = 0;
614 282 : for (auto &item : m_featureItems)
615 : {
616 165 : item.nodeItem.offset = featureOffset;
617 165 : featureOffset += item.size;
618 : }
619 117 : CPLDebugOnly("FlatGeobuf", "Creating Packed R-tree");
620 117 : c = 0;
621 : try
622 : {
623 117 : const auto fillNodeItems = [this](NodeItem *dest)
624 : {
625 117 : size_t i = 0;
626 282 : for (const auto &featureItem : m_featureItems)
627 : {
628 165 : dest[i] = featureItem.nodeItem;
629 165 : ++i;
630 : }
631 234 : };
632 117 : PackedRTree tree(fillNodeItems, m_featureItems.size(), extent);
633 117 : CPLDebugOnly("FlatGeobuf", "PackedRTree extent %f, %f, %f, %f",
634 : extentVector[0], extentVector[1], extentVector[2],
635 : extentVector[3]);
636 117 : tree.streamWrite([this, &c](uint8_t *data, size_t size)
637 117 : { c += VSIFWriteL(data, 1, size, m_poFp); });
638 : }
639 0 : catch (const std::exception &e)
640 : {
641 0 : CPLError(CE_Failure, CPLE_AppDefined, "Create: %s", e.what());
642 0 : return false;
643 : }
644 117 : CPLDebugOnly("FlatGeobuf", "Wrote tree (%lu bytes)",
645 : static_cast<long unsigned int>(c));
646 117 : m_writeOffset += c;
647 :
648 117 : CPLDebugOnly("FlatGeobuf", "Writing feature buffers at offset %lu",
649 : static_cast<long unsigned int>(m_writeOffset));
650 :
651 117 : c = 0;
652 :
653 : // For temporary files not in memory, we use a batch strategy to write the
654 : // final file. That is to say we try to separate reads in the source
655 : // temporary file and writes in the target file as much as possible, and by
656 : // reading source features in increasing offset within a batch.
657 : const bool bUseBatchStrategy =
658 117 : !STARTS_WITH(m_osTempFile.c_str(), "/vsimem/");
659 117 : if (bUseBatchStrategy)
660 : {
661 : const uint32_t nMaxBufferSize = std::max(
662 7 : m_maxFeatureSize,
663 14 : static_cast<uint32_t>(std::min(
664 7 : static_cast<uint64_t>(100 * 1024 * 1024), nTempFileSize)));
665 7 : if (ensureFeatureBuf(nMaxBufferSize) != OGRERR_NONE)
666 0 : return false;
667 7 : uint32_t offsetInBuffer = 0;
668 :
669 : struct BatchItem
670 : {
671 : size_t featureIdx; // index of m_featureItems[]
672 : uint32_t offsetInBuffer;
673 : };
674 :
675 7 : std::vector<BatchItem> batch;
676 :
677 97 : const auto flushBatch = [this, &batch, &offsetInBuffer]()
678 : {
679 : // Sort by increasing source offset
680 7 : std::sort(batch.begin(), batch.end(),
681 88 : [this](const BatchItem &a, const BatchItem &b)
682 : {
683 44 : return m_featureItems[a.featureIdx].offset <
684 44 : m_featureItems[b.featureIdx].offset;
685 : });
686 :
687 : // Read source features
688 23 : for (const auto &batchItem : batch)
689 : {
690 16 : const auto &item = m_featureItems[batchItem.featureIdx];
691 16 : if (VSIFSeekL(m_poFpWrite, item.offset, SEEK_SET) == -1)
692 : {
693 0 : CPLErrorIO("seeking to temp feature location");
694 0 : return false;
695 : }
696 32 : if (VSIFReadL(m_featureBuf + batchItem.offsetInBuffer, 1,
697 16 : item.size, m_poFpWrite) != item.size)
698 : {
699 0 : CPLErrorIO("reading temp feature");
700 0 : return false;
701 : }
702 : }
703 :
704 : // Write target features
705 14 : if (offsetInBuffer > 0 &&
706 7 : VSIFWriteL(m_featureBuf, 1, offsetInBuffer, m_poFp) !=
707 7 : offsetInBuffer)
708 : {
709 0 : CPLErrorIO("writing feature");
710 0 : return false;
711 : }
712 :
713 7 : batch.clear();
714 7 : offsetInBuffer = 0;
715 7 : return true;
716 7 : };
717 :
718 23 : for (size_t i = 0; i < m_featuresCount; i++)
719 : {
720 16 : const auto &featureItem = m_featureItems[i];
721 16 : const auto featureSize = featureItem.size;
722 :
723 16 : if (offsetInBuffer + featureSize > m_featureBufSize)
724 : {
725 0 : if (!flushBatch())
726 : {
727 0 : return false;
728 : }
729 : }
730 :
731 : BatchItem bachItem;
732 16 : bachItem.offsetInBuffer = offsetInBuffer;
733 16 : bachItem.featureIdx = i;
734 16 : batch.emplace_back(bachItem);
735 16 : offsetInBuffer += featureSize;
736 16 : c += featureSize;
737 : }
738 :
739 7 : if (!flushBatch())
740 : {
741 0 : return false;
742 : }
743 : }
744 : else
745 : {
746 110 : const auto err = ensureFeatureBuf(m_maxFeatureSize);
747 110 : if (err != OGRERR_NONE)
748 0 : return false;
749 :
750 259 : for (const auto &featureItem : m_featureItems)
751 : {
752 149 : const auto featureSize = featureItem.size;
753 :
754 : // CPLDebugOnly("FlatGeobuf", "featureItem.offset: %lu",
755 : // static_cast<long unsigned int>(featureItem.offset));
756 : // CPLDebugOnly("FlatGeobuf", "featureSize: %d", featureSize);
757 149 : if (VSIFSeekL(m_poFpWrite, featureItem.offset, SEEK_SET) == -1)
758 : {
759 0 : CPLErrorIO("seeking to temp feature location");
760 0 : return false;
761 : }
762 149 : if (VSIFReadL(m_featureBuf, 1, featureSize, m_poFpWrite) !=
763 149 : featureSize)
764 : {
765 0 : CPLErrorIO("reading temp feature");
766 0 : return false;
767 : }
768 149 : if (VSIFWriteL(m_featureBuf, 1, featureSize, m_poFp) != featureSize)
769 : {
770 0 : CPLErrorIO("writing feature");
771 0 : return false;
772 : }
773 149 : c += featureSize;
774 : }
775 : }
776 :
777 117 : CPLDebugOnly("FlatGeobuf", "Wrote feature buffers (%lu bytes)",
778 : static_cast<long unsigned int>(c));
779 117 : m_writeOffset += c;
780 :
781 117 : CPLDebugOnly("FlatGeobuf", "Now at offset %lu",
782 : static_cast<long unsigned int>(m_writeOffset));
783 :
784 117 : return true;
785 : }
786 :
787 642 : OGRFlatGeobufLayer::~OGRFlatGeobufLayer()
788 : {
789 321 : OGRFlatGeobufLayer::Close();
790 :
791 321 : if (m_poFeatureDefn)
792 321 : m_poFeatureDefn->Release();
793 :
794 321 : if (m_poSRS)
795 25 : m_poSRS->Release();
796 :
797 321 : if (m_featureBuf)
798 252 : VSIFree(m_featureBuf);
799 :
800 321 : if (m_headerBuf)
801 150 : VSIFree(m_headerBuf);
802 642 : }
803 :
804 639 : CPLErr OGRFlatGeobufLayer::Close()
805 : {
806 639 : CPLErr eErr = CE_None;
807 :
808 639 : if (m_create)
809 : {
810 171 : if (!CreateFinalFile())
811 0 : eErr = CE_Failure;
812 171 : m_create = false;
813 : }
814 :
815 639 : if (m_poFp)
816 : {
817 308 : if (VSIFCloseL(m_poFp) != 0)
818 0 : eErr = CE_Failure;
819 308 : m_poFp = nullptr;
820 : }
821 :
822 639 : if (m_poFpWrite)
823 : {
824 171 : if (VSIFCloseL(m_poFpWrite) != 0)
825 0 : eErr = CE_Failure;
826 171 : m_poFpWrite = nullptr;
827 : }
828 :
829 639 : if (!m_osTempFile.empty())
830 : {
831 171 : VSIUnlink(m_osTempFile.c_str());
832 171 : m_osTempFile.clear();
833 : }
834 :
835 639 : return eErr;
836 : }
837 :
838 9 : OGRErr OGRFlatGeobufLayer::readFeatureOffset(uint64_t index,
839 : uint64_t &featureOffset)
840 : {
841 : try
842 : {
843 : const auto treeSize =
844 9 : PackedRTree::size(m_featuresCount, m_indexNodeSize);
845 : const auto levelBounds =
846 18 : PackedRTree::generateLevelBounds(m_featuresCount, m_indexNodeSize);
847 : const auto bottomLevelOffset =
848 9 : m_offset - treeSize +
849 9 : (levelBounds.front().first * sizeof(NodeItem));
850 9 : const auto nodeItemOffset =
851 9 : bottomLevelOffset + (index * sizeof(NodeItem));
852 9 : const auto featureOffsetOffset = nodeItemOffset + (sizeof(double) * 4);
853 9 : if (VSIFSeekL(m_poFp, featureOffsetOffset, SEEK_SET) == -1)
854 0 : return CPLErrorIO("seeking feature offset");
855 9 : if (VSIFReadL(&featureOffset, sizeof(uint64_t), 1, m_poFp) != 1)
856 0 : return CPLErrorIO("reading feature offset");
857 : #if !CPL_IS_LSB
858 : CPL_LSBPTR64(&featureOffset);
859 : #endif
860 9 : return OGRERR_NONE;
861 : }
862 0 : catch (const std::exception &e)
863 : {
864 0 : CPLError(CE_Failure, CPLE_AppDefined,
865 0 : "Failed to calculate tree size: %s", e.what());
866 0 : return OGRERR_FAILURE;
867 : }
868 : }
869 :
870 14 : OGRFeature *OGRFlatGeobufLayer::GetFeature(GIntBig nFeatureId)
871 : {
872 14 : if (m_indexNodeSize == 0)
873 : {
874 0 : return OGRLayer::GetFeature(nFeatureId);
875 : }
876 : else
877 : {
878 14 : if (nFeatureId < 0 ||
879 12 : static_cast<uint64_t>(nFeatureId) >= m_featuresCount)
880 : {
881 5 : return nullptr;
882 : }
883 9 : ResetReading();
884 9 : m_ignoreSpatialFilter = true;
885 9 : m_ignoreAttributeFilter = true;
886 : uint64_t featureOffset;
887 9 : const auto err = readFeatureOffset(nFeatureId, featureOffset);
888 9 : if (err != OGRERR_NONE)
889 : {
890 0 : CPLError(CE_Failure, CPLE_AppDefined,
891 : "Unexpected error reading feature offset from id");
892 0 : return nullptr;
893 : }
894 9 : m_offset = m_offsetFeatures + featureOffset;
895 9 : OGRFeature *poFeature = GetNextFeature();
896 9 : if (poFeature != nullptr)
897 9 : poFeature->SetFID(nFeatureId);
898 9 : ResetReading();
899 9 : return poFeature;
900 : }
901 : }
902 :
903 654 : OGRErr OGRFlatGeobufLayer::readIndex()
904 : {
905 654 : if (m_queriedSpatialIndex || !m_poFilterGeom)
906 474 : return OGRERR_NONE;
907 360 : if (m_sFilterEnvelope.IsInit() && m_sExtent.IsInit() &&
908 114 : m_sFilterEnvelope.MinX <= m_sExtent.MinX &&
909 84 : m_sFilterEnvelope.MinY <= m_sExtent.MinY &&
910 432 : m_sFilterEnvelope.MaxX >= m_sExtent.MaxX &&
911 72 : m_sFilterEnvelope.MaxY >= m_sExtent.MaxY)
912 72 : return OGRERR_NONE;
913 108 : const auto indexNodeSize = m_poHeader->index_node_size();
914 108 : if (indexNodeSize == 0)
915 74 : return OGRERR_NONE;
916 34 : const auto featuresCount = m_poHeader->features_count();
917 34 : if (featuresCount == 0)
918 0 : return OGRERR_NONE;
919 :
920 34 : if (VSIFSeekL(m_poFp, sizeof(magicbytes), SEEK_SET) ==
921 : -1) // skip magic bytes
922 0 : return CPLErrorIO("seeking past magic bytes");
923 : uoffset_t headerSize;
924 34 : if (VSIFReadL(&headerSize, sizeof(uoffset_t), 1, m_poFp) != 1)
925 0 : return CPLErrorIO("reading header size");
926 34 : CPL_LSBPTR32(&headerSize);
927 :
928 : try
929 : {
930 : const auto treeSize =
931 34 : indexNodeSize > 0 ? PackedRTree::size(featuresCount) : 0;
932 34 : if (treeSize > 0 && m_poFilterGeom && !m_ignoreSpatialFilter)
933 : {
934 33 : CPLDebugOnly("FlatGeobuf", "Attempting spatial index query");
935 33 : OGREnvelope env;
936 33 : m_poFilterGeom->getEnvelope(&env);
937 33 : NodeItem n{env.MinX, env.MinY, env.MaxX, env.MaxY, 0};
938 33 : CPLDebugOnly("FlatGeobuf", "Spatial index search on %f,%f,%f,%f",
939 : env.MinX, env.MinY, env.MaxX, env.MaxY);
940 33 : const auto treeOffset =
941 33 : sizeof(magicbytes) + sizeof(uoffset_t) + headerSize;
942 : const auto readNode =
943 122 : [this, treeOffset](uint8_t *buf, size_t i, size_t s)
944 : {
945 61 : if (VSIFSeekL(m_poFp, treeOffset + i, SEEK_SET) == -1)
946 0 : throw std::runtime_error("I/O seek failure");
947 61 : if (VSIFReadL(buf, 1, s, m_poFp) != s)
948 0 : throw std::runtime_error("I/O read file");
949 61 : };
950 66 : m_foundItems = PackedRTree::streamSearch(
951 33 : featuresCount, indexNodeSize, n, readNode);
952 33 : m_featuresCount = m_foundItems.size();
953 33 : CPLDebugOnly("FlatGeobuf",
954 : "%lu features found in spatial index search",
955 : static_cast<long unsigned int>(m_featuresCount));
956 :
957 33 : m_queriedSpatialIndex = true;
958 : }
959 : }
960 0 : catch (const std::exception &e)
961 : {
962 0 : CPLError(CE_Failure, CPLE_AppDefined,
963 0 : "readIndex: Unexpected failure: %s", e.what());
964 0 : return OGRERR_FAILURE;
965 : }
966 :
967 34 : return OGRERR_NONE;
968 : }
969 :
970 29 : GIntBig OGRFlatGeobufLayer::GetFeatureCount(int bForce)
971 : {
972 29 : if (m_poFilterGeom != nullptr || m_poAttrQuery != nullptr ||
973 15 : m_featuresCount == 0)
974 17 : return OGRLayer::GetFeatureCount(bForce);
975 : else
976 12 : return m_featuresCount;
977 : }
978 :
979 : /************************************************************************/
980 : /* ParseDateTime() */
981 : /************************************************************************/
982 :
983 25 : static inline bool ParseDateTime(std::string_view sInput, OGRField *psField)
984 : {
985 48 : return OGRParseDateTimeYYYYMMDDTHHMMSSZ(sInput, psField) ||
986 48 : OGRParseDateTimeYYYYMMDDTHHMMSSsssZ(sInput, psField);
987 : }
988 :
989 636 : OGRFeature *OGRFlatGeobufLayer::GetNextFeature()
990 : {
991 636 : if (m_create)
992 16 : return nullptr;
993 :
994 : while (true)
995 : {
996 690 : if (m_featuresCount > 0 && m_featuresPos >= m_featuresCount)
997 : {
998 76 : CPLDebugOnly("FlatGeobuf", "GetNextFeature: iteration end at %lu",
999 : static_cast<long unsigned int>(m_featuresPos));
1000 620 : return nullptr;
1001 : }
1002 :
1003 614 : if (readIndex() != OGRERR_NONE)
1004 : {
1005 0 : return nullptr;
1006 : }
1007 :
1008 614 : if (m_queriedSpatialIndex && m_featuresCount == 0)
1009 : {
1010 5 : CPLDebugOnly("FlatGeobuf", "GetNextFeature: no features found");
1011 5 : return nullptr;
1012 : }
1013 :
1014 609 : auto poFeature = std::make_unique<OGRFeature>(m_poFeatureDefn);
1015 609 : if (parseFeature(poFeature.get()) != OGRERR_NONE)
1016 : {
1017 4 : CPLError(CE_Failure, CPLE_AppDefined,
1018 : "Fatal error parsing feature");
1019 4 : return nullptr;
1020 : }
1021 :
1022 605 : if (VSIFEofL(m_poFp) || VSIFErrorL(m_poFp))
1023 : {
1024 11 : CPLDebug("FlatGeobuf", "GetNextFeature: iteration end due to EOF");
1025 11 : return nullptr;
1026 : }
1027 :
1028 594 : m_featuresPos++;
1029 :
1030 241 : if ((m_poFilterGeom == nullptr || m_ignoreSpatialFilter ||
1031 1390 : FilterGeometry(poFeature->GetGeometryRef())) &&
1032 556 : (m_poAttrQuery == nullptr || m_ignoreAttributeFilter ||
1033 71 : m_poAttrQuery->Evaluate(poFeature.get())))
1034 524 : return poFeature.release();
1035 70 : }
1036 : }
1037 :
1038 828 : OGRErr OGRFlatGeobufLayer::ensureFeatureBuf(uint32_t featureSize)
1039 : {
1040 828 : if (m_featureBufSize == 0)
1041 : {
1042 252 : const auto newBufSize = std::max(1024U * 32U, featureSize);
1043 252 : CPLDebugOnly("FlatGeobuf", "ensureFeatureBuf: newBufSize: %d",
1044 : newBufSize);
1045 252 : m_featureBuf = static_cast<GByte *>(VSIMalloc(newBufSize));
1046 252 : if (m_featureBuf == nullptr)
1047 0 : return CPLErrorMemoryAllocation("initial feature buffer");
1048 252 : m_featureBufSize = newBufSize;
1049 : }
1050 576 : else if (m_featureBufSize < featureSize)
1051 : {
1052 : // Do not increase this x2 factor without modifying
1053 : // feature_max_buffer_size
1054 0 : const auto newBufSize = std::max(m_featureBufSize * 2, featureSize);
1055 0 : CPLDebugOnly("FlatGeobuf", "ensureFeatureBuf: newBufSize: %d",
1056 : newBufSize);
1057 : const auto featureBuf =
1058 0 : static_cast<GByte *>(VSIRealloc(m_featureBuf, newBufSize));
1059 0 : if (featureBuf == nullptr)
1060 0 : return CPLErrorMemoryAllocation("feature buffer resize");
1061 0 : m_featureBuf = featureBuf;
1062 0 : m_featureBufSize = newBufSize;
1063 : }
1064 828 : return OGRERR_NONE;
1065 : }
1066 :
1067 609 : OGRErr OGRFlatGeobufLayer::parseFeature(OGRFeature *poFeature)
1068 : {
1069 : GIntBig fid;
1070 609 : auto seek = false;
1071 609 : if (m_queriedSpatialIndex && !m_ignoreSpatialFilter)
1072 : {
1073 108 : const auto item = m_foundItems[m_featuresPos];
1074 108 : m_offset = m_offsetFeatures + item.offset;
1075 108 : fid = item.index;
1076 108 : seek = true;
1077 : }
1078 : else
1079 : {
1080 501 : fid = m_featuresPos;
1081 : }
1082 609 : poFeature->SetFID(fid);
1083 :
1084 : // CPLDebugOnly("FlatGeobuf", "m_featuresPos: %lu", static_cast<long
1085 : // unsigned int>(m_featuresPos));
1086 :
1087 609 : if (m_featuresPos == 0)
1088 228 : seek = true;
1089 :
1090 609 : if (seek && VSIFSeekL(m_poFp, m_offset, SEEK_SET) == -1)
1091 : {
1092 0 : if (VSIFEofL(m_poFp))
1093 0 : return OGRERR_NONE;
1094 0 : return CPLErrorIO("seeking to feature location");
1095 : }
1096 : uint32_t featureSize;
1097 609 : if (VSIFReadL(&featureSize, sizeof(featureSize), 1, m_poFp) != 1)
1098 : {
1099 11 : if (VSIFEofL(m_poFp))
1100 11 : return OGRERR_NONE;
1101 0 : return CPLErrorIO("reading feature size");
1102 : }
1103 598 : CPL_LSBPTR32(&featureSize);
1104 :
1105 : // Sanity check to avoid allocated huge amount of memory on corrupted
1106 : // feature
1107 598 : if (featureSize > 100 * 1024 * 1024)
1108 : {
1109 0 : if (featureSize > feature_max_buffer_size)
1110 0 : return CPLErrorInvalidSize("feature");
1111 :
1112 0 : if (m_nFileSize == 0)
1113 : {
1114 : VSIStatBufL sStatBuf;
1115 0 : if (VSIStatL(m_osFilename.c_str(), &sStatBuf) == 0)
1116 : {
1117 0 : m_nFileSize = sStatBuf.st_size;
1118 : }
1119 : }
1120 0 : if (m_offset + featureSize > m_nFileSize)
1121 : {
1122 0 : return CPLErrorIO("reading feature size");
1123 : }
1124 : }
1125 :
1126 598 : const auto err = ensureFeatureBuf(featureSize);
1127 598 : if (err != OGRERR_NONE)
1128 0 : return err;
1129 598 : if (VSIFReadL(m_featureBuf, 1, featureSize, m_poFp) != featureSize)
1130 0 : return CPLErrorIO("reading feature");
1131 598 : m_offset += featureSize + sizeof(featureSize);
1132 :
1133 598 : if (m_bVerifyBuffers)
1134 : {
1135 598 : Verifier v(m_featureBuf, featureSize);
1136 598 : const auto ok = VerifyFeatureBuffer(v);
1137 598 : if (!ok)
1138 : {
1139 0 : CPLError(CE_Failure, CPLE_AppDefined, "Buffer verification failed");
1140 0 : CPLDebugOnly("FlatGeobuf", "m_offset: %lu",
1141 : static_cast<long unsigned int>(m_offset));
1142 0 : CPLDebugOnly("FlatGeobuf", "m_featuresPos: %lu",
1143 : static_cast<long unsigned int>(m_featuresPos));
1144 0 : CPLDebugOnly("FlatGeobuf", "featureSize: %d", featureSize);
1145 0 : return OGRERR_CORRUPT_DATA;
1146 : }
1147 : }
1148 :
1149 598 : const auto feature = GetRoot<Feature>(m_featureBuf);
1150 598 : const auto geometry = feature->geometry();
1151 598 : if (!m_poFeatureDefn->IsGeometryIgnored() && geometry != nullptr)
1152 : {
1153 586 : auto geometryType = m_geometryType;
1154 586 : if (geometryType == GeometryType::Unknown)
1155 6 : geometryType = geometry->type();
1156 : OGRGeometry *poOGRGeometry =
1157 586 : GeometryReader(geometry, geometryType, m_hasZ, m_hasM).read();
1158 586 : if (poOGRGeometry == nullptr)
1159 : {
1160 4 : CPLError(CE_Failure, CPLE_AppDefined, "Failed to read geometry");
1161 4 : return OGRERR_CORRUPT_DATA;
1162 : }
1163 : // #ifdef DEBUG
1164 : // char *wkt;
1165 : // poOGRGeometry->exportToWkt(&wkt);
1166 : // CPLDebugOnly("FlatGeobuf", "readGeometry as wkt: %s",
1167 : // wkt);
1168 : // #endif
1169 582 : if (m_poSRS != nullptr)
1170 318 : poOGRGeometry->assignSpatialReference(m_poSRS);
1171 582 : poFeature->SetGeometryDirectly(poOGRGeometry);
1172 : }
1173 :
1174 594 : const auto properties = feature->properties();
1175 594 : if (properties != nullptr)
1176 : {
1177 497 : const auto data = properties->data();
1178 497 : const auto size = properties->size();
1179 :
1180 : // CPLDebugOnly("FlatGeobuf", "DEBUG parseFeature: size: %lu",
1181 : // static_cast<long unsigned int>(size));
1182 :
1183 : // CPLDebugOnly("FlatGeobuf", "properties->size: %d", size);
1184 497 : uoffset_t offset = 0;
1185 : // size must be at least large enough to contain
1186 : // a single column index and smallest value type
1187 497 : if (size > 0 && size < (sizeof(uint16_t) + sizeof(uint8_t)))
1188 0 : return CPLErrorInvalidSize("property value");
1189 67276 : while (offset + 1 < size)
1190 : {
1191 66779 : if (offset + sizeof(uint16_t) > size)
1192 0 : return CPLErrorInvalidSize("property value");
1193 : uint16_t i;
1194 66779 : memcpy(&i, data + offset, sizeof(i));
1195 66779 : CPL_LSBPTR16(&i);
1196 : // CPLDebugOnly("FlatGeobuf", "DEBUG parseFeature: i: %hu", i);
1197 66779 : offset += sizeof(uint16_t);
1198 : // CPLDebugOnly("FlatGeobuf", "DEBUG parseFeature: offset: %du",
1199 : // offset);
1200 : // TODO: use columns from feature if defined
1201 66779 : const auto columns = m_poHeader->columns();
1202 66779 : if (columns == nullptr)
1203 : {
1204 0 : CPLErrorInvalidPointer("columns");
1205 0 : return OGRERR_CORRUPT_DATA;
1206 : }
1207 66779 : if (i >= columns->size())
1208 : {
1209 0 : CPLError(CE_Failure, CPLE_AppDefined,
1210 : "Column index %hu out of range", i);
1211 0 : return OGRERR_CORRUPT_DATA;
1212 : }
1213 66779 : const auto column = columns->Get(i);
1214 66779 : const auto type = column->type();
1215 66779 : const auto isIgnored = poFeature->GetFieldDefnRef(i)->IsIgnored();
1216 66779 : const auto ogrField = poFeature->GetRawFieldRef(i);
1217 66779 : if (!OGR_RawField_IsUnset(ogrField))
1218 : {
1219 0 : CPLError(CE_Failure, CPLE_AppDefined,
1220 : "Field %d set more than once", i);
1221 0 : return OGRERR_CORRUPT_DATA;
1222 : }
1223 :
1224 66779 : switch (type)
1225 : {
1226 5 : case ColumnType::Bool:
1227 5 : if (offset + sizeof(unsigned char) > size)
1228 0 : return CPLErrorInvalidSize("bool value");
1229 5 : if (!isIgnored)
1230 : {
1231 5 : ogrField->Integer = *(data + offset);
1232 : }
1233 5 : offset += sizeof(unsigned char);
1234 5 : break;
1235 :
1236 1 : case ColumnType::Byte:
1237 1 : if (offset + sizeof(signed char) > size)
1238 0 : return CPLErrorInvalidSize("byte value");
1239 1 : if (!isIgnored)
1240 : {
1241 1 : ogrField->Integer =
1242 1 : *reinterpret_cast<const signed char *>(data +
1243 1 : offset);
1244 : }
1245 1 : offset += sizeof(signed char);
1246 1 : break;
1247 :
1248 1 : case ColumnType::UByte:
1249 1 : if (offset + sizeof(unsigned char) > size)
1250 0 : return CPLErrorInvalidSize("ubyte value");
1251 1 : if (!isIgnored)
1252 : {
1253 1 : ogrField->Integer =
1254 1 : *reinterpret_cast<const unsigned char *>(data +
1255 1 : offset);
1256 : }
1257 1 : offset += sizeof(unsigned char);
1258 1 : break;
1259 :
1260 5 : case ColumnType::Short:
1261 5 : if (offset + sizeof(int16_t) > size)
1262 0 : return CPLErrorInvalidSize("short value");
1263 5 : if (!isIgnored)
1264 : {
1265 : short s;
1266 5 : memcpy(&s, data + offset, sizeof(int16_t));
1267 5 : CPL_LSBPTR16(&s);
1268 5 : ogrField->Integer = s;
1269 : }
1270 5 : offset += sizeof(int16_t);
1271 5 : break;
1272 :
1273 1 : case ColumnType::UShort:
1274 1 : if (offset + sizeof(uint16_t) > size)
1275 0 : return CPLErrorInvalidSize("ushort value");
1276 1 : if (!isIgnored)
1277 : {
1278 : uint16_t s;
1279 1 : memcpy(&s, data + offset, sizeof(uint16_t));
1280 1 : CPL_LSBPTR16(&s);
1281 1 : ogrField->Integer = s;
1282 : }
1283 1 : offset += sizeof(uint16_t);
1284 1 : break;
1285 :
1286 65549 : case ColumnType::Int:
1287 65549 : if (offset + sizeof(int32_t) > size)
1288 0 : return CPLErrorInvalidSize("int32 value");
1289 65549 : if (!isIgnored)
1290 : {
1291 65549 : memcpy(&ogrField->Integer, data + offset,
1292 : sizeof(int32_t));
1293 65549 : CPL_LSBPTR32(&ogrField->Integer);
1294 : }
1295 65549 : offset += sizeof(int32_t);
1296 65549 : break;
1297 :
1298 1 : case ColumnType::UInt:
1299 1 : if (offset + sizeof(uint32_t) > size)
1300 0 : return CPLErrorInvalidSize("uint value");
1301 1 : if (!isIgnored)
1302 : {
1303 : uint32_t v;
1304 1 : memcpy(&v, data + offset, sizeof(int32_t));
1305 1 : CPL_LSBPTR32(&v);
1306 1 : ogrField->Integer64 = v;
1307 : }
1308 1 : offset += sizeof(int32_t);
1309 1 : break;
1310 :
1311 445 : case ColumnType::Long:
1312 445 : if (offset + sizeof(int64_t) > size)
1313 0 : return CPLErrorInvalidSize("int64 value");
1314 445 : if (!isIgnored)
1315 : {
1316 445 : memcpy(&ogrField->Integer64, data + offset,
1317 : sizeof(int64_t));
1318 445 : CPL_LSBPTR64(&ogrField->Integer64);
1319 : }
1320 445 : offset += sizeof(int64_t);
1321 445 : break;
1322 :
1323 1 : case ColumnType::ULong:
1324 1 : if (offset + sizeof(uint64_t) > size)
1325 0 : return CPLErrorInvalidSize("uint64 value");
1326 1 : if (!isIgnored)
1327 : {
1328 : uint64_t v;
1329 1 : memcpy(&v, data + offset, sizeof(v));
1330 1 : CPL_LSBPTR64(&v);
1331 1 : ogrField->Real = static_cast<double>(v);
1332 : }
1333 1 : offset += sizeof(int64_t);
1334 1 : break;
1335 :
1336 4 : case ColumnType::Float:
1337 4 : if (offset + sizeof(float) > size)
1338 0 : return CPLErrorInvalidSize("float value");
1339 4 : if (!isIgnored)
1340 : {
1341 : float f;
1342 4 : memcpy(&f, data + offset, sizeof(float));
1343 4 : CPL_LSBPTR32(&f);
1344 4 : ogrField->Real = f;
1345 : }
1346 4 : offset += sizeof(float);
1347 4 : break;
1348 :
1349 365 : case ColumnType::Double:
1350 365 : if (offset + sizeof(double) > size)
1351 0 : return CPLErrorInvalidSize("double value");
1352 365 : if (!isIgnored)
1353 : {
1354 355 : memcpy(&ogrField->Real, data + offset, sizeof(double));
1355 355 : CPL_LSBPTR64(&ogrField->Real);
1356 : }
1357 365 : offset += sizeof(double);
1358 365 : break;
1359 :
1360 391 : case ColumnType::String:
1361 : case ColumnType::Json:
1362 : {
1363 391 : if (offset + sizeof(uint32_t) > size)
1364 0 : return CPLErrorInvalidSize("string length");
1365 : uint32_t len;
1366 391 : memcpy(&len, data + offset, sizeof(int32_t));
1367 391 : CPL_LSBPTR32(&len);
1368 391 : offset += sizeof(uint32_t);
1369 391 : if (len > size - offset)
1370 0 : return CPLErrorInvalidSize("string value");
1371 391 : if (!isIgnored)
1372 : {
1373 : char *str =
1374 387 : static_cast<char *>(VSI_MALLOC_VERBOSE(len + 1));
1375 387 : if (str == nullptr)
1376 0 : return CPLErrorMemoryAllocation("string value");
1377 387 : memcpy(str, data + offset, len);
1378 387 : str[len] = '\0';
1379 387 : ogrField->String = str;
1380 : }
1381 391 : offset += len;
1382 391 : break;
1383 : }
1384 :
1385 5 : case ColumnType::DateTime:
1386 : {
1387 5 : if (offset + sizeof(uint32_t) > size)
1388 0 : return CPLErrorInvalidSize("datetime length ");
1389 : uint32_t len;
1390 5 : memcpy(&len, data + offset, sizeof(int32_t));
1391 5 : CPL_LSBPTR32(&len);
1392 5 : offset += sizeof(uint32_t);
1393 5 : if (len > size - offset || len > 32)
1394 0 : return CPLErrorInvalidSize("datetime value");
1395 5 : if (!isIgnored)
1396 : {
1397 5 : if (!ParseDateTime(
1398 : std::string_view(reinterpret_cast<const char *>(
1399 5 : data + offset),
1400 : len),
1401 : ogrField))
1402 : {
1403 : char str[32 + 1];
1404 0 : memcpy(str, data + offset, len);
1405 0 : str[len] = '\0';
1406 0 : if (!OGRParseDate(str, ogrField, 0))
1407 : {
1408 0 : OGR_RawField_SetUnset(ogrField);
1409 : }
1410 : }
1411 : }
1412 5 : offset += len;
1413 5 : break;
1414 : }
1415 :
1416 5 : case ColumnType::Binary:
1417 : {
1418 5 : if (offset + sizeof(uint32_t) > size)
1419 0 : return CPLErrorInvalidSize("binary length");
1420 : uint32_t len;
1421 5 : memcpy(&len, data + offset, sizeof(int32_t));
1422 5 : CPL_LSBPTR32(&len);
1423 5 : offset += sizeof(uint32_t);
1424 5 : if (len > static_cast<uint32_t>(INT_MAX) ||
1425 5 : len > size - offset)
1426 0 : return CPLErrorInvalidSize("binary value");
1427 5 : if (!isIgnored)
1428 : {
1429 : GByte *binary = static_cast<GByte *>(
1430 5 : VSI_MALLOC_VERBOSE(len ? len : 1));
1431 5 : if (binary == nullptr)
1432 0 : return CPLErrorMemoryAllocation("string value");
1433 5 : memcpy(binary, data + offset, len);
1434 5 : ogrField->Binary.nCount = static_cast<int>(len);
1435 5 : ogrField->Binary.paData = binary;
1436 : }
1437 5 : offset += len;
1438 5 : break;
1439 : }
1440 : }
1441 : }
1442 : }
1443 594 : return OGRERR_NONE;
1444 : }
1445 :
1446 : /************************************************************************/
1447 : /* GetNextArrowArray() */
1448 : /************************************************************************/
1449 :
1450 70 : int OGRFlatGeobufLayer::GetNextArrowArray(struct ArrowArrayStream *stream,
1451 : struct ArrowArray *out_array)
1452 : {
1453 137 : if (!m_poSharedArrowArrayStreamPrivateData->m_anQueriedFIDs.empty() ||
1454 67 : CPLTestBool(
1455 : CPLGetConfigOption("OGR_FLATGEOBUF_STREAM_BASE_IMPL", "NO")))
1456 : {
1457 3 : return OGRLayer::GetNextArrowArray(stream, out_array);
1458 : }
1459 :
1460 67 : begin:
1461 77 : int errorErrno = EIO;
1462 77 : memset(out_array, 0, sizeof(*out_array));
1463 :
1464 77 : if (m_create)
1465 1 : return EINVAL;
1466 :
1467 76 : if (m_bEOF || (m_featuresCount > 0 && m_featuresPos >= m_featuresCount))
1468 : {
1469 36 : return 0;
1470 : }
1471 :
1472 40 : if (readIndex() != OGRERR_NONE)
1473 0 : return EIO;
1474 :
1475 : OGRArrowArrayHelper sHelper(
1476 : nullptr, // dataset pointer. only used for field domains (not used by
1477 : // FlatGeobuf)
1478 40 : m_poFeatureDefn, m_aosArrowArrayStreamOptions, out_array);
1479 40 : if (out_array->release == nullptr)
1480 : {
1481 0 : return ENOMEM;
1482 : }
1483 :
1484 40 : std::vector<bool> abSetFields(sHelper.m_nFieldCount);
1485 :
1486 : struct tm brokenDown;
1487 40 : memset(&brokenDown, 0, sizeof(brokenDown));
1488 :
1489 40 : int iFeat = 0;
1490 40 : bool bEOFOrError = true;
1491 :
1492 40 : if (m_queriedSpatialIndex && m_featuresCount == 0)
1493 : {
1494 0 : CPLDebugOnly("FlatGeobuf", "GetNextFeature: no features found");
1495 0 : sHelper.m_nMaxBatchSize = 0;
1496 : }
1497 :
1498 40 : const GIntBig nFeatureIdxStart = m_featuresPos;
1499 40 : const bool bDateTimeAsString = m_aosArrowArrayStreamOptions.FetchBool(
1500 : GAS_OPT_DATETIME_AS_STRING, false);
1501 :
1502 40 : const uint32_t nMemLimit = OGRArrowArrayHelper::GetMemLimit();
1503 153 : while (iFeat < sHelper.m_nMaxBatchSize)
1504 : {
1505 142 : bEOFOrError = true;
1506 142 : if (m_featuresCount > 0 && m_featuresPos >= m_featuresCount)
1507 : {
1508 29 : CPLDebugOnly("FlatGeobuf", "GetNextFeature: iteration end at %lu",
1509 : static_cast<long unsigned int>(m_featuresPos));
1510 29 : break;
1511 : }
1512 :
1513 : GIntBig fid;
1514 113 : auto seek = false;
1515 113 : if (m_queriedSpatialIndex && !m_ignoreSpatialFilter)
1516 : {
1517 17 : const auto item = m_foundItems[m_featuresPos];
1518 17 : m_offset = m_offsetFeatures + item.offset;
1519 17 : fid = item.index;
1520 17 : seek = true;
1521 : }
1522 : else
1523 : {
1524 96 : fid = m_featuresPos;
1525 : }
1526 :
1527 113 : if (sHelper.m_panFIDValues)
1528 108 : sHelper.m_panFIDValues[iFeat] = fid;
1529 :
1530 113 : if (m_featuresPos == 0)
1531 36 : seek = true;
1532 :
1533 113 : if (seek && VSIFSeekL(m_poFp, m_offset, SEEK_SET) == -1)
1534 : {
1535 0 : break;
1536 : }
1537 : uint32_t featureSize;
1538 113 : if (VSIFReadL(&featureSize, sizeof(featureSize), 1, m_poFp) != 1)
1539 : {
1540 0 : if (VSIFEofL(m_poFp))
1541 0 : break;
1542 0 : CPLErrorIO("reading feature size");
1543 0 : goto error;
1544 : }
1545 113 : CPL_LSBPTR32(&featureSize);
1546 :
1547 : // Sanity check to avoid allocated huge amount of memory on corrupted
1548 : // feature
1549 113 : if (featureSize > 100 * 1024 * 1024)
1550 : {
1551 0 : if (featureSize > feature_max_buffer_size)
1552 : {
1553 0 : CPLErrorInvalidSize("feature");
1554 0 : goto error;
1555 : }
1556 :
1557 0 : if (m_nFileSize == 0)
1558 : {
1559 : VSIStatBufL sStatBuf;
1560 0 : if (VSIStatL(m_osFilename.c_str(), &sStatBuf) == 0)
1561 : {
1562 0 : m_nFileSize = sStatBuf.st_size;
1563 : }
1564 : }
1565 0 : if (m_offset + featureSize > m_nFileSize)
1566 : {
1567 0 : CPLErrorIO("reading feature size");
1568 0 : goto error;
1569 : }
1570 : }
1571 :
1572 113 : const auto err = ensureFeatureBuf(featureSize);
1573 113 : if (err != OGRERR_NONE)
1574 0 : goto error;
1575 113 : if (VSIFReadL(m_featureBuf, 1, featureSize, m_poFp) != featureSize)
1576 : {
1577 0 : CPLErrorIO("reading feature");
1578 0 : goto error;
1579 : }
1580 113 : m_offset += featureSize + sizeof(featureSize);
1581 :
1582 113 : if (m_bVerifyBuffers)
1583 : {
1584 113 : Verifier v(m_featureBuf, featureSize);
1585 113 : const auto ok = VerifyFeatureBuffer(v);
1586 113 : if (!ok)
1587 : {
1588 0 : CPLError(CE_Failure, CPLE_AppDefined,
1589 : "Buffer verification failed");
1590 0 : CPLDebugOnly("FlatGeobuf", "m_offset: %lu",
1591 : static_cast<long unsigned int>(m_offset));
1592 0 : CPLDebugOnly("FlatGeobuf", "m_featuresPos: %lu",
1593 : static_cast<long unsigned int>(m_featuresPos));
1594 0 : CPLDebugOnly("FlatGeobuf", "featureSize: %d", featureSize);
1595 0 : goto error;
1596 : }
1597 : }
1598 :
1599 113 : const auto feature = GetRoot<Feature>(m_featureBuf);
1600 113 : const auto geometry = feature->geometry();
1601 113 : const auto properties = feature->properties();
1602 113 : if (!m_poFeatureDefn->IsGeometryIgnored() && geometry != nullptr)
1603 : {
1604 107 : auto geometryType = m_geometryType;
1605 107 : if (geometryType == GeometryType::Unknown)
1606 4 : geometryType = geometry->type();
1607 : auto poOGRGeometry = std::unique_ptr<OGRGeometry>(
1608 107 : GeometryReader(geometry, geometryType, m_hasZ, m_hasM).read());
1609 107 : if (poOGRGeometry == nullptr)
1610 : {
1611 0 : CPLError(CE_Failure, CPLE_AppDefined,
1612 : "Failed to read geometry");
1613 0 : goto error;
1614 : }
1615 :
1616 107 : if (!FilterGeometry(poOGRGeometry.get()))
1617 6 : goto end_of_loop;
1618 :
1619 101 : const int iArrowField = sHelper.m_mapOGRGeomFieldToArrowField[0];
1620 101 : const size_t nWKBSize = poOGRGeometry->WkbSize();
1621 :
1622 101 : if (iFeat > 0)
1623 : {
1624 66 : auto psArray = out_array->children[iArrowField];
1625 66 : auto panOffsets = static_cast<int32_t *>(
1626 66 : const_cast<void *>(psArray->buffers[1]));
1627 66 : const uint32_t nCurLength =
1628 66 : static_cast<uint32_t>(panOffsets[iFeat]);
1629 66 : if (nWKBSize <= nMemLimit && nWKBSize > nMemLimit - nCurLength)
1630 : {
1631 0 : goto after_loop;
1632 : }
1633 : }
1634 :
1635 : GByte *outPtr =
1636 101 : sHelper.GetPtrForStringOrBinary(iArrowField, iFeat, nWKBSize);
1637 101 : if (outPtr == nullptr)
1638 : {
1639 0 : errorErrno = ENOMEM;
1640 0 : goto error;
1641 : }
1642 101 : poOGRGeometry->exportToWkb(wkbNDR, outPtr, wkbVariantIso);
1643 : }
1644 :
1645 107 : abSetFields.clear();
1646 107 : abSetFields.resize(sHelper.m_nFieldCount);
1647 :
1648 107 : if (properties != nullptr)
1649 : {
1650 105 : const auto data = properties->data();
1651 105 : const auto size = properties->size();
1652 :
1653 105 : uoffset_t offset = 0;
1654 : // size must be at least large enough to contain
1655 : // a single column index and smallest value type
1656 105 : if (size > 0 && size < (sizeof(uint16_t) + sizeof(uint8_t)))
1657 : {
1658 0 : CPLErrorInvalidSize("property value");
1659 0 : goto error;
1660 : }
1661 :
1662 512 : while (offset + 1 < size)
1663 : {
1664 407 : if (offset + sizeof(uint16_t) > size)
1665 : {
1666 0 : CPLErrorInvalidSize("property value");
1667 0 : goto error;
1668 : }
1669 : uint16_t i;
1670 407 : memcpy(&i, data + offset, sizeof(i));
1671 407 : CPL_LSBPTR16(&i);
1672 407 : offset += sizeof(uint16_t);
1673 : // TODO: use columns from feature if defined
1674 407 : const auto columns = m_poHeader->columns();
1675 407 : if (columns == nullptr)
1676 : {
1677 0 : CPLErrorInvalidPointer("columns");
1678 0 : goto error;
1679 : }
1680 407 : if (i >= columns->size())
1681 : {
1682 0 : CPLError(CE_Failure, CPLE_AppDefined,
1683 : "Column index %hu out of range", i);
1684 0 : goto error;
1685 : }
1686 :
1687 407 : abSetFields[i] = true;
1688 407 : const auto column = columns->Get(i);
1689 407 : const auto type = column->type();
1690 407 : const int iArrowField = sHelper.m_mapOGRFieldToArrowField[i];
1691 407 : const bool isIgnored = iArrowField < 0;
1692 407 : auto psArray =
1693 407 : isIgnored ? nullptr : out_array->children[iArrowField];
1694 :
1695 407 : switch (type)
1696 : {
1697 36 : case ColumnType::Bool:
1698 36 : if (offset + sizeof(unsigned char) > size)
1699 : {
1700 0 : CPLErrorInvalidSize("bool value");
1701 0 : goto error;
1702 : }
1703 36 : if (!isIgnored)
1704 : {
1705 36 : if (*(data + offset))
1706 : {
1707 20 : sHelper.SetBoolOn(psArray, iFeat);
1708 : }
1709 : }
1710 36 : offset += sizeof(unsigned char);
1711 36 : break;
1712 :
1713 0 : case ColumnType::Byte:
1714 0 : if (offset + sizeof(signed char) > size)
1715 : {
1716 0 : CPLErrorInvalidSize("byte value");
1717 0 : goto error;
1718 : }
1719 0 : if (!isIgnored)
1720 : {
1721 0 : sHelper.SetInt8(psArray, iFeat,
1722 0 : *reinterpret_cast<const int8_t *>(
1723 0 : data + offset));
1724 : }
1725 0 : offset += sizeof(signed char);
1726 0 : break;
1727 :
1728 0 : case ColumnType::UByte:
1729 0 : if (offset + sizeof(unsigned char) > size)
1730 : {
1731 0 : CPLErrorInvalidSize("ubyte value");
1732 0 : goto error;
1733 : }
1734 0 : if (!isIgnored)
1735 : {
1736 0 : sHelper.SetUInt8(psArray, iFeat,
1737 0 : *reinterpret_cast<const uint8_t *>(
1738 0 : data + offset));
1739 : }
1740 0 : offset += sizeof(unsigned char);
1741 0 : break;
1742 :
1743 36 : case ColumnType::Short:
1744 36 : if (offset + sizeof(int16_t) > size)
1745 : {
1746 0 : CPLErrorInvalidSize("short value");
1747 0 : goto error;
1748 : }
1749 36 : if (!isIgnored)
1750 : {
1751 : short s;
1752 32 : memcpy(&s, data + offset, sizeof(int16_t));
1753 32 : CPL_LSBPTR16(&s);
1754 32 : sHelper.SetInt16(psArray, iFeat, s);
1755 : }
1756 36 : offset += sizeof(int16_t);
1757 36 : break;
1758 :
1759 0 : case ColumnType::UShort:
1760 0 : if (offset + sizeof(uint16_t) > size)
1761 : {
1762 0 : CPLErrorInvalidSize("ushort value");
1763 0 : goto error;
1764 : }
1765 0 : if (!isIgnored)
1766 : {
1767 : uint16_t s;
1768 0 : memcpy(&s, data + offset, sizeof(uint16_t));
1769 0 : CPL_LSBPTR16(&s);
1770 0 : sHelper.SetInt32(psArray, iFeat, s);
1771 : }
1772 0 : offset += sizeof(uint16_t);
1773 0 : break;
1774 :
1775 20 : case ColumnType::Int:
1776 20 : if (offset + sizeof(int32_t) > size)
1777 : {
1778 0 : CPLErrorInvalidSize("int32 value");
1779 0 : goto error;
1780 : }
1781 20 : if (!isIgnored)
1782 : {
1783 : int32_t nVal;
1784 20 : memcpy(&nVal, data + offset, sizeof(int32_t));
1785 20 : CPL_LSBPTR32(&nVal);
1786 20 : sHelper.SetInt32(psArray, iFeat, nVal);
1787 : }
1788 20 : offset += sizeof(int32_t);
1789 20 : break;
1790 :
1791 0 : case ColumnType::UInt:
1792 0 : if (offset + sizeof(uint32_t) > size)
1793 : {
1794 0 : CPLErrorInvalidSize("uint value");
1795 0 : goto error;
1796 : }
1797 0 : if (!isIgnored)
1798 : {
1799 : uint32_t v;
1800 0 : memcpy(&v, data + offset, sizeof(int32_t));
1801 0 : CPL_LSBPTR32(&v);
1802 0 : sHelper.SetInt64(psArray, iFeat, v);
1803 : }
1804 0 : offset += sizeof(int32_t);
1805 0 : break;
1806 :
1807 80 : case ColumnType::Long:
1808 80 : if (offset + sizeof(int64_t) > size)
1809 : {
1810 0 : CPLErrorInvalidSize("int64 value");
1811 0 : goto error;
1812 : }
1813 80 : if (!isIgnored)
1814 : {
1815 : int64_t v;
1816 80 : memcpy(&v, data + offset, sizeof(int64_t));
1817 80 : CPL_LSBPTR64(&v);
1818 80 : sHelper.SetInt64(psArray, iFeat, v);
1819 : }
1820 80 : offset += sizeof(int64_t);
1821 80 : break;
1822 :
1823 0 : case ColumnType::ULong:
1824 0 : if (offset + sizeof(uint64_t) > size)
1825 : {
1826 0 : CPLErrorInvalidSize("uint64 value");
1827 0 : goto error;
1828 : }
1829 0 : if (!isIgnored)
1830 : {
1831 : uint64_t v;
1832 0 : memcpy(&v, data + offset, sizeof(v));
1833 0 : CPL_LSBPTR64(&v);
1834 0 : sHelper.SetDouble(psArray, iFeat,
1835 : static_cast<double>(v));
1836 : }
1837 0 : offset += sizeof(int64_t);
1838 0 : break;
1839 :
1840 20 : case ColumnType::Float:
1841 20 : if (offset + sizeof(float) > size)
1842 : {
1843 0 : CPLErrorInvalidSize("float value");
1844 0 : goto error;
1845 : }
1846 20 : if (!isIgnored)
1847 : {
1848 : float f;
1849 20 : memcpy(&f, data + offset, sizeof(float));
1850 20 : CPL_LSBPTR32(&f);
1851 20 : sHelper.SetFloat(psArray, iFeat, f);
1852 : }
1853 20 : offset += sizeof(float);
1854 20 : break;
1855 :
1856 80 : case ColumnType::Double:
1857 80 : if (offset + sizeof(double) > size)
1858 : {
1859 0 : CPLErrorInvalidSize("double value");
1860 0 : goto error;
1861 : }
1862 80 : if (!isIgnored)
1863 : {
1864 : double v;
1865 80 : memcpy(&v, data + offset, sizeof(double));
1866 80 : CPL_LSBPTR64(&v);
1867 80 : sHelper.SetDouble(psArray, iFeat, v);
1868 : }
1869 80 : offset += sizeof(double);
1870 80 : break;
1871 :
1872 23 : case ColumnType::DateTime:
1873 : {
1874 23 : if (!bDateTimeAsString)
1875 : {
1876 20 : if (offset + sizeof(uint32_t) > size)
1877 : {
1878 0 : CPLErrorInvalidSize("datetime length ");
1879 0 : goto error;
1880 : }
1881 : uint32_t len;
1882 20 : memcpy(&len, data + offset, sizeof(int32_t));
1883 20 : CPL_LSBPTR32(&len);
1884 20 : offset += sizeof(uint32_t);
1885 20 : if (len > size - offset || len > 32)
1886 : {
1887 0 : CPLErrorInvalidSize("datetime value");
1888 0 : goto error;
1889 : }
1890 20 : if (!isIgnored)
1891 : {
1892 : OGRField ogrField;
1893 20 : if (ParseDateTime(
1894 : std::string_view(
1895 : reinterpret_cast<const char *>(
1896 20 : data + offset),
1897 : len),
1898 : &ogrField))
1899 : {
1900 20 : sHelper.SetDateTime(
1901 : psArray, iFeat, brokenDown,
1902 20 : sHelper.m_anTZFlags[i], ogrField);
1903 : }
1904 : else
1905 : {
1906 : char str[32 + 1];
1907 0 : memcpy(str, data + offset, len);
1908 0 : str[len] = '\0';
1909 0 : if (OGRParseDate(str, &ogrField, 0))
1910 : {
1911 0 : sHelper.SetDateTime(
1912 : psArray, iFeat, brokenDown,
1913 0 : sHelper.m_anTZFlags[i], ogrField);
1914 : }
1915 : }
1916 : }
1917 20 : offset += len;
1918 20 : break;
1919 : }
1920 : else
1921 : {
1922 : [[fallthrough]];
1923 : }
1924 : }
1925 :
1926 : case ColumnType::String:
1927 : case ColumnType::Json:
1928 : case ColumnType::Binary:
1929 : {
1930 115 : if (offset + sizeof(uint32_t) > size)
1931 : {
1932 0 : CPLErrorInvalidSize("string length");
1933 0 : goto error;
1934 : }
1935 : uint32_t len;
1936 115 : memcpy(&len, data + offset, sizeof(int32_t));
1937 115 : CPL_LSBPTR32(&len);
1938 115 : offset += sizeof(uint32_t);
1939 115 : if (len > size - offset)
1940 : {
1941 0 : CPLErrorInvalidSize("string value");
1942 0 : goto error;
1943 : }
1944 115 : if (!isIgnored)
1945 : {
1946 114 : if (iFeat > 0)
1947 : {
1948 61 : auto panOffsets = static_cast<int32_t *>(
1949 61 : const_cast<void *>(psArray->buffers[1]));
1950 61 : const uint32_t nCurLength =
1951 61 : static_cast<uint32_t>(panOffsets[iFeat]);
1952 61 : if (len <= nMemLimit &&
1953 61 : len > nMemLimit - nCurLength)
1954 : {
1955 0 : goto after_loop;
1956 : }
1957 : }
1958 :
1959 114 : GByte *outPtr = sHelper.GetPtrForStringOrBinary(
1960 : iArrowField, iFeat, len);
1961 114 : if (outPtr == nullptr)
1962 : {
1963 0 : errorErrno = ENOMEM;
1964 0 : goto error;
1965 : }
1966 114 : memcpy(outPtr, data + offset, len);
1967 : }
1968 115 : offset += len;
1969 115 : break;
1970 : }
1971 : }
1972 : }
1973 : }
1974 :
1975 : // Mark null fields
1976 627 : for (int i = 0; i < sHelper.m_nFieldCount; i++)
1977 : {
1978 520 : if (!abSetFields[i] && sHelper.m_abNullableFields[i])
1979 : {
1980 113 : const int iArrowField = sHelper.m_mapOGRFieldToArrowField[i];
1981 113 : if (iArrowField >= 0)
1982 : {
1983 113 : sHelper.SetNull(iArrowField, iFeat);
1984 : }
1985 : }
1986 : }
1987 :
1988 107 : iFeat++;
1989 :
1990 113 : end_of_loop:
1991 :
1992 113 : if (VSIFEofL(m_poFp) || VSIFErrorL(m_poFp))
1993 : {
1994 0 : CPLDebug("FlatGeobuf", "GetNextFeature: iteration end due to EOF");
1995 0 : break;
1996 : }
1997 :
1998 113 : m_featuresPos++;
1999 113 : bEOFOrError = false;
2000 : }
2001 11 : after_loop:
2002 40 : if (bEOFOrError)
2003 29 : m_bEOF = true;
2004 :
2005 40 : sHelper.Shrink(iFeat);
2006 :
2007 40 : if (out_array->length != 0 && m_poAttrQuery)
2008 : {
2009 : struct ArrowSchema schema;
2010 21 : stream->get_schema(stream, &schema);
2011 21 : CPLAssert(schema.release != nullptr);
2012 21 : CPLAssert(schema.n_children == out_array->n_children);
2013 : // Spatial filter already evaluated
2014 21 : auto poFilterGeomBackup = m_poFilterGeom;
2015 21 : m_poFilterGeom = nullptr;
2016 21 : CPLStringList aosOptions;
2017 21 : if (!m_poFilterGeom)
2018 : {
2019 : aosOptions.SetNameValue("BASE_SEQUENTIAL_FID",
2020 21 : CPLSPrintf(CPL_FRMT_GIB, nFeatureIdxStart));
2021 : }
2022 21 : PostFilterArrowArray(&schema, out_array, aosOptions.List());
2023 21 : schema.release(&schema);
2024 21 : m_poFilterGeom = poFilterGeomBackup;
2025 : }
2026 :
2027 40 : if (out_array->length == 0)
2028 : {
2029 10 : if (out_array->release)
2030 10 : out_array->release(out_array);
2031 10 : memset(out_array, 0, sizeof(*out_array));
2032 :
2033 10 : if (m_poAttrQuery || m_poFilterGeom)
2034 : {
2035 10 : goto begin;
2036 : }
2037 : }
2038 :
2039 30 : return 0;
2040 :
2041 0 : error:
2042 0 : sHelper.ClearArray();
2043 0 : return errorErrno;
2044 : }
2045 :
2046 65707 : OGRErr OGRFlatGeobufLayer::CreateField(const OGRFieldDefn *poField,
2047 : int /* bApproxOK */)
2048 : {
2049 : // CPLDebugOnly("FlatGeobuf", "CreateField %s %s", poField->GetNameRef(),
2050 : // poField->GetFieldTypeName(poField->GetType()));
2051 65707 : if (!TestCapability(OLCCreateField))
2052 : {
2053 0 : CPLError(CE_Failure, CPLE_AppDefined,
2054 : "Unable to create new fields after first feature written.");
2055 0 : return OGRERR_FAILURE;
2056 : }
2057 :
2058 65707 : if (m_poFeatureDefn->GetFieldCount() > std::numeric_limits<uint16_t>::max())
2059 : {
2060 1 : CPLError(CE_Failure, CPLE_AppDefined,
2061 : "Cannot create features with more than 65536 columns");
2062 1 : return OGRERR_FAILURE;
2063 : }
2064 :
2065 65706 : m_poFeatureDefn->AddFieldDefn(poField);
2066 :
2067 65706 : return OGRERR_NONE;
2068 : }
2069 :
2070 257 : OGRErr OGRFlatGeobufLayer::ICreateFeature(OGRFeature *poNewFeature)
2071 : {
2072 257 : if (!m_create)
2073 : {
2074 1 : CPLError(CE_Failure, CPLE_AppDefined,
2075 : "CreateFeature() not supported on read-only layer");
2076 1 : return OGRERR_FAILURE;
2077 : }
2078 :
2079 256 : const auto fieldCount = m_poFeatureDefn->GetFieldCount();
2080 :
2081 256 : std::vector<uint8_t> &properties = m_writeProperties;
2082 256 : properties.clear();
2083 256 : properties.reserve(1024 * 4);
2084 512 : FlatBufferBuilder fbb;
2085 256 : fbb.TrackMinAlign(8);
2086 :
2087 66319 : for (int i = 0; i < fieldCount; i++)
2088 : {
2089 66063 : const auto fieldDef = m_poFeatureDefn->GetFieldDefn(i);
2090 66063 : if (!poNewFeature->IsFieldSetAndNotNull(i))
2091 99 : continue;
2092 :
2093 65964 : uint16_t column_index_le = static_cast<uint16_t>(i);
2094 65964 : CPL_LSBPTR16(&column_index_le);
2095 :
2096 : // CPLDebugOnly("FlatGeobuf", "DEBUG ICreateFeature: column_index_le:
2097 : // %hu", column_index_le);
2098 :
2099 : std::copy(reinterpret_cast<const uint8_t *>(&column_index_le),
2100 65964 : reinterpret_cast<const uint8_t *>(&column_index_le + 1),
2101 65964 : std::back_inserter(properties));
2102 :
2103 65964 : const auto fieldType = fieldDef->GetType();
2104 65964 : const auto fieldSubType = fieldDef->GetSubType();
2105 65964 : const auto field = poNewFeature->GetRawFieldRef(i);
2106 65964 : switch (fieldType)
2107 : {
2108 65605 : case OGRFieldType::OFTInteger:
2109 : {
2110 65605 : int nVal = field->Integer;
2111 65605 : if (fieldSubType == OFSTBoolean)
2112 : {
2113 6 : GByte byVal = static_cast<GByte>(nVal);
2114 : std::copy(reinterpret_cast<const uint8_t *>(&byVal),
2115 6 : reinterpret_cast<const uint8_t *>(&byVal + 1),
2116 6 : std::back_inserter(properties));
2117 : }
2118 65599 : else if (fieldSubType == OFSTInt16)
2119 : {
2120 6 : short sVal = static_cast<short>(nVal);
2121 6 : CPL_LSBPTR16(&sVal);
2122 : std::copy(reinterpret_cast<const uint8_t *>(&sVal),
2123 6 : reinterpret_cast<const uint8_t *>(&sVal + 1),
2124 6 : std::back_inserter(properties));
2125 : }
2126 : else
2127 : {
2128 65593 : CPL_LSBPTR32(&nVal);
2129 : std::copy(reinterpret_cast<const uint8_t *>(&nVal),
2130 65593 : reinterpret_cast<const uint8_t *>(&nVal + 1),
2131 65593 : std::back_inserter(properties));
2132 : }
2133 65605 : break;
2134 : }
2135 59 : case OGRFieldType::OFTInteger64:
2136 : {
2137 59 : GIntBig nVal = field->Integer64;
2138 59 : CPL_LSBPTR64(&nVal);
2139 : std::copy(reinterpret_cast<const uint8_t *>(&nVal),
2140 59 : reinterpret_cast<const uint8_t *>(&nVal + 1),
2141 59 : std::back_inserter(properties));
2142 59 : break;
2143 : }
2144 89 : case OGRFieldType::OFTReal:
2145 : {
2146 89 : double dfVal = field->Real;
2147 89 : if (fieldSubType == OFSTFloat32)
2148 : {
2149 4 : float fVal = static_cast<float>(dfVal);
2150 4 : CPL_LSBPTR32(&fVal);
2151 : std::copy(reinterpret_cast<const uint8_t *>(&fVal),
2152 4 : reinterpret_cast<const uint8_t *>(&fVal + 1),
2153 4 : std::back_inserter(properties));
2154 : }
2155 : else
2156 : {
2157 85 : CPL_LSBPTR64(&dfVal);
2158 : std::copy(reinterpret_cast<const uint8_t *>(&dfVal),
2159 85 : reinterpret_cast<const uint8_t *>(&dfVal + 1),
2160 85 : std::back_inserter(properties));
2161 : }
2162 89 : break;
2163 : }
2164 103 : case OGRFieldType::OFTDate:
2165 : case OGRFieldType::OFTTime:
2166 : case OGRFieldType::OFTDateTime:
2167 : {
2168 : char szBuffer[OGR_SIZEOF_ISO8601_DATETIME_BUFFER];
2169 : const size_t len =
2170 103 : OGRGetISO8601DateTime(field, false, szBuffer);
2171 103 : uint32_t l_le = static_cast<uint32_t>(len);
2172 103 : CPL_LSBPTR32(&l_le);
2173 : std::copy(reinterpret_cast<const uint8_t *>(&l_le),
2174 103 : reinterpret_cast<const uint8_t *>(&l_le + 1),
2175 103 : std::back_inserter(properties));
2176 : std::copy(szBuffer, szBuffer + len,
2177 103 : std::back_inserter(properties));
2178 103 : break;
2179 : }
2180 103 : case OGRFieldType::OFTString:
2181 : {
2182 103 : const size_t len = strlen(field->String);
2183 206 : if (len >= feature_max_buffer_size ||
2184 103 : properties.size() > feature_max_buffer_size - len)
2185 : {
2186 0 : CPLError(CE_Failure, CPLE_AppDefined,
2187 : "ICreateFeature: String too long");
2188 0 : return OGRERR_FAILURE;
2189 : }
2190 103 : if (!CPLIsUTF8(field->String, static_cast<int>(len)))
2191 : {
2192 0 : CPLError(CE_Failure, CPLE_AppDefined,
2193 : "ICreateFeature: String '%s' is not a valid UTF-8 "
2194 : "string",
2195 : field->String);
2196 0 : return OGRERR_FAILURE;
2197 : }
2198 :
2199 : // Valid cast since feature_max_buffer_size is 2 GB
2200 103 : uint32_t l_le = static_cast<uint32_t>(len);
2201 103 : CPL_LSBPTR32(&l_le);
2202 : std::copy(reinterpret_cast<const uint8_t *>(&l_le),
2203 103 : reinterpret_cast<const uint8_t *>(&l_le + 1),
2204 103 : std::back_inserter(properties));
2205 : try
2206 : {
2207 : // to avoid coverity scan warning: "To avoid a quadratic
2208 : // time penalty when using reserve(), always increase the
2209 : // capacity
2210 : /// by a multiple of its current value"
2211 104 : if (properties.size() + len > properties.capacity() &&
2212 1 : properties.size() <
2213 1 : std::numeric_limits<size_t>::max() / 2)
2214 : {
2215 1 : properties.reserve(std::max(2 * properties.size(),
2216 2 : properties.size() + len));
2217 : }
2218 : }
2219 0 : catch (const std::bad_alloc &)
2220 : {
2221 0 : CPLError(CE_Failure, CPLE_OutOfMemory,
2222 : "ICreateFeature: String too long");
2223 0 : return OGRERR_FAILURE;
2224 : }
2225 103 : std::copy(field->String, field->String + len,
2226 103 : std::back_inserter(properties));
2227 103 : break;
2228 : }
2229 :
2230 5 : case OGRFieldType::OFTBinary:
2231 : {
2232 5 : const size_t len = field->Binary.nCount;
2233 10 : if (len >= feature_max_buffer_size ||
2234 5 : properties.size() > feature_max_buffer_size - len)
2235 : {
2236 0 : CPLError(CE_Failure, CPLE_AppDefined,
2237 : "ICreateFeature: Binary too long");
2238 0 : return OGRERR_FAILURE;
2239 : }
2240 5 : uint32_t l_le = static_cast<uint32_t>(len);
2241 5 : CPL_LSBPTR32(&l_le);
2242 : std::copy(reinterpret_cast<const uint8_t *>(&l_le),
2243 5 : reinterpret_cast<const uint8_t *>(&l_le + 1),
2244 5 : std::back_inserter(properties));
2245 : try
2246 : {
2247 : // to avoid coverity scan warning: "To avoid a quadratic
2248 : // time penalty when using reserve(), always increase the
2249 : // capacity
2250 : /// by a multiple of its current value"
2251 5 : if (properties.size() + len > properties.capacity() &&
2252 0 : properties.size() <
2253 0 : std::numeric_limits<size_t>::max() / 2)
2254 : {
2255 0 : properties.reserve(std::max(2 * properties.size(),
2256 0 : properties.size() + len));
2257 : }
2258 : }
2259 0 : catch (const std::bad_alloc &)
2260 : {
2261 0 : CPLError(CE_Failure, CPLE_OutOfMemory,
2262 : "ICreateFeature: Binary too long");
2263 0 : return OGRERR_FAILURE;
2264 : }
2265 5 : std::copy(field->Binary.paData, field->Binary.paData + len,
2266 5 : std::back_inserter(properties));
2267 5 : break;
2268 : }
2269 :
2270 0 : default:
2271 0 : CPLError(CE_Failure, CPLE_AppDefined,
2272 : "ICreateFeature: Missing implementation for "
2273 : "OGRFieldType %d",
2274 : fieldType);
2275 0 : return OGRERR_FAILURE;
2276 : }
2277 : }
2278 :
2279 : // CPLDebugOnly("FlatGeobuf", "DEBUG ICreateFeature: properties.size():
2280 : // %lu", static_cast<long unsigned int>(properties.size()));
2281 :
2282 256 : const auto ogrGeometry = poNewFeature->GetGeometryRef();
2283 : #ifdef DEBUG
2284 : // char *wkt;
2285 : // ogrGeometry->exportToWkt(&wkt);
2286 : // CPLDebugOnly("FlatGeobuf", "poNewFeature as wkt: %s", wkt);
2287 : #endif
2288 452 : if (m_bCreateSpatialIndexAtClose &&
2289 196 : (ogrGeometry == nullptr || ogrGeometry->IsEmpty()))
2290 : {
2291 35 : CPLError(
2292 : CE_Failure, CPLE_AppDefined,
2293 : "ICreateFeature: NULL geometry not supported with spatial index");
2294 35 : return OGRERR_FAILURE;
2295 : }
2296 431 : if (ogrGeometry != nullptr && m_geometryType != GeometryType::Unknown &&
2297 210 : ogrGeometry->getGeometryType() != m_eGType)
2298 : {
2299 30 : CPLError(CE_Failure, CPLE_AppDefined,
2300 : "ICreateFeature: Mismatched geometry type. "
2301 : "Feature geometry type is %s, "
2302 : "expected layer geometry type is %s",
2303 15 : OGRGeometryTypeToName(ogrGeometry->getGeometryType()),
2304 : OGRGeometryTypeToName(m_eGType));
2305 15 : return OGRERR_FAILURE;
2306 : }
2307 :
2308 : try
2309 : {
2310 : // FlatBuffer serialization will crash/assert if the vectors go
2311 : // beyond FLATBUFFERS_MAX_BUFFER_SIZE. We cannot easily anticipate
2312 : // the size of the FlatBuffer, but WKB might be a good approximation.
2313 : // Takes an extra security margin of 10%
2314 206 : flatbuffers::Offset<FlatGeobuf::Geometry> geometryOffset = 0;
2315 206 : if (ogrGeometry && !ogrGeometry->IsEmpty())
2316 : {
2317 203 : const auto nWKBSize = ogrGeometry->WkbSize();
2318 203 : if (nWKBSize > feature_max_buffer_size - nWKBSize / 10)
2319 : {
2320 0 : CPLError(CE_Failure, CPLE_OutOfMemory,
2321 : "ICreateFeature: Too big geometry");
2322 0 : return OGRERR_FAILURE;
2323 : }
2324 203 : GeometryWriter writer{fbb, ogrGeometry, m_geometryType, m_hasZ,
2325 406 : m_hasM};
2326 203 : geometryOffset = writer.write(0);
2327 : }
2328 206 : const auto pProperties = properties.empty() ? nullptr : &properties;
2329 206 : if (properties.size() > feature_max_buffer_size - geometryOffset.o)
2330 : {
2331 0 : CPLError(CE_Failure, CPLE_OutOfMemory,
2332 : "ICreateFeature: Too big feature");
2333 0 : return OGRERR_FAILURE;
2334 : }
2335 : // TODO: write columns if mixed schema in collection
2336 : const auto feature =
2337 206 : CreateFeatureDirect(fbb, geometryOffset, pProperties);
2338 206 : fbb.FinishSizePrefixed(feature);
2339 :
2340 206 : OGREnvelope psEnvelope;
2341 206 : if (ogrGeometry != nullptr)
2342 : {
2343 204 : ogrGeometry->getEnvelope(&psEnvelope);
2344 204 : if (m_sExtent.IsInit())
2345 60 : m_sExtent.Merge(psEnvelope);
2346 : else
2347 144 : m_sExtent = psEnvelope;
2348 : }
2349 :
2350 206 : if (m_featuresCount == 0)
2351 : {
2352 144 : if (m_poFpWrite == nullptr)
2353 : {
2354 0 : CPLErrorInvalidPointer("output file handler");
2355 0 : return OGRERR_FAILURE;
2356 : }
2357 144 : if (!SupportsSeekWhileWriting(m_osFilename))
2358 : {
2359 2 : writeHeader(m_poFpWrite, 0, nullptr);
2360 : }
2361 : else
2362 : {
2363 : std::vector<double> dummyExtent(
2364 142 : 4, std::numeric_limits<double>::quiet_NaN());
2365 142 : const uint64_t dummyFeatureCount =
2366 : 0xDEADBEEF; // write non-zero value, otherwise the reserved
2367 : // size is not OK
2368 142 : writeHeader(m_poFpWrite, dummyFeatureCount,
2369 : &dummyExtent); // we will update it later
2370 142 : m_offsetAfterHeader = m_writeOffset;
2371 : }
2372 144 : CPLDebugOnly("FlatGeobuf", "Writing first feature at offset: %lu",
2373 : static_cast<long unsigned int>(m_writeOffset));
2374 : }
2375 :
2376 206 : m_maxFeatureSize =
2377 206 : std::max(m_maxFeatureSize, static_cast<uint32_t>(fbb.GetSize()));
2378 : size_t c =
2379 206 : VSIFWriteL(fbb.GetBufferPointer(), 1, fbb.GetSize(), m_poFpWrite);
2380 206 : if (c == 0)
2381 0 : return CPLErrorIO("writing feature");
2382 206 : if (m_bCreateSpatialIndexAtClose)
2383 : {
2384 : FeatureItem item;
2385 181 : item.size = static_cast<uint32_t>(fbb.GetSize());
2386 181 : item.offset = m_writeOffset;
2387 181 : item.nodeItem = {psEnvelope.MinX, psEnvelope.MinY, psEnvelope.MaxX,
2388 181 : psEnvelope.MaxY, 0};
2389 181 : m_featureItems.emplace_back(std::move(item));
2390 : }
2391 206 : m_writeOffset += c;
2392 :
2393 206 : m_featuresCount++;
2394 :
2395 206 : return OGRERR_NONE;
2396 : }
2397 0 : catch (const std::bad_alloc &)
2398 : {
2399 0 : CPLError(CE_Failure, CPLE_OutOfMemory,
2400 : "ICreateFeature: Memory allocation failure");
2401 0 : return OGRERR_FAILURE;
2402 : }
2403 : }
2404 :
2405 14 : OGRErr OGRFlatGeobufLayer::IGetExtent(int iGeomField, OGREnvelope *psExtent,
2406 : bool bForce)
2407 : {
2408 14 : if (m_sExtent.IsInit())
2409 : {
2410 12 : *psExtent = m_sExtent;
2411 12 : return OGRERR_NONE;
2412 : }
2413 2 : return OGRLayer::IGetExtent(iGeomField, psExtent, bForce);
2414 : }
2415 :
2416 66135 : int OGRFlatGeobufLayer::TestCapability(const char *pszCap)
2417 : {
2418 66135 : if (EQUAL(pszCap, OLCCreateField))
2419 65725 : return m_create;
2420 410 : else if (EQUAL(pszCap, OLCSequentialWrite))
2421 18 : return m_create;
2422 392 : else if (EQUAL(pszCap, OLCRandomRead))
2423 4 : return m_poHeader != nullptr && m_poHeader->index_node_size() > 0;
2424 388 : else if (EQUAL(pszCap, OLCIgnoreFields))
2425 1 : return true;
2426 387 : else if (EQUAL(pszCap, OLCMeasuredGeometries))
2427 152 : return true;
2428 235 : else if (EQUAL(pszCap, OLCCurveGeometries))
2429 175 : return true;
2430 60 : else if (EQUAL(pszCap, OLCZGeometries))
2431 3 : return true;
2432 57 : else if (EQUAL(pszCap, OLCFastFeatureCount))
2433 6 : return m_poFilterGeom == nullptr && m_poAttrQuery == nullptr &&
2434 6 : m_featuresCount > 0;
2435 54 : else if (EQUAL(pszCap, OLCFastGetExtent))
2436 5 : return m_sExtent.IsInit();
2437 49 : else if (EQUAL(pszCap, OLCFastSpatialFilter))
2438 0 : return m_poHeader != nullptr && m_poHeader->index_node_size() > 0;
2439 49 : else if (EQUAL(pszCap, OLCStringsAsUTF8))
2440 30 : return true;
2441 19 : else if (EQUAL(pszCap, OLCFastGetArrowStream))
2442 13 : return true;
2443 : else
2444 6 : return false;
2445 : }
2446 :
2447 382 : void OGRFlatGeobufLayer::ResetReading()
2448 : {
2449 382 : CPLDebugOnly("FlatGeobuf", "ResetReading");
2450 382 : m_offset = m_offsetFeatures;
2451 382 : m_bEOF = false;
2452 382 : m_featuresPos = 0;
2453 382 : m_foundItems.clear();
2454 382 : m_featuresCount = m_poHeader ? m_poHeader->features_count() : 0;
2455 382 : m_queriedSpatialIndex = false;
2456 382 : m_ignoreSpatialFilter = false;
2457 382 : m_ignoreAttributeFilter = false;
2458 382 : return;
2459 : }
2460 :
2461 333 : std::string OGRFlatGeobufLayer::GetTempFilePath(const CPLString &fileName,
2462 : CSLConstList papszOptions)
2463 : {
2464 666 : const CPLString osDirname(CPLGetPathSafe(fileName.c_str()));
2465 666 : const CPLString osBasename(CPLGetBasenameSafe(fileName.c_str()));
2466 333 : const char *pszTempDir = CSLFetchNameValue(papszOptions, "TEMPORARY_DIR");
2467 : std::string osTempFile =
2468 : pszTempDir ? CPLFormFilenameSafe(pszTempDir, osBasename, nullptr)
2469 644 : : (STARTS_WITH(fileName, "/vsi") && !STARTS_WITH(fileName, "/vsimem/"))
2470 333 : ? CPLGenerateTempFilenameSafe(osBasename)
2471 666 : : CPLFormFilenameSafe(osDirname, osBasename, nullptr);
2472 333 : osTempFile += "_temp.fgb";
2473 666 : return osTempFile;
2474 : }
2475 :
2476 173 : VSILFILE *OGRFlatGeobufLayer::CreateOutputFile(const CPLString &osFilename,
2477 : CSLConstList papszOptions,
2478 : bool isTemp)
2479 : {
2480 346 : std::string osTempFile;
2481 : VSILFILE *poFpWrite;
2482 : int savedErrno;
2483 173 : if (isTemp)
2484 : {
2485 160 : CPLDebug("FlatGeobuf", "Spatial index requested will write to temp "
2486 : "file and do second pass on close");
2487 160 : osTempFile = GetTempFilePath(osFilename, papszOptions);
2488 160 : poFpWrite = VSIFOpenL(osTempFile.c_str(), "w+b");
2489 160 : savedErrno = errno;
2490 : // Unlink it now to avoid stale temporary file if killing the process
2491 : // (only works on Unix)
2492 160 : VSIUnlink(osTempFile.c_str());
2493 : }
2494 : else
2495 : {
2496 13 : CPLDebug("FlatGeobuf",
2497 : "No spatial index will write directly to output");
2498 13 : if (!SupportsSeekWhileWriting(osFilename))
2499 1 : poFpWrite = VSIFOpenL(osFilename, "wb");
2500 : else
2501 12 : poFpWrite = VSIFOpenL(osFilename, "w+b");
2502 13 : savedErrno = errno;
2503 : }
2504 173 : if (poFpWrite == nullptr)
2505 : {
2506 2 : CPLError(CE_Failure, CPLE_OpenFailed, "Failed to create %s:\n%s",
2507 : osFilename.c_str(), VSIStrerror(savedErrno));
2508 2 : return nullptr;
2509 : }
2510 171 : return poFpWrite;
2511 : }
2512 :
2513 173 : OGRFlatGeobufLayer *OGRFlatGeobufLayer::Create(
2514 : GDALDataset *poDS, const char *pszLayerName, const char *pszFilename,
2515 : const OGRSpatialReference *poSpatialRef, OGRwkbGeometryType eGType,
2516 : bool bCreateSpatialIndexAtClose, CSLConstList papszOptions)
2517 : {
2518 346 : std::string osTempFile = GetTempFilePath(pszFilename, papszOptions);
2519 : VSILFILE *poFpWrite =
2520 173 : CreateOutputFile(pszFilename, papszOptions, bCreateSpatialIndexAtClose);
2521 173 : if (poFpWrite == nullptr)
2522 2 : return nullptr;
2523 : OGRFlatGeobufLayer *layer = new OGRFlatGeobufLayer(
2524 : poDS, pszLayerName, pszFilename, poSpatialRef, eGType,
2525 171 : bCreateSpatialIndexAtClose, poFpWrite, osTempFile, papszOptions);
2526 171 : return layer;
2527 : }
2528 :
2529 150 : OGRFlatGeobufLayer *OGRFlatGeobufLayer::Open(const Header *poHeader,
2530 : GByte *headerBuf,
2531 : const char *pszFilename,
2532 : VSILFILE *poFp, uint64_t offset)
2533 : {
2534 : OGRFlatGeobufLayer *layer =
2535 150 : new OGRFlatGeobufLayer(poHeader, headerBuf, pszFilename, poFp, offset);
2536 150 : return layer;
2537 : }
2538 :
2539 150 : OGRFlatGeobufLayer *OGRFlatGeobufLayer::Open(const char *pszFilename,
2540 : VSILFILE *fp, bool bVerifyBuffers)
2541 : {
2542 150 : uint64_t offset = sizeof(magicbytes);
2543 150 : CPLDebugOnly("FlatGeobuf", "Start at offset: %lu",
2544 : static_cast<long unsigned int>(offset));
2545 150 : if (VSIFSeekL(fp, offset, SEEK_SET) == -1)
2546 : {
2547 0 : CPLError(CE_Failure, CPLE_AppDefined, "Unable to get seek in file");
2548 0 : return nullptr;
2549 : }
2550 : uint32_t headerSize;
2551 150 : if (VSIFReadL(&headerSize, 4, 1, fp) != 1)
2552 : {
2553 0 : CPLError(CE_Failure, CPLE_AppDefined, "Failed to read header size");
2554 0 : return nullptr;
2555 : }
2556 150 : CPL_LSBPTR32(&headerSize);
2557 150 : CPLDebugOnly("FlatGeobuf", "headerSize: %d", headerSize);
2558 150 : if (headerSize > header_max_buffer_size)
2559 : {
2560 0 : CPLError(CE_Failure, CPLE_AppDefined,
2561 : "Header size too large (> 10 MB)");
2562 0 : return nullptr;
2563 : }
2564 : std::unique_ptr<GByte, VSIFreeReleaser> buf(
2565 300 : static_cast<GByte *>(VSIMalloc(headerSize)));
2566 150 : if (buf == nullptr)
2567 : {
2568 0 : CPLError(CE_Failure, CPLE_AppDefined,
2569 : "Failed to allocate memory for header");
2570 0 : return nullptr;
2571 : }
2572 150 : if (VSIFReadL(buf.get(), 1, headerSize, fp) != headerSize)
2573 : {
2574 0 : CPLError(CE_Failure, CPLE_AppDefined, "Failed to read header");
2575 0 : return nullptr;
2576 : }
2577 150 : if (bVerifyBuffers)
2578 : {
2579 149 : Verifier v(buf.get(), headerSize, 64U, 1000000U, false);
2580 149 : const auto ok = VerifyHeaderBuffer(v);
2581 149 : if (!ok)
2582 : {
2583 0 : CPLError(CE_Failure, CPLE_AppDefined,
2584 : "Header failed consistency verification");
2585 0 : return nullptr;
2586 : }
2587 : }
2588 150 : const auto header = GetHeader(buf.get());
2589 150 : offset += 4 + headerSize;
2590 150 : CPLDebugOnly("FlatGeobuf", "Add header size + length prefix to offset (%d)",
2591 : 4 + headerSize);
2592 :
2593 150 : const auto featuresCount = header->features_count();
2594 :
2595 150 : if (featuresCount >
2596 450 : std::min(static_cast<uint64_t>(std::numeric_limits<size_t>::max() / 8),
2597 150 : static_cast<uint64_t>(100) * 1000 * 1000 * 1000))
2598 : {
2599 0 : CPLError(CE_Failure, CPLE_AppDefined, "Too many features");
2600 0 : return nullptr;
2601 : }
2602 :
2603 150 : const auto index_node_size = header->index_node_size();
2604 150 : if (index_node_size > 0)
2605 : {
2606 : try
2607 : {
2608 122 : const auto treeSize = PackedRTree::size(featuresCount);
2609 122 : CPLDebugOnly("FlatGeobuf", "Tree start at offset (%lu)",
2610 : static_cast<long unsigned int>(offset));
2611 122 : offset += treeSize;
2612 122 : CPLDebugOnly("FlatGeobuf", "Add tree size to offset (%lu)",
2613 : static_cast<long unsigned int>(treeSize));
2614 : }
2615 0 : catch (const std::exception &e)
2616 : {
2617 0 : CPLError(CE_Failure, CPLE_AppDefined,
2618 0 : "Failed to calculate tree size: %s", e.what());
2619 0 : return nullptr;
2620 : }
2621 : }
2622 :
2623 150 : CPLDebugOnly("FlatGeobuf", "Features start at offset (%lu)",
2624 : static_cast<long unsigned int>(offset));
2625 :
2626 150 : CPLDebugOnly("FlatGeobuf", "Opening OGRFlatGeobufLayer");
2627 150 : auto poLayer = OGRFlatGeobufLayer::Open(header, buf.release(), pszFilename,
2628 : fp, offset);
2629 150 : poLayer->VerifyBuffers(bVerifyBuffers);
2630 :
2631 150 : return poLayer;
2632 : }
2633 :
2634 : OGRFlatGeobufBaseLayerInterface::~OGRFlatGeobufBaseLayerInterface() = default;
|