-
Notifications
You must be signed in to change notification settings - Fork 749
/
factory.cpp
6300 lines (5645 loc) · 248 KB
/
factory.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
*
* Project: PROJ
* Purpose: ISO19111:2019 implementation
* Author: Even Rouault <even dot rouault at spatialys dot com>
*
******************************************************************************
* Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#ifndef FROM_PROJ_CPP
#define FROM_PROJ_CPP
#endif
#include "proj/common.hpp"
#include "proj/coordinateoperation.hpp"
#include "proj/coordinatesystem.hpp"
#include "proj/crs.hpp"
#include "proj/datum.hpp"
#include "proj/io.hpp"
#include "proj/metadata.hpp"
#include "proj/util.hpp"
#include "proj/internal/coordinateoperation_internal.hpp"
#include "proj/internal/internal.hpp"
#include "proj/internal/io_internal.hpp"
#include "proj/internal/lru_cache.hpp"
#include "proj/internal/tracing.hpp"
#include "sqlite3_utils.hpp"
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <limits>
#include <map>
#include <memory>
#include <sstream> // std::ostringstream
#include <string>
#include "proj_constants.h"
// PROJ include order is sensitive
// clang-format off
#include "proj.h"
#include "proj_internal.h"
#include "proj_api.h"
// clang-format on
#include <sqlite3.h>
// Custom SQLite VFS as our database is not supposed to be modified in
// parallel. This is slightly faster
#define ENABLE_CUSTOM_LOCKLESS_VFS
using namespace NS_PROJ::internal;
using namespace NS_PROJ::common;
NS_PROJ_START
namespace io {
//! @cond Doxygen_Suppress
// CRS subtypes
#define GEOG_2D "geographic 2D"
#define GEOG_3D "geographic 3D"
#define GEOCENTRIC "geocentric"
#define PROJECTED "projected"
#define VERTICAL "vertical"
#define COMPOUND "compound"
#define GEOG_2D_SINGLE_QUOTED "'geographic 2D'"
#define GEOG_3D_SINGLE_QUOTED "'geographic 3D'"
#define GEOCENTRIC_SINGLE_QUOTED "'geocentric'"
// ---------------------------------------------------------------------------
struct SQLValues {
enum class Type { STRING, DOUBLE };
// cppcheck-suppress noExplicitConstructor
SQLValues(const std::string &value) : type_(Type::STRING), str_(value) {}
// cppcheck-suppress noExplicitConstructor
SQLValues(double value) : type_(Type::DOUBLE), double_(value) {}
const Type &type() const { return type_; }
// cppcheck-suppress functionStatic
const std::string &stringValue() const { return str_; }
// cppcheck-suppress functionStatic
double doubleValue() const { return double_; }
private:
Type type_;
std::string str_{};
double double_ = 0.0;
};
// ---------------------------------------------------------------------------
using SQLRow = std::vector<std::string>;
using SQLResultSet = std::list<SQLRow>;
using ListOfParams = std::list<SQLValues>;
// ---------------------------------------------------------------------------
struct DatabaseContext::Private {
Private();
~Private();
void open(const std::string &databasePath, PJ_CONTEXT *ctx);
void setHandle(sqlite3 *sqlite_handle);
sqlite3 *handle() const { return sqlite_handle_; }
PJ_CONTEXT *pjCtxt() const { return pjCtxt_; }
void setPjCtxt(PJ_CONTEXT *ctxt) { pjCtxt_ = ctxt; }
SQLResultSet run(const std::string &sql,
const ListOfParams ¶meters = ListOfParams());
std::vector<std::string> getDatabaseStructure();
// cppcheck-suppress functionStatic
const std::string &getPath() const { return databasePath_; }
void attachExtraDatabases(
const std::vector<std::string> &auxiliaryDatabasePaths);
// Mechanism to detect recursion in calls from
// AuthorityFactory::createXXX() -> createFromUserInput() ->
// AuthorityFactory::createXXX()
struct RecursionDetector {
explicit RecursionDetector(const DatabaseContextNNPtr &context)
: dbContext_(context) {
if (dbContext_->getPrivate()->recLevel_ == 2) {
// Throw exception before incrementing, since the destructor
// will not be called
throw FactoryException("Too many recursive calls");
}
++dbContext_->getPrivate()->recLevel_;
}
~RecursionDetector() { --dbContext_->getPrivate()->recLevel_; }
private:
DatabaseContextNNPtr dbContext_;
};
std::map<std::string, std::list<SQLRow>> &getMapCanonicalizeGRFName() {
return mapCanonicalizeGRFName_;
}
// cppcheck-suppress functionStatic
common::UnitOfMeasurePtr getUOMFromCache(const std::string &code);
// cppcheck-suppress functionStatic
void cache(const std::string &code, const common::UnitOfMeasureNNPtr &uom);
// cppcheck-suppress functionStatic
crs::CRSPtr getCRSFromCache(const std::string &code);
// cppcheck-suppress functionStatic
void cache(const std::string &code, const crs::CRSNNPtr &crs);
datum::GeodeticReferenceFramePtr
// cppcheck-suppress functionStatic
getGeodeticDatumFromCache(const std::string &code);
// cppcheck-suppress functionStatic
void cache(const std::string &code,
const datum::GeodeticReferenceFrameNNPtr &datum);
datum::EllipsoidPtr
// cppcheck-suppress functionStatic
getEllipsoidFromCache(const std::string &code);
// cppcheck-suppress functionStatic
void cache(const std::string &code, const datum::EllipsoidNNPtr &ellipsoid);
datum::PrimeMeridianPtr
// cppcheck-suppress functionStatic
getPrimeMeridianFromCache(const std::string &code);
// cppcheck-suppress functionStatic
void cache(const std::string &code, const datum::PrimeMeridianNNPtr &pm);
// cppcheck-suppress functionStatic
cs::CoordinateSystemPtr
getCoordinateSystemFromCache(const std::string &code);
// cppcheck-suppress functionStatic
void cache(const std::string &code, const cs::CoordinateSystemNNPtr &cs);
// cppcheck-suppress functionStatic
metadata::ExtentPtr getExtentFromCache(const std::string &code);
// cppcheck-suppress functionStatic
void cache(const std::string &code, const metadata::ExtentNNPtr &extent);
// cppcheck-suppress functionStatic
bool getCRSToCRSCoordOpFromCache(
const std::string &code,
std::vector<operation::CoordinateOperationNNPtr> &list);
// cppcheck-suppress functionStatic
void cache(const std::string &code,
const std::vector<operation::CoordinateOperationNNPtr> &list);
struct GridInfoCache {
std::string fullFilename{};
std::string packageName{};
std::string url{};
bool found = false;
bool directDownload = false;
bool openLicense = false;
bool gridAvailable = false;
};
// cppcheck-suppress functionStatic
bool getGridInfoFromCache(const std::string &code, GridInfoCache &info);
// cppcheck-suppress functionStatic
void cache(const std::string &code, const GridInfoCache &info);
private:
friend class DatabaseContext;
std::string databasePath_{};
bool close_handle_ = true;
sqlite3 *sqlite_handle_{};
std::map<std::string, sqlite3_stmt *> mapSqlToStatement_{};
PJ_CONTEXT *pjCtxt_ = nullptr;
int recLevel_ = 0;
bool detach_ = false;
std::string lastMetadataValue_{};
std::map<std::string, std::list<SQLRow>> mapCanonicalizeGRFName_{};
using LRUCacheOfObjects = lru11::Cache<std::string, util::BaseObjectPtr>;
static constexpr size_t CACHE_SIZE = 128;
LRUCacheOfObjects cacheUOM_{CACHE_SIZE};
LRUCacheOfObjects cacheCRS_{CACHE_SIZE};
LRUCacheOfObjects cacheEllipsoid_{CACHE_SIZE};
LRUCacheOfObjects cacheGeodeticDatum_{CACHE_SIZE};
LRUCacheOfObjects cachePrimeMeridian_{CACHE_SIZE};
LRUCacheOfObjects cacheCS_{CACHE_SIZE};
LRUCacheOfObjects cacheExtent_{CACHE_SIZE};
lru11::Cache<std::string, std::vector<operation::CoordinateOperationNNPtr>>
cacheCRSToCrsCoordOp_{CACHE_SIZE};
lru11::Cache<std::string, GridInfoCache> cacheGridInfo_{CACHE_SIZE};
std::map<std::string, std::vector<std::string>> cacheAllowedAuthorities_{};
lru11::Cache<std::string, std::list<std::string>> cacheAliasNames_{
CACHE_SIZE};
static void insertIntoCache(LRUCacheOfObjects &cache,
const std::string &code,
const util::BaseObjectPtr &obj);
static void getFromCache(LRUCacheOfObjects &cache, const std::string &code,
util::BaseObjectPtr &obj);
void closeDB() noexcept;
// cppcheck-suppress functionStatic
void registerFunctions();
#ifdef ENABLE_CUSTOM_LOCKLESS_VFS
std::unique_ptr<SQLite3VFS> vfs_{};
#endif
Private(const Private &) = delete;
Private &operator=(const Private &) = delete;
};
// ---------------------------------------------------------------------------
DatabaseContext::Private::Private() = default;
// ---------------------------------------------------------------------------
DatabaseContext::Private::~Private() {
assert(recLevel_ == 0);
closeDB();
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::closeDB() noexcept {
if (detach_) {
// Workaround a bug visible in SQLite 3.8.1 and 3.8.2 that causes
// a crash in TEST(factory, attachExtraDatabases_auxiliary)
// due to possible wrong caching of key info.
// The bug is specific to using a memory file with shared cache as an
// auxiliary DB.
// The efinitive fix was likely in 3.8.8
// https://github.com/mackyle/sqlite/commit/d412d4b8731991ecbd8811874aa463d0821673eb
// But just after 3.8.2,
// https://github.com/mackyle/sqlite/commit/ccf328c4318eacedab9ed08c404bc4f402dcad19
// also seemed to hide the issue.
// Detaching a database hides the issue, not sure if it is by chance...
try {
run("DETACH DATABASE db_0");
} catch (...) {
}
detach_ = false;
}
for (auto &pair : mapSqlToStatement_) {
sqlite3_finalize(pair.second);
}
mapSqlToStatement_.clear();
if (close_handle_ && sqlite_handle_ != nullptr) {
sqlite3_close(sqlite_handle_);
sqlite_handle_ = nullptr;
}
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::insertIntoCache(LRUCacheOfObjects &cache,
const std::string &code,
const util::BaseObjectPtr &obj) {
cache.insert(code, obj);
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::getFromCache(LRUCacheOfObjects &cache,
const std::string &code,
util::BaseObjectPtr &obj) {
cache.tryGet(code, obj);
}
// ---------------------------------------------------------------------------
bool DatabaseContext::Private::getCRSToCRSCoordOpFromCache(
const std::string &code,
std::vector<operation::CoordinateOperationNNPtr> &list) {
return cacheCRSToCrsCoordOp_.tryGet(code, list);
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::cache(
const std::string &code,
const std::vector<operation::CoordinateOperationNNPtr> &list) {
cacheCRSToCrsCoordOp_.insert(code, list);
}
// ---------------------------------------------------------------------------
crs::CRSPtr DatabaseContext::Private::getCRSFromCache(const std::string &code) {
util::BaseObjectPtr obj;
getFromCache(cacheCRS_, code, obj);
return std::static_pointer_cast<crs::CRS>(obj);
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::cache(const std::string &code,
const crs::CRSNNPtr &crs) {
insertIntoCache(cacheCRS_, code, crs.as_nullable());
}
// ---------------------------------------------------------------------------
common::UnitOfMeasurePtr
DatabaseContext::Private::getUOMFromCache(const std::string &code) {
util::BaseObjectPtr obj;
getFromCache(cacheUOM_, code, obj);
return std::static_pointer_cast<common::UnitOfMeasure>(obj);
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::cache(const std::string &code,
const common::UnitOfMeasureNNPtr &uom) {
insertIntoCache(cacheUOM_, code, uom.as_nullable());
}
// ---------------------------------------------------------------------------
datum::GeodeticReferenceFramePtr
DatabaseContext::Private::getGeodeticDatumFromCache(const std::string &code) {
util::BaseObjectPtr obj;
getFromCache(cacheGeodeticDatum_, code, obj);
return std::static_pointer_cast<datum::GeodeticReferenceFrame>(obj);
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::cache(
const std::string &code, const datum::GeodeticReferenceFrameNNPtr &datum) {
insertIntoCache(cacheGeodeticDatum_, code, datum.as_nullable());
}
// ---------------------------------------------------------------------------
datum::EllipsoidPtr
DatabaseContext::Private::getEllipsoidFromCache(const std::string &code) {
util::BaseObjectPtr obj;
getFromCache(cacheEllipsoid_, code, obj);
return std::static_pointer_cast<datum::Ellipsoid>(obj);
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::cache(const std::string &code,
const datum::EllipsoidNNPtr &ellps) {
insertIntoCache(cacheEllipsoid_, code, ellps.as_nullable());
}
// ---------------------------------------------------------------------------
datum::PrimeMeridianPtr
DatabaseContext::Private::getPrimeMeridianFromCache(const std::string &code) {
util::BaseObjectPtr obj;
getFromCache(cachePrimeMeridian_, code, obj);
return std::static_pointer_cast<datum::PrimeMeridian>(obj);
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::cache(const std::string &code,
const datum::PrimeMeridianNNPtr &pm) {
insertIntoCache(cachePrimeMeridian_, code, pm.as_nullable());
}
// ---------------------------------------------------------------------------
cs::CoordinateSystemPtr DatabaseContext::Private::getCoordinateSystemFromCache(
const std::string &code) {
util::BaseObjectPtr obj;
getFromCache(cacheCS_, code, obj);
return std::static_pointer_cast<cs::CoordinateSystem>(obj);
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::cache(const std::string &code,
const cs::CoordinateSystemNNPtr &cs) {
insertIntoCache(cacheCS_, code, cs.as_nullable());
}
// ---------------------------------------------------------------------------
metadata::ExtentPtr
DatabaseContext::Private::getExtentFromCache(const std::string &code) {
util::BaseObjectPtr obj;
getFromCache(cacheExtent_, code, obj);
return std::static_pointer_cast<metadata::Extent>(obj);
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::cache(const std::string &code,
const metadata::ExtentNNPtr &extent) {
insertIntoCache(cacheExtent_, code, extent.as_nullable());
}
// ---------------------------------------------------------------------------
bool DatabaseContext::Private::getGridInfoFromCache(const std::string &code,
GridInfoCache &info) {
return cacheGridInfo_.tryGet(code, info);
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::cache(const std::string &code,
const GridInfoCache &info) {
cacheGridInfo_.insert(code, info);
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::open(const std::string &databasePath,
PJ_CONTEXT *ctx) {
if (!ctx) {
ctx = pj_get_default_ctx();
}
setPjCtxt(ctx);
std::string path(databasePath);
if (path.empty()) {
path.resize(2048);
const bool found =
pj_find_file(pjCtxt(), "proj.db", &path[0], path.size() - 1) != 0;
path.resize(strlen(path.c_str()));
if (!found) {
throw FactoryException("Cannot find proj.db");
}
}
std::string vfsName;
#ifdef ENABLE_CUSTOM_LOCKLESS_VFS
if (ctx->custom_sqlite3_vfs_name.empty()) {
vfs_ = SQLite3VFS::create(false, true, true);
if (vfs_ == nullptr) {
throw FactoryException("Open of " + path + " failed");
}
vfsName = vfs_->name();
} else
#endif
{
vfsName = ctx->custom_sqlite3_vfs_name;
}
if (sqlite3_open_v2(path.c_str(), &sqlite_handle_,
SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX,
vfsName.empty() ? nullptr : vfsName.c_str()) !=
SQLITE_OK ||
!sqlite_handle_) {
throw FactoryException("Open of " + path + " failed");
}
databasePath_ = path;
registerFunctions();
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::setHandle(sqlite3 *sqlite_handle) {
assert(sqlite_handle);
assert(!sqlite_handle_);
sqlite_handle_ = sqlite_handle;
close_handle_ = false;
registerFunctions();
}
// ---------------------------------------------------------------------------
std::vector<std::string> DatabaseContext::Private::getDatabaseStructure() {
const char *sqls[] = {
"SELECT sql FROM sqlite_master WHERE type = 'table'",
"SELECT sql FROM sqlite_master WHERE type = 'view'",
"SELECT sql FROM sqlite_master WHERE type = 'trigger'"};
std::vector<std::string> res;
for (const auto &sql : sqls) {
auto sqlRes = run(sql);
for (const auto &row : sqlRes) {
res.emplace_back(row[0]);
}
}
return res;
}
// ---------------------------------------------------------------------------
void DatabaseContext::Private::attachExtraDatabases(
const std::vector<std::string> &auxiliaryDatabasePaths) {
assert(close_handle_);
assert(sqlite_handle_);
auto tables =
run("SELECT name FROM sqlite_master WHERE type IN ('table', 'view')");
std::map<std::string, std::vector<std::string>> tableStructure;
for (const auto &rowTable : tables) {
auto tableName = rowTable[0];
auto tableInfo = run("PRAGMA table_info(\"" +
replaceAll(tableName, "\"", "\"\"") + "\")");
for (const auto &rowCol : tableInfo) {
const auto &colName = rowCol[1];
tableStructure[tableName].push_back(colName);
}
}
closeDB();
sqlite3_open_v2(":memory:", &sqlite_handle_,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX
#ifdef SQLITE_OPEN_URI
| SQLITE_OPEN_URI
#endif
,
nullptr);
if (!sqlite_handle_) {
throw FactoryException("cannot create in memory database");
}
run("ATTACH DATABASE '" + replaceAll(databasePath_, "'", "''") +
"' AS db_0");
detach_ = true;
int count = 1;
for (const auto &otherDb : auxiliaryDatabasePaths) {
std::string sql = "ATTACH DATABASE '";
sql += replaceAll(otherDb, "'", "''");
sql += "' AS db_";
sql += toString(static_cast<int>(count));
count++;
run(sql);
}
for (const auto &pair : tableStructure) {
std::string sql("CREATE TEMP VIEW ");
sql += pair.first;
sql += " AS ";
for (size_t i = 0; i <= auxiliaryDatabasePaths.size(); ++i) {
std::string selectFromAux("SELECT ");
bool firstCol = true;
for (const auto &colName : pair.second) {
if (!firstCol) {
selectFromAux += ", ";
}
firstCol = false;
selectFromAux += colName;
}
selectFromAux += " FROM db_";
selectFromAux += toString(static_cast<int>(i));
selectFromAux += ".";
selectFromAux += pair.first;
try {
// Check that the request will succeed. In case of 'sparse'
// databases...
run(selectFromAux + " LIMIT 0");
if (i > 0) {
sql += " UNION ALL ";
}
sql += selectFromAux;
} catch (const std::exception &) {
}
}
run(sql);
}
registerFunctions();
}
// ---------------------------------------------------------------------------
static double PROJ_SQLITE_GetValAsDouble(sqlite3_value *val, bool &gotVal) {
switch (sqlite3_value_type(val)) {
case SQLITE_FLOAT:
gotVal = true;
return sqlite3_value_double(val);
case SQLITE_INTEGER:
gotVal = true;
return static_cast<double>(sqlite3_value_int64(val));
default:
gotVal = false;
return 0.0;
}
}
// ---------------------------------------------------------------------------
static void PROJ_SQLITE_pseudo_area_from_swne(sqlite3_context *pContext,
int /* argc */,
sqlite3_value **argv) {
bool b0, b1, b2, b3;
double south_lat = PROJ_SQLITE_GetValAsDouble(argv[0], b0);
double west_lon = PROJ_SQLITE_GetValAsDouble(argv[1], b1);
double north_lat = PROJ_SQLITE_GetValAsDouble(argv[2], b2);
double east_lon = PROJ_SQLITE_GetValAsDouble(argv[3], b3);
if (!b0 || !b1 || !b2 || !b3) {
sqlite3_result_null(pContext);
return;
}
// Deal with area crossing antimeridian
if (east_lon < west_lon) {
east_lon += 360.0;
}
// Integrate cos(lat) between south_lat and north_lat
double pseudo_area = (east_lon - west_lon) *
(std::sin(common::Angle(north_lat).getSIValue()) -
std::sin(common::Angle(south_lat).getSIValue()));
sqlite3_result_double(pContext, pseudo_area);
}
// ---------------------------------------------------------------------------
static void PROJ_SQLITE_intersects_bbox(sqlite3_context *pContext,
int /* argc */, sqlite3_value **argv) {
bool b0, b1, b2, b3, b4, b5, b6, b7;
double south_lat1 = PROJ_SQLITE_GetValAsDouble(argv[0], b0);
double west_lon1 = PROJ_SQLITE_GetValAsDouble(argv[1], b1);
double north_lat1 = PROJ_SQLITE_GetValAsDouble(argv[2], b2);
double east_lon1 = PROJ_SQLITE_GetValAsDouble(argv[3], b3);
double south_lat2 = PROJ_SQLITE_GetValAsDouble(argv[4], b4);
double west_lon2 = PROJ_SQLITE_GetValAsDouble(argv[5], b5);
double north_lat2 = PROJ_SQLITE_GetValAsDouble(argv[6], b6);
double east_lon2 = PROJ_SQLITE_GetValAsDouble(argv[7], b7);
if (!b0 || !b1 || !b2 || !b3 || !b4 || !b5 || !b6 || !b7) {
sqlite3_result_null(pContext);
return;
}
auto bbox1 = metadata::GeographicBoundingBox::create(west_lon1, south_lat1,
east_lon1, north_lat1);
auto bbox2 = metadata::GeographicBoundingBox::create(west_lon2, south_lat2,
east_lon2, north_lat2);
sqlite3_result_int(pContext, bbox1->intersects(bbox2) ? 1 : 0);
}
// ---------------------------------------------------------------------------
#ifndef SQLITE_DETERMINISTIC
#define SQLITE_DETERMINISTIC 0
#endif
void DatabaseContext::Private::registerFunctions() {
sqlite3_create_function(sqlite_handle_, "pseudo_area_from_swne", 4,
SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
PROJ_SQLITE_pseudo_area_from_swne, nullptr,
nullptr);
sqlite3_create_function(sqlite_handle_, "intersects_bbox", 8,
SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
PROJ_SQLITE_intersects_bbox, nullptr, nullptr);
}
// ---------------------------------------------------------------------------
SQLResultSet DatabaseContext::Private::run(const std::string &sql,
const ListOfParams ¶meters) {
sqlite3_stmt *stmt = nullptr;
auto iter = mapSqlToStatement_.find(sql);
if (iter != mapSqlToStatement_.end()) {
stmt = iter->second;
sqlite3_reset(stmt);
} else {
if (sqlite3_prepare_v2(sqlite_handle_, sql.c_str(),
static_cast<int>(sql.size()), &stmt,
nullptr) != SQLITE_OK) {
throw FactoryException("SQLite error on " + sql + ": " +
sqlite3_errmsg(sqlite_handle_));
}
mapSqlToStatement_.insert(
std::pair<std::string, sqlite3_stmt *>(sql, stmt));
}
int nBindField = 1;
for (const auto ¶m : parameters) {
if (param.type() == SQLValues::Type::STRING) {
auto strValue = param.stringValue();
sqlite3_bind_text(stmt, nBindField, strValue.c_str(),
static_cast<int>(strValue.size()),
SQLITE_TRANSIENT);
} else {
assert(param.type() == SQLValues::Type::DOUBLE);
sqlite3_bind_double(stmt, nBindField, param.doubleValue());
}
nBindField++;
}
#ifdef TRACE_DATABASE
size_t nPos = 0;
std::string sqlSubst(sql);
for (const auto ¶m : parameters) {
nPos = sqlSubst.find('?', nPos);
assert(nPos != std::string::npos);
std::string strValue;
if (param.type() == SQLValues::Type::STRING) {
strValue = '\'' + param.stringValue() + '\'';
} else {
strValue = toString(param.doubleValue());
}
sqlSubst =
sqlSubst.substr(0, nPos) + strValue + sqlSubst.substr(nPos + 1);
nPos += strValue.size();
}
logTrace(sqlSubst, "DATABASE");
#endif
SQLResultSet result;
const int column_count = sqlite3_column_count(stmt);
while (true) {
int ret = sqlite3_step(stmt);
if (ret == SQLITE_ROW) {
SQLRow row(column_count);
for (int i = 0; i < column_count; i++) {
const char *txt = reinterpret_cast<const char *>(
sqlite3_column_text(stmt, i));
if (txt) {
row[i] = txt;
}
}
result.emplace_back(std::move(row));
} else if (ret == SQLITE_DONE) {
break;
} else {
throw FactoryException("SQLite error on " + sql + ": " +
sqlite3_errmsg(sqlite_handle_));
}
}
return result;
}
//! @endcond
// ---------------------------------------------------------------------------
//! @cond Doxygen_Suppress
DatabaseContext::~DatabaseContext() = default;
//! @endcond
// ---------------------------------------------------------------------------
DatabaseContext::DatabaseContext() : d(internal::make_unique<Private>()) {}
// ---------------------------------------------------------------------------
/** \brief Instantiate a database context.
*
* This database context should be used only by one thread at a time.
*
* @param databasePath Path and filename of the database. Might be empty
* string for the default rules to locate the default proj.db
* @param auxiliaryDatabasePaths Path and filename of auxiliary databases.
* Might be empty.
* @param ctx Context used for file search.
* @throw FactoryException
*/
DatabaseContextNNPtr
DatabaseContext::create(const std::string &databasePath,
const std::vector<std::string> &auxiliaryDatabasePaths,
PJ_CONTEXT *ctx) {
auto dbCtx = DatabaseContext::nn_make_shared<DatabaseContext>();
dbCtx->getPrivate()->open(databasePath, ctx);
if (!auxiliaryDatabasePaths.empty()) {
dbCtx->getPrivate()->attachExtraDatabases(auxiliaryDatabasePaths);
}
return dbCtx;
}
// ---------------------------------------------------------------------------
/** \brief Return the list of authorities used in the database.
*/
std::set<std::string> DatabaseContext::getAuthorities() const {
auto res = d->run("SELECT auth_name FROM authority_list");
std::set<std::string> list;
for (const auto &row : res) {
list.insert(row[0]);
}
return list;
}
// ---------------------------------------------------------------------------
/** \brief Return the list of SQL commands (CREATE TABLE, CREATE TRIGGER,
* CREATE VIEW) needed to initialize a new database.
*/
std::vector<std::string> DatabaseContext::getDatabaseStructure() const {
return d->getDatabaseStructure();
}
// ---------------------------------------------------------------------------
/** \brief Return the path to the database.
*/
const std::string &DatabaseContext::getPath() const { return d->getPath(); }
// ---------------------------------------------------------------------------
/** \brief Return a metadata item.
*
* Value remains valid while this is alive and to the next call to getMetadata
*/
const char *DatabaseContext::getMetadata(const char *key) const {
auto res =
d->run("SELECT value FROM metadata WHERE key = ?", {std::string(key)});
if (res.empty()) {
return nullptr;
}
d->lastMetadataValue_ = res.front()[0];
return d->lastMetadataValue_.c_str();
}
// ---------------------------------------------------------------------------
//! @cond Doxygen_Suppress
DatabaseContextNNPtr DatabaseContext::create(void *sqlite_handle) {
auto ctxt = DatabaseContext::nn_make_shared<DatabaseContext>();
ctxt->getPrivate()->setHandle(static_cast<sqlite3 *>(sqlite_handle));
return ctxt;
}
// ---------------------------------------------------------------------------
void *DatabaseContext::getSqliteHandle() const {
return getPrivate()->handle();
}
// ---------------------------------------------------------------------------
bool DatabaseContext::lookForGridAlternative(const std::string &officialName,
std::string &projFilename,
std::string &projFormat,
bool &inverse) const {
auto res = d->run(
"SELECT proj_grid_name, proj_grid_format, inverse_direction FROM "
"grid_alternatives WHERE original_grid_name = ?",
{officialName});
if (res.empty()) {
return false;
}
const auto &row = res.front();
projFilename = row[0];
projFormat = row[1];
inverse = row[2] == "1";
return true;
}
// ---------------------------------------------------------------------------
bool DatabaseContext::lookForGridInfo(
const std::string &projFilename, bool considerKnownGridsAsAvailable,
std::string &fullFilename, std::string &packageName, std::string &url,
bool &directDownload, bool &openLicense, bool &gridAvailable) const {
Private::GridInfoCache info;
const std::string key(projFilename +
(considerKnownGridsAsAvailable ? "true" : "false"));
if (d->getGridInfoFromCache(key, info)) {
fullFilename = info.fullFilename;
packageName = info.packageName;
url = info.url;
directDownload = info.directDownload;
openLicense = info.openLicense;
gridAvailable = info.gridAvailable;
return info.found;
}
fullFilename.clear();
packageName.clear();
url.clear();
openLicense = false;
directDownload = false;
if (considerKnownGridsAsAvailable) {
fullFilename = projFilename;
} else {
fullFilename.resize(2048);
if (d->pjCtxt() == nullptr) {
d->setPjCtxt(pj_get_default_ctx());
}
int errno_before = proj_context_errno(d->pjCtxt());
gridAvailable =
pj_find_file(d->pjCtxt(), projFilename.c_str(), &fullFilename[0],
fullFilename.size() - 1) != 0;
proj_context_errno_set(d->pjCtxt(), errno_before);
fullFilename.resize(strlen(fullFilename.c_str()));
}
auto res =
d->run("SELECT "
"grid_packages.package_name, "
"grid_alternatives.url, "
"grid_packages.url AS package_url, "
"grid_alternatives.open_license, "
"grid_packages.open_license AS package_open_license, "
"grid_alternatives.direct_download, "
"grid_packages.direct_download AS package_direct_download "
"FROM grid_alternatives "
"LEFT JOIN grid_packages ON "
"grid_alternatives.package_name = grid_packages.package_name "
"WHERE proj_grid_name = ? OR old_proj_grid_name = ?",
{projFilename, projFilename});
bool ret = !res.empty();
if (ret) {
const auto &row = res.front();
packageName = std::move(row[0]);
url = row[1].empty() ? std::move(row[2]) : std::move(row[1]);
openLicense = (row[3].empty() ? row[4] : row[3]) == "1";
directDownload = (row[5].empty() ? row[6] : row[5]) == "1";
if (considerKnownGridsAsAvailable &&
(!packageName.empty() || (!url.empty() && openLicense))) {
gridAvailable = true;
}
info.fullFilename = fullFilename;
info.packageName = packageName;
info.url = url;
info.directDownload = directDownload;
info.openLicense = openLicense;
}