Coverage Report

Created: 2025-12-31 08:30

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