Coverage Report

Created: 2024-02-25 06:14

/src/PROJ/src/iso19111/factory.cpp
Line
Count
Source (jump to first uncovered line)
1
/******************************************************************************
2
 *
3
 * Project:  PROJ
4
 * Purpose:  ISO19111:2019 implementation
5
 * Author:   Even Rouault <even dot rouault at spatialys dot com>
6
 *
7
 ******************************************************************************
8
 * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com>
9
 *
10
 * Permission is hereby granted, free of charge, to any person obtaining a
11
 * copy of this software and associated documentation files (the "Software"),
12
 * to deal in the Software without restriction, including without limitation
13
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
14
 * and/or sell copies of the Software, and to permit persons to whom the
15
 * Software is furnished to do so, subject to the following conditions:
16
 *
17
 * The above copyright notice and this permission notice shall be included
18
 * in all copies or substantial portions of the Software.
19
 *
20
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26
 * DEALINGS IN THE SOFTWARE.
27
 ****************************************************************************/
28
29
#ifndef FROM_PROJ_CPP
30
#define FROM_PROJ_CPP
31
#endif
32
33
#include "proj/common.hpp"
34
#include "proj/coordinateoperation.hpp"
35
#include "proj/coordinates.hpp"
36
#include "proj/coordinatesystem.hpp"
37
#include "proj/crs.hpp"
38
#include "proj/datum.hpp"
39
#include "proj/io.hpp"
40
#include "proj/metadata.hpp"
41
#include "proj/util.hpp"
42
43
#include "proj/internal/internal.hpp"
44
#include "proj/internal/io_internal.hpp"
45
#include "proj/internal/lru_cache.hpp"
46
#include "proj/internal/tracing.hpp"
47
48
#include "operation/coordinateoperation_internal.hpp"
49
#include "operation/parammappings.hpp"
50
51
#include "filemanager.hpp"
52
#include "sqlite3_utils.hpp"
53
54
#include <algorithm>
55
#include <cmath>
56
#include <cstdlib>
57
#include <cstring>
58
#include <functional>
59
#include <iomanip>
60
#include <limits>
61
#include <locale>
62
#include <map>
63
#include <memory>
64
#include <mutex>
65
#include <sstream> // std::ostringstream
66
#include <stdexcept>
67
#include <string>
68
69
#include "proj_constants.h"
70
71
// PROJ include order is sensitive
72
// clang-format off
73
#include "proj.h"
74
#include "proj_internal.h"
75
// clang-format on
76
77
#include <sqlite3.h>
78
79
// Custom SQLite VFS as our database is not supposed to be modified in
80
// parallel. This is slightly faster
81
#define ENABLE_CUSTOM_LOCKLESS_VFS
82
83
#if defined(_WIN32) && defined(PROJ_HAS_PTHREADS)
84
#undef PROJ_HAS_PTHREADS
85
#endif
86
87
/* SQLite3 might use seak()+read() or pread[64]() to read data */
88
/* The later allows the same SQLite handle to be safely used in forked */
89
/* children of a parent process, while the former doesn't. */
90
/* So we use pthread_atfork() to set a flag in forked children, to ask them */
91
/* to close and reopen their database handle. */
92
#if defined(PROJ_HAS_PTHREADS) && !defined(SQLITE_USE_PREAD)
93
#include <pthread.h>
94
#define REOPEN_SQLITE_DB_AFTER_FORK
95
#endif
96
97
using namespace NS_PROJ::internal;
98
using namespace NS_PROJ::common;
99
100
NS_PROJ_START
101
namespace io {
102
103
//! @cond Doxygen_Suppress
104
105
// CRS subtypes
106
0
#define GEOG_2D "geographic 2D"
107
0
#define GEOG_3D "geographic 3D"
108
0
#define GEOCENTRIC "geocentric"
109
0
#define OTHER "other"
110
0
#define PROJECTED "projected"
111
0
#define VERTICAL "vertical"
112
0
#define COMPOUND "compound"
113
114
0
#define GEOG_2D_SINGLE_QUOTED "'geographic 2D'"
115
0
#define GEOG_3D_SINGLE_QUOTED "'geographic 3D'"
116
#define GEOCENTRIC_SINGLE_QUOTED "'geocentric'"
117
118
// Coordinate system types
119
constexpr const char *CS_TYPE_ELLIPSOIDAL = cs::EllipsoidalCS::WKT2_TYPE;
120
constexpr const char *CS_TYPE_CARTESIAN = cs::CartesianCS::WKT2_TYPE;
121
constexpr const char *CS_TYPE_SPHERICAL = cs::SphericalCS::WKT2_TYPE;
122
constexpr const char *CS_TYPE_VERTICAL = cs::VerticalCS::WKT2_TYPE;
123
constexpr const char *CS_TYPE_ORDINAL = cs::OrdinalCS::WKT2_TYPE;
124
125
// See data/sql/metadata.sql for the semantics of those constants
126
constexpr int DATABASE_LAYOUT_VERSION_MAJOR = 1;
127
// If the code depends on the new additions, then DATABASE_LAYOUT_VERSION_MINOR
128
// must be incremented.
129
constexpr int DATABASE_LAYOUT_VERSION_MINOR = 3;
130
131
constexpr size_t N_MAX_PARAMS = 7;
132
133
// ---------------------------------------------------------------------------
134
135
struct SQLValues {
136
    enum class Type { STRING, INT, DOUBLE };
137
138
    // cppcheck-suppress noExplicitConstructor
139
0
    SQLValues(const std::string &value) : type_(Type::STRING), str_(value) {}
140
141
    // cppcheck-suppress noExplicitConstructor
142
0
    SQLValues(int value) : type_(Type::INT), int_(value) {}
143
144
    // cppcheck-suppress noExplicitConstructor
145
0
    SQLValues(double value) : type_(Type::DOUBLE), double_(value) {}
146
147
0
    const Type &type() const { return type_; }
148
149
    // cppcheck-suppress functionStatic
150
0
    const std::string &stringValue() const { return str_; }
151
152
    // cppcheck-suppress functionStatic
153
0
    int intValue() const { return int_; }
154
155
    // cppcheck-suppress functionStatic
156
0
    double doubleValue() const { return double_; }
157
158
  private:
159
    Type type_;
160
    std::string str_{};
161
    int int_ = 0;
162
    double double_ = 0.0;
163
};
164
165
// ---------------------------------------------------------------------------
166
167
using SQLRow = std::vector<std::string>;
168
using SQLResultSet = std::list<SQLRow>;
169
using ListOfParams = std::list<SQLValues>;
170
171
// ---------------------------------------------------------------------------
172
173
0
static double PROJ_SQLITE_GetValAsDouble(sqlite3_value *val, bool &gotVal) {
174
0
    switch (sqlite3_value_type(val)) {
175
0
    case SQLITE_FLOAT:
176
0
        gotVal = true;
177
0
        return sqlite3_value_double(val);
178
179
0
    case SQLITE_INTEGER:
180
0
        gotVal = true;
181
0
        return static_cast<double>(sqlite3_value_int64(val));
182
183
0
    default:
184
0
        gotVal = false;
185
0
        return 0.0;
186
0
    }
187
0
}
188
189
// ---------------------------------------------------------------------------
190
191
static void PROJ_SQLITE_pseudo_area_from_swne(sqlite3_context *pContext,
192
                                              int /* argc */,
193
0
                                              sqlite3_value **argv) {
194
0
    bool b0, b1, b2, b3;
195
0
    double south_lat = PROJ_SQLITE_GetValAsDouble(argv[0], b0);
196
0
    double west_lon = PROJ_SQLITE_GetValAsDouble(argv[1], b1);
197
0
    double north_lat = PROJ_SQLITE_GetValAsDouble(argv[2], b2);
198
0
    double east_lon = PROJ_SQLITE_GetValAsDouble(argv[3], b3);
199
0
    if (!b0 || !b1 || !b2 || !b3) {
200
0
        sqlite3_result_null(pContext);
201
0
        return;
202
0
    }
203
    // Deal with area crossing antimeridian
204
0
    if (east_lon < west_lon) {
205
0
        east_lon += 360.0;
206
0
    }
207
    // Integrate cos(lat) between south_lat and north_lat
208
0
    double pseudo_area = (east_lon - west_lon) *
209
0
                         (std::sin(common::Angle(north_lat).getSIValue()) -
210
0
                          std::sin(common::Angle(south_lat).getSIValue()));
211
0
    sqlite3_result_double(pContext, pseudo_area);
212
0
}
213
214
// ---------------------------------------------------------------------------
215
216
static void PROJ_SQLITE_intersects_bbox(sqlite3_context *pContext,
217
0
                                        int /* argc */, sqlite3_value **argv) {
218
0
    bool b0, b1, b2, b3, b4, b5, b6, b7;
219
0
    double south_lat1 = PROJ_SQLITE_GetValAsDouble(argv[0], b0);
220
0
    double west_lon1 = PROJ_SQLITE_GetValAsDouble(argv[1], b1);
221
0
    double north_lat1 = PROJ_SQLITE_GetValAsDouble(argv[2], b2);
222
0
    double east_lon1 = PROJ_SQLITE_GetValAsDouble(argv[3], b3);
223
0
    double south_lat2 = PROJ_SQLITE_GetValAsDouble(argv[4], b4);
224
0
    double west_lon2 = PROJ_SQLITE_GetValAsDouble(argv[5], b5);
225
0
    double north_lat2 = PROJ_SQLITE_GetValAsDouble(argv[6], b6);
226
0
    double east_lon2 = PROJ_SQLITE_GetValAsDouble(argv[7], b7);
227
0
    if (!b0 || !b1 || !b2 || !b3 || !b4 || !b5 || !b6 || !b7) {
228
0
        sqlite3_result_null(pContext);
229
0
        return;
230
0
    }
231
0
    auto bbox1 = metadata::GeographicBoundingBox::create(west_lon1, south_lat1,
232
0
                                                         east_lon1, north_lat1);
233
0
    auto bbox2 = metadata::GeographicBoundingBox::create(west_lon2, south_lat2,
234
0
                                                         east_lon2, north_lat2);
235
0
    sqlite3_result_int(pContext, bbox1->intersects(bbox2) ? 1 : 0);
236
0
}
237
238
// ---------------------------------------------------------------------------
239
240
class SQLiteHandle {
241
    sqlite3 *sqlite_handle_ = nullptr;
242
    bool close_handle_ = true;
243
244
#ifdef REOPEN_SQLITE_DB_AFTER_FORK
245
    bool is_valid_ = true;
246
#endif
247
248
    int nLayoutVersionMajor_ = 0;
249
    int nLayoutVersionMinor_ = 0;
250
251
#ifdef ENABLE_CUSTOM_LOCKLESS_VFS
252
    std::unique_ptr<SQLite3VFS> vfs_{};
253
#endif
254
255
    SQLiteHandle(const SQLiteHandle &) = delete;
256
    SQLiteHandle &operator=(const SQLiteHandle &) = delete;
257
258
    SQLiteHandle(sqlite3 *sqlite_handle, bool close_handle)
259
0
        : sqlite_handle_(sqlite_handle), close_handle_(close_handle) {
260
0
        assert(sqlite_handle_);
261
0
    }
262
263
    // cppcheck-suppress functionStatic
264
    void initialize();
265
266
    SQLResultSet run(const std::string &sql,
267
                     const ListOfParams &parameters = ListOfParams(),
268
                     bool useMaxFloatPrecision = false);
269
270
  public:
271
    ~SQLiteHandle();
272
273
0
    sqlite3 *handle() { return sqlite_handle_; }
274
275
#ifdef REOPEN_SQLITE_DB_AFTER_FORK
276
0
    bool isValid() const { return is_valid_; }
277
278
0
    void invalidate() { is_valid_ = false; }
279
#endif
280
281
    static std::shared_ptr<SQLiteHandle> open(PJ_CONTEXT *ctx,
282
                                              const std::string &path);
283
284
    // might not be shared between thread depending how the handle was opened!
285
    static std::shared_ptr<SQLiteHandle>
286
    initFromExisting(sqlite3 *sqlite_handle, bool close_handle,
287
                     int nLayoutVersionMajor, int nLayoutVersionMinor);
288
289
    static std::unique_ptr<SQLiteHandle>
290
    initFromExistingUniquePtr(sqlite3 *sqlite_handle, bool close_handle);
291
292
    void checkDatabaseLayout(const std::string &mainDbPath,
293
                             const std::string &path,
294
                             const std::string &dbNamePrefix);
295
296
    SQLResultSet run(sqlite3_stmt *stmt, const std::string &sql,
297
                     const ListOfParams &parameters = ListOfParams(),
298
                     bool useMaxFloatPrecision = false);
299
300
0
    inline int getLayoutVersionMajor() const { return nLayoutVersionMajor_; }
301
0
    inline int getLayoutVersionMinor() const { return nLayoutVersionMinor_; }
302
};
303
304
// ---------------------------------------------------------------------------
305
306
0
SQLiteHandle::~SQLiteHandle() {
307
0
    if (close_handle_) {
308
0
        sqlite3_close(sqlite_handle_);
309
0
    }
310
0
}
311
312
// ---------------------------------------------------------------------------
313
314
std::shared_ptr<SQLiteHandle> SQLiteHandle::open(PJ_CONTEXT *ctx,
315
0
                                                 const std::string &path) {
316
317
0
    const int sqlite3VersionNumber = sqlite3_libversion_number();
318
    // Minimum version for correct performance: 3.11
319
0
    if (sqlite3VersionNumber < 3 * 1000000 + 11 * 1000) {
320
0
        pj_log(ctx, PJ_LOG_ERROR,
321
0
               "SQLite3 version is %s, whereas at least 3.11 should be used",
322
0
               sqlite3_libversion());
323
0
    }
324
325
0
    std::string vfsName;
326
0
#ifdef ENABLE_CUSTOM_LOCKLESS_VFS
327
0
    std::unique_ptr<SQLite3VFS> vfs;
328
0
    if (ctx->custom_sqlite3_vfs_name.empty()) {
329
0
        vfs = SQLite3VFS::create(false, true, true);
330
0
        if (vfs == nullptr) {
331
0
            throw FactoryException("Open of " + path + " failed");
332
0
        }
333
0
        vfsName = vfs->name();
334
0
    } else
335
0
#endif
336
0
    {
337
0
        vfsName = ctx->custom_sqlite3_vfs_name;
338
0
    }
339
0
    sqlite3 *sqlite_handle = nullptr;
340
    // SQLITE_OPEN_FULLMUTEX as this will be used from concurrent threads
341
0
    if (sqlite3_open_v2(
342
0
            path.c_str(), &sqlite_handle,
343
0
            SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_URI,
344
0
            vfsName.empty() ? nullptr : vfsName.c_str()) != SQLITE_OK ||
345
0
        !sqlite_handle) {
346
0
        if (sqlite_handle != nullptr) {
347
0
            sqlite3_close(sqlite_handle);
348
0
        }
349
0
        throw FactoryException("Open of " + path + " failed");
350
0
    }
351
0
    auto handle =
352
0
        std::shared_ptr<SQLiteHandle>(new SQLiteHandle(sqlite_handle, true));
353
0
#ifdef ENABLE_CUSTOM_LOCKLESS_VFS
354
0
    handle->vfs_ = std::move(vfs);
355
0
#endif
356
0
    handle->initialize();
357
0
    handle->checkDatabaseLayout(path, path, std::string());
358
0
    return handle;
359
0
}
360
361
// ---------------------------------------------------------------------------
362
363
std::shared_ptr<SQLiteHandle>
364
SQLiteHandle::initFromExisting(sqlite3 *sqlite_handle, bool close_handle,
365
                               int nLayoutVersionMajor,
366
0
                               int nLayoutVersionMinor) {
367
0
    auto handle = std::shared_ptr<SQLiteHandle>(
368
0
        new SQLiteHandle(sqlite_handle, close_handle));
369
0
    handle->nLayoutVersionMajor_ = nLayoutVersionMajor;
370
0
    handle->nLayoutVersionMinor_ = nLayoutVersionMinor;
371
0
    handle->initialize();
372
0
    return handle;
373
0
}
374
375
// ---------------------------------------------------------------------------
376
377
std::unique_ptr<SQLiteHandle>
378
SQLiteHandle::initFromExistingUniquePtr(sqlite3 *sqlite_handle,
379
0
                                        bool close_handle) {
380
0
    auto handle = std::unique_ptr<SQLiteHandle>(
381
0
        new SQLiteHandle(sqlite_handle, close_handle));
382
0
    handle->initialize();
383
0
    return handle;
384
0
}
385
386
// ---------------------------------------------------------------------------
387
388
SQLResultSet SQLiteHandle::run(sqlite3_stmt *stmt, const std::string &sql,
389
                               const ListOfParams &parameters,
390
0
                               bool useMaxFloatPrecision) {
391
0
    int nBindField = 1;
392
0
    for (const auto &param : parameters) {
393
0
        const auto &paramType = param.type();
394
0
        if (paramType == SQLValues::Type::STRING) {
395
0
            const auto &strValue = param.stringValue();
396
0
            sqlite3_bind_text(stmt, nBindField, strValue.c_str(),
397
0
                              static_cast<int>(strValue.size()),
398
0
                              SQLITE_TRANSIENT);
399
0
        } else if (paramType == SQLValues::Type::INT) {
400
0
            sqlite3_bind_int(stmt, nBindField, param.intValue());
401
0
        } else {
402
0
            assert(paramType == SQLValues::Type::DOUBLE);
403
0
            sqlite3_bind_double(stmt, nBindField, param.doubleValue());
404
0
        }
405
0
        nBindField++;
406
0
    }
407
408
#ifdef TRACE_DATABASE
409
    size_t nPos = 0;
410
    std::string sqlSubst(sql);
411
    for (const auto &param : parameters) {
412
        nPos = sqlSubst.find('?', nPos);
413
        assert(nPos != std::string::npos);
414
        std::string strValue;
415
        const auto paramType = param.type();
416
        if (paramType == SQLValues::Type::STRING) {
417
            strValue = '\'' + param.stringValue() + '\'';
418
        } else if (paramType == SQLValues::Type::INT) {
419
            strValue = toString(param.intValue());
420
        } else {
421
            strValue = toString(param.doubleValue());
422
        }
423
        sqlSubst =
424
            sqlSubst.substr(0, nPos) + strValue + sqlSubst.substr(nPos + 1);
425
        nPos += strValue.size();
426
    }
427
    logTrace(sqlSubst, "DATABASE");
428
#endif
429
430
0
    SQLResultSet result;
431
0
    const int column_count = sqlite3_column_count(stmt);
432
0
    while (true) {
433
0
        int ret = sqlite3_step(stmt);
434
0
        if (ret == SQLITE_ROW) {
435
0
            SQLRow row(column_count);
436
0
            for (int i = 0; i < column_count; i++) {
437
0
                if (useMaxFloatPrecision &&
438
0
                    sqlite3_column_type(stmt, i) == SQLITE_FLOAT) {
439
                    // sqlite3_column_text() does not use maximum precision
440
0
                    std::ostringstream buffer;
441
0
                    buffer.imbue(std::locale::classic());
442
0
                    buffer << std::setprecision(18);
443
0
                    buffer << sqlite3_column_double(stmt, i);
444
0
                    row[i] = buffer.str();
445
0
                } else {
446
0
                    const char *txt = reinterpret_cast<const char *>(
447
0
                        sqlite3_column_text(stmt, i));
448
0
                    if (txt) {
449
0
                        row[i] = txt;
450
0
                    }
451
0
                }
452
0
            }
453
0
            result.emplace_back(std::move(row));
454
0
        } else if (ret == SQLITE_DONE) {
455
0
            break;
456
0
        } else {
457
0
            throw FactoryException("SQLite error on " + sql + ": " +
458
0
                                   sqlite3_errmsg(sqlite_handle_));
459
0
        }
460
0
    }
461
0
    return result;
462
0
}
463
464
// ---------------------------------------------------------------------------
465
466
SQLResultSet SQLiteHandle::run(const std::string &sql,
467
                               const ListOfParams &parameters,
468
0
                               bool useMaxFloatPrecision) {
469
0
    sqlite3_stmt *stmt = nullptr;
470
0
    try {
471
0
        if (sqlite3_prepare_v2(sqlite_handle_, sql.c_str(),
472
0
                               static_cast<int>(sql.size()), &stmt,
473
0
                               nullptr) != SQLITE_OK) {
474
0
            throw FactoryException("SQLite error on " + sql + ": " +
475
0
                                   sqlite3_errmsg(sqlite_handle_));
476
0
        }
477
0
        auto ret = run(stmt, sql, parameters, useMaxFloatPrecision);
478
0
        sqlite3_finalize(stmt);
479
0
        return ret;
480
0
    } catch (const std::exception &) {
481
0
        if (stmt)
482
0
            sqlite3_finalize(stmt);
483
0
        throw;
484
0
    }
485
0
}
486
487
// ---------------------------------------------------------------------------
488
489
void SQLiteHandle::checkDatabaseLayout(const std::string &mainDbPath,
490
                                       const std::string &path,
491
0
                                       const std::string &dbNamePrefix) {
492
0
    if (!dbNamePrefix.empty() && run("SELECT 1 FROM " + dbNamePrefix +
493
0
                                     "sqlite_master WHERE name = 'metadata'")
494
0
                                     .empty()) {
495
        // Accept auxiliary databases without metadata table (sparse DBs)
496
0
        return;
497
0
    }
498
0
    auto res = run("SELECT key, value FROM " + dbNamePrefix +
499
0
                   "metadata WHERE key IN "
500
0
                   "('DATABASE.LAYOUT.VERSION.MAJOR', "
501
0
                   "'DATABASE.LAYOUT.VERSION.MINOR')");
502
0
    if (res.empty() && !dbNamePrefix.empty()) {
503
        // Accept auxiliary databases without layout metadata.
504
0
        return;
505
0
    }
506
0
    if (res.size() != 2) {
507
0
        throw FactoryException(
508
0
            path + " lacks DATABASE.LAYOUT.VERSION.MAJOR / "
509
0
                   "DATABASE.LAYOUT.VERSION.MINOR "
510
0
                   "metadata. It comes from another PROJ installation.");
511
0
    }
512
0
    int major = 0;
513
0
    int minor = 0;
514
0
    for (const auto &row : res) {
515
0
        if (row[0] == "DATABASE.LAYOUT.VERSION.MAJOR") {
516
0
            major = atoi(row[1].c_str());
517
0
        } else if (row[0] == "DATABASE.LAYOUT.VERSION.MINOR") {
518
0
            minor = atoi(row[1].c_str());
519
0
        }
520
0
    }
521
0
    if (major != DATABASE_LAYOUT_VERSION_MAJOR) {
522
0
        throw FactoryException(
523
0
            path +
524
0
            " contains DATABASE.LAYOUT.VERSION.MAJOR = " + toString(major) +
525
0
            " whereas " + toString(DATABASE_LAYOUT_VERSION_MAJOR) +
526
0
            " is expected. "
527
0
            "It comes from another PROJ installation.");
528
0
    }
529
530
0
    if (minor < DATABASE_LAYOUT_VERSION_MINOR) {
531
0
        throw FactoryException(
532
0
            path +
533
0
            " contains DATABASE.LAYOUT.VERSION.MINOR = " + toString(minor) +
534
0
            " whereas a number >= " + toString(DATABASE_LAYOUT_VERSION_MINOR) +
535
0
            " is expected. "
536
0
            "It comes from another PROJ installation.");
537
0
    }
538
539
0
    if (dbNamePrefix.empty()) {
540
0
        nLayoutVersionMajor_ = major;
541
0
        nLayoutVersionMinor_ = minor;
542
0
    } else if (nLayoutVersionMajor_ != major || nLayoutVersionMinor_ != minor) {
543
0
        throw FactoryException(
544
0
            "Auxiliary database " + path +
545
0
            " contains a DATABASE.LAYOUT.VERSION =  " + toString(major) + '.' +
546
0
            toString(minor) +
547
0
            " which is different from the one from the main database " +
548
0
            mainDbPath + " which is " + toString(nLayoutVersionMajor_) + '.' +
549
0
            toString(nLayoutVersionMinor_));
550
0
    }
551
0
}
552
553
// ---------------------------------------------------------------------------
554
555
#ifndef SQLITE_DETERMINISTIC
556
#define SQLITE_DETERMINISTIC 0
557
#endif
558
559
0
void SQLiteHandle::initialize() {
560
561
    // There is a bug in sqlite 3.38.0 with some complex queries.
562
    // Cf https://github.com/OSGeo/PROJ/issues/3077
563
    // Disabling Bloom-filter pull-down optimization as suggested in
564
    // https://sqlite.org/forum/forumpost/7d3a75438c
565
0
    const int sqlite3VersionNumber = sqlite3_libversion_number();
566
0
    if (sqlite3VersionNumber == 3 * 1000000 + 38 * 1000) {
567
0
        sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite_handle_,
568
0
                             0x100000);
569
0
    }
570
571
0
    sqlite3_create_function(sqlite_handle_, "pseudo_area_from_swne", 4,
572
0
                            SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
573
0
                            PROJ_SQLITE_pseudo_area_from_swne, nullptr,
574
0
                            nullptr);
575
576
0
    sqlite3_create_function(sqlite_handle_, "intersects_bbox", 8,
577
0
                            SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
578
0
                            PROJ_SQLITE_intersects_bbox, nullptr, nullptr);
579
0
}
580
581
// ---------------------------------------------------------------------------
582
583
class SQLiteHandleCache {
584
#ifdef REOPEN_SQLITE_DB_AFTER_FORK
585
    bool firstTime_ = true;
586
#endif
587
588
    std::mutex sMutex_{};
589
590
    // Map dbname to SQLiteHandle
591
    lru11::Cache<std::string, std::shared_ptr<SQLiteHandle>> cache_{};
592
593
  public:
594
    static SQLiteHandleCache &get();
595
596
    std::shared_ptr<SQLiteHandle> getHandle(const std::string &path,
597
                                            PJ_CONTEXT *ctx);
598
599
    void clear();
600
601
#ifdef REOPEN_SQLITE_DB_AFTER_FORK
602
    void invalidateHandles();
603
#endif
604
};
605
606
// ---------------------------------------------------------------------------
607
608
28.9k
SQLiteHandleCache &SQLiteHandleCache::get() {
609
    // Global cache
610
28.9k
    static SQLiteHandleCache gSQLiteHandleCache;
611
28.9k
    return gSQLiteHandleCache;
612
28.9k
}
613
614
// ---------------------------------------------------------------------------
615
616
28.9k
void SQLiteHandleCache::clear() {
617
28.9k
    std::lock_guard<std::mutex> lock(sMutex_);
618
28.9k
    cache_.clear();
619
28.9k
}
620
621
// ---------------------------------------------------------------------------
622
623
std::shared_ptr<SQLiteHandle>
624
0
SQLiteHandleCache::getHandle(const std::string &path, PJ_CONTEXT *ctx) {
625
0
    std::lock_guard<std::mutex> lock(sMutex_);
626
627
0
#ifdef REOPEN_SQLITE_DB_AFTER_FORK
628
0
    if (firstTime_) {
629
0
        firstTime_ = false;
630
0
        pthread_atfork(nullptr, nullptr,
631
0
                       []() { SQLiteHandleCache::get().invalidateHandles(); });
632
0
    }
633
0
#endif
634
635
0
    std::shared_ptr<SQLiteHandle> handle;
636
0
    std::string key = path + ctx->custom_sqlite3_vfs_name;
637
0
    if (!cache_.tryGet(key, handle)) {
638
0
        handle = SQLiteHandle::open(ctx, path);
639
0
        cache_.insert(key, handle);
640
0
    }
641
0
    return handle;
642
0
}
643
644
#ifdef REOPEN_SQLITE_DB_AFTER_FORK
645
// ---------------------------------------------------------------------------
646
647
0
void SQLiteHandleCache::invalidateHandles() {
648
0
    std::lock_guard<std::mutex> lock(sMutex_);
649
0
    const auto lambda =
650
0
        [](const lru11::KeyValuePair<std::string, std::shared_ptr<SQLiteHandle>>
651
0
               &kvp) { kvp.value->invalidate(); };
652
0
    cache_.cwalk(lambda);
653
0
    cache_.clear();
654
0
}
655
#endif
656
657
// ---------------------------------------------------------------------------
658
659
struct DatabaseContext::Private {
660
    Private();
661
    ~Private();
662
663
    void open(const std::string &databasePath, PJ_CONTEXT *ctx);
664
    void setHandle(sqlite3 *sqlite_handle);
665
666
    const std::shared_ptr<SQLiteHandle> &handle();
667
668
70.6k
    PJ_CONTEXT *pjCtxt() const { return pjCtxt_; }
669
70.6k
    void setPjCtxt(PJ_CONTEXT *ctxt) { pjCtxt_ = ctxt; }
670
671
    SQLResultSet run(const std::string &sql,
672
                     const ListOfParams &parameters = ListOfParams(),
673
                     bool useMaxFloatPrecision = false);
674
675
    std::vector<std::string> getDatabaseStructure();
676
677
    // cppcheck-suppress functionStatic
678
0
    const std::string &getPath() const { return databasePath_; }
679
680
    void attachExtraDatabases(
681
        const std::vector<std::string> &auxiliaryDatabasePaths);
682
683
    // Mechanism to detect recursion in calls from
684
    // AuthorityFactory::createXXX() -> createFromUserInput() ->
685
    // AuthorityFactory::createXXX()
686
    struct RecursionDetector {
687
        explicit RecursionDetector(const DatabaseContextNNPtr &context)
688
0
            : dbContext_(context) {
689
0
            if (dbContext_->getPrivate()->recLevel_ == 2) {
690
                // Throw exception before incrementing, since the destructor
691
                // will not be called
692
0
                throw FactoryException("Too many recursive calls");
693
0
            }
694
0
            ++dbContext_->getPrivate()->recLevel_;
695
0
        }
696
697
0
        ~RecursionDetector() { --dbContext_->getPrivate()->recLevel_; }
698
699
      private:
700
        DatabaseContextNNPtr dbContext_;
701
    };
702
703
0
    std::map<std::string, std::list<SQLRow>> &getMapCanonicalizeGRFName() {
704
0
        return mapCanonicalizeGRFName_;
705
0
    }
706
707
    // cppcheck-suppress functionStatic
708
    common::UnitOfMeasurePtr getUOMFromCache(const std::string &code);
709
    // cppcheck-suppress functionStatic
710
    void cache(const std::string &code, const common::UnitOfMeasureNNPtr &uom);
711
712
    // cppcheck-suppress functionStatic
713
    crs::CRSPtr getCRSFromCache(const std::string &code);
714
    // cppcheck-suppress functionStatic
715
    void cache(const std::string &code, const crs::CRSNNPtr &crs);
716
717
    datum::GeodeticReferenceFramePtr
718
    // cppcheck-suppress functionStatic
719
    getGeodeticDatumFromCache(const std::string &code);
720
    // cppcheck-suppress functionStatic
721
    void cache(const std::string &code,
722
               const datum::GeodeticReferenceFrameNNPtr &datum);
723
724
    datum::DatumEnsemblePtr
725
    // cppcheck-suppress functionStatic
726
    getDatumEnsembleFromCache(const std::string &code);
727
    // cppcheck-suppress functionStatic
728
    void cache(const std::string &code,
729
               const datum::DatumEnsembleNNPtr &datumEnsemble);
730
731
    datum::EllipsoidPtr
732
    // cppcheck-suppress functionStatic
733
    getEllipsoidFromCache(const std::string &code);
734
    // cppcheck-suppress functionStatic
735
    void cache(const std::string &code, const datum::EllipsoidNNPtr &ellipsoid);
736
737
    datum::PrimeMeridianPtr
738
    // cppcheck-suppress functionStatic
739
    getPrimeMeridianFromCache(const std::string &code);
740
    // cppcheck-suppress functionStatic
741
    void cache(const std::string &code, const datum::PrimeMeridianNNPtr &pm);
742
743
    // cppcheck-suppress functionStatic
744
    cs::CoordinateSystemPtr
745
    getCoordinateSystemFromCache(const std::string &code);
746
    // cppcheck-suppress functionStatic
747
    void cache(const std::string &code, const cs::CoordinateSystemNNPtr &cs);
748
749
    // cppcheck-suppress functionStatic
750
    metadata::ExtentPtr getExtentFromCache(const std::string &code);
751
    // cppcheck-suppress functionStatic
752
    void cache(const std::string &code, const metadata::ExtentNNPtr &extent);
753
754
    // cppcheck-suppress functionStatic
755
    bool getCRSToCRSCoordOpFromCache(
756
        const std::string &code,
757
        std::vector<operation::CoordinateOperationNNPtr> &list);
758
    // cppcheck-suppress functionStatic
759
    void cache(const std::string &code,
760
               const std::vector<operation::CoordinateOperationNNPtr> &list);
761
762
    struct GridInfoCache {
763
        std::string fullFilename{};
764
        std::string packageName{};
765
        std::string url{};
766
        bool found = false;
767
        bool directDownload = false;
768
        bool openLicense = false;
769
        bool gridAvailable = false;
770
    };
771
772
    // cppcheck-suppress functionStatic
773
    bool getGridInfoFromCache(const std::string &code, GridInfoCache &info);
774
    // cppcheck-suppress functionStatic
775
    void cache(const std::string &code, const GridInfoCache &info);
776
777
    struct VersionedAuthName {
778
        std::string versionedAuthName{};
779
        std::string authName{};
780
        std::string version{};
781
        int priority = 0;
782
    };
783
    const std::vector<VersionedAuthName> &getCacheAuthNameWithVersion();
784
785
  private:
786
    friend class DatabaseContext;
787
788
    // This is a manual implementation of std::enable_shared_from_this<> that
789
    // avoids publicly deriving from it.
790
    std::weak_ptr<DatabaseContext> self_{};
791
792
    std::string databasePath_{};
793
    std::vector<std::string> auxiliaryDatabasePaths_{};
794
    std::shared_ptr<SQLiteHandle> sqlite_handle_{};
795
    std::map<std::string, sqlite3_stmt *> mapSqlToStatement_{};
796
    PJ_CONTEXT *pjCtxt_ = nullptr;
797
    int recLevel_ = 0;
798
    bool detach_ = false;
799
    std::string lastMetadataValue_{};
800
    std::map<std::string, std::list<SQLRow>> mapCanonicalizeGRFName_{};
801
802
    // Used by startInsertStatementsSession() and related functions
803
    std::string memoryDbForInsertPath_{};
804
    std::unique_ptr<SQLiteHandle> memoryDbHandle_{};
805
806
    using LRUCacheOfObjects = lru11::Cache<std::string, util::BaseObjectPtr>;
807
808
    static constexpr size_t CACHE_SIZE = 128;
809
    LRUCacheOfObjects cacheUOM_{CACHE_SIZE};
810
    LRUCacheOfObjects cacheCRS_{CACHE_SIZE};
811
    LRUCacheOfObjects cacheEllipsoid_{CACHE_SIZE};
812
    LRUCacheOfObjects cacheGeodeticDatum_{CACHE_SIZE};
813
    LRUCacheOfObjects cacheDatumEnsemble_{CACHE_SIZE};
814
    LRUCacheOfObjects cachePrimeMeridian_{CACHE_SIZE};
815
    LRUCacheOfObjects cacheCS_{CACHE_SIZE};
816
    LRUCacheOfObjects cacheExtent_{CACHE_SIZE};
817
    lru11::Cache<std::string, std::vector<operation::CoordinateOperationNNPtr>>
818
        cacheCRSToCrsCoordOp_{CACHE_SIZE};
819
    lru11::Cache<std::string, GridInfoCache> cacheGridInfo_{CACHE_SIZE};
820
821
    std::map<std::string, std::vector<std::string>> cacheAllowedAuthorities_{};
822
823
    lru11::Cache<std::string, std::list<std::string>> cacheAliasNames_{
824
        CACHE_SIZE};
825
826
    std::vector<VersionedAuthName> cacheAuthNameWithVersion_{};
827
828
    static void insertIntoCache(LRUCacheOfObjects &cache,
829
                                const std::string &code,
830
                                const util::BaseObjectPtr &obj);
831
832
    static void getFromCache(LRUCacheOfObjects &cache, const std::string &code,
833
                             util::BaseObjectPtr &obj);
834
835
    void closeDB() noexcept;
836
837
    void clearCaches();
838
839
    std::string findFreeCode(const std::string &tableName,
840
                             const std::string &authName,
841
                             const std::string &codePrototype);
842
843
    void identify(const DatabaseContextNNPtr &dbContext,
844
                  const cs::CoordinateSystemNNPtr &obj, std::string &authName,
845
                  std::string &code);
846
    void identifyOrInsert(const DatabaseContextNNPtr &dbContext,
847
                          const cs::CoordinateSystemNNPtr &obj,
848
                          const std::string &ownerType,
849
                          const std::string &ownerAuthName,
850
                          const std::string &ownerCode, std::string &authName,
851
                          std::string &code,
852
                          std::vector<std::string> &sqlStatements);
853
854
    void identify(const DatabaseContextNNPtr &dbContext,
855
                  const common::UnitOfMeasure &obj, std::string &authName,
856
                  std::string &code);
857
    void identifyOrInsert(const DatabaseContextNNPtr &dbContext,
858
                          const common::UnitOfMeasure &unit,
859
                          const std::string &ownerAuthName,
860
                          std::string &authName, std::string &code,
861
                          std::vector<std::string> &sqlStatements);
862
863
    void appendSql(std::vector<std::string> &sqlStatements,
864
                   const std::string &sql);
865
866
    void
867
    identifyOrInsertUsages(const common::ObjectUsageNNPtr &obj,
868
                           const std::string &tableName,
869
                           const std::string &authName, const std::string &code,
870
                           const std::vector<std::string> &allowedAuthorities,
871
                           std::vector<std::string> &sqlStatements);
872
873
    std::vector<std::string>
874
    getInsertStatementsFor(const datum::PrimeMeridianNNPtr &pm,
875
                           const std::string &authName, const std::string &code,
876
                           bool numericCode,
877
                           const std::vector<std::string> &allowedAuthorities);
878
879
    std::vector<std::string>
880
    getInsertStatementsFor(const datum::EllipsoidNNPtr &ellipsoid,
881
                           const std::string &authName, const std::string &code,
882
                           bool numericCode,
883
                           const std::vector<std::string> &allowedAuthorities);
884
885
    std::vector<std::string>
886
    getInsertStatementsFor(const datum::GeodeticReferenceFrameNNPtr &datum,
887
                           const std::string &authName, const std::string &code,
888
                           bool numericCode,
889
                           const std::vector<std::string> &allowedAuthorities);
890
891
    std::vector<std::string>
892
    getInsertStatementsFor(const datum::DatumEnsembleNNPtr &ensemble,
893
                           const std::string &authName, const std::string &code,
894
                           bool numericCode,
895
                           const std::vector<std::string> &allowedAuthorities);
896
897
    std::vector<std::string>
898
    getInsertStatementsFor(const crs::GeodeticCRSNNPtr &crs,
899
                           const std::string &authName, const std::string &code,
900
                           bool numericCode,
901
                           const std::vector<std::string> &allowedAuthorities);
902
903
    std::vector<std::string>
904
    getInsertStatementsFor(const crs::ProjectedCRSNNPtr &crs,
905
                           const std::string &authName, const std::string &code,
906
                           bool numericCode,
907
                           const std::vector<std::string> &allowedAuthorities);
908
909
    std::vector<std::string>
910
    getInsertStatementsFor(const datum::VerticalReferenceFrameNNPtr &datum,
911
                           const std::string &authName, const std::string &code,
912
                           bool numericCode,
913
                           const std::vector<std::string> &allowedAuthorities);
914
915
    std::vector<std::string>
916
    getInsertStatementsFor(const crs::VerticalCRSNNPtr &crs,
917
                           const std::string &authName, const std::string &code,
918
                           bool numericCode,
919
                           const std::vector<std::string> &allowedAuthorities);
920
921
    std::vector<std::string>
922
    getInsertStatementsFor(const crs::CompoundCRSNNPtr &crs,
923
                           const std::string &authName, const std::string &code,
924
                           bool numericCode,
925
                           const std::vector<std::string> &allowedAuthorities);
926
927
    Private(const Private &) = delete;
928
    Private &operator=(const Private &) = delete;
929
};
930
931
// ---------------------------------------------------------------------------
932
933
70.6k
DatabaseContext::Private::Private() = default;
934
935
// ---------------------------------------------------------------------------
936
937
70.6k
DatabaseContext::Private::~Private() {
938
70.6k
    assert(recLevel_ == 0);
939
940
70.6k
    closeDB();
941
70.6k
}
942
943
// ---------------------------------------------------------------------------
944
945
70.6k
void DatabaseContext::Private::closeDB() noexcept {
946
947
70.6k
    if (detach_) {
948
        // Workaround a bug visible in SQLite 3.8.1 and 3.8.2 that causes
949
        // a crash in TEST(factory, attachExtraDatabases_auxiliary)
950
        // due to possible wrong caching of key info.
951
        // The bug is specific to using a memory file with shared cache as an
952
        // auxiliary DB.
953
        // The fix was likely in 3.8.8
954
        // https://github.com/mackyle/sqlite/commit/d412d4b8731991ecbd8811874aa463d0821673eb
955
        // But just after 3.8.2,
956
        // https://github.com/mackyle/sqlite/commit/ccf328c4318eacedab9ed08c404bc4f402dcad19
957
        // also seemed to hide the issue.
958
        // Detaching a database hides the issue, not sure if it is by chance...
959
0
        try {
960
0
            run("DETACH DATABASE db_0");
961
0
        } catch (...) {
962
0
        }
963
0
        detach_ = false;
964
0
    }
965
966
70.6k
    for (auto &pair : mapSqlToStatement_) {
967
0
        sqlite3_finalize(pair.second);
968
0
    }
969
70.6k
    mapSqlToStatement_.clear();
970
971
70.6k
    sqlite_handle_.reset();
972
70.6k
}
973
974
// ---------------------------------------------------------------------------
975
976
0
void DatabaseContext::Private::clearCaches() {
977
978
0
    cacheUOM_.clear();
979
0
    cacheCRS_.clear();
980
0
    cacheEllipsoid_.clear();
981
0
    cacheGeodeticDatum_.clear();
982
0
    cacheDatumEnsemble_.clear();
983
0
    cachePrimeMeridian_.clear();
984
0
    cacheCS_.clear();
985
0
    cacheExtent_.clear();
986
0
    cacheCRSToCrsCoordOp_.clear();
987
0
    cacheGridInfo_.clear();
988
0
    cacheAllowedAuthorities_.clear();
989
0
    cacheAliasNames_.clear();
990
0
}
991
992
// ---------------------------------------------------------------------------
993
994
0
const std::shared_ptr<SQLiteHandle> &DatabaseContext::Private::handle() {
995
0
#ifdef REOPEN_SQLITE_DB_AFTER_FORK
996
0
    if (sqlite_handle_ && !sqlite_handle_->isValid()) {
997
0
        closeDB();
998
0
        open(databasePath_, pjCtxt_);
999
0
        if (!auxiliaryDatabasePaths_.empty()) {
1000
0
            attachExtraDatabases(auxiliaryDatabasePaths_);
1001
0
        }
1002
0
    }
1003
0
#endif
1004
0
    return sqlite_handle_;
1005
0
}
1006
1007
// ---------------------------------------------------------------------------
1008
1009
void DatabaseContext::Private::insertIntoCache(LRUCacheOfObjects &cache,
1010
                                               const std::string &code,
1011
0
                                               const util::BaseObjectPtr &obj) {
1012
0
    cache.insert(code, obj);
1013
0
}
1014
1015
// ---------------------------------------------------------------------------
1016
1017
void DatabaseContext::Private::getFromCache(LRUCacheOfObjects &cache,
1018
                                            const std::string &code,
1019
0
                                            util::BaseObjectPtr &obj) {
1020
0
    cache.tryGet(code, obj);
1021
0
}
1022
1023
// ---------------------------------------------------------------------------
1024
1025
bool DatabaseContext::Private::getCRSToCRSCoordOpFromCache(
1026
    const std::string &code,
1027
0
    std::vector<operation::CoordinateOperationNNPtr> &list) {
1028
0
    return cacheCRSToCrsCoordOp_.tryGet(code, list);
1029
0
}
1030
1031
// ---------------------------------------------------------------------------
1032
1033
void DatabaseContext::Private::cache(
1034
    const std::string &code,
1035
0
    const std::vector<operation::CoordinateOperationNNPtr> &list) {
1036
0
    cacheCRSToCrsCoordOp_.insert(code, list);
1037
0
}
1038
1039
// ---------------------------------------------------------------------------
1040
1041
0
crs::CRSPtr DatabaseContext::Private::getCRSFromCache(const std::string &code) {
1042
0
    util::BaseObjectPtr obj;
1043
0
    getFromCache(cacheCRS_, code, obj);
1044
0
    return std::static_pointer_cast<crs::CRS>(obj);
1045
0
}
1046
1047
// ---------------------------------------------------------------------------
1048
1049
void DatabaseContext::Private::cache(const std::string &code,
1050
0
                                     const crs::CRSNNPtr &crs) {
1051
0
    insertIntoCache(cacheCRS_, code, crs.as_nullable());
1052
0
}
1053
1054
// ---------------------------------------------------------------------------
1055
1056
common::UnitOfMeasurePtr
1057
0
DatabaseContext::Private::getUOMFromCache(const std::string &code) {
1058
0
    util::BaseObjectPtr obj;
1059
0
    getFromCache(cacheUOM_, code, obj);
1060
0
    return std::static_pointer_cast<common::UnitOfMeasure>(obj);
1061
0
}
1062
1063
// ---------------------------------------------------------------------------
1064
1065
void DatabaseContext::Private::cache(const std::string &code,
1066
0
                                     const common::UnitOfMeasureNNPtr &uom) {
1067
0
    insertIntoCache(cacheUOM_, code, uom.as_nullable());
1068
0
}
1069
1070
// ---------------------------------------------------------------------------
1071
1072
datum::GeodeticReferenceFramePtr
1073
0
DatabaseContext::Private::getGeodeticDatumFromCache(const std::string &code) {
1074
0
    util::BaseObjectPtr obj;
1075
0
    getFromCache(cacheGeodeticDatum_, code, obj);
1076
0
    return std::static_pointer_cast<datum::GeodeticReferenceFrame>(obj);
1077
0
}
1078
1079
// ---------------------------------------------------------------------------
1080
1081
void DatabaseContext::Private::cache(
1082
0
    const std::string &code, const datum::GeodeticReferenceFrameNNPtr &datum) {
1083
0
    insertIntoCache(cacheGeodeticDatum_, code, datum.as_nullable());
1084
0
}
1085
1086
// ---------------------------------------------------------------------------
1087
1088
datum::DatumEnsemblePtr
1089
0
DatabaseContext::Private::getDatumEnsembleFromCache(const std::string &code) {
1090
0
    util::BaseObjectPtr obj;
1091
0
    getFromCache(cacheDatumEnsemble_, code, obj);
1092
0
    return std::static_pointer_cast<datum::DatumEnsemble>(obj);
1093
0
}
1094
1095
// ---------------------------------------------------------------------------
1096
1097
void DatabaseContext::Private::cache(
1098
0
    const std::string &code, const datum::DatumEnsembleNNPtr &datumEnsemble) {
1099
0
    insertIntoCache(cacheDatumEnsemble_, code, datumEnsemble.as_nullable());
1100
0
}
1101
1102
// ---------------------------------------------------------------------------
1103
1104
datum::EllipsoidPtr
1105
0
DatabaseContext::Private::getEllipsoidFromCache(const std::string &code) {
1106
0
    util::BaseObjectPtr obj;
1107
0
    getFromCache(cacheEllipsoid_, code, obj);
1108
0
    return std::static_pointer_cast<datum::Ellipsoid>(obj);
1109
0
}
1110
1111
// ---------------------------------------------------------------------------
1112
1113
void DatabaseContext::Private::cache(const std::string &code,
1114
0
                                     const datum::EllipsoidNNPtr &ellps) {
1115
0
    insertIntoCache(cacheEllipsoid_, code, ellps.as_nullable());
1116
0
}
1117
1118
// ---------------------------------------------------------------------------
1119
1120
datum::PrimeMeridianPtr
1121
0
DatabaseContext::Private::getPrimeMeridianFromCache(const std::string &code) {
1122
0
    util::BaseObjectPtr obj;
1123
0
    getFromCache(cachePrimeMeridian_, code, obj);
1124
0
    return std::static_pointer_cast<datum::PrimeMeridian>(obj);
1125
0
}
1126
1127
// ---------------------------------------------------------------------------
1128
1129
void DatabaseContext::Private::cache(const std::string &code,
1130
0
                                     const datum::PrimeMeridianNNPtr &pm) {
1131
0
    insertIntoCache(cachePrimeMeridian_, code, pm.as_nullable());
1132
0
}
1133
1134
// ---------------------------------------------------------------------------
1135
1136
cs::CoordinateSystemPtr DatabaseContext::Private::getCoordinateSystemFromCache(
1137
0
    const std::string &code) {
1138
0
    util::BaseObjectPtr obj;
1139
0
    getFromCache(cacheCS_, code, obj);
1140
0
    return std::static_pointer_cast<cs::CoordinateSystem>(obj);
1141
0
}
1142
1143
// ---------------------------------------------------------------------------
1144
1145
void DatabaseContext::Private::cache(const std::string &code,
1146
0
                                     const cs::CoordinateSystemNNPtr &cs) {
1147
0
    insertIntoCache(cacheCS_, code, cs.as_nullable());
1148
0
}
1149
1150
// ---------------------------------------------------------------------------
1151
1152
metadata::ExtentPtr
1153
0
DatabaseContext::Private::getExtentFromCache(const std::string &code) {
1154
0
    util::BaseObjectPtr obj;
1155
0
    getFromCache(cacheExtent_, code, obj);
1156
0
    return std::static_pointer_cast<metadata::Extent>(obj);
1157
0
}
1158
1159
// ---------------------------------------------------------------------------
1160
1161
void DatabaseContext::Private::cache(const std::string &code,
1162
0
                                     const metadata::ExtentNNPtr &extent) {
1163
0
    insertIntoCache(cacheExtent_, code, extent.as_nullable());
1164
0
}
1165
1166
// ---------------------------------------------------------------------------
1167
1168
bool DatabaseContext::Private::getGridInfoFromCache(const std::string &code,
1169
0
                                                    GridInfoCache &info) {
1170
0
    return cacheGridInfo_.tryGet(code, info);
1171
0
}
1172
1173
// ---------------------------------------------------------------------------
1174
1175
void DatabaseContext::Private::cache(const std::string &code,
1176
0
                                     const GridInfoCache &info) {
1177
0
    cacheGridInfo_.insert(code, info);
1178
0
}
1179
1180
// ---------------------------------------------------------------------------
1181
1182
void DatabaseContext::Private::open(const std::string &databasePath,
1183
70.6k
                                    PJ_CONTEXT *ctx) {
1184
70.6k
    if (!ctx) {
1185
0
        ctx = pj_get_default_ctx();
1186
0
    }
1187
1188
70.6k
    setPjCtxt(ctx);
1189
70.6k
    std::string path(databasePath);
1190
70.6k
    if (path.empty()) {
1191
70.6k
        path.resize(2048);
1192
70.6k
        const bool found =
1193
70.6k
            pj_find_file(pjCtxt(), "proj.db", &path[0], path.size() - 1) != 0;
1194
70.6k
        path.resize(strlen(path.c_str()));
1195
70.6k
        if (!found) {
1196
70.6k
            throw FactoryException("Cannot find proj.db");
1197
70.6k
        }
1198
70.6k
    }
1199
1200
0
    sqlite_handle_ = SQLiteHandleCache::get().getHandle(path, ctx);
1201
1202
0
    databasePath_ = std::move(path);
1203
0
}
1204
1205
// ---------------------------------------------------------------------------
1206
1207
0
void DatabaseContext::Private::setHandle(sqlite3 *sqlite_handle) {
1208
1209
0
    assert(sqlite_handle);
1210
0
    assert(!sqlite_handle_);
1211
0
    sqlite_handle_ = SQLiteHandle::initFromExisting(sqlite_handle, false, 0, 0);
1212
0
}
1213
1214
// ---------------------------------------------------------------------------
1215
1216
0
std::vector<std::string> DatabaseContext::Private::getDatabaseStructure() {
1217
0
    const std::string dbNamePrefix(auxiliaryDatabasePaths_.empty() &&
1218
0
                                           memoryDbForInsertPath_.empty()
1219
0
                                       ? ""
1220
0
                                       : "db_0.");
1221
0
    const auto sqlBegin("SELECT sql||';' FROM " + dbNamePrefix +
1222
0
                        "sqlite_master WHERE type = ");
1223
0
    const char *tableType = "'table' AND name NOT LIKE 'sqlite_stat%'";
1224
0
    const char *const objectTypes[] = {tableType, "'view'", "'trigger'"};
1225
0
    std::vector<std::string> res;
1226
0
    for (const auto &objectType : objectTypes) {
1227
0
        const auto sqlRes = run(sqlBegin + objectType);
1228
0
        for (const auto &row : sqlRes) {
1229
0
            res.emplace_back(row[0]);
1230
0
        }
1231
0
    }
1232
0
    if (sqlite_handle_->getLayoutVersionMajor() > 0) {
1233
0
        res.emplace_back(
1234
0
            "INSERT INTO metadata VALUES('DATABASE.LAYOUT.VERSION.MAJOR'," +
1235
0
            toString(sqlite_handle_->getLayoutVersionMajor()) + ");");
1236
0
        res.emplace_back(
1237
0
            "INSERT INTO metadata VALUES('DATABASE.LAYOUT.VERSION.MINOR'," +
1238
0
            toString(sqlite_handle_->getLayoutVersionMinor()) + ");");
1239
0
    }
1240
0
    return res;
1241
0
}
1242
1243
// ---------------------------------------------------------------------------
1244
1245
void DatabaseContext::Private::attachExtraDatabases(
1246
0
    const std::vector<std::string> &auxiliaryDatabasePaths) {
1247
1248
0
    auto l_handle = handle();
1249
0
    assert(l_handle);
1250
1251
0
    auto tables =
1252
0
        run("SELECT name FROM sqlite_master WHERE type IN ('table', 'view') "
1253
0
            "AND name NOT LIKE 'sqlite_stat%'");
1254
0
    std::map<std::string, std::vector<std::string>> tableStructure;
1255
0
    for (const auto &rowTable : tables) {
1256
0
        const auto &tableName = rowTable[0];
1257
0
        auto tableInfo = run("PRAGMA table_info(\"" +
1258
0
                             replaceAll(tableName, "\"", "\"\"") + "\")");
1259
0
        for (const auto &rowCol : tableInfo) {
1260
0
            const auto &colName = rowCol[1];
1261
0
            tableStructure[tableName].push_back(colName);
1262
0
        }
1263
0
    }
1264
1265
0
    const int nLayoutVersionMajor = l_handle->getLayoutVersionMajor();
1266
0
    const int nLayoutVersionMinor = l_handle->getLayoutVersionMinor();
1267
1268
0
    closeDB();
1269
0
    if (auxiliaryDatabasePaths.empty()) {
1270
0
        open(databasePath_, pjCtxt());
1271
0
        return;
1272
0
    }
1273
1274
0
    sqlite3 *sqlite_handle = nullptr;
1275
0
    sqlite3_open_v2(
1276
0
        ":memory:", &sqlite_handle,
1277
0
        SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_URI, nullptr);
1278
0
    if (!sqlite_handle) {
1279
0
        throw FactoryException("cannot create in memory database");
1280
0
    }
1281
0
    sqlite_handle_ = SQLiteHandle::initFromExisting(
1282
0
        sqlite_handle, true, nLayoutVersionMajor, nLayoutVersionMinor);
1283
0
    l_handle = sqlite_handle_;
1284
1285
0
    run("ATTACH DATABASE ? AS db_0", {databasePath_});
1286
0
    detach_ = true;
1287
0
    int count = 1;
1288
0
    for (const auto &otherDbPath : auxiliaryDatabasePaths) {
1289
0
        const auto attachedDbName("db_" + toString(static_cast<int>(count)));
1290
0
        std::string sql = "ATTACH DATABASE ? AS ";
1291
0
        sql += attachedDbName;
1292
0
        count++;
1293
0
        run(sql, {otherDbPath});
1294
1295
0
        l_handle->checkDatabaseLayout(databasePath_, otherDbPath,
1296
0
                                      attachedDbName + '.');
1297
0
    }
1298
1299
0
    for (const auto &pair : tableStructure) {
1300
0
        std::string sql("CREATE TEMP VIEW ");
1301
0
        sql += pair.first;
1302
0
        sql += " AS ";
1303
0
        for (size_t i = 0; i <= auxiliaryDatabasePaths.size(); ++i) {
1304
0
            std::string selectFromAux("SELECT ");
1305
0
            bool firstCol = true;
1306
0
            for (const auto &colName : pair.second) {
1307
0
                if (!firstCol) {
1308
0
                    selectFromAux += ", ";
1309
0
                }
1310
0
                firstCol = false;
1311
0
                selectFromAux += colName;
1312
0
            }
1313
0
            selectFromAux += " FROM db_";
1314
0
            selectFromAux += toString(static_cast<int>(i));
1315
0
            selectFromAux += ".";
1316
0
            selectFromAux += pair.first;
1317
1318
0
            try {
1319
                // Check that the request will succeed. In case of 'sparse'
1320
                // databases...
1321
0
                run(selectFromAux + " LIMIT 0");
1322
1323
0
                if (i > 0) {
1324
0
                    sql += " UNION ALL ";
1325
0
                }
1326
0
                sql += selectFromAux;
1327
0
            } catch (const std::exception &) {
1328
0
            }
1329
0
        }
1330
0
        run(sql);
1331
0
    }
1332
0
}
1333
1334
// ---------------------------------------------------------------------------
1335
1336
SQLResultSet DatabaseContext::Private::run(const std::string &sql,
1337
                                           const ListOfParams &parameters,
1338
0
                                           bool useMaxFloatPrecision) {
1339
1340
0
    auto l_handle = handle();
1341
0
    assert(l_handle);
1342
1343
0
    sqlite3_stmt *stmt = nullptr;
1344
0
    auto iter = mapSqlToStatement_.find(sql);
1345
0
    if (iter != mapSqlToStatement_.end()) {
1346
0
        stmt = iter->second;
1347
0
        sqlite3_reset(stmt);
1348
0
    } else {
1349
0
        if (sqlite3_prepare_v2(l_handle->handle(), sql.c_str(),
1350
0
                               static_cast<int>(sql.size()), &stmt,
1351
0
                               nullptr) != SQLITE_OK) {
1352
0
            throw FactoryException("SQLite error on " + sql + ": " +
1353
0
                                   sqlite3_errmsg(l_handle->handle()));
1354
0
        }
1355
0
        mapSqlToStatement_.insert(
1356
0
            std::pair<std::string, sqlite3_stmt *>(sql, stmt));
1357
0
    }
1358
1359
0
    return l_handle->run(stmt, sql, parameters, useMaxFloatPrecision);
1360
0
}
1361
1362
// ---------------------------------------------------------------------------
1363
1364
0
static std::string formatStatement(const char *fmt, ...) {
1365
0
    std::string res;
1366
0
    va_list args;
1367
0
    va_start(args, fmt);
1368
0
    for (int i = 0; fmt[i] != '\0'; ++i) {
1369
0
        if (fmt[i] == '%') {
1370
0
            if (fmt[i + 1] == '%') {
1371
0
                res += '%';
1372
0
            } else if (fmt[i + 1] == 'q') {
1373
0
                const char *arg = va_arg(args, const char *);
1374
0
                for (int j = 0; arg[j] != '\0'; ++j) {
1375
0
                    if (arg[j] == '\'')
1376
0
                        res += arg[j];
1377
0
                    res += arg[j];
1378
0
                }
1379
0
            } else if (fmt[i + 1] == 'Q') {
1380
0
                const char *arg = va_arg(args, const char *);
1381
0
                if (arg == nullptr)
1382
0
                    res += "NULL";
1383
0
                else {
1384
0
                    res += '\'';
1385
0
                    for (int j = 0; arg[j] != '\0'; ++j) {
1386
0
                        if (arg[j] == '\'')
1387
0
                            res += arg[j];
1388
0
                        res += arg[j];
1389
0
                    }
1390
0
                    res += '\'';
1391
0
                }
1392
0
            } else if (fmt[i + 1] == 's') {
1393
0
                const char *arg = va_arg(args, const char *);
1394
0
                res += arg;
1395
0
            } else if (fmt[i + 1] == 'f') {
1396
0
                const double arg = va_arg(args, double);
1397
0
                res += toString(arg);
1398
0
            } else if (fmt[i + 1] == 'd') {
1399
0
                const int arg = va_arg(args, int);
1400
0
                res += toString(arg);
1401
0
            } else {
1402
0
                va_end(args);
1403
0
                throw FactoryException(
1404
0
                    "Unsupported formatter in formatStatement()");
1405
0
            }
1406
0
            ++i;
1407
0
        } else {
1408
0
            res += fmt[i];
1409
0
        }
1410
0
    }
1411
0
    va_end(args);
1412
0
    return res;
1413
0
}
1414
1415
// ---------------------------------------------------------------------------
1416
1417
void DatabaseContext::Private::appendSql(
1418
0
    std::vector<std::string> &sqlStatements, const std::string &sql) {
1419
0
    sqlStatements.emplace_back(sql);
1420
0
    char *errMsg = nullptr;
1421
0
    if (sqlite3_exec(memoryDbHandle_->handle(), sql.c_str(), nullptr, nullptr,
1422
0
                     &errMsg) != SQLITE_OK) {
1423
0
        std::string s("Cannot execute " + sql);
1424
0
        if (errMsg) {
1425
0
            s += " : ";
1426
0
            s += errMsg;
1427
0
        }
1428
0
        sqlite3_free(errMsg);
1429
0
        throw FactoryException(s);
1430
0
    }
1431
0
    sqlite3_free(errMsg);
1432
0
}
1433
1434
// ---------------------------------------------------------------------------
1435
1436
static void identifyFromNameOrCode(
1437
    const DatabaseContextNNPtr &dbContext,
1438
    const std::vector<std::string> &allowedAuthorities,
1439
    const std::string &authNameParent, const common::IdentifiedObjectNNPtr &obj,
1440
    std::function<std::shared_ptr<util::IComparable>(
1441
        const AuthorityFactoryNNPtr &authFactory, const std::string &)>
1442
        instantiateFunc,
1443
    AuthorityFactory::ObjectType objType, std::string &authName,
1444
0
    std::string &code) {
1445
1446
0
    auto allowedAuthoritiesTmp(allowedAuthorities);
1447
0
    allowedAuthoritiesTmp.emplace_back(authNameParent);
1448
1449
0
    for (const auto &id : obj->identifiers()) {
1450
0
        try {
1451
0
            const auto &idAuthName = *(id->codeSpace());
1452
0
            if (std::find(allowedAuthoritiesTmp.begin(),
1453
0
                          allowedAuthoritiesTmp.end(),
1454
0
                          idAuthName) != allowedAuthoritiesTmp.end()) {
1455
0
                const auto factory =
1456
0
                    AuthorityFactory::create(dbContext, idAuthName);
1457
0
                if (instantiateFunc(factory, id->code())
1458
0
                        ->isEquivalentTo(
1459
0
                            obj.get(),
1460
0
                            util::IComparable::Criterion::EQUIVALENT)) {
1461
0
                    authName = idAuthName;
1462
0
                    code = id->code();
1463
0
                    return;
1464
0
                }
1465
0
            }
1466
0
        } catch (const std::exception &) {
1467
0
        }
1468
0
    }
1469
1470
0
    for (const auto &allowedAuthority : allowedAuthoritiesTmp) {
1471
0
        const auto factory =
1472
0
            AuthorityFactory::create(dbContext, allowedAuthority);
1473
0
        const auto candidates =
1474
0
            factory->createObjectsFromName(obj->nameStr(), {objType}, false, 0);
1475
0
        for (const auto &candidate : candidates) {
1476
0
            const auto &ids = candidate->identifiers();
1477
0
            if (!ids.empty() &&
1478
0
                candidate->isEquivalentTo(
1479
0
                    obj.get(), util::IComparable::Criterion::EQUIVALENT)) {
1480
0
                const auto &id = ids.front();
1481
0
                authName = *(id->codeSpace());
1482
0
                code = id->code();
1483
0
                return;
1484
0
            }
1485
0
        }
1486
0
    }
1487
0
}
1488
1489
// ---------------------------------------------------------------------------
1490
1491
static void
1492
identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext,
1493
                       const std::vector<std::string> &allowedAuthorities,
1494
                       const std::string &authNameParent,
1495
                       const datum::DatumEnsembleNNPtr &obj,
1496
0
                       std::string &authName, std::string &code) {
1497
0
    const char *type = "geodetic_datum";
1498
0
    if (!obj->datums().empty() &&
1499
0
        dynamic_cast<const datum::VerticalReferenceFrame *>(
1500
0
            obj->datums().front().get())) {
1501
0
        type = "vertical_datum";
1502
0
    }
1503
0
    const auto instantiateFunc =
1504
0
        [&type](const AuthorityFactoryNNPtr &authFactory,
1505
0
                const std::string &lCode) {
1506
0
            return util::nn_static_pointer_cast<util::IComparable>(
1507
0
                authFactory->createDatumEnsemble(lCode, type));
1508
0
        };
1509
0
    identifyFromNameOrCode(
1510
0
        dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc,
1511
0
        AuthorityFactory::ObjectType::DATUM_ENSEMBLE, authName, code);
1512
0
}
1513
1514
// ---------------------------------------------------------------------------
1515
1516
static void
1517
identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext,
1518
                       const std::vector<std::string> &allowedAuthorities,
1519
                       const std::string &authNameParent,
1520
                       const datum::GeodeticReferenceFrameNNPtr &obj,
1521
0
                       std::string &authName, std::string &code) {
1522
0
    const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory,
1523
0
                                    const std::string &lCode) {
1524
0
        return util::nn_static_pointer_cast<util::IComparable>(
1525
0
            authFactory->createGeodeticDatum(lCode));
1526
0
    };
1527
0
    identifyFromNameOrCode(
1528
0
        dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc,
1529
0
        AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME, authName, code);
1530
0
}
1531
1532
// ---------------------------------------------------------------------------
1533
1534
static void
1535
identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext,
1536
                       const std::vector<std::string> &allowedAuthorities,
1537
                       const std::string &authNameParent,
1538
                       const datum::EllipsoidNNPtr &obj, std::string &authName,
1539
0
                       std::string &code) {
1540
0
    const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory,
1541
0
                                    const std::string &lCode) {
1542
0
        return util::nn_static_pointer_cast<util::IComparable>(
1543
0
            authFactory->createEllipsoid(lCode));
1544
0
    };
1545
0
    identifyFromNameOrCode(
1546
0
        dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc,
1547
0
        AuthorityFactory::ObjectType::ELLIPSOID, authName, code);
1548
0
}
1549
1550
// ---------------------------------------------------------------------------
1551
1552
static void
1553
identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext,
1554
                       const std::vector<std::string> &allowedAuthorities,
1555
                       const std::string &authNameParent,
1556
                       const datum::PrimeMeridianNNPtr &obj,
1557
0
                       std::string &authName, std::string &code) {
1558
0
    const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory,
1559
0
                                    const std::string &lCode) {
1560
0
        return util::nn_static_pointer_cast<util::IComparable>(
1561
0
            authFactory->createPrimeMeridian(lCode));
1562
0
    };
1563
0
    identifyFromNameOrCode(
1564
0
        dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc,
1565
0
        AuthorityFactory::ObjectType::PRIME_MERIDIAN, authName, code);
1566
0
}
1567
1568
// ---------------------------------------------------------------------------
1569
1570
static void
1571
identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext,
1572
                       const std::vector<std::string> &allowedAuthorities,
1573
                       const std::string &authNameParent,
1574
                       const datum::VerticalReferenceFrameNNPtr &obj,
1575
0
                       std::string &authName, std::string &code) {
1576
0
    const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory,
1577
0
                                    const std::string &lCode) {
1578
0
        return util::nn_static_pointer_cast<util::IComparable>(
1579
0
            authFactory->createVerticalDatum(lCode));
1580
0
    };
1581
0
    identifyFromNameOrCode(
1582
0
        dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc,
1583
0
        AuthorityFactory::ObjectType::VERTICAL_REFERENCE_FRAME, authName, code);
1584
0
}
1585
1586
// ---------------------------------------------------------------------------
1587
1588
static void
1589
identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext,
1590
                       const std::vector<std::string> &allowedAuthorities,
1591
                       const std::string &authNameParent,
1592
                       const datum::DatumNNPtr &obj, std::string &authName,
1593
0
                       std::string &code) {
1594
0
    if (const auto geodeticDatum =
1595
0
            util::nn_dynamic_pointer_cast<datum::GeodeticReferenceFrame>(obj)) {
1596
0
        identifyFromNameOrCode(dbContext, allowedAuthorities, authNameParent,
1597
0
                               NN_NO_CHECK(geodeticDatum), authName, code);
1598
0
    } else if (const auto verticalDatum =
1599
0
                   util::nn_dynamic_pointer_cast<datum::VerticalReferenceFrame>(
1600
0
                       obj)) {
1601
0
        identifyFromNameOrCode(dbContext, allowedAuthorities, authNameParent,
1602
0
                               NN_NO_CHECK(verticalDatum), authName, code);
1603
0
    } else {
1604
0
        throw FactoryException("Unhandled type of datum");
1605
0
    }
1606
0
}
1607
1608
// ---------------------------------------------------------------------------
1609
1610
0
static const char *getCSDatabaseType(const cs::CoordinateSystemNNPtr &obj) {
1611
0
    if (dynamic_cast<const cs::EllipsoidalCS *>(obj.get())) {
1612
0
        return CS_TYPE_ELLIPSOIDAL;
1613
0
    } else if (dynamic_cast<const cs::CartesianCS *>(obj.get())) {
1614
0
        return CS_TYPE_CARTESIAN;
1615
0
    } else if (dynamic_cast<const cs::VerticalCS *>(obj.get())) {
1616
0
        return CS_TYPE_VERTICAL;
1617
0
    }
1618
0
    return nullptr;
1619
0
}
1620
1621
// ---------------------------------------------------------------------------
1622
1623
std::string
1624
DatabaseContext::Private::findFreeCode(const std::string &tableName,
1625
                                       const std::string &authName,
1626
0
                                       const std::string &codePrototype) {
1627
0
    std::string code(codePrototype);
1628
0
    if (run("SELECT 1 FROM " + tableName + " WHERE auth_name = ? AND code = ?",
1629
0
            {authName, code})
1630
0
            .empty()) {
1631
0
        return code;
1632
0
    }
1633
1634
0
    for (int counter = 2; counter < 10; counter++) {
1635
0
        code = codePrototype + '_' + toString(counter);
1636
0
        if (run("SELECT 1 FROM " + tableName +
1637
0
                    " WHERE auth_name = ? AND code = ?",
1638
0
                {authName, code})
1639
0
                .empty()) {
1640
0
            return code;
1641
0
        }
1642
0
    }
1643
1644
    // shouldn't happen hopefully...
1645
0
    throw FactoryException("Cannot insert " + tableName +
1646
0
                           ": too many similar codes");
1647
0
}
1648
1649
// ---------------------------------------------------------------------------
1650
1651
0
static const char *getUnitDatabaseType(const common::UnitOfMeasure &unit) {
1652
0
    switch (unit.type()) {
1653
0
    case common::UnitOfMeasure::Type::LINEAR:
1654
0
        return "length";
1655
1656
0
    case common::UnitOfMeasure::Type::ANGULAR:
1657
0
        return "angle";
1658
1659
0
    case common::UnitOfMeasure::Type::SCALE:
1660
0
        return "scale";
1661
1662
0
    case common::UnitOfMeasure::Type::TIME:
1663
0
        return "time";
1664
1665
0
    default:
1666
0
        break;
1667
0
    }
1668
0
    return nullptr;
1669
0
}
1670
1671
// ---------------------------------------------------------------------------
1672
1673
void DatabaseContext::Private::identify(const DatabaseContextNNPtr &dbContext,
1674
                                        const common::UnitOfMeasure &obj,
1675
                                        std::string &authName,
1676
0
                                        std::string &code) {
1677
    // Identify quickly a few well-known units
1678
0
    const double convFactor = obj.conversionToSI();
1679
0
    switch (obj.type()) {
1680
0
    case common::UnitOfMeasure::Type::LINEAR: {
1681
0
        if (convFactor == 1.0) {
1682
0
            authName = metadata::Identifier::EPSG;
1683
0
            code = "9001";
1684
0
            return;
1685
0
        }
1686
0
        break;
1687
0
    }
1688
0
    case common::UnitOfMeasure::Type::ANGULAR: {
1689
0
        constexpr double CONV_FACTOR_DEGREE = 1.74532925199432781271e-02;
1690
0
        if (std::abs(convFactor - CONV_FACTOR_DEGREE) <=
1691
0
            1e-10 * CONV_FACTOR_DEGREE) {
1692
0
            authName = metadata::Identifier::EPSG;
1693
0
            code = "9102";
1694
0
            return;
1695
0
        }
1696
0
        break;
1697
0
    }
1698
0
    case common::UnitOfMeasure::Type::SCALE: {
1699
0
        if (convFactor == 1.0) {
1700
0
            authName = metadata::Identifier::EPSG;
1701
0
            code = "9201";
1702
0
            return;
1703
0
        }
1704
0
        break;
1705
0
    }
1706
0
    default:
1707
0
        break;
1708
0
    }
1709
1710
0
    std::string sql("SELECT auth_name, code FROM unit_of_measure "
1711
0
                    "WHERE abs(conv_factor - ?) <= 1e-10 * conv_factor");
1712
0
    ListOfParams params{convFactor};
1713
0
    const char *type = getUnitDatabaseType(obj);
1714
0
    if (type) {
1715
0
        sql += " AND type = ?";
1716
0
        params.emplace_back(std::string(type));
1717
0
    }
1718
0
    sql += " ORDER BY auth_name, code";
1719
0
    const auto res = run(sql, params);
1720
0
    for (const auto &row : res) {
1721
0
        const auto &rowAuthName = row[0];
1722
0
        const auto &rowCode = row[1];
1723
0
        const auto tmpAuthFactory =
1724
0
            AuthorityFactory::create(dbContext, rowAuthName);
1725
0
        try {
1726
0
            tmpAuthFactory->createUnitOfMeasure(rowCode);
1727
0
            authName = rowAuthName;
1728
0
            code = rowCode;
1729
0
            return;
1730
0
        } catch (const std::exception &) {
1731
0
        }
1732
0
    }
1733
0
}
1734
1735
// ---------------------------------------------------------------------------
1736
1737
void DatabaseContext::Private::identifyOrInsert(
1738
    const DatabaseContextNNPtr &dbContext, const common::UnitOfMeasure &unit,
1739
    const std::string &ownerAuthName, std::string &authName, std::string &code,
1740
0
    std::vector<std::string> &sqlStatements) {
1741
0
    authName = unit.codeSpace();
1742
0
    code = unit.code();
1743
0
    if (authName.empty()) {
1744
0
        identify(dbContext, unit, authName, code);
1745
0
    }
1746
0
    if (!authName.empty()) {
1747
0
        return;
1748
0
    }
1749
0
    const char *type = getUnitDatabaseType(unit);
1750
0
    if (type == nullptr) {
1751
0
        throw FactoryException("Cannot insert this type of UnitOfMeasure");
1752
0
    }
1753
1754
    // Insert new record
1755
0
    authName = ownerAuthName;
1756
0
    const std::string codePrototype(replaceAll(toupper(unit.name()), " ", "_"));
1757
0
    code = findFreeCode("unit_of_measure", authName, codePrototype);
1758
1759
0
    const auto sql = formatStatement(
1760
0
        "INSERT INTO unit_of_measure VALUES('%q','%q','%q','%q',%f,NULL,0);",
1761
0
        authName.c_str(), code.c_str(), unit.name().c_str(), type,
1762
0
        unit.conversionToSI());
1763
0
    appendSql(sqlStatements, sql);
1764
0
}
1765
1766
// ---------------------------------------------------------------------------
1767
1768
void DatabaseContext::Private::identify(const DatabaseContextNNPtr &dbContext,
1769
                                        const cs::CoordinateSystemNNPtr &obj,
1770
                                        std::string &authName,
1771
0
                                        std::string &code) {
1772
1773
0
    const auto &axisList = obj->axisList();
1774
0
    if (axisList.size() == 1U &&
1775
0
        axisList[0]->unit()._isEquivalentTo(UnitOfMeasure::METRE) &&
1776
0
        &(axisList[0]->direction()) == &cs::AxisDirection::UP &&
1777
0
        (axisList[0]->nameStr() == "Up" ||
1778
0
         axisList[0]->nameStr() == "Gravity-related height")) {
1779
        // preferred coordinate system for gravity-related height
1780
0
        authName = metadata::Identifier::EPSG;
1781
0
        code = "6499";
1782
0
        return;
1783
0
    }
1784
1785
0
    std::string sql(
1786
0
        "SELECT auth_name, code FROM coordinate_system WHERE dimension = ?");
1787
0
    ListOfParams params{static_cast<int>(axisList.size())};
1788
0
    const char *type = getCSDatabaseType(obj);
1789
0
    if (type) {
1790
0
        sql += " AND type = ?";
1791
0
        params.emplace_back(std::string(type));
1792
0
    }
1793
0
    sql += " ORDER BY auth_name, code";
1794
0
    const auto res = run(sql, params);
1795
0
    for (const auto &row : res) {
1796
0
        const auto &rowAuthName = row[0];
1797
0
        const auto &rowCode = row[1];
1798
0
        const auto tmpAuthFactory =
1799
0
            AuthorityFactory::create(dbContext, rowAuthName);
1800
0
        try {
1801
0
            const auto cs = tmpAuthFactory->createCoordinateSystem(rowCode);
1802
0
            if (cs->_isEquivalentTo(obj.get(),
1803
0
                                    util::IComparable::Criterion::EQUIVALENT)) {
1804
0
                authName = rowAuthName;
1805
0
                code = rowCode;
1806
0
                if (authName == metadata::Identifier::EPSG && code == "4400") {
1807
                    // preferred coordinate system for cartesian
1808
                    // Easting, Northing
1809
0
                    return;
1810
0
                }
1811
0
                if (authName == metadata::Identifier::EPSG && code == "6422") {
1812
                    // preferred coordinate system for geographic lat, long
1813
0
                    return;
1814
0
                }
1815
0
                if (authName == metadata::Identifier::EPSG && code == "6423") {
1816
                    // preferred coordinate system for geographic lat, long, h
1817
0
                    return;
1818
0
                }
1819
0
            }
1820
0
        } catch (const std::exception &) {
1821
0
        }
1822
0
    }
1823
0
}
1824
1825
// ---------------------------------------------------------------------------
1826
1827
void DatabaseContext::Private::identifyOrInsert(
1828
    const DatabaseContextNNPtr &dbContext, const cs::CoordinateSystemNNPtr &obj,
1829
    const std::string &ownerType, const std::string &ownerAuthName,
1830
    const std::string &ownerCode, std::string &authName, std::string &code,
1831
0
    std::vector<std::string> &sqlStatements) {
1832
1833
0
    identify(dbContext, obj, authName, code);
1834
0
    if (!authName.empty()) {
1835
0
        return;
1836
0
    }
1837
1838
0
    const char *type = getCSDatabaseType(obj);
1839
0
    if (type == nullptr) {
1840
0
        throw FactoryException("Cannot insert this type of CoordinateSystem");
1841
0
    }
1842
1843
    // Insert new record in coordinate_system
1844
0
    authName = ownerAuthName;
1845
0
    const std::string codePrototype("CS_" + ownerType + '_' + ownerCode);
1846
0
    code = findFreeCode("coordinate_system", authName, codePrototype);
1847
1848
0
    const auto &axisList = obj->axisList();
1849
0
    {
1850
0
        const auto sql = formatStatement(
1851
0
            "INSERT INTO coordinate_system VALUES('%q','%q','%q',%d);",
1852
0
            authName.c_str(), code.c_str(), type,
1853
0
            static_cast<int>(axisList.size()));
1854
0
        appendSql(sqlStatements, sql);
1855
0
    }
1856
1857
    // Insert new records for the axis
1858
0
    for (int i = 0; i < static_cast<int>(axisList.size()); ++i) {
1859
0
        const auto &axis = axisList[i];
1860
0
        std::string uomAuthName;
1861
0
        std::string uomCode;
1862
0
        identifyOrInsert(dbContext, axis->unit(), ownerAuthName, uomAuthName,
1863
0
                         uomCode, sqlStatements);
1864
0
        const auto sql = formatStatement(
1865
0
            "INSERT INTO axis VALUES("
1866
0
            "'%q','%q','%q','%q','%q','%q','%q',%d,'%q','%q');",
1867
0
            authName.c_str(), (code + "_AXIS_" + toString(i + 1)).c_str(),
1868
0
            axis->nameStr().c_str(), axis->abbreviation().c_str(),
1869
0
            axis->direction().toString().c_str(), authName.c_str(),
1870
0
            code.c_str(), i + 1, uomAuthName.c_str(), uomCode.c_str());
1871
0
        appendSql(sqlStatements, sql);
1872
0
    }
1873
0
}
1874
1875
// ---------------------------------------------------------------------------
1876
1877
static void
1878
addAllowedAuthoritiesCond(const std::vector<std::string> &allowedAuthorities,
1879
                          const std::string &authName, std::string &sql,
1880
0
                          ListOfParams &params) {
1881
0
    sql += "auth_name IN (?";
1882
0
    params.emplace_back(authName);
1883
0
    for (const auto &allowedAuthority : allowedAuthorities) {
1884
0
        sql += ",?";
1885
0
        params.emplace_back(allowedAuthority);
1886
0
    }
1887
0
    sql += ')';
1888
0
}
1889
1890
// ---------------------------------------------------------------------------
1891
1892
void DatabaseContext::Private::identifyOrInsertUsages(
1893
    const common::ObjectUsageNNPtr &obj, const std::string &tableName,
1894
    const std::string &authName, const std::string &code,
1895
    const std::vector<std::string> &allowedAuthorities,
1896
0
    std::vector<std::string> &sqlStatements) {
1897
1898
0
    std::string usageCode("USAGE_");
1899
0
    const std::string upperTableName(toupper(tableName));
1900
0
    if (!starts_with(code, upperTableName)) {
1901
0
        usageCode += upperTableName;
1902
0
        usageCode += '_';
1903
0
    }
1904
0
    usageCode += code;
1905
1906
0
    const auto &domains = obj->domains();
1907
0
    if (domains.empty()) {
1908
0
        const auto sql =
1909
0
            formatStatement("INSERT INTO usage VALUES('%q','%q','%q','%q','%q',"
1910
0
                            "'PROJ','EXTENT_UNKNOWN','PROJ','SCOPE_UNKNOWN');",
1911
0
                            authName.c_str(), usageCode.c_str(),
1912
0
                            tableName.c_str(), authName.c_str(), code.c_str());
1913
0
        appendSql(sqlStatements, sql);
1914
0
        return;
1915
0
    }
1916
1917
0
    int usageCounter = 1;
1918
0
    for (const auto &domain : domains) {
1919
0
        std::string scopeAuthName;
1920
0
        std::string scopeCode;
1921
0
        const auto &scope = domain->scope();
1922
0
        if (scope.has_value()) {
1923
0
            std::string sql =
1924
0
                "SELECT auth_name, code, "
1925
0
                "(CASE WHEN auth_name = 'EPSG' THEN 0 ELSE 1 END) "
1926
0
                "AS order_idx "
1927
0
                "FROM scope WHERE scope = ? AND deprecated = 0 AND ";
1928
0
            ListOfParams params{*scope};
1929
0
            addAllowedAuthoritiesCond(allowedAuthorities, authName, sql,
1930
0
                                      params);
1931
0
            sql += " ORDER BY order_idx, auth_name, code";
1932
0
            const auto rows = run(sql, params);
1933
0
            if (!rows.empty()) {
1934
0
                const auto &row = rows.front();
1935
0
                scopeAuthName = row[0];
1936
0
                scopeCode = row[1];
1937
0
            } else {
1938
0
                scopeAuthName = authName;
1939
0
                scopeCode = "SCOPE_";
1940
0
                scopeCode += tableName;
1941
0
                scopeCode += '_';
1942
0
                scopeCode += code;
1943
0
                const auto sqlToInsert = formatStatement(
1944
0
                    "INSERT INTO scope VALUES('%q','%q','%q',0);",
1945
0
                    scopeAuthName.c_str(), scopeCode.c_str(), scope->c_str());
1946
0
                appendSql(sqlStatements, sqlToInsert);
1947
0
            }
1948
0
        } else {
1949
0
            scopeAuthName = "PROJ";
1950
0
            scopeCode = "SCOPE_UNKNOWN";
1951
0
        }
1952
1953
0
        std::string extentAuthName("PROJ");
1954
0
        std::string extentCode("EXTENT_UNKNOWN");
1955
0
        const auto &extent = domain->domainOfValidity();
1956
0
        if (extent) {
1957
0
            const auto &geogElts = extent->geographicElements();
1958
0
            if (!geogElts.empty()) {
1959
0
                const auto bbox =
1960
0
                    dynamic_cast<const metadata::GeographicBoundingBox *>(
1961
0
                        geogElts.front().get());
1962
0
                if (bbox) {
1963
0
                    std::string sql =
1964
0
                        "SELECT auth_name, code, "
1965
0
                        "(CASE WHEN auth_name = 'EPSG' THEN 0 ELSE 1 END) "
1966
0
                        "AS order_idx "
1967
0
                        "FROM extent WHERE south_lat = ? AND north_lat = ? "
1968
0
                        "AND west_lon = ? AND east_lon = ? AND deprecated = 0 "
1969
0
                        "AND ";
1970
0
                    ListOfParams params{
1971
0
                        bbox->southBoundLatitude(), bbox->northBoundLatitude(),
1972
0
                        bbox->westBoundLongitude(), bbox->eastBoundLongitude()};
1973
0
                    addAllowedAuthoritiesCond(allowedAuthorities, authName, sql,
1974
0
                                              params);
1975
0
                    sql += " ORDER BY order_idx, auth_name, code";
1976
0
                    const auto rows = run(sql, params);
1977
0
                    if (!rows.empty()) {
1978
0
                        const auto &row = rows.front();
1979
0
                        extentAuthName = row[0];
1980
0
                        extentCode = row[1];
1981
0
                    } else {
1982
0
                        extentAuthName = authName;
1983
0
                        extentCode = "EXTENT_";
1984
0
                        extentCode += tableName;
1985
0
                        extentCode += '_';
1986
0
                        extentCode += code;
1987
0
                        std::string description(*(extent->description()));
1988
0
                        if (description.empty()) {
1989
0
                            description = "unknown";
1990
0
                        }
1991
0
                        const auto sqlToInsert = formatStatement(
1992
0
                            "INSERT INTO extent "
1993
0
                            "VALUES('%q','%q','%q','%q',%f,%f,%f,%f,0);",
1994
0
                            extentAuthName.c_str(), extentCode.c_str(),
1995
0
                            description.c_str(), description.c_str(),
1996
0
                            bbox->southBoundLatitude(),
1997
0
                            bbox->northBoundLatitude(),
1998
0
                            bbox->westBoundLongitude(),
1999
0
                            bbox->eastBoundLongitude());
2000
0
                        appendSql(sqlStatements, sqlToInsert);
2001
0
                    }
2002
0
                }
2003
0
            }
2004
0
        }
2005
2006
0
        if (domains.size() > 1) {
2007
0
            usageCode += '_';
2008
0
            usageCode += toString(usageCounter);
2009
0
        }
2010
0
        const auto sql = formatStatement(
2011
0
            "INSERT INTO usage VALUES('%q','%q','%q','%q','%q',"
2012
0
            "'%q','%q','%q','%q');",
2013
0
            authName.c_str(), usageCode.c_str(), tableName.c_str(),
2014
0
            authName.c_str(), code.c_str(), extentAuthName.c_str(),
2015
0
            extentCode.c_str(), scopeAuthName.c_str(), scopeCode.c_str());
2016
0
        appendSql(sqlStatements, sql);
2017
2018
0
        usageCounter++;
2019
0
    }
2020
0
}
2021
2022
// ---------------------------------------------------------------------------
2023
2024
std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor(
2025
    const datum::PrimeMeridianNNPtr &pm, const std::string &authName,
2026
    const std::string &code, bool /*numericCode*/,
2027
0
    const std::vector<std::string> &allowedAuthorities) {
2028
2029
0
    const auto self = NN_NO_CHECK(self_.lock());
2030
2031
    // Check if the object is already known under that code
2032
0
    std::string pmAuthName;
2033
0
    std::string pmCode;
2034
0
    identifyFromNameOrCode(self, allowedAuthorities, authName, pm, pmAuthName,
2035
0
                           pmCode);
2036
0
    if (pmAuthName == authName && pmCode == code) {
2037
0
        return {};
2038
0
    }
2039
2040
0
    std::vector<std::string> sqlStatements;
2041
2042
    // Insert new record in prime_meridian table
2043
0
    std::string uomAuthName;
2044
0
    std::string uomCode;
2045
0
    identifyOrInsert(self, pm->longitude().unit(), authName, uomAuthName,
2046
0
                     uomCode, sqlStatements);
2047
2048
0
    const auto sql = formatStatement(
2049
0
        "INSERT INTO prime_meridian VALUES("
2050
0
        "'%q','%q','%q',%f,'%q','%q',0);",
2051
0
        authName.c_str(), code.c_str(), pm->nameStr().c_str(),
2052
0
        pm->longitude().value(), uomAuthName.c_str(), uomCode.c_str());
2053
0
    appendSql(sqlStatements, sql);
2054
2055
0
    return sqlStatements;
2056
0
}
2057
2058
// ---------------------------------------------------------------------------
2059
2060
std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor(
2061
    const datum::EllipsoidNNPtr &ellipsoid, const std::string &authName,
2062
    const std::string &code, bool /*numericCode*/,
2063
0
    const std::vector<std::string> &allowedAuthorities) {
2064
2065
0
    const auto self = NN_NO_CHECK(self_.lock());
2066
2067
    // Check if the object is already known under that code
2068
0
    std::string ellipsoidAuthName;
2069
0
    std::string ellipsoidCode;
2070
0
    identifyFromNameOrCode(self, allowedAuthorities, authName, ellipsoid,
2071
0
                           ellipsoidAuthName, ellipsoidCode);
2072
0
    if (ellipsoidAuthName == authName && ellipsoidCode == code) {
2073
0
        return {};
2074
0
    }
2075
2076
0
    std::vector<std::string> sqlStatements;
2077
2078
    // Find or insert celestial body
2079
0
    const auto &semiMajorAxis = ellipsoid->semiMajorAxis();
2080
0
    const double semiMajorAxisMetre = semiMajorAxis.getSIValue();
2081
0
    constexpr double tolerance = 0.005;
2082
0
    std::string bodyAuthName;
2083
0
    std::string bodyCode;
2084
0
    auto res = run("SELECT auth_name, code, "
2085
0
                   "(ABS(semi_major_axis - ?) / semi_major_axis ) "
2086
0
                   "AS rel_error FROM celestial_body WHERE rel_error <= ?",
2087
0
                   {semiMajorAxisMetre, tolerance});
2088
0
    if (!res.empty()) {
2089
0
        const auto &row = res.front();
2090
0
        bodyAuthName = row[0];
2091
0
        bodyCode = row[1];
2092
0
    } else {
2093
0
        bodyAuthName = authName;
2094
0
        bodyCode = "BODY_" + code;
2095
0
        const auto bodyName = "Body of " + ellipsoid->nameStr();
2096
0
        const auto sql = formatStatement(
2097
0
            "INSERT INTO celestial_body VALUES('%q','%q','%q',%f);",
2098
0
            bodyAuthName.c_str(), bodyCode.c_str(), bodyName.c_str(),
2099
0
            semiMajorAxisMetre);
2100
0
        appendSql(sqlStatements, sql);
2101
0
    }
2102
2103
    // Insert new record in ellipsoid table
2104
0
    std::string uomAuthName;
2105
0
    std::string uomCode;
2106
0
    identifyOrInsert(self, semiMajorAxis.unit(), authName, uomAuthName, uomCode,
2107
0
                     sqlStatements);
2108
0
    std::string invFlattening("NULL");
2109
0
    std::string semiMinorAxis("NULL");
2110
0
    if (ellipsoid->isSphere() || ellipsoid->semiMinorAxis().has_value()) {
2111
0
        semiMinorAxis = toString(ellipsoid->computeSemiMinorAxis().value());
2112
0
    } else {
2113
0
        invFlattening = toString(ellipsoid->computedInverseFlattening());
2114
0
    }
2115
2116
0
    const auto sql = formatStatement(
2117
0
        "INSERT INTO ellipsoid VALUES("
2118
0
        "'%q','%q','%q','%q','%q','%q',%f,'%q','%q',%s,%s,0);",
2119
0
        authName.c_str(), code.c_str(), ellipsoid->nameStr().c_str(),
2120
0
        "", // description
2121
0
        bodyAuthName.c_str(), bodyCode.c_str(), semiMajorAxis.value(),
2122
0
        uomAuthName.c_str(), uomCode.c_str(), invFlattening.c_str(),
2123
0
        semiMinorAxis.c_str());
2124
0
    appendSql(sqlStatements, sql);
2125
2126
0
    return sqlStatements;
2127
0
}
2128
2129
// ---------------------------------------------------------------------------
2130
2131
0
static std::string anchorEpochToStr(double val) {
2132
0
    constexpr int BUF_SIZE = 16;
2133
0
    char szBuffer[BUF_SIZE];
2134
0
    sqlite3_snprintf(BUF_SIZE, szBuffer, "%.3f", val);
2135
0
    return szBuffer;
2136
0
}
2137
2138
// ---------------------------------------------------------------------------
2139
2140
std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor(
2141
    const datum::GeodeticReferenceFrameNNPtr &datum,
2142
    const std::string &authName, const std::string &code, bool numericCode,
2143
0
    const std::vector<std::string> &allowedAuthorities) {
2144
2145
0
    const auto self = NN_NO_CHECK(self_.lock());
2146
2147
    // Check if the object is already known under that code
2148
0
    std::string datumAuthName;
2149
0
    std::string datumCode;
2150
0
    identifyFromNameOrCode(self, allowedAuthorities, authName, datum,
2151
0
                           datumAuthName, datumCode);
2152
0
    if (datumAuthName == authName && datumCode == code) {
2153
0
        return {};
2154
0
    }
2155
2156
0
    std::vector<std::string> sqlStatements;
2157
2158
    // Find or insert ellipsoid
2159
0
    std::string ellipsoidAuthName;
2160
0
    std::string ellipsoidCode;
2161
0
    const auto &ellipsoidOfDatum = datum->ellipsoid();
2162
0
    identifyFromNameOrCode(self, allowedAuthorities, authName, ellipsoidOfDatum,
2163
0
                           ellipsoidAuthName, ellipsoidCode);
2164
0
    if (ellipsoidAuthName.empty()) {
2165
0
        ellipsoidAuthName = authName;
2166
0
        if (numericCode) {
2167
0
            ellipsoidCode = self->suggestsCodeFor(ellipsoidOfDatum,
2168
0
                                                  ellipsoidAuthName, true);
2169
0
        } else {
2170
0
            ellipsoidCode = "ELLPS_" + code;
2171
0
        }
2172
0
        sqlStatements = self->getInsertStatementsFor(
2173
0
            ellipsoidOfDatum, ellipsoidAuthName, ellipsoidCode, numericCode,
2174
0
            allowedAuthorities);
2175
0
    }
2176
2177
    // Find or insert prime meridian
2178
0
    std::string pmAuthName;
2179
0
    std::string pmCode;
2180
0
    const auto &pmOfDatum = datum->primeMeridian();
2181
0
    identifyFromNameOrCode(self, allowedAuthorities, authName, pmOfDatum,
2182
0
                           pmAuthName, pmCode);
2183
0
    if (pmAuthName.empty()) {
2184
0
        pmAuthName = authName;
2185
0
        if (numericCode) {
2186
0
            pmCode = self->suggestsCodeFor(pmOfDatum, pmAuthName, true);
2187
0
        } else {
2188
0
            pmCode = "PM_" + code;
2189
0
        }
2190
0
        const auto sqlStatementsTmp = self->getInsertStatementsFor(
2191
0
            pmOfDatum, pmAuthName, pmCode, numericCode, allowedAuthorities);
2192
0
        sqlStatements.insert(sqlStatements.end(), sqlStatementsTmp.begin(),
2193
0
                             sqlStatementsTmp.end());
2194
0
    }
2195
2196
    // Insert new record in geodetic_datum table
2197
0
    std::string publicationDate("NULL");
2198
0
    if (datum->publicationDate().has_value()) {
2199
0
        publicationDate = '\'';
2200
0
        publicationDate +=
2201
0
            replaceAll(datum->publicationDate()->toString(), "'", "''");
2202
0
        publicationDate += '\'';
2203
0
    }
2204
0
    std::string frameReferenceEpoch("NULL");
2205
0
    const auto dynamicDatum =
2206
0
        dynamic_cast<const datum::DynamicGeodeticReferenceFrame *>(datum.get());
2207
0
    if (dynamicDatum) {
2208
0
        frameReferenceEpoch =
2209
0
            toString(dynamicDatum->frameReferenceEpoch().value());
2210
0
    }
2211
0
    const std::string anchor(*(datum->anchorDefinition()));
2212
0
    const util::optional<common::Measure> &anchorEpoch = datum->anchorEpoch();
2213
0
    const auto sql = formatStatement(
2214
0
        "INSERT INTO geodetic_datum VALUES("
2215
0
        "'%q','%q','%q','%q','%q','%q','%q','%q',%s,%s,NULL,%Q,%s,0);",
2216
0
        authName.c_str(), code.c_str(), datum->nameStr().c_str(),
2217
0
        "", // description
2218
0
        ellipsoidAuthName.c_str(), ellipsoidCode.c_str(), pmAuthName.c_str(),
2219
0
        pmCode.c_str(), publicationDate.c_str(), frameReferenceEpoch.c_str(),
2220
0
        anchor.empty() ? nullptr : anchor.c_str(),
2221
0
        anchorEpoch.has_value()
2222
0
            ? anchorEpochToStr(
2223
0
                  anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR))
2224
0
                  .c_str()
2225
0
            : "NULL");
2226
0
    appendSql(sqlStatements, sql);
2227
2228
0
    identifyOrInsertUsages(datum, "geodetic_datum", authName, code,
2229
0
                           allowedAuthorities, sqlStatements);
2230
2231
0
    return sqlStatements;
2232
0
}
2233
2234
// ---------------------------------------------------------------------------
2235
2236
std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor(
2237
    const datum::DatumEnsembleNNPtr &ensemble, const std::string &authName,
2238
    const std::string &code, bool numericCode,
2239
0
    const std::vector<std::string> &allowedAuthorities) {
2240
0
    const auto self = NN_NO_CHECK(self_.lock());
2241
2242
    // Check if the object is already known under that code
2243
0
    std::string datumAuthName;
2244
0
    std::string datumCode;
2245
0
    identifyFromNameOrCode(self, allowedAuthorities, authName, ensemble,
2246
0
                           datumAuthName, datumCode);
2247
0
    if (datumAuthName == authName && datumCode == code) {
2248
0
        return {};
2249
0
    }
2250
2251
0
    std::vector<std::string> sqlStatements;
2252
2253
0
    const auto &members = ensemble->datums();
2254
0
    assert(!members.empty());
2255
2256
0
    int counter = 1;
2257
0
    std::vector<std::pair<std::string, std::string>> membersId;
2258
0
    for (const auto &member : members) {
2259
0
        std::string memberAuthName;
2260
0
        std::string memberCode;
2261
0
        identifyFromNameOrCode(self, allowedAuthorities, authName, member,
2262
0
                               memberAuthName, memberCode);
2263
0
        if (memberAuthName.empty()) {
2264
0
            memberAuthName = authName;
2265
0
            if (numericCode) {
2266
0
                memberCode =
2267
0
                    self->suggestsCodeFor(member, memberAuthName, true);
2268
0
            } else {
2269
0
                memberCode = "MEMBER_" + toString(counter) + "_OF_" + code;
2270
0
            }
2271
0
            const auto sqlStatementsTmp =
2272
0
                self->getInsertStatementsFor(member, memberAuthName, memberCode,
2273
0
                                             numericCode, allowedAuthorities);
2274
0
            sqlStatements.insert(sqlStatements.end(), sqlStatementsTmp.begin(),
2275
0
                                 sqlStatementsTmp.end());
2276
0
        }
2277
2278
0
        membersId.emplace_back(
2279
0
            std::pair<std::string, std::string>(memberAuthName, memberCode));
2280
2281
0
        ++counter;
2282
0
    }
2283
2284
0
    const bool isGeodetic =
2285
0
        util::nn_dynamic_pointer_cast<datum::GeodeticReferenceFrame>(
2286
0
            members.front()) != nullptr;
2287
2288
    // Insert new record in geodetic_datum/vertical_datum table
2289
0
    const double accuracy =
2290
0
        c_locale_stod(ensemble->positionalAccuracy()->value());
2291
0
    if (isGeodetic) {
2292
0
        const auto firstDatum =
2293
0
            AuthorityFactory::create(self, membersId.front().first)
2294
0
                ->createGeodeticDatum(membersId.front().second);
2295
0
        const auto &ellipsoid = firstDatum->ellipsoid();
2296
0
        const auto &ellipsoidIds = ellipsoid->identifiers();
2297
0
        assert(!ellipsoidIds.empty());
2298
0
        const std::string &ellipsoidAuthName =
2299
0
            *(ellipsoidIds.front()->codeSpace());
2300
0
        const std::string &ellipsoidCode = ellipsoidIds.front()->code();
2301
0
        const auto &pm = firstDatum->primeMeridian();
2302
0
        const auto &pmIds = pm->identifiers();
2303
0
        assert(!pmIds.empty());
2304
0
        const std::string &pmAuthName = *(pmIds.front()->codeSpace());
2305
0
        const std::string &pmCode = pmIds.front()->code();
2306
0
        const std::string anchor(*(firstDatum->anchorDefinition()));
2307
0
        const util::optional<common::Measure> &anchorEpoch =
2308
0
            firstDatum->anchorEpoch();
2309
0
        const auto sql = formatStatement(
2310
0
            "INSERT INTO geodetic_datum VALUES("
2311
0
            "'%q','%q','%q','%q','%q','%q','%q','%q',NULL,NULL,%f,%Q,%s,0);",
2312
0
            authName.c_str(), code.c_str(), ensemble->nameStr().c_str(),
2313
0
            "", // description
2314
0
            ellipsoidAuthName.c_str(), ellipsoidCode.c_str(),
2315
0
            pmAuthName.c_str(), pmCode.c_str(), accuracy,
2316
0
            anchor.empty() ? nullptr : anchor.c_str(),
2317
0
            anchorEpoch.has_value()
2318
0
                ? anchorEpochToStr(
2319
0
                      anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR))
2320
0
                      .c_str()
2321
0
                : "NULL");
2322
0
        appendSql(sqlStatements, sql);
2323
0
    } else {
2324
0
        const auto firstDatum =
2325
0
            AuthorityFactory::create(self, membersId.front().first)
2326
0
                ->createVerticalDatum(membersId.front().second);
2327
0
        const std::string anchor(*(firstDatum->anchorDefinition()));
2328
0
        const util::optional<common::Measure> &anchorEpoch =
2329
0
            firstDatum->anchorEpoch();
2330
0
        const auto sql = formatStatement(
2331
0
            "INSERT INTO vertical_datum VALUES("
2332
0
            "'%q','%q','%q','%q',NULL,NULL,%f,%Q,%s,0);",
2333
0
            authName.c_str(), code.c_str(), ensemble->nameStr().c_str(),
2334
0
            "", // description
2335
0
            accuracy, anchor.empty() ? nullptr : anchor.c_str(),
2336
0
            anchorEpoch.has_value()
2337
0
                ? anchorEpochToStr(
2338
0
                      anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR))
2339
0
                      .c_str()
2340
0
                : "NULL");
2341
0
        appendSql(sqlStatements, sql);
2342
0
    }
2343
0
    identifyOrInsertUsages(ensemble,
2344
0
                           isGeodetic ? "geodetic_datum" : "vertical_datum",
2345
0
                           authName, code, allowedAuthorities, sqlStatements);
2346
2347
0
    const char *tableName = isGeodetic ? "geodetic_datum_ensemble_member"
2348
0
                                       : "vertical_datum_ensemble_member";
2349
0
    counter = 1;
2350
0
    for (const auto &authCodePair : membersId) {
2351
0
        const auto sql = formatStatement(
2352
0
            "INSERT INTO %s VALUES("
2353
0
            "'%q','%q','%q','%q',%d);",
2354
0
            tableName, authName.c_str(), code.c_str(),
2355
0
            authCodePair.first.c_str(), authCodePair.second.c_str(), counter);
2356
0
        appendSql(sqlStatements, sql);
2357
0
        ++counter;
2358
0
    }
2359
2360
0
    return sqlStatements;
2361
0
}
2362
2363
// ---------------------------------------------------------------------------
2364
2365
std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor(
2366
    const crs::GeodeticCRSNNPtr &crs, const std::string &authName,
2367
    const std::string &code, bool numericCode,
2368
0
    const std::vector<std::string> &allowedAuthorities) {
2369
2370
0
    const auto self = NN_NO_CHECK(self_.lock());
2371
2372
0
    std::vector<std::string> sqlStatements;
2373
2374
    // Find or insert datum/datum ensemble
2375
0
    std::string datumAuthName;
2376
0
    std::string datumCode;
2377
0
    const auto &ensemble = crs->datumEnsemble();
2378
0
    if (ensemble) {
2379
0
        const auto ensembleNN = NN_NO_CHECK(ensemble);
2380
0
        identifyFromNameOrCode(self, allowedAuthorities, authName, ensembleNN,
2381
0
                               datumAuthName, datumCode);
2382
0
        if (datumAuthName.empty()) {
2383
0
            datumAuthName = authName;
2384
0
            if (numericCode) {
2385
0
                datumCode =
2386
0
                    self->suggestsCodeFor(ensembleNN, datumAuthName, true);
2387
0
            } else {
2388
0
                datumCode = "GEODETIC_DATUM_" + code;
2389
0
            }
2390
0
            sqlStatements = self->getInsertStatementsFor(
2391
0
                ensembleNN, datumAuthName, datumCode, numericCode,
2392
0
                allowedAuthorities);
2393
0
        }
2394
0
    } else {
2395
0
        const auto &datum = crs->datum();
2396
0
        assert(datum);
2397
0
        const auto datumNN = NN_NO_CHECK(datum);
2398
0
        identifyFromNameOrCode(self, allowedAuthorities, authName, datumNN,
2399
0
                               datumAuthName, datumCode);
2400
0
        if (datumAuthName.empty()) {
2401
0
            datumAuthName = authName;
2402
0
            if (numericCode) {
2403
0
                datumCode = self->suggestsCodeFor(datumNN, datumAuthName, true);
2404
0
            } else {
2405
0
                datumCode = "GEODETIC_DATUM_" + code;
2406
0
            }
2407
0
            sqlStatements =
2408
0
                self->getInsertStatementsFor(datumNN, datumAuthName, datumCode,
2409
0
                                             numericCode, allowedAuthorities);
2410
0
        }
2411
0
    }
2412
2413
    // Find or insert coordinate system
2414
0
    const auto &coordinateSystem = crs->coordinateSystem();
2415
0
    std::string csAuthName;
2416
0
    std::string csCode;
2417
0
    identifyOrInsert(self, coordinateSystem, "GEODETIC_CRS", authName, code,
2418
0
                     csAuthName, csCode, sqlStatements);
2419
2420
0
    const char *type = GEOG_2D;
2421
0
    if (coordinateSystem->axisList().size() == 3) {
2422
0
        if (dynamic_cast<const crs::GeographicCRS *>(crs.get())) {
2423
0
            type = GEOG_3D;
2424
0
        } else {
2425
0
            type = GEOCENTRIC;
2426
0
        }
2427
0
    }
2428
2429
    // Insert new record in geodetic_crs table
2430
0
    const auto sql =
2431
0
        formatStatement("INSERT INTO geodetic_crs VALUES("
2432
0
                        "'%q','%q','%q','%q','%q','%q','%q','%q','%q',NULL,0);",
2433
0
                        authName.c_str(), code.c_str(), crs->nameStr().c_str(),
2434
0
                        "", // description
2435
0
                        type, csAuthName.c_str(), csCode.c_str(),
2436
0
                        datumAuthName.c_str(), datumCode.c_str());
2437
0
    appendSql(sqlStatements, sql);
2438
2439
0
    identifyOrInsertUsages(crs, "geodetic_crs", authName, code,
2440
0
                           allowedAuthorities, sqlStatements);
2441
0
    return sqlStatements;
2442
0
}
2443
2444
// ---------------------------------------------------------------------------
2445
2446
std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor(
2447
    const crs::ProjectedCRSNNPtr &crs, const std::string &authName,
2448
    const std::string &code, bool numericCode,
2449
0
    const std::vector<std::string> &allowedAuthorities) {
2450
2451
0
    const auto self = NN_NO_CHECK(self_.lock());
2452
2453
0
    std::vector<std::string> sqlStatements;
2454
2455
    // Find or insert base geodetic CRS
2456
0
    const auto &baseCRS = crs->baseCRS();
2457
0
    std::string geodAuthName;
2458
0
    std::string geodCode;
2459
2460
0
    auto allowedAuthoritiesTmp(allowedAuthorities);
2461
0
    allowedAuthoritiesTmp.emplace_back(authName);
2462
0
    for (const auto &allowedAuthority : allowedAuthoritiesTmp) {
2463
0
        const auto factory = AuthorityFactory::create(self, allowedAuthority);
2464
0
        const auto candidates = baseCRS->identify(factory);
2465
0
        for (const auto &candidate : candidates) {
2466
0
            if (candidate.second == 100) {
2467
0
                const auto &ids = candidate.first->identifiers();
2468
0
                if (!ids.empty()) {
2469
0
                    const auto &id = ids.front();
2470
0
                    geodAuthName = *(id->codeSpace());
2471
0
                    geodCode = id->code();
2472
0
                    break;
2473
0
                }
2474
0
            }
2475
0
            if (!geodAuthName.empty()) {
2476
0
                break;
2477
0
            }
2478
0
        }
2479
0
    }
2480
0
    if (geodAuthName.empty()) {
2481
0
        geodAuthName = authName;
2482
0
        geodCode = "GEODETIC_CRS_" + code;
2483
0
        sqlStatements = self->getInsertStatementsFor(
2484
0
            baseCRS, geodAuthName, geodCode, numericCode, allowedAuthorities);
2485
0
    }
2486
2487
    // Insert new record in conversion table
2488
0
    const auto &conversion = crs->derivingConversionRef();
2489
0
    std::string convAuthName(authName);
2490
0
    std::string convCode("CONVERSION_" + code);
2491
0
    if (numericCode) {
2492
0
        convCode = self->suggestsCodeFor(conversion, convAuthName, true);
2493
0
    }
2494
0
    {
2495
0
        const auto &method = conversion->method();
2496
0
        const auto &methodIds = method->identifiers();
2497
0
        std::string methodAuthName;
2498
0
        std::string methodCode;
2499
0
        const operation::MethodMapping *methodMapping = nullptr;
2500
0
        if (methodIds.empty()) {
2501
0
            const int epsgCode = method->getEPSGCode();
2502
0
            if (epsgCode > 0) {
2503
0
                methodAuthName = metadata::Identifier::EPSG;
2504
0
                methodCode = toString(epsgCode);
2505
0
            } else {
2506
0
                const auto &methodName = method->nameStr();
2507
0
                size_t nProjectionMethodMappings = 0;
2508
0
                const auto projectionMethodMappings =
2509
0
                    operation::getProjectionMethodMappings(
2510
0
                        nProjectionMethodMappings);
2511
0
                for (size_t i = 0; i < nProjectionMethodMappings; ++i) {
2512
0
                    const auto &mapping = projectionMethodMappings[i];
2513
0
                    if (metadata::Identifier::isEquivalentName(
2514
0
                            mapping.wkt2_name, methodName.c_str())) {
2515
0
                        methodMapping = &mapping;
2516
0
                    }
2517
0
                }
2518
0
                if (methodMapping == nullptr ||
2519
0
                    methodMapping->proj_name_main == nullptr) {
2520
0
                    throw FactoryException("Cannot insert projection with "
2521
0
                                           "method without identifier");
2522
0
                }
2523
0
                methodAuthName = "PROJ";
2524
0
                methodCode = methodMapping->proj_name_main;
2525
0
                if (methodMapping->proj_name_aux) {
2526
0
                    methodCode += ' ';
2527
0
                    methodCode += methodMapping->proj_name_aux;
2528
0
                }
2529
0
            }
2530
0
        } else {
2531
0
            const auto &methodId = methodIds.front();
2532
0
            methodAuthName = *(methodId->codeSpace());
2533
0
            methodCode = methodId->code();
2534
0
        }
2535
2536
0
        auto sql = formatStatement("INSERT INTO conversion VALUES("
2537
0
                                   "'%q','%q','%q','','%q','%q','%q'",
2538
0
                                   convAuthName.c_str(), convCode.c_str(),
2539
0
                                   conversion->nameStr().c_str(),
2540
0
                                   methodAuthName.c_str(), methodCode.c_str(),
2541
0
                                   method->nameStr().c_str());
2542
0
        const auto &srcValues = conversion->parameterValues();
2543
0
        if (srcValues.size() > N_MAX_PARAMS) {
2544
0
            throw FactoryException("Cannot insert projection with more than " +
2545
0
                                   toString(static_cast<int>(N_MAX_PARAMS)) +
2546
0
                                   " parameters");
2547
0
        }
2548
2549
0
        std::vector<operation::GeneralParameterValueNNPtr> values;
2550
0
        if (methodMapping == nullptr) {
2551
0
            if (methodAuthName == metadata::Identifier::EPSG) {
2552
0
                methodMapping = operation::getMapping(atoi(methodCode.c_str()));
2553
0
            } else {
2554
0
                methodMapping =
2555
0
                    operation::getMapping(method->nameStr().c_str());
2556
0
            }
2557
0
        }
2558
0
        if (methodMapping != nullptr) {
2559
            // Re-order projection parameters in their reference order
2560
0
            for (size_t j = 0; methodMapping->params[j] != nullptr; ++j) {
2561
0
                for (size_t i = 0; i < srcValues.size(); ++i) {
2562
0
                    auto opParamValue = dynamic_cast<
2563
0
                        const operation::OperationParameterValue *>(
2564
0
                        srcValues[i].get());
2565
0
                    if (!opParamValue) {
2566
0
                        throw FactoryException("Cannot insert projection with "
2567
0
                                               "non-OperationParameterValue");
2568
0
                    }
2569
0
                    if (methodMapping->params[j]->wkt2_name &&
2570
0
                        opParamValue->parameter()->nameStr() ==
2571
0
                            methodMapping->params[j]->wkt2_name) {
2572
0
                        values.emplace_back(srcValues[i]);
2573
0
                    }
2574
0
                }
2575
0
            }
2576
0
        }
2577
0
        if (values.size() != srcValues.size()) {
2578
0
            values = srcValues;
2579
0
        }
2580
2581
0
        for (const auto &genOpParamvalue : values) {
2582
0
            auto opParamValue =
2583
0
                dynamic_cast<const operation::OperationParameterValue *>(
2584
0
                    genOpParamvalue.get());
2585
0
            if (!opParamValue) {
2586
0
                throw FactoryException("Cannot insert projection with "
2587
0
                                       "non-OperationParameterValue");
2588
0
            }
2589
0
            const auto &param = opParamValue->parameter();
2590
0
            const auto &paramIds = param->identifiers();
2591
0
            std::string paramAuthName;
2592
0
            std::string paramCode;
2593
0
            if (paramIds.empty()) {
2594
0
                const int paramEPSGCode = param->getEPSGCode();
2595
0
                if (paramEPSGCode == 0) {
2596
0
                    throw FactoryException(
2597
0
                        "Cannot insert projection with method parameter "
2598
0
                        "without identifier");
2599
0
                }
2600
0
                paramAuthName = metadata::Identifier::EPSG;
2601
0
                paramCode = toString(paramEPSGCode);
2602
0
            } else {
2603
0
                const auto &paramId = paramIds.front();
2604
0
                paramAuthName = *(paramId->codeSpace());
2605
0
                paramCode = paramId->code();
2606
0
            }
2607
0
            const auto &value = opParamValue->parameterValue()->value();
2608
0
            const auto &unit = value.unit();
2609
0
            std::string uomAuthName;
2610
0
            std::string uomCode;
2611
0
            identifyOrInsert(self, unit, authName, uomAuthName, uomCode,
2612
0
                             sqlStatements);
2613
0
            sql += formatStatement(",'%q','%q','%q',%f,'%q','%q'",
2614
0
                                   paramAuthName.c_str(), paramCode.c_str(),
2615
0
                                   param->nameStr().c_str(), value.value(),
2616
0
                                   uomAuthName.c_str(), uomCode.c_str());
2617
0
        }
2618
0
        for (size_t i = values.size(); i < N_MAX_PARAMS; ++i) {
2619
0
            sql += ",NULL,NULL,NULL,NULL,NULL,NULL";
2620
0
        }
2621
0
        sql += ",0);";
2622
0
        appendSql(sqlStatements, sql);
2623
0
        identifyOrInsertUsages(crs, "conversion", convAuthName, convCode,
2624
0
                               allowedAuthorities, sqlStatements);
2625
0
    }
2626
2627
    // Find or insert coordinate system
2628
0
    const auto &coordinateSystem = crs->coordinateSystem();
2629
0
    std::string csAuthName;
2630
0
    std::string csCode;
2631
0
    identifyOrInsert(self, coordinateSystem, "PROJECTED_CRS", authName, code,
2632
0
                     csAuthName, csCode, sqlStatements);
2633
2634
    // Insert new record in projected_crs table
2635
0
    const auto sql = formatStatement(
2636
0
        "INSERT INTO projected_crs VALUES("
2637
0
        "'%q','%q','%q','%q','%q','%q','%q','%q','%q','%q',NULL,0);",
2638
0
        authName.c_str(), code.c_str(), crs->nameStr().c_str(),
2639
0
        "", // description
2640
0
        csAuthName.c_str(), csCode.c_str(), geodAuthName.c_str(),
2641
0
        geodCode.c_str(), convAuthName.c_str(), convCode.c_str());
2642
0
    appendSql(sqlStatements, sql);
2643
2644
0
    identifyOrInsertUsages(crs, "projected_crs", authName, code,
2645
0
                           allowedAuthorities, sqlStatements);
2646
2647
0
    return sqlStatements;
2648
0
}
2649
2650
// ---------------------------------------------------------------------------
2651
2652
std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor(
2653
    const datum::VerticalReferenceFrameNNPtr &datum,
2654
    const std::string &authName, const std::string &code,
2655
    bool /* numericCode */,
2656
0
    const std::vector<std::string> &allowedAuthorities) {
2657
2658
0
    const auto self = NN_NO_CHECK(self_.lock());
2659
2660
0
    std::vector<std::string> sqlStatements;
2661
2662
    // Check if the object is already known under that code
2663
0
    std::string datumAuthName;
2664
0
    std::string datumCode;
2665
0
    identifyFromNameOrCode(self, allowedAuthorities, authName, datum,
2666
0
                           datumAuthName, datumCode);
2667
0
    if (datumAuthName == authName && datumCode == code) {
2668
0
        return {};
2669
0
    }
2670
2671
    // Insert new record in vertical_datum table
2672
0
    std::string publicationDate("NULL");
2673
0
    if (datum->publicationDate().has_value()) {
2674
0
        publicationDate = '\'';
2675
0
        publicationDate +=
2676
0
            replaceAll(datum->publicationDate()->toString(), "'", "''");
2677
0
        publicationDate += '\'';
2678
0
    }
2679
0
    std::string frameReferenceEpoch("NULL");
2680
0
    const auto dynamicDatum =
2681
0
        dynamic_cast<const datum::DynamicVerticalReferenceFrame *>(datum.get());
2682
0
    if (dynamicDatum) {
2683
0
        frameReferenceEpoch =
2684
0
            toString(dynamicDatum->frameReferenceEpoch().value());
2685
0
    }
2686
0
    const std::string anchor(*(datum->anchorDefinition()));
2687
0
    const util::optional<common::Measure> &anchorEpoch = datum->anchorEpoch();
2688
0
    const auto sql = formatStatement(
2689
0
        "INSERT INTO vertical_datum VALUES("
2690
0
        "'%q','%q','%q','%q',%s,%s,NULL,%Q,%s,0);",
2691
0
        authName.c_str(), code.c_str(), datum->nameStr().c_str(),
2692
0
        "", // description
2693
0
        publicationDate.c_str(), frameReferenceEpoch.c_str(),
2694
0
        anchor.empty() ? nullptr : anchor.c_str(),
2695
0
        anchorEpoch.has_value()
2696
0
            ? anchorEpochToStr(
2697
0
                  anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR))
2698
0
                  .c_str()
2699
0
            : "NULL");
2700
0
    appendSql(sqlStatements, sql);
2701
2702
0
    identifyOrInsertUsages(datum, "vertical_datum", authName, code,
2703
0
                           allowedAuthorities, sqlStatements);
2704
2705
0
    return sqlStatements;
2706
0
}
2707
2708
// ---------------------------------------------------------------------------
2709
2710
std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor(
2711
    const crs::VerticalCRSNNPtr &crs, const std::string &authName,
2712
    const std::string &code, bool numericCode,
2713
0
    const std::vector<std::string> &allowedAuthorities) {
2714
2715
0
    const auto self = NN_NO_CHECK(self_.lock());
2716
2717
0
    std::vector<std::string> sqlStatements;
2718
2719
    // Find or insert datum/datum ensemble
2720
0
    std::string datumAuthName;
2721
0
    std::string datumCode;
2722
0
    const auto &ensemble = crs->datumEnsemble();
2723
0
    if (ensemble) {
2724
0
        const auto ensembleNN = NN_NO_CHECK(ensemble);
2725
0
        identifyFromNameOrCode(self, allowedAuthorities, authName, ensembleNN,
2726
0
                               datumAuthName, datumCode);
2727
0
        if (datumAuthName.empty()) {
2728
0
            datumAuthName = authName;
2729
0
            if (numericCode) {
2730
0
                datumCode =
2731
0
                    self->suggestsCodeFor(ensembleNN, datumAuthName, true);
2732
0
            } else {
2733
0
                datumCode = "VERTICAL_DATUM_" + code;
2734
0
            }
2735
0
            sqlStatements = self->getInsertStatementsFor(
2736
0
                ensembleNN, datumAuthName, datumCode, numericCode,
2737
0
                allowedAuthorities);
2738
0
        }
2739
0
    } else {
2740
0
        const auto &datum = crs->datum();
2741
0
        assert(datum);
2742
0
        const auto datumNN = NN_NO_CHECK(datum);
2743
0
        identifyFromNameOrCode(self, allowedAuthorities, authName, datumNN,
2744
0
                               datumAuthName, datumCode);
2745
0
        if (datumAuthName.empty()) {
2746
0
            datumAuthName = authName;
2747
0
            if (numericCode) {
2748
0
                datumCode = self->suggestsCodeFor(datumNN, datumAuthName, true);
2749
0
            } else {
2750
0
                datumCode = "VERTICAL_DATUM_" + code;
2751
0
            }
2752
0
            sqlStatements =
2753
0
                self->getInsertStatementsFor(datumNN, datumAuthName, datumCode,
2754
0
                                             numericCode, allowedAuthorities);
2755
0
        }
2756
0
    }
2757
2758
    // Find or insert coordinate system
2759
0
    const auto &coordinateSystem = crs->coordinateSystem();
2760
0
    std::string csAuthName;
2761
0
    std::string csCode;
2762
0
    identifyOrInsert(self, coordinateSystem, "VERTICAL_CRS", authName, code,
2763
0
                     csAuthName, csCode, sqlStatements);
2764
2765
    // Insert new record in vertical_crs table
2766
0
    const auto sql =
2767
0
        formatStatement("INSERT INTO vertical_crs VALUES("
2768
0
                        "'%q','%q','%q','%q','%q','%q','%q','%q',0);",
2769
0
                        authName.c_str(), code.c_str(), crs->nameStr().c_str(),
2770
0
                        "", // description
2771
0
                        csAuthName.c_str(), csCode.c_str(),
2772
0
                        datumAuthName.c_str(), datumCode.c_str());
2773
0
    appendSql(sqlStatements, sql);
2774
2775
0
    identifyOrInsertUsages(crs, "vertical_crs", authName, code,
2776
0
                           allowedAuthorities, sqlStatements);
2777
2778
0
    return sqlStatements;
2779
0
}
2780
2781
// ---------------------------------------------------------------------------
2782
2783
std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor(
2784
    const crs::CompoundCRSNNPtr &crs, const std::string &authName,
2785
    const std::string &code, bool numericCode,
2786
0
    const std::vector<std::string> &allowedAuthorities) {
2787
2788
0
    const auto self = NN_NO_CHECK(self_.lock());
2789
2790
0
    std::vector<std::string> sqlStatements;
2791
2792
0
    int counter = 1;
2793
0
    std::vector<std::pair<std::string, std::string>> componentsId;
2794
0
    const auto &components = crs->componentReferenceSystems();
2795
0
    if (components.size() != 2) {
2796
0
        throw FactoryException(
2797
0
            "Cannot insert compound CRS with number of components != 2");
2798
0
    }
2799
2800
0
    auto allowedAuthoritiesTmp(allowedAuthorities);
2801
0
    allowedAuthoritiesTmp.emplace_back(authName);
2802
2803
0
    for (const auto &component : components) {
2804
0
        std::string compAuthName;
2805
0
        std::string compCode;
2806
2807
0
        for (const auto &allowedAuthority : allowedAuthoritiesTmp) {
2808
0
            const auto factory =
2809
0
                AuthorityFactory::create(self, allowedAuthority);
2810
0
            const auto candidates = component->identify(factory);
2811
0
            for (const auto &candidate : candidates) {
2812
0
                if (candidate.second == 100) {
2813
0
                    const auto &ids = candidate.first->identifiers();
2814
0
                    if (!ids.empty()) {
2815
0
                        const auto &id = ids.front();
2816
0
                        compAuthName = *(id->codeSpace());
2817
0
                        compCode = id->code();
2818
0
                        break;
2819
0
                    }
2820
0
                }
2821
0
                if (!compAuthName.empty()) {
2822
0
                    break;
2823
0
                }
2824
0
            }
2825
0
        }
2826
2827
0
        if (compAuthName.empty()) {
2828
0
            compAuthName = authName;
2829
0
            if (numericCode) {
2830
0
                compCode = self->suggestsCodeFor(component, compAuthName, true);
2831
0
            } else {
2832
0
                compCode = "COMPONENT_" + code + '_' + toString(counter);
2833
0
            }
2834
0
            const auto sqlStatementsTmp =
2835
0
                self->getInsertStatementsFor(component, compAuthName, compCode,
2836
0
                                             numericCode, allowedAuthorities);
2837
0
            sqlStatements.insert(sqlStatements.end(), sqlStatementsTmp.begin(),
2838
0
                                 sqlStatementsTmp.end());
2839
0
        }
2840
2841
0
        componentsId.emplace_back(
2842
0
            std::pair<std::string, std::string>(compAuthName, compCode));
2843
2844
0
        ++counter;
2845
0
    }
2846
2847
    // Insert new record in compound_crs table
2848
0
    const auto sql = formatStatement(
2849
0
        "INSERT INTO compound_crs VALUES("
2850
0
        "'%q','%q','%q','%q','%q','%q','%q','%q',0);",
2851
0
        authName.c_str(), code.c_str(), crs->nameStr().c_str(),
2852
0
        "", // description
2853
0
        componentsId[0].first.c_str(), componentsId[0].second.c_str(),
2854
0
        componentsId[1].first.c_str(), componentsId[1].second.c_str());
2855
0
    appendSql(sqlStatements, sql);
2856
2857
0
    identifyOrInsertUsages(crs, "compound_crs", authName, code,
2858
0
                           allowedAuthorities, sqlStatements);
2859
2860
0
    return sqlStatements;
2861
0
}
2862
2863
//! @endcond
2864
2865
// ---------------------------------------------------------------------------
2866
2867
//! @cond Doxygen_Suppress
2868
70.6k
DatabaseContext::~DatabaseContext() {
2869
70.6k
    try {
2870
70.6k
        stopInsertStatementsSession();
2871
70.6k
    } catch (const std::exception &) {
2872
0
    }
2873
70.6k
}
2874
//! @endcond
2875
2876
// ---------------------------------------------------------------------------
2877
2878
70.6k
DatabaseContext::DatabaseContext() : d(internal::make_unique<Private>()) {}
2879
2880
// ---------------------------------------------------------------------------
2881
2882
/** \brief Instantiate a database context.
2883
 *
2884
 * This database context should be used only by one thread at a time.
2885
 *
2886
 * @param databasePath Path and filename of the database. Might be empty
2887
 * string for the default rules to locate the default proj.db
2888
 * @param auxiliaryDatabasePaths Path and filename of auxiliary databases.
2889
 * Might be empty.
2890
 * Starting with PROJ 8.1, if this parameter is an empty array,
2891
 * the PROJ_AUX_DB environment variable will be used, if set.
2892
 * It must contain one or several paths. If several paths are
2893
 * provided, they must be separated by the colon (:) character on Unix, and
2894
 * on Windows, by the semi-colon (;) character.
2895
 * @param ctx Context used for file search.
2896
 * @throw FactoryException
2897
 */
2898
DatabaseContextNNPtr
2899
DatabaseContext::create(const std::string &databasePath,
2900
                        const std::vector<std::string> &auxiliaryDatabasePaths,
2901
70.6k
                        PJ_CONTEXT *ctx) {
2902
70.6k
    auto dbCtx = DatabaseContext::nn_make_shared<DatabaseContext>();
2903
70.6k
    auto dbCtxPrivate = dbCtx->getPrivate();
2904
70.6k
    dbCtxPrivate->open(databasePath, ctx);
2905
70.6k
    auto auxDbs(auxiliaryDatabasePaths);
2906
70.6k
    if (auxDbs.empty()) {
2907
0
        const char *auxDbStr = getenv("PROJ_AUX_DB");
2908
0
        if (auxDbStr) {
2909
#ifdef _WIN32
2910
            const char *delim = ";";
2911
#else
2912
0
            const char *delim = ":";
2913
0
#endif
2914
0
            auxDbs = split(auxDbStr, delim);
2915
0
        }
2916
0
    }
2917
70.6k
    if (!auxDbs.empty()) {
2918
0
        dbCtxPrivate->attachExtraDatabases(auxDbs);
2919
0
        dbCtxPrivate->auxiliaryDatabasePaths_ = std::move(auxDbs);
2920
0
    }
2921
70.6k
    dbCtxPrivate->self_ = dbCtx.as_nullable();
2922
70.6k
    return dbCtx;
2923
70.6k
}
2924
2925
// ---------------------------------------------------------------------------
2926
2927
/** \brief Return the list of authorities used in the database.
2928
 */
2929
0
std::set<std::string> DatabaseContext::getAuthorities() const {
2930
0
    auto res = d->run("SELECT auth_name FROM authority_list");
2931
0
    std::set<std::string> list;
2932
0
    for (const auto &row : res) {
2933
0
        list.insert(row[0]);
2934
0
    }
2935
0
    return list;
2936
0
}
2937
2938
// ---------------------------------------------------------------------------
2939
2940
/** \brief Return the list of SQL commands (CREATE TABLE, CREATE TRIGGER,
2941
 * CREATE VIEW) needed to initialize a new database.
2942
 */
2943
0
std::vector<std::string> DatabaseContext::getDatabaseStructure() const {
2944
0
    return d->getDatabaseStructure();
2945
0
}
2946
2947
// ---------------------------------------------------------------------------
2948
2949
/** \brief Return the path to the database.
2950
 */
2951
0
const std::string &DatabaseContext::getPath() const { return d->getPath(); }
2952
2953
// ---------------------------------------------------------------------------
2954
2955
/** \brief Return a metadata item.
2956
 *
2957
 * Value remains valid while this is alive and to the next call to getMetadata
2958
 */
2959
0
const char *DatabaseContext::getMetadata(const char *key) const {
2960
0
    auto res =
2961
0
        d->run("SELECT value FROM metadata WHERE key = ?", {std::string(key)});
2962
0
    if (res.empty()) {
2963
0
        return nullptr;
2964
0
    }
2965
0
    d->lastMetadataValue_ = res.front()[0];
2966
0
    return d->lastMetadataValue_.c_str();
2967
0
}
2968
2969
// ---------------------------------------------------------------------------
2970
2971
/** \brief Starts a session for getInsertStatementsFor()
2972
 *
2973
 * Starts a new session for one or several calls to getInsertStatementsFor().
2974
 * An insertion session guarantees that the inserted objects will not create
2975
 * conflicting intermediate objects.
2976
 *
2977
 * The session must be stopped with stopInsertStatementsSession().
2978
 *
2979
 * Only one session may be active at a time for a given database context.
2980
 *
2981
 * @throw FactoryException
2982
 * @since 8.1
2983
 */
2984
0
void DatabaseContext::startInsertStatementsSession() {
2985
0
    if (d->memoryDbHandle_) {
2986
0
        throw FactoryException(
2987
0
            "startInsertStatementsSession() cannot be invoked until "
2988
0
            "stopInsertStatementsSession() is.");
2989
0
    }
2990
2991
0
    d->memoryDbForInsertPath_.clear();
2992
0
    const auto sqlStatements = getDatabaseStructure();
2993
2994
    // Create a in-memory temporary sqlite3 database
2995
0
    std::ostringstream buffer;
2996
0
    buffer << "file:temp_db_for_insert_statements_";
2997
0
    buffer << this;
2998
0
    buffer << ".db?mode=memory&cache=shared";
2999
0
    d->memoryDbForInsertPath_ = buffer.str();
3000
0
    sqlite3 *memoryDbHandle = nullptr;
3001
0
    sqlite3_open_v2(
3002
0
        d->memoryDbForInsertPath_.c_str(), &memoryDbHandle,
3003
0
        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI, nullptr);
3004
0
    if (memoryDbHandle == nullptr) {
3005
0
        throw FactoryException("Cannot create in-memory database");
3006
0
    }
3007
0
    d->memoryDbHandle_ =
3008
0
        SQLiteHandle::initFromExistingUniquePtr(memoryDbHandle, true);
3009
3010
    // Fill the structure of this database
3011
0
    for (const auto &sql : sqlStatements) {
3012
0
        char *errmsg = nullptr;
3013
0
        if (sqlite3_exec(d->memoryDbHandle_->handle(), sql.c_str(), nullptr,
3014
0
                         nullptr, &errmsg) != SQLITE_OK) {
3015
0
            const auto sErrMsg =
3016
0
                "Cannot execute " + sql + ": " + (errmsg ? errmsg : "");
3017
0
            sqlite3_free(errmsg);
3018
0
            throw FactoryException(sErrMsg);
3019
0
        }
3020
0
        sqlite3_free(errmsg);
3021
0
    }
3022
3023
    // Attach this database to the current one(s)
3024
0
    auto auxiliaryDatabasePaths(d->auxiliaryDatabasePaths_);
3025
0
    auxiliaryDatabasePaths.push_back(d->memoryDbForInsertPath_);
3026
0
    d->attachExtraDatabases(auxiliaryDatabasePaths);
3027
0
}
3028
3029
// ---------------------------------------------------------------------------
3030
3031
/** \brief Suggests a database code for the passed object.
3032
 *
3033
 * Supported type of objects are PrimeMeridian, Ellipsoid, Datum, DatumEnsemble,
3034
 * GeodeticCRS, ProjectedCRS, VerticalCRS, CompoundCRS, BoundCRS, Conversion.
3035
 *
3036
 * @param object Object for which to suggest a code.
3037
 * @param authName Authority name into which the object will be inserted.
3038
 * @param numericCode Whether the code should be numeric, or derived from the
3039
 * object name.
3040
 * @return the suggested code, that is guaranteed to not conflict with an
3041
 * existing one.
3042
 *
3043
 * @throw FactoryException
3044
 * @since 8.1
3045
 */
3046
std::string
3047
DatabaseContext::suggestsCodeFor(const common::IdentifiedObjectNNPtr &object,
3048
                                 const std::string &authName,
3049
0
                                 bool numericCode) {
3050
0
    const char *tableName = "";
3051
0
    if (dynamic_cast<const datum::PrimeMeridian *>(object.get())) {
3052
0
        tableName = "prime_meridian";
3053
0
    } else if (dynamic_cast<const datum::Ellipsoid *>(object.get())) {
3054
0
        tableName = "ellipsoid";
3055
0
    } else if (dynamic_cast<const datum::GeodeticReferenceFrame *>(
3056
0
                   object.get())) {
3057
0
        tableName = "geodetic_datum";
3058
0
    } else if (dynamic_cast<const datum::VerticalReferenceFrame *>(
3059
0
                   object.get())) {
3060
0
        tableName = "vertical_datum";
3061
0
    } else if (const auto ensemble =
3062
0
                   dynamic_cast<const datum::DatumEnsemble *>(object.get())) {
3063
0
        const auto &datums = ensemble->datums();
3064
0
        if (!datums.empty() &&
3065
0
            dynamic_cast<const datum::GeodeticReferenceFrame *>(
3066
0
                datums[0].get())) {
3067
0
            tableName = "geodetic_datum";
3068
0
        } else {
3069
0
            tableName = "vertical_datum";
3070
0
        }
3071
0
    } else if (const auto boundCRS =
3072
0
                   dynamic_cast<const crs::BoundCRS *>(object.get())) {
3073
0
        return suggestsCodeFor(boundCRS->baseCRS(), authName, numericCode);
3074
0
    } else if (dynamic_cast<const crs::CRS *>(object.get())) {
3075
0
        tableName = "crs_view";
3076
0
    } else if (dynamic_cast<const operation::Conversion *>(object.get())) {
3077
0
        tableName = "conversion";
3078
0
    } else {
3079
0
        throw FactoryException("suggestsCodeFor(): unhandled type of object");
3080
0
    }
3081
3082
0
    if (numericCode) {
3083
0
        std::string sql("SELECT MAX(code) FROM ");
3084
0
        sql += tableName;
3085
0
        sql += " WHERE auth_name = ? AND code >= '1' AND code <= '999999999' "
3086
0
               "AND upper(code) = lower(code)";
3087
0
        const auto res = d->run(sql, {authName});
3088
0
        if (res.empty()) {
3089
0
            return "1";
3090
0
        }
3091
0
        return toString(atoi(res.front()[0].c_str()) + 1);
3092
0
    }
3093
3094
0
    std::string code;
3095
0
    code.reserve(object->nameStr().size());
3096
0
    bool insertUnderscore = false;
3097
0
    for (const auto ch : toupper(object->nameStr())) {
3098
0
        if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z')) {
3099
0
            if (insertUnderscore && code.back() != '_')
3100
0
                code += '_';
3101
0
            code += ch;
3102
0
            insertUnderscore = false;
3103
0
        } else {
3104
0
            insertUnderscore = true;
3105
0
        }
3106
0
    }
3107
0
    return d->findFreeCode(tableName, authName, code);
3108
0
}
3109
3110
// ---------------------------------------------------------------------------
3111
3112
/** \brief Returns SQL statements needed to insert the passed object into the
3113
 * database.
3114
 *
3115
 * startInsertStatementsSession() must have been called previously.
3116
 *
3117
 * @param object The object to insert into the database. Currently only
3118
 *               PrimeMeridian, Ellipsoid, Datum, GeodeticCRS, ProjectedCRS,
3119
 *               VerticalCRS, CompoundCRS or BoundCRS are supported.
3120
 * @param authName Authority name into which the object will be inserted.
3121
 * @param code Code with which the object will be inserted.
3122
 * @param numericCode Whether intermediate objects that can be created should
3123
 *                    use numeric codes (true), or may be alphanumeric (false)
3124
 * @param allowedAuthorities Authorities to which intermediate objects are
3125
 *                           allowed to refer to. authName will be implicitly
3126
 *                           added to it. Note that unit, coordinate
3127
 *                           systems, projection methods and parameters will in
3128
 *                           any case be allowed to refer to EPSG.
3129
 * @throw FactoryException
3130
 * @since 8.1
3131
 */
3132
std::vector<std::string> DatabaseContext::getInsertStatementsFor(
3133
    const common::IdentifiedObjectNNPtr &object, const std::string &authName,
3134
    const std::string &code, bool numericCode,
3135
0
    const std::vector<std::string> &allowedAuthorities) {
3136
0
    if (d->memoryDbHandle_ == nullptr) {
3137
0
        throw FactoryException(
3138
0
            "startInsertStatementsSession() should be invoked first");
3139
0
    }
3140
3141
0
    const auto crs = util::nn_dynamic_pointer_cast<crs::CRS>(object);
3142
0
    if (crs) {
3143
        // Check if the object is already known under that code
3144
0
        const auto self = NN_NO_CHECK(d->self_.lock());
3145
0
        auto allowedAuthoritiesTmp(allowedAuthorities);
3146
0
        allowedAuthoritiesTmp.emplace_back(authName);
3147
0
        for (const auto &allowedAuthority : allowedAuthoritiesTmp) {
3148
0
            const auto factory =
3149
0
                AuthorityFactory::create(self, allowedAuthority);
3150
0
            const auto candidates = crs->identify(factory);
3151
0
            for (const auto &candidate : candidates) {
3152
0
                if (candidate.second == 100) {
3153
0
                    const auto &ids = candidate.first->identifiers();
3154
0
                    for (const auto &id : ids) {
3155
0
                        if (*(id->codeSpace()) == authName &&
3156
0
                            id->code() == code) {
3157
0
                            return {};
3158
0
                        }
3159
0
                    }
3160
0
                }
3161
0
            }
3162
0
        }
3163
0
    }
3164
3165
0
    if (const auto pm =
3166
0
            util::nn_dynamic_pointer_cast<datum::PrimeMeridian>(object)) {
3167
0
        return d->getInsertStatementsFor(NN_NO_CHECK(pm), authName, code,
3168
0
                                         numericCode, allowedAuthorities);
3169
0
    }
3170
3171
0
    else if (const auto ellipsoid =
3172
0
                 util::nn_dynamic_pointer_cast<datum::Ellipsoid>(object)) {
3173
0
        return d->getInsertStatementsFor(NN_NO_CHECK(ellipsoid), authName, code,
3174
0
                                         numericCode, allowedAuthorities);
3175
0
    }
3176
3177
0
    else if (const auto geodeticDatum =
3178
0
                 util::nn_dynamic_pointer_cast<datum::GeodeticReferenceFrame>(
3179
0
                     object)) {
3180
0
        return d->getInsertStatementsFor(NN_NO_CHECK(geodeticDatum), authName,
3181
0
                                         code, numericCode, allowedAuthorities);
3182
0
    }
3183
3184
0
    else if (const auto ensemble =
3185
0
                 util::nn_dynamic_pointer_cast<datum::DatumEnsemble>(object)) {
3186
0
        return d->getInsertStatementsFor(NN_NO_CHECK(ensemble), authName, code,
3187
0
                                         numericCode, allowedAuthorities);
3188
0
    }
3189
3190
0
    else if (const auto geodCRS =
3191
0
                 std::dynamic_pointer_cast<crs::GeodeticCRS>(crs)) {
3192
0
        return d->getInsertStatementsFor(NN_NO_CHECK(geodCRS), authName, code,
3193
0
                                         numericCode, allowedAuthorities);
3194
0
    }
3195
3196
0
    else if (const auto projCRS =
3197
0
                 std::dynamic_pointer_cast<crs::ProjectedCRS>(crs)) {
3198
0
        return d->getInsertStatementsFor(NN_NO_CHECK(projCRS), authName, code,
3199
0
                                         numericCode, allowedAuthorities);
3200
0
    }
3201
3202
0
    else if (const auto verticalDatum =
3203
0
                 util::nn_dynamic_pointer_cast<datum::VerticalReferenceFrame>(
3204
0
                     object)) {
3205
0
        return d->getInsertStatementsFor(NN_NO_CHECK(verticalDatum), authName,
3206
0
                                         code, numericCode, allowedAuthorities);
3207
0
    }
3208
3209
0
    else if (const auto vertCRS =
3210
0
                 std::dynamic_pointer_cast<crs::VerticalCRS>(crs)) {
3211
0
        return d->getInsertStatementsFor(NN_NO_CHECK(vertCRS), authName, code,
3212
0
                                         numericCode, allowedAuthorities);
3213
0
    }
3214
3215
0
    else if (const auto compoundCRS =
3216
0
                 std::dynamic_pointer_cast<crs::CompoundCRS>(crs)) {
3217
0
        return d->getInsertStatementsFor(NN_NO_CHECK(compoundCRS), authName,
3218
0
                                         code, numericCode, allowedAuthorities);
3219
0
    }
3220
3221
0
    else if (const auto boundCRS =
3222
0
                 std::dynamic_pointer_cast<crs::BoundCRS>(crs)) {
3223
0
        return getInsertStatementsFor(boundCRS->baseCRS(), authName, code,
3224
0
                                      numericCode, allowedAuthorities);
3225
0
    }
3226
3227
0
    else {
3228
0
        throw FactoryException(
3229
0
            "getInsertStatementsFor(): unhandled type of object");
3230
0
    }
3231
0
}
3232
3233
// ---------------------------------------------------------------------------
3234
3235
/** \brief Stops an insertion session started with
3236
 * startInsertStatementsSession()
3237
 *
3238
 * @since 8.1
3239
 */
3240
70.6k
void DatabaseContext::stopInsertStatementsSession() {
3241
70.6k
    if (d->memoryDbHandle_) {
3242
0
        d->clearCaches();
3243
0
        d->attachExtraDatabases(d->auxiliaryDatabasePaths_);
3244
0
        d->memoryDbHandle_.reset();
3245
0
        d->memoryDbForInsertPath_.clear();
3246
0
    }
3247
70.6k
}
3248
3249
// ---------------------------------------------------------------------------
3250
3251
//! @cond Doxygen_Suppress
3252
3253
0
DatabaseContextNNPtr DatabaseContext::create(void *sqlite_handle) {
3254
0
    auto ctxt = DatabaseContext::nn_make_shared<DatabaseContext>();
3255
0
    ctxt->getPrivate()->setHandle(static_cast<sqlite3 *>(sqlite_handle));
3256
0
    return ctxt;
3257
0
}
3258
3259
// ---------------------------------------------------------------------------
3260
3261
0
void *DatabaseContext::getSqliteHandle() const { return d->handle()->handle(); }
3262
3263
// ---------------------------------------------------------------------------
3264
3265
bool DatabaseContext::lookForGridAlternative(const std::string &officialName,
3266
                                             std::string &projFilename,
3267
                                             std::string &projFormat,
3268
0
                                             bool &inverse) const {
3269
0
    auto res = d->run(
3270
0
        "SELECT proj_grid_name, proj_grid_format, inverse_direction FROM "
3271
0
        "grid_alternatives WHERE original_grid_name = ? AND "
3272
0
        "proj_grid_name <> ''",
3273
0
        {officialName});
3274
0
    if (res.empty()) {
3275
0
        return false;
3276
0
    }
3277
0
    const auto &row = res.front();
3278
0
    projFilename = row[0];
3279
0
    projFormat = row[1];
3280
0
    inverse = row[2] == "1";
3281
0
    return true;
3282
0
}
3283
3284
// ---------------------------------------------------------------------------
3285
3286
bool DatabaseContext::lookForGridInfo(
3287
    const std::string &projFilename, bool considerKnownGridsAsAvailable,
3288
    std::string &fullFilename, std::string &packageName, std::string &url,
3289
0
    bool &directDownload, bool &openLicense, bool &gridAvailable) const {
3290
0
    Private::GridInfoCache info;
3291
3292
0
    if (projFilename == "null") {
3293
        // Special case for implicit "null" grid.
3294
0
        fullFilename.clear();
3295
0
        packageName.clear();
3296
0
        url.clear();
3297
0
        directDownload = false;
3298
0
        openLicense = true;
3299
0
        gridAvailable = true;
3300
0
        return true;
3301
0
    }
3302
3303
0
    auto ctxt = d->pjCtxt();
3304
0
    if (ctxt == nullptr) {
3305
0
        ctxt = pj_get_default_ctx();
3306
0
        d->setPjCtxt(ctxt);
3307
0
    }
3308
3309
0
    std::string key(projFilename);
3310
0
    key += proj_context_is_network_enabled(ctxt) ? "true" : "false";
3311
0
    key += considerKnownGridsAsAvailable ? "true" : "false";
3312
0
    if (d->getGridInfoFromCache(key, info)) {
3313
0
        fullFilename = info.fullFilename;
3314
0
        packageName = info.packageName;
3315
0
        url = info.url;
3316
0
        directDownload = info.directDownload;
3317
0
        openLicense = info.openLicense;
3318
0
        gridAvailable = info.gridAvailable;
3319
0
        return info.found;
3320
0
    }
3321
3322
0
    fullFilename.clear();
3323
0
    packageName.clear();
3324
0
    url.clear();
3325
0
    openLicense = false;
3326
0
    directDownload = false;
3327
3328
0
    fullFilename.resize(2048);
3329
0
    int errno_before = proj_context_errno(ctxt);
3330
0
    gridAvailable = NS_PROJ::FileManager::open_resource_file(
3331
0
                        ctxt, projFilename.c_str(), &fullFilename[0],
3332
0
                        fullFilename.size() - 1) != nullptr;
3333
0
    proj_context_errno_set(ctxt, errno_before);
3334
0
    fullFilename.resize(strlen(fullFilename.c_str()));
3335
3336
0
    auto res =
3337
0
        d->run("SELECT "
3338
0
               "grid_packages.package_name, "
3339
0
               "grid_alternatives.url, "
3340
0
               "grid_packages.url AS package_url, "
3341
0
               "grid_alternatives.open_license, "
3342
0
               "grid_packages.open_license AS package_open_license, "
3343
0
               "grid_alternatives.direct_download, "
3344
0
               "grid_packages.direct_download AS package_direct_download, "
3345
0
               "grid_alternatives.proj_grid_name, "
3346
0
               "grid_alternatives.old_proj_grid_name "
3347
0
               "FROM grid_alternatives "
3348
0
               "LEFT JOIN grid_packages ON "
3349
0
               "grid_alternatives.package_name = grid_packages.package_name "
3350
0
               "WHERE proj_grid_name = ? OR old_proj_grid_name = ?",
3351
0
               {projFilename, projFilename});
3352
0
    bool ret = !res.empty();
3353
0
    if (ret) {
3354
0
        const auto &row = res.front();
3355
0
        packageName = std::move(row[0]);
3356
0
        url = row[1].empty() ? std::move(row[2]) : std::move(row[1]);
3357
0
        openLicense = (row[3].empty() ? row[4] : row[3]) == "1";
3358
0
        directDownload = (row[5].empty() ? row[6] : row[5]) == "1";
3359
3360
0
        const auto &proj_grid_name = row[7];
3361
0
        const auto &old_proj_grid_name = row[8];
3362
0
        if (proj_grid_name != old_proj_grid_name &&
3363
0
            old_proj_grid_name == projFilename) {
3364
0
            std::string fullFilenameNewName;
3365
0
            fullFilenameNewName.resize(2048);
3366
0
            errno_before = proj_context_errno(ctxt);
3367
0
            bool gridAvailableWithNewName =
3368
0
                pj_find_file(ctxt, proj_grid_name.c_str(),
3369
0
                             &fullFilenameNewName[0],
3370
0
                             fullFilenameNewName.size() - 1) != 0;
3371
0
            proj_context_errno_set(ctxt, errno_before);
3372
0
            fullFilenameNewName.resize(strlen(fullFilenameNewName.c_str()));
3373
0
            if (gridAvailableWithNewName) {
3374
0
                gridAvailable = true;
3375
0
                fullFilename = std::move(fullFilenameNewName);
3376
0
            }
3377
0
        }
3378
3379
0
        if (considerKnownGridsAsAvailable &&
3380
0
            (!packageName.empty() || (!url.empty() && openLicense))) {
3381
0
            gridAvailable = true;
3382
0
        }
3383
3384
0
        info.packageName = packageName;
3385
0
        std::string endpoint(proj_context_get_url_endpoint(d->pjCtxt()));
3386
0
        if (!endpoint.empty() && starts_with(url, "https://cdn.proj.org/")) {
3387
0
            if (endpoint.back() != '/') {
3388
0
                endpoint += '/';
3389
0
            }
3390
0
            url = endpoint + url.substr(strlen("https://cdn.proj.org/"));
3391
0
        }
3392
0
        info.directDownload = directDownload;
3393
0
        info.openLicense = openLicense;
3394
0
    } else {
3395
0
        if (starts_with(fullFilename, "http://") ||
3396
0
            starts_with(fullFilename, "https://")) {
3397
0
            url = fullFilename;
3398
0
            fullFilename.clear();
3399
0
        }
3400
0
    }
3401
3402
0
    info.fullFilename = fullFilename;
3403
0
    info.url = url;
3404
0
    info.gridAvailable = gridAvailable;
3405
0
    info.found = ret;
3406
0
    d->cache(key, info);
3407
0
    return ret;
3408
0
}
3409
3410
// ---------------------------------------------------------------------------
3411
3412
bool DatabaseContext::isKnownName(const std::string &name,
3413
0
                                  const std::string &tableName) const {
3414
0
    std::string sql("SELECT 1 FROM \"");
3415
0
    sql += replaceAll(tableName, "\"", "\"\"");
3416
0
    sql += "\" WHERE name = ? LIMIT 1";
3417
0
    return !d->run(sql, {name}).empty();
3418
0
}
3419
// ---------------------------------------------------------------------------
3420
3421
std::string
3422
0
DatabaseContext::getProjGridName(const std::string &oldProjGridName) {
3423
0
    auto res = d->run("SELECT proj_grid_name FROM grid_alternatives WHERE "
3424
0
                      "old_proj_grid_name = ?",
3425
0
                      {oldProjGridName});
3426
0
    if (res.empty()) {
3427
0
        return std::string();
3428
0
    }
3429
0
    return res.front()[0];
3430
0
}
3431
3432
// ---------------------------------------------------------------------------
3433
3434
0
std::string DatabaseContext::getOldProjGridName(const std::string &gridName) {
3435
0
    auto res = d->run("SELECT old_proj_grid_name FROM grid_alternatives WHERE "
3436
0
                      "proj_grid_name = ?",
3437
0
                      {gridName});
3438
0
    if (res.empty()) {
3439
0
        return std::string();
3440
0
    }
3441
0
    return res.front()[0];
3442
0
}
3443
3444
// ---------------------------------------------------------------------------
3445
3446
// scripts/build_db_from_esri.py adds a second alias for
3447
// names that have '[' in them. See get_old_esri_name()
3448
// in scripts/build_db_from_esri.py
3449
// So if we only have two aliases detect that situation to get the official
3450
// new name
3451
0
static std::string getUniqueEsriAlias(const std::list<std::string> &l) {
3452
0
    std::string first = l.front();
3453
0
    std::string second = *(std::next(l.begin()));
3454
0
    if (second.find('[') != std::string::npos)
3455
0
        std::swap(first, second);
3456
0
    if (replaceAll(replaceAll(replaceAll(first, "[", ""), "]", ""), "-", "_") ==
3457
0
        second) {
3458
0
        return first;
3459
0
    }
3460
0
    return std::string();
3461
0
}
3462
3463
// ---------------------------------------------------------------------------
3464
3465
/** \brief Gets the alias name from an official name.
3466
 *
3467
 * @param officialName Official name. Mandatory
3468
 * @param tableName Table name/category. Mandatory.
3469
 *                  "geographic_2D_crs" and "geographic_3D_crs" are also
3470
 *                  accepted as special names to add a constraint on the "type"
3471
 *                  column of the "geodetic_crs" table.
3472
 * @param source Source of the alias. Mandatory
3473
 * @return Alias name (or empty if not found).
3474
 * @throw FactoryException
3475
 */
3476
std::string
3477
DatabaseContext::getAliasFromOfficialName(const std::string &officialName,
3478
                                          const std::string &tableName,
3479
0
                                          const std::string &source) const {
3480
0
    std::string sql("SELECT auth_name, code FROM \"");
3481
0
    const auto genuineTableName =
3482
0
        tableName == "geographic_2D_crs" || tableName == "geographic_3D_crs"
3483
0
            ? "geodetic_crs"
3484
0
            : tableName;
3485
0
    sql += replaceAll(genuineTableName, "\"", "\"\"");
3486
0
    sql += "\" WHERE name = ?";
3487
0
    if (tableName == "geodetic_crs" || tableName == "geographic_2D_crs") {
3488
0
        sql += " AND type = " GEOG_2D_SINGLE_QUOTED;
3489
0
    } else if (tableName == "geographic_3D_crs") {
3490
0
        sql += " AND type = " GEOG_3D_SINGLE_QUOTED;
3491
0
    }
3492
0
    sql += " ORDER BY deprecated";
3493
0
    auto res = d->run(sql, {officialName});
3494
    // Sorry for the hack excluding NAD83 + geographic_3D_crs, but otherwise
3495
    // EPSG has a weird alias from NAD83 to EPSG:4152 which happens to be
3496
    // NAD83(HARN), and that's definitely not desirable.
3497
0
    if (res.empty() &&
3498
0
        !(officialName == "NAD83" && tableName == "geographic_3D_crs")) {
3499
0
        res = d->run(
3500
0
            "SELECT auth_name, code FROM alias_name WHERE table_name = ? AND "
3501
0
            "alt_name = ? AND source IN ('EPSG', 'PROJ')",
3502
0
            {genuineTableName, officialName});
3503
0
        if (res.size() != 1) {
3504
0
            return std::string();
3505
0
        }
3506
0
    }
3507
0
    for (const auto &row : res) {
3508
0
        auto res2 =
3509
0
            d->run("SELECT alt_name FROM alias_name WHERE table_name = ? AND "
3510
0
                   "auth_name = ? AND code = ? AND source = ?",
3511
0
                   {genuineTableName, row[0], row[1], source});
3512
0
        if (!res2.empty()) {
3513
0
            if (res2.size() == 2 && source == "ESRI") {
3514
0
                std::list<std::string> l;
3515
0
                l.emplace_back(res2.front()[0]);
3516
0
                l.emplace_back((*(std::next(res2.begin())))[0]);
3517
0
                const auto uniqueEsriAlias = getUniqueEsriAlias(l);
3518
0
                if (!uniqueEsriAlias.empty())
3519
0
                    return uniqueEsriAlias;
3520
0
            }
3521
0
            return res2.front()[0];
3522
0
        }
3523
0
    }
3524
0
    return std::string();
3525
0
}
3526
3527
// ---------------------------------------------------------------------------
3528
3529
/** \brief Gets the alias names for an object.
3530
 *
3531
 * Either authName + code or officialName must be non empty.
3532
 *
3533
 * @param authName Authority.
3534
 * @param code Code.
3535
 * @param officialName Official name.
3536
 * @param tableName Table name/category. Mandatory.
3537
 *                  "geographic_2D_crs" and "geographic_3D_crs" are also
3538
 *                  accepted as special names to add a constraint on the "type"
3539
 *                  column of the "geodetic_crs" table.
3540
 * @param source Source of the alias. May be empty.
3541
 * @return Aliases
3542
 */
3543
std::list<std::string> DatabaseContext::getAliases(
3544
    const std::string &authName, const std::string &code,
3545
    const std::string &officialName, const std::string &tableName,
3546
0
    const std::string &source) const {
3547
3548
0
    std::list<std::string> res;
3549
0
    const auto key(authName + code + officialName + tableName + source);
3550
0
    if (d->cacheAliasNames_.tryGet(key, res)) {
3551
0
        return res;
3552
0
    }
3553
3554
0
    std::string resolvedAuthName(authName);
3555
0
    std::string resolvedCode(code);
3556
0
    const auto genuineTableName =
3557
0
        tableName == "geographic_2D_crs" || tableName == "geographic_3D_crs"
3558
0
            ? "geodetic_crs"
3559
0
            : tableName;
3560
0
    if (authName.empty() || code.empty()) {
3561
0
        std::string sql("SELECT auth_name, code FROM \"");
3562
0
        sql += replaceAll(genuineTableName, "\"", "\"\"");
3563
0
        sql += "\" WHERE name = ?";
3564
0
        if (tableName == "geodetic_crs" || tableName == "geographic_2D_crs") {
3565
0
            sql += " AND type = " GEOG_2D_SINGLE_QUOTED;
3566
0
        } else if (tableName == "geographic_3D_crs") {
3567
0
            sql += " AND type = " GEOG_3D_SINGLE_QUOTED;
3568
0
        }
3569
0
        sql += " ORDER BY deprecated";
3570
0
        auto resSql = d->run(sql, {officialName});
3571
0
        if (resSql.empty()) {
3572
0
            resSql = d->run("SELECT auth_name, code FROM alias_name WHERE "
3573
0
                            "table_name = ? AND "
3574
0
                            "alt_name = ? AND source IN ('EPSG', 'PROJ')",
3575
0
                            {genuineTableName, officialName});
3576
0
            if (resSql.size() != 1) {
3577
0
                d->cacheAliasNames_.insert(key, res);
3578
0
                return res;
3579
0
            }
3580
0
        }
3581
0
        const auto &row = resSql.front();
3582
0
        resolvedAuthName = row[0];
3583
0
        resolvedCode = row[1];
3584
0
    }
3585
0
    std::string sql("SELECT alt_name FROM alias_name WHERE table_name = ? AND "
3586
0
                    "auth_name = ? AND code = ?");
3587
0
    ListOfParams params{genuineTableName, resolvedAuthName, resolvedCode};
3588
0
    if (!source.empty()) {
3589
0
        sql += " AND source = ?";
3590
0
        params.emplace_back(source);
3591
0
    }
3592
0
    auto resSql = d->run(sql, params);
3593
0
    for (const auto &row : resSql) {
3594
0
        res.emplace_back(row[0]);
3595
0
    }
3596
3597
0
    if (res.size() == 2 && source == "ESRI") {
3598
0
        const auto uniqueEsriAlias = getUniqueEsriAlias(res);
3599
0
        if (!uniqueEsriAlias.empty()) {
3600
0
            res.clear();
3601
0
            res.emplace_back(uniqueEsriAlias);
3602
0
        }
3603
0
    }
3604
3605
0
    d->cacheAliasNames_.insert(key, res);
3606
0
    return res;
3607
0
}
3608
3609
// ---------------------------------------------------------------------------
3610
3611
/** \brief Return the 'name' column of a table for an object
3612
 *
3613
 * @param tableName Table name/category.
3614
 * @param authName Authority name of the object.
3615
 * @param code Code of the object
3616
 * @return Name (or empty)
3617
 * @throw FactoryException
3618
 */
3619
std::string DatabaseContext::getName(const std::string &tableName,
3620
                                     const std::string &authName,
3621
0
                                     const std::string &code) const {
3622
0
    std::string sql("SELECT name FROM \"");
3623
0
    sql += replaceAll(tableName, "\"", "\"\"");
3624
0
    sql += "\" WHERE auth_name = ? AND code = ?";
3625
0
    auto res = d->run(sql, {authName, code});
3626
0
    if (res.empty()) {
3627
0
        return std::string();
3628
0
    }
3629
0
    return res.front()[0];
3630
0
}
3631
3632
// ---------------------------------------------------------------------------
3633
3634
/** \brief Return the 'text_definition' column of a table for an object
3635
 *
3636
 * @param tableName Table name/category.
3637
 * @param authName Authority name of the object.
3638
 * @param code Code of the object
3639
 * @return Text definition (or empty)
3640
 * @throw FactoryException
3641
 */
3642
std::string DatabaseContext::getTextDefinition(const std::string &tableName,
3643
                                               const std::string &authName,
3644
0
                                               const std::string &code) const {
3645
0
    std::string sql("SELECT text_definition FROM \"");
3646
0
    sql += replaceAll(tableName, "\"", "\"\"");
3647
0
    sql += "\" WHERE auth_name = ? AND code = ?";
3648
0
    auto res = d->run(sql, {authName, code});
3649
0
    if (res.empty()) {
3650
0
        return std::string();
3651
0
    }
3652
0
    return res.front()[0];
3653
0
}
3654
3655
// ---------------------------------------------------------------------------
3656
3657
/** \brief Return the allowed authorities when researching transformations
3658
 * between different authorities.
3659
 *
3660
 * @throw FactoryException
3661
 */
3662
std::vector<std::string> DatabaseContext::getAllowedAuthorities(
3663
    const std::string &sourceAuthName,
3664
0
    const std::string &targetAuthName) const {
3665
3666
0
    const auto key(sourceAuthName + targetAuthName);
3667
0
    auto hit = d->cacheAllowedAuthorities_.find(key);
3668
0
    if (hit != d->cacheAllowedAuthorities_.end()) {
3669
0
        return hit->second;
3670
0
    }
3671
3672
0
    auto sqlRes = d->run(
3673
0
        "SELECT allowed_authorities FROM authority_to_authority_preference "
3674
0
        "WHERE source_auth_name = ? AND target_auth_name = ?",
3675
0
        {sourceAuthName, targetAuthName});
3676
0
    if (sqlRes.empty()) {
3677
0
        sqlRes = d->run(
3678
0
            "SELECT allowed_authorities FROM authority_to_authority_preference "
3679
0
            "WHERE source_auth_name = ? AND target_auth_name = 'any'",
3680
0
            {sourceAuthName});
3681
0
    }
3682
0
    if (sqlRes.empty()) {
3683
0
        sqlRes = d->run(
3684
0
            "SELECT allowed_authorities FROM authority_to_authority_preference "
3685
0
            "WHERE source_auth_name = 'any' AND target_auth_name = ?",
3686
0
            {targetAuthName});
3687
0
    }
3688
0
    if (sqlRes.empty()) {
3689
0
        sqlRes = d->run(
3690
0
            "SELECT allowed_authorities FROM authority_to_authority_preference "
3691
0
            "WHERE source_auth_name = 'any' AND target_auth_name = 'any'",
3692
0
            {});
3693
0
    }
3694
0
    if (sqlRes.empty()) {
3695
0
        d->cacheAllowedAuthorities_[key] = std::vector<std::string>();
3696
0
        return std::vector<std::string>();
3697
0
    }
3698
0
    auto res = split(sqlRes.front()[0], ',');
3699
0
    d->cacheAllowedAuthorities_[key] = res;
3700
0
    return res;
3701
0
}
3702
3703
// ---------------------------------------------------------------------------
3704
3705
std::list<std::pair<std::string, std::string>>
3706
DatabaseContext::getNonDeprecated(const std::string &tableName,
3707
                                  const std::string &authName,
3708
0
                                  const std::string &code) const {
3709
0
    auto sqlRes =
3710
0
        d->run("SELECT replacement_auth_name, replacement_code, source "
3711
0
               "FROM deprecation "
3712
0
               "WHERE table_name = ? AND deprecated_auth_name = ? "
3713
0
               "AND deprecated_code = ?",
3714
0
               {tableName, authName, code});
3715
0
    std::list<std::pair<std::string, std::string>> res;
3716
0
    for (const auto &row : sqlRes) {
3717
0
        const auto &source = row[2];
3718
0
        if (source == "PROJ") {
3719
0
            const auto &replacement_auth_name = row[0];
3720
0
            const auto &replacement_code = row[1];
3721
0
            res.emplace_back(replacement_auth_name, replacement_code);
3722
0
        }
3723
0
    }
3724
0
    if (!res.empty()) {
3725
0
        return res;
3726
0
    }
3727
0
    for (const auto &row : sqlRes) {
3728
0
        const auto &replacement_auth_name = row[0];
3729
0
        const auto &replacement_code = row[1];
3730
0
        res.emplace_back(replacement_auth_name, replacement_code);
3731
0
    }
3732
0
    return res;
3733
0
}
3734
3735
// ---------------------------------------------------------------------------
3736
3737
const std::vector<DatabaseContext::Private::VersionedAuthName> &
3738
0
DatabaseContext::Private::getCacheAuthNameWithVersion() {
3739
0
    if (cacheAuthNameWithVersion_.empty()) {
3740
0
        const auto sqlRes =
3741
0
            run("SELECT versioned_auth_name, auth_name, version, priority "
3742
0
                "FROM versioned_auth_name_mapping");
3743
0
        for (const auto &row : sqlRes) {
3744
0
            VersionedAuthName van;
3745
0
            van.versionedAuthName = row[0];
3746
0
            van.authName = row[1];
3747
0
            van.version = row[2];
3748
0
            van.priority = atoi(row[3].c_str());
3749
0
            cacheAuthNameWithVersion_.emplace_back(std::move(van));
3750
0
        }
3751
0
    }
3752
0
    return cacheAuthNameWithVersion_;
3753
0
}
3754
3755
// ---------------------------------------------------------------------------
3756
3757
// From IAU_2015 returns (IAU,2015)
3758
bool DatabaseContext::getAuthorityAndVersion(
3759
    const std::string &versionedAuthName, std::string &authNameOut,
3760
0
    std::string &versionOut) {
3761
3762
0
    for (const auto &van : d->getCacheAuthNameWithVersion()) {
3763
0
        if (van.versionedAuthName == versionedAuthName) {
3764
0
            authNameOut = van.authName;
3765
0
            versionOut = van.version;
3766
0
            return true;
3767
0
        }
3768
0
    }
3769
0
    return false;
3770
0
}
3771
3772
// ---------------------------------------------------------------------------
3773
3774
// From IAU and 2015, returns IAU_2015
3775
bool DatabaseContext::getVersionedAuthority(const std::string &authName,
3776
                                            const std::string &version,
3777
0
                                            std::string &versionedAuthNameOut) {
3778
3779
0
    for (const auto &van : d->getCacheAuthNameWithVersion()) {
3780
0
        if (van.authName == authName && van.version == version) {
3781
0
            versionedAuthNameOut = van.versionedAuthName;
3782
0
            return true;
3783
0
        }
3784
0
    }
3785
0
    return false;
3786
0
}
3787
3788
// ---------------------------------------------------------------------------
3789
3790
// From IAU returns IAU_latest, ... IAU_2015
3791
std::vector<std::string>
3792
0
DatabaseContext::getVersionedAuthoritiesFromName(const std::string &authName) {
3793
3794
0
    typedef std::pair<std::string, int> VersionedAuthNamePriority;
3795
0
    std::vector<VersionedAuthNamePriority> tmp;
3796
0
    for (const auto &van : d->getCacheAuthNameWithVersion()) {
3797
0
        if (van.authName == authName) {
3798
0
            tmp.emplace_back(
3799
0
                VersionedAuthNamePriority(van.versionedAuthName, van.priority));
3800
0
        }
3801
0
    }
3802
0
    std::vector<std::string> res;
3803
0
    if (!tmp.empty()) {
3804
        // Sort by decreasing priority
3805
0
        std::sort(tmp.begin(), tmp.end(),
3806
0
                  [](const VersionedAuthNamePriority &a,
3807
0
                     const VersionedAuthNamePriority &b) {
3808
0
                      return b.second > a.second;
3809
0
                  });
3810
0
        for (const auto &pair : tmp)
3811
0
            res.emplace_back(pair.first);
3812
0
    }
3813
0
    return res;
3814
0
}
3815
3816
// ---------------------------------------------------------------------------
3817
3818
std::vector<operation::CoordinateOperationNNPtr>
3819
DatabaseContext::getTransformationsForGridName(
3820
0
    const DatabaseContextNNPtr &databaseContext, const std::string &gridName) {
3821
0
    auto sqlRes = databaseContext->d->run(
3822
0
        "SELECT auth_name, code FROM grid_transformation "
3823
0
        "WHERE grid_name = ? OR grid_name IN "
3824
0
        "(SELECT original_grid_name FROM grid_alternatives "
3825
0
        "WHERE proj_grid_name = ?) ORDER BY auth_name, code",
3826
0
        {gridName, gridName});
3827
0
    std::vector<operation::CoordinateOperationNNPtr> res;
3828
0
    for (const auto &row : sqlRes) {
3829
0
        res.emplace_back(AuthorityFactory::create(databaseContext, row[0])
3830
0
                             ->createCoordinateOperation(row[1], true));
3831
0
    }
3832
0
    return res;
3833
0
}
3834
3835
//! @endcond
3836
3837
// ---------------------------------------------------------------------------
3838
3839
//! @cond Doxygen_Suppress
3840
struct AuthorityFactory::Private {
3841
    Private(const DatabaseContextNNPtr &contextIn,
3842
            const std::string &authorityName)
3843
0
        : context_(contextIn), authority_(authorityName) {}
3844
3845
0
    inline const std::string &authority() PROJ_PURE_DEFN { return authority_; }
3846
3847
0
    inline const DatabaseContextNNPtr &context() PROJ_PURE_DEFN {
3848
0
        return context_;
3849
0
    }
3850
3851
    // cppcheck-suppress functionStatic
3852
0
    void setThis(AuthorityFactoryNNPtr factory) {
3853
0
        thisFactory_ = factory.as_nullable();
3854
0
    }
3855
3856
    // cppcheck-suppress functionStatic
3857
0
    AuthorityFactoryPtr getSharedFromThis() { return thisFactory_.lock(); }
3858
3859
0
    inline AuthorityFactoryNNPtr createFactory(const std::string &auth_name) {
3860
0
        if (auth_name == authority_) {
3861
0
            return NN_NO_CHECK(thisFactory_.lock());
3862
0
        }
3863
0
        return AuthorityFactory::create(context_, auth_name);
3864
0
    }
3865
3866
    bool rejectOpDueToMissingGrid(const operation::CoordinateOperationNNPtr &op,
3867
                                  bool considerKnownGridsAsAvailable);
3868
3869
    UnitOfMeasure createUnitOfMeasure(const std::string &auth_name,
3870
                                      const std::string &code);
3871
3872
    util::PropertyMap
3873
    createProperties(const std::string &code, const std::string &name,
3874
                     bool deprecated,
3875
                     const std::vector<ObjectDomainNNPtr> &usages);
3876
3877
    util::PropertyMap
3878
    createPropertiesSearchUsages(const std::string &table_name,
3879
                                 const std::string &code,
3880
                                 const std::string &name, bool deprecated);
3881
3882
    util::PropertyMap createPropertiesSearchUsages(
3883
        const std::string &table_name, const std::string &code,
3884
        const std::string &name, bool deprecated, const std::string &remarks);
3885
3886
    SQLResultSet run(const std::string &sql,
3887
                     const ListOfParams &parameters = ListOfParams());
3888
3889
    SQLResultSet runWithCodeParam(const std::string &sql,
3890
                                  const std::string &code);
3891
3892
    SQLResultSet runWithCodeParam(const char *sql, const std::string &code);
3893
3894
0
    bool hasAuthorityRestriction() const {
3895
0
        return !authority_.empty() && authority_ != "any";
3896
0
    }
3897
3898
    SQLResultSet createProjectedCRSBegin(const std::string &code);
3899
    crs::ProjectedCRSNNPtr createProjectedCRSEnd(const std::string &code,
3900
                                                 const SQLResultSet &res);
3901
3902
  private:
3903
    DatabaseContextNNPtr context_;
3904
    std::string authority_;
3905
    std::weak_ptr<AuthorityFactory> thisFactory_{};
3906
};
3907
3908
// ---------------------------------------------------------------------------
3909
3910
SQLResultSet AuthorityFactory::Private::run(const std::string &sql,
3911
0
                                            const ListOfParams &parameters) {
3912
0
    return context()->getPrivate()->run(sql, parameters);
3913
0
}
3914
3915
// ---------------------------------------------------------------------------
3916
3917
SQLResultSet
3918
AuthorityFactory::Private::runWithCodeParam(const std::string &sql,
3919
0
                                            const std::string &code) {
3920
0
    return run(sql, {authority(), code});
3921
0
}
3922
3923
// ---------------------------------------------------------------------------
3924
3925
SQLResultSet
3926
AuthorityFactory::Private::runWithCodeParam(const char *sql,
3927
0
                                            const std::string &code) {
3928
0
    return runWithCodeParam(std::string(sql), code);
3929
0
}
3930
3931
// ---------------------------------------------------------------------------
3932
3933
UnitOfMeasure
3934
AuthorityFactory::Private::createUnitOfMeasure(const std::string &auth_name,
3935
0
                                               const std::string &code) {
3936
0
    return *(createFactory(auth_name)->createUnitOfMeasure(code));
3937
0
}
3938
3939
// ---------------------------------------------------------------------------
3940
3941
util::PropertyMap AuthorityFactory::Private::createProperties(
3942
    const std::string &code, const std::string &name, bool deprecated,
3943
0
    const std::vector<ObjectDomainNNPtr> &usages) {
3944
0
    auto props = util::PropertyMap()
3945
0
                     .set(metadata::Identifier::CODESPACE_KEY, authority())
3946
0
                     .set(metadata::Identifier::CODE_KEY, code)
3947
0
                     .set(common::IdentifiedObject::NAME_KEY, name);
3948
0
    if (deprecated) {
3949
0
        props.set(common::IdentifiedObject::DEPRECATED_KEY, true);
3950
0
    }
3951
0
    if (!usages.empty()) {
3952
3953
0
        auto array(util::ArrayOfBaseObject::create());
3954
0
        for (const auto &usage : usages) {
3955
0
            array->add(usage);
3956
0
        }
3957
0
        props.set(common::ObjectUsage::OBJECT_DOMAIN_KEY,
3958
0
                  util::nn_static_pointer_cast<util::BaseObject>(array));
3959
0
    }
3960
0
    return props;
3961
0
}
3962
3963
// ---------------------------------------------------------------------------
3964
3965
util::PropertyMap AuthorityFactory::Private::createPropertiesSearchUsages(
3966
    const std::string &table_name, const std::string &code,
3967
0
    const std::string &name, bool deprecated) {
3968
3969
0
    SQLResultSet res;
3970
0
    if (table_name == "geodetic_crs" && code == "4326" &&
3971
0
        authority() == "EPSG") {
3972
        // EPSG v10.077 has changed the extent from 1262 to 2830, whose
3973
        // description is super verbose.
3974
        // Cf https://epsg.org/closed-change-request/browse/id/2022.086
3975
        // To avoid churn in our WKT2 output, hot patch to the usage of
3976
        // 10.076 and earlier
3977
0
        res = run("SELECT extent.description, extent.south_lat, "
3978
0
                  "extent.north_lat, extent.west_lon, extent.east_lon, "
3979
0
                  "scope.scope, 0 AS score FROM extent, scope WHERE "
3980
0
                  "extent.code = 1262 and scope.code = 1183");
3981
0
    } else {
3982
0
        const std::string sql(
3983
0
            "SELECT extent.description, extent.south_lat, "
3984
0
            "extent.north_lat, extent.west_lon, extent.east_lon, "
3985
0
            "scope.scope, "
3986
0
            "(CASE WHEN scope.scope LIKE '%large scale%' THEN 0 ELSE 1 END) "
3987
0
            "AS score "
3988
0
            "FROM usage "
3989
0
            "JOIN extent ON usage.extent_auth_name = extent.auth_name AND "
3990
0
            "usage.extent_code = extent.code "
3991
0
            "JOIN scope ON usage.scope_auth_name = scope.auth_name AND "
3992
0
            "usage.scope_code = scope.code "
3993
0
            "WHERE object_table_name = ? AND object_auth_name = ? AND "
3994
0
            "object_code = ? AND "
3995
            // We voluntary exclude extent and scope with a specific code
3996
0
            "NOT (usage.extent_auth_name = 'PROJ' AND "
3997
0
            "usage.extent_code = 'EXTENT_UNKNOWN') AND "
3998
0
            "NOT (usage.scope_auth_name = 'PROJ' AND "
3999
0
            "usage.scope_code = 'SCOPE_UNKNOWN') "
4000
0
            "ORDER BY score, usage.auth_name, usage.code");
4001
0
        res = run(sql, {table_name, authority(), code});
4002
0
    }
4003
0
    std::vector<ObjectDomainNNPtr> usages;
4004
0
    for (const auto &row : res) {
4005
0
        try {
4006
0
            size_t idx = 0;
4007
0
            const auto &extent_description = row[idx++];
4008
0
            const auto &south_lat_str = row[idx++];
4009
0
            const auto &north_lat_str = row[idx++];
4010
0
            const auto &west_lon_str = row[idx++];
4011
0
            const auto &east_lon_str = row[idx++];
4012
0
            const auto &scope = row[idx];
4013
4014
0
            util::optional<std::string> scopeOpt;
4015
0
            if (!scope.empty()) {
4016
0
                scopeOpt = scope;
4017
0
            }
4018
4019
0
            metadata::ExtentPtr extent;
4020
0
            if (south_lat_str.empty()) {
4021
0
                extent = metadata::Extent::create(
4022
0
                             util::optional<std::string>(extent_description),
4023
0
                             {}, {}, {})
4024
0
                             .as_nullable();
4025
0
            } else {
4026
0
                double south_lat = c_locale_stod(south_lat_str);
4027
0
                double north_lat = c_locale_stod(north_lat_str);
4028
0
                double west_lon = c_locale_stod(west_lon_str);
4029
0
                double east_lon = c_locale_stod(east_lon_str);
4030
0
                auto bbox = metadata::GeographicBoundingBox::create(
4031
0
                    west_lon, south_lat, east_lon, north_lat);
4032
0
                extent = metadata::Extent::create(
4033
0
                             util::optional<std::string>(extent_description),
4034
0
                             std::vector<metadata::GeographicExtentNNPtr>{bbox},
4035
0
                             std::vector<metadata::VerticalExtentNNPtr>(),
4036
0
                             std::vector<metadata::TemporalExtentNNPtr>())
4037
0
                             .as_nullable();
4038
0
            }
4039
4040
0
            usages.emplace_back(ObjectDomain::create(scopeOpt, extent));
4041
0
        } catch (const std::exception &) {
4042
0
        }
4043
0
    }
4044
0
    return createProperties(code, name, deprecated, std::move(usages));
4045
0
}
4046
4047
// ---------------------------------------------------------------------------
4048
4049
util::PropertyMap AuthorityFactory::Private::createPropertiesSearchUsages(
4050
    const std::string &table_name, const std::string &code,
4051
0
    const std::string &name, bool deprecated, const std::string &remarks) {
4052
0
    auto props =
4053
0
        createPropertiesSearchUsages(table_name, code, name, deprecated);
4054
0
    if (!remarks.empty())
4055
0
        props.set(common::IdentifiedObject::REMARKS_KEY, remarks);
4056
0
    return props;
4057
0
}
4058
4059
// ---------------------------------------------------------------------------
4060
4061
bool AuthorityFactory::Private::rejectOpDueToMissingGrid(
4062
    const operation::CoordinateOperationNNPtr &op,
4063
0
    bool considerKnownGridsAsAvailable) {
4064
4065
0
    struct DisableNetwork {
4066
0
        const DatabaseContextNNPtr &m_dbContext;
4067
0
        bool m_old_network_enabled = false;
4068
4069
0
        explicit DisableNetwork(const DatabaseContextNNPtr &l_context)
4070
0
            : m_dbContext(l_context) {
4071
0
            auto ctxt = m_dbContext->d->pjCtxt();
4072
0
            if (ctxt == nullptr) {
4073
0
                ctxt = pj_get_default_ctx();
4074
0
                m_dbContext->d->setPjCtxt(ctxt);
4075
0
            }
4076
0
            m_old_network_enabled =
4077
0
                proj_context_is_network_enabled(ctxt) != FALSE;
4078
0
            if (m_old_network_enabled)
4079
0
                proj_context_set_enable_network(ctxt, false);
4080
0
        }
4081
4082
0
        ~DisableNetwork() {
4083
0
            if (m_old_network_enabled) {
4084
0
                auto ctxt = m_dbContext->d->pjCtxt();
4085
0
                proj_context_set_enable_network(ctxt, true);
4086
0
            }
4087
0
        }
4088
0
    };
4089
4090
0
    auto &l_context = context();
4091
    // Temporarily disable networking as we are only interested in known grids
4092
0
    DisableNetwork disabler(l_context);
4093
4094
0
    for (const auto &gridDesc :
4095
0
         op->gridsNeeded(l_context, considerKnownGridsAsAvailable)) {
4096
0
        if (!gridDesc.available) {
4097
0
            return true;
4098
0
        }
4099
0
    }
4100
0
    return false;
4101
0
}
4102
4103
//! @endcond
4104
4105
// ---------------------------------------------------------------------------
4106
4107
//! @cond Doxygen_Suppress
4108
0
AuthorityFactory::~AuthorityFactory() = default;
4109
//! @endcond
4110
4111
// ---------------------------------------------------------------------------
4112
4113
AuthorityFactory::AuthorityFactory(const DatabaseContextNNPtr &context,
4114
                                   const std::string &authorityName)
4115
0
    : d(internal::make_unique<Private>(context, authorityName)) {}
4116
4117
// ---------------------------------------------------------------------------
4118
4119
// clang-format off
4120
/** \brief Instantiate a AuthorityFactory.
4121
 *
4122
 * The authority name might be set to the empty string in the particular case
4123
 * where createFromCoordinateReferenceSystemCodes(const std::string&,const std::string&,const std::string&,const std::string&) const
4124
 * is called.
4125
 *
4126
 * @param context Context.
4127
 * @param authorityName Authority name.
4128
 * @return new AuthorityFactory.
4129
 */
4130
// clang-format on
4131
4132
AuthorityFactoryNNPtr
4133
AuthorityFactory::create(const DatabaseContextNNPtr &context,
4134
0
                         const std::string &authorityName) {
4135
0
    const auto getFactory = [&context, &authorityName]() {
4136
0
        for (const auto &knownName :
4137
0
             {metadata::Identifier::EPSG.c_str(), "ESRI", "PROJ"}) {
4138
0
            if (ci_equal(authorityName, knownName)) {
4139
0
                return AuthorityFactory::nn_make_shared<AuthorityFactory>(
4140
0
                    context, knownName);
4141
0
            }
4142
0
        }
4143
0
        return AuthorityFactory::nn_make_shared<AuthorityFactory>(
4144
0
            context, authorityName);
4145
0
    };
4146
0
    auto factory = getFactory();
4147
0
    factory->d->setThis(factory);
4148
0
    return factory;
4149
0
}
4150
4151
// ---------------------------------------------------------------------------
4152
4153
/** \brief Returns the database context. */
4154
0
const DatabaseContextNNPtr &AuthorityFactory::databaseContext() const {
4155
0
    return d->context();
4156
0
}
4157
4158
// ---------------------------------------------------------------------------
4159
4160
//! @cond Doxygen_Suppress
4161
AuthorityFactory::CRSInfo::CRSInfo()
4162
    : authName{}, code{}, name{}, type{ObjectType::CRS}, deprecated{},
4163
      bbox_valid{}, west_lon_degree{}, south_lat_degree{}, east_lon_degree{},
4164
      north_lat_degree{}, areaName{}, projectionMethodName{},
4165
0
      celestialBodyName{} {}
4166
//! @endcond
4167
4168
// ---------------------------------------------------------------------------
4169
4170
/** \brief Returns an arbitrary object from a code.
4171
 *
4172
 * The returned object will typically be an instance of Datum,
4173
 * CoordinateSystem, ReferenceSystem or CoordinateOperation. If the type of
4174
 * the object is know at compile time, it is recommended to invoke the most
4175
 * precise method instead of this one (for example
4176
 * createCoordinateReferenceSystem(code) instead of createObject(code)
4177
 * if the caller know he is asking for a coordinate reference system).
4178
 *
4179
 * If there are several objects with the same code, a FactoryException is
4180
 * thrown.
4181
 *
4182
 * @param code Object code allocated by authority. (e.g. "4326")
4183
 * @return object.
4184
 * @throw NoSuchAuthorityCodeException
4185
 * @throw FactoryException
4186
 */
4187
4188
util::BaseObjectNNPtr
4189
0
AuthorityFactory::createObject(const std::string &code) const {
4190
4191
0
    auto res = d->runWithCodeParam("SELECT table_name, type FROM object_view "
4192
0
                                   "WHERE auth_name = ? AND code = ?",
4193
0
                                   code);
4194
0
    if (res.empty()) {
4195
0
        throw NoSuchAuthorityCodeException("not found", d->authority(), code);
4196
0
    }
4197
0
    if (res.size() != 1) {
4198
0
        std::string msg(
4199
0
            "More than one object matching specified code. Objects found in ");
4200
0
        bool first = true;
4201
0
        for (const auto &row : res) {
4202
0
            if (!first)
4203
0
                msg += ", ";
4204
0
            msg += row[0];
4205
0
            first = false;
4206
0
        }
4207
0
        throw FactoryException(msg);
4208
0
    }
4209
0
    const auto &first_row = res.front();
4210
0
    const auto &table_name = first_row[0];
4211
0
    const auto &type = first_row[1];
4212
0
    if (table_name == "extent") {
4213
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4214
0
            createExtent(code));
4215
0
    }
4216
0
    if (table_name == "unit_of_measure") {
4217
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4218
0
            createUnitOfMeasure(code));
4219
0
    }
4220
0
    if (table_name == "prime_meridian") {
4221
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4222
0
            createPrimeMeridian(code));
4223
0
    }
4224
0
    if (table_name == "ellipsoid") {
4225
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4226
0
            createEllipsoid(code));
4227
0
    }
4228
0
    if (table_name == "geodetic_datum") {
4229
0
        if (type == "ensemble") {
4230
0
            return util::nn_static_pointer_cast<util::BaseObject>(
4231
0
                createDatumEnsemble(code, table_name));
4232
0
        }
4233
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4234
0
            createGeodeticDatum(code));
4235
0
    }
4236
0
    if (table_name == "vertical_datum") {
4237
0
        if (type == "ensemble") {
4238
0
            return util::nn_static_pointer_cast<util::BaseObject>(
4239
0
                createDatumEnsemble(code, table_name));
4240
0
        }
4241
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4242
0
            createVerticalDatum(code));
4243
0
    }
4244
0
    if (table_name == "geodetic_crs") {
4245
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4246
0
            createGeodeticCRS(code));
4247
0
    }
4248
0
    if (table_name == "vertical_crs") {
4249
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4250
0
            createVerticalCRS(code));
4251
0
    }
4252
0
    if (table_name == "projected_crs") {
4253
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4254
0
            createProjectedCRS(code));
4255
0
    }
4256
0
    if (table_name == "compound_crs") {
4257
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4258
0
            createCompoundCRS(code));
4259
0
    }
4260
0
    if (table_name == "conversion") {
4261
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4262
0
            createConversion(code));
4263
0
    }
4264
0
    if (table_name == "helmert_transformation" ||
4265
0
        table_name == "grid_transformation" ||
4266
0
        table_name == "other_transformation" ||
4267
0
        table_name == "concatenated_operation") {
4268
0
        return util::nn_static_pointer_cast<util::BaseObject>(
4269
0
            createCoordinateOperation(code, false));
4270
0
    }
4271
0
    throw FactoryException("unimplemented factory for " + res.front()[0]);
4272
0
}
4273
4274
// ---------------------------------------------------------------------------
4275
4276
//! @cond Doxygen_Suppress
4277
static FactoryException buildFactoryException(const char *type,
4278
                                              const std::string &authName,
4279
                                              const std::string &code,
4280
0
                                              const std::exception &ex) {
4281
0
    return FactoryException(std::string("cannot build ") + type + " " +
4282
0
                            authName + ":" + code + ": " + ex.what());
4283
0
}
4284
//! @endcond
4285
4286
// ---------------------------------------------------------------------------
4287
4288
/** \brief Returns a metadata::Extent from the specified code.
4289
 *
4290
 * @param code Object code allocated by authority.
4291
 * @return object.
4292
 * @throw NoSuchAuthorityCodeException
4293
 * @throw FactoryException
4294
 */
4295
4296
metadata::ExtentNNPtr
4297
0
AuthorityFactory::createExtent(const std::string &code) const {
4298
0
    const auto cacheKey(d->authority() + code);
4299
0
    {
4300
0
        auto extent = d->context()->d->getExtentFromCache(cacheKey);
4301
0
        if (extent) {
4302
0
            return NN_NO_CHECK(extent);
4303
0
        }
4304
0
    }
4305
0
    auto sql = "SELECT description, south_lat, north_lat, west_lon, east_lon, "
4306
0
               "deprecated FROM extent WHERE auth_name = ? AND code = ?";
4307
0
    auto res = d->runWithCodeParam(sql, code);
4308
0
    if (res.empty()) {
4309
0
        throw NoSuchAuthorityCodeException("extent not found", d->authority(),
4310
0
                                           code);
4311
0
    }
4312
0
    try {
4313
0
        const auto &row = res.front();
4314
0
        const auto &description = row[0];
4315
0
        if (row[1].empty()) {
4316
0
            auto extent = metadata::Extent::create(
4317
0
                util::optional<std::string>(description), {}, {}, {});
4318
0
            d->context()->d->cache(cacheKey, extent);
4319
0
            return extent;
4320
0
        }
4321
0
        double south_lat = c_locale_stod(row[1]);
4322
0
        double north_lat = c_locale_stod(row[2]);
4323
0
        double west_lon = c_locale_stod(row[3]);
4324
0
        double east_lon = c_locale_stod(row[4]);
4325
0
        auto bbox = metadata::GeographicBoundingBox::create(
4326
0
            west_lon, south_lat, east_lon, north_lat);
4327
4328
0
        auto extent = metadata::Extent::create(
4329
0
            util::optional<std::string>(description),
4330
0
            std::vector<metadata::GeographicExtentNNPtr>{bbox},
4331
0
            std::vector<metadata::VerticalExtentNNPtr>(),
4332
0
            std::vector<metadata::TemporalExtentNNPtr>());
4333
0
        d->context()->d->cache(cacheKey, extent);
4334
0
        return extent;
4335
4336
0
    } catch (const std::exception &ex) {
4337
0
        throw buildFactoryException("extent", d->authority(), code, ex);
4338
0
    }
4339
0
}
4340
4341
// ---------------------------------------------------------------------------
4342
4343
/** \brief Returns a common::UnitOfMeasure from the specified code.
4344
 *
4345
 * @param code Object code allocated by authority.
4346
 * @return object.
4347
 * @throw NoSuchAuthorityCodeException
4348
 * @throw FactoryException
4349
 */
4350
4351
UnitOfMeasureNNPtr
4352
0
AuthorityFactory::createUnitOfMeasure(const std::string &code) const {
4353
0
    const auto cacheKey(d->authority() + code);
4354
0
    {
4355
0
        auto uom = d->context()->d->getUOMFromCache(cacheKey);
4356
0
        if (uom) {
4357
0
            return NN_NO_CHECK(uom);
4358
0
        }
4359
0
    }
4360
0
    auto res = d->context()->d->run(
4361
0
        "SELECT name, conv_factor, type, deprecated FROM unit_of_measure WHERE "
4362
0
        "auth_name = ? AND code = ?",
4363
0
        {d->authority(), code}, true);
4364
0
    if (res.empty()) {
4365
0
        throw NoSuchAuthorityCodeException("unit of measure not found",
4366
0
                                           d->authority(), code);
4367
0
    }
4368
0
    try {
4369
0
        const auto &row = res.front();
4370
0
        const auto &name =
4371
0
            (row[0] == "degree (supplier to define representation)")
4372
0
                ? UnitOfMeasure::DEGREE.name()
4373
0
                : row[0];
4374
0
        double conv_factor = (code == "9107" || code == "9108")
4375
0
                                 ? UnitOfMeasure::DEGREE.conversionToSI()
4376
0
                                 : c_locale_stod(row[1]);
4377
0
        constexpr double EPS = 1e-10;
4378
0
        if (std::fabs(conv_factor - UnitOfMeasure::DEGREE.conversionToSI()) <
4379
0
            EPS * UnitOfMeasure::DEGREE.conversionToSI()) {
4380
0
            conv_factor = UnitOfMeasure::DEGREE.conversionToSI();
4381
0
        }
4382
0
        if (std::fabs(conv_factor -
4383
0
                      UnitOfMeasure::ARC_SECOND.conversionToSI()) <
4384
0
            EPS * UnitOfMeasure::ARC_SECOND.conversionToSI()) {
4385
0
            conv_factor = UnitOfMeasure::ARC_SECOND.conversionToSI();
4386
0
        }
4387
0
        const auto &type_str = row[2];
4388
0
        UnitOfMeasure::Type unitType = UnitOfMeasure::Type::UNKNOWN;
4389
0
        if (type_str == "length")
4390
0
            unitType = UnitOfMeasure::Type::LINEAR;
4391
0
        else if (type_str == "angle")
4392
0
            unitType = UnitOfMeasure::Type::ANGULAR;
4393
0
        else if (type_str == "scale")
4394
0
            unitType = UnitOfMeasure::Type::SCALE;
4395
0
        else if (type_str == "time")
4396
0
            unitType = UnitOfMeasure::Type::TIME;
4397
0
        auto uom = util::nn_make_shared<UnitOfMeasure>(
4398
0
            name, conv_factor, unitType, d->authority(), code);
4399
0
        d->context()->d->cache(cacheKey, uom);
4400
0
        return uom;
4401
0
    } catch (const std::exception &ex) {
4402
0
        throw buildFactoryException("unit of measure", d->authority(), code,
4403
0
                                    ex);
4404
0
    }
4405
0
}
4406
4407
// ---------------------------------------------------------------------------
4408
4409
//! @cond Doxygen_Suppress
4410
static double normalizeMeasure(const std::string &uom_code,
4411
                               const std::string &value,
4412
0
                               std::string &normalized_uom_code) {
4413
0
    if (uom_code == "9110") // DDD.MMSSsss.....
4414
0
    {
4415
0
        double normalized_value = c_locale_stod(value);
4416
0
        std::ostringstream buffer;
4417
0
        buffer.imbue(std::locale::classic());
4418
0
        constexpr size_t precision = 12;
4419
0
        buffer << std::fixed << std::setprecision(precision)
4420
0
               << normalized_value;
4421
0
        auto formatted = buffer.str();
4422
0
        size_t dotPos = formatted.find('.');
4423
0
        assert(dotPos + 1 + precision == formatted.size());
4424
0
        auto minutes = formatted.substr(dotPos + 1, 2);
4425
0
        auto seconds = formatted.substr(dotPos + 3);
4426
0
        assert(seconds.size() == precision - 2);
4427
0
        normalized_value =
4428
0
            (normalized_value < 0 ? -1.0 : 1.0) *
4429
0
            (std::floor(std::fabs(normalized_value)) +
4430
0
             c_locale_stod(minutes) / 60. +
4431
0
             (c_locale_stod(seconds) / std::pow(10, seconds.size() - 2)) /
4432
0
                 3600.);
4433
0
        normalized_uom_code = common::UnitOfMeasure::DEGREE.code();
4434
        /* coverity[overflow_sink] */
4435
0
        return normalized_value;
4436
0
    } else {
4437
0
        normalized_uom_code = uom_code;
4438
0
        return c_locale_stod(value);
4439
0
    }
4440
0
}
4441
//! @endcond
4442
4443
// ---------------------------------------------------------------------------
4444
4445
/** \brief Returns a datum::PrimeMeridian from the specified code.
4446
 *
4447
 * @param code Object code allocated by authority.
4448
 * @return object.
4449
 * @throw NoSuchAuthorityCodeException
4450
 * @throw FactoryException
4451
 */
4452
4453
datum::PrimeMeridianNNPtr
4454
0
AuthorityFactory::createPrimeMeridian(const std::string &code) const {
4455
0
    const auto cacheKey(d->authority() + code);
4456
0
    {
4457
0
        auto pm = d->context()->d->getPrimeMeridianFromCache(cacheKey);
4458
0
        if (pm) {
4459
0
            return NN_NO_CHECK(pm);
4460
0
        }
4461
0
    }
4462
0
    auto res = d->runWithCodeParam(
4463
0
        "SELECT name, longitude, uom_auth_name, uom_code, deprecated FROM "
4464
0
        "prime_meridian WHERE "
4465
0
        "auth_name = ? AND code = ?",
4466
0
        code);
4467
0
    if (res.empty()) {
4468
0
        throw NoSuchAuthorityCodeException("prime meridian not found",
4469
0
                                           d->authority(), code);
4470
0
    }
4471
0
    try {
4472
0
        const auto &row = res.front();
4473
0
        const auto &name = row[0];
4474
0
        const auto &longitude = row[1];
4475
0
        const auto &uom_auth_name = row[2];
4476
0
        const auto &uom_code = row[3];
4477
0
        const bool deprecated = row[4] == "1";
4478
4479
0
        std::string normalized_uom_code(uom_code);
4480
0
        const double normalized_value =
4481
0
            normalizeMeasure(uom_code, longitude, normalized_uom_code);
4482
4483
0
        auto uom = d->createUnitOfMeasure(uom_auth_name, normalized_uom_code);
4484
0
        auto props = d->createProperties(code, name, deprecated, {});
4485
0
        auto pm = datum::PrimeMeridian::create(
4486
0
            props, common::Angle(normalized_value, uom));
4487
0
        d->context()->d->cache(cacheKey, pm);
4488
0
        return pm;
4489
0
    } catch (const std::exception &ex) {
4490
0
        throw buildFactoryException("prime meridian", d->authority(), code, ex);
4491
0
    }
4492
0
}
4493
4494
// ---------------------------------------------------------------------------
4495
4496
/** \brief Identify a celestial body from an approximate radius.
4497
 *
4498
 * @param semi_major_axis Approximate semi-major axis.
4499
 * @param tolerance Relative error allowed.
4500
 * @return celestial body name if one single match found.
4501
 * @throw FactoryException
4502
 */
4503
4504
std::string
4505
AuthorityFactory::identifyBodyFromSemiMajorAxis(double semi_major_axis,
4506
0
                                                double tolerance) const {
4507
0
    auto res =
4508
0
        d->run("SELECT name, (ABS(semi_major_axis - ?) / semi_major_axis ) "
4509
0
               "AS rel_error FROM celestial_body WHERE rel_error <= ?",
4510
0
               {semi_major_axis, tolerance});
4511
0
    if (res.empty()) {
4512
0
        throw FactoryException("no match found");
4513
0
    }
4514
0
    if (res.size() > 1) {
4515
0
        for (const auto &row : res) {
4516
0
            if (row[0] != res.front()[0]) {
4517
0
                throw FactoryException("more than one match found");
4518
0
            }
4519
0
        }
4520
0
    }
4521
0
    return res.front()[0];
4522
0
}
4523
4524
// ---------------------------------------------------------------------------
4525
4526
/** \brief Returns a datum::Ellipsoid from the specified code.
4527
 *
4528
 * @param code Object code allocated by authority.
4529
 * @return object.
4530
 * @throw NoSuchAuthorityCodeException
4531
 * @throw FactoryException
4532
 */
4533
4534
datum::EllipsoidNNPtr
4535
0
AuthorityFactory::createEllipsoid(const std::string &code) const {
4536
0
    const auto cacheKey(d->authority() + code);
4537
0
    {
4538
0
        auto ellps = d->context()->d->getEllipsoidFromCache(cacheKey);
4539
0
        if (ellps) {
4540
0
            return NN_NO_CHECK(ellps);
4541
0
        }
4542
0
    }
4543
0
    auto res = d->runWithCodeParam(
4544
0
        "SELECT ellipsoid.name, ellipsoid.semi_major_axis, "
4545
0
        "ellipsoid.uom_auth_name, ellipsoid.uom_code, "
4546
0
        "ellipsoid.inv_flattening, ellipsoid.semi_minor_axis, "
4547
0
        "celestial_body.name AS body_name, ellipsoid.deprecated FROM "
4548
0
        "ellipsoid JOIN celestial_body "
4549
0
        "ON ellipsoid.celestial_body_auth_name = celestial_body.auth_name AND "
4550
0
        "ellipsoid.celestial_body_code = celestial_body.code WHERE "
4551
0
        "ellipsoid.auth_name = ? AND ellipsoid.code = ?",
4552
0
        code);
4553
0
    if (res.empty()) {
4554
0
        throw NoSuchAuthorityCodeException("ellipsoid not found",
4555
0
                                           d->authority(), code);
4556
0
    }
4557
0
    try {
4558
0
        const auto &row = res.front();
4559
0
        const auto &name = row[0];
4560
0
        const auto &semi_major_axis_str = row[1];
4561
0
        double semi_major_axis = c_locale_stod(semi_major_axis_str);
4562
0
        const auto &uom_auth_name = row[2];
4563
0
        const auto &uom_code = row[3];
4564
0
        const auto &inv_flattening_str = row[4];
4565
0
        const auto &semi_minor_axis_str = row[5];
4566
0
        const auto &body = row[6];
4567
0
        const bool deprecated = row[7] == "1";
4568
0
        auto uom = d->createUnitOfMeasure(uom_auth_name, uom_code);
4569
0
        auto props = d->createProperties(code, name, deprecated, {});
4570
0
        if (!inv_flattening_str.empty()) {
4571
0
            auto ellps = datum::Ellipsoid::createFlattenedSphere(
4572
0
                props, common::Length(semi_major_axis, uom),
4573
0
                common::Scale(c_locale_stod(inv_flattening_str)), body);
4574
0
            d->context()->d->cache(cacheKey, ellps);
4575
0
            return ellps;
4576
0
        } else if (semi_major_axis_str == semi_minor_axis_str) {
4577
0
            auto ellps = datum::Ellipsoid::createSphere(
4578
0
                props, common::Length(semi_major_axis, uom), body);
4579
0
            d->context()->d->cache(cacheKey, ellps);
4580
0
            return ellps;
4581
0
        } else {
4582
0
            auto ellps = datum::Ellipsoid::createTwoAxis(
4583
0
                props, common::Length(semi_major_axis, uom),
4584
0
                common::Length(c_locale_stod(semi_minor_axis_str), uom), body);
4585
0
            d->context()->d->cache(cacheKey, ellps);
4586
0
            return ellps;
4587
0
        }
4588
0
    } catch (const std::exception &ex) {
4589
0
        throw buildFactoryException("ellipsoid", d->authority(), code, ex);
4590
0
    }
4591
0
}
4592
4593
// ---------------------------------------------------------------------------
4594
4595
/** \brief Returns a datum::GeodeticReferenceFrame from the specified code.
4596
 *
4597
 * @param code Object code allocated by authority.
4598
 * @return object.
4599
 * @throw NoSuchAuthorityCodeException
4600
 * @throw FactoryException
4601
 */
4602
4603
datum::GeodeticReferenceFrameNNPtr
4604
0
AuthorityFactory::createGeodeticDatum(const std::string &code) const {
4605
4606
0
    datum::GeodeticReferenceFramePtr datum;
4607
0
    datum::DatumEnsemblePtr datumEnsemble;
4608
0
    constexpr bool turnEnsembleAsDatum = true;
4609
0
    createGeodeticDatumOrEnsemble(code, datum, datumEnsemble,
4610
0
                                  turnEnsembleAsDatum);
4611
0
    return NN_NO_CHECK(datum);
4612
0
}
4613
4614
// ---------------------------------------------------------------------------
4615
4616
void AuthorityFactory::createGeodeticDatumOrEnsemble(
4617
    const std::string &code, datum::GeodeticReferenceFramePtr &outDatum,
4618
0
    datum::DatumEnsemblePtr &outDatumEnsemble, bool turnEnsembleAsDatum) const {
4619
0
    const auto cacheKey(d->authority() + code);
4620
0
    {
4621
0
        outDatumEnsemble = d->context()->d->getDatumEnsembleFromCache(cacheKey);
4622
0
        if (outDatumEnsemble) {
4623
0
            if (!turnEnsembleAsDatum)
4624
0
                return;
4625
0
            outDatumEnsemble = nullptr;
4626
0
        }
4627
0
        outDatum = d->context()->d->getGeodeticDatumFromCache(cacheKey);
4628
0
        if (outDatum) {
4629
0
            return;
4630
0
        }
4631
0
    }
4632
0
    auto res = d->runWithCodeParam(
4633
0
        "SELECT name, ellipsoid_auth_name, ellipsoid_code, "
4634
0
        "prime_meridian_auth_name, prime_meridian_code, "
4635
0
        "publication_date, frame_reference_epoch, "
4636
0
        "ensemble_accuracy, anchor, anchor_epoch, deprecated "
4637
0
        "FROM geodetic_datum "
4638
0
        "WHERE "
4639
0
        "auth_name = ? AND code = ?",
4640
0
        code);
4641
0
    if (res.empty()) {
4642
0
        throw NoSuchAuthorityCodeException("geodetic datum not found",
4643
0
                                           d->authority(), code);
4644
0
    }
4645
0
    try {
4646
0
        const auto &row = res.front();
4647
0
        const auto &name = row[0];
4648
0
        const auto &ellipsoid_auth_name = row[1];
4649
0
        const auto &ellipsoid_code = row[2];
4650
0
        const auto &prime_meridian_auth_name = row[3];
4651
</