/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 | | #ifdef EMBED_RESOURCE_FILES |
80 | | #include "embedded_resources.h" |
81 | | #endif |
82 | | |
83 | | // Custom SQLite VFS as our database is not supposed to be modified in |
84 | | // parallel. This is slightly faster |
85 | | #define ENABLE_CUSTOM_LOCKLESS_VFS |
86 | | |
87 | | #if defined(_WIN32) && defined(PROJ_HAS_PTHREADS) |
88 | | #undef PROJ_HAS_PTHREADS |
89 | | #endif |
90 | | |
91 | | /* SQLite3 might use seak()+read() or pread[64]() to read data */ |
92 | | /* The later allows the same SQLite handle to be safely used in forked */ |
93 | | /* children of a parent process, while the former doesn't. */ |
94 | | /* So we use pthread_atfork() to set a flag in forked children, to ask them */ |
95 | | /* to close and reopen their database handle. */ |
96 | | #if defined(PROJ_HAS_PTHREADS) && !defined(SQLITE_USE_PREAD) |
97 | | #include <pthread.h> |
98 | | #define REOPEN_SQLITE_DB_AFTER_FORK |
99 | | #endif |
100 | | |
101 | | using namespace NS_PROJ::internal; |
102 | | using namespace NS_PROJ::common; |
103 | | |
104 | | NS_PROJ_START |
105 | | namespace io { |
106 | | |
107 | | //! @cond Doxygen_Suppress |
108 | | |
109 | | // CRS subtypes |
110 | 82.3k | #define GEOG_2D "geographic 2D" |
111 | 40.6k | #define GEOG_3D "geographic 3D" |
112 | 24.0k | #define GEOCENTRIC "geocentric" |
113 | 379 | #define OTHER "other" |
114 | 167 | #define PROJECTED "projected" |
115 | 48 | #define ENGINEERING "engineering" |
116 | 319 | #define VERTICAL "vertical" |
117 | 46 | #define COMPOUND "compound" |
118 | | |
119 | 0 | #define GEOG_2D_SINGLE_QUOTED "'geographic 2D'" |
120 | 0 | #define GEOG_3D_SINGLE_QUOTED "'geographic 3D'" |
121 | | #define GEOCENTRIC_SINGLE_QUOTED "'geocentric'" |
122 | | |
123 | | // Coordinate system types |
124 | | constexpr const char *CS_TYPE_ELLIPSOIDAL = cs::EllipsoidalCS::WKT2_TYPE; |
125 | | constexpr const char *CS_TYPE_CARTESIAN = cs::CartesianCS::WKT2_TYPE; |
126 | | constexpr const char *CS_TYPE_SPHERICAL = cs::SphericalCS::WKT2_TYPE; |
127 | | constexpr const char *CS_TYPE_VERTICAL = cs::VerticalCS::WKT2_TYPE; |
128 | | constexpr const char *CS_TYPE_ORDINAL = cs::OrdinalCS::WKT2_TYPE; |
129 | | |
130 | | // See data/sql/metadata.sql for the semantics of those constants |
131 | | constexpr int DATABASE_LAYOUT_VERSION_MAJOR = 1; |
132 | | // If the code depends on the new additions, then DATABASE_LAYOUT_VERSION_MINOR |
133 | | // must be incremented. |
134 | | constexpr int DATABASE_LAYOUT_VERSION_MINOR = 5; |
135 | | |
136 | | constexpr size_t N_MAX_PARAMS = 7; |
137 | | |
138 | | #ifdef EMBED_RESOURCE_FILES |
139 | | constexpr const char *EMBEDDED_PROJ_DB = "__embedded_proj_db__"; |
140 | | #endif |
141 | | |
142 | | // --------------------------------------------------------------------------- |
143 | | |
144 | | struct SQLValues { |
145 | | enum class Type { STRING, INT, DOUBLE }; |
146 | | |
147 | | // cppcheck-suppress noExplicitConstructor |
148 | 2.75M | SQLValues(const std::string &value) : type_(Type::STRING), str_(value) {} |
149 | | |
150 | | // cppcheck-suppress noExplicitConstructor |
151 | 0 | SQLValues(int value) : type_(Type::INT), int_(value) {} |
152 | | |
153 | | // cppcheck-suppress noExplicitConstructor |
154 | 107k | SQLValues(double value) : type_(Type::DOUBLE), double_(value) {} |
155 | | |
156 | 3.66M | const Type &type() const { return type_; } |
157 | | |
158 | | // cppcheck-suppress functionStatic |
159 | 3.24M | const std::string &stringValue() const { return str_; } |
160 | | |
161 | | // cppcheck-suppress functionStatic |
162 | 0 | int intValue() const { return int_; } |
163 | | |
164 | | // cppcheck-suppress functionStatic |
165 | 424k | double doubleValue() const { return double_; } |
166 | | |
167 | | private: |
168 | | Type type_; |
169 | | std::string str_{}; |
170 | | int int_ = 0; |
171 | | double double_ = 0.0; |
172 | | }; |
173 | | |
174 | | // --------------------------------------------------------------------------- |
175 | | |
176 | | using SQLRow = std::vector<std::string>; |
177 | | using SQLResultSet = std::list<SQLRow>; |
178 | | using ListOfParams = std::list<SQLValues>; |
179 | | |
180 | | // --------------------------------------------------------------------------- |
181 | | |
182 | 1.67M | static double PROJ_SQLITE_GetValAsDouble(sqlite3_value *val, bool &gotVal) { |
183 | 1.67M | switch (sqlite3_value_type(val)) { |
184 | 1.67M | case SQLITE_FLOAT: |
185 | 1.67M | gotVal = true; |
186 | 1.67M | return sqlite3_value_double(val); |
187 | | |
188 | 0 | case SQLITE_INTEGER: |
189 | 0 | gotVal = true; |
190 | 0 | return static_cast<double>(sqlite3_value_int64(val)); |
191 | | |
192 | 0 | default: |
193 | 0 | gotVal = false; |
194 | 0 | return 0.0; |
195 | 1.67M | } |
196 | 1.67M | } |
197 | | |
198 | | // --------------------------------------------------------------------------- |
199 | | |
200 | | static void PROJ_SQLITE_pseudo_area_from_swne(sqlite3_context *pContext, |
201 | | int /* argc */, |
202 | 32.7k | sqlite3_value **argv) { |
203 | 32.7k | bool b0, b1, b2, b3; |
204 | 32.7k | double south_lat = PROJ_SQLITE_GetValAsDouble(argv[0], b0); |
205 | 32.7k | double west_lon = PROJ_SQLITE_GetValAsDouble(argv[1], b1); |
206 | 32.7k | double north_lat = PROJ_SQLITE_GetValAsDouble(argv[2], b2); |
207 | 32.7k | double east_lon = PROJ_SQLITE_GetValAsDouble(argv[3], b3); |
208 | 32.7k | if (!b0 || !b1 || !b2 || !b3) { |
209 | 0 | sqlite3_result_null(pContext); |
210 | 0 | return; |
211 | 0 | } |
212 | | // Deal with area crossing antimeridian |
213 | 32.7k | if (east_lon < west_lon) { |
214 | 497 | east_lon += 360.0; |
215 | 497 | } |
216 | | // Integrate cos(lat) between south_lat and north_lat |
217 | 32.7k | double pseudo_area = (east_lon - west_lon) * |
218 | 32.7k | (std::sin(common::Angle(north_lat).getSIValue()) - |
219 | 32.7k | std::sin(common::Angle(south_lat).getSIValue())); |
220 | 32.7k | sqlite3_result_double(pContext, pseudo_area); |
221 | 32.7k | } |
222 | | |
223 | | // --------------------------------------------------------------------------- |
224 | | |
225 | | static void PROJ_SQLITE_intersects_bbox(sqlite3_context *pContext, |
226 | 193k | int /* argc */, sqlite3_value **argv) { |
227 | 193k | bool b0, b1, b2, b3, b4, b5, b6, b7; |
228 | 193k | double south_lat1 = PROJ_SQLITE_GetValAsDouble(argv[0], b0); |
229 | 193k | double west_lon1 = PROJ_SQLITE_GetValAsDouble(argv[1], b1); |
230 | 193k | double north_lat1 = PROJ_SQLITE_GetValAsDouble(argv[2], b2); |
231 | 193k | double east_lon1 = PROJ_SQLITE_GetValAsDouble(argv[3], b3); |
232 | 193k | double south_lat2 = PROJ_SQLITE_GetValAsDouble(argv[4], b4); |
233 | 193k | double west_lon2 = PROJ_SQLITE_GetValAsDouble(argv[5], b5); |
234 | 193k | double north_lat2 = PROJ_SQLITE_GetValAsDouble(argv[6], b6); |
235 | 193k | double east_lon2 = PROJ_SQLITE_GetValAsDouble(argv[7], b7); |
236 | 193k | if (!b0 || !b1 || !b2 || !b3 || !b4 || !b5 || !b6 || !b7) { |
237 | 0 | sqlite3_result_null(pContext); |
238 | 0 | return; |
239 | 0 | } |
240 | 193k | auto bbox1 = metadata::GeographicBoundingBox::create(west_lon1, south_lat1, |
241 | 193k | east_lon1, north_lat1); |
242 | 193k | auto bbox2 = metadata::GeographicBoundingBox::create(west_lon2, south_lat2, |
243 | 193k | east_lon2, north_lat2); |
244 | 193k | sqlite3_result_int(pContext, bbox1->intersects(bbox2) ? 1 : 0); |
245 | 193k | } |
246 | | |
247 | | // --------------------------------------------------------------------------- |
248 | | |
249 | | class SQLiteHandle { |
250 | | std::string path_{}; |
251 | | sqlite3 *sqlite_handle_ = nullptr; |
252 | | bool close_handle_ = true; |
253 | | |
254 | | #ifdef REOPEN_SQLITE_DB_AFTER_FORK |
255 | | bool is_valid_ = true; |
256 | | #endif |
257 | | |
258 | | int nLayoutVersionMajor_ = 0; |
259 | | int nLayoutVersionMinor_ = 0; |
260 | | |
261 | | #if defined(ENABLE_CUSTOM_LOCKLESS_VFS) || defined(EMBED_RESOURCE_FILES) |
262 | | std::unique_ptr<SQLite3VFS> vfs_{}; |
263 | | #endif |
264 | | |
265 | | SQLiteHandle(const SQLiteHandle &) = delete; |
266 | | SQLiteHandle &operator=(const SQLiteHandle &) = delete; |
267 | | |
268 | | SQLiteHandle(sqlite3 *sqlite_handle, bool close_handle) |
269 | 8.61k | : sqlite_handle_(sqlite_handle), close_handle_(close_handle) { |
270 | 8.61k | assert(sqlite_handle_); |
271 | 8.61k | } |
272 | | |
273 | | // cppcheck-suppress functionStatic |
274 | | void initialize(); |
275 | | |
276 | | SQLResultSet run(const std::string &sql, |
277 | | const ListOfParams ¶meters = ListOfParams(), |
278 | | bool useMaxFloatPrecision = false); |
279 | | |
280 | | public: |
281 | | ~SQLiteHandle(); |
282 | | |
283 | 8.61k | const std::string &path() const { return path_; } |
284 | | |
285 | 66.3k | sqlite3 *handle() { return sqlite_handle_; } |
286 | | |
287 | | #ifdef REOPEN_SQLITE_DB_AFTER_FORK |
288 | 1.04M | bool isValid() const { return is_valid_; } |
289 | | |
290 | 0 | void invalidate() { is_valid_ = false; } |
291 | | #endif |
292 | | |
293 | | static std::shared_ptr<SQLiteHandle> open(PJ_CONTEXT *ctx, |
294 | | const std::string &path); |
295 | | |
296 | | // might not be shared between thread depending how the handle was opened! |
297 | | static std::shared_ptr<SQLiteHandle> |
298 | | initFromExisting(sqlite3 *sqlite_handle, bool close_handle, |
299 | | int nLayoutVersionMajor, int nLayoutVersionMinor); |
300 | | |
301 | | static std::unique_ptr<SQLiteHandle> |
302 | | initFromExistingUniquePtr(sqlite3 *sqlite_handle, bool close_handle); |
303 | | |
304 | | void checkDatabaseLayout(const std::string &mainDbPath, |
305 | | const std::string &path, |
306 | | const std::string &dbNamePrefix); |
307 | | |
308 | | SQLResultSet run(sqlite3_stmt *stmt, const std::string &sql, |
309 | | const ListOfParams ¶meters = ListOfParams(), |
310 | | bool useMaxFloatPrecision = false); |
311 | | |
312 | 0 | inline int getLayoutVersionMajor() const { return nLayoutVersionMajor_; } |
313 | 0 | inline int getLayoutVersionMinor() const { return nLayoutVersionMinor_; } |
314 | | }; |
315 | | |
316 | | // --------------------------------------------------------------------------- |
317 | | |
318 | 8.61k | SQLiteHandle::~SQLiteHandle() { |
319 | 8.61k | if (close_handle_) { |
320 | 8.61k | sqlite3_close(sqlite_handle_); |
321 | 8.61k | } |
322 | 8.61k | } |
323 | | |
324 | | // --------------------------------------------------------------------------- |
325 | | |
326 | | std::shared_ptr<SQLiteHandle> SQLiteHandle::open(PJ_CONTEXT *ctx, |
327 | 8.61k | const std::string &pathIn) { |
328 | | |
329 | 8.61k | std::string path(pathIn); |
330 | 8.61k | const int sqlite3VersionNumber = sqlite3_libversion_number(); |
331 | | // Minimum version for correct performance: 3.11 |
332 | 8.61k | if (sqlite3VersionNumber < 3 * 1000000 + 11 * 1000) { |
333 | 0 | pj_log(ctx, PJ_LOG_ERROR, |
334 | 0 | "SQLite3 version is %s, whereas at least 3.11 should be used", |
335 | 0 | sqlite3_libversion()); |
336 | 0 | } |
337 | | |
338 | 8.61k | std::string vfsName; |
339 | 8.61k | #if defined(ENABLE_CUSTOM_LOCKLESS_VFS) || defined(EMBED_RESOURCE_FILES) |
340 | 8.61k | std::unique_ptr<SQLite3VFS> vfs; |
341 | 8.61k | #endif |
342 | | |
343 | 8.61k | #ifdef EMBED_RESOURCE_FILES |
344 | 8.61k | if (path == EMBEDDED_PROJ_DB && ctx->custom_sqlite3_vfs_name.empty()) { |
345 | 8.61k | unsigned int proj_db_size = 0; |
346 | 8.61k | const unsigned char *proj_db = pj_get_embedded_proj_db(&proj_db_size); |
347 | | |
348 | 8.61k | vfs = SQLite3VFS::createMem(proj_db, proj_db_size); |
349 | 8.61k | if (vfs == nullptr) { |
350 | 0 | throw FactoryException("Open of " + path + " failed"); |
351 | 0 | } |
352 | | |
353 | 8.61k | std::ostringstream buffer; |
354 | 8.61k | buffer << "file:/proj.db?immutable=1&ptr="; |
355 | 8.61k | buffer << reinterpret_cast<uintptr_t>(proj_db); |
356 | 8.61k | buffer << "&sz="; |
357 | 8.61k | buffer << proj_db_size; |
358 | 8.61k | buffer << "&max="; |
359 | 8.61k | buffer << proj_db_size; |
360 | 8.61k | buffer << "&vfs="; |
361 | 8.61k | buffer << vfs->name(); |
362 | 8.61k | path = buffer.str(); |
363 | 8.61k | } else |
364 | 0 | #endif |
365 | | |
366 | 0 | #ifdef ENABLE_CUSTOM_LOCKLESS_VFS |
367 | 0 | if (ctx->custom_sqlite3_vfs_name.empty()) { |
368 | 0 | vfs = SQLite3VFS::create(false, true, true); |
369 | 0 | if (vfs == nullptr) { |
370 | 0 | throw FactoryException("Open of " + path + " failed"); |
371 | 0 | } |
372 | 0 | vfsName = vfs->name(); |
373 | 0 | } else |
374 | 0 | #endif |
375 | 0 | { |
376 | 0 | vfsName = ctx->custom_sqlite3_vfs_name; |
377 | 0 | } |
378 | 8.61k | sqlite3 *sqlite_handle = nullptr; |
379 | | // SQLITE_OPEN_FULLMUTEX as this will be used from concurrent threads |
380 | 8.61k | if (sqlite3_open_v2( |
381 | 8.61k | path.c_str(), &sqlite_handle, |
382 | 8.61k | SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_URI, |
383 | 8.61k | vfsName.empty() ? nullptr : vfsName.c_str()) != SQLITE_OK || |
384 | 8.61k | !sqlite_handle) { |
385 | 0 | if (sqlite_handle != nullptr) { |
386 | 0 | sqlite3_close(sqlite_handle); |
387 | 0 | } |
388 | 0 | throw FactoryException("Open of " + path + " failed"); |
389 | 0 | } |
390 | 8.61k | auto handle = |
391 | 8.61k | std::shared_ptr<SQLiteHandle>(new SQLiteHandle(sqlite_handle, true)); |
392 | 8.61k | #if defined(ENABLE_CUSTOM_LOCKLESS_VFS) || defined(EMBED_RESOURCE_FILES) |
393 | 8.61k | handle->vfs_ = std::move(vfs); |
394 | 8.61k | #endif |
395 | 8.61k | handle->initialize(); |
396 | 8.61k | handle->path_ = path; |
397 | 8.61k | handle->checkDatabaseLayout(path, path, std::string()); |
398 | 8.61k | return handle; |
399 | 8.61k | } |
400 | | |
401 | | // --------------------------------------------------------------------------- |
402 | | |
403 | | std::shared_ptr<SQLiteHandle> |
404 | | SQLiteHandle::initFromExisting(sqlite3 *sqlite_handle, bool close_handle, |
405 | | int nLayoutVersionMajor, |
406 | 0 | int nLayoutVersionMinor) { |
407 | 0 | auto handle = std::shared_ptr<SQLiteHandle>( |
408 | 0 | new SQLiteHandle(sqlite_handle, close_handle)); |
409 | 0 | handle->nLayoutVersionMajor_ = nLayoutVersionMajor; |
410 | 0 | handle->nLayoutVersionMinor_ = nLayoutVersionMinor; |
411 | 0 | handle->initialize(); |
412 | 0 | return handle; |
413 | 0 | } |
414 | | |
415 | | // --------------------------------------------------------------------------- |
416 | | |
417 | | std::unique_ptr<SQLiteHandle> |
418 | | SQLiteHandle::initFromExistingUniquePtr(sqlite3 *sqlite_handle, |
419 | 0 | bool close_handle) { |
420 | 0 | auto handle = std::unique_ptr<SQLiteHandle>( |
421 | 0 | new SQLiteHandle(sqlite_handle, close_handle)); |
422 | 0 | handle->initialize(); |
423 | 0 | return handle; |
424 | 0 | } |
425 | | |
426 | | // --------------------------------------------------------------------------- |
427 | | |
428 | | SQLResultSet SQLiteHandle::run(sqlite3_stmt *stmt, const std::string &sql, |
429 | | const ListOfParams ¶meters, |
430 | 1.05M | bool useMaxFloatPrecision) { |
431 | 1.05M | int nBindField = 1; |
432 | 3.66M | for (const auto ¶m : parameters) { |
433 | 3.66M | const auto ¶mType = param.type(); |
434 | 3.66M | if (paramType == SQLValues::Type::STRING) { |
435 | 3.24M | const auto &strValue = param.stringValue(); |
436 | 3.24M | sqlite3_bind_text(stmt, nBindField, strValue.c_str(), |
437 | 3.24M | static_cast<int>(strValue.size()), |
438 | 3.24M | SQLITE_TRANSIENT); |
439 | 3.24M | } else if (paramType == SQLValues::Type::INT) { |
440 | 0 | sqlite3_bind_int(stmt, nBindField, param.intValue()); |
441 | 424k | } else { |
442 | 424k | assert(paramType == SQLValues::Type::DOUBLE); |
443 | 424k | sqlite3_bind_double(stmt, nBindField, param.doubleValue()); |
444 | 424k | } |
445 | 3.66M | nBindField++; |
446 | 3.66M | } |
447 | | |
448 | | #ifdef TRACE_DATABASE |
449 | | size_t nPos = 0; |
450 | | std::string sqlSubst(sql); |
451 | | for (const auto ¶m : parameters) { |
452 | | nPos = sqlSubst.find('?', nPos); |
453 | | assert(nPos != std::string::npos); |
454 | | std::string strValue; |
455 | | const auto paramType = param.type(); |
456 | | if (paramType == SQLValues::Type::STRING) { |
457 | | strValue = '\'' + param.stringValue() + '\''; |
458 | | } else if (paramType == SQLValues::Type::INT) { |
459 | | strValue = toString(param.intValue()); |
460 | | } else { |
461 | | strValue = toString(param.doubleValue()); |
462 | | } |
463 | | sqlSubst = |
464 | | sqlSubst.substr(0, nPos) + strValue + sqlSubst.substr(nPos + 1); |
465 | | nPos += strValue.size(); |
466 | | } |
467 | | logTrace(sqlSubst, "DATABASE"); |
468 | | #endif |
469 | | |
470 | 1.05M | SQLResultSet result; |
471 | 1.05M | const int column_count = sqlite3_column_count(stmt); |
472 | 57.6M | while (true) { |
473 | 57.6M | int ret = sqlite3_step(stmt); |
474 | 57.6M | if (ret == SQLITE_ROW) { |
475 | 56.6M | SQLRow row(column_count); |
476 | 400M | for (int i = 0; i < column_count; i++) { |
477 | 344M | if (useMaxFloatPrecision && |
478 | 344M | sqlite3_column_type(stmt, i) == SQLITE_FLOAT) { |
479 | | // sqlite3_column_text() does not use maximum precision |
480 | 13.3k | std::ostringstream buffer; |
481 | 13.3k | buffer.imbue(std::locale::classic()); |
482 | 13.3k | buffer << std::setprecision(18); |
483 | 13.3k | buffer << sqlite3_column_double(stmt, i); |
484 | 13.3k | row[i] = buffer.str(); |
485 | 344M | } else { |
486 | 344M | const char *txt = reinterpret_cast<const char *>( |
487 | 344M | sqlite3_column_text(stmt, i)); |
488 | 344M | if (txt) { |
489 | 342M | row[i] = txt; |
490 | 342M | } |
491 | 344M | } |
492 | 344M | } |
493 | 56.6M | result.emplace_back(std::move(row)); |
494 | 56.6M | } else if (ret == SQLITE_DONE) { |
495 | 1.05M | break; |
496 | 1.05M | } else { |
497 | 0 | throw FactoryException(std::string("SQLite error [ ") |
498 | 0 | .append("code = ") |
499 | 0 | .append(internal::toString(ret)) |
500 | 0 | .append(", msg = ") |
501 | 0 | .append(sqlite3_errmsg(sqlite_handle_)) |
502 | 0 | .append(" ] on ") |
503 | 0 | .append(sql)); |
504 | 0 | } |
505 | 57.6M | } |
506 | 1.05M | return result; |
507 | 1.05M | } |
508 | | |
509 | | // --------------------------------------------------------------------------- |
510 | | |
511 | | SQLResultSet SQLiteHandle::run(const std::string &sql, |
512 | | const ListOfParams ¶meters, |
513 | 8.61k | bool useMaxFloatPrecision) { |
514 | 8.61k | sqlite3_stmt *stmt = nullptr; |
515 | 8.61k | try { |
516 | 8.61k | if (sqlite3_prepare_v2(sqlite_handle_, sql.c_str(), |
517 | 8.61k | static_cast<int>(sql.size()), &stmt, |
518 | 8.61k | nullptr) != SQLITE_OK) { |
519 | 0 | throw FactoryException(std::string("SQLite error [ ") |
520 | 0 | .append(sqlite3_errmsg(sqlite_handle_)) |
521 | 0 | .append(" ] on ") |
522 | 0 | .append(sql)); |
523 | 0 | } |
524 | 8.61k | auto ret = run(stmt, sql, parameters, useMaxFloatPrecision); |
525 | 8.61k | sqlite3_finalize(stmt); |
526 | 8.61k | return ret; |
527 | 8.61k | } catch (const std::exception &) { |
528 | 0 | if (stmt) |
529 | 0 | sqlite3_finalize(stmt); |
530 | 0 | throw; |
531 | 0 | } |
532 | 8.61k | } |
533 | | |
534 | | // --------------------------------------------------------------------------- |
535 | | |
536 | | void SQLiteHandle::checkDatabaseLayout(const std::string &mainDbPath, |
537 | | const std::string &path, |
538 | 8.61k | const std::string &dbNamePrefix) { |
539 | 8.61k | if (!dbNamePrefix.empty() && run("SELECT 1 FROM " + dbNamePrefix + |
540 | 0 | "sqlite_master WHERE name = 'metadata'") |
541 | 0 | .empty()) { |
542 | | // Accept auxiliary databases without metadata table (sparse DBs) |
543 | 0 | return; |
544 | 0 | } |
545 | 8.61k | auto res = run("SELECT key, value FROM " + dbNamePrefix + |
546 | 8.61k | "metadata WHERE key IN " |
547 | 8.61k | "('DATABASE.LAYOUT.VERSION.MAJOR', " |
548 | 8.61k | "'DATABASE.LAYOUT.VERSION.MINOR')"); |
549 | 8.61k | if (res.empty() && !dbNamePrefix.empty()) { |
550 | | // Accept auxiliary databases without layout metadata. |
551 | 0 | return; |
552 | 0 | } |
553 | 8.61k | if (res.size() != 2) { |
554 | 0 | throw FactoryException( |
555 | 0 | path + " lacks DATABASE.LAYOUT.VERSION.MAJOR / " |
556 | 0 | "DATABASE.LAYOUT.VERSION.MINOR " |
557 | 0 | "metadata. It comes from another PROJ installation."); |
558 | 0 | } |
559 | 8.61k | int major = 0; |
560 | 8.61k | int minor = 0; |
561 | 17.2k | for (const auto &row : res) { |
562 | 17.2k | if (row[0] == "DATABASE.LAYOUT.VERSION.MAJOR") { |
563 | 8.61k | major = atoi(row[1].c_str()); |
564 | 8.61k | } else if (row[0] == "DATABASE.LAYOUT.VERSION.MINOR") { |
565 | 8.61k | minor = atoi(row[1].c_str()); |
566 | 8.61k | } |
567 | 17.2k | } |
568 | 8.61k | if (major != DATABASE_LAYOUT_VERSION_MAJOR) { |
569 | 0 | throw FactoryException( |
570 | 0 | path + |
571 | 0 | " contains DATABASE.LAYOUT.VERSION.MAJOR = " + toString(major) + |
572 | 0 | " whereas " + toString(DATABASE_LAYOUT_VERSION_MAJOR) + |
573 | 0 | " is expected. " |
574 | 0 | "It comes from another PROJ installation."); |
575 | 0 | } |
576 | | |
577 | 8.61k | if (minor < DATABASE_LAYOUT_VERSION_MINOR) { |
578 | 0 | throw FactoryException( |
579 | 0 | path + |
580 | 0 | " contains DATABASE.LAYOUT.VERSION.MINOR = " + toString(minor) + |
581 | 0 | " whereas a number >= " + toString(DATABASE_LAYOUT_VERSION_MINOR) + |
582 | 0 | " is expected. " |
583 | 0 | "It comes from another PROJ installation."); |
584 | 0 | } |
585 | | |
586 | 8.61k | if (dbNamePrefix.empty()) { |
587 | 8.61k | nLayoutVersionMajor_ = major; |
588 | 8.61k | nLayoutVersionMinor_ = minor; |
589 | 8.61k | } else if (nLayoutVersionMajor_ != major || nLayoutVersionMinor_ != minor) { |
590 | 0 | throw FactoryException( |
591 | 0 | "Auxiliary database " + path + |
592 | 0 | " contains a DATABASE.LAYOUT.VERSION = " + toString(major) + '.' + |
593 | 0 | toString(minor) + |
594 | 0 | " which is different from the one from the main database " + |
595 | 0 | mainDbPath + " which is " + toString(nLayoutVersionMajor_) + '.' + |
596 | 0 | toString(nLayoutVersionMinor_)); |
597 | 0 | } |
598 | 8.61k | } |
599 | | |
600 | | // --------------------------------------------------------------------------- |
601 | | |
602 | | #ifndef SQLITE_DETERMINISTIC |
603 | | #define SQLITE_DETERMINISTIC 0 |
604 | | #endif |
605 | | |
606 | 8.61k | void SQLiteHandle::initialize() { |
607 | | |
608 | | // There is a bug in sqlite 3.38.0 with some complex queries. |
609 | | // Cf https://github.com/OSGeo/PROJ/issues/3077 |
610 | | // Disabling Bloom-filter pull-down optimization as suggested in |
611 | | // https://sqlite.org/forum/forumpost/7d3a75438c |
612 | 8.61k | const int sqlite3VersionNumber = sqlite3_libversion_number(); |
613 | 8.61k | if (sqlite3VersionNumber == 3 * 1000000 + 38 * 1000) { |
614 | 0 | sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite_handle_, |
615 | 0 | 0x100000); |
616 | 0 | } |
617 | | |
618 | 8.61k | sqlite3_create_function(sqlite_handle_, "pseudo_area_from_swne", 4, |
619 | 8.61k | SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr, |
620 | 8.61k | PROJ_SQLITE_pseudo_area_from_swne, nullptr, |
621 | 8.61k | nullptr); |
622 | | |
623 | 8.61k | sqlite3_create_function(sqlite_handle_, "intersects_bbox", 8, |
624 | 8.61k | SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr, |
625 | 8.61k | PROJ_SQLITE_intersects_bbox, nullptr, nullptr); |
626 | 8.61k | } |
627 | | |
628 | | // --------------------------------------------------------------------------- |
629 | | |
630 | | class SQLiteHandleCache { |
631 | | #ifdef REOPEN_SQLITE_DB_AFTER_FORK |
632 | | bool firstTime_ = true; |
633 | | #endif |
634 | | |
635 | | std::mutex sMutex_{}; |
636 | | |
637 | | // Map dbname to SQLiteHandle |
638 | | lru11::Cache<std::string, std::shared_ptr<SQLiteHandle>> cache_{}; |
639 | | |
640 | | public: |
641 | | static SQLiteHandleCache &get(); |
642 | | |
643 | | std::shared_ptr<SQLiteHandle> getHandle(const std::string &path, |
644 | | PJ_CONTEXT *ctx); |
645 | | |
646 | | void clear(); |
647 | | |
648 | | #ifdef REOPEN_SQLITE_DB_AFTER_FORK |
649 | | void invalidateHandles(); |
650 | | #endif |
651 | | }; |
652 | | |
653 | | // --------------------------------------------------------------------------- |
654 | | |
655 | 18.4k | SQLiteHandleCache &SQLiteHandleCache::get() { |
656 | | // Global cache |
657 | 18.4k | static SQLiteHandleCache gSQLiteHandleCache; |
658 | 18.4k | return gSQLiteHandleCache; |
659 | 18.4k | } |
660 | | |
661 | | // --------------------------------------------------------------------------- |
662 | | |
663 | 9.80k | void SQLiteHandleCache::clear() { |
664 | 9.80k | std::lock_guard<std::mutex> lock(sMutex_); |
665 | 9.80k | cache_.clear(); |
666 | 9.80k | } |
667 | | |
668 | | // --------------------------------------------------------------------------- |
669 | | |
670 | | std::shared_ptr<SQLiteHandle> |
671 | 8.61k | SQLiteHandleCache::getHandle(const std::string &path, PJ_CONTEXT *ctx) { |
672 | 8.61k | std::lock_guard<std::mutex> lock(sMutex_); |
673 | | |
674 | 8.61k | #ifdef REOPEN_SQLITE_DB_AFTER_FORK |
675 | 8.61k | if (firstTime_) { |
676 | 1 | firstTime_ = false; |
677 | 1 | pthread_atfork( |
678 | 1 | []() { |
679 | | // This mutex needs to be acquired by 'invalidateHandles()'. |
680 | | // The forking thread needs to own this mutex during the fork. |
681 | | // Otherwise there's an opporunity for another thread to own |
682 | | // the mutex during the fork, leaving the child process unable |
683 | | // to acquire the mutex in invalidateHandles(). |
684 | 0 | SQLiteHandleCache::get().sMutex_.lock(); |
685 | 0 | }, |
686 | 1 | []() { SQLiteHandleCache::get().sMutex_.unlock(); }, |
687 | 1 | []() { |
688 | 0 | SQLiteHandleCache::get().sMutex_.unlock(); |
689 | 0 | SQLiteHandleCache::get().invalidateHandles(); |
690 | 0 | }); |
691 | 1 | } |
692 | 8.61k | #endif |
693 | | |
694 | 8.61k | std::shared_ptr<SQLiteHandle> handle; |
695 | 8.61k | std::string key = path + ctx->custom_sqlite3_vfs_name; |
696 | 8.61k | if (!cache_.tryGet(key, handle)) { |
697 | 8.61k | handle = SQLiteHandle::open(ctx, path); |
698 | 8.61k | cache_.insert(key, handle); |
699 | 8.61k | } |
700 | 8.61k | return handle; |
701 | 8.61k | } |
702 | | |
703 | | #ifdef REOPEN_SQLITE_DB_AFTER_FORK |
704 | | // --------------------------------------------------------------------------- |
705 | | |
706 | 0 | void SQLiteHandleCache::invalidateHandles() { |
707 | 0 | std::lock_guard<std::mutex> lock(sMutex_); |
708 | 0 | const auto lambda = |
709 | 0 | [](const lru11::KeyValuePair<std::string, std::shared_ptr<SQLiteHandle>> |
710 | 0 | &kvp) { kvp.value->invalidate(); }; |
711 | 0 | cache_.cwalk(lambda); |
712 | 0 | cache_.clear(); |
713 | 0 | } |
714 | | #endif |
715 | | |
716 | | // --------------------------------------------------------------------------- |
717 | | |
718 | | struct DatabaseContext::Private { |
719 | | Private(); |
720 | | ~Private(); |
721 | | |
722 | | void open(const std::string &databasePath, PJ_CONTEXT *ctx); |
723 | | void setHandle(sqlite3 *sqlite_handle); |
724 | | |
725 | | const std::shared_ptr<SQLiteHandle> &handle(); |
726 | | |
727 | 202k | PJ_CONTEXT *pjCtxt() const { return pjCtxt_; } |
728 | 8.61k | void setPjCtxt(PJ_CONTEXT *ctxt) { pjCtxt_ = ctxt; } |
729 | | |
730 | | SQLResultSet run(const std::string &sql, |
731 | | const ListOfParams ¶meters = ListOfParams(), |
732 | | bool useMaxFloatPrecision = false); |
733 | | |
734 | | std::vector<std::string> getDatabaseStructure(); |
735 | | |
736 | | // cppcheck-suppress functionStatic |
737 | 0 | const std::string &getPath() const { return databasePath_; } |
738 | | |
739 | | void attachExtraDatabases( |
740 | | const std::vector<std::string> &auxiliaryDatabasePaths); |
741 | | |
742 | | // Mechanism to detect recursion in calls from |
743 | | // AuthorityFactory::createXXX() -> createFromUserInput() -> |
744 | | // AuthorityFactory::createXXX() |
745 | | struct RecursionDetector { |
746 | | explicit RecursionDetector(const DatabaseContextNNPtr &context) |
747 | 284 | : dbContext_(context) { |
748 | 284 | if (dbContext_->getPrivate()->recLevel_ == 2) { |
749 | | // Throw exception before incrementing, since the destructor |
750 | | // will not be called |
751 | 0 | throw FactoryException("Too many recursive calls"); |
752 | 0 | } |
753 | 284 | ++dbContext_->getPrivate()->recLevel_; |
754 | 284 | } |
755 | | |
756 | 284 | ~RecursionDetector() { --dbContext_->getPrivate()->recLevel_; } |
757 | | |
758 | | private: |
759 | | DatabaseContextNNPtr dbContext_; |
760 | | }; |
761 | | |
762 | 112 | std::map<std::string, std::list<SQLRow>> &getMapCanonicalizeGRFName() { |
763 | 112 | return mapCanonicalizeGRFName_; |
764 | 112 | } |
765 | | |
766 | | // cppcheck-suppress functionStatic |
767 | | common::UnitOfMeasurePtr getUOMFromCache(const std::string &code); |
768 | | // cppcheck-suppress functionStatic |
769 | | void cache(const std::string &code, const common::UnitOfMeasureNNPtr &uom); |
770 | | |
771 | | // cppcheck-suppress functionStatic |
772 | | crs::CRSPtr getCRSFromCache(const std::string &code); |
773 | | // cppcheck-suppress functionStatic |
774 | | void cache(const std::string &code, const crs::CRSNNPtr &crs); |
775 | | |
776 | | datum::GeodeticReferenceFramePtr |
777 | | // cppcheck-suppress functionStatic |
778 | | getGeodeticDatumFromCache(const std::string &code); |
779 | | // cppcheck-suppress functionStatic |
780 | | void cache(const std::string &code, |
781 | | const datum::GeodeticReferenceFrameNNPtr &datum); |
782 | | |
783 | | datum::DatumEnsemblePtr |
784 | | // cppcheck-suppress functionStatic |
785 | | getDatumEnsembleFromCache(const std::string &code); |
786 | | // cppcheck-suppress functionStatic |
787 | | void cache(const std::string &code, |
788 | | const datum::DatumEnsembleNNPtr &datumEnsemble); |
789 | | |
790 | | datum::EllipsoidPtr |
791 | | // cppcheck-suppress functionStatic |
792 | | getEllipsoidFromCache(const std::string &code); |
793 | | // cppcheck-suppress functionStatic |
794 | | void cache(const std::string &code, const datum::EllipsoidNNPtr &ellipsoid); |
795 | | |
796 | | datum::PrimeMeridianPtr |
797 | | // cppcheck-suppress functionStatic |
798 | | getPrimeMeridianFromCache(const std::string &code); |
799 | | // cppcheck-suppress functionStatic |
800 | | void cache(const std::string &code, const datum::PrimeMeridianNNPtr &pm); |
801 | | |
802 | | // cppcheck-suppress functionStatic |
803 | | cs::CoordinateSystemPtr |
804 | | getCoordinateSystemFromCache(const std::string &code); |
805 | | // cppcheck-suppress functionStatic |
806 | | void cache(const std::string &code, const cs::CoordinateSystemNNPtr &cs); |
807 | | |
808 | | // cppcheck-suppress functionStatic |
809 | | metadata::ExtentPtr getExtentFromCache(const std::string &code); |
810 | | // cppcheck-suppress functionStatic |
811 | | void cache(const std::string &code, const metadata::ExtentNNPtr &extent); |
812 | | |
813 | | // cppcheck-suppress functionStatic |
814 | | bool getCRSToCRSCoordOpFromCache( |
815 | | const std::string &code, |
816 | | std::vector<operation::CoordinateOperationNNPtr> &list); |
817 | | // cppcheck-suppress functionStatic |
818 | | void cache(const std::string &code, |
819 | | const std::vector<operation::CoordinateOperationNNPtr> &list); |
820 | | |
821 | | struct GridInfoCache { |
822 | | std::string fullFilename{}; |
823 | | std::string packageName{}; |
824 | | std::string url{}; |
825 | | bool found = false; |
826 | | bool directDownload = false; |
827 | | bool openLicense = false; |
828 | | bool gridAvailable = false; |
829 | | }; |
830 | | |
831 | | // cppcheck-suppress functionStatic |
832 | | bool getGridInfoFromCache(const std::string &code, GridInfoCache &info); |
833 | | // cppcheck-suppress functionStatic |
834 | | void evictGridInfoFromCache(const std::string &code); |
835 | | // cppcheck-suppress functionStatic |
836 | | void cache(const std::string &code, const GridInfoCache &info); |
837 | | |
838 | | struct VersionedAuthName { |
839 | | std::string versionedAuthName{}; |
840 | | std::string authName{}; |
841 | | std::string version{}; |
842 | | int priority = 0; |
843 | | }; |
844 | | const std::vector<VersionedAuthName> &getCacheAuthNameWithVersion(); |
845 | | |
846 | | private: |
847 | | friend class DatabaseContext; |
848 | | |
849 | | // This is a manual implementation of std::enable_shared_from_this<> that |
850 | | // avoids publicly deriving from it. |
851 | | std::weak_ptr<DatabaseContext> self_{}; |
852 | | |
853 | | std::string databasePath_{}; |
854 | | std::vector<std::string> auxiliaryDatabasePaths_{}; |
855 | | std::shared_ptr<SQLiteHandle> sqlite_handle_{}; |
856 | | unsigned int queryCounter_ = 0; |
857 | | std::map<std::string, sqlite3_stmt *> mapSqlToStatement_{}; |
858 | | PJ_CONTEXT *pjCtxt_ = nullptr; |
859 | | int recLevel_ = 0; |
860 | | bool detach_ = false; |
861 | | std::string lastMetadataValue_{}; |
862 | | std::map<std::string, std::list<SQLRow>> mapCanonicalizeGRFName_{}; |
863 | | |
864 | | // Used by startInsertStatementsSession() and related functions |
865 | | std::string memoryDbForInsertPath_{}; |
866 | | std::unique_ptr<SQLiteHandle> memoryDbHandle_{}; |
867 | | |
868 | | using LRUCacheOfObjects = lru11::Cache<std::string, util::BaseObjectPtr>; |
869 | | |
870 | | static constexpr size_t CACHE_SIZE = 128; |
871 | | LRUCacheOfObjects cacheUOM_{CACHE_SIZE}; |
872 | | LRUCacheOfObjects cacheCRS_{CACHE_SIZE}; |
873 | | LRUCacheOfObjects cacheEllipsoid_{CACHE_SIZE}; |
874 | | LRUCacheOfObjects cacheGeodeticDatum_{CACHE_SIZE}; |
875 | | LRUCacheOfObjects cacheDatumEnsemble_{CACHE_SIZE}; |
876 | | LRUCacheOfObjects cachePrimeMeridian_{CACHE_SIZE}; |
877 | | LRUCacheOfObjects cacheCS_{CACHE_SIZE}; |
878 | | LRUCacheOfObjects cacheExtent_{CACHE_SIZE}; |
879 | | lru11::Cache<std::string, std::vector<operation::CoordinateOperationNNPtr>> |
880 | | cacheCRSToCrsCoordOp_{CACHE_SIZE}; |
881 | | lru11::Cache<std::string, GridInfoCache> cacheGridInfo_{CACHE_SIZE}; |
882 | | |
883 | | std::map<std::string, std::vector<std::string>> cacheAllowedAuthorities_{}; |
884 | | |
885 | | lru11::Cache<std::string, std::list<std::string>> cacheAliasNames_{ |
886 | | CACHE_SIZE}; |
887 | | lru11::Cache<std::string, std::string> cacheNames_{CACHE_SIZE}; |
888 | | |
889 | | std::vector<VersionedAuthName> cacheAuthNameWithVersion_{}; |
890 | | |
891 | | static void insertIntoCache(LRUCacheOfObjects &cache, |
892 | | const std::string &code, |
893 | | const util::BaseObjectPtr &obj); |
894 | | |
895 | | static void getFromCache(LRUCacheOfObjects &cache, const std::string &code, |
896 | | util::BaseObjectPtr &obj); |
897 | | |
898 | | void closeDB() noexcept; |
899 | | |
900 | | void clearCaches(); |
901 | | |
902 | | std::string findFreeCode(const std::string &tableName, |
903 | | const std::string &authName, |
904 | | const std::string &codePrototype); |
905 | | |
906 | | void identify(const DatabaseContextNNPtr &dbContext, |
907 | | const cs::CoordinateSystemNNPtr &obj, std::string &authName, |
908 | | std::string &code); |
909 | | void identifyOrInsert(const DatabaseContextNNPtr &dbContext, |
910 | | const cs::CoordinateSystemNNPtr &obj, |
911 | | const std::string &ownerType, |
912 | | const std::string &ownerAuthName, |
913 | | const std::string &ownerCode, std::string &authName, |
914 | | std::string &code, |
915 | | std::vector<std::string> &sqlStatements); |
916 | | |
917 | | void identify(const DatabaseContextNNPtr &dbContext, |
918 | | const common::UnitOfMeasure &obj, std::string &authName, |
919 | | std::string &code); |
920 | | void identifyOrInsert(const DatabaseContextNNPtr &dbContext, |
921 | | const common::UnitOfMeasure &unit, |
922 | | const std::string &ownerAuthName, |
923 | | std::string &authName, std::string &code, |
924 | | std::vector<std::string> &sqlStatements); |
925 | | |
926 | | void appendSql(std::vector<std::string> &sqlStatements, |
927 | | const std::string &sql); |
928 | | |
929 | | void |
930 | | identifyOrInsertUsages(const common::ObjectUsageNNPtr &obj, |
931 | | const std::string &tableName, |
932 | | const std::string &authName, const std::string &code, |
933 | | const std::vector<std::string> &allowedAuthorities, |
934 | | std::vector<std::string> &sqlStatements); |
935 | | |
936 | | std::vector<std::string> |
937 | | getInsertStatementsFor(const datum::PrimeMeridianNNPtr &pm, |
938 | | const std::string &authName, const std::string &code, |
939 | | bool numericCode, |
940 | | const std::vector<std::string> &allowedAuthorities); |
941 | | |
942 | | std::vector<std::string> |
943 | | getInsertStatementsFor(const datum::EllipsoidNNPtr &ellipsoid, |
944 | | const std::string &authName, const std::string &code, |
945 | | bool numericCode, |
946 | | const std::vector<std::string> &allowedAuthorities); |
947 | | |
948 | | std::vector<std::string> |
949 | | getInsertStatementsFor(const datum::GeodeticReferenceFrameNNPtr &datum, |
950 | | const std::string &authName, const std::string &code, |
951 | | bool numericCode, |
952 | | const std::vector<std::string> &allowedAuthorities); |
953 | | |
954 | | std::vector<std::string> |
955 | | getInsertStatementsFor(const datum::DatumEnsembleNNPtr &ensemble, |
956 | | const std::string &authName, const std::string &code, |
957 | | bool numericCode, |
958 | | const std::vector<std::string> &allowedAuthorities); |
959 | | |
960 | | std::vector<std::string> |
961 | | getInsertStatementsFor(const crs::GeodeticCRSNNPtr &crs, |
962 | | const std::string &authName, const std::string &code, |
963 | | bool numericCode, |
964 | | const std::vector<std::string> &allowedAuthorities); |
965 | | |
966 | | std::vector<std::string> |
967 | | getInsertStatementsFor(const crs::ProjectedCRSNNPtr &crs, |
968 | | const std::string &authName, const std::string &code, |
969 | | bool numericCode, |
970 | | const std::vector<std::string> &allowedAuthorities); |
971 | | |
972 | | std::vector<std::string> |
973 | | getInsertStatementsFor(const datum::VerticalReferenceFrameNNPtr &datum, |
974 | | const std::string &authName, const std::string &code, |
975 | | bool numericCode, |
976 | | const std::vector<std::string> &allowedAuthorities); |
977 | | |
978 | | std::vector<std::string> |
979 | | getInsertStatementsFor(const crs::VerticalCRSNNPtr &crs, |
980 | | const std::string &authName, const std::string &code, |
981 | | bool numericCode, |
982 | | const std::vector<std::string> &allowedAuthorities); |
983 | | |
984 | | std::vector<std::string> |
985 | | getInsertStatementsFor(const crs::CompoundCRSNNPtr &crs, |
986 | | const std::string &authName, const std::string &code, |
987 | | bool numericCode, |
988 | | const std::vector<std::string> &allowedAuthorities); |
989 | | |
990 | | Private(const Private &) = delete; |
991 | | Private &operator=(const Private &) = delete; |
992 | | }; |
993 | | |
994 | | // --------------------------------------------------------------------------- |
995 | | |
996 | 8.61k | DatabaseContext::Private::Private() = default; |
997 | | |
998 | | // --------------------------------------------------------------------------- |
999 | | |
1000 | 8.61k | DatabaseContext::Private::~Private() { |
1001 | 8.61k | assert(recLevel_ == 0); |
1002 | | |
1003 | 8.61k | closeDB(); |
1004 | 8.61k | } |
1005 | | |
1006 | | // --------------------------------------------------------------------------- |
1007 | | |
1008 | 8.61k | void DatabaseContext::Private::closeDB() noexcept { |
1009 | | |
1010 | 8.61k | if (detach_) { |
1011 | | // Workaround a bug visible in SQLite 3.8.1 and 3.8.2 that causes |
1012 | | // a crash in TEST(factory, attachExtraDatabases_auxiliary) |
1013 | | // due to possible wrong caching of key info. |
1014 | | // The bug is specific to using a memory file with shared cache as an |
1015 | | // auxiliary DB. |
1016 | | // The fix was likely in 3.8.8 |
1017 | | // https://github.com/mackyle/sqlite/commit/d412d4b8731991ecbd8811874aa463d0821673eb |
1018 | | // But just after 3.8.2, |
1019 | | // https://github.com/mackyle/sqlite/commit/ccf328c4318eacedab9ed08c404bc4f402dcad19 |
1020 | | // also seemed to hide the issue. |
1021 | | // Detaching a database hides the issue, not sure if it is by chance... |
1022 | 0 | try { |
1023 | 0 | run("DETACH DATABASE db_0"); |
1024 | 0 | } catch (...) { |
1025 | 0 | } |
1026 | 0 | detach_ = false; |
1027 | 0 | } |
1028 | | |
1029 | 66.3k | for (auto &pair : mapSqlToStatement_) { |
1030 | 66.3k | sqlite3_finalize(pair.second); |
1031 | 66.3k | } |
1032 | 8.61k | mapSqlToStatement_.clear(); |
1033 | | |
1034 | 8.61k | sqlite_handle_.reset(); |
1035 | 8.61k | } |
1036 | | |
1037 | | // --------------------------------------------------------------------------- |
1038 | | |
1039 | 0 | void DatabaseContext::Private::clearCaches() { |
1040 | |
|
1041 | 0 | cacheUOM_.clear(); |
1042 | 0 | cacheCRS_.clear(); |
1043 | 0 | cacheEllipsoid_.clear(); |
1044 | 0 | cacheGeodeticDatum_.clear(); |
1045 | 0 | cacheDatumEnsemble_.clear(); |
1046 | 0 | cachePrimeMeridian_.clear(); |
1047 | 0 | cacheCS_.clear(); |
1048 | 0 | cacheExtent_.clear(); |
1049 | 0 | cacheCRSToCrsCoordOp_.clear(); |
1050 | 0 | cacheGridInfo_.clear(); |
1051 | 0 | cacheAllowedAuthorities_.clear(); |
1052 | 0 | cacheAliasNames_.clear(); |
1053 | 0 | cacheNames_.clear(); |
1054 | 0 | } |
1055 | | |
1056 | | // --------------------------------------------------------------------------- |
1057 | | |
1058 | 1.04M | const std::shared_ptr<SQLiteHandle> &DatabaseContext::Private::handle() { |
1059 | 1.04M | #ifdef REOPEN_SQLITE_DB_AFTER_FORK |
1060 | 1.04M | if (sqlite_handle_ && !sqlite_handle_->isValid()) { |
1061 | 0 | closeDB(); |
1062 | 0 | open(databasePath_, pjCtxt_); |
1063 | 0 | if (!auxiliaryDatabasePaths_.empty()) { |
1064 | 0 | attachExtraDatabases(auxiliaryDatabasePaths_); |
1065 | 0 | } |
1066 | 0 | } |
1067 | 1.04M | #endif |
1068 | 1.04M | return sqlite_handle_; |
1069 | 1.04M | } |
1070 | | |
1071 | | // --------------------------------------------------------------------------- |
1072 | | |
1073 | | void DatabaseContext::Private::insertIntoCache(LRUCacheOfObjects &cache, |
1074 | | const std::string &code, |
1075 | 104k | const util::BaseObjectPtr &obj) { |
1076 | 104k | cache.insert(code, obj); |
1077 | 104k | } |
1078 | | |
1079 | | // --------------------------------------------------------------------------- |
1080 | | |
1081 | | void DatabaseContext::Private::getFromCache(LRUCacheOfObjects &cache, |
1082 | | const std::string &code, |
1083 | 1.46M | util::BaseObjectPtr &obj) { |
1084 | 1.46M | cache.tryGet(code, obj); |
1085 | 1.46M | } |
1086 | | |
1087 | | // --------------------------------------------------------------------------- |
1088 | | |
1089 | | bool DatabaseContext::Private::getCRSToCRSCoordOpFromCache( |
1090 | | const std::string &code, |
1091 | 135k | std::vector<operation::CoordinateOperationNNPtr> &list) { |
1092 | 135k | return cacheCRSToCrsCoordOp_.tryGet(code, list); |
1093 | 135k | } |
1094 | | |
1095 | | // --------------------------------------------------------------------------- |
1096 | | |
1097 | | void DatabaseContext::Private::cache( |
1098 | | const std::string &code, |
1099 | 34.8k | const std::vector<operation::CoordinateOperationNNPtr> &list) { |
1100 | 34.8k | cacheCRSToCrsCoordOp_.insert(code, list); |
1101 | 34.8k | } |
1102 | | |
1103 | | // --------------------------------------------------------------------------- |
1104 | | |
1105 | 695k | crs::CRSPtr DatabaseContext::Private::getCRSFromCache(const std::string &code) { |
1106 | 695k | util::BaseObjectPtr obj; |
1107 | 695k | getFromCache(cacheCRS_, code, obj); |
1108 | 695k | return std::static_pointer_cast<crs::CRS>(obj); |
1109 | 695k | } |
1110 | | |
1111 | | // --------------------------------------------------------------------------- |
1112 | | |
1113 | | void DatabaseContext::Private::cache(const std::string &code, |
1114 | 36.2k | const crs::CRSNNPtr &crs) { |
1115 | 36.2k | insertIntoCache(cacheCRS_, code, crs.as_nullable()); |
1116 | 36.2k | } |
1117 | | |
1118 | | // --------------------------------------------------------------------------- |
1119 | | |
1120 | | common::UnitOfMeasurePtr |
1121 | 114k | DatabaseContext::Private::getUOMFromCache(const std::string &code) { |
1122 | 114k | util::BaseObjectPtr obj; |
1123 | 114k | getFromCache(cacheUOM_, code, obj); |
1124 | 114k | return std::static_pointer_cast<common::UnitOfMeasure>(obj); |
1125 | 114k | } |
1126 | | |
1127 | | // --------------------------------------------------------------------------- |
1128 | | |
1129 | | void DatabaseContext::Private::cache(const std::string &code, |
1130 | 13.3k | const common::UnitOfMeasureNNPtr &uom) { |
1131 | 13.3k | insertIntoCache(cacheUOM_, code, uom.as_nullable()); |
1132 | 13.3k | } |
1133 | | |
1134 | | // --------------------------------------------------------------------------- |
1135 | | |
1136 | | datum::GeodeticReferenceFramePtr |
1137 | 267k | DatabaseContext::Private::getGeodeticDatumFromCache(const std::string &code) { |
1138 | 267k | util::BaseObjectPtr obj; |
1139 | 267k | getFromCache(cacheGeodeticDatum_, code, obj); |
1140 | 267k | return std::static_pointer_cast<datum::GeodeticReferenceFrame>(obj); |
1141 | 267k | } |
1142 | | |
1143 | | // --------------------------------------------------------------------------- |
1144 | | |
1145 | | void DatabaseContext::Private::cache( |
1146 | 30.7k | const std::string &code, const datum::GeodeticReferenceFrameNNPtr &datum) { |
1147 | 30.7k | insertIntoCache(cacheGeodeticDatum_, code, datum.as_nullable()); |
1148 | 30.7k | } |
1149 | | |
1150 | | // --------------------------------------------------------------------------- |
1151 | | |
1152 | | datum::DatumEnsemblePtr |
1153 | 285k | DatabaseContext::Private::getDatumEnsembleFromCache(const std::string &code) { |
1154 | 285k | util::BaseObjectPtr obj; |
1155 | 285k | getFromCache(cacheDatumEnsemble_, code, obj); |
1156 | 285k | return std::static_pointer_cast<datum::DatumEnsemble>(obj); |
1157 | 285k | } |
1158 | | |
1159 | | // --------------------------------------------------------------------------- |
1160 | | |
1161 | | void DatabaseContext::Private::cache( |
1162 | 2.61k | const std::string &code, const datum::DatumEnsembleNNPtr &datumEnsemble) { |
1163 | 2.61k | insertIntoCache(cacheDatumEnsemble_, code, datumEnsemble.as_nullable()); |
1164 | 2.61k | } |
1165 | | |
1166 | | // --------------------------------------------------------------------------- |
1167 | | |
1168 | | datum::EllipsoidPtr |
1169 | 30.9k | DatabaseContext::Private::getEllipsoidFromCache(const std::string &code) { |
1170 | 30.9k | util::BaseObjectPtr obj; |
1171 | 30.9k | getFromCache(cacheEllipsoid_, code, obj); |
1172 | 30.9k | return std::static_pointer_cast<datum::Ellipsoid>(obj); |
1173 | 30.9k | } |
1174 | | |
1175 | | // --------------------------------------------------------------------------- |
1176 | | |
1177 | | void DatabaseContext::Private::cache(const std::string &code, |
1178 | 5.95k | const datum::EllipsoidNNPtr &ellps) { |
1179 | 5.95k | insertIntoCache(cacheEllipsoid_, code, ellps.as_nullable()); |
1180 | 5.95k | } |
1181 | | |
1182 | | // --------------------------------------------------------------------------- |
1183 | | |
1184 | | datum::PrimeMeridianPtr |
1185 | 30.7k | DatabaseContext::Private::getPrimeMeridianFromCache(const std::string &code) { |
1186 | 30.7k | util::BaseObjectPtr obj; |
1187 | 30.7k | getFromCache(cachePrimeMeridian_, code, obj); |
1188 | 30.7k | return std::static_pointer_cast<datum::PrimeMeridian>(obj); |
1189 | 30.7k | } |
1190 | | |
1191 | | // --------------------------------------------------------------------------- |
1192 | | |
1193 | | void DatabaseContext::Private::cache(const std::string &code, |
1194 | 3.30k | const datum::PrimeMeridianNNPtr &pm) { |
1195 | 3.30k | insertIntoCache(cachePrimeMeridian_, code, pm.as_nullable()); |
1196 | 3.30k | } |
1197 | | |
1198 | | // --------------------------------------------------------------------------- |
1199 | | |
1200 | | cs::CoordinateSystemPtr DatabaseContext::Private::getCoordinateSystemFromCache( |
1201 | 35.9k | const std::string &code) { |
1202 | 35.9k | util::BaseObjectPtr obj; |
1203 | 35.9k | getFromCache(cacheCS_, code, obj); |
1204 | 35.9k | return std::static_pointer_cast<cs::CoordinateSystem>(obj); |
1205 | 35.9k | } |
1206 | | |
1207 | | // --------------------------------------------------------------------------- |
1208 | | |
1209 | | void DatabaseContext::Private::cache(const std::string &code, |
1210 | 12.8k | const cs::CoordinateSystemNNPtr &cs) { |
1211 | 12.8k | insertIntoCache(cacheCS_, code, cs.as_nullable()); |
1212 | 12.8k | } |
1213 | | |
1214 | | // --------------------------------------------------------------------------- |
1215 | | |
1216 | | metadata::ExtentPtr |
1217 | 0 | DatabaseContext::Private::getExtentFromCache(const std::string &code) { |
1218 | 0 | util::BaseObjectPtr obj; |
1219 | 0 | getFromCache(cacheExtent_, code, obj); |
1220 | 0 | return std::static_pointer_cast<metadata::Extent>(obj); |
1221 | 0 | } |
1222 | | |
1223 | | // --------------------------------------------------------------------------- |
1224 | | |
1225 | | void DatabaseContext::Private::cache(const std::string &code, |
1226 | 0 | const metadata::ExtentNNPtr &extent) { |
1227 | 0 | insertIntoCache(cacheExtent_, code, extent.as_nullable()); |
1228 | 0 | } |
1229 | | |
1230 | | // --------------------------------------------------------------------------- |
1231 | | |
1232 | | bool DatabaseContext::Private::getGridInfoFromCache(const std::string &code, |
1233 | 123k | GridInfoCache &info) { |
1234 | 123k | return cacheGridInfo_.tryGet(code, info); |
1235 | 123k | } |
1236 | | |
1237 | | // --------------------------------------------------------------------------- |
1238 | | |
1239 | 0 | void DatabaseContext::Private::evictGridInfoFromCache(const std::string &code) { |
1240 | 0 | cacheGridInfo_.remove(code); |
1241 | 0 | } |
1242 | | |
1243 | | // --------------------------------------------------------------------------- |
1244 | | |
1245 | | void DatabaseContext::Private::cache(const std::string &code, |
1246 | 26.8k | const GridInfoCache &info) { |
1247 | 26.8k | cacheGridInfo_.insert(code, info); |
1248 | 26.8k | } |
1249 | | |
1250 | | // --------------------------------------------------------------------------- |
1251 | | |
1252 | | void DatabaseContext::Private::open(const std::string &databasePath, |
1253 | 8.61k | PJ_CONTEXT *ctx) { |
1254 | 8.61k | if (!ctx) { |
1255 | 0 | ctx = pj_get_default_ctx(); |
1256 | 0 | } |
1257 | | |
1258 | 8.61k | setPjCtxt(ctx); |
1259 | 8.61k | std::string path(databasePath); |
1260 | 8.61k | if (path.empty()) { |
1261 | 8.61k | #ifndef USE_ONLY_EMBEDDED_RESOURCE_FILES |
1262 | 8.61k | path.resize(2048); |
1263 | 8.61k | const bool found = |
1264 | 8.61k | pj_find_file(pjCtxt(), "proj.db", &path[0], path.size() - 1) != 0; |
1265 | 8.61k | path.resize(strlen(path.c_str())); |
1266 | 8.61k | if (!found) |
1267 | 8.61k | #endif |
1268 | 8.61k | { |
1269 | 8.61k | #ifdef EMBED_RESOURCE_FILES |
1270 | 8.61k | path = EMBEDDED_PROJ_DB; |
1271 | | #else |
1272 | | throw FactoryException("Cannot find proj.db"); |
1273 | | #endif |
1274 | 8.61k | } |
1275 | 8.61k | } |
1276 | | |
1277 | 8.61k | sqlite_handle_ = SQLiteHandleCache::get().getHandle(path, ctx); |
1278 | | |
1279 | 8.61k | databasePath_ = sqlite_handle_->path(); |
1280 | 8.61k | } |
1281 | | |
1282 | | // --------------------------------------------------------------------------- |
1283 | | |
1284 | 0 | void DatabaseContext::Private::setHandle(sqlite3 *sqlite_handle) { |
1285 | |
|
1286 | 0 | assert(sqlite_handle); |
1287 | 0 | assert(!sqlite_handle_); |
1288 | 0 | sqlite_handle_ = SQLiteHandle::initFromExisting(sqlite_handle, false, 0, 0); |
1289 | 0 | } |
1290 | | |
1291 | | // --------------------------------------------------------------------------- |
1292 | | |
1293 | 0 | std::vector<std::string> DatabaseContext::Private::getDatabaseStructure() { |
1294 | 0 | const std::string dbNamePrefix(auxiliaryDatabasePaths_.empty() && |
1295 | 0 | memoryDbForInsertPath_.empty() |
1296 | 0 | ? "" |
1297 | 0 | : "db_0."); |
1298 | 0 | const auto sqlBegin("SELECT sql||';' FROM " + dbNamePrefix + |
1299 | 0 | "sqlite_master WHERE type = "); |
1300 | 0 | const char *tableType = "'table' AND name NOT LIKE 'sqlite_stat%'"; |
1301 | 0 | const char *const objectTypes[] = {tableType, "'view'", "'trigger'"}; |
1302 | 0 | std::vector<std::string> res; |
1303 | 0 | for (const auto &objectType : objectTypes) { |
1304 | 0 | const auto sqlRes = run(sqlBegin + objectType); |
1305 | 0 | for (const auto &row : sqlRes) { |
1306 | 0 | res.emplace_back(row[0]); |
1307 | 0 | } |
1308 | 0 | } |
1309 | 0 | if (sqlite_handle_->getLayoutVersionMajor() > 0) { |
1310 | 0 | res.emplace_back( |
1311 | 0 | "INSERT INTO metadata VALUES('DATABASE.LAYOUT.VERSION.MAJOR'," + |
1312 | 0 | toString(sqlite_handle_->getLayoutVersionMajor()) + ");"); |
1313 | 0 | res.emplace_back( |
1314 | 0 | "INSERT INTO metadata VALUES('DATABASE.LAYOUT.VERSION.MINOR'," + |
1315 | 0 | toString(sqlite_handle_->getLayoutVersionMinor()) + ");"); |
1316 | 0 | } |
1317 | 0 | return res; |
1318 | 0 | } |
1319 | | |
1320 | | // --------------------------------------------------------------------------- |
1321 | | |
1322 | | void DatabaseContext::Private::attachExtraDatabases( |
1323 | 0 | const std::vector<std::string> &auxiliaryDatabasePaths) { |
1324 | |
|
1325 | 0 | auto l_handle = handle(); |
1326 | 0 | assert(l_handle); |
1327 | |
|
1328 | 0 | auto tables = run("SELECT name, type, sql FROM sqlite_master WHERE type IN " |
1329 | 0 | "('table', 'view') " |
1330 | 0 | "AND name NOT LIKE 'sqlite_stat%'"); |
1331 | |
|
1332 | 0 | struct TableStructure { |
1333 | 0 | std::string name{}; |
1334 | 0 | bool isTable = false; |
1335 | 0 | std::string sql{}; |
1336 | 0 | std::vector<std::string> columns{}; |
1337 | 0 | }; |
1338 | 0 | std::vector<TableStructure> tablesStructure; |
1339 | 0 | for (const auto &rowTable : tables) { |
1340 | 0 | TableStructure tableStructure; |
1341 | 0 | tableStructure.name = rowTable[0]; |
1342 | 0 | tableStructure.isTable = rowTable[1] == "table"; |
1343 | 0 | tableStructure.sql = rowTable[2]; |
1344 | 0 | auto tableInfo = |
1345 | 0 | run("PRAGMA table_info(\"" + |
1346 | 0 | replaceAll(tableStructure.name, "\"", "\"\"") + "\")"); |
1347 | 0 | for (const auto &rowCol : tableInfo) { |
1348 | 0 | const auto &colName = rowCol[1]; |
1349 | 0 | tableStructure.columns.push_back(colName); |
1350 | 0 | } |
1351 | 0 | tablesStructure.push_back(std::move(tableStructure)); |
1352 | 0 | } |
1353 | |
|
1354 | 0 | const int nLayoutVersionMajor = l_handle->getLayoutVersionMajor(); |
1355 | 0 | const int nLayoutVersionMinor = l_handle->getLayoutVersionMinor(); |
1356 | |
|
1357 | 0 | closeDB(); |
1358 | 0 | if (auxiliaryDatabasePaths.empty()) { |
1359 | 0 | open(databasePath_, pjCtxt()); |
1360 | 0 | return; |
1361 | 0 | } |
1362 | | |
1363 | 0 | sqlite3 *sqlite_handle = nullptr; |
1364 | 0 | sqlite3_open_v2( |
1365 | 0 | ":memory:", &sqlite_handle, |
1366 | 0 | SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_URI, nullptr); |
1367 | 0 | if (!sqlite_handle) { |
1368 | 0 | throw FactoryException("cannot create in memory database"); |
1369 | 0 | } |
1370 | 0 | sqlite_handle_ = SQLiteHandle::initFromExisting( |
1371 | 0 | sqlite_handle, true, nLayoutVersionMajor, nLayoutVersionMinor); |
1372 | 0 | l_handle = sqlite_handle_; |
1373 | |
|
1374 | 0 | run("ATTACH DATABASE ? AS db_0", {databasePath_}); |
1375 | 0 | detach_ = true; |
1376 | 0 | int count = 1; |
1377 | 0 | for (const auto &otherDbPath : auxiliaryDatabasePaths) { |
1378 | 0 | const auto attachedDbName("db_" + toString(static_cast<int>(count))); |
1379 | 0 | std::string sql = "ATTACH DATABASE ? AS "; |
1380 | 0 | sql += attachedDbName; |
1381 | 0 | count++; |
1382 | 0 | run(sql, {otherDbPath}); |
1383 | |
|
1384 | 0 | l_handle->checkDatabaseLayout(databasePath_, otherDbPath, |
1385 | 0 | attachedDbName + '.'); |
1386 | 0 | } |
1387 | |
|
1388 | 0 | for (const auto &tableStructure : tablesStructure) { |
1389 | 0 | if (tableStructure.isTable) { |
1390 | 0 | std::string sql("CREATE TEMP VIEW "); |
1391 | 0 | sql += tableStructure.name; |
1392 | 0 | sql += " AS "; |
1393 | 0 | for (size_t i = 0; i <= auxiliaryDatabasePaths.size(); ++i) { |
1394 | 0 | std::string selectFromAux("SELECT "); |
1395 | 0 | bool firstCol = true; |
1396 | 0 | for (const auto &colName : tableStructure.columns) { |
1397 | 0 | if (!firstCol) { |
1398 | 0 | selectFromAux += ", "; |
1399 | 0 | } |
1400 | 0 | firstCol = false; |
1401 | 0 | selectFromAux += colName; |
1402 | 0 | } |
1403 | 0 | selectFromAux += " FROM db_"; |
1404 | 0 | selectFromAux += toString(static_cast<int>(i)); |
1405 | 0 | selectFromAux += "."; |
1406 | 0 | selectFromAux += tableStructure.name; |
1407 | |
|
1408 | 0 | try { |
1409 | | // Check that the request will succeed. In case of 'sparse' |
1410 | | // databases... |
1411 | 0 | run(selectFromAux + " LIMIT 0"); |
1412 | |
|
1413 | 0 | if (i > 0) { |
1414 | 0 | if (tableStructure.name == "conversion_method") |
1415 | 0 | sql += " UNION "; |
1416 | 0 | else |
1417 | 0 | sql += " UNION ALL "; |
1418 | 0 | } |
1419 | 0 | sql += selectFromAux; |
1420 | 0 | } catch (const std::exception &) { |
1421 | 0 | } |
1422 | 0 | } |
1423 | 0 | run(sql); |
1424 | 0 | } else { |
1425 | 0 | run(replaceAll(tableStructure.sql, "CREATE VIEW", |
1426 | 0 | "CREATE TEMP VIEW")); |
1427 | 0 | } |
1428 | 0 | } |
1429 | 0 | } |
1430 | | |
1431 | | // --------------------------------------------------------------------------- |
1432 | | |
1433 | | SQLResultSet DatabaseContext::Private::run(const std::string &sql, |
1434 | | const ListOfParams ¶meters, |
1435 | 1.04M | bool useMaxFloatPrecision) { |
1436 | | |
1437 | 1.04M | auto l_handle = handle(); |
1438 | 1.04M | assert(l_handle); |
1439 | | |
1440 | 1.04M | sqlite3_stmt *stmt = nullptr; |
1441 | 1.04M | auto iter = mapSqlToStatement_.find(sql); |
1442 | 1.04M | if (iter != mapSqlToStatement_.end()) { |
1443 | 976k | stmt = iter->second; |
1444 | 976k | sqlite3_reset(stmt); |
1445 | 976k | } else { |
1446 | 66.3k | if (sqlite3_prepare_v2(l_handle->handle(), sql.c_str(), |
1447 | 66.3k | static_cast<int>(sql.size()), &stmt, |
1448 | 66.3k | nullptr) != SQLITE_OK) { |
1449 | 0 | throw FactoryException( |
1450 | 0 | std::string("SQLite error [ ") |
1451 | 0 | .append(sqlite3_errmsg(l_handle->handle())) |
1452 | 0 | .append(" ] on ") |
1453 | 0 | .append(sql)); |
1454 | 0 | } |
1455 | 66.3k | mapSqlToStatement_.insert( |
1456 | 66.3k | std::pair<std::string, sqlite3_stmt *>(sql, stmt)); |
1457 | 66.3k | } |
1458 | | |
1459 | 1.04M | ++queryCounter_; |
1460 | | |
1461 | 1.04M | return l_handle->run(stmt, sql, parameters, useMaxFloatPrecision); |
1462 | 1.04M | } |
1463 | | |
1464 | | // --------------------------------------------------------------------------- |
1465 | | |
1466 | 0 | static std::string formatStatement(const char *fmt, ...) { |
1467 | 0 | std::string res; |
1468 | 0 | va_list args; |
1469 | 0 | va_start(args, fmt); |
1470 | 0 | for (int i = 0; fmt[i] != '\0'; ++i) { |
1471 | 0 | if (fmt[i] == '%') { |
1472 | 0 | if (fmt[i + 1] == '%') { |
1473 | 0 | res += '%'; |
1474 | 0 | } else if (fmt[i + 1] == 'q') { |
1475 | 0 | const char *arg = va_arg(args, const char *); |
1476 | 0 | for (int j = 0; arg[j] != '\0'; ++j) { |
1477 | 0 | if (arg[j] == '\'') |
1478 | 0 | res += arg[j]; |
1479 | 0 | res += arg[j]; |
1480 | 0 | } |
1481 | 0 | } else if (fmt[i + 1] == 'Q') { |
1482 | 0 | const char *arg = va_arg(args, const char *); |
1483 | 0 | if (arg == nullptr) |
1484 | 0 | res += "NULL"; |
1485 | 0 | else { |
1486 | 0 | res += '\''; |
1487 | 0 | for (int j = 0; arg[j] != '\0'; ++j) { |
1488 | 0 | if (arg[j] == '\'') |
1489 | 0 | res += arg[j]; |
1490 | 0 | res += arg[j]; |
1491 | 0 | } |
1492 | 0 | res += '\''; |
1493 | 0 | } |
1494 | 0 | } else if (fmt[i + 1] == 's') { |
1495 | 0 | const char *arg = va_arg(args, const char *); |
1496 | 0 | res += arg; |
1497 | 0 | } else if (fmt[i + 1] == 'f') { |
1498 | 0 | const double arg = va_arg(args, double); |
1499 | 0 | res += toString(arg); |
1500 | 0 | } else if (fmt[i + 1] == 'd') { |
1501 | 0 | const int arg = va_arg(args, int); |
1502 | 0 | res += toString(arg); |
1503 | 0 | } else { |
1504 | 0 | va_end(args); |
1505 | 0 | throw FactoryException( |
1506 | 0 | "Unsupported formatter in formatStatement()"); |
1507 | 0 | } |
1508 | 0 | ++i; |
1509 | 0 | } else { |
1510 | 0 | res += fmt[i]; |
1511 | 0 | } |
1512 | 0 | } |
1513 | 0 | va_end(args); |
1514 | 0 | return res; |
1515 | 0 | } |
1516 | | |
1517 | | // --------------------------------------------------------------------------- |
1518 | | |
1519 | | void DatabaseContext::Private::appendSql( |
1520 | 0 | std::vector<std::string> &sqlStatements, const std::string &sql) { |
1521 | 0 | sqlStatements.emplace_back(sql); |
1522 | 0 | char *errMsg = nullptr; |
1523 | 0 | if (sqlite3_exec(memoryDbHandle_->handle(), sql.c_str(), nullptr, nullptr, |
1524 | 0 | &errMsg) != SQLITE_OK) { |
1525 | 0 | std::string s("Cannot execute " + sql); |
1526 | 0 | if (errMsg) { |
1527 | 0 | s += " : "; |
1528 | 0 | s += errMsg; |
1529 | 0 | } |
1530 | 0 | sqlite3_free(errMsg); |
1531 | 0 | throw FactoryException(s); |
1532 | 0 | } |
1533 | 0 | sqlite3_free(errMsg); |
1534 | 0 | } |
1535 | | |
1536 | | // --------------------------------------------------------------------------- |
1537 | | |
1538 | | static void identifyFromNameOrCode( |
1539 | | const DatabaseContextNNPtr &dbContext, |
1540 | | const std::vector<std::string> &allowedAuthorities, |
1541 | | const std::string &authNameParent, const common::IdentifiedObjectNNPtr &obj, |
1542 | | std::function<std::shared_ptr<util::IComparable>( |
1543 | | const AuthorityFactoryNNPtr &authFactory, const std::string &)> |
1544 | | instantiateFunc, |
1545 | | AuthorityFactory::ObjectType objType, std::string &authName, |
1546 | 0 | std::string &code) { |
1547 | |
|
1548 | 0 | auto allowedAuthoritiesTmp(allowedAuthorities); |
1549 | 0 | allowedAuthoritiesTmp.emplace_back(authNameParent); |
1550 | |
|
1551 | 0 | for (const auto &id : obj->identifiers()) { |
1552 | 0 | try { |
1553 | 0 | const auto &idAuthName = *(id->codeSpace()); |
1554 | 0 | if (std::find(allowedAuthoritiesTmp.begin(), |
1555 | 0 | allowedAuthoritiesTmp.end(), |
1556 | 0 | idAuthName) != allowedAuthoritiesTmp.end()) { |
1557 | 0 | const auto factory = |
1558 | 0 | AuthorityFactory::create(dbContext, idAuthName); |
1559 | 0 | if (instantiateFunc(factory, id->code()) |
1560 | 0 | ->isEquivalentTo( |
1561 | 0 | obj.get(), |
1562 | 0 | util::IComparable::Criterion::EQUIVALENT)) { |
1563 | 0 | authName = idAuthName; |
1564 | 0 | code = id->code(); |
1565 | 0 | return; |
1566 | 0 | } |
1567 | 0 | } |
1568 | 0 | } catch (const std::exception &) { |
1569 | 0 | } |
1570 | 0 | } |
1571 | | |
1572 | 0 | for (const auto &allowedAuthority : allowedAuthoritiesTmp) { |
1573 | 0 | const auto factory = |
1574 | 0 | AuthorityFactory::create(dbContext, allowedAuthority); |
1575 | 0 | const auto candidates = |
1576 | 0 | factory->createObjectsFromName(obj->nameStr(), {objType}, false, 0); |
1577 | 0 | for (const auto &candidate : candidates) { |
1578 | 0 | const auto &ids = candidate->identifiers(); |
1579 | 0 | if (!ids.empty() && |
1580 | 0 | candidate->isEquivalentTo( |
1581 | 0 | obj.get(), util::IComparable::Criterion::EQUIVALENT)) { |
1582 | 0 | const auto &id = ids.front(); |
1583 | 0 | authName = *(id->codeSpace()); |
1584 | 0 | code = id->code(); |
1585 | 0 | return; |
1586 | 0 | } |
1587 | 0 | } |
1588 | 0 | } |
1589 | 0 | } |
1590 | | |
1591 | | // --------------------------------------------------------------------------- |
1592 | | |
1593 | | static void |
1594 | | identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, |
1595 | | const std::vector<std::string> &allowedAuthorities, |
1596 | | const std::string &authNameParent, |
1597 | | const datum::DatumEnsembleNNPtr &obj, |
1598 | 0 | std::string &authName, std::string &code) { |
1599 | 0 | const char *type = "geodetic_datum"; |
1600 | 0 | if (!obj->datums().empty() && |
1601 | 0 | dynamic_cast<const datum::VerticalReferenceFrame *>( |
1602 | 0 | obj->datums().front().get())) { |
1603 | 0 | type = "vertical_datum"; |
1604 | 0 | } |
1605 | 0 | const auto instantiateFunc = |
1606 | 0 | [&type](const AuthorityFactoryNNPtr &authFactory, |
1607 | 0 | const std::string &lCode) { |
1608 | 0 | return util::nn_static_pointer_cast<util::IComparable>( |
1609 | 0 | authFactory->createDatumEnsemble(lCode, type)); |
1610 | 0 | }; |
1611 | 0 | identifyFromNameOrCode( |
1612 | 0 | dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc, |
1613 | 0 | AuthorityFactory::ObjectType::DATUM_ENSEMBLE, authName, code); |
1614 | 0 | } |
1615 | | |
1616 | | // --------------------------------------------------------------------------- |
1617 | | |
1618 | | static void |
1619 | | identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, |
1620 | | const std::vector<std::string> &allowedAuthorities, |
1621 | | const std::string &authNameParent, |
1622 | | const datum::GeodeticReferenceFrameNNPtr &obj, |
1623 | 0 | std::string &authName, std::string &code) { |
1624 | 0 | const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory, |
1625 | 0 | const std::string &lCode) { |
1626 | 0 | return util::nn_static_pointer_cast<util::IComparable>( |
1627 | 0 | authFactory->createGeodeticDatum(lCode)); |
1628 | 0 | }; |
1629 | 0 | identifyFromNameOrCode( |
1630 | 0 | dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc, |
1631 | 0 | AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME, authName, code); |
1632 | 0 | } |
1633 | | |
1634 | | // --------------------------------------------------------------------------- |
1635 | | |
1636 | | static void |
1637 | | identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, |
1638 | | const std::vector<std::string> &allowedAuthorities, |
1639 | | const std::string &authNameParent, |
1640 | | const datum::EllipsoidNNPtr &obj, std::string &authName, |
1641 | 0 | std::string &code) { |
1642 | 0 | const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory, |
1643 | 0 | const std::string &lCode) { |
1644 | 0 | return util::nn_static_pointer_cast<util::IComparable>( |
1645 | 0 | authFactory->createEllipsoid(lCode)); |
1646 | 0 | }; |
1647 | 0 | identifyFromNameOrCode( |
1648 | 0 | dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc, |
1649 | 0 | AuthorityFactory::ObjectType::ELLIPSOID, authName, code); |
1650 | 0 | } |
1651 | | |
1652 | | // --------------------------------------------------------------------------- |
1653 | | |
1654 | | static void |
1655 | | identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, |
1656 | | const std::vector<std::string> &allowedAuthorities, |
1657 | | const std::string &authNameParent, |
1658 | | const datum::PrimeMeridianNNPtr &obj, |
1659 | 0 | std::string &authName, std::string &code) { |
1660 | 0 | const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory, |
1661 | 0 | const std::string &lCode) { |
1662 | 0 | return util::nn_static_pointer_cast<util::IComparable>( |
1663 | 0 | authFactory->createPrimeMeridian(lCode)); |
1664 | 0 | }; |
1665 | 0 | identifyFromNameOrCode( |
1666 | 0 | dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc, |
1667 | 0 | AuthorityFactory::ObjectType::PRIME_MERIDIAN, authName, code); |
1668 | 0 | } |
1669 | | |
1670 | | // --------------------------------------------------------------------------- |
1671 | | |
1672 | | static void |
1673 | | identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, |
1674 | | const std::vector<std::string> &allowedAuthorities, |
1675 | | const std::string &authNameParent, |
1676 | | const datum::VerticalReferenceFrameNNPtr &obj, |
1677 | 0 | std::string &authName, std::string &code) { |
1678 | 0 | const auto instantiateFunc = [](const AuthorityFactoryNNPtr &authFactory, |
1679 | 0 | const std::string &lCode) { |
1680 | 0 | return util::nn_static_pointer_cast<util::IComparable>( |
1681 | 0 | authFactory->createVerticalDatum(lCode)); |
1682 | 0 | }; |
1683 | 0 | identifyFromNameOrCode( |
1684 | 0 | dbContext, allowedAuthorities, authNameParent, obj, instantiateFunc, |
1685 | 0 | AuthorityFactory::ObjectType::VERTICAL_REFERENCE_FRAME, authName, code); |
1686 | 0 | } |
1687 | | |
1688 | | // --------------------------------------------------------------------------- |
1689 | | |
1690 | | static void |
1691 | | identifyFromNameOrCode(const DatabaseContextNNPtr &dbContext, |
1692 | | const std::vector<std::string> &allowedAuthorities, |
1693 | | const std::string &authNameParent, |
1694 | | const datum::DatumNNPtr &obj, std::string &authName, |
1695 | 0 | std::string &code) { |
1696 | 0 | if (const auto geodeticDatum = |
1697 | 0 | util::nn_dynamic_pointer_cast<datum::GeodeticReferenceFrame>(obj)) { |
1698 | 0 | identifyFromNameOrCode(dbContext, allowedAuthorities, authNameParent, |
1699 | 0 | NN_NO_CHECK(geodeticDatum), authName, code); |
1700 | 0 | } else if (const auto verticalDatum = |
1701 | 0 | util::nn_dynamic_pointer_cast<datum::VerticalReferenceFrame>( |
1702 | 0 | obj)) { |
1703 | 0 | identifyFromNameOrCode(dbContext, allowedAuthorities, authNameParent, |
1704 | 0 | NN_NO_CHECK(verticalDatum), authName, code); |
1705 | 0 | } else { |
1706 | 0 | throw FactoryException("Unhandled type of datum"); |
1707 | 0 | } |
1708 | 0 | } |
1709 | | |
1710 | | // --------------------------------------------------------------------------- |
1711 | | |
1712 | 0 | static const char *getCSDatabaseType(const cs::CoordinateSystemNNPtr &obj) { |
1713 | 0 | if (dynamic_cast<const cs::EllipsoidalCS *>(obj.get())) { |
1714 | 0 | return CS_TYPE_ELLIPSOIDAL; |
1715 | 0 | } else if (dynamic_cast<const cs::CartesianCS *>(obj.get())) { |
1716 | 0 | return CS_TYPE_CARTESIAN; |
1717 | 0 | } else if (dynamic_cast<const cs::VerticalCS *>(obj.get())) { |
1718 | 0 | return CS_TYPE_VERTICAL; |
1719 | 0 | } |
1720 | 0 | return nullptr; |
1721 | 0 | } |
1722 | | |
1723 | | // --------------------------------------------------------------------------- |
1724 | | |
1725 | | std::string |
1726 | | DatabaseContext::Private::findFreeCode(const std::string &tableName, |
1727 | | const std::string &authName, |
1728 | 0 | const std::string &codePrototype) { |
1729 | 0 | std::string code(codePrototype); |
1730 | 0 | if (run("SELECT 1 FROM " + tableName + " WHERE auth_name = ? AND code = ?", |
1731 | 0 | {authName, code}) |
1732 | 0 | .empty()) { |
1733 | 0 | return code; |
1734 | 0 | } |
1735 | | |
1736 | 0 | for (int counter = 2; counter < 10; counter++) { |
1737 | 0 | code = codePrototype + '_' + toString(counter); |
1738 | 0 | if (run("SELECT 1 FROM " + tableName + |
1739 | 0 | " WHERE auth_name = ? AND code = ?", |
1740 | 0 | {authName, code}) |
1741 | 0 | .empty()) { |
1742 | 0 | return code; |
1743 | 0 | } |
1744 | 0 | } |
1745 | | |
1746 | | // shouldn't happen hopefully... |
1747 | 0 | throw FactoryException("Cannot insert " + tableName + |
1748 | 0 | ": too many similar codes"); |
1749 | 0 | } |
1750 | | |
1751 | | // --------------------------------------------------------------------------- |
1752 | | |
1753 | 0 | static const char *getUnitDatabaseType(const common::UnitOfMeasure &unit) { |
1754 | 0 | switch (unit.type()) { |
1755 | 0 | case common::UnitOfMeasure::Type::LINEAR: |
1756 | 0 | return "length"; |
1757 | | |
1758 | 0 | case common::UnitOfMeasure::Type::ANGULAR: |
1759 | 0 | return "angle"; |
1760 | | |
1761 | 0 | case common::UnitOfMeasure::Type::SCALE: |
1762 | 0 | return "scale"; |
1763 | | |
1764 | 0 | case common::UnitOfMeasure::Type::TIME: |
1765 | 0 | return "time"; |
1766 | | |
1767 | 0 | default: |
1768 | 0 | break; |
1769 | 0 | } |
1770 | 0 | return nullptr; |
1771 | 0 | } |
1772 | | |
1773 | | // --------------------------------------------------------------------------- |
1774 | | |
1775 | | void DatabaseContext::Private::identify(const DatabaseContextNNPtr &dbContext, |
1776 | | const common::UnitOfMeasure &obj, |
1777 | | std::string &authName, |
1778 | 0 | std::string &code) { |
1779 | | // Identify quickly a few well-known units |
1780 | 0 | const double convFactor = obj.conversionToSI(); |
1781 | 0 | switch (obj.type()) { |
1782 | 0 | case common::UnitOfMeasure::Type::LINEAR: { |
1783 | 0 | if (convFactor == 1.0) { |
1784 | 0 | authName = metadata::Identifier::EPSG; |
1785 | 0 | code = "9001"; |
1786 | 0 | return; |
1787 | 0 | } |
1788 | 0 | break; |
1789 | 0 | } |
1790 | 0 | case common::UnitOfMeasure::Type::ANGULAR: { |
1791 | 0 | constexpr double CONV_FACTOR_DEGREE = 1.74532925199432781271e-02; |
1792 | 0 | if (std::abs(convFactor - CONV_FACTOR_DEGREE) <= |
1793 | 0 | 1e-10 * CONV_FACTOR_DEGREE) { |
1794 | 0 | authName = metadata::Identifier::EPSG; |
1795 | 0 | code = "9102"; |
1796 | 0 | return; |
1797 | 0 | } |
1798 | 0 | break; |
1799 | 0 | } |
1800 | 0 | case common::UnitOfMeasure::Type::SCALE: { |
1801 | 0 | if (convFactor == 1.0) { |
1802 | 0 | authName = metadata::Identifier::EPSG; |
1803 | 0 | code = "9201"; |
1804 | 0 | return; |
1805 | 0 | } |
1806 | 0 | break; |
1807 | 0 | } |
1808 | 0 | default: |
1809 | 0 | break; |
1810 | 0 | } |
1811 | | |
1812 | 0 | std::string sql("SELECT auth_name, code FROM unit_of_measure " |
1813 | 0 | "WHERE abs(conv_factor - ?) <= 1e-10 * conv_factor"); |
1814 | 0 | ListOfParams params{convFactor}; |
1815 | 0 | const char *type = getUnitDatabaseType(obj); |
1816 | 0 | if (type) { |
1817 | 0 | sql += " AND type = ?"; |
1818 | 0 | params.emplace_back(std::string(type)); |
1819 | 0 | } |
1820 | 0 | sql += " ORDER BY auth_name, code"; |
1821 | 0 | const auto res = run(sql, params); |
1822 | 0 | for (const auto &row : res) { |
1823 | 0 | const auto &rowAuthName = row[0]; |
1824 | 0 | const auto &rowCode = row[1]; |
1825 | 0 | const auto tmpAuthFactory = |
1826 | 0 | AuthorityFactory::create(dbContext, rowAuthName); |
1827 | 0 | try { |
1828 | 0 | tmpAuthFactory->createUnitOfMeasure(rowCode); |
1829 | 0 | authName = rowAuthName; |
1830 | 0 | code = rowCode; |
1831 | 0 | return; |
1832 | 0 | } catch (const std::exception &) { |
1833 | 0 | } |
1834 | 0 | } |
1835 | 0 | } |
1836 | | |
1837 | | // --------------------------------------------------------------------------- |
1838 | | |
1839 | | void DatabaseContext::Private::identifyOrInsert( |
1840 | | const DatabaseContextNNPtr &dbContext, const common::UnitOfMeasure &unit, |
1841 | | const std::string &ownerAuthName, std::string &authName, std::string &code, |
1842 | 0 | std::vector<std::string> &sqlStatements) { |
1843 | 0 | authName = unit.codeSpace(); |
1844 | 0 | code = unit.code(); |
1845 | 0 | if (authName.empty()) { |
1846 | 0 | identify(dbContext, unit, authName, code); |
1847 | 0 | } |
1848 | 0 | if (!authName.empty()) { |
1849 | 0 | return; |
1850 | 0 | } |
1851 | 0 | const char *type = getUnitDatabaseType(unit); |
1852 | 0 | if (type == nullptr) { |
1853 | 0 | throw FactoryException("Cannot insert this type of UnitOfMeasure"); |
1854 | 0 | } |
1855 | | |
1856 | | // Insert new record |
1857 | 0 | authName = ownerAuthName; |
1858 | 0 | const std::string codePrototype(replaceAll(toupper(unit.name()), " ", "_")); |
1859 | 0 | code = findFreeCode("unit_of_measure", authName, codePrototype); |
1860 | |
|
1861 | 0 | const auto sql = formatStatement( |
1862 | 0 | "INSERT INTO unit_of_measure VALUES('%q','%q','%q','%q',%f,NULL,0);", |
1863 | 0 | authName.c_str(), code.c_str(), unit.name().c_str(), type, |
1864 | 0 | unit.conversionToSI()); |
1865 | 0 | appendSql(sqlStatements, sql); |
1866 | 0 | } |
1867 | | |
1868 | | // --------------------------------------------------------------------------- |
1869 | | |
1870 | | void DatabaseContext::Private::identify(const DatabaseContextNNPtr &dbContext, |
1871 | | const cs::CoordinateSystemNNPtr &obj, |
1872 | | std::string &authName, |
1873 | 0 | std::string &code) { |
1874 | |
|
1875 | 0 | const auto &axisList = obj->axisList(); |
1876 | 0 | if (axisList.size() == 1U && |
1877 | 0 | axisList[0]->unit()._isEquivalentTo(UnitOfMeasure::METRE) && |
1878 | 0 | &(axisList[0]->direction()) == &cs::AxisDirection::UP && |
1879 | 0 | (axisList[0]->nameStr() == "Up" || |
1880 | 0 | axisList[0]->nameStr() == "Gravity-related height")) { |
1881 | | // preferred coordinate system for gravity-related height |
1882 | 0 | authName = metadata::Identifier::EPSG; |
1883 | 0 | code = "6499"; |
1884 | 0 | return; |
1885 | 0 | } |
1886 | | |
1887 | 0 | std::string sql( |
1888 | 0 | "SELECT auth_name, code FROM coordinate_system WHERE dimension = ?"); |
1889 | 0 | ListOfParams params{static_cast<int>(axisList.size())}; |
1890 | 0 | const char *type = getCSDatabaseType(obj); |
1891 | 0 | if (type) { |
1892 | 0 | sql += " AND type = ?"; |
1893 | 0 | params.emplace_back(std::string(type)); |
1894 | 0 | } |
1895 | 0 | sql += " ORDER BY auth_name, code"; |
1896 | 0 | const auto res = run(sql, params); |
1897 | 0 | for (const auto &row : res) { |
1898 | 0 | const auto &rowAuthName = row[0]; |
1899 | 0 | const auto &rowCode = row[1]; |
1900 | 0 | const auto tmpAuthFactory = |
1901 | 0 | AuthorityFactory::create(dbContext, rowAuthName); |
1902 | 0 | try { |
1903 | 0 | const auto cs = tmpAuthFactory->createCoordinateSystem(rowCode); |
1904 | 0 | if (cs->_isEquivalentTo(obj.get(), |
1905 | 0 | util::IComparable::Criterion::EQUIVALENT)) { |
1906 | 0 | authName = rowAuthName; |
1907 | 0 | code = rowCode; |
1908 | 0 | if (authName == metadata::Identifier::EPSG && code == "4400") { |
1909 | | // preferred coordinate system for cartesian |
1910 | | // Easting, Northing |
1911 | 0 | return; |
1912 | 0 | } |
1913 | 0 | if (authName == metadata::Identifier::EPSG && code == "6422") { |
1914 | | // preferred coordinate system for geographic lat, long |
1915 | 0 | return; |
1916 | 0 | } |
1917 | 0 | if (authName == metadata::Identifier::EPSG && code == "6423") { |
1918 | | // preferred coordinate system for geographic lat, long, h |
1919 | 0 | return; |
1920 | 0 | } |
1921 | 0 | } |
1922 | 0 | } catch (const std::exception &) { |
1923 | 0 | } |
1924 | 0 | } |
1925 | 0 | } |
1926 | | |
1927 | | // --------------------------------------------------------------------------- |
1928 | | |
1929 | | void DatabaseContext::Private::identifyOrInsert( |
1930 | | const DatabaseContextNNPtr &dbContext, const cs::CoordinateSystemNNPtr &obj, |
1931 | | const std::string &ownerType, const std::string &ownerAuthName, |
1932 | | const std::string &ownerCode, std::string &authName, std::string &code, |
1933 | 0 | std::vector<std::string> &sqlStatements) { |
1934 | |
|
1935 | 0 | identify(dbContext, obj, authName, code); |
1936 | 0 | if (!authName.empty()) { |
1937 | 0 | return; |
1938 | 0 | } |
1939 | | |
1940 | 0 | const char *type = getCSDatabaseType(obj); |
1941 | 0 | if (type == nullptr) { |
1942 | 0 | throw FactoryException("Cannot insert this type of CoordinateSystem"); |
1943 | 0 | } |
1944 | | |
1945 | | // Insert new record in coordinate_system |
1946 | 0 | authName = ownerAuthName; |
1947 | 0 | const std::string codePrototype("CS_" + ownerType + '_' + ownerCode); |
1948 | 0 | code = findFreeCode("coordinate_system", authName, codePrototype); |
1949 | |
|
1950 | 0 | const auto &axisList = obj->axisList(); |
1951 | 0 | { |
1952 | 0 | const auto sql = formatStatement( |
1953 | 0 | "INSERT INTO coordinate_system VALUES('%q','%q','%q',%d);", |
1954 | 0 | authName.c_str(), code.c_str(), type, |
1955 | 0 | static_cast<int>(axisList.size())); |
1956 | 0 | appendSql(sqlStatements, sql); |
1957 | 0 | } |
1958 | | |
1959 | | // Insert new records for the axis |
1960 | 0 | for (int i = 0; i < static_cast<int>(axisList.size()); ++i) { |
1961 | 0 | const auto &axis = axisList[i]; |
1962 | 0 | std::string uomAuthName; |
1963 | 0 | std::string uomCode; |
1964 | 0 | identifyOrInsert(dbContext, axis->unit(), ownerAuthName, uomAuthName, |
1965 | 0 | uomCode, sqlStatements); |
1966 | 0 | const auto sql = formatStatement( |
1967 | 0 | "INSERT INTO axis VALUES(" |
1968 | 0 | "'%q','%q','%q','%q','%q','%q','%q',%d,'%q','%q');", |
1969 | 0 | authName.c_str(), (code + "_AXIS_" + toString(i + 1)).c_str(), |
1970 | 0 | axis->nameStr().c_str(), axis->abbreviation().c_str(), |
1971 | 0 | axis->direction().toString().c_str(), authName.c_str(), |
1972 | 0 | code.c_str(), i + 1, uomAuthName.c_str(), uomCode.c_str()); |
1973 | 0 | appendSql(sqlStatements, sql); |
1974 | 0 | } |
1975 | 0 | } |
1976 | | |
1977 | | // --------------------------------------------------------------------------- |
1978 | | |
1979 | | static void |
1980 | | addAllowedAuthoritiesCond(const std::vector<std::string> &allowedAuthorities, |
1981 | | const std::string &authName, std::string &sql, |
1982 | 0 | ListOfParams ¶ms) { |
1983 | 0 | sql += "auth_name IN (?"; |
1984 | 0 | params.emplace_back(authName); |
1985 | 0 | for (const auto &allowedAuthority : allowedAuthorities) { |
1986 | 0 | sql += ",?"; |
1987 | 0 | params.emplace_back(allowedAuthority); |
1988 | 0 | } |
1989 | 0 | sql += ')'; |
1990 | 0 | } |
1991 | | |
1992 | | // --------------------------------------------------------------------------- |
1993 | | |
1994 | | void DatabaseContext::Private::identifyOrInsertUsages( |
1995 | | const common::ObjectUsageNNPtr &obj, const std::string &tableName, |
1996 | | const std::string &authName, const std::string &code, |
1997 | | const std::vector<std::string> &allowedAuthorities, |
1998 | 0 | std::vector<std::string> &sqlStatements) { |
1999 | |
|
2000 | 0 | std::string usageCode("USAGE_"); |
2001 | 0 | const std::string upperTableName(toupper(tableName)); |
2002 | 0 | if (!starts_with(code, upperTableName)) { |
2003 | 0 | usageCode += upperTableName; |
2004 | 0 | usageCode += '_'; |
2005 | 0 | } |
2006 | 0 | usageCode += code; |
2007 | |
|
2008 | 0 | const auto &domains = obj->domains(); |
2009 | 0 | if (domains.empty()) { |
2010 | 0 | const auto sql = |
2011 | 0 | formatStatement("INSERT INTO usage VALUES('%q','%q','%q','%q','%q'," |
2012 | 0 | "'PROJ','EXTENT_UNKNOWN','PROJ','SCOPE_UNKNOWN');", |
2013 | 0 | authName.c_str(), usageCode.c_str(), |
2014 | 0 | tableName.c_str(), authName.c_str(), code.c_str()); |
2015 | 0 | appendSql(sqlStatements, sql); |
2016 | 0 | return; |
2017 | 0 | } |
2018 | | |
2019 | 0 | int usageCounter = 1; |
2020 | 0 | for (const auto &domain : domains) { |
2021 | 0 | std::string scopeAuthName; |
2022 | 0 | std::string scopeCode; |
2023 | 0 | const auto &scope = domain->scope(); |
2024 | 0 | if (scope.has_value()) { |
2025 | 0 | std::string sql = |
2026 | 0 | "SELECT auth_name, code, " |
2027 | 0 | "(CASE WHEN auth_name = 'EPSG' THEN 0 ELSE 1 END) " |
2028 | 0 | "AS order_idx " |
2029 | 0 | "FROM scope WHERE scope = ? AND deprecated = 0 AND "; |
2030 | 0 | ListOfParams params{*scope}; |
2031 | 0 | addAllowedAuthoritiesCond(allowedAuthorities, authName, sql, |
2032 | 0 | params); |
2033 | 0 | sql += " ORDER BY order_idx, auth_name, code"; |
2034 | 0 | const auto rows = run(sql, params); |
2035 | 0 | if (!rows.empty()) { |
2036 | 0 | const auto &row = rows.front(); |
2037 | 0 | scopeAuthName = row[0]; |
2038 | 0 | scopeCode = row[1]; |
2039 | 0 | } else { |
2040 | 0 | scopeAuthName = authName; |
2041 | 0 | scopeCode = "SCOPE_"; |
2042 | 0 | scopeCode += tableName; |
2043 | 0 | scopeCode += '_'; |
2044 | 0 | scopeCode += code; |
2045 | 0 | const auto sqlToInsert = formatStatement( |
2046 | 0 | "INSERT INTO scope VALUES('%q','%q','%q',0);", |
2047 | 0 | scopeAuthName.c_str(), scopeCode.c_str(), scope->c_str()); |
2048 | 0 | appendSql(sqlStatements, sqlToInsert); |
2049 | 0 | } |
2050 | 0 | } else { |
2051 | 0 | scopeAuthName = "PROJ"; |
2052 | 0 | scopeCode = "SCOPE_UNKNOWN"; |
2053 | 0 | } |
2054 | |
|
2055 | 0 | std::string extentAuthName("PROJ"); |
2056 | 0 | std::string extentCode("EXTENT_UNKNOWN"); |
2057 | 0 | const auto &extent = domain->domainOfValidity(); |
2058 | 0 | if (extent) { |
2059 | 0 | const auto &geogElts = extent->geographicElements(); |
2060 | 0 | if (!geogElts.empty()) { |
2061 | 0 | const auto bbox = |
2062 | 0 | dynamic_cast<const metadata::GeographicBoundingBox *>( |
2063 | 0 | geogElts.front().get()); |
2064 | 0 | if (bbox) { |
2065 | 0 | std::string sql = |
2066 | 0 | "SELECT auth_name, code, " |
2067 | 0 | "(CASE WHEN auth_name = 'EPSG' THEN 0 ELSE 1 END) " |
2068 | 0 | "AS order_idx " |
2069 | 0 | "FROM extent WHERE south_lat = ? AND north_lat = ? " |
2070 | 0 | "AND west_lon = ? AND east_lon = ? AND deprecated = 0 " |
2071 | 0 | "AND "; |
2072 | 0 | ListOfParams params{ |
2073 | 0 | bbox->southBoundLatitude(), bbox->northBoundLatitude(), |
2074 | 0 | bbox->westBoundLongitude(), bbox->eastBoundLongitude()}; |
2075 | 0 | addAllowedAuthoritiesCond(allowedAuthorities, authName, sql, |
2076 | 0 | params); |
2077 | 0 | sql += " ORDER BY order_idx, auth_name, code"; |
2078 | 0 | const auto rows = run(sql, params); |
2079 | 0 | if (!rows.empty()) { |
2080 | 0 | const auto &row = rows.front(); |
2081 | 0 | extentAuthName = row[0]; |
2082 | 0 | extentCode = row[1]; |
2083 | 0 | } else { |
2084 | 0 | extentAuthName = authName; |
2085 | 0 | extentCode = "EXTENT_"; |
2086 | 0 | extentCode += tableName; |
2087 | 0 | extentCode += '_'; |
2088 | 0 | extentCode += code; |
2089 | 0 | std::string description(*(extent->description())); |
2090 | 0 | if (description.empty()) { |
2091 | 0 | description = "unknown"; |
2092 | 0 | } |
2093 | 0 | const auto sqlToInsert = formatStatement( |
2094 | 0 | "INSERT INTO extent " |
2095 | 0 | "VALUES('%q','%q','%q','%q',%f,%f,%f,%f,0);", |
2096 | 0 | extentAuthName.c_str(), extentCode.c_str(), |
2097 | 0 | description.c_str(), description.c_str(), |
2098 | 0 | bbox->southBoundLatitude(), |
2099 | 0 | bbox->northBoundLatitude(), |
2100 | 0 | bbox->westBoundLongitude(), |
2101 | 0 | bbox->eastBoundLongitude()); |
2102 | 0 | appendSql(sqlStatements, sqlToInsert); |
2103 | 0 | } |
2104 | 0 | } |
2105 | 0 | } |
2106 | 0 | } |
2107 | |
|
2108 | 0 | if (domains.size() > 1) { |
2109 | 0 | usageCode += '_'; |
2110 | 0 | usageCode += toString(usageCounter); |
2111 | 0 | } |
2112 | 0 | const auto sql = formatStatement( |
2113 | 0 | "INSERT INTO usage VALUES('%q','%q','%q','%q','%q'," |
2114 | 0 | "'%q','%q','%q','%q');", |
2115 | 0 | authName.c_str(), usageCode.c_str(), tableName.c_str(), |
2116 | 0 | authName.c_str(), code.c_str(), extentAuthName.c_str(), |
2117 | 0 | extentCode.c_str(), scopeAuthName.c_str(), scopeCode.c_str()); |
2118 | 0 | appendSql(sqlStatements, sql); |
2119 | |
|
2120 | 0 | usageCounter++; |
2121 | 0 | } |
2122 | 0 | } |
2123 | | |
2124 | | // --------------------------------------------------------------------------- |
2125 | | |
2126 | | std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( |
2127 | | const datum::PrimeMeridianNNPtr &pm, const std::string &authName, |
2128 | | const std::string &code, bool /*numericCode*/, |
2129 | 0 | const std::vector<std::string> &allowedAuthorities) { |
2130 | |
|
2131 | 0 | const auto self = NN_NO_CHECK(self_.lock()); |
2132 | | |
2133 | | // Check if the object is already known under that code |
2134 | 0 | std::string pmAuthName; |
2135 | 0 | std::string pmCode; |
2136 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, pm, pmAuthName, |
2137 | 0 | pmCode); |
2138 | 0 | if (pmAuthName == authName && pmCode == code) { |
2139 | 0 | return {}; |
2140 | 0 | } |
2141 | | |
2142 | 0 | std::vector<std::string> sqlStatements; |
2143 | | |
2144 | | // Insert new record in prime_meridian table |
2145 | 0 | std::string uomAuthName; |
2146 | 0 | std::string uomCode; |
2147 | 0 | identifyOrInsert(self, pm->longitude().unit(), authName, uomAuthName, |
2148 | 0 | uomCode, sqlStatements); |
2149 | |
|
2150 | 0 | const auto sql = formatStatement( |
2151 | 0 | "INSERT INTO prime_meridian VALUES(" |
2152 | 0 | "'%q','%q','%q',%f,'%q','%q',0);", |
2153 | 0 | authName.c_str(), code.c_str(), pm->nameStr().c_str(), |
2154 | 0 | pm->longitude().value(), uomAuthName.c_str(), uomCode.c_str()); |
2155 | 0 | appendSql(sqlStatements, sql); |
2156 | |
|
2157 | 0 | return sqlStatements; |
2158 | 0 | } |
2159 | | |
2160 | | // --------------------------------------------------------------------------- |
2161 | | |
2162 | | std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( |
2163 | | const datum::EllipsoidNNPtr &ellipsoid, const std::string &authName, |
2164 | | const std::string &code, bool /*numericCode*/, |
2165 | 0 | const std::vector<std::string> &allowedAuthorities) { |
2166 | |
|
2167 | 0 | const auto self = NN_NO_CHECK(self_.lock()); |
2168 | | |
2169 | | // Check if the object is already known under that code |
2170 | 0 | std::string ellipsoidAuthName; |
2171 | 0 | std::string ellipsoidCode; |
2172 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, ellipsoid, |
2173 | 0 | ellipsoidAuthName, ellipsoidCode); |
2174 | 0 | if (ellipsoidAuthName == authName && ellipsoidCode == code) { |
2175 | 0 | return {}; |
2176 | 0 | } |
2177 | | |
2178 | 0 | std::vector<std::string> sqlStatements; |
2179 | | |
2180 | | // Find or insert celestial body |
2181 | 0 | const auto &semiMajorAxis = ellipsoid->semiMajorAxis(); |
2182 | 0 | const double semiMajorAxisMetre = semiMajorAxis.getSIValue(); |
2183 | 0 | constexpr double tolerance = 0.005; |
2184 | 0 | std::string bodyAuthName; |
2185 | 0 | std::string bodyCode; |
2186 | 0 | auto res = run("SELECT auth_name, code, " |
2187 | 0 | "(ABS(semi_major_axis - ?) / semi_major_axis ) " |
2188 | 0 | "AS rel_error FROM celestial_body WHERE rel_error <= ?", |
2189 | 0 | {semiMajorAxisMetre, tolerance}); |
2190 | 0 | if (!res.empty()) { |
2191 | 0 | const auto &row = res.front(); |
2192 | 0 | bodyAuthName = row[0]; |
2193 | 0 | bodyCode = row[1]; |
2194 | 0 | } else { |
2195 | 0 | bodyAuthName = authName; |
2196 | 0 | bodyCode = "BODY_" + code; |
2197 | 0 | const auto bodyName = "Body of " + ellipsoid->nameStr(); |
2198 | 0 | const auto sql = formatStatement( |
2199 | 0 | "INSERT INTO celestial_body VALUES('%q','%q','%q',%f);", |
2200 | 0 | bodyAuthName.c_str(), bodyCode.c_str(), bodyName.c_str(), |
2201 | 0 | semiMajorAxisMetre); |
2202 | 0 | appendSql(sqlStatements, sql); |
2203 | 0 | } |
2204 | | |
2205 | | // Insert new record in ellipsoid table |
2206 | 0 | std::string uomAuthName; |
2207 | 0 | std::string uomCode; |
2208 | 0 | identifyOrInsert(self, semiMajorAxis.unit(), authName, uomAuthName, uomCode, |
2209 | 0 | sqlStatements); |
2210 | 0 | std::string invFlattening("NULL"); |
2211 | 0 | std::string semiMinorAxis("NULL"); |
2212 | 0 | if (ellipsoid->isSphere() || ellipsoid->semiMinorAxis().has_value()) { |
2213 | 0 | semiMinorAxis = toString(ellipsoid->computeSemiMinorAxis().value()); |
2214 | 0 | } else { |
2215 | 0 | invFlattening = toString(ellipsoid->computedInverseFlattening()); |
2216 | 0 | } |
2217 | |
|
2218 | 0 | const auto sql = formatStatement( |
2219 | 0 | "INSERT INTO ellipsoid VALUES(" |
2220 | 0 | "'%q','%q','%q','%q','%q','%q',%f,'%q','%q',%s,%s,0);", |
2221 | 0 | authName.c_str(), code.c_str(), ellipsoid->nameStr().c_str(), |
2222 | 0 | "", // description |
2223 | 0 | bodyAuthName.c_str(), bodyCode.c_str(), semiMajorAxis.value(), |
2224 | 0 | uomAuthName.c_str(), uomCode.c_str(), invFlattening.c_str(), |
2225 | 0 | semiMinorAxis.c_str()); |
2226 | 0 | appendSql(sqlStatements, sql); |
2227 | |
|
2228 | 0 | return sqlStatements; |
2229 | 0 | } |
2230 | | |
2231 | | // --------------------------------------------------------------------------- |
2232 | | |
2233 | 0 | static std::string anchorEpochToStr(double val) { |
2234 | 0 | constexpr int BUF_SIZE = 16; |
2235 | 0 | char szBuffer[BUF_SIZE]; |
2236 | 0 | sqlite3_snprintf(BUF_SIZE, szBuffer, "%.3f", val); |
2237 | 0 | return szBuffer; |
2238 | 0 | } |
2239 | | |
2240 | | // --------------------------------------------------------------------------- |
2241 | | |
2242 | | std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( |
2243 | | const datum::GeodeticReferenceFrameNNPtr &datum, |
2244 | | const std::string &authName, const std::string &code, bool numericCode, |
2245 | 0 | const std::vector<std::string> &allowedAuthorities) { |
2246 | |
|
2247 | 0 | const auto self = NN_NO_CHECK(self_.lock()); |
2248 | | |
2249 | | // Check if the object is already known under that code |
2250 | 0 | std::string datumAuthName; |
2251 | 0 | std::string datumCode; |
2252 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, datum, |
2253 | 0 | datumAuthName, datumCode); |
2254 | 0 | if (datumAuthName == authName && datumCode == code) { |
2255 | 0 | return {}; |
2256 | 0 | } |
2257 | | |
2258 | 0 | std::vector<std::string> sqlStatements; |
2259 | | |
2260 | | // Find or insert ellipsoid |
2261 | 0 | std::string ellipsoidAuthName; |
2262 | 0 | std::string ellipsoidCode; |
2263 | 0 | const auto &ellipsoidOfDatum = datum->ellipsoid(); |
2264 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, ellipsoidOfDatum, |
2265 | 0 | ellipsoidAuthName, ellipsoidCode); |
2266 | 0 | if (ellipsoidAuthName.empty()) { |
2267 | 0 | ellipsoidAuthName = authName; |
2268 | 0 | if (numericCode) { |
2269 | 0 | ellipsoidCode = self->suggestsCodeFor(ellipsoidOfDatum, |
2270 | 0 | ellipsoidAuthName, true); |
2271 | 0 | } else { |
2272 | 0 | ellipsoidCode = "ELLPS_" + code; |
2273 | 0 | } |
2274 | 0 | sqlStatements = self->getInsertStatementsFor( |
2275 | 0 | ellipsoidOfDatum, ellipsoidAuthName, ellipsoidCode, numericCode, |
2276 | 0 | allowedAuthorities); |
2277 | 0 | } |
2278 | | |
2279 | | // Find or insert prime meridian |
2280 | 0 | std::string pmAuthName; |
2281 | 0 | std::string pmCode; |
2282 | 0 | const auto &pmOfDatum = datum->primeMeridian(); |
2283 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, pmOfDatum, |
2284 | 0 | pmAuthName, pmCode); |
2285 | 0 | if (pmAuthName.empty()) { |
2286 | 0 | pmAuthName = authName; |
2287 | 0 | if (numericCode) { |
2288 | 0 | pmCode = self->suggestsCodeFor(pmOfDatum, pmAuthName, true); |
2289 | 0 | } else { |
2290 | 0 | pmCode = "PM_" + code; |
2291 | 0 | } |
2292 | 0 | const auto sqlStatementsTmp = self->getInsertStatementsFor( |
2293 | 0 | pmOfDatum, pmAuthName, pmCode, numericCode, allowedAuthorities); |
2294 | 0 | sqlStatements.insert(sqlStatements.end(), sqlStatementsTmp.begin(), |
2295 | 0 | sqlStatementsTmp.end()); |
2296 | 0 | } |
2297 | | |
2298 | | // Insert new record in geodetic_datum table |
2299 | 0 | std::string publicationDate("NULL"); |
2300 | 0 | if (datum->publicationDate().has_value()) { |
2301 | 0 | publicationDate = '\''; |
2302 | 0 | publicationDate += |
2303 | 0 | replaceAll(datum->publicationDate()->toString(), "'", "''"); |
2304 | 0 | publicationDate += '\''; |
2305 | 0 | } |
2306 | 0 | std::string frameReferenceEpoch("NULL"); |
2307 | 0 | const auto dynamicDatum = |
2308 | 0 | dynamic_cast<const datum::DynamicGeodeticReferenceFrame *>(datum.get()); |
2309 | 0 | if (dynamicDatum) { |
2310 | 0 | frameReferenceEpoch = |
2311 | 0 | toString(dynamicDatum->frameReferenceEpoch().value()); |
2312 | 0 | } |
2313 | 0 | const std::string anchor(*(datum->anchorDefinition())); |
2314 | 0 | const util::optional<common::Measure> &anchorEpoch = datum->anchorEpoch(); |
2315 | 0 | const auto sql = formatStatement( |
2316 | 0 | "INSERT INTO geodetic_datum VALUES(" |
2317 | 0 | "'%q','%q','%q','%q','%q','%q','%q','%q',%s,%s,NULL,%Q,%s,0);", |
2318 | 0 | authName.c_str(), code.c_str(), datum->nameStr().c_str(), |
2319 | 0 | "", // description |
2320 | 0 | ellipsoidAuthName.c_str(), ellipsoidCode.c_str(), pmAuthName.c_str(), |
2321 | 0 | pmCode.c_str(), publicationDate.c_str(), frameReferenceEpoch.c_str(), |
2322 | 0 | anchor.empty() ? nullptr : anchor.c_str(), |
2323 | 0 | anchorEpoch.has_value() |
2324 | 0 | ? anchorEpochToStr( |
2325 | 0 | anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR)) |
2326 | 0 | .c_str() |
2327 | 0 | : "NULL"); |
2328 | 0 | appendSql(sqlStatements, sql); |
2329 | |
|
2330 | 0 | identifyOrInsertUsages(datum, "geodetic_datum", authName, code, |
2331 | 0 | allowedAuthorities, sqlStatements); |
2332 | |
|
2333 | 0 | return sqlStatements; |
2334 | 0 | } |
2335 | | |
2336 | | // --------------------------------------------------------------------------- |
2337 | | |
2338 | | std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( |
2339 | | const datum::DatumEnsembleNNPtr &ensemble, const std::string &authName, |
2340 | | const std::string &code, bool numericCode, |
2341 | 0 | const std::vector<std::string> &allowedAuthorities) { |
2342 | 0 | const auto self = NN_NO_CHECK(self_.lock()); |
2343 | | |
2344 | | // Check if the object is already known under that code |
2345 | 0 | std::string datumAuthName; |
2346 | 0 | std::string datumCode; |
2347 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, ensemble, |
2348 | 0 | datumAuthName, datumCode); |
2349 | 0 | if (datumAuthName == authName && datumCode == code) { |
2350 | 0 | return {}; |
2351 | 0 | } |
2352 | | |
2353 | 0 | std::vector<std::string> sqlStatements; |
2354 | |
|
2355 | 0 | const auto &members = ensemble->datums(); |
2356 | 0 | assert(!members.empty()); |
2357 | |
|
2358 | 0 | int counter = 1; |
2359 | 0 | std::vector<std::pair<std::string, std::string>> membersId; |
2360 | 0 | for (const auto &member : members) { |
2361 | 0 | std::string memberAuthName; |
2362 | 0 | std::string memberCode; |
2363 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, member, |
2364 | 0 | memberAuthName, memberCode); |
2365 | 0 | if (memberAuthName.empty()) { |
2366 | 0 | memberAuthName = authName; |
2367 | 0 | if (numericCode) { |
2368 | 0 | memberCode = |
2369 | 0 | self->suggestsCodeFor(member, memberAuthName, true); |
2370 | 0 | } else { |
2371 | 0 | memberCode = "MEMBER_" + toString(counter) + "_OF_" + code; |
2372 | 0 | } |
2373 | 0 | const auto sqlStatementsTmp = |
2374 | 0 | self->getInsertStatementsFor(member, memberAuthName, memberCode, |
2375 | 0 | numericCode, allowedAuthorities); |
2376 | 0 | sqlStatements.insert(sqlStatements.end(), sqlStatementsTmp.begin(), |
2377 | 0 | sqlStatementsTmp.end()); |
2378 | 0 | } |
2379 | |
|
2380 | 0 | membersId.emplace_back( |
2381 | 0 | std::pair<std::string, std::string>(memberAuthName, memberCode)); |
2382 | |
|
2383 | 0 | ++counter; |
2384 | 0 | } |
2385 | |
|
2386 | 0 | const bool isGeodetic = |
2387 | 0 | util::nn_dynamic_pointer_cast<datum::GeodeticReferenceFrame>( |
2388 | 0 | members.front()) != nullptr; |
2389 | | |
2390 | | // Insert new record in geodetic_datum/vertical_datum table |
2391 | 0 | const double accuracy = |
2392 | 0 | c_locale_stod(ensemble->positionalAccuracy()->value()); |
2393 | 0 | if (isGeodetic) { |
2394 | 0 | const auto firstDatum = |
2395 | 0 | AuthorityFactory::create(self, membersId.front().first) |
2396 | 0 | ->createGeodeticDatum(membersId.front().second); |
2397 | 0 | const auto &ellipsoid = firstDatum->ellipsoid(); |
2398 | 0 | const auto &ellipsoidIds = ellipsoid->identifiers(); |
2399 | 0 | assert(!ellipsoidIds.empty()); |
2400 | 0 | const std::string &ellipsoidAuthName = |
2401 | 0 | *(ellipsoidIds.front()->codeSpace()); |
2402 | 0 | const std::string &ellipsoidCode = ellipsoidIds.front()->code(); |
2403 | 0 | const auto &pm = firstDatum->primeMeridian(); |
2404 | 0 | const auto &pmIds = pm->identifiers(); |
2405 | 0 | assert(!pmIds.empty()); |
2406 | 0 | const std::string &pmAuthName = *(pmIds.front()->codeSpace()); |
2407 | 0 | const std::string &pmCode = pmIds.front()->code(); |
2408 | 0 | const std::string anchor(*(firstDatum->anchorDefinition())); |
2409 | 0 | const util::optional<common::Measure> &anchorEpoch = |
2410 | 0 | firstDatum->anchorEpoch(); |
2411 | 0 | const auto sql = formatStatement( |
2412 | 0 | "INSERT INTO geodetic_datum VALUES(" |
2413 | 0 | "'%q','%q','%q','%q','%q','%q','%q','%q',NULL,NULL,%f,%Q,%s,0);", |
2414 | 0 | authName.c_str(), code.c_str(), ensemble->nameStr().c_str(), |
2415 | 0 | "", // description |
2416 | 0 | ellipsoidAuthName.c_str(), ellipsoidCode.c_str(), |
2417 | 0 | pmAuthName.c_str(), pmCode.c_str(), accuracy, |
2418 | 0 | anchor.empty() ? nullptr : anchor.c_str(), |
2419 | 0 | anchorEpoch.has_value() |
2420 | 0 | ? anchorEpochToStr( |
2421 | 0 | anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR)) |
2422 | 0 | .c_str() |
2423 | 0 | : "NULL"); |
2424 | 0 | appendSql(sqlStatements, sql); |
2425 | 0 | } else { |
2426 | 0 | const auto firstDatum = |
2427 | 0 | AuthorityFactory::create(self, membersId.front().first) |
2428 | 0 | ->createVerticalDatum(membersId.front().second); |
2429 | 0 | const std::string anchor(*(firstDatum->anchorDefinition())); |
2430 | 0 | const util::optional<common::Measure> &anchorEpoch = |
2431 | 0 | firstDatum->anchorEpoch(); |
2432 | 0 | const auto sql = formatStatement( |
2433 | 0 | "INSERT INTO vertical_datum VALUES(" |
2434 | 0 | "'%q','%q','%q','%q',NULL,NULL,%f,%Q,%s,0);", |
2435 | 0 | authName.c_str(), code.c_str(), ensemble->nameStr().c_str(), |
2436 | 0 | "", // description |
2437 | 0 | accuracy, anchor.empty() ? nullptr : anchor.c_str(), |
2438 | 0 | anchorEpoch.has_value() |
2439 | 0 | ? anchorEpochToStr( |
2440 | 0 | anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR)) |
2441 | 0 | .c_str() |
2442 | 0 | : "NULL"); |
2443 | 0 | appendSql(sqlStatements, sql); |
2444 | 0 | } |
2445 | 0 | identifyOrInsertUsages(ensemble, |
2446 | 0 | isGeodetic ? "geodetic_datum" : "vertical_datum", |
2447 | 0 | authName, code, allowedAuthorities, sqlStatements); |
2448 | |
|
2449 | 0 | const char *tableName = isGeodetic ? "geodetic_datum_ensemble_member" |
2450 | 0 | : "vertical_datum_ensemble_member"; |
2451 | 0 | counter = 1; |
2452 | 0 | for (const auto &authCodePair : membersId) { |
2453 | 0 | const auto sql = formatStatement( |
2454 | 0 | "INSERT INTO %s VALUES(" |
2455 | 0 | "'%q','%q','%q','%q',%d);", |
2456 | 0 | tableName, authName.c_str(), code.c_str(), |
2457 | 0 | authCodePair.first.c_str(), authCodePair.second.c_str(), counter); |
2458 | 0 | appendSql(sqlStatements, sql); |
2459 | 0 | ++counter; |
2460 | 0 | } |
2461 | |
|
2462 | 0 | return sqlStatements; |
2463 | 0 | } |
2464 | | |
2465 | | // --------------------------------------------------------------------------- |
2466 | | |
2467 | | std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( |
2468 | | const crs::GeodeticCRSNNPtr &crs, const std::string &authName, |
2469 | | const std::string &code, bool numericCode, |
2470 | 0 | const std::vector<std::string> &allowedAuthorities) { |
2471 | |
|
2472 | 0 | const auto self = NN_NO_CHECK(self_.lock()); |
2473 | |
|
2474 | 0 | std::vector<std::string> sqlStatements; |
2475 | | |
2476 | | // Find or insert datum/datum ensemble |
2477 | 0 | std::string datumAuthName; |
2478 | 0 | std::string datumCode; |
2479 | 0 | const auto &ensemble = crs->datumEnsemble(); |
2480 | 0 | if (ensemble) { |
2481 | 0 | const auto ensembleNN = NN_NO_CHECK(ensemble); |
2482 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, ensembleNN, |
2483 | 0 | datumAuthName, datumCode); |
2484 | 0 | if (datumAuthName.empty()) { |
2485 | 0 | datumAuthName = authName; |
2486 | 0 | if (numericCode) { |
2487 | 0 | datumCode = |
2488 | 0 | self->suggestsCodeFor(ensembleNN, datumAuthName, true); |
2489 | 0 | } else { |
2490 | 0 | datumCode = "GEODETIC_DATUM_" + code; |
2491 | 0 | } |
2492 | 0 | sqlStatements = self->getInsertStatementsFor( |
2493 | 0 | ensembleNN, datumAuthName, datumCode, numericCode, |
2494 | 0 | allowedAuthorities); |
2495 | 0 | } |
2496 | 0 | } else { |
2497 | 0 | const auto &datum = crs->datum(); |
2498 | 0 | assert(datum); |
2499 | 0 | const auto datumNN = NN_NO_CHECK(datum); |
2500 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, datumNN, |
2501 | 0 | datumAuthName, datumCode); |
2502 | 0 | if (datumAuthName.empty()) { |
2503 | 0 | datumAuthName = authName; |
2504 | 0 | if (numericCode) { |
2505 | 0 | datumCode = self->suggestsCodeFor(datumNN, datumAuthName, true); |
2506 | 0 | } else { |
2507 | 0 | datumCode = "GEODETIC_DATUM_" + code; |
2508 | 0 | } |
2509 | 0 | sqlStatements = |
2510 | 0 | self->getInsertStatementsFor(datumNN, datumAuthName, datumCode, |
2511 | 0 | numericCode, allowedAuthorities); |
2512 | 0 | } |
2513 | 0 | } |
2514 | | |
2515 | | // Find or insert coordinate system |
2516 | 0 | const auto &coordinateSystem = crs->coordinateSystem(); |
2517 | 0 | std::string csAuthName; |
2518 | 0 | std::string csCode; |
2519 | 0 | identifyOrInsert(self, coordinateSystem, "GEODETIC_CRS", authName, code, |
2520 | 0 | csAuthName, csCode, sqlStatements); |
2521 | |
|
2522 | 0 | const char *type = GEOG_2D; |
2523 | 0 | if (coordinateSystem->axisList().size() == 3) { |
2524 | 0 | if (dynamic_cast<const crs::GeographicCRS *>(crs.get())) { |
2525 | 0 | type = GEOG_3D; |
2526 | 0 | } else { |
2527 | 0 | type = GEOCENTRIC; |
2528 | 0 | } |
2529 | 0 | } |
2530 | | |
2531 | | // Insert new record in geodetic_crs table |
2532 | 0 | const auto sql = |
2533 | 0 | formatStatement("INSERT INTO geodetic_crs VALUES(" |
2534 | 0 | "'%q','%q','%q','%q','%q','%q','%q','%q','%q',NULL,0);", |
2535 | 0 | authName.c_str(), code.c_str(), crs->nameStr().c_str(), |
2536 | 0 | "", // description |
2537 | 0 | type, csAuthName.c_str(), csCode.c_str(), |
2538 | 0 | datumAuthName.c_str(), datumCode.c_str()); |
2539 | 0 | appendSql(sqlStatements, sql); |
2540 | |
|
2541 | 0 | identifyOrInsertUsages(crs, "geodetic_crs", authName, code, |
2542 | 0 | allowedAuthorities, sqlStatements); |
2543 | 0 | return sqlStatements; |
2544 | 0 | } |
2545 | | |
2546 | | // --------------------------------------------------------------------------- |
2547 | | |
2548 | | std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( |
2549 | | const crs::ProjectedCRSNNPtr &crs, const std::string &authName, |
2550 | | const std::string &code, bool numericCode, |
2551 | 0 | const std::vector<std::string> &allowedAuthorities) { |
2552 | |
|
2553 | 0 | const auto self = NN_NO_CHECK(self_.lock()); |
2554 | |
|
2555 | 0 | std::vector<std::string> sqlStatements; |
2556 | | |
2557 | | // Find or insert base geodetic CRS |
2558 | 0 | const auto &baseCRS = crs->baseCRS(); |
2559 | 0 | std::string geodAuthName; |
2560 | 0 | std::string geodCode; |
2561 | |
|
2562 | 0 | auto allowedAuthoritiesTmp(allowedAuthorities); |
2563 | 0 | allowedAuthoritiesTmp.emplace_back(authName); |
2564 | 0 | for (const auto &allowedAuthority : allowedAuthoritiesTmp) { |
2565 | 0 | const auto factory = AuthorityFactory::create(self, allowedAuthority); |
2566 | 0 | const auto candidates = baseCRS->identify(factory); |
2567 | 0 | for (const auto &candidate : candidates) { |
2568 | 0 | if (candidate.second == 100) { |
2569 | 0 | const auto &ids = candidate.first->identifiers(); |
2570 | 0 | if (!ids.empty()) { |
2571 | 0 | const auto &id = ids.front(); |
2572 | 0 | geodAuthName = *(id->codeSpace()); |
2573 | 0 | geodCode = id->code(); |
2574 | 0 | break; |
2575 | 0 | } |
2576 | 0 | } |
2577 | 0 | if (!geodAuthName.empty()) { |
2578 | 0 | break; |
2579 | 0 | } |
2580 | 0 | } |
2581 | 0 | } |
2582 | 0 | if (geodAuthName.empty()) { |
2583 | 0 | geodAuthName = authName; |
2584 | 0 | geodCode = "GEODETIC_CRS_" + code; |
2585 | 0 | sqlStatements = self->getInsertStatementsFor( |
2586 | 0 | baseCRS, geodAuthName, geodCode, numericCode, allowedAuthorities); |
2587 | 0 | } |
2588 | | |
2589 | | // Insert new record in conversion table |
2590 | 0 | const auto &conversion = crs->derivingConversionRef(); |
2591 | 0 | std::string convAuthName(authName); |
2592 | 0 | std::string convCode("CONVERSION_" + code); |
2593 | 0 | if (numericCode) { |
2594 | 0 | convCode = self->suggestsCodeFor(conversion, convAuthName, true); |
2595 | 0 | } |
2596 | 0 | { |
2597 | 0 | const auto &method = conversion->method(); |
2598 | 0 | const auto &methodIds = method->identifiers(); |
2599 | 0 | std::string methodAuthName; |
2600 | 0 | std::string methodCode; |
2601 | 0 | const operation::MethodMapping *methodMapping = nullptr; |
2602 | 0 | if (methodIds.empty()) { |
2603 | 0 | const int epsgCode = method->getEPSGCode(); |
2604 | 0 | if (epsgCode > 0) { |
2605 | 0 | methodAuthName = metadata::Identifier::EPSG; |
2606 | 0 | methodCode = toString(epsgCode); |
2607 | 0 | } else { |
2608 | 0 | const auto &methodName = method->nameStr(); |
2609 | 0 | size_t nProjectionMethodMappings = 0; |
2610 | 0 | const auto projectionMethodMappings = |
2611 | 0 | operation::getProjectionMethodMappings( |
2612 | 0 | nProjectionMethodMappings); |
2613 | 0 | for (size_t i = 0; i < nProjectionMethodMappings; ++i) { |
2614 | 0 | const auto &mapping = projectionMethodMappings[i]; |
2615 | 0 | if (metadata::Identifier::isEquivalentName( |
2616 | 0 | mapping.wkt2_name, methodName.c_str())) { |
2617 | 0 | methodMapping = &mapping; |
2618 | 0 | } |
2619 | 0 | } |
2620 | 0 | if (methodMapping == nullptr || |
2621 | 0 | methodMapping->proj_name_main == nullptr) { |
2622 | 0 | throw FactoryException("Cannot insert projection with " |
2623 | 0 | "method without identifier"); |
2624 | 0 | } |
2625 | 0 | methodAuthName = "PROJ"; |
2626 | 0 | methodCode = methodMapping->proj_name_main; |
2627 | 0 | if (methodMapping->proj_name_aux) { |
2628 | 0 | methodCode += ' '; |
2629 | 0 | methodCode += methodMapping->proj_name_aux; |
2630 | 0 | } |
2631 | 0 | } |
2632 | 0 | } else { |
2633 | 0 | const auto &methodId = methodIds.front(); |
2634 | 0 | methodAuthName = *(methodId->codeSpace()); |
2635 | 0 | methodCode = methodId->code(); |
2636 | 0 | } |
2637 | | |
2638 | 0 | auto sql = formatStatement("INSERT INTO conversion VALUES(" |
2639 | 0 | "'%q','%q','%q','','%q','%q','%q'", |
2640 | 0 | convAuthName.c_str(), convCode.c_str(), |
2641 | 0 | conversion->nameStr().c_str(), |
2642 | 0 | methodAuthName.c_str(), methodCode.c_str(), |
2643 | 0 | method->nameStr().c_str()); |
2644 | 0 | const auto &srcValues = conversion->parameterValues(); |
2645 | 0 | if (srcValues.size() > N_MAX_PARAMS) { |
2646 | 0 | throw FactoryException("Cannot insert projection with more than " + |
2647 | 0 | toString(static_cast<int>(N_MAX_PARAMS)) + |
2648 | 0 | " parameters"); |
2649 | 0 | } |
2650 | | |
2651 | 0 | std::vector<operation::GeneralParameterValueNNPtr> values; |
2652 | 0 | if (methodMapping == nullptr) { |
2653 | 0 | if (methodAuthName == metadata::Identifier::EPSG) { |
2654 | 0 | methodMapping = operation::getMapping(atoi(methodCode.c_str())); |
2655 | 0 | } else { |
2656 | 0 | methodMapping = |
2657 | 0 | operation::getMapping(method->nameStr().c_str()); |
2658 | 0 | } |
2659 | 0 | } |
2660 | 0 | if (methodMapping != nullptr) { |
2661 | | // Re-order projection parameters in their reference order |
2662 | 0 | for (size_t j = 0; methodMapping->params[j] != nullptr; ++j) { |
2663 | 0 | for (size_t i = 0; i < srcValues.size(); ++i) { |
2664 | 0 | auto opParamValue = dynamic_cast< |
2665 | 0 | const operation::OperationParameterValue *>( |
2666 | 0 | srcValues[i].get()); |
2667 | 0 | if (!opParamValue) { |
2668 | 0 | throw FactoryException("Cannot insert projection with " |
2669 | 0 | "non-OperationParameterValue"); |
2670 | 0 | } |
2671 | 0 | if (methodMapping->params[j]->wkt2_name && |
2672 | 0 | opParamValue->parameter()->nameStr() == |
2673 | 0 | methodMapping->params[j]->wkt2_name) { |
2674 | 0 | values.emplace_back(srcValues[i]); |
2675 | 0 | } |
2676 | 0 | } |
2677 | 0 | } |
2678 | 0 | } |
2679 | 0 | if (values.size() != srcValues.size()) { |
2680 | 0 | values = srcValues; |
2681 | 0 | } |
2682 | |
|
2683 | 0 | for (const auto &genOpParamvalue : values) { |
2684 | 0 | auto opParamValue = |
2685 | 0 | dynamic_cast<const operation::OperationParameterValue *>( |
2686 | 0 | genOpParamvalue.get()); |
2687 | 0 | if (!opParamValue) { |
2688 | 0 | throw FactoryException("Cannot insert projection with " |
2689 | 0 | "non-OperationParameterValue"); |
2690 | 0 | } |
2691 | 0 | const auto ¶m = opParamValue->parameter(); |
2692 | 0 | const auto ¶mIds = param->identifiers(); |
2693 | 0 | std::string paramAuthName; |
2694 | 0 | std::string paramCode; |
2695 | 0 | if (paramIds.empty()) { |
2696 | 0 | const int paramEPSGCode = param->getEPSGCode(); |
2697 | 0 | if (paramEPSGCode == 0) { |
2698 | 0 | throw FactoryException( |
2699 | 0 | "Cannot insert projection with method parameter " |
2700 | 0 | "without identifier"); |
2701 | 0 | } |
2702 | 0 | paramAuthName = metadata::Identifier::EPSG; |
2703 | 0 | paramCode = toString(paramEPSGCode); |
2704 | 0 | } else { |
2705 | 0 | const auto ¶mId = paramIds.front(); |
2706 | 0 | paramAuthName = *(paramId->codeSpace()); |
2707 | 0 | paramCode = paramId->code(); |
2708 | 0 | } |
2709 | 0 | const auto &value = opParamValue->parameterValue()->value(); |
2710 | 0 | const auto &unit = value.unit(); |
2711 | 0 | std::string uomAuthName; |
2712 | 0 | std::string uomCode; |
2713 | 0 | identifyOrInsert(self, unit, authName, uomAuthName, uomCode, |
2714 | 0 | sqlStatements); |
2715 | 0 | sql += formatStatement(",'%q','%q','%q',%f,'%q','%q'", |
2716 | 0 | paramAuthName.c_str(), paramCode.c_str(), |
2717 | 0 | param->nameStr().c_str(), value.value(), |
2718 | 0 | uomAuthName.c_str(), uomCode.c_str()); |
2719 | 0 | } |
2720 | 0 | for (size_t i = values.size(); i < N_MAX_PARAMS; ++i) { |
2721 | 0 | sql += ",NULL,NULL,NULL,NULL,NULL,NULL"; |
2722 | 0 | } |
2723 | 0 | sql += ",0);"; |
2724 | 0 | appendSql(sqlStatements, sql); |
2725 | 0 | identifyOrInsertUsages(crs, "conversion", convAuthName, convCode, |
2726 | 0 | allowedAuthorities, sqlStatements); |
2727 | 0 | } |
2728 | | |
2729 | | // Find or insert coordinate system |
2730 | 0 | const auto &coordinateSystem = crs->coordinateSystem(); |
2731 | 0 | std::string csAuthName; |
2732 | 0 | std::string csCode; |
2733 | 0 | identifyOrInsert(self, coordinateSystem, "PROJECTED_CRS", authName, code, |
2734 | 0 | csAuthName, csCode, sqlStatements); |
2735 | | |
2736 | | // Insert new record in projected_crs table |
2737 | 0 | const auto sql = formatStatement( |
2738 | 0 | "INSERT INTO projected_crs VALUES(" |
2739 | 0 | "'%q','%q','%q','%q','%q','%q','%q','%q','%q','%q',NULL,0);", |
2740 | 0 | authName.c_str(), code.c_str(), crs->nameStr().c_str(), |
2741 | 0 | "", // description |
2742 | 0 | csAuthName.c_str(), csCode.c_str(), geodAuthName.c_str(), |
2743 | 0 | geodCode.c_str(), convAuthName.c_str(), convCode.c_str()); |
2744 | 0 | appendSql(sqlStatements, sql); |
2745 | |
|
2746 | 0 | identifyOrInsertUsages(crs, "projected_crs", authName, code, |
2747 | 0 | allowedAuthorities, sqlStatements); |
2748 | |
|
2749 | 0 | return sqlStatements; |
2750 | 0 | } |
2751 | | |
2752 | | // --------------------------------------------------------------------------- |
2753 | | |
2754 | | std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( |
2755 | | const datum::VerticalReferenceFrameNNPtr &datum, |
2756 | | const std::string &authName, const std::string &code, |
2757 | | bool /* numericCode */, |
2758 | 0 | const std::vector<std::string> &allowedAuthorities) { |
2759 | |
|
2760 | 0 | const auto self = NN_NO_CHECK(self_.lock()); |
2761 | |
|
2762 | 0 | std::vector<std::string> sqlStatements; |
2763 | | |
2764 | | // Check if the object is already known under that code |
2765 | 0 | std::string datumAuthName; |
2766 | 0 | std::string datumCode; |
2767 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, datum, |
2768 | 0 | datumAuthName, datumCode); |
2769 | 0 | if (datumAuthName == authName && datumCode == code) { |
2770 | 0 | return {}; |
2771 | 0 | } |
2772 | | |
2773 | | // Insert new record in vertical_datum table |
2774 | 0 | std::string publicationDate("NULL"); |
2775 | 0 | if (datum->publicationDate().has_value()) { |
2776 | 0 | publicationDate = '\''; |
2777 | 0 | publicationDate += |
2778 | 0 | replaceAll(datum->publicationDate()->toString(), "'", "''"); |
2779 | 0 | publicationDate += '\''; |
2780 | 0 | } |
2781 | 0 | std::string frameReferenceEpoch("NULL"); |
2782 | 0 | const auto dynamicDatum = |
2783 | 0 | dynamic_cast<const datum::DynamicVerticalReferenceFrame *>(datum.get()); |
2784 | 0 | if (dynamicDatum) { |
2785 | 0 | frameReferenceEpoch = |
2786 | 0 | toString(dynamicDatum->frameReferenceEpoch().value()); |
2787 | 0 | } |
2788 | 0 | const std::string anchor(*(datum->anchorDefinition())); |
2789 | 0 | const util::optional<common::Measure> &anchorEpoch = datum->anchorEpoch(); |
2790 | 0 | const auto sql = formatStatement( |
2791 | 0 | "INSERT INTO vertical_datum VALUES(" |
2792 | 0 | "'%q','%q','%q','%q',%s,%s,NULL,%Q,%s,0);", |
2793 | 0 | authName.c_str(), code.c_str(), datum->nameStr().c_str(), |
2794 | 0 | "", // description |
2795 | 0 | publicationDate.c_str(), frameReferenceEpoch.c_str(), |
2796 | 0 | anchor.empty() ? nullptr : anchor.c_str(), |
2797 | 0 | anchorEpoch.has_value() |
2798 | 0 | ? anchorEpochToStr( |
2799 | 0 | anchorEpoch->convertToUnit(common::UnitOfMeasure::YEAR)) |
2800 | 0 | .c_str() |
2801 | 0 | : "NULL"); |
2802 | 0 | appendSql(sqlStatements, sql); |
2803 | |
|
2804 | 0 | identifyOrInsertUsages(datum, "vertical_datum", authName, code, |
2805 | 0 | allowedAuthorities, sqlStatements); |
2806 | |
|
2807 | 0 | return sqlStatements; |
2808 | 0 | } |
2809 | | |
2810 | | // --------------------------------------------------------------------------- |
2811 | | |
2812 | | std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( |
2813 | | const crs::VerticalCRSNNPtr &crs, const std::string &authName, |
2814 | | const std::string &code, bool numericCode, |
2815 | 0 | const std::vector<std::string> &allowedAuthorities) { |
2816 | |
|
2817 | 0 | const auto self = NN_NO_CHECK(self_.lock()); |
2818 | |
|
2819 | 0 | std::vector<std::string> sqlStatements; |
2820 | | |
2821 | | // Find or insert datum/datum ensemble |
2822 | 0 | std::string datumAuthName; |
2823 | 0 | std::string datumCode; |
2824 | 0 | const auto &ensemble = crs->datumEnsemble(); |
2825 | 0 | if (ensemble) { |
2826 | 0 | const auto ensembleNN = NN_NO_CHECK(ensemble); |
2827 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, ensembleNN, |
2828 | 0 | datumAuthName, datumCode); |
2829 | 0 | if (datumAuthName.empty()) { |
2830 | 0 | datumAuthName = authName; |
2831 | 0 | if (numericCode) { |
2832 | 0 | datumCode = |
2833 | 0 | self->suggestsCodeFor(ensembleNN, datumAuthName, true); |
2834 | 0 | } else { |
2835 | 0 | datumCode = "VERTICAL_DATUM_" + code; |
2836 | 0 | } |
2837 | 0 | sqlStatements = self->getInsertStatementsFor( |
2838 | 0 | ensembleNN, datumAuthName, datumCode, numericCode, |
2839 | 0 | allowedAuthorities); |
2840 | 0 | } |
2841 | 0 | } else { |
2842 | 0 | const auto &datum = crs->datum(); |
2843 | 0 | assert(datum); |
2844 | 0 | const auto datumNN = NN_NO_CHECK(datum); |
2845 | 0 | identifyFromNameOrCode(self, allowedAuthorities, authName, datumNN, |
2846 | 0 | datumAuthName, datumCode); |
2847 | 0 | if (datumAuthName.empty()) { |
2848 | 0 | datumAuthName = authName; |
2849 | 0 | if (numericCode) { |
2850 | 0 | datumCode = self->suggestsCodeFor(datumNN, datumAuthName, true); |
2851 | 0 | } else { |
2852 | 0 | datumCode = "VERTICAL_DATUM_" + code; |
2853 | 0 | } |
2854 | 0 | sqlStatements = |
2855 | 0 | self->getInsertStatementsFor(datumNN, datumAuthName, datumCode, |
2856 | 0 | numericCode, allowedAuthorities); |
2857 | 0 | } |
2858 | 0 | } |
2859 | | |
2860 | | // Find or insert coordinate system |
2861 | 0 | const auto &coordinateSystem = crs->coordinateSystem(); |
2862 | 0 | std::string csAuthName; |
2863 | 0 | std::string csCode; |
2864 | 0 | identifyOrInsert(self, coordinateSystem, "VERTICAL_CRS", authName, code, |
2865 | 0 | csAuthName, csCode, sqlStatements); |
2866 | | |
2867 | | // Insert new record in vertical_crs table |
2868 | 0 | const auto sql = |
2869 | 0 | formatStatement("INSERT INTO vertical_crs VALUES(" |
2870 | 0 | "'%q','%q','%q','%q','%q','%q','%q','%q',0);", |
2871 | 0 | authName.c_str(), code.c_str(), crs->nameStr().c_str(), |
2872 | 0 | "", // description |
2873 | 0 | csAuthName.c_str(), csCode.c_str(), |
2874 | 0 | datumAuthName.c_str(), datumCode.c_str()); |
2875 | 0 | appendSql(sqlStatements, sql); |
2876 | |
|
2877 | 0 | identifyOrInsertUsages(crs, "vertical_crs", authName, code, |
2878 | 0 | allowedAuthorities, sqlStatements); |
2879 | |
|
2880 | 0 | return sqlStatements; |
2881 | 0 | } |
2882 | | |
2883 | | // --------------------------------------------------------------------------- |
2884 | | |
2885 | | std::vector<std::string> DatabaseContext::Private::getInsertStatementsFor( |
2886 | | const crs::CompoundCRSNNPtr &crs, const std::string &authName, |
2887 | | const std::string &code, bool numericCode, |
2888 | 0 | const std::vector<std::string> &allowedAuthorities) { |
2889 | |
|
2890 | 0 | const auto self = NN_NO_CHECK(self_.lock()); |
2891 | |
|
2892 | 0 | std::vector<std::string> sqlStatements; |
2893 | |
|
2894 | 0 | int counter = 1; |
2895 | 0 | std::vector<std::pair<std::string, std::string>> componentsId; |
2896 | 0 | const auto &components = crs->componentReferenceSystems(); |
2897 | 0 | if (components.size() != 2) { |
2898 | 0 | throw FactoryException( |
2899 | 0 | "Cannot insert compound CRS with number of components != 2"); |
2900 | 0 | } |
2901 | | |
2902 | 0 | auto allowedAuthoritiesTmp(allowedAuthorities); |
2903 | 0 | allowedAuthoritiesTmp.emplace_back(authName); |
2904 | |
|
2905 | 0 | for (const auto &component : components) { |
2906 | 0 | std::string compAuthName; |
2907 | 0 | std::string compCode; |
2908 | |
|
2909 | 0 | for (const auto &allowedAuthority : allowedAuthoritiesTmp) { |
2910 | 0 | const auto factory = |
2911 | 0 | AuthorityFactory::create(self, allowedAuthority); |
2912 | 0 | const auto candidates = component->identify(factory); |
2913 | 0 | for (const auto &candidate : candidates) { |
2914 | 0 | if (candidate.second == 100) { |
2915 | 0 | const auto &ids = candidate.first->identifiers(); |
2916 | 0 | if (!ids.empty()) { |
2917 | 0 | const auto &id = ids.front(); |
2918 | 0 | compAuthName = *(id->codeSpace()); |
2919 | 0 | compCode = id->code(); |
2920 | 0 | break; |
2921 | 0 | } |
2922 | 0 | } |
2923 | 0 | if (!compAuthName.empty()) { |
2924 | 0 | break; |
2925 | 0 | } |
2926 | 0 | } |
2927 | 0 | } |
2928 | |
|
2929 | 0 | if (compAuthName.empty()) { |
2930 | 0 | compAuthName = authName; |
2931 | 0 | if (numericCode) { |
2932 | 0 | compCode = self->suggestsCodeFor(component, compAuthName, true); |
2933 | 0 | } else { |
2934 | 0 | compCode = "COMPONENT_" + code + '_' + toString(counter); |
2935 | 0 | } |
2936 | 0 | const auto sqlStatementsTmp = |
2937 | 0 | self->getInsertStatementsFor(component, compAuthName, compCode, |
2938 | 0 | numericCode, allowedAuthorities); |
2939 | 0 | sqlStatements.insert(sqlStatements.end(), sqlStatementsTmp.begin(), |
2940 | 0 | sqlStatementsTmp.end()); |
2941 | 0 | } |
2942 | |
|
2943 | 0 | componentsId.emplace_back( |
2944 | 0 | std::pair<std::string, std::string>(compAuthName, compCode)); |
2945 | |
|
2946 | 0 | ++counter; |
2947 | 0 | } |
2948 | | |
2949 | | // Insert new record in compound_crs table |
2950 | 0 | const auto sql = formatStatement( |
2951 | 0 | "INSERT INTO compound_crs VALUES(" |
2952 | 0 | "'%q','%q','%q','%q','%q','%q','%q','%q',0);", |
2953 | 0 | authName.c_str(), code.c_str(), crs->nameStr().c_str(), |
2954 | 0 | "", // description |
2955 | 0 | componentsId[0].first.c_str(), componentsId[0].second.c_str(), |
2956 | 0 | componentsId[1].first.c_str(), componentsId[1].second.c_str()); |
2957 | 0 | appendSql(sqlStatements, sql); |
2958 | |
|
2959 | 0 | identifyOrInsertUsages(crs, "compound_crs", authName, code, |
2960 | 0 | allowedAuthorities, sqlStatements); |
2961 | |
|
2962 | 0 | return sqlStatements; |
2963 | 0 | } |
2964 | | |
2965 | | //! @endcond |
2966 | | |
2967 | | // --------------------------------------------------------------------------- |
2968 | | |
2969 | | //! @cond Doxygen_Suppress |
2970 | 8.61k | DatabaseContext::~DatabaseContext() { |
2971 | 8.61k | try { |
2972 | 8.61k | stopInsertStatementsSession(); |
2973 | 8.61k | } catch (const std::exception &) { |
2974 | 0 | } |
2975 | 8.61k | } |
2976 | | //! @endcond |
2977 | | |
2978 | | // --------------------------------------------------------------------------- |
2979 | | |
2980 | 8.61k | DatabaseContext::DatabaseContext() : d(std::make_unique<Private>()) {} |
2981 | | |
2982 | | // --------------------------------------------------------------------------- |
2983 | | |
2984 | | /** \brief Instantiate a database context. |
2985 | | * |
2986 | | * This database context should be used only by one thread at a time. |
2987 | | * |
2988 | | * @param databasePath Path and filename of the database. Might be empty |
2989 | | * string for the default rules to locate the default proj.db |
2990 | | * @param auxiliaryDatabasePaths Path and filename of auxiliary databases. |
2991 | | * Might be empty. |
2992 | | * Starting with PROJ 8.1, if this parameter is an empty array, |
2993 | | * the PROJ_AUX_DB environment variable will be used, if set. |
2994 | | * It must contain one or several paths. If several paths are |
2995 | | * provided, they must be separated by the colon (:) character on Unix, and |
2996 | | * on Windows, by the semi-colon (;) character. |
2997 | | * @param ctx Context used for file search. |
2998 | | * @throw FactoryException if the database cannot be opened. |
2999 | | */ |
3000 | | DatabaseContextNNPtr |
3001 | | DatabaseContext::create(const std::string &databasePath, |
3002 | | const std::vector<std::string> &auxiliaryDatabasePaths, |
3003 | 8.61k | PJ_CONTEXT *ctx) { |
3004 | 8.61k | auto dbCtx = DatabaseContext::nn_make_shared<DatabaseContext>(); |
3005 | 8.61k | auto dbCtxPrivate = dbCtx->getPrivate(); |
3006 | 8.61k | dbCtxPrivate->open(databasePath, ctx); |
3007 | 8.61k | auto auxDbs(auxiliaryDatabasePaths); |
3008 | 8.61k | if (auxDbs.empty()) { |
3009 | 8.61k | const char *auxDbStr = getenv("PROJ_AUX_DB"); |
3010 | 8.61k | if (auxDbStr) { |
3011 | | #ifdef _WIN32 |
3012 | | const char *delim = ";"; |
3013 | | #else |
3014 | 0 | const char *delim = ":"; |
3015 | 0 | #endif |
3016 | 0 | auxDbs = split(auxDbStr, delim); |
3017 | 0 | } |
3018 | 8.61k | } |
3019 | 8.61k | if (!auxDbs.empty()) { |
3020 | 0 | dbCtxPrivate->attachExtraDatabases(auxDbs); |
3021 | 0 | dbCtxPrivate->auxiliaryDatabasePaths_ = std::move(auxDbs); |
3022 | 0 | } |
3023 | 8.61k | dbCtxPrivate->self_ = dbCtx.as_nullable(); |
3024 | 8.61k | return dbCtx; |
3025 | 8.61k | } |
3026 | | |
3027 | | // --------------------------------------------------------------------------- |
3028 | | |
3029 | | /** \brief Return the list of authorities used in the database. |
3030 | | */ |
3031 | 92 | std::set<std::string> DatabaseContext::getAuthorities() const { |
3032 | 92 | auto res = d->run("SELECT auth_name FROM authority_list"); |
3033 | 92 | std::set<std::string> list; |
3034 | 736 | for (const auto &row : res) { |
3035 | 736 | list.insert(row[0]); |
3036 | 736 | } |
3037 | 92 | return list; |
3038 | 92 | } |
3039 | | |
3040 | | // --------------------------------------------------------------------------- |
3041 | | |
3042 | | /** \brief Return the list of SQL commands (CREATE TABLE, CREATE TRIGGER, |
3043 | | * CREATE VIEW) needed to initialize a new database. |
3044 | | */ |
3045 | 0 | std::vector<std::string> DatabaseContext::getDatabaseStructure() const { |
3046 | 0 | return d->getDatabaseStructure(); |
3047 | 0 | } |
3048 | | |
3049 | | // --------------------------------------------------------------------------- |
3050 | | |
3051 | | /** \brief Return the path to the database. |
3052 | | */ |
3053 | 0 | const std::string &DatabaseContext::getPath() const { return d->getPath(); } |
3054 | | |
3055 | | // --------------------------------------------------------------------------- |
3056 | | |
3057 | | /** \brief Return a metadata item. |
3058 | | * |
3059 | | * Value remains valid while this is alive and to the next call to getMetadata |
3060 | | */ |
3061 | 0 | const char *DatabaseContext::getMetadata(const char *key) const { |
3062 | 0 | auto res = |
3063 | 0 | d->run("SELECT value FROM metadata WHERE key = ?", {std::string(key)}); |
3064 | 0 | if (res.empty()) { |
3065 | 0 | return nullptr; |
3066 | 0 | } |
3067 | 0 | d->lastMetadataValue_ = res.front()[0]; |
3068 | 0 | return d->lastMetadataValue_.c_str(); |
3069 | 0 | } |
3070 | | |
3071 | | // --------------------------------------------------------------------------- |
3072 | | |
3073 | | /** \brief Starts a session for getInsertStatementsFor() |
3074 | | * |
3075 | | * Starts a new session for one or several calls to getInsertStatementsFor(). |
3076 | | * An insertion session guarantees that the inserted objects will not create |
3077 | | * conflicting intermediate objects. |
3078 | | * |
3079 | | * The session must be stopped with stopInsertStatementsSession(). |
3080 | | * |
3081 | | * Only one session may be active at a time for a given database context. |
3082 | | * |
3083 | | * @throw FactoryException in case of error. |
3084 | | * @since 8.1 |
3085 | | */ |
3086 | 0 | void DatabaseContext::startInsertStatementsSession() { |
3087 | 0 | if (d->memoryDbHandle_) { |
3088 | 0 | throw FactoryException( |
3089 | 0 | "startInsertStatementsSession() cannot be invoked until " |
3090 | 0 | "stopInsertStatementsSession() is."); |
3091 | 0 | } |
3092 | | |
3093 | 0 | d->memoryDbForInsertPath_.clear(); |
3094 | 0 | const auto sqlStatements = getDatabaseStructure(); |
3095 | | |
3096 | | // Create a in-memory temporary sqlite3 database |
3097 | 0 | std::ostringstream buffer; |
3098 | 0 | buffer << "file:temp_db_for_insert_statements_"; |
3099 | 0 | buffer << this; |
3100 | 0 | buffer << ".db?mode=memory&cache=shared"; |
3101 | 0 | d->memoryDbForInsertPath_ = buffer.str(); |
3102 | 0 | sqlite3 *memoryDbHandle = nullptr; |
3103 | 0 | sqlite3_open_v2( |
3104 | 0 | d->memoryDbForInsertPath_.c_str(), &memoryDbHandle, |
3105 | 0 | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI, nullptr); |
3106 | 0 | if (memoryDbHandle == nullptr) { |
3107 | 0 | throw FactoryException("Cannot create in-memory database"); |
3108 | 0 | } |
3109 | 0 | d->memoryDbHandle_ = |
3110 | 0 | SQLiteHandle::initFromExistingUniquePtr(memoryDbHandle, true); |
3111 | | |
3112 | | // Fill the structure of this database |
3113 | 0 | for (const auto &sql : sqlStatements) { |
3114 | 0 | char *errmsg = nullptr; |
3115 | 0 | if (sqlite3_exec(d->memoryDbHandle_->handle(), sql.c_str(), nullptr, |
3116 | 0 | nullptr, &errmsg) != SQLITE_OK) { |
3117 | 0 | const auto sErrMsg = |
3118 | 0 | "Cannot execute " + sql + ": " + (errmsg ? errmsg : ""); |
3119 | 0 | sqlite3_free(errmsg); |
3120 | 0 | throw FactoryException(sErrMsg); |
3121 | 0 | } |
3122 | 0 | sqlite3_free(errmsg); |
3123 | 0 | } |
3124 | | |
3125 | | // Attach this database to the current one(s) |
3126 | 0 | auto auxiliaryDatabasePaths(d->auxiliaryDatabasePaths_); |
3127 | 0 | auxiliaryDatabasePaths.push_back(d->memoryDbForInsertPath_); |
3128 | 0 | d->attachExtraDatabases(auxiliaryDatabasePaths); |
3129 | 0 | } |
3130 | | |
3131 | | // --------------------------------------------------------------------------- |
3132 | | |
3133 | | /** \brief Suggests a database code for the passed object. |
3134 | | * |
3135 | | * Supported type of objects are PrimeMeridian, Ellipsoid, Datum, DatumEnsemble, |
3136 | | * GeodeticCRS, ProjectedCRS, VerticalCRS, CompoundCRS, BoundCRS, Conversion. |
3137 | | * |
3138 | | * @param object Object for which to suggest a code. |
3139 | | * @param authName Authority name into which the object will be inserted. |
3140 | | * @param numericCode Whether the code should be numeric, or derived from the |
3141 | | * object name. |
3142 | | * @return the suggested code, that is guaranteed to not conflict with an |
3143 | | * existing one. |
3144 | | * |
3145 | | * @throw FactoryException in case of error. |
3146 | | * @since 8.1 |
3147 | | */ |
3148 | | std::string |
3149 | | DatabaseContext::suggestsCodeFor(const common::IdentifiedObjectNNPtr &object, |
3150 | | const std::string &authName, |
3151 | 0 | bool numericCode) { |
3152 | 0 | const char *tableName = "prime_meridian"; |
3153 | 0 | if (dynamic_cast<const datum::PrimeMeridian *>(object.get())) { |
3154 | | // tableName = "prime_meridian"; |
3155 | 0 | } else if (dynamic_cast<const datum::Ellipsoid *>(object.get())) { |
3156 | 0 | tableName = "ellipsoid"; |
3157 | 0 | } else if (dynamic_cast<const datum::GeodeticReferenceFrame *>( |
3158 | 0 | object.get())) { |
3159 | 0 | tableName = "geodetic_datum"; |
3160 | 0 | } else if (dynamic_cast<const datum::VerticalReferenceFrame *>( |
3161 | 0 | object.get())) { |
3162 | 0 | tableName = "vertical_datum"; |
3163 | 0 | } else if (const auto ensemble = |
3164 | 0 | dynamic_cast<const datum::DatumEnsemble *>(object.get())) { |
3165 | 0 | const auto &datums = ensemble->datums(); |
3166 | 0 | if (!datums.empty() && |
3167 | 0 | dynamic_cast<const datum::GeodeticReferenceFrame *>( |
3168 | 0 | datums[0].get())) { |
3169 | 0 | tableName = "geodetic_datum"; |
3170 | 0 | } else { |
3171 | 0 | tableName = "vertical_datum"; |
3172 | 0 | } |
3173 | 0 | } else if (const auto boundCRS = |
3174 | 0 | dynamic_cast<const crs::BoundCRS *>(object.get())) { |
3175 | 0 | return suggestsCodeFor(boundCRS->baseCRS(), authName, numericCode); |
3176 | 0 | } else if (dynamic_cast<const crs::CRS *>(object.get())) { |
3177 | 0 | tableName = "crs_view"; |
3178 | 0 | } else if (dynamic_cast<const operation::Conversion *>(object.get())) { |
3179 | 0 | tableName = "conversion"; |
3180 | 0 | } else { |
3181 | 0 | throw FactoryException("suggestsCodeFor(): unhandled type of object"); |
3182 | 0 | } |
3183 | | |
3184 | 0 | if (numericCode) { |
3185 | 0 | std::string sql("SELECT MAX(code) FROM "); |
3186 | 0 | sql += tableName; |
3187 | 0 | sql += " WHERE auth_name = ? AND code >= '1' AND code <= '999999999' " |
3188 | 0 | "AND upper(code) = lower(code)"; |
3189 | 0 | const auto res = d->run(sql, {authName}); |
3190 | 0 | if (res.empty()) { |
3191 | 0 | return "1"; |
3192 | 0 | } |
3193 | 0 | return toString(atoi(res.front()[0].c_str()) + 1); |
3194 | 0 | } |
3195 | | |
3196 | 0 | std::string code; |
3197 | 0 | code.reserve(object->nameStr().size()); |
3198 | 0 | bool insertUnderscore = false; |
3199 | 0 | for (const auto ch : toupper(object->nameStr())) { |
3200 | 0 | if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z')) { |
3201 | 0 | if (insertUnderscore && code.back() != '_') |
3202 | 0 | code += '_'; |
3203 | 0 | code += ch; |
3204 | 0 | insertUnderscore = false; |
3205 | 0 | } else { |
3206 | 0 | insertUnderscore = true; |
3207 | 0 | } |
3208 | 0 | } |
3209 | 0 | return d->findFreeCode(tableName, authName, code); |
3210 | 0 | } |
3211 | | |
3212 | | // --------------------------------------------------------------------------- |
3213 | | |
3214 | | /** \brief Returns SQL statements needed to insert the passed object into the |
3215 | | * database. |
3216 | | * |
3217 | | * startInsertStatementsSession() must have been called previously. |
3218 | | * |
3219 | | * @param object The object to insert into the database. Currently only |
3220 | | * PrimeMeridian, Ellipsoid, Datum, GeodeticCRS, ProjectedCRS, |
3221 | | * VerticalCRS, CompoundCRS or BoundCRS are supported. |
3222 | | * @param authName Authority name into which the object will be inserted. |
3223 | | * @param code Code with which the object will be inserted. |
3224 | | * @param numericCode Whether intermediate objects that can be created should |
3225 | | * use numeric codes (true), or may be alphanumeric (false) |
3226 | | * @param allowedAuthorities Authorities to which intermediate objects are |
3227 | | * allowed to refer to. authName will be implicitly |
3228 | | * added to it. Note that unit, coordinate |
3229 | | * systems, projection methods and parameters will in |
3230 | | * any case be allowed to refer to EPSG. |
3231 | | * @throw FactoryException in case of error. |
3232 | | * @since 8.1 |
3233 | | */ |
3234 | | std::vector<std::string> DatabaseContext::getInsertStatementsFor( |
3235 | | const common::IdentifiedObjectNNPtr &object, const std::string &authName, |
3236 | | const std::string &code, bool numericCode, |
3237 | 0 | const std::vector<std::string> &allowedAuthorities) { |
3238 | 0 | if (d->memoryDbHandle_ == nullptr) { |
3239 | 0 | throw FactoryException( |
3240 | 0 | "startInsertStatementsSession() should be invoked first"); |
3241 | 0 | } |
3242 | | |
3243 | 0 | const auto crs = util::nn_dynamic_pointer_cast<crs::CRS>(object); |
3244 | 0 | if (crs) { |
3245 | | // Check if the object is already known under that code |
3246 | 0 | const auto self = NN_NO_CHECK(d->self_.lock()); |
3247 | 0 | auto allowedAuthoritiesTmp(allowedAuthorities); |
3248 | 0 | allowedAuthoritiesTmp.emplace_back(authName); |
3249 | 0 | for (const auto &allowedAuthority : allowedAuthoritiesTmp) { |
3250 | 0 | const auto factory = |
3251 | 0 | AuthorityFactory::create(self, allowedAuthority); |
3252 | 0 | const auto candidates = crs->identify(factory); |
3253 | 0 | for (const auto &candidate : candidates) { |
3254 | 0 | if (candidate.second == 100) { |
3255 | 0 | const auto &ids = candidate.first->identifiers(); |
3256 | 0 | for (const auto &id : ids) { |
3257 | 0 | if (*(id->codeSpace()) == authName && |
3258 | 0 | id->code() == code) { |
3259 | 0 | return {}; |
3260 | 0 | } |
3261 | 0 | } |
3262 | 0 | } |
3263 | 0 | } |
3264 | 0 | } |
3265 | 0 | } |
3266 | | |
3267 | 0 | if (const auto pm = |
3268 | 0 | util::nn_dynamic_pointer_cast<datum::PrimeMeridian>(object)) { |
3269 | 0 | return d->getInsertStatementsFor(NN_NO_CHECK(pm), authName, code, |
3270 | 0 | numericCode, allowedAuthorities); |
3271 | 0 | } |
3272 | | |
3273 | 0 | else if (const auto ellipsoid = |
3274 | 0 | util::nn_dynamic_pointer_cast<datum::Ellipsoid>(object)) { |
3275 | 0 | return d->getInsertStatementsFor(NN_NO_CHECK(ellipsoid), authName, code, |
3276 | 0 | numericCode, allowedAuthorities); |
3277 | 0 | } |
3278 | | |
3279 | 0 | else if (const auto geodeticDatum = |
3280 | 0 | util::nn_dynamic_pointer_cast<datum::GeodeticReferenceFrame>( |
3281 | 0 | object)) { |
3282 | 0 | return d->getInsertStatementsFor(NN_NO_CHECK(geodeticDatum), authName, |
3283 | 0 | code, numericCode, allowedAuthorities); |
3284 | 0 | } |
3285 | | |
3286 | 0 | else if (const auto ensemble = |
3287 | 0 | util::nn_dynamic_pointer_cast<datum::DatumEnsemble>(object)) { |
3288 | 0 | return d->getInsertStatementsFor(NN_NO_CHECK(ensemble), authName, code, |
3289 | 0 | numericCode, allowedAuthorities); |
3290 | 0 | } |
3291 | | |
3292 | 0 | else if (const auto geodCRS = |
3293 | 0 | std::dynamic_pointer_cast<crs::GeodeticCRS>(crs)) { |
3294 | 0 | return d->getInsertStatementsFor(NN_NO_CHECK(geodCRS), authName, code, |
3295 | 0 | numericCode, allowedAuthorities); |
3296 | 0 | } |
3297 | | |
3298 | 0 | else if (const auto projCRS = |
3299 | 0 | std::dynamic_pointer_cast<crs::ProjectedCRS>(crs)) { |
3300 | 0 | return d->getInsertStatementsFor(NN_NO_CHECK(projCRS), authName, code, |
3301 | 0 | numericCode, allowedAuthorities); |
3302 | 0 | } |
3303 | | |
3304 | 0 | else if (const auto verticalDatum = |
3305 | 0 | util::nn_dynamic_pointer_cast<datum::VerticalReferenceFrame>( |
3306 | 0 | object)) { |
3307 | 0 | return d->getInsertStatementsFor(NN_NO_CHECK(verticalDatum), authName, |
3308 | 0 | code, numericCode, allowedAuthorities); |
3309 | 0 | } |
3310 | | |
3311 | 0 | else if (const auto vertCRS = |
3312 | 0 | std::dynamic_pointer_cast<crs::VerticalCRS>(crs)) { |
3313 | 0 | return d->getInsertStatementsFor(NN_NO_CHECK(vertCRS), authName, code, |
3314 | 0 | numericCode, allowedAuthorities); |
3315 | 0 | } |
3316 | | |
3317 | 0 | else if (const auto compoundCRS = |
3318 | 0 | std::dynamic_pointer_cast<crs::CompoundCRS>(crs)) { |
3319 | 0 | return d->getInsertStatementsFor(NN_NO_CHECK(compoundCRS), authName, |
3320 | 0 | code, numericCode, allowedAuthorities); |
3321 | 0 | } |
3322 | | |
3323 | 0 | else if (const auto boundCRS = |
3324 | 0 | std::dynamic_pointer_cast<crs::BoundCRS>(crs)) { |
3325 | 0 | return getInsertStatementsFor(boundCRS->baseCRS(), authName, code, |
3326 | 0 | numericCode, allowedAuthorities); |
3327 | 0 | } |
3328 | | |
3329 | 0 | else { |
3330 | 0 | throw FactoryException( |
3331 | 0 | "getInsertStatementsFor(): unhandled type of object"); |
3332 | 0 | } |
3333 | 0 | } |
3334 | | |
3335 | | // --------------------------------------------------------------------------- |
3336 | | |
3337 | | /** \brief Stops an insertion session started with |
3338 | | * startInsertStatementsSession() |
3339 | | * |
3340 | | * @since 8.1 |
3341 | | */ |
3342 | 8.61k | void DatabaseContext::stopInsertStatementsSession() { |
3343 | 8.61k | if (d->memoryDbHandle_) { |
3344 | 0 | d->clearCaches(); |
3345 | 0 | d->attachExtraDatabases(d->auxiliaryDatabasePaths_); |
3346 | 0 | d->memoryDbHandle_.reset(); |
3347 | 0 | d->memoryDbForInsertPath_.clear(); |
3348 | 0 | } |
3349 | 8.61k | } |
3350 | | |
3351 | | // --------------------------------------------------------------------------- |
3352 | | |
3353 | | //! @cond Doxygen_Suppress |
3354 | | |
3355 | 0 | DatabaseContextNNPtr DatabaseContext::create(void *sqlite_handle) { |
3356 | 0 | auto ctxt = DatabaseContext::nn_make_shared<DatabaseContext>(); |
3357 | 0 | ctxt->getPrivate()->setHandle(static_cast<sqlite3 *>(sqlite_handle)); |
3358 | 0 | return ctxt; |
3359 | 0 | } |
3360 | | |
3361 | | // --------------------------------------------------------------------------- |
3362 | | |
3363 | 0 | void *DatabaseContext::getSqliteHandle() const { return d->handle()->handle(); } |
3364 | | |
3365 | | // --------------------------------------------------------------------------- |
3366 | | |
3367 | | bool DatabaseContext::lookForGridAlternative(const std::string &officialName, |
3368 | | std::string &projFilename, |
3369 | | std::string &projFormat, |
3370 | 98.2k | bool &inverse) const { |
3371 | 98.2k | auto res = d->run( |
3372 | 98.2k | "SELECT proj_grid_name, proj_grid_format, inverse_direction FROM " |
3373 | 98.2k | "grid_alternatives WHERE original_grid_name = ? AND " |
3374 | 98.2k | "proj_grid_name <> ''", |
3375 | 98.2k | {officialName}); |
3376 | 98.2k | if (res.empty()) { |
3377 | 2.06k | return false; |
3378 | 2.06k | } |
3379 | 96.1k | const auto &row = res.front(); |
3380 | 96.1k | projFilename = row[0]; |
3381 | 96.1k | projFormat = row[1]; |
3382 | 96.1k | inverse = row[2] == "1"; |
3383 | 96.1k | return true; |
3384 | 98.2k | } |
3385 | | |
3386 | | // --------------------------------------------------------------------------- |
3387 | | |
3388 | | static std::string makeCachedGridKey(const std::string &projFilename, |
3389 | | bool networkEnabled, |
3390 | 123k | bool considerKnownGridsAsAvailable) { |
3391 | 123k | std::string key(projFilename); |
3392 | 123k | key += networkEnabled ? "true" : "false"; |
3393 | 123k | key += considerKnownGridsAsAvailable ? "true" : "false"; |
3394 | 123k | return key; |
3395 | 123k | } |
3396 | | |
3397 | | // --------------------------------------------------------------------------- |
3398 | | |
3399 | | /** Invalidates information related to projFilename that might have been |
3400 | | * previously cached by lookForGridInfo(). |
3401 | | * |
3402 | | * This is useful when downloading a new grid during a session. |
3403 | | */ |
3404 | 0 | void DatabaseContext::invalidateGridInfo(const std::string &projFilename) { |
3405 | 0 | d->evictGridInfoFromCache(makeCachedGridKey(projFilename, false, false)); |
3406 | 0 | d->evictGridInfoFromCache(makeCachedGridKey(projFilename, false, true)); |
3407 | 0 | d->evictGridInfoFromCache(makeCachedGridKey(projFilename, true, false)); |
3408 | 0 | d->evictGridInfoFromCache(makeCachedGridKey(projFilename, true, true)); |
3409 | 0 | } |
3410 | | |
3411 | | // --------------------------------------------------------------------------- |
3412 | | |
3413 | | bool DatabaseContext::lookForGridInfo( |
3414 | | const std::string &projFilename, bool considerKnownGridsAsAvailable, |
3415 | | std::string &fullFilename, std::string &packageName, std::string &url, |
3416 | 124k | bool &directDownload, bool &openLicense, bool &gridAvailable) const { |
3417 | 124k | Private::GridInfoCache info; |
3418 | | |
3419 | 124k | if (projFilename == "null") { |
3420 | | // Special case for implicit "null" grid. |
3421 | 190 | fullFilename.clear(); |
3422 | 190 | packageName.clear(); |
3423 | 190 | url.clear(); |
3424 | 190 | directDownload = false; |
3425 | 190 | openLicense = true; |
3426 | 190 | gridAvailable = true; |
3427 | 190 | return true; |
3428 | 190 | } |
3429 | | |
3430 | 123k | auto ctxt = d->pjCtxt(); |
3431 | 123k | if (ctxt == nullptr) { |
3432 | 0 | ctxt = pj_get_default_ctx(); |
3433 | 0 | d->setPjCtxt(ctxt); |
3434 | 0 | } |
3435 | | |
3436 | 123k | const std::string key(makeCachedGridKey( |
3437 | 123k | projFilename, proj_context_is_network_enabled(ctxt) != false, |
3438 | 123k | considerKnownGridsAsAvailable)); |
3439 | 123k | if (d->getGridInfoFromCache(key, info)) { |
3440 | 97.0k | fullFilename = info.fullFilename; |
3441 | 97.0k | packageName = info.packageName; |
3442 | 97.0k | url = info.url; |
3443 | 97.0k | directDownload = info.directDownload; |
3444 | 97.0k | openLicense = info.openLicense; |
3445 | 97.0k | gridAvailable = info.gridAvailable; |
3446 | 97.0k | return info.found; |
3447 | 97.0k | } |
3448 | | |
3449 | 26.8k | fullFilename.clear(); |
3450 | 26.8k | packageName.clear(); |
3451 | 26.8k | url.clear(); |
3452 | 26.8k | openLicense = false; |
3453 | 26.8k | directDownload = false; |
3454 | 26.8k | gridAvailable = false; |
3455 | | |
3456 | 26.8k | const auto resolveFullFilename = [ctxt, &fullFilename, &projFilename]() { |
3457 | 26.8k | fullFilename.resize(2048); |
3458 | 26.8k | const int errno_before = proj_context_errno(ctxt); |
3459 | 26.8k | bool lGridAvailable = NS_PROJ::FileManager::open_resource_file( |
3460 | 26.8k | ctxt, projFilename.c_str(), &fullFilename[0], |
3461 | 26.8k | fullFilename.size() - 1) != nullptr; |
3462 | 26.8k | proj_context_errno_set(ctxt, errno_before); |
3463 | 26.8k | fullFilename.resize(strlen(fullFilename.c_str())); |
3464 | 26.8k | return lGridAvailable; |
3465 | 26.8k | }; |
3466 | | |
3467 | 26.8k | auto res = |
3468 | 26.8k | d->run("SELECT " |
3469 | 26.8k | "grid_packages.package_name, " |
3470 | 26.8k | "grid_alternatives.url, " |
3471 | 26.8k | "grid_packages.url AS package_url, " |
3472 | 26.8k | "grid_alternatives.open_license, " |
3473 | 26.8k | "grid_packages.open_license AS package_open_license, " |
3474 | 26.8k | "grid_alternatives.direct_download, " |
3475 | 26.8k | "grid_packages.direct_download AS package_direct_download, " |
3476 | 26.8k | "grid_alternatives.proj_grid_name, " |
3477 | 26.8k | "grid_alternatives.old_proj_grid_name " |
3478 | 26.8k | "FROM grid_alternatives " |
3479 | 26.8k | "LEFT JOIN grid_packages ON " |
3480 | 26.8k | "grid_alternatives.package_name = grid_packages.package_name " |
3481 | 26.8k | "WHERE proj_grid_name = ? OR old_proj_grid_name = ?", |
3482 | 26.8k | {projFilename, projFilename}); |
3483 | 26.8k | bool ret = !res.empty(); |
3484 | 26.8k | if (ret) { |
3485 | 19.1k | const auto &row = res.front(); |
3486 | 19.1k | packageName = std::move(row[0]); |
3487 | 19.1k | url = row[1].empty() ? std::move(row[2]) : std::move(row[1]); |
3488 | 19.1k | openLicense = (row[3].empty() ? row[4] : row[3]) == "1"; |
3489 | 19.1k | directDownload = (row[5].empty() ? row[6] : row[5]) == "1"; |
3490 | | |
3491 | 19.1k | const auto &proj_grid_name = row[7]; |
3492 | 19.1k | const auto &old_proj_grid_name = row[8]; |
3493 | 19.1k | if (proj_grid_name != old_proj_grid_name && |
3494 | 19.1k | old_proj_grid_name == projFilename) { |
3495 | 65 | std::string fullFilenameNewName; |
3496 | 65 | fullFilenameNewName.resize(2048); |
3497 | 65 | const int errno_before = proj_context_errno(ctxt); |
3498 | 65 | bool gridAvailableWithNewName = |
3499 | 65 | pj_find_file(ctxt, proj_grid_name.c_str(), |
3500 | 65 | &fullFilenameNewName[0], |
3501 | 65 | fullFilenameNewName.size() - 1) != 0; |
3502 | 65 | proj_context_errno_set(ctxt, errno_before); |
3503 | 65 | fullFilenameNewName.resize(strlen(fullFilenameNewName.c_str())); |
3504 | 65 | if (gridAvailableWithNewName) { |
3505 | 0 | gridAvailable = true; |
3506 | 0 | fullFilename = std::move(fullFilenameNewName); |
3507 | 0 | } |
3508 | 65 | } |
3509 | | |
3510 | 19.1k | if (!gridAvailable && considerKnownGridsAsAvailable && |
3511 | 19.1k | (!packageName.empty() || (!url.empty() && openLicense))) { |
3512 | | |
3513 | | // In considerKnownGridsAsAvailable mode, try to fetch the local |
3514 | | // file name if it exists, but do not attempt network access. |
3515 | 2 | const auto network_was_enabled = |
3516 | 2 | proj_context_is_network_enabled(ctxt); |
3517 | 2 | proj_context_set_enable_network(ctxt, false); |
3518 | 2 | (void)resolveFullFilename(); |
3519 | 2 | proj_context_set_enable_network(ctxt, network_was_enabled); |
3520 | | |
3521 | 2 | gridAvailable = true; |
3522 | 2 | } |
3523 | | |
3524 | 19.1k | info.packageName = packageName; |
3525 | 19.1k | std::string endpoint(proj_context_get_url_endpoint(d->pjCtxt())); |
3526 | 19.1k | if (!endpoint.empty() && starts_with(url, "https://cdn.proj.org/")) { |
3527 | 19.0k | if (endpoint.back() != '/') { |
3528 | 19.0k | endpoint += '/'; |
3529 | 19.0k | } |
3530 | 19.0k | url = endpoint + url.substr(strlen("https://cdn.proj.org/")); |
3531 | 19.0k | } |
3532 | 19.1k | info.directDownload = directDownload; |
3533 | 19.1k | info.openLicense = openLicense; |
3534 | | |
3535 | 19.1k | if (!gridAvailable) { |
3536 | 19.1k | gridAvailable = resolveFullFilename(); |
3537 | 19.1k | } |
3538 | 19.1k | } else { |
3539 | 7.67k | gridAvailable = resolveFullFilename(); |
3540 | | |
3541 | 7.67k | if (starts_with(fullFilename, "http://") || |
3542 | 7.67k | starts_with(fullFilename, "https://")) { |
3543 | 0 | url = fullFilename; |
3544 | 0 | fullFilename.clear(); |
3545 | 0 | } |
3546 | 7.67k | } |
3547 | | |
3548 | 26.8k | info.fullFilename = fullFilename; |
3549 | 26.8k | info.url = url; |
3550 | 26.8k | info.gridAvailable = gridAvailable; |
3551 | 26.8k | info.found = ret; |
3552 | 26.8k | d->cache(key, info); |
3553 | 26.8k | return ret; |
3554 | 123k | } |
3555 | | |
3556 | | // --------------------------------------------------------------------------- |
3557 | | |
3558 | | /** Returns the number of queries to the database since the creation of this |
3559 | | * instance. |
3560 | | */ |
3561 | 0 | unsigned int DatabaseContext::getQueryCounter() const { |
3562 | 0 | return d->queryCounter_; |
3563 | 0 | } |
3564 | | |
3565 | | // --------------------------------------------------------------------------- |
3566 | | |
3567 | | bool DatabaseContext::isKnownName(const std::string &name, |
3568 | 0 | const std::string &tableName) const { |
3569 | 0 | std::string sql("SELECT 1 FROM \""); |
3570 | 0 | sql += replaceAll(tableName, "\"", "\"\""); |
3571 | 0 | sql += "\" WHERE name = ? LIMIT 1"; |
3572 | 0 | return !d->run(sql, {name}).empty(); |
3573 | 0 | } |
3574 | | // --------------------------------------------------------------------------- |
3575 | | |
3576 | | std::string |
3577 | 22.4k | DatabaseContext::getProjGridName(const std::string &oldProjGridName) { |
3578 | 22.4k | auto res = d->run("SELECT proj_grid_name FROM grid_alternatives WHERE " |
3579 | 22.4k | "old_proj_grid_name = ?", |
3580 | 22.4k | {oldProjGridName}); |
3581 | 22.4k | if (res.empty()) { |
3582 | 22.0k | return std::string(); |
3583 | 22.0k | } |
3584 | 326 | return res.front()[0]; |
3585 | 22.4k | } |
3586 | | |
3587 | | // --------------------------------------------------------------------------- |
3588 | | |
3589 | 19.3k | std::string DatabaseContext::getOldProjGridName(const std::string &gridName) { |
3590 | 19.3k | auto res = d->run("SELECT old_proj_grid_name FROM grid_alternatives WHERE " |
3591 | 19.3k | "proj_grid_name = ?", |
3592 | 19.3k | {gridName}); |
3593 | 19.3k | if (res.empty()) { |
3594 | 294 | return std::string(); |
3595 | 294 | } |
3596 | 19.0k | return res.front()[0]; |
3597 | 19.3k | } |
3598 | | |
3599 | | // --------------------------------------------------------------------------- |
3600 | | |
3601 | | // scripts/build_db_from_esri.py adds a second alias for |
3602 | | // names that have '[' in them. See get_old_esri_name() |
3603 | | // in scripts/build_db_from_esri.py |
3604 | | // So if we only have two aliases detect that situation to get the official |
3605 | | // new name |
3606 | 0 | static std::string getUniqueEsriAlias(const std::list<std::string> &l) { |
3607 | 0 | std::string first = l.front(); |
3608 | 0 | std::string second = *(std::next(l.begin())); |
3609 | 0 | if (second.find('[') != std::string::npos) |
3610 | 0 | std::swap(first, second); |
3611 | 0 | if (replaceAll(replaceAll(replaceAll(first, "[", ""), "]", ""), "-", "_") == |
3612 | 0 | second) { |
3613 | 0 | return first; |
3614 | 0 | } |
3615 | 0 | return std::string(); |
3616 | 0 | } |
3617 | | |
3618 | | // --------------------------------------------------------------------------- |
3619 | | |
3620 | | /** \brief Gets the alias name from an official name. |
3621 | | * |
3622 | | * @param officialName Official name. Mandatory |
3623 | | * @param tableName Table name/category. Mandatory. |
3624 | | * "geographic_2D_crs" and "geographic_3D_crs" are also |
3625 | | * accepted as special names to add a constraint on the "type" |
3626 | | * column of the "geodetic_crs" table. |
3627 | | * @param source Source of the alias. Mandatory |
3628 | | * @return Alias name (or empty if not found). |
3629 | | * @throw FactoryException in case of error. |
3630 | | */ |
3631 | | std::string |
3632 | | DatabaseContext::getAliasFromOfficialName(const std::string &officialName, |
3633 | | const std::string &tableName, |
3634 | 0 | const std::string &source) const { |
3635 | 0 | std::string sql("SELECT auth_name, code FROM \""); |
3636 | 0 | const auto genuineTableName = |
3637 | 0 | tableName == "geographic_2D_crs" || tableName == "geographic_3D_crs" |
3638 | 0 | ? "geodetic_crs" |
3639 | 0 | : tableName; |
3640 | 0 | sql += replaceAll(genuineTableName, "\"", "\"\""); |
3641 | 0 | sql += "\" WHERE name = ?"; |
3642 | 0 | if (tableName == "geodetic_crs" || tableName == "geographic_2D_crs") { |
3643 | 0 | sql += " AND type = " GEOG_2D_SINGLE_QUOTED; |
3644 | 0 | } else if (tableName == "geographic_3D_crs") { |
3645 | 0 | sql += " AND type = " GEOG_3D_SINGLE_QUOTED; |
3646 | 0 | } |
3647 | 0 | sql += " ORDER BY deprecated"; |
3648 | 0 | auto res = d->run(sql, {officialName}); |
3649 | | // Sorry for the hack excluding NAD83 + geographic_3D_crs, but otherwise |
3650 | | // EPSG has a weird alias from NAD83 to EPSG:4152 which happens to be |
3651 | | // NAD83(HARN), and that's definitely not desirable. |
3652 | 0 | if (res.empty() && |
3653 | 0 | !(officialName == "NAD83" && tableName == "geographic_3D_crs")) { |
3654 | 0 | res = d->run( |
3655 | 0 | "SELECT auth_name, code FROM alias_name WHERE table_name = ? AND " |
3656 | 0 | "alt_name = ? AND source IN ('EPSG', 'PROJ')", |
3657 | 0 | {genuineTableName, officialName}); |
3658 | 0 | if (res.size() != 1) { |
3659 | 0 | return std::string(); |
3660 | 0 | } |
3661 | 0 | } |
3662 | 0 | for (const auto &row : res) { |
3663 | 0 | auto res2 = |
3664 | 0 | d->run("SELECT alt_name FROM alias_name WHERE table_name = ? AND " |
3665 | 0 | "auth_name = ? AND code = ? AND source = ?", |
3666 | 0 | {genuineTableName, row[0], row[1], source}); |
3667 | 0 | if (!res2.empty()) { |
3668 | 0 | if (res2.size() == 2 && source == "ESRI") { |
3669 | 0 | std::list<std::string> l; |
3670 | 0 | l.emplace_back(res2.front()[0]); |
3671 | 0 | l.emplace_back((*(std::next(res2.begin())))[0]); |
3672 | 0 | std::string uniqueEsriAlias = getUniqueEsriAlias(l); |
3673 | 0 | if (!uniqueEsriAlias.empty()) |
3674 | 0 | return uniqueEsriAlias; |
3675 | 0 | } |
3676 | 0 | return res2.front()[0]; |
3677 | 0 | } |
3678 | 0 | } |
3679 | 0 | return std::string(); |
3680 | 0 | } |
3681 | | |
3682 | | // --------------------------------------------------------------------------- |
3683 | | |
3684 | | /** \brief Gets the alias names for an object. |
3685 | | * |
3686 | | * Either authName + code or officialName must be non empty. |
3687 | | * |
3688 | | * @param authName Authority. |
3689 | | * @param code Code. |
3690 | | * @param officialName Official name. |
3691 | | * @param tableName Table name/category. Mandatory. |
3692 | | * "geographic_2D_crs" and "geographic_3D_crs" are also |
3693 | | * accepted as special names to add a constraint on the "type" |
3694 | | * column of the "geodetic_crs" table. |
3695 | | * @param source Source of the alias. May be empty. |
3696 | | * @return Aliases |
3697 | | */ |
3698 | | std::list<std::string> DatabaseContext::getAliases( |
3699 | | const std::string &authName, const std::string &code, |
3700 | | const std::string &officialName, const std::string &tableName, |
3701 | 67.4k | const std::string &source) const { |
3702 | | |
3703 | 67.4k | std::list<std::string> res; |
3704 | 67.4k | const auto key(authName + code + officialName + tableName + source); |
3705 | 67.4k | if (d->cacheAliasNames_.tryGet(key, res)) { |
3706 | 65.1k | return res; |
3707 | 65.1k | } |
3708 | | |
3709 | 2.32k | std::string resolvedAuthName(authName); |
3710 | 2.32k | std::string resolvedCode(code); |
3711 | 2.32k | const auto genuineTableName = |
3712 | 2.32k | tableName == "geographic_2D_crs" || tableName == "geographic_3D_crs" |
3713 | 2.32k | ? "geodetic_crs" |
3714 | 2.32k | : tableName; |
3715 | 2.32k | if (authName.empty() || code.empty()) { |
3716 | 63 | std::string sql("SELECT auth_name, code FROM \""); |
3717 | 63 | sql += replaceAll(genuineTableName, "\"", "\"\""); |
3718 | 63 | sql += "\" WHERE name = ?"; |
3719 | 63 | if (tableName == "geodetic_crs" || tableName == "geographic_2D_crs") { |
3720 | 0 | sql += " AND type = " GEOG_2D_SINGLE_QUOTED; |
3721 | 63 | } else if (tableName == "geographic_3D_crs") { |
3722 | 0 | sql += " AND type = " GEOG_3D_SINGLE_QUOTED; |
3723 | 0 | } |
3724 | 63 | sql += " ORDER BY deprecated"; |
3725 | 63 | auto resSql = d->run(sql, {officialName}); |
3726 | 63 | if (resSql.empty()) { |
3727 | 63 | resSql = d->run("SELECT auth_name, code FROM alias_name WHERE " |
3728 | 63 | "table_name = ? AND " |
3729 | 63 | "alt_name = ? AND source IN ('EPSG', 'PROJ')", |
3730 | 63 | {genuineTableName, officialName}); |
3731 | 63 | if (resSql.size() != 1) { |
3732 | 63 | d->cacheAliasNames_.insert(key, res); |
3733 | 63 | return res; |
3734 | 63 | } |
3735 | 63 | } |
3736 | 0 | const auto &row = resSql.front(); |
3737 | 0 | resolvedAuthName = row[0]; |
3738 | 0 | resolvedCode = row[1]; |
3739 | 0 | } |
3740 | 2.26k | std::string sql("SELECT alt_name FROM alias_name WHERE table_name = ? AND " |
3741 | 2.26k | "auth_name = ? AND code = ?"); |
3742 | 2.26k | ListOfParams params{genuineTableName, resolvedAuthName, resolvedCode}; |
3743 | 2.26k | if (!source.empty()) { |
3744 | 0 | sql += " AND source = ?"; |
3745 | 0 | params.emplace_back(source); |
3746 | 0 | } |
3747 | 2.26k | auto resSql = d->run(sql, params); |
3748 | 8.29k | for (const auto &row : resSql) { |
3749 | 8.29k | res.emplace_back(row[0]); |
3750 | 8.29k | } |
3751 | | |
3752 | 2.26k | if (res.size() == 2 && source == "ESRI") { |
3753 | 0 | const auto uniqueEsriAlias = getUniqueEsriAlias(res); |
3754 | 0 | if (!uniqueEsriAlias.empty()) { |
3755 | 0 | res.clear(); |
3756 | 0 | res.emplace_back(uniqueEsriAlias); |
3757 | 0 | } |
3758 | 0 | } |
3759 | | |
3760 | 2.26k | d->cacheAliasNames_.insert(key, res); |
3761 | 2.26k | return res; |
3762 | 2.32k | } |
3763 | | |
3764 | | // --------------------------------------------------------------------------- |
3765 | | |
3766 | | /** \brief Return the 'name' column of a table for an object |
3767 | | * |
3768 | | * @param tableName Table name/category. |
3769 | | * @param authName Authority name of the object. |
3770 | | * @param code Code of the object |
3771 | | * @return Name (or empty) |
3772 | | * @throw FactoryException in case of error. |
3773 | | */ |
3774 | | std::string DatabaseContext::getName(const std::string &tableName, |
3775 | | const std::string &authName, |
3776 | 67.1k | const std::string &code) const { |
3777 | 67.1k | std::string res; |
3778 | 67.1k | const auto key(tableName + authName + code); |
3779 | 67.1k | if (d->cacheNames_.tryGet(key, res)) { |
3780 | 65.0k | return res; |
3781 | 65.0k | } |
3782 | | |
3783 | 2.13k | std::string sql("SELECT name FROM \""); |
3784 | 2.13k | sql += replaceAll(tableName, "\"", "\"\""); |
3785 | 2.13k | sql += "\" WHERE auth_name = ? AND code = ?"; |
3786 | 2.13k | auto sqlRes = d->run(sql, {authName, code}); |
3787 | 2.13k | if (sqlRes.empty()) { |
3788 | 2 | res.clear(); |
3789 | 2.12k | } else { |
3790 | 2.12k | res = sqlRes.front()[0]; |
3791 | 2.12k | } |
3792 | 2.13k | d->cacheNames_.insert(key, res); |
3793 | 2.13k | return res; |
3794 | 67.1k | } |
3795 | | |
3796 | | // --------------------------------------------------------------------------- |
3797 | | |
3798 | | /** \brief Return the 'text_definition' column of a table for an object |
3799 | | * |
3800 | | * @param tableName Table name/category. |
3801 | | * @param authName Authority name of the object. |
3802 | | * @param code Code of the object |
3803 | | * @return Text definition (or empty) |
3804 | | * @throw FactoryException in case of error. |
3805 | | */ |
3806 | | std::string DatabaseContext::getTextDefinition(const std::string &tableName, |
3807 | | const std::string &authName, |
3808 | 0 | const std::string &code) const { |
3809 | 0 | std::string sql("SELECT text_definition FROM \""); |
3810 | 0 | sql += replaceAll(tableName, "\"", "\"\""); |
3811 | 0 | sql += "\" WHERE auth_name = ? AND code = ?"; |
3812 | 0 | auto res = d->run(sql, {authName, code}); |
3813 | 0 | if (res.empty()) { |
3814 | 0 | return std::string(); |
3815 | 0 | } |
3816 | 0 | return res.front()[0]; |
3817 | 0 | } |
3818 | | |
3819 | | // --------------------------------------------------------------------------- |
3820 | | |
3821 | | /** \brief Return the allowed authorities when researching transformations |
3822 | | * between different authorities. |
3823 | | * |
3824 | | * @throw FactoryException in case of error. |
3825 | | */ |
3826 | | std::vector<std::string> DatabaseContext::getAllowedAuthorities( |
3827 | | const std::string &sourceAuthName, |
3828 | 74.8k | const std::string &targetAuthName) const { |
3829 | | |
3830 | 74.8k | const auto key(sourceAuthName + targetAuthName); |
3831 | 74.8k | auto hit = d->cacheAllowedAuthorities_.find(key); |
3832 | 74.8k | if (hit != d->cacheAllowedAuthorities_.end()) { |
3833 | 72.9k | return hit->second; |
3834 | 72.9k | } |
3835 | | |
3836 | 1.86k | auto sqlRes = d->run( |
3837 | 1.86k | "SELECT allowed_authorities FROM authority_to_authority_preference " |
3838 | 1.86k | "WHERE source_auth_name = ? AND target_auth_name = ?", |
3839 | 1.86k | {sourceAuthName, targetAuthName}); |
3840 | 1.86k | if (sqlRes.empty()) { |
3841 | 552 | sqlRes = d->run( |
3842 | 552 | "SELECT allowed_authorities FROM authority_to_authority_preference " |
3843 | 552 | "WHERE source_auth_name = ? AND target_auth_name = 'any'", |
3844 | 552 | {sourceAuthName}); |
3845 | 552 | } |
3846 | 1.86k | if (sqlRes.empty()) { |
3847 | 552 | sqlRes = d->run( |
3848 | 552 | "SELECT allowed_authorities FROM authority_to_authority_preference " |
3849 | 552 | "WHERE source_auth_name = 'any' AND target_auth_name = ?", |
3850 | 552 | {targetAuthName}); |
3851 | 552 | } |
3852 | 1.86k | if (sqlRes.empty()) { |
3853 | 352 | sqlRes = d->run( |
3854 | 352 | "SELECT allowed_authorities FROM authority_to_authority_preference " |
3855 | 352 | "WHERE source_auth_name = 'any' AND target_auth_name = 'any'", |
3856 | 352 | {}); |
3857 | 352 | } |
3858 | 1.86k | if (sqlRes.empty()) { |
3859 | 352 | d->cacheAllowedAuthorities_[key] = std::vector<std::string>(); |
3860 | 352 | return std::vector<std::string>(); |
3861 | 352 | } |
3862 | 1.51k | auto res = split(sqlRes.front()[0], ','); |
3863 | 1.51k | d->cacheAllowedAuthorities_[key] = res; |
3864 | 1.51k | return res; |
3865 | 1.86k | } |
3866 | | |
3867 | | // --------------------------------------------------------------------------- |
3868 | | |
3869 | | std::list<std::pair<std::string, std::string>> |
3870 | | DatabaseContext::getNonDeprecated(const std::string &tableName, |
3871 | | const std::string &authName, |
3872 | 0 | const std::string &code) const { |
3873 | 0 | auto sqlRes = |
3874 | 0 | d->run("SELECT replacement_auth_name, replacement_code, source " |
3875 | 0 | "FROM deprecation " |
3876 | 0 | "WHERE table_name = ? AND deprecated_auth_name = ? " |
3877 | 0 | "AND deprecated_code = ?", |
3878 | 0 | {tableName, authName, code}); |
3879 | 0 | std::list<std::pair<std::string, std::string>> res; |
3880 | 0 | for (const auto &row : sqlRes) { |
3881 | 0 | const auto &source = row[2]; |
3882 | 0 | if (source == "PROJ") { |
3883 | 0 | const auto &replacement_auth_name = row[0]; |
3884 | 0 | const auto &replacement_code = row[1]; |
3885 | 0 | res.emplace_back(replacement_auth_name, replacement_code); |
3886 | 0 | } |
3887 | 0 | } |
3888 | 0 | if (!res.empty()) { |
3889 | 0 | return res; |
3890 | 0 | } |
3891 | 0 | for (const auto &row : sqlRes) { |
3892 | 0 | const auto &replacement_auth_name = row[0]; |
3893 | 0 | const auto &replacement_code = row[1]; |
3894 | 0 | res.emplace_back(replacement_auth_name, replacement_code); |
3895 | 0 | } |
3896 | 0 | return res; |
3897 | 0 | } |
3898 | | |
3899 | | // --------------------------------------------------------------------------- |
3900 | | |
3901 | | const std::vector<DatabaseContext::Private::VersionedAuthName> & |
3902 | 413 | DatabaseContext::Private::getCacheAuthNameWithVersion() { |
3903 | 413 | if (cacheAuthNameWithVersion_.empty()) { |
3904 | 152 | const auto sqlRes = |
3905 | 152 | run("SELECT versioned_auth_name, auth_name, version, priority " |
3906 | 152 | "FROM versioned_auth_name_mapping"); |
3907 | 152 | for (const auto &row : sqlRes) { |
3908 | 152 | VersionedAuthName van; |
3909 | 152 | van.versionedAuthName = row[0]; |
3910 | 152 | van.authName = row[1]; |
3911 | 152 | van.version = row[2]; |
3912 | 152 | van.priority = atoi(row[3].c_str()); |
3913 | 152 | cacheAuthNameWithVersion_.emplace_back(std::move(van)); |
3914 | 152 | } |
3915 | 152 | } |
3916 | 413 | return cacheAuthNameWithVersion_; |
3917 | 413 | } |
3918 | | |
3919 | | // --------------------------------------------------------------------------- |
3920 | | |
3921 | | // From IAU_2015 returns (IAU,2015) |
3922 | | bool DatabaseContext::getAuthorityAndVersion( |
3923 | | const std::string &versionedAuthName, std::string &authNameOut, |
3924 | 0 | std::string &versionOut) { |
3925 | |
|
3926 | 0 | for (const auto &van : d->getCacheAuthNameWithVersion()) { |
3927 | 0 | if (van.versionedAuthName == versionedAuthName) { |
3928 | 0 | authNameOut = van.authName; |
3929 | 0 | versionOut = van.version; |
3930 | 0 | return true; |
3931 | 0 | } |
3932 | 0 | } |
3933 | 0 | return false; |
3934 | 0 | } |
3935 | | |
3936 | | // --------------------------------------------------------------------------- |
3937 | | |
3938 | | // From IAU and 2015, returns IAU_2015 |
3939 | | bool DatabaseContext::getVersionedAuthority(const std::string &authName, |
3940 | | const std::string &version, |
3941 | 308 | std::string &versionedAuthNameOut) { |
3942 | | |
3943 | 308 | for (const auto &van : d->getCacheAuthNameWithVersion()) { |
3944 | 308 | if (van.authName == authName && van.version == version) { |
3945 | 0 | versionedAuthNameOut = van.versionedAuthName; |
3946 | 0 | return true; |
3947 | 0 | } |
3948 | 308 | } |
3949 | 308 | return false; |
3950 | 308 | } |
3951 | | |
3952 | | // --------------------------------------------------------------------------- |
3953 | | |
3954 | | // From IAU returns IAU_latest, ... IAU_2015 |
3955 | | std::vector<std::string> |
3956 | 105 | DatabaseContext::getVersionedAuthoritiesFromName(const std::string &authName) { |
3957 | | |
3958 | 105 | typedef std::pair<std::string, int> VersionedAuthNamePriority; |
3959 | 105 | std::vector<VersionedAuthNamePriority> tmp; |
3960 | 105 | for (const auto &van : d->getCacheAuthNameWithVersion()) { |
3961 | 105 | if (van.authName == authName) { |
3962 | 0 | tmp.emplace_back( |
3963 | 0 | VersionedAuthNamePriority(van.versionedAuthName, van.priority)); |
3964 | 0 | } |
3965 | 105 | } |
3966 | 105 | std::vector<std::string> res; |
3967 | 105 | if (!tmp.empty()) { |
3968 | | // Sort by decreasing priority |
3969 | 0 | std::sort(tmp.begin(), tmp.end(), |
3970 | 0 | [](const VersionedAuthNamePriority &a, |
3971 | 0 | const VersionedAuthNamePriority &b) { |
3972 | 0 | return b.second > a.second; |
3973 | 0 | }); |
3974 | 0 | for (const auto &pair : tmp) |
3975 | 0 | res.emplace_back(pair.first); |
3976 | 0 | } |
3977 | 105 | return res; |
3978 | 105 | } |
3979 | | |
3980 | | // --------------------------------------------------------------------------- |
3981 | | |
3982 | | std::vector<operation::CoordinateOperationNNPtr> |
3983 | | DatabaseContext::getTransformationsForGridName( |
3984 | 0 | const DatabaseContextNNPtr &databaseContext, const std::string &gridName) { |
3985 | 0 | auto sqlRes = databaseContext->d->run( |
3986 | 0 | "SELECT auth_name, code FROM grid_transformation " |
3987 | 0 | "WHERE grid_name = ? OR grid_name IN " |
3988 | 0 | "(SELECT original_grid_name FROM grid_alternatives " |
3989 | 0 | "WHERE proj_grid_name = ?) ORDER BY auth_name, code", |
3990 | 0 | {gridName, gridName}); |
3991 | 0 | std::vector<operation::CoordinateOperationNNPtr> res; |
3992 | 0 | for (const auto &row : sqlRes) { |
3993 | 0 | res.emplace_back(AuthorityFactory::create(databaseContext, row[0]) |
3994 | 0 | ->createCoordinateOperation(row[1], true)); |
3995 | 0 | } |
3996 | 0 | return res; |
3997 | 0 | } |
3998 | | |
3999 | | // --------------------------------------------------------------------------- |
4000 | | |
4001 | | // Fixes wrong towgs84 values returned by epsg.io when using a Coordinate Frame |
4002 | | // transformation, where they neglect to reverse the sign of the rotation terms. |
4003 | | // Cf https://github.com/OSGeo/PROJ/issues/4170 and |
4004 | | // https://github.com/maptiler/epsg.io/issues/194 |
4005 | | // We do that only when we found a valid Coordinate Frame rotation that |
4006 | | // has the same numeric values (and no corresponding Position Vector |
4007 | | // transformation with same values, or Coordinate Frame transformation with |
4008 | | // opposite sign for rotation terms, both are highly unlikely) |
4009 | | bool DatabaseContext::toWGS84AutocorrectWrongValues( |
4010 | | double &tx, double &ty, double &tz, double &rx, double &ry, double &rz, |
4011 | 6 | double &scale_difference) const { |
4012 | 6 | if (rx == 0 && ry == 0 && rz == 0) |
4013 | 2 | return false; |
4014 | | // 9606: Position Vector transformation (geog2D domain) |
4015 | | // 9607: Coordinate Frame rotation (geog2D domain) |
4016 | 4 | std::string sql( |
4017 | 4 | "SELECT DISTINCT method_code " |
4018 | 4 | "FROM helmert_transformation_table WHERE " |
4019 | 4 | "abs(tx - ?) <= 1e-8 * abs(tx) AND " |
4020 | 4 | "abs(ty - ?) <= 1e-8 * abs(ty) AND " |
4021 | 4 | "abs(tz - ?) <= 1e-8 * abs(tz) AND " |
4022 | 4 | "abs(rx - ?) <= 1e-8 * abs(rx) AND " |
4023 | 4 | "abs(ry - ?) <= 1e-8 * abs(ry) AND " |
4024 | 4 | "abs(rz - ?) <= 1e-8 * abs(rz) AND " |
4025 | 4 | "abs(scale_difference - ?) <= 1e-8 * abs(scale_difference) AND " |
4026 | 4 | "method_auth_name = 'EPSG' AND " |
4027 | 4 | "method_code IN (9606, 9607) AND " |
4028 | 4 | "translation_uom_auth_name = 'EPSG' AND " |
4029 | 4 | "translation_uom_code = 9001 AND " // metre |
4030 | 4 | "rotation_uom_auth_name = 'EPSG' AND " |
4031 | 4 | "rotation_uom_code = 9104 AND " // arc-second |
4032 | 4 | "scale_difference_uom_auth_name = 'EPSG' AND " |
4033 | 4 | "scale_difference_uom_code = 9202 AND " // parts per million |
4034 | 4 | "deprecated = 0"); |
4035 | 4 | ListOfParams params; |
4036 | 4 | params.emplace_back(tx); |
4037 | 4 | params.emplace_back(ty); |
4038 | 4 | params.emplace_back(tz); |
4039 | 4 | params.emplace_back(rx); |
4040 | 4 | params.emplace_back(ry); |
4041 | 4 | params.emplace_back(rz); |
4042 | 4 | params.emplace_back(scale_difference); |
4043 | 4 | bool bFound9606 = false; |
4044 | 4 | bool bFound9607 = false; |
4045 | 4 | for (const auto &row : d->run(sql, params)) { |
4046 | 0 | if (row[0] == "9606") { |
4047 | 0 | bFound9606 = true; |
4048 | 0 | } else if (row[0] == "9607") { |
4049 | 0 | bFound9607 = true; |
4050 | 0 | } |
4051 | 0 | } |
4052 | 4 | if (bFound9607 && !bFound9606) { |
4053 | 0 | params.clear(); |
4054 | 0 | params.emplace_back(tx); |
4055 | 0 | params.emplace_back(ty); |
4056 | 0 | params.emplace_back(tz); |
4057 | 0 | params.emplace_back(-rx); |
4058 | 0 | params.emplace_back(-ry); |
4059 | 0 | params.emplace_back(-rz); |
4060 | 0 | params.emplace_back(scale_difference); |
4061 | 0 | if (d->run(sql, params).empty()) { |
4062 | 0 | if (d->pjCtxt()) { |
4063 | 0 | pj_log(d->pjCtxt(), PJ_LOG_ERROR, |
4064 | 0 | "Auto-correcting wrong sign of rotation terms of " |
4065 | 0 | "TOWGS84 clause from %s,%s,%s,%s,%s,%s,%s to " |
4066 | 0 | "%s,%s,%s,%s,%s,%s,%s", |
4067 | 0 | internal::toString(tx).c_str(), |
4068 | 0 | internal::toString(ty).c_str(), |
4069 | 0 | internal::toString(tz).c_str(), |
4070 | 0 | internal::toString(rx).c_str(), |
4071 | 0 | internal::toString(ry).c_str(), |
4072 | 0 | internal::toString(rz).c_str(), |
4073 | 0 | internal::toString(scale_difference).c_str(), |
4074 | 0 | internal::toString(tx).c_str(), |
4075 | 0 | internal::toString(ty).c_str(), |
4076 | 0 | internal::toString(tz).c_str(), |
4077 | 0 | internal::toString(-rx).c_str(), |
4078 | 0 | internal::toString(-ry).c_str(), |
4079 | 0 | internal::toString(-rz).c_str(), |
4080 | 0 | internal::toString(scale_difference).c_str()); |
4081 | 0 | } |
4082 | 0 | rx = -rx; |
4083 | 0 | ry = -ry; |
4084 | 0 | rz = -rz; |
4085 | 0 | return true; |
4086 | 0 | } |
4087 | 0 | } |
4088 | 4 | return false; |
4089 | 4 | } |
4090 | | |
4091 | | //! @endcond |
4092 | | |
4093 | | // --------------------------------------------------------------------------- |
4094 | | |
4095 | | //! @cond Doxygen_Suppress |
4096 | | struct AuthorityFactory::Private { |
4097 | | Private(const DatabaseContextNNPtr &contextIn, |
4098 | | const std::string &authorityName) |
4099 | 877k | : context_(contextIn), authority_(authorityName) {} |
4100 | | |
4101 | 2.49M | inline const std::string &authority() PROJ_PURE_DEFN { return authority_; } |
4102 | | |
4103 | 3.56M | inline const DatabaseContextNNPtr &context() PROJ_PURE_DEFN { |
4104 | 3.56M | return context_; |
4105 | 3.56M | } |
4106 | | |
4107 | | // cppcheck-suppress functionStatic |
4108 | 877k | void setThis(AuthorityFactoryNNPtr factory) { |
4109 | 877k | thisFactory_ = factory.as_nullable(); |
4110 | 877k | } |
4111 | | |
4112 | | // cppcheck-suppress functionStatic |
4113 | 13.9k | AuthorityFactoryPtr getSharedFromThis() { return thisFactory_.lock(); } |
4114 | | |
4115 | 942k | inline AuthorityFactoryNNPtr createFactory(const std::string &auth_name) { |
4116 | 942k | if (auth_name == authority_) { |
4117 | 671k | return NN_NO_CHECK(thisFactory_.lock()); |
4118 | 671k | } |
4119 | 270k | return AuthorityFactory::create(context_, auth_name); |
4120 | 942k | } |
4121 | | |
4122 | | bool rejectOpDueToMissingGrid(const operation::CoordinateOperationNNPtr &op, |
4123 | | bool considerKnownGridsAsAvailable); |
4124 | | |
4125 | | UnitOfMeasure createUnitOfMeasure(const std::string &auth_name, |
4126 | | const std::string &code); |
4127 | | |
4128 | | util::PropertyMap |
4129 | | createProperties(const std::string &code, const std::string &name, |
4130 | | bool deprecated, |
4131 | | const std::vector<ObjectDomainNNPtr> &usages); |
4132 | | |
4133 | | util::PropertyMap |
4134 | | createPropertiesSearchUsages(const std::string &table_name, |
4135 | | const std::string &code, |
4136 | | const std::string &name, bool deprecated); |
4137 | | |
4138 | | util::PropertyMap createPropertiesSearchUsages( |
4139 | | const std::string &table_name, const std::string &code, |
4140 | | const std::string &name, bool deprecated, const std::string &remarks); |
4141 | | |
4142 | | SQLResultSet run(const std::string &sql, |
4143 | | const ListOfParams ¶meters = ListOfParams()); |
4144 | | |
4145 | | SQLResultSet runWithCodeParam(const std::string &sql, |
4146 | | const std::string &code); |
4147 | | |
4148 | | SQLResultSet runWithCodeParam(const char *sql, const std::string &code); |
4149 | | |
4150 | 234k | bool hasAuthorityRestriction() const { |
4151 | 234k | return !authority_.empty() && authority_ != "any"; |
4152 | 234k | } |
4153 | | |
4154 | | SQLResultSet createProjectedCRSBegin(const std::string &code); |
4155 | | crs::ProjectedCRSNNPtr createProjectedCRSEnd(const std::string &code, |
4156 | | const SQLResultSet &res); |
4157 | | |
4158 | | private: |
4159 | | DatabaseContextNNPtr context_; |
4160 | | std::string authority_; |
4161 | | std::weak_ptr<AuthorityFactory> thisFactory_{}; |
4162 | | }; |
4163 | | |
4164 | | // --------------------------------------------------------------------------- |
4165 | | |
4166 | | SQLResultSet AuthorityFactory::Private::run(const std::string &sql, |
4167 | 854k | const ListOfParams ¶meters) { |
4168 | 854k | return context()->getPrivate()->run(sql, parameters); |
4169 | 854k | } |
4170 | | |
4171 | | // --------------------------------------------------------------------------- |
4172 | | |
4173 | | SQLResultSet |
4174 | | AuthorityFactory::Private::runWithCodeParam(const std::string &sql, |
4175 | 376k | const std::string &code) { |
4176 | 376k | return run(sql, {authority(), code}); |
4177 | 376k | } |
4178 | | |
4179 | | // --------------------------------------------------------------------------- |
4180 | | |
4181 | | SQLResultSet |
4182 | | AuthorityFactory::Private::runWithCodeParam(const char *sql, |
4183 | 342k | const std::string &code) { |
4184 | 342k | return runWithCodeParam(std::string(sql), code); |
4185 | 342k | } |
4186 | | |
4187 | | // --------------------------------------------------------------------------- |
4188 | | |
4189 | | UnitOfMeasure |
4190 | | AuthorityFactory::Private::createUnitOfMeasure(const std::string &auth_name, |
4191 | 114k | const std::string &code) { |
4192 | 114k | return *(createFactory(auth_name)->createUnitOfMeasure(code)); |
4193 | 114k | } |
4194 | | |
4195 | | // --------------------------------------------------------------------------- |
4196 | | |
4197 | | util::PropertyMap AuthorityFactory::Private::createProperties( |
4198 | | const std::string &code, const std::string &name, bool deprecated, |
4199 | 246k | const std::vector<ObjectDomainNNPtr> &usages) { |
4200 | 246k | auto props = util::PropertyMap() |
4201 | 246k | .set(metadata::Identifier::CODESPACE_KEY, authority()) |
4202 | 246k | .set(metadata::Identifier::CODE_KEY, code) |
4203 | 246k | .set(common::IdentifiedObject::NAME_KEY, name); |
4204 | 246k | if (deprecated) { |
4205 | 229 | props.set(common::IdentifiedObject::DEPRECATED_KEY, true); |
4206 | 229 | } |
4207 | 246k | if (!usages.empty()) { |
4208 | | |
4209 | 236k | auto array(util::ArrayOfBaseObject::create()); |
4210 | 236k | for (const auto &usage : usages) { |
4211 | 236k | array->add(usage); |
4212 | 236k | } |
4213 | 236k | props.set(common::ObjectUsage::OBJECT_DOMAIN_KEY, |
4214 | 236k | util::nn_static_pointer_cast<util::BaseObject>(array)); |
4215 | 236k | } |
4216 | 246k | return props; |
4217 | 246k | } |
4218 | | |
4219 | | // --------------------------------------------------------------------------- |
4220 | | |
4221 | | util::PropertyMap AuthorityFactory::Private::createPropertiesSearchUsages( |
4222 | | const std::string &table_name, const std::string &code, |
4223 | 236k | const std::string &name, bool deprecated) { |
4224 | | |
4225 | 236k | SQLResultSet res; |
4226 | 236k | if (table_name == "geodetic_crs" && code == "4326" && |
4227 | 236k | authority() == "EPSG") { |
4228 | | // EPSG v10.077 has changed the extent from 1262 to 2830, whose |
4229 | | // description is super verbose. |
4230 | | // Cf https://epsg.org/closed-change-request/browse/id/2022.086 |
4231 | | // To avoid churn in our WKT2 output, hot patch to the usage of |
4232 | | // 10.076 and earlier |
4233 | 2.34k | res = run("SELECT extent.description, extent.south_lat, " |
4234 | 2.34k | "extent.north_lat, extent.west_lon, extent.east_lon, " |
4235 | 2.34k | "scope.scope, 0 AS score FROM extent, scope WHERE " |
4236 | 2.34k | "extent.code = 1262 and scope.code = 1183"); |
4237 | 234k | } else { |
4238 | 234k | const std::string sql( |
4239 | 234k | "SELECT extent.description, extent.south_lat, " |
4240 | 234k | "extent.north_lat, extent.west_lon, extent.east_lon, " |
4241 | 234k | "scope.scope, " |
4242 | 234k | "(CASE WHEN scope.scope LIKE '%large scale%' THEN 0 ELSE 1 END) " |
4243 | 234k | "AS score " |
4244 | 234k | "FROM usage " |
4245 | 234k | "JOIN extent ON usage.extent_auth_name = extent.auth_name AND " |
4246 | 234k | "usage.extent_code = extent.code " |
4247 | 234k | "JOIN scope ON usage.scope_auth_name = scope.auth_name AND " |
4248 | 234k | "usage.scope_code = scope.code " |
4249 | 234k | "WHERE object_table_name = ? AND object_auth_name = ? AND " |
4250 | 234k | "object_code = ? AND " |
4251 | | // We voluntary exclude extent and scope with a specific code |
4252 | 234k | "NOT (usage.extent_auth_name = 'PROJ' AND " |
4253 | 234k | "usage.extent_code = 'EXTENT_UNKNOWN') AND " |
4254 | 234k | "NOT (usage.scope_auth_name = 'PROJ' AND " |
4255 | 234k | "usage.scope_code = 'SCOPE_UNKNOWN') " |
4256 | 234k | "ORDER BY score, usage.auth_name, usage.code"); |
4257 | 234k | res = run(sql, {table_name, authority(), code}); |
4258 | 234k | } |
4259 | 236k | std::vector<ObjectDomainNNPtr> usages; |
4260 | 236k | for (const auto &row : res) { |
4261 | 236k | try { |
4262 | 236k | size_t idx = 0; |
4263 | 236k | const auto &extent_description = row[idx++]; |
4264 | 236k | const auto &south_lat_str = row[idx++]; |
4265 | 236k | const auto &north_lat_str = row[idx++]; |
4266 | 236k | const auto &west_lon_str = row[idx++]; |
4267 | 236k | const auto &east_lon_str = row[idx++]; |
4268 | 236k | const auto &scope = row[idx]; |
4269 | | |
4270 | 236k | util::optional<std::string> scopeOpt; |
4271 | 236k | if (!scope.empty()) { |
4272 | 236k | scopeOpt = scope; |
4273 | 236k | } |
4274 | | |
4275 | 236k | metadata::ExtentPtr extent; |
4276 | 236k | if (south_lat_str.empty()) { |
4277 | 0 | extent = metadata::Extent::create( |
4278 | 0 | util::optional<std::string>(extent_description), |
4279 | 0 | {}, {}, {}) |
4280 | 0 | .as_nullable(); |
4281 | 236k | } else { |
4282 | 236k | double south_lat = c_locale_stod(south_lat_str); |
4283 | 236k | double north_lat = c_locale_stod(north_lat_str); |
4284 | 236k | double west_lon = c_locale_stod(west_lon_str); |
4285 | 236k | double east_lon = c_locale_stod(east_lon_str); |
4286 | 236k | auto bbox = metadata::GeographicBoundingBox::create( |
4287 | 236k | west_lon, south_lat, east_lon, north_lat); |
4288 | 236k | extent = metadata::Extent::create( |
4289 | 236k | util::optional<std::string>(extent_description), |
4290 | 236k | std::vector<metadata::GeographicExtentNNPtr>{bbox}, |
4291 | 236k | std::vector<metadata::VerticalExtentNNPtr>(), |
4292 | 236k | std::vector<metadata::TemporalExtentNNPtr>()) |
4293 | 236k | .as_nullable(); |
4294 | 236k | } |
4295 | | |
4296 | 236k | usages.emplace_back(ObjectDomain::create(scopeOpt, extent)); |
4297 | 236k | } catch (const std::exception &) { |
4298 | 0 | } |
4299 | 236k | } |
4300 | 236k | return createProperties(code, name, deprecated, std::move(usages)); |
4301 | 236k | } |
4302 | | |
4303 | | // --------------------------------------------------------------------------- |
4304 | | |
4305 | | util::PropertyMap AuthorityFactory::Private::createPropertiesSearchUsages( |
4306 | | const std::string &table_name, const std::string &code, |
4307 | 195k | const std::string &name, bool deprecated, const std::string &remarks) { |
4308 | 195k | auto props = |
4309 | 195k | createPropertiesSearchUsages(table_name, code, name, deprecated); |
4310 | 195k | if (!remarks.empty()) |
4311 | 159k | props.set(common::IdentifiedObject::REMARKS_KEY, remarks); |
4312 | 195k | return props; |
4313 | 195k | } |
4314 | | |
4315 | | // --------------------------------------------------------------------------- |
4316 | | |
4317 | | bool AuthorityFactory::Private::rejectOpDueToMissingGrid( |
4318 | | const operation::CoordinateOperationNNPtr &op, |
4319 | 50.8k | bool considerKnownGridsAsAvailable) { |
4320 | | |
4321 | 50.8k | struct DisableNetwork { |
4322 | 50.8k | const DatabaseContextNNPtr &m_dbContext; |
4323 | 50.8k | bool m_old_network_enabled = false; |
4324 | | |
4325 | 50.8k | explicit DisableNetwork(const DatabaseContextNNPtr &l_context) |
4326 | 50.8k | : m_dbContext(l_context) { |
4327 | 50.8k | auto ctxt = m_dbContext->d->pjCtxt(); |
4328 | 50.8k | if (ctxt == nullptr) { |
4329 | 0 | ctxt = pj_get_default_ctx(); |
4330 | 0 | m_dbContext->d->setPjCtxt(ctxt); |
4331 | 0 | } |
4332 | 50.8k | m_old_network_enabled = |
4333 | 50.8k | proj_context_is_network_enabled(ctxt) != FALSE; |
4334 | 50.8k | if (m_old_network_enabled) |
4335 | 0 | proj_context_set_enable_network(ctxt, false); |
4336 | 50.8k | } |
4337 | | |
4338 | 50.8k | ~DisableNetwork() { |
4339 | 50.8k | if (m_old_network_enabled) { |
4340 | 0 | auto ctxt = m_dbContext->d->pjCtxt(); |
4341 | 0 | proj_context_set_enable_network(ctxt, true); |
4342 | 0 | } |
4343 | 50.8k | } |
4344 | 50.8k | }; |
4345 | | |
4346 | 50.8k | auto &l_context = context(); |
4347 | | // Temporarily disable networking as we are only interested in known grids |
4348 | 50.8k | DisableNetwork disabler(l_context); |
4349 | | |
4350 | 50.8k | for (const auto &gridDesc : |
4351 | 50.8k | op->gridsNeeded(l_context, considerKnownGridsAsAvailable)) { |
4352 | 37.0k | if (!gridDesc.available) { |
4353 | 37.0k | return true; |
4354 | 37.0k | } |
4355 | 37.0k | } |
4356 | 13.7k | return false; |
4357 | 50.8k | } |
4358 | | |
4359 | | //! @endcond |
4360 | | |
4361 | | // --------------------------------------------------------------------------- |
4362 | | |
4363 | | //! @cond Doxygen_Suppress |
4364 | 877k | AuthorityFactory::~AuthorityFactory() = default; |
4365 | | //! @endcond |
4366 | | |
4367 | | // --------------------------------------------------------------------------- |
4368 | | |
4369 | | AuthorityFactory::AuthorityFactory(const DatabaseContextNNPtr &context, |
4370 | | const std::string &authorityName) |
4371 | 877k | : d(std::make_unique<Private>(context, authorityName)) {} |
4372 | | |
4373 | | // --------------------------------------------------------------------------- |
4374 | | |
4375 | | // clang-format off |
4376 | | /** \brief Instantiate a AuthorityFactory. |
4377 | | * |
4378 | | * The authority name might be set to the empty string in the particular case |
4379 | | * where createFromCoordinateReferenceSystemCodes(const std::string&,const std::string&,const std::string&,const std::string&) const |
4380 | | * is called. |
4381 | | * |
4382 | | * @param context Context. |
4383 | | * @param authorityName Authority name. |
4384 | | * @return new AuthorityFactory. |
4385 | | */ |
4386 | | // clang-format on |
4387 | | |
4388 | | AuthorityFactoryNNPtr |
4389 | | AuthorityFactory::create(const DatabaseContextNNPtr &context, |
4390 | 877k | const std::string &authorityName) { |
4391 | 877k | const auto getFactory = [&context, &authorityName]() { |
4392 | 877k | for (const auto &knownName : |
4393 | 1.38M | {metadata::Identifier::EPSG.c_str(), "ESRI", "PROJ"}) { |
4394 | 1.38M | if (ci_equal(authorityName, knownName)) { |
4395 | 671k | return AuthorityFactory::nn_make_shared<AuthorityFactory>( |
4396 | 671k | context, knownName); |
4397 | 671k | } |
4398 | 1.38M | } |
4399 | 206k | return AuthorityFactory::nn_make_shared<AuthorityFactory>( |
4400 | 206k | context, authorityName); |
4401 | 877k | }; |
4402 | 877k | auto factory = getFactory(); |
4403 | 877k | factory->d->setThis(factory); |
4404 | 877k | return factory; |
4405 | 877k | } |
4406 | | |
4407 | | // --------------------------------------------------------------------------- |
4408 | | |
4409 | | /** \brief Returns the database context. */ |
4410 | 753k | const DatabaseContextNNPtr &AuthorityFactory::databaseContext() const { |
4411 | 753k | return d->context(); |
4412 | 753k | } |
4413 | | |
4414 | | // --------------------------------------------------------------------------- |
4415 | | |
4416 | | //! @cond Doxygen_Suppress |
4417 | | AuthorityFactory::CRSInfo::CRSInfo() |
4418 | 0 | : authName{}, code{}, name{}, type{ObjectType::CRS}, deprecated{}, |
4419 | 0 | bbox_valid{}, west_lon_degree{}, south_lat_degree{}, east_lon_degree{}, |
4420 | 0 | north_lat_degree{}, areaName{}, projectionMethodName{}, |
4421 | 0 | celestialBodyName{} {} |
4422 | | //! @endcond |
4423 | | |
4424 | | // --------------------------------------------------------------------------- |
4425 | | |
4426 | | /** \brief Returns an arbitrary object from a code. |
4427 | | * |
4428 | | * The returned object will typically be an instance of Datum, |
4429 | | * CoordinateSystem, ReferenceSystem or CoordinateOperation. If the type of |
4430 | | * the object is know at compile time, it is recommended to invoke the most |
4431 | | * precise method instead of this one (for example |
4432 | | * createCoordinateReferenceSystem(code) instead of createObject(code) |
4433 | | * if the caller know he is asking for a coordinate reference system). |
4434 | | * |
4435 | | * If there are several objects with the same code, a FactoryException is |
4436 | | * thrown. |
4437 | | * |
4438 | | * @param code Object code allocated by authority. (e.g. "4326") |
4439 | | * @return object. |
4440 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
4441 | | * @throw FactoryException in case of other errors. |
4442 | | */ |
4443 | | |
4444 | | util::BaseObjectNNPtr |
4445 | 0 | AuthorityFactory::createObject(const std::string &code) const { |
4446 | |
|
4447 | 0 | auto res = d->runWithCodeParam("SELECT table_name, type FROM object_view " |
4448 | 0 | "WHERE auth_name = ? AND code = ?", |
4449 | 0 | code); |
4450 | 0 | if (res.empty()) { |
4451 | 0 | throw NoSuchAuthorityCodeException("not found", d->authority(), code); |
4452 | 0 | } |
4453 | 0 | if (res.size() != 1) { |
4454 | 0 | std::string msg( |
4455 | 0 | "More than one object matching specified code. Objects found in "); |
4456 | 0 | bool first = true; |
4457 | 0 | for (const auto &row : res) { |
4458 | 0 | if (!first) |
4459 | 0 | msg += ", "; |
4460 | 0 | msg += row[0]; |
4461 | 0 | first = false; |
4462 | 0 | } |
4463 | 0 | throw FactoryException(msg); |
4464 | 0 | } |
4465 | 0 | const auto &first_row = res.front(); |
4466 | 0 | const auto &table_name = first_row[0]; |
4467 | 0 | const auto &type = first_row[1]; |
4468 | 0 | if (table_name == "extent") { |
4469 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4470 | 0 | createExtent(code)); |
4471 | 0 | } |
4472 | 0 | if (table_name == "unit_of_measure") { |
4473 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4474 | 0 | createUnitOfMeasure(code)); |
4475 | 0 | } |
4476 | 0 | if (table_name == "prime_meridian") { |
4477 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4478 | 0 | createPrimeMeridian(code)); |
4479 | 0 | } |
4480 | 0 | if (table_name == "ellipsoid") { |
4481 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4482 | 0 | createEllipsoid(code)); |
4483 | 0 | } |
4484 | 0 | if (table_name == "geodetic_datum") { |
4485 | 0 | if (type == "ensemble") { |
4486 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4487 | 0 | createDatumEnsemble(code, table_name)); |
4488 | 0 | } |
4489 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4490 | 0 | createGeodeticDatum(code)); |
4491 | 0 | } |
4492 | 0 | if (table_name == "vertical_datum") { |
4493 | 0 | if (type == "ensemble") { |
4494 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4495 | 0 | createDatumEnsemble(code, table_name)); |
4496 | 0 | } |
4497 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4498 | 0 | createVerticalDatum(code)); |
4499 | 0 | } |
4500 | 0 | if (table_name == "engineering_datum") { |
4501 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4502 | 0 | createEngineeringDatum(code)); |
4503 | 0 | } |
4504 | 0 | if (table_name == "geodetic_crs") { |
4505 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4506 | 0 | createGeodeticCRS(code)); |
4507 | 0 | } |
4508 | 0 | if (table_name == "vertical_crs") { |
4509 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4510 | 0 | createVerticalCRS(code)); |
4511 | 0 | } |
4512 | 0 | if (table_name == "projected_crs") { |
4513 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4514 | 0 | createProjectedCRS(code)); |
4515 | 0 | } |
4516 | 0 | if (table_name == "compound_crs") { |
4517 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4518 | 0 | createCompoundCRS(code)); |
4519 | 0 | } |
4520 | 0 | if (table_name == "engineering_crs") { |
4521 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4522 | 0 | createEngineeringCRS(code)); |
4523 | 0 | } |
4524 | 0 | if (table_name == "conversion") { |
4525 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4526 | 0 | createConversion(code)); |
4527 | 0 | } |
4528 | 0 | if (table_name == "helmert_transformation" || |
4529 | 0 | table_name == "grid_transformation" || |
4530 | 0 | table_name == "other_transformation" || |
4531 | 0 | table_name == "concatenated_operation") { |
4532 | 0 | return util::nn_static_pointer_cast<util::BaseObject>( |
4533 | 0 | createCoordinateOperation(code, false)); |
4534 | 0 | } |
4535 | 0 | throw FactoryException("unimplemented factory for " + res.front()[0]); |
4536 | 0 | } |
4537 | | |
4538 | | // --------------------------------------------------------------------------- |
4539 | | |
4540 | | //! @cond Doxygen_Suppress |
4541 | | static FactoryException buildFactoryException(const char *type, |
4542 | | const std::string &authName, |
4543 | | const std::string &code, |
4544 | 0 | const std::exception &ex) { |
4545 | 0 | return FactoryException(std::string("cannot build ") + type + " " + |
4546 | 0 | authName + ":" + code + ": " + ex.what()); |
4547 | 0 | } |
4548 | | //! @endcond |
4549 | | |
4550 | | // --------------------------------------------------------------------------- |
4551 | | |
4552 | | /** \brief Returns a metadata::Extent from the specified code. |
4553 | | * |
4554 | | * @param code Object code allocated by authority. |
4555 | | * @return object. |
4556 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
4557 | | * @throw FactoryException in case of other errors. |
4558 | | */ |
4559 | | |
4560 | | metadata::ExtentNNPtr |
4561 | 0 | AuthorityFactory::createExtent(const std::string &code) const { |
4562 | 0 | const auto cacheKey(d->authority() + code); |
4563 | 0 | { |
4564 | 0 | auto extent = d->context()->d->getExtentFromCache(cacheKey); |
4565 | 0 | if (extent) { |
4566 | 0 | return NN_NO_CHECK(extent); |
4567 | 0 | } |
4568 | 0 | } |
4569 | 0 | auto sql = "SELECT description, south_lat, north_lat, west_lon, east_lon, " |
4570 | 0 | "deprecated FROM extent WHERE auth_name = ? AND code = ?"; |
4571 | 0 | auto res = d->runWithCodeParam(sql, code); |
4572 | 0 | if (res.empty()) { |
4573 | 0 | throw NoSuchAuthorityCodeException("extent not found", d->authority(), |
4574 | 0 | code); |
4575 | 0 | } |
4576 | 0 | try { |
4577 | 0 | const auto &row = res.front(); |
4578 | 0 | const auto &description = row[0]; |
4579 | 0 | if (row[1].empty()) { |
4580 | 0 | auto extent = metadata::Extent::create( |
4581 | 0 | util::optional<std::string>(description), {}, {}, {}); |
4582 | 0 | d->context()->d->cache(cacheKey, extent); |
4583 | 0 | return extent; |
4584 | 0 | } |
4585 | 0 | double south_lat = c_locale_stod(row[1]); |
4586 | 0 | double north_lat = c_locale_stod(row[2]); |
4587 | 0 | double west_lon = c_locale_stod(row[3]); |
4588 | 0 | double east_lon = c_locale_stod(row[4]); |
4589 | 0 | auto bbox = metadata::GeographicBoundingBox::create( |
4590 | 0 | west_lon, south_lat, east_lon, north_lat); |
4591 | |
|
4592 | 0 | auto extent = metadata::Extent::create( |
4593 | 0 | util::optional<std::string>(description), |
4594 | 0 | std::vector<metadata::GeographicExtentNNPtr>{bbox}, |
4595 | 0 | std::vector<metadata::VerticalExtentNNPtr>(), |
4596 | 0 | std::vector<metadata::TemporalExtentNNPtr>()); |
4597 | 0 | d->context()->d->cache(cacheKey, extent); |
4598 | 0 | return extent; |
4599 | |
|
4600 | 0 | } catch (const std::exception &ex) { |
4601 | 0 | throw buildFactoryException("extent", d->authority(), code, ex); |
4602 | 0 | } |
4603 | 0 | } |
4604 | | |
4605 | | // --------------------------------------------------------------------------- |
4606 | | |
4607 | | /** \brief Returns a common::UnitOfMeasure from the specified code. |
4608 | | * |
4609 | | * @param code Object code allocated by authority. |
4610 | | * @return object. |
4611 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
4612 | | * @throw FactoryException in case of other errors. |
4613 | | */ |
4614 | | |
4615 | | UnitOfMeasureNNPtr |
4616 | 114k | AuthorityFactory::createUnitOfMeasure(const std::string &code) const { |
4617 | 114k | const auto cacheKey(d->authority() + code); |
4618 | 114k | { |
4619 | 114k | auto uom = d->context()->d->getUOMFromCache(cacheKey); |
4620 | 114k | if (uom) { |
4621 | 100k | return NN_NO_CHECK(uom); |
4622 | 100k | } |
4623 | 114k | } |
4624 | 13.3k | auto res = d->context()->d->run( |
4625 | 13.3k | "SELECT name, conv_factor, type, deprecated FROM unit_of_measure WHERE " |
4626 | 13.3k | "auth_name = ? AND code = ?", |
4627 | 13.3k | {d->authority(), code}, true); |
4628 | 13.3k | if (res.empty()) { |
4629 | 0 | throw NoSuchAuthorityCodeException("unit of measure not found", |
4630 | 0 | d->authority(), code); |
4631 | 0 | } |
4632 | 13.3k | try { |
4633 | 13.3k | const auto &row = res.front(); |
4634 | 13.3k | const auto &name = |
4635 | 13.3k | (row[0] == "degree (supplier to define representation)") |
4636 | 13.3k | ? UnitOfMeasure::DEGREE.name() |
4637 | 13.3k | : row[0]; |
4638 | 13.3k | double conv_factor = (code == "9107" || code == "9108") |
4639 | 13.3k | ? UnitOfMeasure::DEGREE.conversionToSI() |
4640 | 13.3k | : c_locale_stod(row[1]); |
4641 | 13.3k | constexpr double EPS = 1e-10; |
4642 | 13.3k | if (std::fabs(conv_factor - UnitOfMeasure::DEGREE.conversionToSI()) < |
4643 | 13.3k | EPS * UnitOfMeasure::DEGREE.conversionToSI()) { |
4644 | 5.98k | conv_factor = UnitOfMeasure::DEGREE.conversionToSI(); |
4645 | 5.98k | } |
4646 | 13.3k | if (std::fabs(conv_factor - |
4647 | 13.3k | UnitOfMeasure::ARC_SECOND.conversionToSI()) < |
4648 | 13.3k | EPS * UnitOfMeasure::ARC_SECOND.conversionToSI()) { |
4649 | 740 | conv_factor = UnitOfMeasure::ARC_SECOND.conversionToSI(); |
4650 | 740 | } |
4651 | 13.3k | const auto &type_str = row[2]; |
4652 | 13.3k | UnitOfMeasure::Type unitType = UnitOfMeasure::Type::UNKNOWN; |
4653 | 13.3k | if (type_str == "length") |
4654 | 3.87k | unitType = UnitOfMeasure::Type::LINEAR; |
4655 | 9.46k | else if (type_str == "angle") |
4656 | 7.55k | unitType = UnitOfMeasure::Type::ANGULAR; |
4657 | 1.91k | else if (type_str == "scale") |
4658 | 1.70k | unitType = UnitOfMeasure::Type::SCALE; |
4659 | 205 | else if (type_str == "time") |
4660 | 205 | unitType = UnitOfMeasure::Type::TIME; |
4661 | 13.3k | auto uom = util::nn_make_shared<UnitOfMeasure>( |
4662 | 13.3k | name, conv_factor, unitType, d->authority(), code); |
4663 | 13.3k | d->context()->d->cache(cacheKey, uom); |
4664 | 13.3k | return uom; |
4665 | 13.3k | } catch (const std::exception &ex) { |
4666 | 0 | throw buildFactoryException("unit of measure", d->authority(), code, |
4667 | 0 | ex); |
4668 | 0 | } |
4669 | 13.3k | } |
4670 | | |
4671 | | // --------------------------------------------------------------------------- |
4672 | | |
4673 | | //! @cond Doxygen_Suppress |
4674 | | static double normalizeMeasure(const std::string &uom_code, |
4675 | | const std::string &value, |
4676 | 18.9k | std::string &normalized_uom_code) { |
4677 | 18.9k | if (uom_code == "9110") // DDD.MMSSsss..... |
4678 | 3.30k | { |
4679 | 3.30k | double normalized_value = c_locale_stod(value); |
4680 | 3.30k | std::ostringstream buffer; |
4681 | 3.30k | buffer.imbue(std::locale::classic()); |
4682 | 3.30k | constexpr size_t precision = 12; |
4683 | 3.30k | buffer << std::fixed << std::setprecision(precision) |
4684 | 3.30k | << normalized_value; |
4685 | 3.30k | auto formatted = buffer.str(); |
4686 | 3.30k | size_t dotPos = formatted.find('.'); |
4687 | 3.30k | assert(dotPos + 1 + precision == formatted.size()); |
4688 | 3.30k | auto minutes = formatted.substr(dotPos + 1, 2); |
4689 | 3.30k | auto seconds = formatted.substr(dotPos + 3); |
4690 | 3.30k | assert(seconds.size() == precision - 2); |
4691 | 3.30k | normalized_value = |
4692 | 3.30k | (normalized_value < 0 ? -1.0 : 1.0) * |
4693 | 3.30k | (std::floor(std::fabs(normalized_value)) + |
4694 | 3.30k | c_locale_stod(minutes) / 60. + |
4695 | 3.30k | (c_locale_stod(seconds) / std::pow(10, seconds.size() - 2)) / |
4696 | 3.30k | 3600.); |
4697 | 3.30k | normalized_uom_code = common::UnitOfMeasure::DEGREE.code(); |
4698 | | /* coverity[overflow_sink] */ |
4699 | 3.30k | return normalized_value; |
4700 | 15.6k | } else { |
4701 | 15.6k | normalized_uom_code = uom_code; |
4702 | 15.6k | return c_locale_stod(value); |
4703 | 15.6k | } |
4704 | 18.9k | } |
4705 | | //! @endcond |
4706 | | |
4707 | | // --------------------------------------------------------------------------- |
4708 | | |
4709 | | /** \brief Returns a datum::PrimeMeridian from the specified code. |
4710 | | * |
4711 | | * @param code Object code allocated by authority. |
4712 | | * @return object. |
4713 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
4714 | | * @throw FactoryException in case of other errors. |
4715 | | */ |
4716 | | |
4717 | | datum::PrimeMeridianNNPtr |
4718 | 30.7k | AuthorityFactory::createPrimeMeridian(const std::string &code) const { |
4719 | 30.7k | const auto cacheKey(d->authority() + code); |
4720 | 30.7k | { |
4721 | 30.7k | auto pm = d->context()->d->getPrimeMeridianFromCache(cacheKey); |
4722 | 30.7k | if (pm) { |
4723 | 27.4k | return NN_NO_CHECK(pm); |
4724 | 27.4k | } |
4725 | 30.7k | } |
4726 | 3.30k | auto res = d->runWithCodeParam( |
4727 | 3.30k | "SELECT name, longitude, uom_auth_name, uom_code, deprecated FROM " |
4728 | 3.30k | "prime_meridian WHERE " |
4729 | 3.30k | "auth_name = ? AND code = ?", |
4730 | 3.30k | code); |
4731 | 3.30k | if (res.empty()) { |
4732 | 0 | throw NoSuchAuthorityCodeException("prime meridian not found", |
4733 | 0 | d->authority(), code); |
4734 | 0 | } |
4735 | 3.30k | try { |
4736 | 3.30k | const auto &row = res.front(); |
4737 | 3.30k | const auto &name = row[0]; |
4738 | 3.30k | const auto &longitude = row[1]; |
4739 | 3.30k | const auto &uom_auth_name = row[2]; |
4740 | 3.30k | const auto &uom_code = row[3]; |
4741 | 3.30k | const bool deprecated = row[4] == "1"; |
4742 | | |
4743 | 3.30k | std::string normalized_uom_code(uom_code); |
4744 | 3.30k | const double normalized_value = |
4745 | 3.30k | normalizeMeasure(uom_code, longitude, normalized_uom_code); |
4746 | | |
4747 | 3.30k | auto uom = d->createUnitOfMeasure(uom_auth_name, normalized_uom_code); |
4748 | 3.30k | auto props = d->createProperties(code, name, deprecated, {}); |
4749 | 3.30k | auto pm = datum::PrimeMeridian::create( |
4750 | 3.30k | props, common::Angle(normalized_value, uom)); |
4751 | 3.30k | d->context()->d->cache(cacheKey, pm); |
4752 | 3.30k | return pm; |
4753 | 3.30k | } catch (const std::exception &ex) { |
4754 | 0 | throw buildFactoryException("prime meridian", d->authority(), code, ex); |
4755 | 0 | } |
4756 | 3.30k | } |
4757 | | |
4758 | | // --------------------------------------------------------------------------- |
4759 | | |
4760 | | /** \brief Identify a celestial body from an approximate radius. |
4761 | | * |
4762 | | * @param semi_major_axis Approximate semi-major axis. |
4763 | | * @param tolerance Relative error allowed. |
4764 | | * @return celestial body name if one single match found. |
4765 | | * @throw FactoryException in case of error. |
4766 | | */ |
4767 | | |
4768 | | std::string |
4769 | | AuthorityFactory::identifyBodyFromSemiMajorAxis(double semi_major_axis, |
4770 | 1.08k | double tolerance) const { |
4771 | 1.08k | auto res = |
4772 | 1.08k | d->run("SELECT DISTINCT name, " |
4773 | 1.08k | "(ABS(semi_major_axis - ?) / semi_major_axis ) AS rel_error " |
4774 | 1.08k | "FROM celestial_body WHERE rel_error <= ? " |
4775 | 1.08k | "ORDER BY rel_error, name", |
4776 | 1.08k | {semi_major_axis, tolerance}); |
4777 | 1.08k | if (res.empty()) { |
4778 | 988 | throw FactoryException("no match found"); |
4779 | 988 | } |
4780 | 96 | constexpr int IDX_NAME = 0; |
4781 | 96 | if (res.size() > 1) { |
4782 | 22 | constexpr int IDX_REL_ERROR = 1; |
4783 | | // If the first object has a relative error of 0 and the next one |
4784 | | // a non-zero error, then use the first one. |
4785 | 22 | if (res.front()[IDX_REL_ERROR] == "0" && |
4786 | 22 | (*std::next(res.begin()))[IDX_REL_ERROR] != "0") { |
4787 | 0 | return res.front()[IDX_NAME]; |
4788 | 0 | } |
4789 | 44 | for (const auto &row : res) { |
4790 | 44 | if (row[IDX_NAME] != res.front()[IDX_NAME]) { |
4791 | 20 | throw FactoryException("more than one match found"); |
4792 | 20 | } |
4793 | 44 | } |
4794 | 22 | } |
4795 | 76 | return res.front()[IDX_NAME]; |
4796 | 96 | } |
4797 | | |
4798 | | // --------------------------------------------------------------------------- |
4799 | | |
4800 | | /** \brief Returns a datum::Ellipsoid from the specified code. |
4801 | | * |
4802 | | * @param code Object code allocated by authority. |
4803 | | * @return object. |
4804 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
4805 | | * @throw FactoryException in case of other errors. |
4806 | | */ |
4807 | | |
4808 | | datum::EllipsoidNNPtr |
4809 | 30.9k | AuthorityFactory::createEllipsoid(const std::string &code) const { |
4810 | 30.9k | const auto cacheKey(d->authority() + code); |
4811 | 30.9k | { |
4812 | 30.9k | auto ellps = d->context()->d->getEllipsoidFromCache(cacheKey); |
4813 | 30.9k | if (ellps) { |
4814 | 25.0k | return NN_NO_CHECK(ellps); |
4815 | 25.0k | } |
4816 | 30.9k | } |
4817 | 5.95k | auto res = d->runWithCodeParam( |
4818 | 5.95k | "SELECT ellipsoid.name, ellipsoid.semi_major_axis, " |
4819 | 5.95k | "ellipsoid.uom_auth_name, ellipsoid.uom_code, " |
4820 | 5.95k | "ellipsoid.inv_flattening, ellipsoid.semi_minor_axis, " |
4821 | 5.95k | "celestial_body.name AS body_name, ellipsoid.deprecated FROM " |
4822 | 5.95k | "ellipsoid JOIN celestial_body " |
4823 | 5.95k | "ON ellipsoid.celestial_body_auth_name = celestial_body.auth_name AND " |
4824 | 5.95k | "ellipsoid.celestial_body_code = celestial_body.code WHERE " |
4825 | 5.95k | "ellipsoid.auth_name = ? AND ellipsoid.code = ?", |
4826 | 5.95k | code); |
4827 | 5.95k | if (res.empty()) { |
4828 | 0 | throw NoSuchAuthorityCodeException("ellipsoid not found", |
4829 | 0 | d->authority(), code); |
4830 | 0 | } |
4831 | 5.95k | try { |
4832 | 5.95k | const auto &row = res.front(); |
4833 | 5.95k | const auto &name = row[0]; |
4834 | 5.95k | const auto &semi_major_axis_str = row[1]; |
4835 | 5.95k | double semi_major_axis = c_locale_stod(semi_major_axis_str); |
4836 | 5.95k | const auto &uom_auth_name = row[2]; |
4837 | 5.95k | const auto &uom_code = row[3]; |
4838 | 5.95k | const auto &inv_flattening_str = row[4]; |
4839 | 5.95k | const auto &semi_minor_axis_str = row[5]; |
4840 | 5.95k | const auto &body = row[6]; |
4841 | 5.95k | const bool deprecated = row[7] == "1"; |
4842 | 5.95k | auto uom = d->createUnitOfMeasure(uom_auth_name, uom_code); |
4843 | 5.95k | auto props = d->createProperties(code, name, deprecated, {}); |
4844 | 5.95k | if (!inv_flattening_str.empty()) { |
4845 | 5.22k | auto ellps = datum::Ellipsoid::createFlattenedSphere( |
4846 | 5.22k | props, common::Length(semi_major_axis, uom), |
4847 | 5.22k | common::Scale(c_locale_stod(inv_flattening_str)), body); |
4848 | 5.22k | d->context()->d->cache(cacheKey, ellps); |
4849 | 5.22k | return ellps; |
4850 | 5.22k | } else if (semi_major_axis_str == semi_minor_axis_str) { |
4851 | 54 | auto ellps = datum::Ellipsoid::createSphere( |
4852 | 54 | props, common::Length(semi_major_axis, uom), body); |
4853 | 54 | d->context()->d->cache(cacheKey, ellps); |
4854 | 54 | return ellps; |
4855 | 682 | } else { |
4856 | 682 | auto ellps = datum::Ellipsoid::createTwoAxis( |
4857 | 682 | props, common::Length(semi_major_axis, uom), |
4858 | 682 | common::Length(c_locale_stod(semi_minor_axis_str), uom), body); |
4859 | 682 | d->context()->d->cache(cacheKey, ellps); |
4860 | 682 | return ellps; |
4861 | 682 | } |
4862 | 5.95k | } catch (const std::exception &ex) { |
4863 | 0 | throw buildFactoryException("ellipsoid", d->authority(), code, ex); |
4864 | 0 | } |
4865 | 5.95k | } |
4866 | | |
4867 | | // --------------------------------------------------------------------------- |
4868 | | |
4869 | | /** \brief Returns a datum::GeodeticReferenceFrame from the specified code. |
4870 | | * |
4871 | | * @param code Object code allocated by authority. |
4872 | | * @return object. |
4873 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
4874 | | * @throw FactoryException in case of other errors. |
4875 | | */ |
4876 | | |
4877 | | datum::GeodeticReferenceFrameNNPtr |
4878 | 252k | AuthorityFactory::createGeodeticDatum(const std::string &code) const { |
4879 | | |
4880 | 252k | datum::GeodeticReferenceFramePtr datum; |
4881 | 252k | datum::DatumEnsemblePtr datumEnsemble; |
4882 | 252k | constexpr bool turnEnsembleAsDatum = true; |
4883 | 252k | createGeodeticDatumOrEnsemble(code, datum, datumEnsemble, |
4884 | 252k | turnEnsembleAsDatum); |
4885 | 252k | return NN_NO_CHECK(datum); |
4886 | 252k | } |
4887 | | |
4888 | | // --------------------------------------------------------------------------- |
4889 | | |
4890 | | void AuthorityFactory::createGeodeticDatumOrEnsemble( |
4891 | | const std::string &code, datum::GeodeticReferenceFramePtr &outDatum, |
4892 | 285k | datum::DatumEnsemblePtr &outDatumEnsemble, bool turnEnsembleAsDatum) const { |
4893 | 285k | const auto cacheKey(d->authority() + code); |
4894 | 285k | { |
4895 | 285k | outDatumEnsemble = d->context()->d->getDatumEnsembleFromCache(cacheKey); |
4896 | 285k | if (outDatumEnsemble) { |
4897 | 249k | if (!turnEnsembleAsDatum) |
4898 | 18.4k | return; |
4899 | 230k | outDatumEnsemble = nullptr; |
4900 | 230k | } |
4901 | 267k | outDatum = d->context()->d->getGeodeticDatumFromCache(cacheKey); |
4902 | 267k | if (outDatum) { |
4903 | 233k | return; |
4904 | 233k | } |
4905 | 267k | } |
4906 | 33.3k | auto res = d->runWithCodeParam( |
4907 | 33.3k | "SELECT name, ellipsoid_auth_name, ellipsoid_code, " |
4908 | 33.3k | "prime_meridian_auth_name, prime_meridian_code, " |
4909 | 33.3k | "publication_date, frame_reference_epoch, " |
4910 | 33.3k | "ensemble_accuracy, anchor, anchor_epoch, deprecated " |
4911 | 33.3k | "FROM geodetic_datum " |
4912 | 33.3k | "WHERE " |
4913 | 33.3k | "auth_name = ? AND code = ?", |
4914 | 33.3k | code); |
4915 | 33.3k | if (res.empty()) { |
4916 | 28 | throw NoSuchAuthorityCodeException("geodetic datum not found", |
4917 | 28 | d->authority(), code); |
4918 | 28 | } |
4919 | 33.3k | try { |
4920 | 33.3k | const auto &row = res.front(); |
4921 | 33.3k | const auto &name = row[0]; |
4922 | 33.3k | const auto &ellipsoid_auth_name = row[1]; |
4923 | 33.3k | const auto &ellipsoid_code = row[2]; |
4924 | 33.3k | const auto &prime_meridian_auth_name = row[3]; |
4925 | 33.3k | const auto &prime_meridian_code = row[4]; |
4926 | 33.3k | const auto &publication_date = row[5]; |
4927 | 33.3k | const auto &frame_reference_epoch = row[6]; |
4928 | 33.3k | const auto &ensemble_accuracy = row[7]; |
4929 | 33.3k | const auto &anchor = row[8]; |
4930 | 33.3k | const auto &anchor_epoch = row[9]; |
4931 | 33.3k | const bool deprecated = row[10] == "1"; |
4932 | | |
4933 | 33.3k | std::string massagedName = name; |
4934 | 33.3k | if (turnEnsembleAsDatum) { |
4935 | 23.7k | if (name == "World Geodetic System 1984 ensemble") { |
4936 | 2.10k | massagedName = "World Geodetic System 1984"; |
4937 | 21.6k | } else if (name == |
4938 | 21.6k | "European Terrestrial Reference System 1989 ensemble") { |
4939 | 109 | massagedName = "European Terrestrial Reference System 1989"; |
4940 | 109 | } |
4941 | 23.7k | } |
4942 | 33.3k | auto props = d->createPropertiesSearchUsages("geodetic_datum", code, |
4943 | 33.3k | massagedName, deprecated); |
4944 | | |
4945 | 33.3k | if (!turnEnsembleAsDatum && !ensemble_accuracy.empty()) { |
4946 | 2.61k | auto resMembers = |
4947 | 2.61k | d->run("SELECT member_auth_name, member_code FROM " |
4948 | 2.61k | "geodetic_datum_ensemble_member WHERE " |
4949 | 2.61k | "ensemble_auth_name = ? AND ensemble_code = ? " |
4950 | 2.61k | "ORDER BY sequence", |
4951 | 2.61k | {d->authority(), code}); |
4952 | | |
4953 | 2.61k | std::vector<datum::DatumNNPtr> members; |
4954 | 21.7k | for (const auto &memberRow : resMembers) { |
4955 | 21.7k | members.push_back( |
4956 | 21.7k | d->createFactory(memberRow[0])->createDatum(memberRow[1])); |
4957 | 21.7k | } |
4958 | 2.61k | auto datumEnsemble = datum::DatumEnsemble::create( |
4959 | 2.61k | props, std::move(members), |
4960 | 2.61k | metadata::PositionalAccuracy::create(ensemble_accuracy)); |
4961 | 2.61k | d->context()->d->cache(cacheKey, datumEnsemble); |
4962 | 2.61k | outDatumEnsemble = datumEnsemble.as_nullable(); |
4963 | 30.7k | } else { |
4964 | 30.7k | auto ellipsoid = d->createFactory(ellipsoid_auth_name) |
4965 | 30.7k | ->createEllipsoid(ellipsoid_code); |
4966 | 30.7k | auto pm = d->createFactory(prime_meridian_auth_name) |
4967 | 30.7k | ->createPrimeMeridian(prime_meridian_code); |
4968 | | |
4969 | 30.7k | auto anchorOpt = util::optional<std::string>(); |
4970 | 30.7k | if (!anchor.empty()) |
4971 | 61 | anchorOpt = anchor; |
4972 | 30.7k | if (!publication_date.empty()) { |
4973 | 27.4k | props.set("PUBLICATION_DATE", publication_date); |
4974 | 27.4k | } |
4975 | 30.7k | if (!anchor_epoch.empty()) { |
4976 | 548 | props.set("ANCHOR_EPOCH", anchor_epoch); |
4977 | 548 | } |
4978 | 30.7k | auto datum = frame_reference_epoch.empty() |
4979 | 30.7k | ? datum::GeodeticReferenceFrame::create( |
4980 | 8.03k | props, ellipsoid, anchorOpt, pm) |
4981 | 30.7k | : util::nn_static_pointer_cast< |
4982 | 22.7k | datum::GeodeticReferenceFrame>( |
4983 | 22.7k | datum::DynamicGeodeticReferenceFrame::create( |
4984 | 22.7k | props, ellipsoid, anchorOpt, pm, |
4985 | 22.7k | common::Measure( |
4986 | 22.7k | c_locale_stod(frame_reference_epoch), |
4987 | 22.7k | common::UnitOfMeasure::YEAR), |
4988 | 22.7k | util::optional<std::string>())); |
4989 | 30.7k | d->context()->d->cache(cacheKey, datum); |
4990 | 30.7k | outDatum = datum.as_nullable(); |
4991 | 30.7k | } |
4992 | 33.3k | } catch (const std::exception &ex) { |
4993 | 0 | throw buildFactoryException("geodetic reference frame", d->authority(), |
4994 | 0 | code, ex); |
4995 | 0 | } |
4996 | 33.3k | } |
4997 | | |
4998 | | // --------------------------------------------------------------------------- |
4999 | | |
5000 | | /** \brief Returns a datum::VerticalReferenceFrame from the specified code. |
5001 | | * |
5002 | | * @param code Object code allocated by authority. |
5003 | | * @return object. |
5004 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5005 | | * @throw FactoryException in case of other errors. |
5006 | | */ |
5007 | | |
5008 | | datum::VerticalReferenceFrameNNPtr |
5009 | 114 | AuthorityFactory::createVerticalDatum(const std::string &code) const { |
5010 | 114 | datum::VerticalReferenceFramePtr datum; |
5011 | 114 | datum::DatumEnsemblePtr datumEnsemble; |
5012 | 114 | constexpr bool turnEnsembleAsDatum = true; |
5013 | 114 | createVerticalDatumOrEnsemble(code, datum, datumEnsemble, |
5014 | 114 | turnEnsembleAsDatum); |
5015 | 114 | return NN_NO_CHECK(datum); |
5016 | 114 | } |
5017 | | |
5018 | | // --------------------------------------------------------------------------- |
5019 | | |
5020 | | void AuthorityFactory::createVerticalDatumOrEnsemble( |
5021 | | const std::string &code, datum::VerticalReferenceFramePtr &outDatum, |
5022 | 1.31k | datum::DatumEnsemblePtr &outDatumEnsemble, bool turnEnsembleAsDatum) const { |
5023 | 1.31k | auto res = |
5024 | 1.31k | d->runWithCodeParam("SELECT name, publication_date, " |
5025 | 1.31k | "frame_reference_epoch, ensemble_accuracy, anchor, " |
5026 | 1.31k | "anchor_epoch, deprecated FROM " |
5027 | 1.31k | "vertical_datum WHERE auth_name = ? AND code = ?", |
5028 | 1.31k | code); |
5029 | 1.31k | if (res.empty()) { |
5030 | 0 | throw NoSuchAuthorityCodeException("vertical datum not found", |
5031 | 0 | d->authority(), code); |
5032 | 0 | } |
5033 | 1.31k | try { |
5034 | 1.31k | const auto &row = res.front(); |
5035 | 1.31k | const auto &name = row[0]; |
5036 | 1.31k | const auto &publication_date = row[1]; |
5037 | 1.31k | const auto &frame_reference_epoch = row[2]; |
5038 | 1.31k | const auto &ensemble_accuracy = row[3]; |
5039 | 1.31k | const auto &anchor = row[4]; |
5040 | 1.31k | const auto &anchor_epoch = row[5]; |
5041 | 1.31k | const bool deprecated = row[6] == "1"; |
5042 | 1.31k | auto props = d->createPropertiesSearchUsages("vertical_datum", code, |
5043 | 1.31k | name, deprecated); |
5044 | 1.31k | if (!turnEnsembleAsDatum && !ensemble_accuracy.empty()) { |
5045 | 22 | auto resMembers = |
5046 | 22 | d->run("SELECT member_auth_name, member_code FROM " |
5047 | 22 | "vertical_datum_ensemble_member WHERE " |
5048 | 22 | "ensemble_auth_name = ? AND ensemble_code = ? " |
5049 | 22 | "ORDER BY sequence", |
5050 | 22 | {d->authority(), code}); |
5051 | | |
5052 | 22 | std::vector<datum::DatumNNPtr> members; |
5053 | 114 | for (const auto &memberRow : resMembers) { |
5054 | 114 | members.push_back( |
5055 | 114 | d->createFactory(memberRow[0])->createDatum(memberRow[1])); |
5056 | 114 | } |
5057 | 22 | auto datumEnsemble = datum::DatumEnsemble::create( |
5058 | 22 | props, std::move(members), |
5059 | 22 | metadata::PositionalAccuracy::create(ensemble_accuracy)); |
5060 | 22 | outDatumEnsemble = datumEnsemble.as_nullable(); |
5061 | 1.28k | } else { |
5062 | 1.28k | if (!publication_date.empty()) { |
5063 | 565 | props.set("PUBLICATION_DATE", publication_date); |
5064 | 565 | } |
5065 | 1.28k | if (!anchor_epoch.empty()) { |
5066 | 15 | props.set("ANCHOR_EPOCH", anchor_epoch); |
5067 | 15 | } |
5068 | 1.28k | if (d->authority() == "ESRI" && |
5069 | 1.28k | starts_with(code, "from_geogdatum_")) { |
5070 | 487 | props.set("VERT_DATUM_TYPE", "2002"); |
5071 | 487 | } |
5072 | 1.28k | auto anchorOpt = util::optional<std::string>(); |
5073 | 1.28k | if (!anchor.empty()) |
5074 | 0 | anchorOpt = anchor; |
5075 | 1.28k | if (frame_reference_epoch.empty()) { |
5076 | 1.27k | outDatum = |
5077 | 1.27k | datum::VerticalReferenceFrame::create(props, anchorOpt) |
5078 | 1.27k | .as_nullable(); |
5079 | 1.27k | } else { |
5080 | 12 | outDatum = |
5081 | 12 | datum::DynamicVerticalReferenceFrame::create( |
5082 | 12 | props, anchorOpt, |
5083 | 12 | util::optional<datum::RealizationMethod>(), |
5084 | 12 | common::Measure(c_locale_stod(frame_reference_epoch), |
5085 | 12 | common::UnitOfMeasure::YEAR), |
5086 | 12 | util::optional<std::string>()) |
5087 | 12 | .as_nullable(); |
5088 | 12 | } |
5089 | 1.28k | } |
5090 | 1.31k | } catch (const std::exception &ex) { |
5091 | 0 | throw buildFactoryException("vertical reference frame", d->authority(), |
5092 | 0 | code, ex); |
5093 | 0 | } |
5094 | 1.31k | } |
5095 | | |
5096 | | // --------------------------------------------------------------------------- |
5097 | | |
5098 | | /** \brief Returns a datum::EngineeringDatum from the specified code. |
5099 | | * |
5100 | | * @param code Object code allocated by authority. |
5101 | | * @return object. |
5102 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5103 | | * @throw FactoryException in case of other errors. |
5104 | | * @since 9.6 |
5105 | | */ |
5106 | | |
5107 | | datum::EngineeringDatumNNPtr |
5108 | 17 | AuthorityFactory::createEngineeringDatum(const std::string &code) const { |
5109 | 17 | auto res = d->runWithCodeParam( |
5110 | 17 | "SELECT name, publication_date, " |
5111 | 17 | "anchor, anchor_epoch, deprecated FROM " |
5112 | 17 | "engineering_datum WHERE auth_name = ? AND code = ?", |
5113 | 17 | code); |
5114 | 17 | if (res.empty()) { |
5115 | 0 | throw NoSuchAuthorityCodeException("engineering datum not found", |
5116 | 0 | d->authority(), code); |
5117 | 0 | } |
5118 | 17 | try { |
5119 | 17 | const auto &row = res.front(); |
5120 | 17 | const auto &name = row[0]; |
5121 | 17 | const auto &publication_date = row[1]; |
5122 | 17 | const auto &anchor = row[2]; |
5123 | 17 | const auto &anchor_epoch = row[3]; |
5124 | 17 | const bool deprecated = row[4] == "1"; |
5125 | 17 | auto props = d->createPropertiesSearchUsages("engineering_datum", code, |
5126 | 17 | name, deprecated); |
5127 | | |
5128 | 17 | if (!publication_date.empty()) { |
5129 | 1 | props.set("PUBLICATION_DATE", publication_date); |
5130 | 1 | } |
5131 | 17 | if (!anchor_epoch.empty()) { |
5132 | 0 | props.set("ANCHOR_EPOCH", anchor_epoch); |
5133 | 0 | } |
5134 | 17 | auto anchorOpt = util::optional<std::string>(); |
5135 | 17 | if (!anchor.empty()) |
5136 | 0 | anchorOpt = anchor; |
5137 | 17 | return datum::EngineeringDatum::create(props, anchorOpt); |
5138 | 17 | } catch (const std::exception &ex) { |
5139 | 0 | throw buildFactoryException("engineering datum", d->authority(), code, |
5140 | 0 | ex); |
5141 | 0 | } |
5142 | 17 | } |
5143 | | |
5144 | | // --------------------------------------------------------------------------- |
5145 | | |
5146 | | /** \brief Returns a datum::DatumEnsemble from the specified code. |
5147 | | * |
5148 | | * @param code Object code allocated by authority. |
5149 | | * @param type "geodetic_datum", "vertical_datum" or empty string if unknown |
5150 | | * @return object. |
5151 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5152 | | * @throw FactoryException in case of other errors. |
5153 | | */ |
5154 | | |
5155 | | datum::DatumEnsembleNNPtr |
5156 | | AuthorityFactory::createDatumEnsemble(const std::string &code, |
5157 | 0 | const std::string &type) const { |
5158 | 0 | auto res = d->run( |
5159 | 0 | "SELECT 'geodetic_datum', name, ensemble_accuracy, deprecated FROM " |
5160 | 0 | "geodetic_datum WHERE " |
5161 | 0 | "auth_name = ? AND code = ? AND ensemble_accuracy IS NOT NULL " |
5162 | 0 | "UNION ALL " |
5163 | 0 | "SELECT 'vertical_datum', name, ensemble_accuracy, deprecated FROM " |
5164 | 0 | "vertical_datum WHERE " |
5165 | 0 | "auth_name = ? AND code = ? AND ensemble_accuracy IS NOT NULL", |
5166 | 0 | {d->authority(), code, d->authority(), code}); |
5167 | 0 | if (res.empty()) { |
5168 | 0 | throw NoSuchAuthorityCodeException("datum ensemble not found", |
5169 | 0 | d->authority(), code); |
5170 | 0 | } |
5171 | 0 | for (const auto &row : res) { |
5172 | 0 | const std::string &gotType = row[0]; |
5173 | 0 | const std::string &name = row[1]; |
5174 | 0 | const std::string &ensembleAccuracy = row[2]; |
5175 | 0 | const bool deprecated = row[3] == "1"; |
5176 | 0 | if (type.empty() || type == gotType) { |
5177 | 0 | auto resMembers = |
5178 | 0 | d->run("SELECT member_auth_name, member_code FROM " + gotType + |
5179 | 0 | "_ensemble_member WHERE " |
5180 | 0 | "ensemble_auth_name = ? AND ensemble_code = ? " |
5181 | 0 | "ORDER BY sequence", |
5182 | 0 | {d->authority(), code}); |
5183 | |
|
5184 | 0 | std::vector<datum::DatumNNPtr> members; |
5185 | 0 | for (const auto &memberRow : resMembers) { |
5186 | 0 | members.push_back( |
5187 | 0 | d->createFactory(memberRow[0])->createDatum(memberRow[1])); |
5188 | 0 | } |
5189 | 0 | auto props = d->createPropertiesSearchUsages(gotType, code, name, |
5190 | 0 | deprecated); |
5191 | 0 | return datum::DatumEnsemble::create( |
5192 | 0 | props, std::move(members), |
5193 | 0 | metadata::PositionalAccuracy::create(ensembleAccuracy)); |
5194 | 0 | } |
5195 | 0 | } |
5196 | 0 | throw NoSuchAuthorityCodeException("datum ensemble not found", |
5197 | 0 | d->authority(), code); |
5198 | 0 | } |
5199 | | |
5200 | | // --------------------------------------------------------------------------- |
5201 | | |
5202 | | /** \brief Returns a datum::Datum from the specified code. |
5203 | | * |
5204 | | * @param code Object code allocated by authority. |
5205 | | * @return object. |
5206 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5207 | | * @throw FactoryException in case of other errors. |
5208 | | */ |
5209 | | |
5210 | 21.8k | datum::DatumNNPtr AuthorityFactory::createDatum(const std::string &code) const { |
5211 | 21.8k | auto res = d->run( |
5212 | 21.8k | "SELECT 'geodetic_datum' FROM geodetic_datum WHERE " |
5213 | 21.8k | "auth_name = ? AND code = ? " |
5214 | 21.8k | "UNION ALL SELECT 'vertical_datum' FROM vertical_datum WHERE " |
5215 | 21.8k | "auth_name = ? AND code = ? " |
5216 | 21.8k | "UNION ALL SELECT 'engineering_datum' FROM engineering_datum " |
5217 | 21.8k | "WHERE " |
5218 | 21.8k | "auth_name = ? AND code = ?", |
5219 | 21.8k | {d->authority(), code, d->authority(), code, d->authority(), code}); |
5220 | 21.8k | if (res.empty()) { |
5221 | 0 | throw NoSuchAuthorityCodeException("datum not found", d->authority(), |
5222 | 0 | code); |
5223 | 0 | } |
5224 | 21.8k | const auto &type = res.front()[0]; |
5225 | 21.8k | if (type == "geodetic_datum") { |
5226 | 21.7k | return createGeodeticDatum(code); |
5227 | 21.7k | } |
5228 | 114 | if (type == "vertical_datum") { |
5229 | 114 | return createVerticalDatum(code); |
5230 | 114 | } |
5231 | 0 | return createEngineeringDatum(code); |
5232 | 114 | } |
5233 | | |
5234 | | // --------------------------------------------------------------------------- |
5235 | | |
5236 | | //! @cond Doxygen_Suppress |
5237 | 100 | static cs::MeridianPtr createMeridian(const std::string &val) { |
5238 | 100 | try { |
5239 | 100 | const std::string degW(std::string("\xC2\xB0") + "W"); |
5240 | 100 | if (ends_with(val, degW)) { |
5241 | 18 | return cs::Meridian::create(common::Angle( |
5242 | 18 | -c_locale_stod(val.substr(0, val.size() - degW.size())))); |
5243 | 18 | } |
5244 | 82 | const std::string degE(std::string("\xC2\xB0") + "E"); |
5245 | 82 | if (ends_with(val, degE)) { |
5246 | 82 | return cs::Meridian::create(common::Angle( |
5247 | 82 | c_locale_stod(val.substr(0, val.size() - degE.size())))); |
5248 | 82 | } |
5249 | 82 | } catch (const std::exception &) { |
5250 | 0 | } |
5251 | 0 | return nullptr; |
5252 | 100 | } |
5253 | | //! @endcond |
5254 | | |
5255 | | // --------------------------------------------------------------------------- |
5256 | | |
5257 | | /** \brief Returns a cs::CoordinateSystem from the specified code. |
5258 | | * |
5259 | | * @param code Object code allocated by authority. |
5260 | | * @return object. |
5261 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5262 | | * @throw FactoryException in case of other errors. |
5263 | | */ |
5264 | | |
5265 | | cs::CoordinateSystemNNPtr |
5266 | 35.9k | AuthorityFactory::createCoordinateSystem(const std::string &code) const { |
5267 | 35.9k | const auto cacheKey(d->authority() + code); |
5268 | 35.9k | { |
5269 | 35.9k | auto cs = d->context()->d->getCoordinateSystemFromCache(cacheKey); |
5270 | 35.9k | if (cs) { |
5271 | 23.1k | return NN_NO_CHECK(cs); |
5272 | 23.1k | } |
5273 | 35.9k | } |
5274 | 12.8k | auto res = d->runWithCodeParam( |
5275 | 12.8k | "SELECT axis.name, abbrev, orientation, uom_auth_name, uom_code, " |
5276 | 12.8k | "cs.type FROM " |
5277 | 12.8k | "axis LEFT JOIN coordinate_system cs ON " |
5278 | 12.8k | "axis.coordinate_system_auth_name = cs.auth_name AND " |
5279 | 12.8k | "axis.coordinate_system_code = cs.code WHERE " |
5280 | 12.8k | "coordinate_system_auth_name = ? AND coordinate_system_code = ? ORDER " |
5281 | 12.8k | "BY coordinate_system_order", |
5282 | 12.8k | code); |
5283 | 12.8k | if (res.empty()) { |
5284 | 0 | throw NoSuchAuthorityCodeException("coordinate system not found", |
5285 | 0 | d->authority(), code); |
5286 | 0 | } |
5287 | | |
5288 | 12.8k | const auto &csType = res.front()[5]; |
5289 | 12.8k | std::vector<cs::CoordinateSystemAxisNNPtr> axisList; |
5290 | 31.4k | for (const auto &row : res) { |
5291 | 31.4k | const auto &name = row[0]; |
5292 | 31.4k | const auto &abbrev = row[1]; |
5293 | 31.4k | const auto &orientation = row[2]; |
5294 | 31.4k | const auto &uom_auth_name = row[3]; |
5295 | 31.4k | const auto &uom_code = row[4]; |
5296 | 31.4k | if (uom_auth_name.empty() && csType != CS_TYPE_ORDINAL) { |
5297 | 0 | throw FactoryException("no unit of measure for an axis is only " |
5298 | 0 | "supported for ordinatal CS"); |
5299 | 0 | } |
5300 | 31.4k | auto uom = uom_auth_name.empty() |
5301 | 31.4k | ? common::UnitOfMeasure::NONE |
5302 | 31.4k | : d->createUnitOfMeasure(uom_auth_name, uom_code); |
5303 | 31.4k | auto props = |
5304 | 31.4k | util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, name); |
5305 | 31.4k | const cs::AxisDirection *direction = |
5306 | 31.4k | cs::AxisDirection::valueOf(orientation); |
5307 | 31.4k | cs::MeridianPtr meridian; |
5308 | 31.4k | if (direction == nullptr) { |
5309 | 100 | if (orientation == "Geocentre > equator/0" |
5310 | 100 | "\xC2\xB0" |
5311 | 100 | "E") { |
5312 | 0 | direction = &(cs::AxisDirection::GEOCENTRIC_X); |
5313 | 100 | } else if (orientation == "Geocentre > equator/90" |
5314 | 100 | "\xC2\xB0" |
5315 | 100 | "E") { |
5316 | 0 | direction = &(cs::AxisDirection::GEOCENTRIC_Y); |
5317 | 100 | } else if (orientation == "Geocentre > north pole") { |
5318 | 0 | direction = &(cs::AxisDirection::GEOCENTRIC_Z); |
5319 | 100 | } else if (starts_with(orientation, "North along ")) { |
5320 | 58 | direction = &(cs::AxisDirection::NORTH); |
5321 | 58 | meridian = |
5322 | 58 | createMeridian(orientation.substr(strlen("North along "))); |
5323 | 58 | } else if (starts_with(orientation, "South along ")) { |
5324 | 42 | direction = &(cs::AxisDirection::SOUTH); |
5325 | 42 | meridian = |
5326 | 42 | createMeridian(orientation.substr(strlen("South along "))); |
5327 | 42 | } else { |
5328 | 0 | throw FactoryException("unknown axis direction: " + |
5329 | 0 | orientation); |
5330 | 0 | } |
5331 | 100 | } |
5332 | 31.4k | axisList.emplace_back(cs::CoordinateSystemAxis::create( |
5333 | 31.4k | props, abbrev, *direction, uom, meridian)); |
5334 | 31.4k | } |
5335 | | |
5336 | 12.8k | const auto cacheAndRet = [this, |
5337 | 12.8k | &cacheKey](const cs::CoordinateSystemNNPtr &cs) { |
5338 | 12.8k | d->context()->d->cache(cacheKey, cs); |
5339 | 12.8k | return cs; |
5340 | 12.8k | }; |
5341 | | |
5342 | 12.8k | auto props = util::PropertyMap() |
5343 | 12.8k | .set(metadata::Identifier::CODESPACE_KEY, d->authority()) |
5344 | 12.8k | .set(metadata::Identifier::CODE_KEY, code); |
5345 | 12.8k | if (csType == CS_TYPE_ELLIPSOIDAL) { |
5346 | 8.91k | if (axisList.size() == 2) { |
5347 | 4.85k | return cacheAndRet( |
5348 | 4.85k | cs::EllipsoidalCS::create(props, axisList[0], axisList[1])); |
5349 | 4.85k | } |
5350 | 4.06k | if (axisList.size() == 3) { |
5351 | 4.06k | return cacheAndRet(cs::EllipsoidalCS::create( |
5352 | 4.06k | props, axisList[0], axisList[1], axisList[2])); |
5353 | 4.06k | } |
5354 | 0 | throw FactoryException("invalid number of axis for EllipsoidalCS"); |
5355 | 4.06k | } |
5356 | 3.89k | if (csType == CS_TYPE_CARTESIAN) { |
5357 | 3.35k | if (axisList.size() == 2) { |
5358 | 1.08k | return cacheAndRet( |
5359 | 1.08k | cs::CartesianCS::create(props, axisList[0], axisList[1])); |
5360 | 1.08k | } |
5361 | 2.26k | if (axisList.size() == 3) { |
5362 | 2.26k | return cacheAndRet(cs::CartesianCS::create( |
5363 | 2.26k | props, axisList[0], axisList[1], axisList[2])); |
5364 | 2.26k | } |
5365 | 0 | throw FactoryException("invalid number of axis for CartesianCS"); |
5366 | 2.26k | } |
5367 | 542 | if (csType == CS_TYPE_SPHERICAL) { |
5368 | 14 | if (axisList.size() == 2) { |
5369 | 14 | return cacheAndRet( |
5370 | 14 | cs::SphericalCS::create(props, axisList[0], axisList[1])); |
5371 | 14 | } |
5372 | 0 | if (axisList.size() == 3) { |
5373 | 0 | return cacheAndRet(cs::SphericalCS::create( |
5374 | 0 | props, axisList[0], axisList[1], axisList[2])); |
5375 | 0 | } |
5376 | 0 | throw FactoryException("invalid number of axis for SphericalCS"); |
5377 | 0 | } |
5378 | 528 | if (csType == CS_TYPE_VERTICAL) { |
5379 | 528 | if (axisList.size() == 1) { |
5380 | 528 | return cacheAndRet(cs::VerticalCS::create(props, axisList[0])); |
5381 | 528 | } |
5382 | 0 | throw FactoryException("invalid number of axis for VerticalCS"); |
5383 | 528 | } |
5384 | 0 | if (csType == CS_TYPE_ORDINAL) { |
5385 | 0 | return cacheAndRet(cs::OrdinalCS::create(props, axisList)); |
5386 | 0 | } |
5387 | 0 | throw FactoryException("unhandled coordinate system type: " + csType); |
5388 | 0 | } |
5389 | | |
5390 | | // --------------------------------------------------------------------------- |
5391 | | |
5392 | | /** \brief Returns a crs::GeodeticCRS from the specified code. |
5393 | | * |
5394 | | * @param code Object code allocated by authority. |
5395 | | * @return object. |
5396 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5397 | | * @throw FactoryException in case of other errors. |
5398 | | */ |
5399 | | |
5400 | | crs::GeodeticCRSNNPtr |
5401 | 111k | AuthorityFactory::createGeodeticCRS(const std::string &code) const { |
5402 | 111k | return createGeodeticCRS(code, false); |
5403 | 111k | } |
5404 | | |
5405 | | // --------------------------------------------------------------------------- |
5406 | | |
5407 | | /** \brief Returns a crs::GeographicCRS from the specified code. |
5408 | | * |
5409 | | * @param code Object code allocated by authority. |
5410 | | * @return object. |
5411 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5412 | | * @throw FactoryException in case of other errors. |
5413 | | */ |
5414 | | |
5415 | | crs::GeographicCRSNNPtr |
5416 | 592 | AuthorityFactory::createGeographicCRS(const std::string &code) const { |
5417 | 592 | auto crs(util::nn_dynamic_pointer_cast<crs::GeographicCRS>( |
5418 | 592 | createGeodeticCRS(code, true))); |
5419 | 592 | if (!crs) { |
5420 | 0 | throw NoSuchAuthorityCodeException("geographicCRS not found", |
5421 | 0 | d->authority(), code); |
5422 | 0 | } |
5423 | 592 | return NN_NO_CHECK(crs); |
5424 | 592 | } |
5425 | | |
5426 | | // --------------------------------------------------------------------------- |
5427 | | |
5428 | | static crs::GeodeticCRSNNPtr |
5429 | | cloneWithProps(const crs::GeodeticCRSNNPtr &geodCRS, |
5430 | 0 | const util::PropertyMap &props) { |
5431 | 0 | auto cs = geodCRS->coordinateSystem(); |
5432 | 0 | auto ellipsoidalCS = util::nn_dynamic_pointer_cast<cs::EllipsoidalCS>(cs); |
5433 | 0 | if (ellipsoidalCS) { |
5434 | 0 | return crs::GeographicCRS::create(props, geodCRS->datum(), |
5435 | 0 | geodCRS->datumEnsemble(), |
5436 | 0 | NN_NO_CHECK(ellipsoidalCS)); |
5437 | 0 | } |
5438 | 0 | auto geocentricCS = util::nn_dynamic_pointer_cast<cs::CartesianCS>(cs); |
5439 | 0 | if (geocentricCS) { |
5440 | 0 | return crs::GeodeticCRS::create(props, geodCRS->datum(), |
5441 | 0 | geodCRS->datumEnsemble(), |
5442 | 0 | NN_NO_CHECK(geocentricCS)); |
5443 | 0 | } |
5444 | 0 | return geodCRS; |
5445 | 0 | } |
5446 | | |
5447 | | // --------------------------------------------------------------------------- |
5448 | | |
5449 | | crs::GeodeticCRSNNPtr |
5450 | | AuthorityFactory::createGeodeticCRS(const std::string &code, |
5451 | 112k | bool geographicOnly) const { |
5452 | 112k | const auto cacheKey(d->authority() + code); |
5453 | 112k | auto crs = d->context()->d->getCRSFromCache(cacheKey); |
5454 | 112k | if (crs) { |
5455 | 80.1k | auto geogCRS = std::dynamic_pointer_cast<crs::GeodeticCRS>(crs); |
5456 | 80.1k | if (geogCRS) { |
5457 | 80.1k | return NN_NO_CHECK(geogCRS); |
5458 | 80.1k | } |
5459 | 0 | throw NoSuchAuthorityCodeException("geodeticCRS not found", |
5460 | 0 | d->authority(), code); |
5461 | 80.1k | } |
5462 | 32.3k | std::string sql("SELECT name, type, coordinate_system_auth_name, " |
5463 | 32.3k | "coordinate_system_code, datum_auth_name, datum_code, " |
5464 | 32.3k | "text_definition, deprecated, description FROM " |
5465 | 32.3k | "geodetic_crs WHERE auth_name = ? AND code = ?"); |
5466 | 32.3k | if (geographicOnly) { |
5467 | 16 | sql += " AND type in (" GEOG_2D_SINGLE_QUOTED "," GEOG_3D_SINGLE_QUOTED |
5468 | 16 | ")"; |
5469 | 16 | } |
5470 | 32.3k | auto res = d->runWithCodeParam(sql, code); |
5471 | 32.3k | if (res.empty()) { |
5472 | 16 | throw NoSuchAuthorityCodeException("geodeticCRS not found", |
5473 | 16 | d->authority(), code); |
5474 | 16 | } |
5475 | 32.3k | try { |
5476 | 32.3k | const auto &row = res.front(); |
5477 | 32.3k | const auto &name = row[0]; |
5478 | 32.3k | const auto &type = row[1]; |
5479 | 32.3k | const auto &cs_auth_name = row[2]; |
5480 | 32.3k | const auto &cs_code = row[3]; |
5481 | 32.3k | const auto &datum_auth_name = row[4]; |
5482 | 32.3k | const auto &datum_code = row[5]; |
5483 | 32.3k | const auto &text_definition = row[6]; |
5484 | 32.3k | const bool deprecated = row[7] == "1"; |
5485 | 32.3k | const auto &remarks = row[8]; |
5486 | | |
5487 | 32.3k | auto props = d->createPropertiesSearchUsages("geodetic_crs", code, name, |
5488 | 32.3k | deprecated, remarks); |
5489 | | |
5490 | 32.3k | if (!text_definition.empty()) { |
5491 | 0 | DatabaseContext::Private::RecursionDetector detector(d->context()); |
5492 | 0 | auto obj = createFromUserInput( |
5493 | 0 | pj_add_type_crs_if_needed(text_definition), d->context()); |
5494 | 0 | auto geodCRS = util::nn_dynamic_pointer_cast<crs::GeodeticCRS>(obj); |
5495 | 0 | if (geodCRS) { |
5496 | 0 | auto crsRet = cloneWithProps(NN_NO_CHECK(geodCRS), props); |
5497 | 0 | d->context()->d->cache(cacheKey, crsRet); |
5498 | 0 | return crsRet; |
5499 | 0 | } |
5500 | | |
5501 | 0 | auto boundCRS = dynamic_cast<const crs::BoundCRS *>(obj.get()); |
5502 | 0 | if (boundCRS) { |
5503 | 0 | geodCRS = util::nn_dynamic_pointer_cast<crs::GeodeticCRS>( |
5504 | 0 | boundCRS->baseCRS()); |
5505 | 0 | if (geodCRS) { |
5506 | 0 | auto newBoundCRS = crs::BoundCRS::create( |
5507 | 0 | cloneWithProps(NN_NO_CHECK(geodCRS), props), |
5508 | 0 | boundCRS->hubCRS(), boundCRS->transformation()); |
5509 | 0 | return NN_NO_CHECK( |
5510 | 0 | util::nn_dynamic_pointer_cast<crs::GeodeticCRS>( |
5511 | 0 | newBoundCRS->baseCRSWithCanonicalBoundCRS())); |
5512 | 0 | } |
5513 | 0 | } |
5514 | | |
5515 | 0 | throw FactoryException( |
5516 | 0 | "text_definition does not define a GeodeticCRS"); |
5517 | 0 | } |
5518 | | |
5519 | 32.3k | auto cs = |
5520 | 32.3k | d->createFactory(cs_auth_name)->createCoordinateSystem(cs_code); |
5521 | 32.3k | datum::GeodeticReferenceFramePtr datum; |
5522 | 32.3k | datum::DatumEnsemblePtr datumEnsemble; |
5523 | 32.3k | constexpr bool turnEnsembleAsDatum = false; |
5524 | 32.3k | d->createFactory(datum_auth_name) |
5525 | 32.3k | ->createGeodeticDatumOrEnsemble(datum_code, datum, datumEnsemble, |
5526 | 32.3k | turnEnsembleAsDatum); |
5527 | | |
5528 | 32.3k | auto ellipsoidalCS = |
5529 | 32.3k | util::nn_dynamic_pointer_cast<cs::EllipsoidalCS>(cs); |
5530 | 32.3k | if ((type == GEOG_2D || type == GEOG_3D) && ellipsoidalCS) { |
5531 | 24.2k | auto crsRet = crs::GeographicCRS::create( |
5532 | 24.2k | props, datum, datumEnsemble, NN_NO_CHECK(ellipsoidalCS)); |
5533 | 24.2k | d->context()->d->cache(cacheKey, crsRet); |
5534 | 24.2k | return crsRet; |
5535 | 24.2k | } |
5536 | | |
5537 | 8.10k | auto geocentricCS = util::nn_dynamic_pointer_cast<cs::CartesianCS>(cs); |
5538 | 8.10k | if (type == GEOCENTRIC && geocentricCS) { |
5539 | 8.07k | auto crsRet = crs::GeodeticCRS::create(props, datum, datumEnsemble, |
5540 | 8.07k | NN_NO_CHECK(geocentricCS)); |
5541 | 8.07k | d->context()->d->cache(cacheKey, crsRet); |
5542 | 8.07k | return crsRet; |
5543 | 8.07k | } |
5544 | | |
5545 | 30 | auto sphericalCS = util::nn_dynamic_pointer_cast<cs::SphericalCS>(cs); |
5546 | 30 | if (type == OTHER && sphericalCS) { |
5547 | 30 | auto crsRet = crs::GeodeticCRS::create(props, datum, datumEnsemble, |
5548 | 30 | NN_NO_CHECK(sphericalCS)); |
5549 | 30 | d->context()->d->cache(cacheKey, crsRet); |
5550 | 30 | return crsRet; |
5551 | 30 | } |
5552 | | |
5553 | 0 | throw FactoryException("unsupported (type, CS type) for geodeticCRS: " + |
5554 | 0 | type + ", " + cs->getWKT2Type(true)); |
5555 | 30 | } catch (const std::exception &ex) { |
5556 | 0 | throw buildFactoryException("geodeticCRS", d->authority(), code, ex); |
5557 | 0 | } |
5558 | 32.3k | } |
5559 | | |
5560 | | // --------------------------------------------------------------------------- |
5561 | | |
5562 | | /** \brief Returns a crs::VerticalCRS from the specified code. |
5563 | | * |
5564 | | * @param code Object code allocated by authority. |
5565 | | * @return object. |
5566 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5567 | | * @throw FactoryException in case of other errors. |
5568 | | */ |
5569 | | |
5570 | | crs::VerticalCRSNNPtr |
5571 | 1.30k | AuthorityFactory::createVerticalCRS(const std::string &code) const { |
5572 | 1.30k | const auto cacheKey(d->authority() + code); |
5573 | 1.30k | auto crs = d->context()->d->getCRSFromCache(cacheKey); |
5574 | 1.30k | if (crs) { |
5575 | 283 | auto projCRS = std::dynamic_pointer_cast<crs::VerticalCRS>(crs); |
5576 | 283 | if (projCRS) { |
5577 | 283 | return NN_NO_CHECK(projCRS); |
5578 | 283 | } |
5579 | 0 | throw NoSuchAuthorityCodeException("verticalCRS not found", |
5580 | 0 | d->authority(), code); |
5581 | 283 | } |
5582 | 1.02k | auto res = d->runWithCodeParam( |
5583 | 1.02k | "SELECT name, coordinate_system_auth_name, " |
5584 | 1.02k | "coordinate_system_code, datum_auth_name, datum_code, " |
5585 | 1.02k | "deprecated FROM " |
5586 | 1.02k | "vertical_crs WHERE auth_name = ? AND code = ?", |
5587 | 1.02k | code); |
5588 | 1.02k | if (res.empty()) { |
5589 | 0 | throw NoSuchAuthorityCodeException("verticalCRS not found", |
5590 | 0 | d->authority(), code); |
5591 | 0 | } |
5592 | 1.02k | try { |
5593 | 1.02k | const auto &row = res.front(); |
5594 | 1.02k | const auto &name = row[0]; |
5595 | 1.02k | const auto &cs_auth_name = row[1]; |
5596 | 1.02k | const auto &cs_code = row[2]; |
5597 | 1.02k | const auto &datum_auth_name = row[3]; |
5598 | 1.02k | const auto &datum_code = row[4]; |
5599 | 1.02k | const bool deprecated = row[5] == "1"; |
5600 | 1.02k | auto cs = |
5601 | 1.02k | d->createFactory(cs_auth_name)->createCoordinateSystem(cs_code); |
5602 | 1.02k | datum::VerticalReferenceFramePtr datum; |
5603 | 1.02k | datum::DatumEnsemblePtr datumEnsemble; |
5604 | 1.02k | constexpr bool turnEnsembleAsDatum = false; |
5605 | 1.02k | d->createFactory(datum_auth_name) |
5606 | 1.02k | ->createVerticalDatumOrEnsemble(datum_code, datum, datumEnsemble, |
5607 | 1.02k | turnEnsembleAsDatum); |
5608 | 1.02k | auto props = d->createPropertiesSearchUsages("vertical_crs", code, name, |
5609 | 1.02k | deprecated); |
5610 | | |
5611 | 1.02k | auto verticalCS = util::nn_dynamic_pointer_cast<cs::VerticalCS>(cs); |
5612 | 1.02k | if (verticalCS) { |
5613 | 1.02k | auto crsRet = crs::VerticalCRS::create(props, datum, datumEnsemble, |
5614 | 1.02k | NN_NO_CHECK(verticalCS)); |
5615 | 1.02k | d->context()->d->cache(cacheKey, crsRet); |
5616 | 1.02k | return crsRet; |
5617 | 1.02k | } |
5618 | 0 | throw FactoryException("unsupported CS type for verticalCRS: " + |
5619 | 0 | cs->getWKT2Type(true)); |
5620 | 1.02k | } catch (const std::exception &ex) { |
5621 | 0 | throw buildFactoryException("verticalCRS", d->authority(), code, ex); |
5622 | 0 | } |
5623 | 1.02k | } |
5624 | | |
5625 | | // --------------------------------------------------------------------------- |
5626 | | |
5627 | | /** \brief Returns a crs::EngineeringCRS from the specified code. |
5628 | | * |
5629 | | * @param code Object code allocated by authority. |
5630 | | * @return object. |
5631 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5632 | | * @throw FactoryException in case of other errors. |
5633 | | * @since 9.6 |
5634 | | */ |
5635 | | |
5636 | | crs::EngineeringCRSNNPtr |
5637 | 11 | AuthorityFactory::createEngineeringCRS(const std::string &code) const { |
5638 | 11 | const auto cacheKey(d->authority() + code); |
5639 | 11 | auto crs = d->context()->d->getCRSFromCache(cacheKey); |
5640 | 11 | if (crs) { |
5641 | 0 | auto engCRS = std::dynamic_pointer_cast<crs::EngineeringCRS>(crs); |
5642 | 0 | if (engCRS) { |
5643 | 0 | return NN_NO_CHECK(engCRS); |
5644 | 0 | } |
5645 | 0 | throw NoSuchAuthorityCodeException("engineeringCRS not found", |
5646 | 0 | d->authority(), code); |
5647 | 0 | } |
5648 | 11 | auto res = d->runWithCodeParam( |
5649 | 11 | "SELECT name, coordinate_system_auth_name, " |
5650 | 11 | "coordinate_system_code, datum_auth_name, datum_code, " |
5651 | 11 | "deprecated FROM " |
5652 | 11 | "engineering_crs WHERE auth_name = ? AND code = ?", |
5653 | 11 | code); |
5654 | 11 | if (res.empty()) { |
5655 | 0 | throw NoSuchAuthorityCodeException("engineeringCRS not found", |
5656 | 0 | d->authority(), code); |
5657 | 0 | } |
5658 | 11 | try { |
5659 | 11 | const auto &row = res.front(); |
5660 | 11 | const auto &name = row[0]; |
5661 | 11 | const auto &cs_auth_name = row[1]; |
5662 | 11 | const auto &cs_code = row[2]; |
5663 | 11 | const auto &datum_auth_name = row[3]; |
5664 | 11 | const auto &datum_code = row[4]; |
5665 | 11 | const bool deprecated = row[5] == "1"; |
5666 | 11 | auto cs = |
5667 | 11 | d->createFactory(cs_auth_name)->createCoordinateSystem(cs_code); |
5668 | 11 | auto datum = d->createFactory(datum_auth_name) |
5669 | 11 | ->createEngineeringDatum(datum_code); |
5670 | 11 | auto props = d->createPropertiesSearchUsages("engineering_crs", code, |
5671 | 11 | name, deprecated); |
5672 | 11 | auto crsRet = crs::EngineeringCRS::create(props, datum, cs); |
5673 | 11 | d->context()->d->cache(cacheKey, crsRet); |
5674 | 11 | return crsRet; |
5675 | 11 | } catch (const std::exception &ex) { |
5676 | 0 | throw buildFactoryException("engineeringCRS", d->authority(), code, ex); |
5677 | 0 | } |
5678 | 11 | } |
5679 | | |
5680 | | // --------------------------------------------------------------------------- |
5681 | | |
5682 | | /** \brief Returns a operation::Conversion from the specified code. |
5683 | | * |
5684 | | * @param code Object code allocated by authority. |
5685 | | * @return object. |
5686 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5687 | | * @throw FactoryException in case of other errors. |
5688 | | */ |
5689 | | |
5690 | | operation::ConversionNNPtr |
5691 | 3.06k | AuthorityFactory::createConversion(const std::string &code) const { |
5692 | | |
5693 | 3.06k | static const char *sql = |
5694 | 3.06k | "SELECT name, description, " |
5695 | 3.06k | "method_auth_name, method_code, method_name, " |
5696 | | |
5697 | 3.06k | "param1_auth_name, param1_code, param1_name, param1_value, " |
5698 | 3.06k | "param1_uom_auth_name, param1_uom_code, " |
5699 | | |
5700 | 3.06k | "param2_auth_name, param2_code, param2_name, param2_value, " |
5701 | 3.06k | "param2_uom_auth_name, param2_uom_code, " |
5702 | | |
5703 | 3.06k | "param3_auth_name, param3_code, param3_name, param3_value, " |
5704 | 3.06k | "param3_uom_auth_name, param3_uom_code, " |
5705 | | |
5706 | 3.06k | "param4_auth_name, param4_code, param4_name, param4_value, " |
5707 | 3.06k | "param4_uom_auth_name, param4_uom_code, " |
5708 | | |
5709 | 3.06k | "param5_auth_name, param5_code, param5_name, param5_value, " |
5710 | 3.06k | "param5_uom_auth_name, param5_uom_code, " |
5711 | | |
5712 | 3.06k | "param6_auth_name, param6_code, param6_name, param6_value, " |
5713 | 3.06k | "param6_uom_auth_name, param6_uom_code, " |
5714 | | |
5715 | 3.06k | "param7_auth_name, param7_code, param7_name, param7_value, " |
5716 | 3.06k | "param7_uom_auth_name, param7_uom_code, " |
5717 | | |
5718 | 3.06k | "deprecated FROM conversion WHERE auth_name = ? AND code = ?"; |
5719 | | |
5720 | 3.06k | auto res = d->runWithCodeParam(sql, code); |
5721 | 3.06k | if (res.empty()) { |
5722 | 0 | try { |
5723 | | // Conversions using methods Change of Vertical Unit or |
5724 | | // Height Depth Reversal are stored in other_transformation |
5725 | 0 | auto op = createCoordinateOperation( |
5726 | 0 | code, false /* allowConcatenated */, |
5727 | 0 | false /* usePROJAlternativeGridNames */, |
5728 | 0 | "other_transformation"); |
5729 | 0 | auto conv = |
5730 | 0 | util::nn_dynamic_pointer_cast<operation::Conversion>(op); |
5731 | 0 | if (conv) { |
5732 | 0 | return NN_NO_CHECK(conv); |
5733 | 0 | } |
5734 | 0 | } catch (const std::exception &) { |
5735 | 0 | } |
5736 | 0 | throw NoSuchAuthorityCodeException("conversion not found", |
5737 | 0 | d->authority(), code); |
5738 | 0 | } |
5739 | 3.06k | try { |
5740 | 3.06k | const auto &row = res.front(); |
5741 | 3.06k | size_t idx = 0; |
5742 | 3.06k | const auto &name = row[idx++]; |
5743 | 3.06k | const auto &description = row[idx++]; |
5744 | 3.06k | const auto &method_auth_name = row[idx++]; |
5745 | 3.06k | const auto &method_code = row[idx++]; |
5746 | 3.06k | const auto &method_name = row[idx++]; |
5747 | 3.06k | const size_t base_param_idx = idx; |
5748 | 3.06k | std::vector<operation::OperationParameterNNPtr> parameters; |
5749 | 3.06k | std::vector<operation::ParameterValueNNPtr> values; |
5750 | 18.5k | for (size_t i = 0; i < N_MAX_PARAMS; ++i) { |
5751 | 18.4k | const auto ¶m_auth_name = row[base_param_idx + i * 6 + 0]; |
5752 | 18.4k | if (param_auth_name.empty()) { |
5753 | 3.01k | break; |
5754 | 3.01k | } |
5755 | 15.4k | const auto ¶m_code = row[base_param_idx + i * 6 + 1]; |
5756 | 15.4k | const auto ¶m_name = row[base_param_idx + i * 6 + 2]; |
5757 | 15.4k | const auto ¶m_value = row[base_param_idx + i * 6 + 3]; |
5758 | 15.4k | const auto ¶m_uom_auth_name = row[base_param_idx + i * 6 + 4]; |
5759 | 15.4k | const auto ¶m_uom_code = row[base_param_idx + i * 6 + 5]; |
5760 | 15.4k | parameters.emplace_back(operation::OperationParameter::create( |
5761 | 15.4k | util::PropertyMap() |
5762 | 15.4k | .set(metadata::Identifier::CODESPACE_KEY, param_auth_name) |
5763 | 15.4k | .set(metadata::Identifier::CODE_KEY, param_code) |
5764 | 15.4k | .set(common::IdentifiedObject::NAME_KEY, param_name))); |
5765 | 15.4k | std::string normalized_uom_code(param_uom_code); |
5766 | 15.4k | const double normalized_value = normalizeMeasure( |
5767 | 15.4k | param_uom_code, param_value, normalized_uom_code); |
5768 | 15.4k | auto uom = d->createUnitOfMeasure(param_uom_auth_name, |
5769 | 15.4k | normalized_uom_code); |
5770 | 15.4k | values.emplace_back(operation::ParameterValue::create( |
5771 | 15.4k | common::Measure(normalized_value, uom))); |
5772 | 15.4k | } |
5773 | 3.06k | const bool deprecated = row[base_param_idx + N_MAX_PARAMS * 6] == "1"; |
5774 | | |
5775 | 3.06k | auto propConversion = d->createPropertiesSearchUsages( |
5776 | 3.06k | "conversion", code, name, deprecated); |
5777 | 3.06k | if (!description.empty()) |
5778 | 1.38k | propConversion.set(common::IdentifiedObject::REMARKS_KEY, |
5779 | 1.38k | description); |
5780 | | |
5781 | 3.06k | auto propMethod = util::PropertyMap().set( |
5782 | 3.06k | common::IdentifiedObject::NAME_KEY, method_name); |
5783 | 3.06k | if (!method_auth_name.empty()) { |
5784 | 3.06k | propMethod |
5785 | 3.06k | .set(metadata::Identifier::CODESPACE_KEY, method_auth_name) |
5786 | 3.06k | .set(metadata::Identifier::CODE_KEY, method_code); |
5787 | 3.06k | } |
5788 | | |
5789 | 3.06k | return operation::Conversion::create(propConversion, propMethod, |
5790 | 3.06k | parameters, values); |
5791 | 3.06k | } catch (const std::exception &ex) { |
5792 | 0 | throw buildFactoryException("conversion", d->authority(), code, ex); |
5793 | 0 | } |
5794 | 3.06k | } |
5795 | | |
5796 | | // --------------------------------------------------------------------------- |
5797 | | |
5798 | | /** \brief Returns a crs::ProjectedCRS from the specified code. |
5799 | | * |
5800 | | * @param code Object code allocated by authority. |
5801 | | * @return object. |
5802 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5803 | | * @throw FactoryException in case of other errors. |
5804 | | */ |
5805 | | |
5806 | | crs::ProjectedCRSNNPtr |
5807 | 2.86k | AuthorityFactory::createProjectedCRS(const std::string &code) const { |
5808 | 2.86k | const auto cacheKey(d->authority() + code); |
5809 | 2.86k | auto crs = d->context()->d->getCRSFromCache(cacheKey); |
5810 | 2.86k | if (crs) { |
5811 | 42 | auto projCRS = std::dynamic_pointer_cast<crs::ProjectedCRS>(crs); |
5812 | 42 | if (projCRS) { |
5813 | 42 | return NN_NO_CHECK(projCRS); |
5814 | 42 | } |
5815 | 0 | throw NoSuchAuthorityCodeException("projectedCRS not found", |
5816 | 0 | d->authority(), code); |
5817 | 42 | } |
5818 | 2.82k | return d->createProjectedCRSEnd(code, d->createProjectedCRSBegin(code)); |
5819 | 2.86k | } |
5820 | | |
5821 | | // --------------------------------------------------------------------------- |
5822 | | //! @cond Doxygen_Suppress |
5823 | | |
5824 | | /** Returns the result of the SQL query needed by createProjectedCRSEnd |
5825 | | * |
5826 | | * The split in two functions is for createFromCoordinateReferenceSystemCodes() |
5827 | | * convenience, to avoid throwing exceptions. |
5828 | | */ |
5829 | | SQLResultSet |
5830 | 2.82k | AuthorityFactory::Private::createProjectedCRSBegin(const std::string &code) { |
5831 | 2.82k | return runWithCodeParam( |
5832 | 2.82k | "SELECT name, coordinate_system_auth_name, " |
5833 | 2.82k | "coordinate_system_code, geodetic_crs_auth_name, geodetic_crs_code, " |
5834 | 2.82k | "conversion_auth_name, conversion_code, " |
5835 | 2.82k | "text_definition, " |
5836 | 2.82k | "deprecated FROM projected_crs WHERE auth_name = ? AND code = ?", |
5837 | 2.82k | code); |
5838 | 2.82k | } |
5839 | | |
5840 | | // --------------------------------------------------------------------------- |
5841 | | |
5842 | | /** Build a ProjectedCRS from the result of createProjectedCRSBegin() */ |
5843 | | crs::ProjectedCRSNNPtr |
5844 | | AuthorityFactory::Private::createProjectedCRSEnd(const std::string &code, |
5845 | 2.82k | const SQLResultSet &res) { |
5846 | 2.82k | const auto cacheKey(authority() + code); |
5847 | 2.82k | if (res.empty()) { |
5848 | 7 | throw NoSuchAuthorityCodeException("projectedCRS not found", |
5849 | 7 | authority(), code); |
5850 | 7 | } |
5851 | 2.81k | try { |
5852 | 2.81k | const auto &row = res.front(); |
5853 | 2.81k | const auto &name = row[0]; |
5854 | 2.81k | const auto &cs_auth_name = row[1]; |
5855 | 2.81k | const auto &cs_code = row[2]; |
5856 | 2.81k | const auto &geodetic_crs_auth_name = row[3]; |
5857 | 2.81k | const auto &geodetic_crs_code = row[4]; |
5858 | 2.81k | const auto &conversion_auth_name = row[5]; |
5859 | 2.81k | const auto &conversion_code = row[6]; |
5860 | 2.81k | const auto &text_definition = row[7]; |
5861 | 2.81k | const bool deprecated = row[8] == "1"; |
5862 | | |
5863 | 2.81k | auto props = createPropertiesSearchUsages("projected_crs", code, name, |
5864 | 2.81k | deprecated); |
5865 | | |
5866 | 2.81k | if (!text_definition.empty()) { |
5867 | 284 | DatabaseContext::Private::RecursionDetector detector(context()); |
5868 | 284 | auto obj = createFromUserInput( |
5869 | 284 | pj_add_type_crs_if_needed(text_definition), context()); |
5870 | 284 | auto projCRS = dynamic_cast<const crs::ProjectedCRS *>(obj.get()); |
5871 | 284 | if (projCRS) { |
5872 | 284 | auto conv = projCRS->derivingConversion(); |
5873 | 284 | auto newConv = |
5874 | 284 | (conv->nameStr() == "unnamed") |
5875 | 284 | ? operation::Conversion::create( |
5876 | 271 | util::PropertyMap().set( |
5877 | 271 | common::IdentifiedObject::NAME_KEY, name), |
5878 | 271 | conv->method(), conv->parameterValues()) |
5879 | 284 | : std::move(conv); |
5880 | 284 | auto crsRet = crs::ProjectedCRS::create( |
5881 | 284 | props, projCRS->baseCRS(), newConv, |
5882 | 284 | projCRS->coordinateSystem()); |
5883 | 284 | context()->d->cache(cacheKey, crsRet); |
5884 | 284 | return crsRet; |
5885 | 284 | } |
5886 | | |
5887 | 0 | auto boundCRS = dynamic_cast<const crs::BoundCRS *>(obj.get()); |
5888 | 0 | if (boundCRS) { |
5889 | 0 | projCRS = dynamic_cast<const crs::ProjectedCRS *>( |
5890 | 0 | boundCRS->baseCRS().get()); |
5891 | 0 | if (projCRS) { |
5892 | 0 | auto newBoundCRS = crs::BoundCRS::create( |
5893 | 0 | crs::ProjectedCRS::create(props, projCRS->baseCRS(), |
5894 | 0 | projCRS->derivingConversion(), |
5895 | 0 | projCRS->coordinateSystem()), |
5896 | 0 | boundCRS->hubCRS(), boundCRS->transformation()); |
5897 | 0 | return NN_NO_CHECK( |
5898 | 0 | util::nn_dynamic_pointer_cast<crs::ProjectedCRS>( |
5899 | 0 | newBoundCRS->baseCRSWithCanonicalBoundCRS())); |
5900 | 0 | } |
5901 | 0 | } |
5902 | | |
5903 | 0 | throw FactoryException( |
5904 | 0 | "text_definition does not define a ProjectedCRS"); |
5905 | 0 | } |
5906 | | |
5907 | 2.53k | auto cs = createFactory(cs_auth_name)->createCoordinateSystem(cs_code); |
5908 | | |
5909 | 2.53k | auto baseCRS = createFactory(geodetic_crs_auth_name) |
5910 | 2.53k | ->createGeodeticCRS(geodetic_crs_code); |
5911 | | |
5912 | 2.53k | auto conv = createFactory(conversion_auth_name) |
5913 | 2.53k | ->createConversion(conversion_code); |
5914 | 2.53k | if (conv->nameStr() == "unnamed") { |
5915 | 251 | conv = conv->shallowClone(); |
5916 | 251 | conv->setProperties(util::PropertyMap().set( |
5917 | 251 | common::IdentifiedObject::NAME_KEY, name)); |
5918 | 251 | } |
5919 | | |
5920 | 2.53k | auto cartesianCS = util::nn_dynamic_pointer_cast<cs::CartesianCS>(cs); |
5921 | 2.53k | if (cartesianCS) { |
5922 | 2.53k | auto crsRet = crs::ProjectedCRS::create(props, baseCRS, conv, |
5923 | 2.53k | NN_NO_CHECK(cartesianCS)); |
5924 | 2.53k | context()->d->cache(cacheKey, crsRet); |
5925 | 2.53k | return crsRet; |
5926 | 2.53k | } |
5927 | 0 | throw FactoryException("unsupported CS type for projectedCRS: " + |
5928 | 0 | cs->getWKT2Type(true)); |
5929 | 2.53k | } catch (const std::exception &ex) { |
5930 | 0 | throw buildFactoryException("projectedCRS", authority(), code, ex); |
5931 | 0 | } |
5932 | 2.81k | } |
5933 | | //! @endcond |
5934 | | |
5935 | | // --------------------------------------------------------------------------- |
5936 | | |
5937 | | /** \brief Returns a crs::CompoundCRS from the specified code. |
5938 | | * |
5939 | | * @param code Object code allocated by authority. |
5940 | | * @return object. |
5941 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5942 | | * @throw FactoryException in case of other errors. |
5943 | | */ |
5944 | | |
5945 | | crs::CompoundCRSNNPtr |
5946 | 291 | AuthorityFactory::createCompoundCRS(const std::string &code) const { |
5947 | 291 | auto res = |
5948 | 291 | d->runWithCodeParam("SELECT name, horiz_crs_auth_name, horiz_crs_code, " |
5949 | 291 | "vertical_crs_auth_name, vertical_crs_code, " |
5950 | 291 | "deprecated FROM " |
5951 | 291 | "compound_crs WHERE auth_name = ? AND code = ?", |
5952 | 291 | code); |
5953 | 291 | if (res.empty()) { |
5954 | 1 | throw NoSuchAuthorityCodeException("compoundCRS not found", |
5955 | 1 | d->authority(), code); |
5956 | 1 | } |
5957 | 290 | try { |
5958 | 290 | const auto &row = res.front(); |
5959 | 290 | const auto &name = row[0]; |
5960 | 290 | const auto &horiz_crs_auth_name = row[1]; |
5961 | 290 | const auto &horiz_crs_code = row[2]; |
5962 | 290 | const auto &vertical_crs_auth_name = row[3]; |
5963 | 290 | const auto &vertical_crs_code = row[4]; |
5964 | 290 | const bool deprecated = row[5] == "1"; |
5965 | | |
5966 | 290 | auto horizCRS = |
5967 | 290 | d->createFactory(horiz_crs_auth_name) |
5968 | 290 | ->createCoordinateReferenceSystem(horiz_crs_code, false); |
5969 | 290 | auto vertCRS = d->createFactory(vertical_crs_auth_name) |
5970 | 290 | ->createVerticalCRS(vertical_crs_code); |
5971 | | |
5972 | 290 | auto props = d->createPropertiesSearchUsages("compound_crs", code, name, |
5973 | 290 | deprecated); |
5974 | 290 | return crs::CompoundCRS::create( |
5975 | 290 | props, std::vector<crs::CRSNNPtr>{std::move(horizCRS), |
5976 | 290 | std::move(vertCRS)}); |
5977 | 290 | } catch (const std::exception &ex) { |
5978 | 0 | throw buildFactoryException("compoundCRS", d->authority(), code, ex); |
5979 | 0 | } |
5980 | 290 | } |
5981 | | |
5982 | | // --------------------------------------------------------------------------- |
5983 | | |
5984 | | /** \brief Returns a crs::CRS from the specified code. |
5985 | | * |
5986 | | * @param code Object code allocated by authority. |
5987 | | * @return object. |
5988 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
5989 | | * @throw FactoryException in case of other errors. |
5990 | | */ |
5991 | | |
5992 | | crs::CRSNNPtr AuthorityFactory::createCoordinateReferenceSystem( |
5993 | 543k | const std::string &code) const { |
5994 | 543k | return createCoordinateReferenceSystem(code, true); |
5995 | 543k | } |
5996 | | |
5997 | | //! @cond Doxygen_Suppress |
5998 | | |
5999 | | crs::CRSNNPtr |
6000 | | AuthorityFactory::createCoordinateReferenceSystem(const std::string &code, |
6001 | 544k | bool allowCompound) const { |
6002 | 544k | const auto cacheKey(d->authority() + code); |
6003 | 544k | auto crs = d->context()->d->getCRSFromCache(cacheKey); |
6004 | 544k | if (crs) { |
6005 | 538k | return NN_NO_CHECK(crs); |
6006 | 538k | } |
6007 | | |
6008 | 6.02k | if (d->authority() == metadata::Identifier::OGC) { |
6009 | 30 | if (code == "AnsiDate") { |
6010 | | // Derived from http://www.opengis.net/def/crs/OGC/0/AnsiDate |
6011 | 0 | return crs::TemporalCRS::create( |
6012 | 0 | util::PropertyMap() |
6013 | | // above URL indicates Julian Date" as name... likely wrong |
6014 | 0 | .set(common::IdentifiedObject::NAME_KEY, "Ansi Date") |
6015 | 0 | .set(metadata::Identifier::CODESPACE_KEY, d->authority()) |
6016 | 0 | .set(metadata::Identifier::CODE_KEY, code), |
6017 | 0 | datum::TemporalDatum::create( |
6018 | 0 | util::PropertyMap().set( |
6019 | 0 | common::IdentifiedObject::NAME_KEY, |
6020 | 0 | "Epoch time for the ANSI date (1-Jan-1601, 00h00 UTC) " |
6021 | 0 | "as day 1."), |
6022 | 0 | common::DateTime::create("1600-12-31T00:00:00Z"), |
6023 | 0 | datum::TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN), |
6024 | 0 | cs::TemporalCountCS::create( |
6025 | 0 | util::PropertyMap(), |
6026 | 0 | cs::CoordinateSystemAxis::create( |
6027 | 0 | util::PropertyMap().set( |
6028 | 0 | common::IdentifiedObject::NAME_KEY, "Time"), |
6029 | 0 | "T", cs::AxisDirection::FUTURE, |
6030 | 0 | common::UnitOfMeasure("day", 0, |
6031 | 0 | UnitOfMeasure::Type::TIME)))); |
6032 | 0 | } |
6033 | 30 | if (code == "JulianDate") { |
6034 | | // Derived from http://www.opengis.net/def/crs/OGC/0/JulianDate |
6035 | 0 | return crs::TemporalCRS::create( |
6036 | 0 | util::PropertyMap() |
6037 | 0 | .set(common::IdentifiedObject::NAME_KEY, "Julian Date") |
6038 | 0 | .set(metadata::Identifier::CODESPACE_KEY, d->authority()) |
6039 | 0 | .set(metadata::Identifier::CODE_KEY, code), |
6040 | 0 | datum::TemporalDatum::create( |
6041 | 0 | util::PropertyMap().set( |
6042 | 0 | common::IdentifiedObject::NAME_KEY, |
6043 | 0 | "The beginning of the Julian period."), |
6044 | 0 | common::DateTime::create("-4714-11-24T12:00:00Z"), |
6045 | 0 | datum::TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN), |
6046 | 0 | cs::TemporalCountCS::create( |
6047 | 0 | util::PropertyMap(), |
6048 | 0 | cs::CoordinateSystemAxis::create( |
6049 | 0 | util::PropertyMap().set( |
6050 | 0 | common::IdentifiedObject::NAME_KEY, "Time"), |
6051 | 0 | "T", cs::AxisDirection::FUTURE, |
6052 | 0 | common::UnitOfMeasure("day", 0, |
6053 | 0 | UnitOfMeasure::Type::TIME)))); |
6054 | 0 | } |
6055 | 30 | if (code == "UnixTime") { |
6056 | | // Derived from http://www.opengis.net/def/crs/OGC/0/UnixTime |
6057 | 0 | return crs::TemporalCRS::create( |
6058 | 0 | util::PropertyMap() |
6059 | 0 | .set(common::IdentifiedObject::NAME_KEY, "Unix Time") |
6060 | 0 | .set(metadata::Identifier::CODESPACE_KEY, d->authority()) |
6061 | 0 | .set(metadata::Identifier::CODE_KEY, code), |
6062 | 0 | datum::TemporalDatum::create( |
6063 | 0 | util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, |
6064 | 0 | "Unix epoch"), |
6065 | 0 | common::DateTime::create("1970-01-01T00:00:00Z"), |
6066 | 0 | datum::TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN), |
6067 | 0 | cs::TemporalCountCS::create( |
6068 | 0 | util::PropertyMap(), |
6069 | 0 | cs::CoordinateSystemAxis::create( |
6070 | 0 | util::PropertyMap().set( |
6071 | 0 | common::IdentifiedObject::NAME_KEY, "Time"), |
6072 | 0 | "T", cs::AxisDirection::FUTURE, |
6073 | 0 | common::UnitOfMeasure::SECOND))); |
6074 | 0 | } |
6075 | 30 | if (code == "84") { |
6076 | 0 | return createCoordinateReferenceSystem("CRS84", false); |
6077 | 0 | } |
6078 | 30 | } |
6079 | | |
6080 | 6.02k | auto res = d->runWithCodeParam( |
6081 | 6.02k | "SELECT type FROM crs_view WHERE auth_name = ? AND code = ?", code); |
6082 | 6.02k | if (res.empty()) { |
6083 | 270 | throw NoSuchAuthorityCodeException("crs not found", d->authority(), |
6084 | 270 | code); |
6085 | 270 | } |
6086 | 5.75k | const auto &type = res.front()[0]; |
6087 | 5.75k | if (type == GEOG_2D || type == GEOG_3D || type == GEOCENTRIC || |
6088 | 5.75k | type == OTHER) { |
6089 | 5.44k | return createGeodeticCRS(code); |
6090 | 5.44k | } |
6091 | 319 | if (type == VERTICAL) { |
6092 | 152 | return createVerticalCRS(code); |
6093 | 152 | } |
6094 | 167 | if (type == PROJECTED) { |
6095 | 119 | return createProjectedCRS(code); |
6096 | 119 | } |
6097 | 48 | if (type == ENGINEERING) { |
6098 | 2 | return createEngineeringCRS(code); |
6099 | 2 | } |
6100 | 46 | if (allowCompound && type == COMPOUND) { |
6101 | 46 | return createCompoundCRS(code); |
6102 | 46 | } |
6103 | 0 | throw FactoryException("unhandled CRS type: " + type); |
6104 | 46 | } |
6105 | | |
6106 | | //! @endcond |
6107 | | |
6108 | | // --------------------------------------------------------------------------- |
6109 | | |
6110 | | /** \brief Returns a coordinates::CoordinateMetadata from the specified code. |
6111 | | * |
6112 | | * @param code Object code allocated by authority. |
6113 | | * @return object. |
6114 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
6115 | | * @throw FactoryException in case of other errors. |
6116 | | * @since 9.4 |
6117 | | */ |
6118 | | |
6119 | | coordinates::CoordinateMetadataNNPtr |
6120 | 0 | AuthorityFactory::createCoordinateMetadata(const std::string &code) const { |
6121 | 0 | auto res = d->runWithCodeParam( |
6122 | 0 | "SELECT crs_auth_name, crs_code, crs_text_definition, coordinate_epoch " |
6123 | 0 | "FROM coordinate_metadata WHERE auth_name = ? AND code = ?", |
6124 | 0 | code); |
6125 | 0 | if (res.empty()) { |
6126 | 0 | throw NoSuchAuthorityCodeException("coordinate_metadata not found", |
6127 | 0 | d->authority(), code); |
6128 | 0 | } |
6129 | 0 | try { |
6130 | 0 | const auto &row = res.front(); |
6131 | 0 | const auto &crs_auth_name = row[0]; |
6132 | 0 | const auto &crs_code = row[1]; |
6133 | 0 | const auto &crs_text_definition = row[2]; |
6134 | 0 | const auto &coordinate_epoch = row[3]; |
6135 | |
|
6136 | 0 | auto l_context = d->context(); |
6137 | 0 | DatabaseContext::Private::RecursionDetector detector(l_context); |
6138 | 0 | auto crs = |
6139 | 0 | !crs_auth_name.empty() |
6140 | 0 | ? d->createFactory(crs_auth_name) |
6141 | 0 | ->createCoordinateReferenceSystem(crs_code) |
6142 | 0 | .as_nullable() |
6143 | 0 | : util::nn_dynamic_pointer_cast<crs::CRS>( |
6144 | 0 | createFromUserInput(crs_text_definition, l_context)); |
6145 | 0 | if (!crs) { |
6146 | 0 | throw FactoryException( |
6147 | 0 | std::string("cannot build CoordinateMetadata ") + |
6148 | 0 | d->authority() + ":" + code + ": cannot build CRS"); |
6149 | 0 | } |
6150 | 0 | if (coordinate_epoch.empty()) { |
6151 | 0 | return coordinates::CoordinateMetadata::create(NN_NO_CHECK(crs)); |
6152 | 0 | } else { |
6153 | 0 | return coordinates::CoordinateMetadata::create( |
6154 | 0 | NN_NO_CHECK(crs), c_locale_stod(coordinate_epoch), |
6155 | 0 | l_context.as_nullable()); |
6156 | 0 | } |
6157 | 0 | } catch (const std::exception &ex) { |
6158 | 0 | throw buildFactoryException("CoordinateMetadata", d->authority(), code, |
6159 | 0 | ex); |
6160 | 0 | } |
6161 | 0 | } |
6162 | | |
6163 | | // --------------------------------------------------------------------------- |
6164 | | |
6165 | | //! @cond Doxygen_Suppress |
6166 | | |
6167 | | static util::PropertyMap createMapNameEPSGCode(const std::string &name, |
6168 | 145k | int code) { |
6169 | 145k | return util::PropertyMap() |
6170 | 145k | .set(common::IdentifiedObject::NAME_KEY, name) |
6171 | 145k | .set(metadata::Identifier::CODESPACE_KEY, metadata::Identifier::EPSG) |
6172 | 145k | .set(metadata::Identifier::CODE_KEY, code); |
6173 | 145k | } |
6174 | | |
6175 | | // --------------------------------------------------------------------------- |
6176 | | |
6177 | 145k | static operation::OperationParameterNNPtr createOpParamNameEPSGCode(int code) { |
6178 | 145k | const char *name = operation::OperationParameter::getNameForEPSGCode(code); |
6179 | 145k | assert(name); |
6180 | 145k | return operation::OperationParameter::create( |
6181 | 145k | createMapNameEPSGCode(name, code)); |
6182 | 145k | } |
6183 | | |
6184 | | static operation::ParameterValueNNPtr createLength(const std::string &value, |
6185 | 98.0k | const UnitOfMeasure &uom) { |
6186 | 98.0k | return operation::ParameterValue::create( |
6187 | 98.0k | common::Length(c_locale_stod(value), uom)); |
6188 | 98.0k | } |
6189 | | |
6190 | | static operation::ParameterValueNNPtr createAngle(const std::string &value, |
6191 | 32.5k | const UnitOfMeasure &uom) { |
6192 | 32.5k | return operation::ParameterValue::create( |
6193 | 32.5k | common::Angle(c_locale_stod(value), uom)); |
6194 | 32.5k | } |
6195 | | |
6196 | | //! @endcond |
6197 | | |
6198 | | // --------------------------------------------------------------------------- |
6199 | | |
6200 | | /** \brief Returns a operation::CoordinateOperation from the specified code. |
6201 | | * |
6202 | | * @param code Object code allocated by authority. |
6203 | | * @param usePROJAlternativeGridNames Whether PROJ alternative grid names |
6204 | | * should be substituted to the official grid names. |
6205 | | * @return object. |
6206 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
6207 | | * @throw FactoryException in case of other errors. |
6208 | | */ |
6209 | | |
6210 | | operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( |
6211 | 1.13k | const std::string &code, bool usePROJAlternativeGridNames) const { |
6212 | 1.13k | return createCoordinateOperation(code, true, usePROJAlternativeGridNames, |
6213 | 1.13k | std::string()); |
6214 | 1.13k | } |
6215 | | |
6216 | | operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( |
6217 | | const std::string &code, bool allowConcatenated, |
6218 | 162k | bool usePROJAlternativeGridNames, const std::string &typeIn) const { |
6219 | 162k | std::string type(typeIn); |
6220 | 162k | if (type.empty()) { |
6221 | 75.8k | auto res = d->runWithCodeParam( |
6222 | 75.8k | "SELECT type FROM coordinate_operation_with_conversion_view " |
6223 | 75.8k | "WHERE auth_name = ? AND code = ?", |
6224 | 75.8k | code); |
6225 | 75.8k | if (res.empty()) { |
6226 | 0 | throw NoSuchAuthorityCodeException("coordinate operation not found", |
6227 | 0 | d->authority(), code); |
6228 | 0 | } |
6229 | 75.8k | type = res.front()[0]; |
6230 | 75.8k | } |
6231 | | |
6232 | 162k | if (type == "conversion") { |
6233 | 26 | return createConversion(code); |
6234 | 26 | } |
6235 | | |
6236 | 162k | if (type == "helmert_transformation") { |
6237 | | |
6238 | 29.3k | auto res = d->runWithCodeParam( |
6239 | 29.3k | "SELECT name, description, " |
6240 | 29.3k | "method_auth_name, method_code, method_name, " |
6241 | 29.3k | "source_crs_auth_name, source_crs_code, target_crs_auth_name, " |
6242 | 29.3k | "target_crs_code, " |
6243 | 29.3k | "accuracy, tx, ty, tz, translation_uom_auth_name, " |
6244 | 29.3k | "translation_uom_code, rx, ry, rz, rotation_uom_auth_name, " |
6245 | 29.3k | "rotation_uom_code, scale_difference, " |
6246 | 29.3k | "scale_difference_uom_auth_name, scale_difference_uom_code, " |
6247 | 29.3k | "rate_tx, rate_ty, rate_tz, rate_translation_uom_auth_name, " |
6248 | 29.3k | "rate_translation_uom_code, rate_rx, rate_ry, rate_rz, " |
6249 | 29.3k | "rate_rotation_uom_auth_name, rate_rotation_uom_code, " |
6250 | 29.3k | "rate_scale_difference, rate_scale_difference_uom_auth_name, " |
6251 | 29.3k | "rate_scale_difference_uom_code, epoch, epoch_uom_auth_name, " |
6252 | 29.3k | "epoch_uom_code, px, py, pz, pivot_uom_auth_name, pivot_uom_code, " |
6253 | 29.3k | "operation_version, deprecated FROM " |
6254 | 29.3k | "helmert_transformation WHERE auth_name = ? AND code = ?", |
6255 | 29.3k | code); |
6256 | 29.3k | if (res.empty()) { |
6257 | | // shouldn't happen if foreign keys are OK |
6258 | 0 | throw NoSuchAuthorityCodeException( |
6259 | 0 | "helmert_transformation not found", d->authority(), code); |
6260 | 0 | } |
6261 | 29.3k | try { |
6262 | 29.3k | const auto &row = res.front(); |
6263 | 29.3k | size_t idx = 0; |
6264 | 29.3k | const auto &name = row[idx++]; |
6265 | 29.3k | const auto &description = row[idx++]; |
6266 | 29.3k | const auto &method_auth_name = row[idx++]; |
6267 | 29.3k | const auto &method_code = row[idx++]; |
6268 | 29.3k | const auto &method_name = row[idx++]; |
6269 | 29.3k | const auto &source_crs_auth_name = row[idx++]; |
6270 | 29.3k | const auto &source_crs_code = row[idx++]; |
6271 | 29.3k | const auto &target_crs_auth_name = row[idx++]; |
6272 | 29.3k | const auto &target_crs_code = row[idx++]; |
6273 | 29.3k | const auto &accuracy = row[idx++]; |
6274 | | |
6275 | 29.3k | const auto &tx = row[idx++]; |
6276 | 29.3k | const auto &ty = row[idx++]; |
6277 | 29.3k | const auto &tz = row[idx++]; |
6278 | 29.3k | const auto &translation_uom_auth_name = row[idx++]; |
6279 | 29.3k | const auto &translation_uom_code = row[idx++]; |
6280 | 29.3k | const auto &rx = row[idx++]; |
6281 | 29.3k | const auto &ry = row[idx++]; |
6282 | 29.3k | const auto &rz = row[idx++]; |
6283 | 29.3k | const auto &rotation_uom_auth_name = row[idx++]; |
6284 | 29.3k | const auto &rotation_uom_code = row[idx++]; |
6285 | 29.3k | const auto &scale_difference = row[idx++]; |
6286 | 29.3k | const auto &scale_difference_uom_auth_name = row[idx++]; |
6287 | 29.3k | const auto &scale_difference_uom_code = row[idx++]; |
6288 | | |
6289 | 29.3k | const auto &rate_tx = row[idx++]; |
6290 | 29.3k | const auto &rate_ty = row[idx++]; |
6291 | 29.3k | const auto &rate_tz = row[idx++]; |
6292 | 29.3k | const auto &rate_translation_uom_auth_name = row[idx++]; |
6293 | 29.3k | const auto &rate_translation_uom_code = row[idx++]; |
6294 | 29.3k | const auto &rate_rx = row[idx++]; |
6295 | 29.3k | const auto &rate_ry = row[idx++]; |
6296 | 29.3k | const auto &rate_rz = row[idx++]; |
6297 | 29.3k | const auto &rate_rotation_uom_auth_name = row[idx++]; |
6298 | 29.3k | const auto &rate_rotation_uom_code = row[idx++]; |
6299 | 29.3k | const auto &rate_scale_difference = row[idx++]; |
6300 | 29.3k | const auto &rate_scale_difference_uom_auth_name = row[idx++]; |
6301 | 29.3k | const auto &rate_scale_difference_uom_code = row[idx++]; |
6302 | | |
6303 | 29.3k | const auto &epoch = row[idx++]; |
6304 | 29.3k | const auto &epoch_uom_auth_name = row[idx++]; |
6305 | 29.3k | const auto &epoch_uom_code = row[idx++]; |
6306 | | |
6307 | 29.3k | const auto &px = row[idx++]; |
6308 | 29.3k | const auto &py = row[idx++]; |
6309 | 29.3k | const auto &pz = row[idx++]; |
6310 | 29.3k | const auto &pivot_uom_auth_name = row[idx++]; |
6311 | 29.3k | const auto &pivot_uom_code = row[idx++]; |
6312 | | |
6313 | 29.3k | const auto &operation_version = row[idx++]; |
6314 | 29.3k | const auto &deprecated_str = row[idx++]; |
6315 | 29.3k | const bool deprecated = deprecated_str == "1"; |
6316 | 29.3k | assert(idx == row.size()); |
6317 | | |
6318 | 29.3k | auto uom_translation = d->createUnitOfMeasure( |
6319 | 29.3k | translation_uom_auth_name, translation_uom_code); |
6320 | | |
6321 | 29.3k | auto uom_epoch = epoch_uom_auth_name.empty() |
6322 | 29.3k | ? common::UnitOfMeasure::NONE |
6323 | 29.3k | : d->createUnitOfMeasure(epoch_uom_auth_name, |
6324 | 3.57k | epoch_uom_code); |
6325 | | |
6326 | 29.3k | auto sourceCRS = |
6327 | 29.3k | d->createFactory(source_crs_auth_name) |
6328 | 29.3k | ->createCoordinateReferenceSystem(source_crs_code); |
6329 | 29.3k | auto targetCRS = |
6330 | 29.3k | d->createFactory(target_crs_auth_name) |
6331 | 29.3k | ->createCoordinateReferenceSystem(target_crs_code); |
6332 | | |
6333 | 29.3k | std::vector<operation::OperationParameterNNPtr> parameters; |
6334 | 29.3k | std::vector<operation::ParameterValueNNPtr> values; |
6335 | | |
6336 | 29.3k | parameters.emplace_back(createOpParamNameEPSGCode( |
6337 | 29.3k | EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION)); |
6338 | 29.3k | values.emplace_back(createLength(tx, uom_translation)); |
6339 | | |
6340 | 29.3k | parameters.emplace_back(createOpParamNameEPSGCode( |
6341 | 29.3k | EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION)); |
6342 | 29.3k | values.emplace_back(createLength(ty, uom_translation)); |
6343 | | |
6344 | 29.3k | parameters.emplace_back(createOpParamNameEPSGCode( |
6345 | 29.3k | EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION)); |
6346 | 29.3k | values.emplace_back(createLength(tz, uom_translation)); |
6347 | | |
6348 | 29.3k | if (!rx.empty()) { |
6349 | | // Helmert 7-, 8-, 10- or 15- parameter cases |
6350 | 7.48k | auto uom_rotation = d->createUnitOfMeasure( |
6351 | 7.48k | rotation_uom_auth_name, rotation_uom_code); |
6352 | | |
6353 | 7.48k | parameters.emplace_back(createOpParamNameEPSGCode( |
6354 | 7.48k | EPSG_CODE_PARAMETER_X_AXIS_ROTATION)); |
6355 | 7.48k | values.emplace_back(createAngle(rx, uom_rotation)); |
6356 | | |
6357 | 7.48k | parameters.emplace_back(createOpParamNameEPSGCode( |
6358 | 7.48k | EPSG_CODE_PARAMETER_Y_AXIS_ROTATION)); |
6359 | 7.48k | values.emplace_back(createAngle(ry, uom_rotation)); |
6360 | | |
6361 | 7.48k | parameters.emplace_back(createOpParamNameEPSGCode( |
6362 | 7.48k | EPSG_CODE_PARAMETER_Z_AXIS_ROTATION)); |
6363 | 7.48k | values.emplace_back(createAngle(rz, uom_rotation)); |
6364 | | |
6365 | 7.48k | auto uom_scale_difference = |
6366 | 7.48k | scale_difference_uom_auth_name.empty() |
6367 | 7.48k | ? common::UnitOfMeasure::NONE |
6368 | 7.48k | : d->createUnitOfMeasure(scale_difference_uom_auth_name, |
6369 | 7.48k | scale_difference_uom_code); |
6370 | | |
6371 | 7.48k | parameters.emplace_back(createOpParamNameEPSGCode( |
6372 | 7.48k | EPSG_CODE_PARAMETER_SCALE_DIFFERENCE)); |
6373 | 7.48k | values.emplace_back(operation::ParameterValue::create( |
6374 | 7.48k | common::Scale(c_locale_stod(scale_difference), |
6375 | 7.48k | uom_scale_difference))); |
6376 | 7.48k | } |
6377 | | |
6378 | 29.3k | if (!rate_tx.empty()) { |
6379 | | // Helmert 15-parameter |
6380 | | |
6381 | 3.36k | auto uom_rate_translation = d->createUnitOfMeasure( |
6382 | 3.36k | rate_translation_uom_auth_name, rate_translation_uom_code); |
6383 | | |
6384 | 3.36k | parameters.emplace_back(createOpParamNameEPSGCode( |
6385 | 3.36k | EPSG_CODE_PARAMETER_RATE_X_AXIS_TRANSLATION)); |
6386 | 3.36k | values.emplace_back( |
6387 | 3.36k | createLength(rate_tx, uom_rate_translation)); |
6388 | | |
6389 | 3.36k | parameters.emplace_back(createOpParamNameEPSGCode( |
6390 | 3.36k | EPSG_CODE_PARAMETER_RATE_Y_AXIS_TRANSLATION)); |
6391 | 3.36k | values.emplace_back( |
6392 | 3.36k | createLength(rate_ty, uom_rate_translation)); |
6393 | | |
6394 | 3.36k | parameters.emplace_back(createOpParamNameEPSGCode( |
6395 | 3.36k | EPSG_CODE_PARAMETER_RATE_Z_AXIS_TRANSLATION)); |
6396 | 3.36k | values.emplace_back( |
6397 | 3.36k | createLength(rate_tz, uom_rate_translation)); |
6398 | | |
6399 | 3.36k | auto uom_rate_rotation = d->createUnitOfMeasure( |
6400 | 3.36k | rate_rotation_uom_auth_name, rate_rotation_uom_code); |
6401 | | |
6402 | 3.36k | parameters.emplace_back(createOpParamNameEPSGCode( |
6403 | 3.36k | EPSG_CODE_PARAMETER_RATE_X_AXIS_ROTATION)); |
6404 | 3.36k | values.emplace_back(createAngle(rate_rx, uom_rate_rotation)); |
6405 | | |
6406 | 3.36k | parameters.emplace_back(createOpParamNameEPSGCode( |
6407 | 3.36k | EPSG_CODE_PARAMETER_RATE_Y_AXIS_ROTATION)); |
6408 | 3.36k | values.emplace_back(createAngle(rate_ry, uom_rate_rotation)); |
6409 | | |
6410 | 3.36k | parameters.emplace_back(createOpParamNameEPSGCode( |
6411 | 3.36k | EPSG_CODE_PARAMETER_RATE_Z_AXIS_ROTATION)); |
6412 | 3.36k | values.emplace_back(createAngle(rate_rz, uom_rate_rotation)); |
6413 | | |
6414 | 3.36k | auto uom_rate_scale_difference = |
6415 | 3.36k | d->createUnitOfMeasure(rate_scale_difference_uom_auth_name, |
6416 | 3.36k | rate_scale_difference_uom_code); |
6417 | 3.36k | parameters.emplace_back(createOpParamNameEPSGCode( |
6418 | 3.36k | EPSG_CODE_PARAMETER_RATE_SCALE_DIFFERENCE)); |
6419 | 3.36k | values.emplace_back(operation::ParameterValue::create( |
6420 | 3.36k | common::Scale(c_locale_stod(rate_scale_difference), |
6421 | 3.36k | uom_rate_scale_difference))); |
6422 | | |
6423 | 3.36k | parameters.emplace_back(createOpParamNameEPSGCode( |
6424 | 3.36k | EPSG_CODE_PARAMETER_REFERENCE_EPOCH)); |
6425 | 3.36k | values.emplace_back(operation::ParameterValue::create( |
6426 | 3.36k | common::Measure(c_locale_stod(epoch), uom_epoch))); |
6427 | 25.9k | } else if (uom_epoch != common::UnitOfMeasure::NONE) { |
6428 | | // Helmert 8-parameter |
6429 | 213 | parameters.emplace_back(createOpParamNameEPSGCode( |
6430 | 213 | EPSG_CODE_PARAMETER_TRANSFORMATION_REFERENCE_EPOCH)); |
6431 | 213 | values.emplace_back(operation::ParameterValue::create( |
6432 | 213 | common::Measure(c_locale_stod(epoch), uom_epoch))); |
6433 | 25.7k | } else if (!px.empty()) { |
6434 | | // Molodensky-Badekas case |
6435 | 16 | auto uom_pivot = |
6436 | 16 | d->createUnitOfMeasure(pivot_uom_auth_name, pivot_uom_code); |
6437 | | |
6438 | 16 | parameters.emplace_back(createOpParamNameEPSGCode( |
6439 | 16 | EPSG_CODE_PARAMETER_ORDINATE_1_EVAL_POINT)); |
6440 | 16 | values.emplace_back(createLength(px, uom_pivot)); |
6441 | | |
6442 | 16 | parameters.emplace_back(createOpParamNameEPSGCode( |
6443 | 16 | EPSG_CODE_PARAMETER_ORDINATE_2_EVAL_POINT)); |
6444 | 16 | values.emplace_back(createLength(py, uom_pivot)); |
6445 | | |
6446 | 16 | parameters.emplace_back(createOpParamNameEPSGCode( |
6447 | 16 | EPSG_CODE_PARAMETER_ORDINATE_3_EVAL_POINT)); |
6448 | 16 | values.emplace_back(createLength(pz, uom_pivot)); |
6449 | 16 | } |
6450 | | |
6451 | 29.3k | auto props = d->createPropertiesSearchUsages( |
6452 | 29.3k | type, code, name, deprecated, description); |
6453 | 29.3k | if (!operation_version.empty()) { |
6454 | 28.5k | props.set(operation::CoordinateOperation::OPERATION_VERSION_KEY, |
6455 | 28.5k | operation_version); |
6456 | 28.5k | } |
6457 | | |
6458 | 29.3k | auto propsMethod = |
6459 | 29.3k | util::PropertyMap() |
6460 | 29.3k | .set(metadata::Identifier::CODESPACE_KEY, method_auth_name) |
6461 | 29.3k | .set(metadata::Identifier::CODE_KEY, method_code) |
6462 | 29.3k | .set(common::IdentifiedObject::NAME_KEY, method_name); |
6463 | | |
6464 | 29.3k | std::vector<metadata::PositionalAccuracyNNPtr> accuracies; |
6465 | 29.3k | if (!accuracy.empty() && accuracy != "999.0") { |
6466 | 29.0k | accuracies.emplace_back( |
6467 | 29.0k | metadata::PositionalAccuracy::create(accuracy)); |
6468 | 29.0k | } |
6469 | 29.3k | return operation::Transformation::create( |
6470 | 29.3k | props, sourceCRS, targetCRS, nullptr, propsMethod, parameters, |
6471 | 29.3k | values, accuracies); |
6472 | | |
6473 | 29.3k | } catch (const std::exception &ex) { |
6474 | 0 | throw buildFactoryException("transformation", d->authority(), code, |
6475 | 0 | ex); |
6476 | 0 | } |
6477 | 29.3k | } |
6478 | | |
6479 | 133k | if (type == "grid_transformation") { |
6480 | 96.7k | auto res = d->runWithCodeParam( |
6481 | 96.7k | "SELECT name, description, " |
6482 | 96.7k | "method_auth_name, method_code, method_name, " |
6483 | 96.7k | "source_crs_auth_name, source_crs_code, target_crs_auth_name, " |
6484 | 96.7k | "target_crs_code, " |
6485 | 96.7k | "accuracy, grid_param_auth_name, grid_param_code, grid_param_name, " |
6486 | 96.7k | "grid_name, " |
6487 | 96.7k | "grid2_param_auth_name, grid2_param_code, grid2_param_name, " |
6488 | 96.7k | "grid2_name, " |
6489 | 96.7k | "interpolation_crs_auth_name, interpolation_crs_code, " |
6490 | 96.7k | "operation_version, deprecated FROM " |
6491 | 96.7k | "grid_transformation WHERE auth_name = ? AND code = ?", |
6492 | 96.7k | code); |
6493 | 96.7k | if (res.empty()) { |
6494 | | // shouldn't happen if foreign keys are OK |
6495 | 0 | throw NoSuchAuthorityCodeException("grid_transformation not found", |
6496 | 0 | d->authority(), code); |
6497 | 0 | } |
6498 | 96.7k | try { |
6499 | 96.7k | const auto &row = res.front(); |
6500 | 96.7k | size_t idx = 0; |
6501 | 96.7k | const auto &name = row[idx++]; |
6502 | 96.7k | const auto &description = row[idx++]; |
6503 | 96.7k | const auto &method_auth_name = row[idx++]; |
6504 | 96.7k | const auto &method_code = row[idx++]; |
6505 | 96.7k | const auto &method_name = row[idx++]; |
6506 | 96.7k | const auto &source_crs_auth_name = row[idx++]; |
6507 | 96.7k | const auto &source_crs_code = row[idx++]; |
6508 | 96.7k | const auto &target_crs_auth_name = row[idx++]; |
6509 | 96.7k | const auto &target_crs_code = row[idx++]; |
6510 | 96.7k | const auto &accuracy = row[idx++]; |
6511 | 96.7k | const auto &grid_param_auth_name = row[idx++]; |
6512 | 96.7k | const auto &grid_param_code = row[idx++]; |
6513 | 96.7k | const auto &grid_param_name = row[idx++]; |
6514 | 96.7k | const auto &grid_name = row[idx++]; |
6515 | 96.7k | const auto &grid2_param_auth_name = row[idx++]; |
6516 | 96.7k | const auto &grid2_param_code = row[idx++]; |
6517 | 96.7k | const auto &grid2_param_name = row[idx++]; |
6518 | 96.7k | const auto &grid2_name = row[idx++]; |
6519 | 96.7k | const auto &interpolation_crs_auth_name = row[idx++]; |
6520 | 96.7k | const auto &interpolation_crs_code = row[idx++]; |
6521 | 96.7k | const auto &operation_version = row[idx++]; |
6522 | 96.7k | const auto &deprecated_str = row[idx++]; |
6523 | 96.7k | const bool deprecated = deprecated_str == "1"; |
6524 | 96.7k | assert(idx == row.size()); |
6525 | | |
6526 | 96.7k | auto sourceCRS = |
6527 | 96.7k | d->createFactory(source_crs_auth_name) |
6528 | 96.7k | ->createCoordinateReferenceSystem(source_crs_code); |
6529 | 96.7k | auto targetCRS = |
6530 | 96.7k | d->createFactory(target_crs_auth_name) |
6531 | 96.7k | ->createCoordinateReferenceSystem(target_crs_code); |
6532 | 96.7k | auto interpolationCRS = |
6533 | 96.7k | interpolation_crs_auth_name.empty() |
6534 | 96.7k | ? nullptr |
6535 | 96.7k | : d->createFactory(interpolation_crs_auth_name) |
6536 | 174 | ->createCoordinateReferenceSystem( |
6537 | 174 | interpolation_crs_code) |
6538 | 174 | .as_nullable(); |
6539 | | |
6540 | 96.7k | std::vector<operation::OperationParameterNNPtr> parameters; |
6541 | 96.7k | std::vector<operation::ParameterValueNNPtr> values; |
6542 | | |
6543 | 96.7k | parameters.emplace_back(operation::OperationParameter::create( |
6544 | 96.7k | util::PropertyMap() |
6545 | 96.7k | .set(common::IdentifiedObject::NAME_KEY, grid_param_name) |
6546 | 96.7k | .set(metadata::Identifier::CODESPACE_KEY, |
6547 | 96.7k | grid_param_auth_name) |
6548 | 96.7k | .set(metadata::Identifier::CODE_KEY, grid_param_code))); |
6549 | 96.7k | values.emplace_back( |
6550 | 96.7k | operation::ParameterValue::createFilename(grid_name)); |
6551 | 96.7k | if (!grid2_name.empty()) { |
6552 | 87.9k | parameters.emplace_back(operation::OperationParameter::create( |
6553 | 87.9k | util::PropertyMap() |
6554 | 87.9k | .set(common::IdentifiedObject::NAME_KEY, |
6555 | 87.9k | grid2_param_name) |
6556 | 87.9k | .set(metadata::Identifier::CODESPACE_KEY, |
6557 | 87.9k | grid2_param_auth_name) |
6558 | 87.9k | .set(metadata::Identifier::CODE_KEY, |
6559 | 87.9k | grid2_param_code))); |
6560 | 87.9k | values.emplace_back( |
6561 | 87.9k | operation::ParameterValue::createFilename(grid2_name)); |
6562 | 87.9k | } |
6563 | | |
6564 | 96.7k | auto props = d->createPropertiesSearchUsages( |
6565 | 96.7k | type, code, name, deprecated, description); |
6566 | 96.7k | if (!operation_version.empty()) { |
6567 | 96.7k | props.set(operation::CoordinateOperation::OPERATION_VERSION_KEY, |
6568 | 96.7k | operation_version); |
6569 | 96.7k | } |
6570 | 96.7k | auto propsMethod = |
6571 | 96.7k | util::PropertyMap() |
6572 | 96.7k | .set(metadata::Identifier::CODESPACE_KEY, method_auth_name) |
6573 | 96.7k | .set(metadata::Identifier::CODE_KEY, method_code) |
6574 | 96.7k | .set(common::IdentifiedObject::NAME_KEY, method_name); |
6575 | | |
6576 | 96.7k | std::vector<metadata::PositionalAccuracyNNPtr> accuracies; |
6577 | 96.7k | if (!accuracy.empty() && accuracy != "999.0") { |
6578 | 96.7k | accuracies.emplace_back( |
6579 | 96.7k | metadata::PositionalAccuracy::create(accuracy)); |
6580 | 96.7k | } |
6581 | | |
6582 | | // A bit fragile to detect the operation type with the method name, |
6583 | | // but not worth changing the database model |
6584 | 96.7k | if (starts_with(method_name, "Point motion")) { |
6585 | 41 | if (!sourceCRS->isEquivalentTo(targetCRS.get())) { |
6586 | 0 | throw operation::InvalidOperation( |
6587 | 0 | "source_crs and target_crs should be the same for a " |
6588 | 0 | "PointMotionOperation"); |
6589 | 0 | } |
6590 | | |
6591 | 41 | auto pmo = operation::PointMotionOperation::create( |
6592 | 41 | props, sourceCRS, propsMethod, parameters, values, |
6593 | 41 | accuracies); |
6594 | 41 | if (usePROJAlternativeGridNames) { |
6595 | 40 | return pmo->substitutePROJAlternativeGridNames( |
6596 | 40 | d->context()); |
6597 | 40 | } |
6598 | 1 | return pmo; |
6599 | 41 | } |
6600 | | |
6601 | 96.7k | auto transf = operation::Transformation::create( |
6602 | 96.7k | props, sourceCRS, targetCRS, interpolationCRS, propsMethod, |
6603 | 96.7k | parameters, values, accuracies); |
6604 | 96.7k | if (usePROJAlternativeGridNames) { |
6605 | 96.7k | return transf->substitutePROJAlternativeGridNames(d->context()); |
6606 | 96.7k | } |
6607 | 0 | return transf; |
6608 | | |
6609 | 96.7k | } catch (const std::exception &ex) { |
6610 | 0 | throw buildFactoryException("transformation", d->authority(), code, |
6611 | 0 | ex); |
6612 | 0 | } |
6613 | 96.7k | } |
6614 | | |
6615 | 36.5k | if (type == "other_transformation") { |
6616 | 1.46k | std::ostringstream buffer; |
6617 | 1.46k | buffer.imbue(std::locale::classic()); |
6618 | 1.46k | buffer |
6619 | 1.46k | << "SELECT name, description, " |
6620 | 1.46k | "method_auth_name, method_code, method_name, " |
6621 | 1.46k | "source_crs_auth_name, source_crs_code, target_crs_auth_name, " |
6622 | 1.46k | "target_crs_code, " |
6623 | 1.46k | "interpolation_crs_auth_name, interpolation_crs_code, " |
6624 | 1.46k | "operation_version, accuracy, deprecated"; |
6625 | 11.6k | for (size_t i = 1; i <= N_MAX_PARAMS; ++i) { |
6626 | 10.2k | buffer << ", param" << i << "_auth_name"; |
6627 | 10.2k | buffer << ", param" << i << "_code"; |
6628 | 10.2k | buffer << ", param" << i << "_name"; |
6629 | 10.2k | buffer << ", param" << i << "_value"; |
6630 | 10.2k | buffer << ", param" << i << "_uom_auth_name"; |
6631 | 10.2k | buffer << ", param" << i << "_uom_code"; |
6632 | 10.2k | } |
6633 | 1.46k | buffer << " FROM other_transformation " |
6634 | 1.46k | "WHERE auth_name = ? AND code = ?"; |
6635 | | |
6636 | 1.46k | auto res = d->runWithCodeParam(buffer.str(), code); |
6637 | 1.46k | if (res.empty()) { |
6638 | | // shouldn't happen if foreign keys are OK |
6639 | 0 | throw NoSuchAuthorityCodeException("other_transformation not found", |
6640 | 0 | d->authority(), code); |
6641 | 0 | } |
6642 | 1.46k | try { |
6643 | 1.46k | const auto &row = res.front(); |
6644 | 1.46k | size_t idx = 0; |
6645 | 1.46k | const auto &name = row[idx++]; |
6646 | 1.46k | const auto &description = row[idx++]; |
6647 | 1.46k | const auto &method_auth_name = row[idx++]; |
6648 | 1.46k | const auto &method_code = row[idx++]; |
6649 | 1.46k | const auto &method_name = row[idx++]; |
6650 | 1.46k | const auto &source_crs_auth_name = row[idx++]; |
6651 | 1.46k | const auto &source_crs_code = row[idx++]; |
6652 | 1.46k | const auto &target_crs_auth_name = row[idx++]; |
6653 | 1.46k | const auto &target_crs_code = row[idx++]; |
6654 | 1.46k | const auto &interpolation_crs_auth_name = row[idx++]; |
6655 | 1.46k | const auto &interpolation_crs_code = row[idx++]; |
6656 | 1.46k | const auto &operation_version = row[idx++]; |
6657 | 1.46k | const auto &accuracy = row[idx++]; |
6658 | 1.46k | const auto &deprecated_str = row[idx++]; |
6659 | 1.46k | const bool deprecated = deprecated_str == "1"; |
6660 | | |
6661 | 1.46k | const size_t base_param_idx = idx; |
6662 | 1.46k | std::vector<operation::OperationParameterNNPtr> parameters; |
6663 | 1.46k | std::vector<operation::ParameterValueNNPtr> values; |
6664 | 1.68k | for (size_t i = 0; i < N_MAX_PARAMS; ++i) { |
6665 | 1.68k | const auto ¶m_auth_name = row[base_param_idx + i * 6 + 0]; |
6666 | 1.68k | if (param_auth_name.empty()) { |
6667 | 1.46k | break; |
6668 | 1.46k | } |
6669 | 226 | const auto ¶m_code = row[base_param_idx + i * 6 + 1]; |
6670 | 226 | const auto ¶m_name = row[base_param_idx + i * 6 + 2]; |
6671 | 226 | const auto ¶m_value = row[base_param_idx + i * 6 + 3]; |
6672 | 226 | const auto ¶m_uom_auth_name = |
6673 | 226 | row[base_param_idx + i * 6 + 4]; |
6674 | 226 | const auto ¶m_uom_code = row[base_param_idx + i * 6 + 5]; |
6675 | 226 | parameters.emplace_back(operation::OperationParameter::create( |
6676 | 226 | util::PropertyMap() |
6677 | 226 | .set(metadata::Identifier::CODESPACE_KEY, |
6678 | 226 | param_auth_name) |
6679 | 226 | .set(metadata::Identifier::CODE_KEY, param_code) |
6680 | 226 | .set(common::IdentifiedObject::NAME_KEY, param_name))); |
6681 | 226 | std::string normalized_uom_code(param_uom_code); |
6682 | 226 | const double normalized_value = normalizeMeasure( |
6683 | 226 | param_uom_code, param_value, normalized_uom_code); |
6684 | 226 | auto uom = d->createUnitOfMeasure(param_uom_auth_name, |
6685 | 226 | normalized_uom_code); |
6686 | 226 | values.emplace_back(operation::ParameterValue::create( |
6687 | 226 | common::Measure(normalized_value, uom))); |
6688 | 226 | } |
6689 | 1.46k | idx = base_param_idx + 6 * N_MAX_PARAMS; |
6690 | 1.46k | (void)idx; |
6691 | 1.46k | assert(idx == row.size()); |
6692 | | |
6693 | 1.46k | auto sourceCRS = |
6694 | 1.46k | d->createFactory(source_crs_auth_name) |
6695 | 1.46k | ->createCoordinateReferenceSystem(source_crs_code); |
6696 | 1.46k | auto targetCRS = |
6697 | 1.46k | d->createFactory(target_crs_auth_name) |
6698 | 1.46k | ->createCoordinateReferenceSystem(target_crs_code); |
6699 | 1.46k | auto interpolationCRS = |
6700 | 1.46k | interpolation_crs_auth_name.empty() |
6701 | 1.46k | ? nullptr |
6702 | 1.46k | : d->createFactory(interpolation_crs_auth_name) |
6703 | 4 | ->createCoordinateReferenceSystem( |
6704 | 4 | interpolation_crs_code) |
6705 | 4 | .as_nullable(); |
6706 | | |
6707 | 1.46k | auto props = d->createPropertiesSearchUsages( |
6708 | 1.46k | type, code, name, deprecated, description); |
6709 | 1.46k | if (!operation_version.empty()) { |
6710 | 1.39k | props.set(operation::CoordinateOperation::OPERATION_VERSION_KEY, |
6711 | 1.39k | operation_version); |
6712 | 1.39k | } |
6713 | | |
6714 | 1.46k | std::vector<metadata::PositionalAccuracyNNPtr> accuracies; |
6715 | 1.46k | if (!accuracy.empty() && accuracy != "999.0") { |
6716 | 1.46k | accuracies.emplace_back( |
6717 | 1.46k | metadata::PositionalAccuracy::create(accuracy)); |
6718 | 1.46k | } |
6719 | | |
6720 | 1.46k | if (method_auth_name == "PROJ") { |
6721 | 1.27k | if (method_code == "PROJString") { |
6722 | 1.27k | auto op = operation::SingleOperation::createPROJBased( |
6723 | 1.27k | props, method_name, sourceCRS, targetCRS, accuracies); |
6724 | 1.27k | op->setCRSs(sourceCRS, targetCRS, interpolationCRS); |
6725 | 1.27k | return op; |
6726 | 1.27k | } else if (method_code == "WKT") { |
6727 | 0 | auto op = util::nn_dynamic_pointer_cast< |
6728 | 0 | operation::CoordinateOperation>( |
6729 | 0 | WKTParser().createFromWKT(method_name)); |
6730 | 0 | if (!op) { |
6731 | 0 | throw FactoryException("WKT string does not express a " |
6732 | 0 | "coordinate operation"); |
6733 | 0 | } |
6734 | 0 | op->setCRSs(sourceCRS, targetCRS, interpolationCRS); |
6735 | 0 | return NN_NO_CHECK(op); |
6736 | 0 | } |
6737 | 1.27k | } |
6738 | | |
6739 | 187 | auto propsMethod = |
6740 | 187 | util::PropertyMap() |
6741 | 187 | .set(metadata::Identifier::CODESPACE_KEY, method_auth_name) |
6742 | 187 | .set(metadata::Identifier::CODE_KEY, method_code) |
6743 | 187 | .set(common::IdentifiedObject::NAME_KEY, method_name); |
6744 | | |
6745 | 187 | if (method_auth_name == metadata::Identifier::EPSG) { |
6746 | 187 | int method_code_int = std::atoi(method_code.c_str()); |
6747 | 187 | if (operation::isAxisOrderReversal(method_code_int) || |
6748 | 187 | method_code_int == EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT || |
6749 | 187 | method_code_int == |
6750 | 135 | EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR || |
6751 | 187 | method_code_int == EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL) { |
6752 | 52 | auto op = operation::Conversion::create(props, propsMethod, |
6753 | 52 | parameters, values); |
6754 | 52 | op->setCRSs(sourceCRS, targetCRS, interpolationCRS); |
6755 | 52 | return op; |
6756 | 52 | } |
6757 | 187 | } |
6758 | 135 | return operation::Transformation::create( |
6759 | 135 | props, sourceCRS, targetCRS, interpolationCRS, propsMethod, |
6760 | 135 | parameters, values, accuracies); |
6761 | | |
6762 | 187 | } catch (const std::exception &ex) { |
6763 | 0 | throw buildFactoryException("transformation", d->authority(), code, |
6764 | 0 | ex); |
6765 | 0 | } |
6766 | 1.46k | } |
6767 | | |
6768 | 35.1k | if (allowConcatenated && type == "concatenated_operation") { |
6769 | 35.1k | auto res = d->runWithCodeParam( |
6770 | 35.1k | "SELECT name, description, " |
6771 | 35.1k | "source_crs_auth_name, source_crs_code, " |
6772 | 35.1k | "target_crs_auth_name, target_crs_code, " |
6773 | 35.1k | "accuracy, " |
6774 | 35.1k | "operation_version, deprecated FROM " |
6775 | 35.1k | "concatenated_operation WHERE auth_name = ? AND code = ?", |
6776 | 35.1k | code); |
6777 | 35.1k | if (res.empty()) { |
6778 | | // shouldn't happen if foreign keys are OK |
6779 | 0 | throw NoSuchAuthorityCodeException( |
6780 | 0 | "concatenated_operation not found", d->authority(), code); |
6781 | 0 | } |
6782 | | |
6783 | 35.1k | auto resSteps = d->runWithCodeParam( |
6784 | 35.1k | "SELECT step_auth_name, step_code, step_direction FROM " |
6785 | 35.1k | "concatenated_operation_step WHERE operation_auth_name = ? " |
6786 | 35.1k | "AND operation_code = ? ORDER BY step_number", |
6787 | 35.1k | code); |
6788 | | |
6789 | 35.1k | try { |
6790 | 35.1k | const auto &row = res.front(); |
6791 | 35.1k | size_t idx = 0; |
6792 | 35.1k | const auto &name = row[idx++]; |
6793 | 35.1k | const auto &description = row[idx++]; |
6794 | 35.1k | const auto &source_crs_auth_name = row[idx++]; |
6795 | 35.1k | const auto &source_crs_code = row[idx++]; |
6796 | 35.1k | const auto &target_crs_auth_name = row[idx++]; |
6797 | 35.1k | const auto &target_crs_code = row[idx++]; |
6798 | 35.1k | const auto &accuracy = row[idx++]; |
6799 | 35.1k | const auto &operation_version = row[idx++]; |
6800 | 35.1k | const auto &deprecated_str = row[idx++]; |
6801 | 35.1k | const bool deprecated = deprecated_str == "1"; |
6802 | | |
6803 | 35.1k | std::vector<operation::CoordinateOperationNNPtr> operations; |
6804 | 35.1k | size_t countExplicitDirection = 0; |
6805 | 74.7k | for (const auto &rowStep : resSteps) { |
6806 | 74.7k | const auto &step_auth_name = rowStep[0]; |
6807 | 74.7k | const auto &step_code = rowStep[1]; |
6808 | 74.7k | const auto &step_direction = rowStep[2]; |
6809 | 74.7k | auto stepOp = |
6810 | 74.7k | d->createFactory(step_auth_name) |
6811 | 74.7k | ->createCoordinateOperation(step_code, false, |
6812 | 74.7k | usePROJAlternativeGridNames, |
6813 | 74.7k | std::string()); |
6814 | 74.7k | if (step_direction == "forward") { |
6815 | 9.14k | ++countExplicitDirection; |
6816 | 9.14k | operations.push_back(std::move(stepOp)); |
6817 | 65.6k | } else if (step_direction == "reverse") { |
6818 | 519 | ++countExplicitDirection; |
6819 | 519 | operations.push_back(stepOp->inverse()); |
6820 | 65.0k | } else { |
6821 | 65.0k | operations.push_back(std::move(stepOp)); |
6822 | 65.0k | } |
6823 | 74.7k | } |
6824 | | |
6825 | 35.1k | if (countExplicitDirection > 0 && |
6826 | 35.1k | countExplicitDirection != resSteps.size()) { |
6827 | 0 | throw FactoryException("not all steps have a defined direction " |
6828 | 0 | "for concatenated operation " + |
6829 | 0 | code); |
6830 | 0 | } |
6831 | | |
6832 | 35.1k | const bool fixDirectionAllowed = (countExplicitDirection == 0); |
6833 | 35.1k | operation::ConcatenatedOperation::fixSteps( |
6834 | 35.1k | d->createFactory(source_crs_auth_name) |
6835 | 35.1k | ->createCoordinateReferenceSystem(source_crs_code), |
6836 | 35.1k | d->createFactory(target_crs_auth_name) |
6837 | 35.1k | ->createCoordinateReferenceSystem(target_crs_code), |
6838 | 35.1k | operations, d->context(), fixDirectionAllowed); |
6839 | | |
6840 | 35.1k | auto props = d->createPropertiesSearchUsages( |
6841 | 35.1k | type, code, name, deprecated, description); |
6842 | 35.1k | if (!operation_version.empty()) { |
6843 | 32.0k | props.set(operation::CoordinateOperation::OPERATION_VERSION_KEY, |
6844 | 32.0k | operation_version); |
6845 | 32.0k | } |
6846 | | |
6847 | 35.1k | std::vector<metadata::PositionalAccuracyNNPtr> accuracies; |
6848 | 35.1k | if (!accuracy.empty()) { |
6849 | 35.1k | if (accuracy != "999.0") { |
6850 | 35.1k | accuracies.emplace_back( |
6851 | 35.1k | metadata::PositionalAccuracy::create(accuracy)); |
6852 | 35.1k | } |
6853 | 35.1k | } else { |
6854 | | // Try to compute a reasonable accuracy from the members |
6855 | 8 | double totalAcc = -1; |
6856 | 8 | try { |
6857 | 19 | for (const auto &op : operations) { |
6858 | 19 | auto accs = op->coordinateOperationAccuracies(); |
6859 | 19 | if (accs.size() == 1) { |
6860 | 8 | double acc = c_locale_stod(accs[0]->value()); |
6861 | 8 | if (totalAcc < 0) { |
6862 | 5 | totalAcc = acc; |
6863 | 5 | } else { |
6864 | 3 | totalAcc += acc; |
6865 | 3 | } |
6866 | 11 | } else if (dynamic_cast<const operation::Conversion *>( |
6867 | 11 | op.get())) { |
6868 | | // A conversion is perfectly accurate. |
6869 | 6 | if (totalAcc < 0) { |
6870 | 3 | totalAcc = 0; |
6871 | 3 | } |
6872 | 6 | } else { |
6873 | 5 | totalAcc = -1; |
6874 | 5 | break; |
6875 | 5 | } |
6876 | 19 | } |
6877 | 8 | if (totalAcc >= 0) { |
6878 | 3 | accuracies.emplace_back( |
6879 | 3 | metadata::PositionalAccuracy::create( |
6880 | 3 | toString(totalAcc))); |
6881 | 3 | } |
6882 | 8 | } catch (const std::exception &) { |
6883 | 0 | } |
6884 | 8 | } |
6885 | 35.1k | return operation::ConcatenatedOperation::create(props, operations, |
6886 | 35.1k | accuracies); |
6887 | | |
6888 | 35.1k | } catch (const std::exception &ex) { |
6889 | 0 | throw buildFactoryException("transformation", d->authority(), code, |
6890 | 0 | ex); |
6891 | 0 | } |
6892 | 35.1k | } |
6893 | | |
6894 | 0 | throw FactoryException("unhandled coordinate operation type: " + type); |
6895 | 35.1k | } |
6896 | | |
6897 | | // --------------------------------------------------------------------------- |
6898 | | |
6899 | | /** \brief Returns a list operation::CoordinateOperation between two CRS. |
6900 | | * |
6901 | | * The list is ordered with preferred operations first. No attempt is made |
6902 | | * at inferring operations that are not explicitly in the database. |
6903 | | * |
6904 | | * Deprecated operations are rejected. |
6905 | | * |
6906 | | * @param sourceCRSCode Source CRS code allocated by authority. |
6907 | | * @param targetCRSCode Source CRS code allocated by authority. |
6908 | | * @return list of coordinate operations |
6909 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
6910 | | * @throw FactoryException in case of other errors. |
6911 | | */ |
6912 | | |
6913 | | std::vector<operation::CoordinateOperationNNPtr> |
6914 | | AuthorityFactory::createFromCoordinateReferenceSystemCodes( |
6915 | 0 | const std::string &sourceCRSCode, const std::string &targetCRSCode) const { |
6916 | 0 | return createFromCoordinateReferenceSystemCodes( |
6917 | 0 | d->authority(), sourceCRSCode, d->authority(), targetCRSCode, false, |
6918 | 0 | false, false, false); |
6919 | 0 | } |
6920 | | |
6921 | | // --------------------------------------------------------------------------- |
6922 | | |
6923 | | /** \brief Returns a list of geoid models available for that crs |
6924 | | * |
6925 | | * The list includes the geoid models connected directly with the crs, |
6926 | | * or via "Height Depth Reversal" or "Change of Vertical Unit" transformations |
6927 | | * |
6928 | | * @param code crs code allocated by authority. |
6929 | | * @return list of geoid model names |
6930 | | * @throw FactoryException in case of error. |
6931 | | */ |
6932 | | |
6933 | | std::list<std::string> |
6934 | 0 | AuthorityFactory::getGeoidModels(const std::string &code) const { |
6935 | |
|
6936 | 0 | ListOfParams params; |
6937 | 0 | std::string sql; |
6938 | 0 | sql += "SELECT DISTINCT GM0.name " |
6939 | 0 | " FROM geoid_model GM0 " |
6940 | 0 | "INNER JOIN grid_transformation GT0 " |
6941 | 0 | " ON GT0.code = GM0.operation_code " |
6942 | 0 | " AND GT0.auth_name = GM0.operation_auth_name " |
6943 | 0 | " AND GT0.deprecated = 0 " |
6944 | 0 | "INNER JOIN vertical_crs VC0 " |
6945 | 0 | " ON VC0.code = GT0.target_crs_code " |
6946 | 0 | " AND VC0.auth_name = GT0.target_crs_auth_name " |
6947 | 0 | "INNER JOIN vertical_crs VC1 " |
6948 | 0 | " ON VC1.datum_code = VC0.datum_code " |
6949 | 0 | " AND VC1.datum_auth_name = VC0.datum_auth_name " |
6950 | 0 | " AND VC1.code = ? "; |
6951 | 0 | params.emplace_back(code); |
6952 | 0 | if (d->hasAuthorityRestriction()) { |
6953 | 0 | sql += " AND GT0.target_crs_auth_name = ? "; |
6954 | 0 | params.emplace_back(d->authority()); |
6955 | 0 | } |
6956 | 0 | sql += " ORDER BY 1 "; |
6957 | |
|
6958 | 0 | auto sqlRes = d->run(sql, params); |
6959 | 0 | std::list<std::string> res; |
6960 | 0 | for (const auto &row : sqlRes) { |
6961 | 0 | res.push_back(row[0]); |
6962 | 0 | } |
6963 | 0 | return res; |
6964 | 0 | } |
6965 | | |
6966 | | // --------------------------------------------------------------------------- |
6967 | | |
6968 | | /** \brief Returns a list operation::CoordinateOperation between two CRS. |
6969 | | * |
6970 | | * The list is ordered with preferred operations first. No attempt is made |
6971 | | * at inferring operations that are not explicitly in the database (see |
6972 | | * createFromCRSCodesWithIntermediates() for that), and only |
6973 | | * source -> target operations are searched (i.e. if target -> source is |
6974 | | * present, you need to call this method with the arguments reversed, and apply |
6975 | | * the reverse transformations). |
6976 | | * |
6977 | | * Deprecated operations are rejected. |
6978 | | * |
6979 | | * If getAuthority() returns empty, then coordinate operations from all |
6980 | | * authorities are considered. |
6981 | | * |
6982 | | * @param sourceCRSAuthName Authority name of sourceCRSCode |
6983 | | * @param sourceCRSCode Source CRS code allocated by authority |
6984 | | * sourceCRSAuthName. |
6985 | | * @param targetCRSAuthName Authority name of targetCRSCode |
6986 | | * @param targetCRSCode Source CRS code allocated by authority |
6987 | | * targetCRSAuthName. |
6988 | | * @param usePROJAlternativeGridNames Whether PROJ alternative grid names |
6989 | | * should be substituted to the official grid names. |
6990 | | * @param discardIfMissingGrid Whether coordinate operations that reference |
6991 | | * missing grids should be removed from the result set. |
6992 | | * @param considerKnownGridsAsAvailable Whether known grids should be considered |
6993 | | * as available (typically when network is enabled). |
6994 | | * @param discardSuperseded Whether coordinate operations that are superseded |
6995 | | * (but not deprecated) should be removed from the result set. |
6996 | | * @param tryReverseOrder whether to search in the reverse order too (and thus |
6997 | | * inverse results found that way) |
6998 | | * @param reportOnlyIntersectingTransformations if intersectingExtent1 and |
6999 | | * intersectingExtent2 should be honored in a strict way. |
7000 | | * @param intersectingExtent1 Optional extent that the resulting operations |
7001 | | * must intersect. |
7002 | | * @param intersectingExtent2 Optional extent that the resulting operations |
7003 | | * must intersect. |
7004 | | * @return list of coordinate operations |
7005 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
7006 | | * @throw FactoryException in case of other errors. |
7007 | | */ |
7008 | | |
7009 | | std::vector<operation::CoordinateOperationNNPtr> |
7010 | | AuthorityFactory::createFromCoordinateReferenceSystemCodes( |
7011 | | const std::string &sourceCRSAuthName, const std::string &sourceCRSCode, |
7012 | | const std::string &targetCRSAuthName, const std::string &targetCRSCode, |
7013 | | bool usePROJAlternativeGridNames, bool discardIfMissingGrid, |
7014 | | bool considerKnownGridsAsAvailable, bool discardSuperseded, |
7015 | | bool tryReverseOrder, bool reportOnlyIntersectingTransformations, |
7016 | | const metadata::ExtentPtr &intersectingExtent1, |
7017 | 135k | const metadata::ExtentPtr &intersectingExtent2) const { |
7018 | | |
7019 | 135k | auto cacheKey(d->authority()); |
7020 | 135k | cacheKey += sourceCRSAuthName.empty() ? "{empty}" : sourceCRSAuthName; |
7021 | 135k | cacheKey += sourceCRSCode; |
7022 | 135k | cacheKey += targetCRSAuthName.empty() ? "{empty}" : targetCRSAuthName; |
7023 | 135k | cacheKey += targetCRSCode; |
7024 | 135k | cacheKey += (usePROJAlternativeGridNames ? '1' : '0'); |
7025 | 135k | cacheKey += (discardIfMissingGrid ? '1' : '0'); |
7026 | 135k | cacheKey += (considerKnownGridsAsAvailable ? '1' : '0'); |
7027 | 135k | cacheKey += (discardSuperseded ? '1' : '0'); |
7028 | 135k | cacheKey += (tryReverseOrder ? '1' : '0'); |
7029 | 135k | cacheKey += (reportOnlyIntersectingTransformations ? '1' : '0'); |
7030 | 270k | for (const auto &extent : {intersectingExtent1, intersectingExtent2}) { |
7031 | 270k | if (extent) { |
7032 | 142k | const auto &geogExtent = extent->geographicElements(); |
7033 | 142k | if (geogExtent.size() == 1) { |
7034 | 142k | auto bbox = |
7035 | 142k | dynamic_cast<const metadata::GeographicBoundingBox *>( |
7036 | 142k | geogExtent[0].get()); |
7037 | 142k | if (bbox) { |
7038 | 142k | cacheKey += toString(bbox->southBoundLatitude()); |
7039 | 142k | cacheKey += toString(bbox->westBoundLongitude()); |
7040 | 142k | cacheKey += toString(bbox->northBoundLatitude()); |
7041 | 142k | cacheKey += toString(bbox->eastBoundLongitude()); |
7042 | 142k | } |
7043 | 142k | } |
7044 | 142k | } |
7045 | 270k | } |
7046 | | |
7047 | 135k | std::vector<operation::CoordinateOperationNNPtr> list; |
7048 | | |
7049 | 135k | if (d->context()->d->getCRSToCRSCoordOpFromCache(cacheKey, list)) { |
7050 | 100k | return list; |
7051 | 100k | } |
7052 | | |
7053 | | // Check if sourceCRS would be the base of a ProjectedCRS targetCRS |
7054 | | // In which case use the conversion of the ProjectedCRS |
7055 | 34.8k | if (!targetCRSAuthName.empty()) { |
7056 | 34.8k | auto targetFactory = d->createFactory(targetCRSAuthName); |
7057 | 34.8k | const auto cacheKeyProjectedCRS(targetFactory->d->authority() + |
7058 | 34.8k | targetCRSCode); |
7059 | 34.8k | auto crs = targetFactory->d->context()->d->getCRSFromCache( |
7060 | 34.8k | cacheKeyProjectedCRS); |
7061 | 34.8k | crs::ProjectedCRSPtr targetProjCRS; |
7062 | 34.8k | if (crs) { |
7063 | 34.8k | targetProjCRS = std::dynamic_pointer_cast<crs::ProjectedCRS>(crs); |
7064 | 34.8k | } else { |
7065 | 0 | const auto sqlRes = |
7066 | 0 | targetFactory->d->createProjectedCRSBegin(targetCRSCode); |
7067 | 0 | if (!sqlRes.empty()) { |
7068 | 0 | try { |
7069 | 0 | targetProjCRS = |
7070 | 0 | targetFactory->d |
7071 | 0 | ->createProjectedCRSEnd(targetCRSCode, sqlRes) |
7072 | 0 | .as_nullable(); |
7073 | 0 | } catch (const std::exception &) { |
7074 | 0 | } |
7075 | 0 | } |
7076 | 0 | } |
7077 | 34.8k | if (targetProjCRS) { |
7078 | 3 | const auto &baseIds = targetProjCRS->baseCRS()->identifiers(); |
7079 | 3 | if (sourceCRSAuthName.empty() || |
7080 | 3 | (!baseIds.empty() && |
7081 | 3 | *(baseIds.front()->codeSpace()) == sourceCRSAuthName && |
7082 | 3 | baseIds.front()->code() == sourceCRSCode)) { |
7083 | 0 | bool ok = true; |
7084 | 0 | auto conv = targetProjCRS->derivingConversion(); |
7085 | 0 | if (d->hasAuthorityRestriction()) { |
7086 | 0 | ok = *(conv->identifiers().front()->codeSpace()) == |
7087 | 0 | d->authority(); |
7088 | 0 | } |
7089 | 0 | if (ok) { |
7090 | 0 | list.emplace_back(conv); |
7091 | 0 | d->context()->d->cache(cacheKey, list); |
7092 | 0 | return list; |
7093 | 0 | } |
7094 | 0 | } |
7095 | 3 | } |
7096 | 34.8k | } |
7097 | | |
7098 | 34.8k | std::string sql; |
7099 | 34.8k | if (discardSuperseded) { |
7100 | 34.8k | sql = "SELECT cov.source_crs_auth_name, cov.source_crs_code, " |
7101 | 34.8k | "cov.target_crs_auth_name, cov.target_crs_code, " |
7102 | 34.8k | "cov.auth_name, cov.code, cov.table_name, " |
7103 | 34.8k | "extent.south_lat, extent.west_lon, extent.north_lat, " |
7104 | 34.8k | "extent.east_lon, " |
7105 | 34.8k | "ss.replacement_auth_name, ss.replacement_code, " |
7106 | 34.8k | "(gt.auth_name IS NOT NULL) AS replacement_is_grid_transform, " |
7107 | 34.8k | "(ga.proj_grid_name IS NOT NULL) AS replacement_is_known_grid " |
7108 | 34.8k | "FROM " |
7109 | 34.8k | "coordinate_operation_view cov " |
7110 | 34.8k | "JOIN usage ON " |
7111 | 34.8k | "usage.object_table_name = cov.table_name AND " |
7112 | 34.8k | "usage.object_auth_name = cov.auth_name AND " |
7113 | 34.8k | "usage.object_code = cov.code " |
7114 | 34.8k | "JOIN extent " |
7115 | 34.8k | "ON extent.auth_name = usage.extent_auth_name AND " |
7116 | 34.8k | "extent.code = usage.extent_code " |
7117 | 34.8k | "LEFT JOIN supersession ss ON " |
7118 | 34.8k | "ss.superseded_table_name = cov.table_name AND " |
7119 | 34.8k | "ss.superseded_auth_name = cov.auth_name AND " |
7120 | 34.8k | "ss.superseded_code = cov.code AND " |
7121 | 34.8k | "ss.superseded_table_name = ss.replacement_table_name AND " |
7122 | 34.8k | "ss.same_source_target_crs = 1 " |
7123 | 34.8k | "LEFT JOIN grid_transformation gt ON " |
7124 | 34.8k | "gt.auth_name = ss.replacement_auth_name AND " |
7125 | 34.8k | "gt.code = ss.replacement_code " |
7126 | 34.8k | "LEFT JOIN grid_alternatives ga ON " |
7127 | 34.8k | "ga.original_grid_name = gt.grid_name " |
7128 | 34.8k | "WHERE "; |
7129 | 34.8k | } else { |
7130 | 0 | sql = "SELECT source_crs_auth_name, source_crs_code, " |
7131 | 0 | "target_crs_auth_name, target_crs_code, " |
7132 | 0 | "cov.auth_name, cov.code, cov.table_name, " |
7133 | 0 | "extent.south_lat, extent.west_lon, extent.north_lat, " |
7134 | 0 | "extent.east_lon " |
7135 | 0 | "FROM " |
7136 | 0 | "coordinate_operation_view cov " |
7137 | 0 | "JOIN usage ON " |
7138 | 0 | "usage.object_table_name = cov.table_name AND " |
7139 | 0 | "usage.object_auth_name = cov.auth_name AND " |
7140 | 0 | "usage.object_code = cov.code " |
7141 | 0 | "JOIN extent " |
7142 | 0 | "ON extent.auth_name = usage.extent_auth_name AND " |
7143 | 0 | "extent.code = usage.extent_code " |
7144 | 0 | "WHERE "; |
7145 | 0 | } |
7146 | 34.8k | ListOfParams params; |
7147 | 34.8k | if (!sourceCRSAuthName.empty() && !targetCRSAuthName.empty()) { |
7148 | 34.7k | if (tryReverseOrder) { |
7149 | 34.7k | sql += "((cov.source_crs_auth_name = ? AND cov.source_crs_code = ? " |
7150 | 34.7k | "AND " |
7151 | 34.7k | "cov.target_crs_auth_name = ? AND cov.target_crs_code = ?) " |
7152 | 34.7k | "OR " |
7153 | 34.7k | "(cov.source_crs_auth_name = ? AND cov.source_crs_code = ? " |
7154 | 34.7k | "AND " |
7155 | 34.7k | "cov.target_crs_auth_name = ? AND cov.target_crs_code = ?)) " |
7156 | 34.7k | "AND "; |
7157 | 34.7k | params.emplace_back(sourceCRSAuthName); |
7158 | 34.7k | params.emplace_back(sourceCRSCode); |
7159 | 34.7k | params.emplace_back(targetCRSAuthName); |
7160 | 34.7k | params.emplace_back(targetCRSCode); |
7161 | 34.7k | params.emplace_back(targetCRSAuthName); |
7162 | 34.7k | params.emplace_back(targetCRSCode); |
7163 | 34.7k | params.emplace_back(sourceCRSAuthName); |
7164 | 34.7k | params.emplace_back(sourceCRSCode); |
7165 | 34.7k | } else { |
7166 | 0 | sql += "cov.source_crs_auth_name = ? AND cov.source_crs_code = ? " |
7167 | 0 | "AND " |
7168 | 0 | "cov.target_crs_auth_name = ? AND cov.target_crs_code = ? " |
7169 | 0 | "AND "; |
7170 | 0 | params.emplace_back(sourceCRSAuthName); |
7171 | 0 | params.emplace_back(sourceCRSCode); |
7172 | 0 | params.emplace_back(targetCRSAuthName); |
7173 | 0 | params.emplace_back(targetCRSCode); |
7174 | 0 | } |
7175 | 34.7k | } else if (!sourceCRSAuthName.empty()) { |
7176 | 0 | if (tryReverseOrder) { |
7177 | 0 | sql += "((cov.source_crs_auth_name = ? AND cov.source_crs_code = ? " |
7178 | 0 | ")OR " |
7179 | 0 | "(cov.target_crs_auth_name = ? AND cov.target_crs_code = ?))" |
7180 | 0 | " AND "; |
7181 | 0 | params.emplace_back(sourceCRSAuthName); |
7182 | 0 | params.emplace_back(sourceCRSCode); |
7183 | 0 | params.emplace_back(sourceCRSAuthName); |
7184 | 0 | params.emplace_back(sourceCRSCode); |
7185 | 0 | } else { |
7186 | 0 | sql += "cov.source_crs_auth_name = ? AND cov.source_crs_code = ? " |
7187 | 0 | "AND "; |
7188 | 0 | params.emplace_back(sourceCRSAuthName); |
7189 | 0 | params.emplace_back(sourceCRSCode); |
7190 | 0 | } |
7191 | 87 | } else if (!targetCRSAuthName.empty()) { |
7192 | 87 | if (tryReverseOrder) { |
7193 | 87 | sql += "((cov.source_crs_auth_name = ? AND cov.source_crs_code = ?)" |
7194 | 87 | " OR " |
7195 | 87 | "(cov.target_crs_auth_name = ? AND cov.target_crs_code = ?))" |
7196 | 87 | " AND "; |
7197 | 87 | params.emplace_back(targetCRSAuthName); |
7198 | 87 | params.emplace_back(targetCRSCode); |
7199 | 87 | params.emplace_back(targetCRSAuthName); |
7200 | 87 | params.emplace_back(targetCRSCode); |
7201 | 87 | } else { |
7202 | 0 | sql += "cov.target_crs_auth_name = ? AND cov.target_crs_code = ? " |
7203 | 0 | "AND "; |
7204 | 0 | params.emplace_back(targetCRSAuthName); |
7205 | 0 | params.emplace_back(targetCRSCode); |
7206 | 0 | } |
7207 | 87 | } |
7208 | 34.8k | sql += "cov.deprecated = 0"; |
7209 | 34.8k | if (d->hasAuthorityRestriction()) { |
7210 | 31.9k | sql += " AND cov.auth_name = ?"; |
7211 | 31.9k | params.emplace_back(d->authority()); |
7212 | 31.9k | } |
7213 | 34.8k | sql += " ORDER BY pseudo_area_from_swne(south_lat, west_lon, north_lat, " |
7214 | 34.8k | "east_lon) DESC, " |
7215 | 34.8k | "(CASE WHEN cov.accuracy is NULL THEN 1 ELSE 0 END), cov.accuracy"; |
7216 | 34.8k | auto res = d->run(sql, params); |
7217 | 34.8k | std::set<std::pair<std::string, std::string>> setTransf; |
7218 | 34.8k | if (discardSuperseded) { |
7219 | 34.8k | for (const auto &row : res) { |
7220 | 32.7k | const auto &auth_name = row[4]; |
7221 | 32.7k | const auto &code = row[5]; |
7222 | 32.7k | setTransf.insert( |
7223 | 32.7k | std::pair<std::string, std::string>(auth_name, code)); |
7224 | 32.7k | } |
7225 | 34.8k | } |
7226 | | |
7227 | | // Do a pass to determine if there are transformations that intersect |
7228 | | // intersectingExtent1 & intersectingExtent2 |
7229 | 34.8k | std::vector<bool> intersectingTransformations; |
7230 | 34.8k | intersectingTransformations.resize(res.size()); |
7231 | 34.8k | bool hasIntersectingTransformations = false; |
7232 | 34.8k | size_t i = 0; |
7233 | 34.8k | for (const auto &row : res) { |
7234 | 32.7k | size_t thisI = i; |
7235 | 32.7k | ++i; |
7236 | 32.7k | if (discardSuperseded) { |
7237 | 32.7k | const auto &replacement_auth_name = row[11]; |
7238 | 32.7k | const auto &replacement_code = row[12]; |
7239 | 32.7k | const bool replacement_is_grid_transform = row[13] == "1"; |
7240 | 32.7k | const bool replacement_is_known_grid = row[14] == "1"; |
7241 | 32.7k | if (!replacement_auth_name.empty() && |
7242 | | // Ignore supersession if the replacement uses a unknown grid |
7243 | 32.7k | !(replacement_is_grid_transform && |
7244 | 157 | !replacement_is_known_grid) && |
7245 | 32.7k | setTransf.find(std::pair<std::string, std::string>( |
7246 | 149 | replacement_auth_name, replacement_code)) != |
7247 | 149 | setTransf.end()) { |
7248 | | // Skip transformations that are superseded by others that got |
7249 | | // returned in the result set. |
7250 | 149 | continue; |
7251 | 149 | } |
7252 | 32.7k | } |
7253 | | |
7254 | 32.6k | bool intersecting = true; |
7255 | 32.6k | try { |
7256 | 32.6k | double south_lat = c_locale_stod(row[7]); |
7257 | 32.6k | double west_lon = c_locale_stod(row[8]); |
7258 | 32.6k | double north_lat = c_locale_stod(row[9]); |
7259 | 32.6k | double east_lon = c_locale_stod(row[10]); |
7260 | 32.6k | auto transf_extent = metadata::Extent::createFromBBOX( |
7261 | 32.6k | west_lon, south_lat, east_lon, north_lat); |
7262 | | |
7263 | 32.6k | for (const auto &extent : |
7264 | 64.9k | {intersectingExtent1, intersectingExtent2}) { |
7265 | 64.9k | if (extent) { |
7266 | 982 | if (!transf_extent->intersects(NN_NO_CHECK(extent))) { |
7267 | 272 | intersecting = false; |
7268 | 272 | break; |
7269 | 272 | } |
7270 | 982 | } |
7271 | 64.9k | } |
7272 | 32.6k | } catch (const std::exception &) { |
7273 | 0 | } |
7274 | | |
7275 | 32.6k | intersectingTransformations[thisI] = intersecting; |
7276 | 32.6k | if (intersecting) |
7277 | 32.3k | hasIntersectingTransformations = true; |
7278 | 32.6k | } |
7279 | | |
7280 | | // If there are intersecting transformations, then only report those ones |
7281 | | // If there are no intersecting transformations, report all of them |
7282 | | // This is for the "projinfo -s EPSG:32631 -t EPSG:2171" use case where we |
7283 | | // still want to be able to use the Pulkovo datum shift if EPSG:32631 |
7284 | | // coordinates are used |
7285 | 34.8k | i = 0; |
7286 | 34.8k | for (const auto &row : res) { |
7287 | 32.7k | size_t thisI = i; |
7288 | 32.7k | ++i; |
7289 | 32.7k | if ((hasIntersectingTransformations || |
7290 | 32.7k | reportOnlyIntersectingTransformations) && |
7291 | 32.7k | !intersectingTransformations[thisI]) { |
7292 | 241 | continue; |
7293 | 241 | } |
7294 | 32.5k | if (discardSuperseded) { |
7295 | 32.5k | const auto &replacement_auth_name = row[11]; |
7296 | 32.5k | const auto &replacement_code = row[12]; |
7297 | 32.5k | const bool replacement_is_grid_transform = row[13] == "1"; |
7298 | 32.5k | const bool replacement_is_known_grid = row[14] == "1"; |
7299 | 32.5k | if (!replacement_auth_name.empty() && |
7300 | | // Ignore supersession if the replacement uses a unknown grid |
7301 | 32.5k | !(replacement_is_grid_transform && |
7302 | 8 | !replacement_is_known_grid) && |
7303 | 32.5k | setTransf.find(std::pair<std::string, std::string>( |
7304 | 2 | replacement_auth_name, replacement_code)) != |
7305 | 2 | setTransf.end()) { |
7306 | | // Skip transformations that are superseded by others that got |
7307 | | // returned in the result set. |
7308 | 2 | continue; |
7309 | 2 | } |
7310 | 32.5k | } |
7311 | | |
7312 | 32.5k | const auto &source_crs_auth_name = row[0]; |
7313 | 32.5k | const auto &source_crs_code = row[1]; |
7314 | 32.5k | const auto &target_crs_auth_name = row[2]; |
7315 | 32.5k | const auto &target_crs_code = row[3]; |
7316 | 32.5k | const auto &auth_name = row[4]; |
7317 | 32.5k | const auto &code = row[5]; |
7318 | 32.5k | const auto &table_name = row[6]; |
7319 | 32.5k | try { |
7320 | 32.5k | auto op = d->createFactory(auth_name)->createCoordinateOperation( |
7321 | 32.5k | code, true, usePROJAlternativeGridNames, table_name); |
7322 | 32.5k | if (tryReverseOrder && |
7323 | 32.5k | (!sourceCRSAuthName.empty() |
7324 | 32.5k | ? (source_crs_auth_name != sourceCRSAuthName || |
7325 | 32.4k | source_crs_code != sourceCRSCode) |
7326 | 32.5k | : (target_crs_auth_name != targetCRSAuthName || |
7327 | 19.8k | target_crs_code != targetCRSCode))) { |
7328 | 19.8k | op = op->inverse(); |
7329 | 19.8k | } |
7330 | 32.5k | if (!discardIfMissingGrid || |
7331 | 32.5k | !d->rejectOpDueToMissingGrid(op, |
7332 | 32.5k | considerKnownGridsAsAvailable)) { |
7333 | 10.8k | list.emplace_back(op); |
7334 | 10.8k | } |
7335 | 32.5k | } catch (const std::exception &e) { |
7336 | | // Mostly for debugging purposes when using an inconsistent |
7337 | | // database |
7338 | 0 | if (getenv("PROJ_IGNORE_INSTANTIATION_ERRORS")) { |
7339 | 0 | fprintf(stderr, "Ignoring invalid operation: %s\n", e.what()); |
7340 | 0 | } else { |
7341 | 0 | throw; |
7342 | 0 | } |
7343 | 0 | } |
7344 | 32.5k | } |
7345 | 34.8k | d->context()->d->cache(cacheKey, list); |
7346 | 34.8k | return list; |
7347 | 34.8k | } |
7348 | | |
7349 | | // --------------------------------------------------------------------------- |
7350 | | |
7351 | | //! @cond Doxygen_Suppress |
7352 | | static bool useIrrelevantPivot(const operation::CoordinateOperationNNPtr &op, |
7353 | | const std::string &sourceCRSAuthName, |
7354 | | const std::string &sourceCRSCode, |
7355 | | const std::string &targetCRSAuthName, |
7356 | 54.2k | const std::string &targetCRSCode) { |
7357 | 54.2k | auto concat = |
7358 | 54.2k | dynamic_cast<const operation::ConcatenatedOperation *>(op.get()); |
7359 | 54.2k | if (!concat) { |
7360 | 32.9k | return false; |
7361 | 32.9k | } |
7362 | 21.3k | auto ops = concat->operations(); |
7363 | 31.9k | for (size_t i = 0; i + 1 < ops.size(); i++) { |
7364 | 26.8k | auto targetCRS = ops[i]->targetCRS(); |
7365 | 26.8k | if (targetCRS) { |
7366 | 26.8k | const auto &ids = targetCRS->identifiers(); |
7367 | 26.8k | if (ids.size() == 1 && |
7368 | 26.8k | ((*ids[0]->codeSpace() == sourceCRSAuthName && |
7369 | 26.8k | ids[0]->code() == sourceCRSCode) || |
7370 | 26.8k | (*ids[0]->codeSpace() == targetCRSAuthName && |
7371 | 20.2k | ids[0]->code() == targetCRSCode))) { |
7372 | 16.2k | return true; |
7373 | 16.2k | } |
7374 | 26.8k | } |
7375 | 26.8k | } |
7376 | 5.10k | return false; |
7377 | 21.3k | } |
7378 | | //! @endcond |
7379 | | |
7380 | | // --------------------------------------------------------------------------- |
7381 | | |
7382 | | /** \brief Returns a list operation::CoordinateOperation between two CRS, |
7383 | | * using intermediate codes. |
7384 | | * |
7385 | | * The list is ordered with preferred operations first. |
7386 | | * |
7387 | | * Deprecated operations are rejected. |
7388 | | * |
7389 | | * The method will take care of considering all potential combinations (i.e. |
7390 | | * contrary to createFromCoordinateReferenceSystemCodes(), you do not need to |
7391 | | * call it with sourceCRS and targetCRS switched) |
7392 | | * |
7393 | | * If getAuthority() returns empty, then coordinate operations from all |
7394 | | * authorities are considered. |
7395 | | * |
7396 | | * @param sourceCRSAuthName Authority name of sourceCRSCode |
7397 | | * @param sourceCRSCode Source CRS code allocated by authority |
7398 | | * sourceCRSAuthName. |
7399 | | * @param targetCRSAuthName Authority name of targetCRSCode |
7400 | | * @param targetCRSCode Source CRS code allocated by authority |
7401 | | * targetCRSAuthName. |
7402 | | * @param usePROJAlternativeGridNames Whether PROJ alternative grid names |
7403 | | * should be substituted to the official grid names. |
7404 | | * @param discardIfMissingGrid Whether coordinate operations that reference |
7405 | | * missing grids should be removed from the result set. |
7406 | | * @param considerKnownGridsAsAvailable Whether known grids should be considered |
7407 | | * as available (typically when network is enabled). |
7408 | | * @param discardSuperseded Whether coordinate operations that are superseded |
7409 | | * (but not deprecated) should be removed from the result set. |
7410 | | * @param intermediateCRSAuthCodes List of (auth_name, code) of CRS that can be |
7411 | | * used as potential intermediate CRS. If the list is empty, the database will |
7412 | | * be used to find common CRS in operations involving both the source and |
7413 | | * target CRS. |
7414 | | * @param allowedIntermediateObjectType Restrict the type of the intermediate |
7415 | | * object considered. |
7416 | | * Only ObjectType::CRS and ObjectType::GEOGRAPHIC_CRS supported currently |
7417 | | * @param allowedAuthorities One or several authority name allowed for the two |
7418 | | * coordinate operations that are going to be searched. When this vector is |
7419 | | * no empty, it overrides the authority of this object. This is useful for |
7420 | | * example when the coordinate operations to chain belong to two different |
7421 | | * allowed authorities. |
7422 | | * @param intersectingExtent1 Optional extent that the resulting operations |
7423 | | * must intersect. |
7424 | | * @param intersectingExtent2 Optional extent that the resulting operations |
7425 | | * must intersect. |
7426 | | * @return list of coordinate operations |
7427 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
7428 | | * @throw FactoryException in case of other errors. |
7429 | | */ |
7430 | | |
7431 | | std::vector<operation::CoordinateOperationNNPtr> |
7432 | | AuthorityFactory::createFromCRSCodesWithIntermediates( |
7433 | | const std::string &sourceCRSAuthName, const std::string &sourceCRSCode, |
7434 | | const std::string &targetCRSAuthName, const std::string &targetCRSCode, |
7435 | | bool usePROJAlternativeGridNames, bool discardIfMissingGrid, |
7436 | | bool considerKnownGridsAsAvailable, bool discardSuperseded, |
7437 | | const std::vector<std::pair<std::string, std::string>> |
7438 | | &intermediateCRSAuthCodes, |
7439 | | ObjectType allowedIntermediateObjectType, |
7440 | | const std::vector<std::string> &allowedAuthorities, |
7441 | | const metadata::ExtentPtr &intersectingExtent1, |
7442 | 25.1k | const metadata::ExtentPtr &intersectingExtent2) const { |
7443 | | |
7444 | 25.1k | std::vector<operation::CoordinateOperationNNPtr> listTmp; |
7445 | | |
7446 | 25.1k | if (sourceCRSAuthName == targetCRSAuthName && |
7447 | 25.1k | sourceCRSCode == targetCRSCode) { |
7448 | 60 | return listTmp; |
7449 | 60 | } |
7450 | | |
7451 | 25.0k | const auto CheckIfHasOperations = [this](const std::string &auth_name, |
7452 | 46.8k | const std::string &code) { |
7453 | 46.8k | return !(d->run("SELECT 1 FROM coordinate_operation_view WHERE " |
7454 | 46.8k | "(source_crs_auth_name = ? AND source_crs_code = ?) OR " |
7455 | 46.8k | "(target_crs_auth_name = ? AND target_crs_code = ?) " |
7456 | 46.8k | "LIMIT 1", |
7457 | 46.8k | {auth_name, code, auth_name, code}) |
7458 | 46.8k | .empty()); |
7459 | 46.8k | }; |
7460 | | |
7461 | | // If the source or target CRS are not the source or target of an operation, |
7462 | | // do not run the next costly requests. |
7463 | 25.0k | if (!CheckIfHasOperations(sourceCRSAuthName, sourceCRSCode) || |
7464 | 25.0k | !CheckIfHasOperations(targetCRSAuthName, targetCRSCode)) { |
7465 | 6.37k | return listTmp; |
7466 | 6.37k | } |
7467 | | |
7468 | 18.7k | const std::string sqlProlog( |
7469 | 18.7k | discardSuperseded |
7470 | 18.7k | ? |
7471 | | |
7472 | 18.7k | "SELECT v1.table_name as table1, " |
7473 | 18.7k | "v1.auth_name AS auth_name1, v1.code AS code1, " |
7474 | 18.7k | "v1.accuracy AS accuracy1, " |
7475 | 18.7k | "v2.table_name as table2, " |
7476 | 18.7k | "v2.auth_name AS auth_name2, v2.code AS code2, " |
7477 | 18.7k | "v2.accuracy as accuracy2, " |
7478 | 18.7k | "a1.south_lat AS south_lat1, " |
7479 | 18.7k | "a1.west_lon AS west_lon1, " |
7480 | 18.7k | "a1.north_lat AS north_lat1, " |
7481 | 18.7k | "a1.east_lon AS east_lon1, " |
7482 | 18.7k | "a2.south_lat AS south_lat2, " |
7483 | 18.7k | "a2.west_lon AS west_lon2, " |
7484 | 18.7k | "a2.north_lat AS north_lat2, " |
7485 | 18.7k | "a2.east_lon AS east_lon2, " |
7486 | 18.7k | "ss1.replacement_auth_name AS replacement_auth_name1, " |
7487 | 18.7k | "ss1.replacement_code AS replacement_code1, " |
7488 | 18.7k | "ss2.replacement_auth_name AS replacement_auth_name2, " |
7489 | 18.7k | "ss2.replacement_code AS replacement_code2 " |
7490 | 18.7k | "FROM coordinate_operation_view v1 " |
7491 | 18.7k | "JOIN coordinate_operation_view v2 " |
7492 | 18.7k | : |
7493 | | |
7494 | 18.7k | "SELECT v1.table_name as table1, " |
7495 | 0 | "v1.auth_name AS auth_name1, v1.code AS code1, " |
7496 | 0 | "v1.accuracy AS accuracy1, " |
7497 | 0 | "v2.table_name as table2, " |
7498 | 0 | "v2.auth_name AS auth_name2, v2.code AS code2, " |
7499 | 0 | "v2.accuracy as accuracy2, " |
7500 | 0 | "a1.south_lat AS south_lat1, " |
7501 | 0 | "a1.west_lon AS west_lon1, " |
7502 | 0 | "a1.north_lat AS north_lat1, " |
7503 | 0 | "a1.east_lon AS east_lon1, " |
7504 | 0 | "a2.south_lat AS south_lat2, " |
7505 | 0 | "a2.west_lon AS west_lon2, " |
7506 | 0 | "a2.north_lat AS north_lat2, " |
7507 | 0 | "a2.east_lon AS east_lon2 " |
7508 | 0 | "FROM coordinate_operation_view v1 " |
7509 | 0 | "JOIN coordinate_operation_view v2 "); |
7510 | | |
7511 | 18.7k | const char *joinSupersession = |
7512 | 18.7k | "LEFT JOIN supersession ss1 ON " |
7513 | 18.7k | "ss1.superseded_table_name = v1.table_name AND " |
7514 | 18.7k | "ss1.superseded_auth_name = v1.auth_name AND " |
7515 | 18.7k | "ss1.superseded_code = v1.code AND " |
7516 | 18.7k | "ss1.superseded_table_name = ss1.replacement_table_name AND " |
7517 | 18.7k | "ss1.same_source_target_crs = 1 " |
7518 | 18.7k | "LEFT JOIN supersession ss2 ON " |
7519 | 18.7k | "ss2.superseded_table_name = v2.table_name AND " |
7520 | 18.7k | "ss2.superseded_auth_name = v2.auth_name AND " |
7521 | 18.7k | "ss2.superseded_code = v2.code AND " |
7522 | 18.7k | "ss2.superseded_table_name = ss2.replacement_table_name AND " |
7523 | 18.7k | "ss2.same_source_target_crs = 1 "; |
7524 | 18.7k | const std::string joinArea( |
7525 | 18.7k | (discardSuperseded ? std::string(joinSupersession) : std::string()) |
7526 | 18.7k | .append("JOIN usage u1 ON " |
7527 | 18.7k | "u1.object_table_name = v1.table_name AND " |
7528 | 18.7k | "u1.object_auth_name = v1.auth_name AND " |
7529 | 18.7k | "u1.object_code = v1.code " |
7530 | 18.7k | "JOIN extent a1 " |
7531 | 18.7k | "ON a1.auth_name = u1.extent_auth_name AND " |
7532 | 18.7k | "a1.code = u1.extent_code " |
7533 | 18.7k | "JOIN usage u2 ON " |
7534 | 18.7k | "u2.object_table_name = v2.table_name AND " |
7535 | 18.7k | "u2.object_auth_name = v2.auth_name AND " |
7536 | 18.7k | "u2.object_code = v2.code " |
7537 | 18.7k | "JOIN extent a2 " |
7538 | 18.7k | "ON a2.auth_name = u2.extent_auth_name AND " |
7539 | 18.7k | "a2.code = u2.extent_code ")); |
7540 | 18.7k | const std::string orderBy( |
7541 | 18.7k | "ORDER BY (CASE WHEN accuracy1 is NULL THEN 1 ELSE 0 END) + " |
7542 | 18.7k | "(CASE WHEN accuracy2 is NULL THEN 1 ELSE 0 END), " |
7543 | 18.7k | "accuracy1 + accuracy2"); |
7544 | | |
7545 | | // Case (source->intermediate) and (intermediate->target) |
7546 | 18.7k | std::string sql( |
7547 | 18.7k | sqlProlog + |
7548 | 18.7k | "ON v1.target_crs_auth_name = v2.source_crs_auth_name " |
7549 | 18.7k | "AND v1.target_crs_code = v2.source_crs_code " + |
7550 | 18.7k | joinArea + |
7551 | 18.7k | "WHERE v1.source_crs_auth_name = ? AND v1.source_crs_code = ? " |
7552 | 18.7k | "AND v2.target_crs_auth_name = ? AND v2.target_crs_code = ? "); |
7553 | 18.7k | std::string minDate; |
7554 | 18.7k | std::string criterionOnIntermediateCRS; |
7555 | | |
7556 | 18.7k | const auto sourceCRS = d->createFactory(sourceCRSAuthName) |
7557 | 18.7k | ->createCoordinateReferenceSystem(sourceCRSCode); |
7558 | 18.7k | const auto targetCRS = d->createFactory(targetCRSAuthName) |
7559 | 18.7k | ->createCoordinateReferenceSystem(targetCRSCode); |
7560 | | |
7561 | 18.7k | const bool ETRFtoETRF = starts_with(sourceCRS->nameStr(), "ETRF") && |
7562 | 18.7k | starts_with(targetCRS->nameStr(), "ETRF"); |
7563 | | |
7564 | 18.7k | const bool NAD83_CSRS_to_NAD83_CSRS = |
7565 | 18.7k | starts_with(sourceCRS->nameStr(), "NAD83(CSRS)") && |
7566 | 18.7k | starts_with(targetCRS->nameStr(), "NAD83(CSRS)"); |
7567 | | |
7568 | 18.7k | if (allowedIntermediateObjectType == ObjectType::GEOGRAPHIC_CRS) { |
7569 | 12.8k | const auto &sourceGeogCRS = |
7570 | 12.8k | dynamic_cast<const crs::GeographicCRS *>(sourceCRS.get()); |
7571 | 12.8k | const auto &targetGeogCRS = |
7572 | 12.8k | dynamic_cast<const crs::GeographicCRS *>(targetCRS.get()); |
7573 | 12.8k | if (sourceGeogCRS && targetGeogCRS) { |
7574 | 12.8k | const auto &sourceDatum = sourceGeogCRS->datum(); |
7575 | 12.8k | const auto &targetDatum = targetGeogCRS->datum(); |
7576 | 12.8k | if (sourceDatum && sourceDatum->publicationDate().has_value() && |
7577 | 12.8k | targetDatum && targetDatum->publicationDate().has_value()) { |
7578 | 1.14k | const auto sourceDate( |
7579 | 1.14k | sourceDatum->publicationDate()->toString()); |
7580 | 1.14k | const auto targetDate( |
7581 | 1.14k | targetDatum->publicationDate()->toString()); |
7582 | 1.14k | minDate = std::min(sourceDate, targetDate); |
7583 | | // Check that the datum of the intermediateCRS has a publication |
7584 | | // date most recent that the one of the source and the target |
7585 | | // CRS Except when using the usual WGS84 pivot which happens to |
7586 | | // have a NULL publication date. |
7587 | 1.14k | criterionOnIntermediateCRS = |
7588 | 1.14k | "AND EXISTS(SELECT 1 FROM geodetic_crs x " |
7589 | 1.14k | "JOIN geodetic_datum y " |
7590 | 1.14k | "ON " |
7591 | 1.14k | "y.auth_name = x.datum_auth_name AND " |
7592 | 1.14k | "y.code = x.datum_code " |
7593 | 1.14k | "WHERE " |
7594 | 1.14k | "x.auth_name = v1.target_crs_auth_name AND " |
7595 | 1.14k | "x.code = v1.target_crs_code AND " |
7596 | 1.14k | "x.type IN ('geographic 2D', 'geographic 3D') AND " |
7597 | 1.14k | "(y.publication_date IS NULL OR " |
7598 | 1.14k | "(y.publication_date >= '" + |
7599 | 1.14k | minDate + "'))) "; |
7600 | 1.14k | } |
7601 | 12.8k | } |
7602 | 12.8k | if (criterionOnIntermediateCRS.empty()) { |
7603 | 11.6k | criterionOnIntermediateCRS = |
7604 | 11.6k | "AND EXISTS(SELECT 1 FROM geodetic_crs x WHERE " |
7605 | 11.6k | "x.auth_name = v1.target_crs_auth_name AND " |
7606 | 11.6k | "x.code = v1.target_crs_code AND " |
7607 | 11.6k | "x.type IN ('geographic 2D', 'geographic 3D')) "; |
7608 | 11.6k | } |
7609 | 12.8k | sql += criterionOnIntermediateCRS; |
7610 | 12.8k | } |
7611 | 18.7k | auto params = ListOfParams{sourceCRSAuthName, sourceCRSCode, |
7612 | 18.7k | targetCRSAuthName, targetCRSCode}; |
7613 | 18.7k | std::string additionalWhere( |
7614 | 18.7k | "AND v1.deprecated = 0 AND v2.deprecated = 0 " |
7615 | 18.7k | "AND intersects_bbox(south_lat1, west_lon1, north_lat1, east_lon1, " |
7616 | 18.7k | "south_lat2, west_lon2, north_lat2, east_lon2) = 1 "); |
7617 | 18.7k | if (!allowedAuthorities.empty()) { |
7618 | 14.7k | additionalWhere += "AND v1.auth_name IN ("; |
7619 | 59.1k | for (size_t i = 0; i < allowedAuthorities.size(); i++) { |
7620 | 44.3k | if (i > 0) |
7621 | 29.5k | additionalWhere += ','; |
7622 | 44.3k | additionalWhere += '?'; |
7623 | 44.3k | } |
7624 | 14.7k | additionalWhere += ") AND v2.auth_name IN ("; |
7625 | 59.1k | for (size_t i = 0; i < allowedAuthorities.size(); i++) { |
7626 | 44.3k | if (i > 0) |
7627 | 29.5k | additionalWhere += ','; |
7628 | 44.3k | additionalWhere += '?'; |
7629 | 44.3k | } |
7630 | 14.7k | additionalWhere += ')'; |
7631 | 44.3k | for (const auto &allowedAuthority : allowedAuthorities) { |
7632 | 44.3k | params.emplace_back(allowedAuthority); |
7633 | 44.3k | } |
7634 | 44.3k | for (const auto &allowedAuthority : allowedAuthorities) { |
7635 | 44.3k | params.emplace_back(allowedAuthority); |
7636 | 44.3k | } |
7637 | 14.7k | } |
7638 | 18.7k | if (d->hasAuthorityRestriction()) { |
7639 | 0 | additionalWhere += "AND v1.auth_name = ? AND v2.auth_name = ? "; |
7640 | 0 | params.emplace_back(d->authority()); |
7641 | 0 | params.emplace_back(d->authority()); |
7642 | 0 | } |
7643 | 37.4k | for (const auto &extent : {intersectingExtent1, intersectingExtent2}) { |
7644 | 37.4k | if (extent) { |
7645 | 19.0k | const auto &geogExtent = extent->geographicElements(); |
7646 | 19.0k | if (geogExtent.size() == 1) { |
7647 | 19.0k | auto bbox = |
7648 | 19.0k | dynamic_cast<const metadata::GeographicBoundingBox *>( |
7649 | 19.0k | geogExtent[0].get()); |
7650 | 19.0k | if (bbox) { |
7651 | 19.0k | const double south_lat = bbox->southBoundLatitude(); |
7652 | 19.0k | const double west_lon = bbox->westBoundLongitude(); |
7653 | 19.0k | const double north_lat = bbox->northBoundLatitude(); |
7654 | 19.0k | const double east_lon = bbox->eastBoundLongitude(); |
7655 | 19.0k | if (south_lat != -90.0 || west_lon != -180.0 || |
7656 | 19.0k | north_lat != 90.0 || east_lon != 180.0) { |
7657 | 13.2k | additionalWhere += |
7658 | 13.2k | "AND intersects_bbox(south_lat1, " |
7659 | 13.2k | "west_lon1, north_lat1, east_lon1, ?, ?, ?, ?) AND " |
7660 | 13.2k | "intersects_bbox(south_lat2, west_lon2, " |
7661 | 13.2k | "north_lat2, east_lon2, ?, ?, ?, ?) "; |
7662 | 13.2k | params.emplace_back(south_lat); |
7663 | 13.2k | params.emplace_back(west_lon); |
7664 | 13.2k | params.emplace_back(north_lat); |
7665 | 13.2k | params.emplace_back(east_lon); |
7666 | 13.2k | params.emplace_back(south_lat); |
7667 | 13.2k | params.emplace_back(west_lon); |
7668 | 13.2k | params.emplace_back(north_lat); |
7669 | 13.2k | params.emplace_back(east_lon); |
7670 | 13.2k | } |
7671 | 19.0k | } |
7672 | 19.0k | } |
7673 | 19.0k | } |
7674 | 37.4k | } |
7675 | | |
7676 | 18.7k | const auto buildIntermediateWhere = |
7677 | 18.7k | [&intermediateCRSAuthCodes](const std::string &first_field, |
7678 | 74.8k | const std::string &second_field) { |
7679 | 74.8k | if (intermediateCRSAuthCodes.empty()) { |
7680 | 74.8k | return std::string(); |
7681 | 74.8k | } |
7682 | 0 | std::string l_sql(" AND ("); |
7683 | 0 | for (size_t i = 0; i < intermediateCRSAuthCodes.size(); ++i) { |
7684 | 0 | if (i > 0) { |
7685 | 0 | l_sql += " OR"; |
7686 | 0 | } |
7687 | 0 | l_sql += "(v1." + first_field + "_crs_auth_name = ? AND "; |
7688 | 0 | l_sql += "v1." + first_field + "_crs_code = ? AND "; |
7689 | 0 | l_sql += "v2." + second_field + "_crs_auth_name = ? AND "; |
7690 | 0 | l_sql += "v2." + second_field + "_crs_code = ?) "; |
7691 | 0 | } |
7692 | 0 | l_sql += ')'; |
7693 | 0 | return l_sql; |
7694 | 74.8k | }; |
7695 | | |
7696 | 18.7k | std::string intermediateWhere = buildIntermediateWhere("target", "source"); |
7697 | 18.7k | for (const auto &pair : intermediateCRSAuthCodes) { |
7698 | 0 | params.emplace_back(pair.first); |
7699 | 0 | params.emplace_back(pair.second); |
7700 | 0 | params.emplace_back(pair.first); |
7701 | 0 | params.emplace_back(pair.second); |
7702 | 0 | } |
7703 | 18.7k | auto res = |
7704 | 18.7k | d->run(sql + additionalWhere + intermediateWhere + orderBy, params); |
7705 | | |
7706 | 74.8k | const auto filterOutSuperseded = [](SQLResultSet &&resultSet) { |
7707 | 74.8k | std::set<std::pair<std::string, std::string>> setTransf1; |
7708 | 74.8k | std::set<std::pair<std::string, std::string>> setTransf2; |
7709 | 74.8k | for (const auto &row : resultSet) { |
7710 | | // table1 |
7711 | 27.8k | const auto &auth_name1 = row[1]; |
7712 | 27.8k | const auto &code1 = row[2]; |
7713 | | // accuracy1 |
7714 | | // table2 |
7715 | 27.8k | const auto &auth_name2 = row[5]; |
7716 | 27.8k | const auto &code2 = row[6]; |
7717 | 27.8k | setTransf1.insert( |
7718 | 27.8k | std::pair<std::string, std::string>(auth_name1, code1)); |
7719 | 27.8k | setTransf2.insert( |
7720 | 27.8k | std::pair<std::string, std::string>(auth_name2, code2)); |
7721 | 27.8k | } |
7722 | 74.8k | SQLResultSet filteredResultSet; |
7723 | 74.8k | for (const auto &row : resultSet) { |
7724 | 27.8k | const auto &replacement_auth_name1 = row[16]; |
7725 | 27.8k | const auto &replacement_code1 = row[17]; |
7726 | 27.8k | const auto &replacement_auth_name2 = row[18]; |
7727 | 27.8k | const auto &replacement_code2 = row[19]; |
7728 | 27.8k | if (!replacement_auth_name1.empty() && |
7729 | 27.8k | setTransf1.find(std::pair<std::string, std::string>( |
7730 | 139 | replacement_auth_name1, replacement_code1)) != |
7731 | 139 | setTransf1.end()) { |
7732 | | // Skip transformations that are superseded by others that got |
7733 | | // returned in the result set. |
7734 | 139 | continue; |
7735 | 139 | } |
7736 | 27.7k | if (!replacement_auth_name2.empty() && |
7737 | 27.7k | setTransf2.find(std::pair<std::string, std::string>( |
7738 | 41 | replacement_auth_name2, replacement_code2)) != |
7739 | 41 | setTransf2.end()) { |
7740 | | // Skip transformations that are superseded by others that got |
7741 | | // returned in the result set. |
7742 | 41 | continue; |
7743 | 41 | } |
7744 | 27.7k | filteredResultSet.emplace_back(row); |
7745 | 27.7k | } |
7746 | 74.8k | return filteredResultSet; |
7747 | 74.8k | }; |
7748 | | |
7749 | 18.7k | if (discardSuperseded) { |
7750 | 18.7k | res = filterOutSuperseded(std::move(res)); |
7751 | 18.7k | } |
7752 | | |
7753 | 18.7k | const auto checkPivot = [ETRFtoETRF, NAD83_CSRS_to_NAD83_CSRS, &sourceCRS, |
7754 | 18.7k | &targetCRS](const crs::CRSPtr &intermediateCRS) { |
7755 | | // Make sure that ETRF2000 to ETRF2014 doesn't go through ITRF9x or |
7756 | | // ITRF>2014 |
7757 | 18.1k | if (ETRFtoETRF && intermediateCRS && |
7758 | 18.1k | starts_with(intermediateCRS->nameStr(), "ITRF")) { |
7759 | 93 | const auto normalizeDate = [](int v) { |
7760 | 93 | return (v >= 80 && v <= 99) ? v + 1900 : v; |
7761 | 93 | }; |
7762 | 31 | const int srcDate = normalizeDate( |
7763 | 31 | atoi(sourceCRS->nameStr().c_str() + strlen("ETRF"))); |
7764 | 31 | const int tgtDate = normalizeDate( |
7765 | 31 | atoi(targetCRS->nameStr().c_str() + strlen("ETRF"))); |
7766 | 31 | const int intermDate = normalizeDate( |
7767 | 31 | atoi(intermediateCRS->nameStr().c_str() + strlen("ITRF"))); |
7768 | 31 | if (srcDate > 0 && tgtDate > 0 && intermDate > 0) { |
7769 | 31 | if (intermDate < std::min(srcDate, tgtDate) || |
7770 | 31 | intermDate > std::max(srcDate, tgtDate)) { |
7771 | 17 | return false; |
7772 | 17 | } |
7773 | 31 | } |
7774 | 31 | } |
7775 | | |
7776 | | // Make sure that NAD83(CSRS)[x] to NAD83(CSRS)[y) doesn't go through |
7777 | | // NAD83 generic. Cf https://github.com/OSGeo/PROJ/issues/4464 |
7778 | 18.0k | if (NAD83_CSRS_to_NAD83_CSRS && intermediateCRS && |
7779 | 18.0k | (intermediateCRS->nameStr() == "NAD83" || |
7780 | 0 | intermediateCRS->nameStr() == "WGS 84")) { |
7781 | 0 | return false; |
7782 | 0 | } |
7783 | | |
7784 | 18.0k | return true; |
7785 | 18.0k | }; |
7786 | | |
7787 | 18.7k | for (const auto &row : res) { |
7788 | 309 | const auto &table1 = row[0]; |
7789 | 309 | const auto &auth_name1 = row[1]; |
7790 | 309 | const auto &code1 = row[2]; |
7791 | | // const auto &accuracy1 = row[3]; |
7792 | 309 | const auto &table2 = row[4]; |
7793 | 309 | const auto &auth_name2 = row[5]; |
7794 | 309 | const auto &code2 = row[6]; |
7795 | | // const auto &accuracy2 = row[7]; |
7796 | 309 | try { |
7797 | 309 | auto op1 = |
7798 | 309 | d->createFactory(auth_name1) |
7799 | 309 | ->createCoordinateOperation( |
7800 | 309 | code1, true, usePROJAlternativeGridNames, table1); |
7801 | 309 | if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, |
7802 | 309 | targetCRSAuthName, targetCRSCode)) { |
7803 | 0 | continue; |
7804 | 0 | } |
7805 | 309 | if (!checkPivot(op1->targetCRS())) { |
7806 | 0 | continue; |
7807 | 0 | } |
7808 | 309 | auto op2 = |
7809 | 309 | d->createFactory(auth_name2) |
7810 | 309 | ->createCoordinateOperation( |
7811 | 309 | code2, true, usePROJAlternativeGridNames, table2); |
7812 | 309 | if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, |
7813 | 309 | targetCRSAuthName, targetCRSCode)) { |
7814 | 0 | continue; |
7815 | 0 | } |
7816 | | |
7817 | 309 | listTmp.emplace_back( |
7818 | 309 | operation::ConcatenatedOperation::createComputeMetadata( |
7819 | 309 | {std::move(op1), std::move(op2)}, false)); |
7820 | 309 | } catch (const std::exception &e) { |
7821 | | // Mostly for debugging purposes when using an inconsistent |
7822 | | // database |
7823 | 0 | if (getenv("PROJ_IGNORE_INSTANTIATION_ERRORS")) { |
7824 | 0 | fprintf(stderr, "Ignoring invalid operation: %s\n", e.what()); |
7825 | 0 | } else { |
7826 | 0 | throw; |
7827 | 0 | } |
7828 | 0 | } |
7829 | 309 | } |
7830 | | |
7831 | | // Case (source->intermediate) and (target->intermediate) |
7832 | 18.7k | sql = sqlProlog + |
7833 | 18.7k | "ON v1.target_crs_auth_name = v2.target_crs_auth_name " |
7834 | 18.7k | "AND v1.target_crs_code = v2.target_crs_code " + |
7835 | 18.7k | joinArea + |
7836 | 18.7k | "WHERE v1.source_crs_auth_name = ? AND v1.source_crs_code = ? " |
7837 | 18.7k | "AND v2.source_crs_auth_name = ? AND v2.source_crs_code = ? "; |
7838 | 18.7k | if (allowedIntermediateObjectType == ObjectType::GEOGRAPHIC_CRS) { |
7839 | 12.8k | sql += criterionOnIntermediateCRS; |
7840 | 12.8k | } |
7841 | 18.7k | intermediateWhere = buildIntermediateWhere("target", "target"); |
7842 | 18.7k | res = d->run(sql + additionalWhere + intermediateWhere + orderBy, params); |
7843 | 18.7k | if (discardSuperseded) { |
7844 | 18.7k | res = filterOutSuperseded(std::move(res)); |
7845 | 18.7k | } |
7846 | | |
7847 | 24.3k | for (const auto &row : res) { |
7848 | 24.3k | const auto &table1 = row[0]; |
7849 | 24.3k | const auto &auth_name1 = row[1]; |
7850 | 24.3k | const auto &code1 = row[2]; |
7851 | | // const auto &accuracy1 = row[3]; |
7852 | 24.3k | const auto &table2 = row[4]; |
7853 | 24.3k | const auto &auth_name2 = row[5]; |
7854 | 24.3k | const auto &code2 = row[6]; |
7855 | | // const auto &accuracy2 = row[7]; |
7856 | 24.3k | try { |
7857 | 24.3k | auto op1 = |
7858 | 24.3k | d->createFactory(auth_name1) |
7859 | 24.3k | ->createCoordinateOperation( |
7860 | 24.3k | code1, true, usePROJAlternativeGridNames, table1); |
7861 | 24.3k | if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, |
7862 | 24.3k | targetCRSAuthName, targetCRSCode)) { |
7863 | 9.59k | continue; |
7864 | 9.59k | } |
7865 | 14.7k | if (!checkPivot(op1->targetCRS())) { |
7866 | 0 | continue; |
7867 | 0 | } |
7868 | 14.7k | auto op2 = |
7869 | 14.7k | d->createFactory(auth_name2) |
7870 | 14.7k | ->createCoordinateOperation( |
7871 | 14.7k | code2, true, usePROJAlternativeGridNames, table2); |
7872 | 14.7k | if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, |
7873 | 14.7k | targetCRSAuthName, targetCRSCode)) { |
7874 | 6.40k | continue; |
7875 | 6.40k | } |
7876 | | |
7877 | 8.33k | listTmp.emplace_back( |
7878 | 8.33k | operation::ConcatenatedOperation::createComputeMetadata( |
7879 | 8.33k | {std::move(op1), op2->inverse()}, false)); |
7880 | 8.33k | } catch (const std::exception &e) { |
7881 | | // Mostly for debugging purposes when using an inconsistent |
7882 | | // database |
7883 | 0 | if (getenv("PROJ_IGNORE_INSTANTIATION_ERRORS")) { |
7884 | 0 | fprintf(stderr, "Ignoring invalid operation: %s\n", e.what()); |
7885 | 0 | } else { |
7886 | 0 | throw; |
7887 | 0 | } |
7888 | 0 | } |
7889 | 24.3k | } |
7890 | | |
7891 | | // Case (intermediate->source) and (intermediate->target) |
7892 | 18.7k | sql = sqlProlog + |
7893 | 18.7k | "ON v1.source_crs_auth_name = v2.source_crs_auth_name " |
7894 | 18.7k | "AND v1.source_crs_code = v2.source_crs_code " + |
7895 | 18.7k | joinArea + |
7896 | 18.7k | "WHERE v1.target_crs_auth_name = ? AND v1.target_crs_code = ? " |
7897 | 18.7k | "AND v2.target_crs_auth_name = ? AND v2.target_crs_code = ? "; |
7898 | 18.7k | if (allowedIntermediateObjectType == ObjectType::GEOGRAPHIC_CRS) { |
7899 | 12.8k | if (!minDate.empty()) { |
7900 | 1.14k | criterionOnIntermediateCRS = |
7901 | 1.14k | "AND EXISTS(SELECT 1 FROM geodetic_crs x " |
7902 | 1.14k | "JOIN geodetic_datum y " |
7903 | 1.14k | "ON " |
7904 | 1.14k | "y.auth_name = x.datum_auth_name AND " |
7905 | 1.14k | "y.code = x.datum_code " |
7906 | 1.14k | "WHERE " |
7907 | 1.14k | "x.auth_name = v1.source_crs_auth_name AND " |
7908 | 1.14k | "x.code = v1.source_crs_code AND " |
7909 | 1.14k | "x.type IN ('geographic 2D', 'geographic 3D') AND " |
7910 | 1.14k | "(y.publication_date IS NULL OR " |
7911 | 1.14k | "(y.publication_date >= '" + |
7912 | 1.14k | minDate + "'))) "; |
7913 | 11.6k | } else { |
7914 | 11.6k | criterionOnIntermediateCRS = |
7915 | 11.6k | "AND EXISTS(SELECT 1 FROM geodetic_crs x WHERE " |
7916 | 11.6k | "x.auth_name = v1.source_crs_auth_name AND " |
7917 | 11.6k | "x.code = v1.source_crs_code AND " |
7918 | 11.6k | "x.type IN ('geographic 2D', 'geographic 3D')) "; |
7919 | 11.6k | } |
7920 | 12.8k | sql += criterionOnIntermediateCRS; |
7921 | 12.8k | } |
7922 | 18.7k | intermediateWhere = buildIntermediateWhere("source", "source"); |
7923 | 18.7k | res = d->run(sql + additionalWhere + intermediateWhere + orderBy, params); |
7924 | 18.7k | if (discardSuperseded) { |
7925 | 18.7k | res = filterOutSuperseded(std::move(res)); |
7926 | 18.7k | } |
7927 | 18.7k | for (const auto &row : res) { |
7928 | 2.63k | const auto &table1 = row[0]; |
7929 | 2.63k | const auto &auth_name1 = row[1]; |
7930 | 2.63k | const auto &code1 = row[2]; |
7931 | | // const auto &accuracy1 = row[3]; |
7932 | 2.63k | const auto &table2 = row[4]; |
7933 | 2.63k | const auto &auth_name2 = row[5]; |
7934 | 2.63k | const auto &code2 = row[6]; |
7935 | | // const auto &accuracy2 = row[7]; |
7936 | 2.63k | try { |
7937 | 2.63k | auto op1 = |
7938 | 2.63k | d->createFactory(auth_name1) |
7939 | 2.63k | ->createCoordinateOperation( |
7940 | 2.63k | code1, true, usePROJAlternativeGridNames, table1); |
7941 | 2.63k | if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, |
7942 | 2.63k | targetCRSAuthName, targetCRSCode)) { |
7943 | 3 | continue; |
7944 | 3 | } |
7945 | 2.63k | if (!checkPivot(op1->sourceCRS())) { |
7946 | 17 | continue; |
7947 | 17 | } |
7948 | 2.61k | auto op2 = |
7949 | 2.61k | d->createFactory(auth_name2) |
7950 | 2.61k | ->createCoordinateOperation( |
7951 | 2.61k | code2, true, usePROJAlternativeGridNames, table2); |
7952 | 2.61k | if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, |
7953 | 2.61k | targetCRSAuthName, targetCRSCode)) { |
7954 | 192 | continue; |
7955 | 192 | } |
7956 | | |
7957 | 2.42k | listTmp.emplace_back( |
7958 | 2.42k | operation::ConcatenatedOperation::createComputeMetadata( |
7959 | 2.42k | {op1->inverse(), std::move(op2)}, false)); |
7960 | 2.42k | } catch (const std::exception &e) { |
7961 | | // Mostly for debugging purposes when using an inconsistent |
7962 | | // database |
7963 | 0 | if (getenv("PROJ_IGNORE_INSTANTIATION_ERRORS")) { |
7964 | 0 | fprintf(stderr, "Ignoring invalid operation: %s\n", e.what()); |
7965 | 0 | } else { |
7966 | 0 | throw; |
7967 | 0 | } |
7968 | 0 | } |
7969 | 2.63k | } |
7970 | | |
7971 | | // Case (intermediate->source) and (target->intermediate) |
7972 | 18.7k | sql = sqlProlog + |
7973 | 18.7k | "ON v1.source_crs_auth_name = v2.target_crs_auth_name " |
7974 | 18.7k | "AND v1.source_crs_code = v2.target_crs_code " + |
7975 | 18.7k | joinArea + |
7976 | 18.7k | "WHERE v1.target_crs_auth_name = ? AND v1.target_crs_code = ? " |
7977 | 18.7k | "AND v2.source_crs_auth_name = ? AND v2.source_crs_code = ? "; |
7978 | 18.7k | if (allowedIntermediateObjectType == ObjectType::GEOGRAPHIC_CRS) { |
7979 | 12.8k | sql += criterionOnIntermediateCRS; |
7980 | 12.8k | } |
7981 | 18.7k | intermediateWhere = buildIntermediateWhere("source", "target"); |
7982 | 18.7k | res = d->run(sql + additionalWhere + intermediateWhere + orderBy, params); |
7983 | 18.7k | if (discardSuperseded) { |
7984 | 18.7k | res = filterOutSuperseded(std::move(res)); |
7985 | 18.7k | } |
7986 | 18.7k | for (const auto &row : res) { |
7987 | 424 | const auto &table1 = row[0]; |
7988 | 424 | const auto &auth_name1 = row[1]; |
7989 | 424 | const auto &code1 = row[2]; |
7990 | | // const auto &accuracy1 = row[3]; |
7991 | 424 | const auto &table2 = row[4]; |
7992 | 424 | const auto &auth_name2 = row[5]; |
7993 | 424 | const auto &code2 = row[6]; |
7994 | | // const auto &accuracy2 = row[7]; |
7995 | 424 | try { |
7996 | 424 | auto op1 = |
7997 | 424 | d->createFactory(auth_name1) |
7998 | 424 | ->createCoordinateOperation( |
7999 | 424 | code1, true, usePROJAlternativeGridNames, table1); |
8000 | 424 | if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, |
8001 | 424 | targetCRSAuthName, targetCRSCode)) { |
8002 | 0 | continue; |
8003 | 0 | } |
8004 | 424 | if (!checkPivot(op1->sourceCRS())) { |
8005 | 0 | continue; |
8006 | 0 | } |
8007 | 424 | auto op2 = |
8008 | 424 | d->createFactory(auth_name2) |
8009 | 424 | ->createCoordinateOperation( |
8010 | 424 | code2, true, usePROJAlternativeGridNames, table2); |
8011 | 424 | if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, |
8012 | 424 | targetCRSAuthName, targetCRSCode)) { |
8013 | 0 | continue; |
8014 | 0 | } |
8015 | | |
8016 | 424 | listTmp.emplace_back( |
8017 | 424 | operation::ConcatenatedOperation::createComputeMetadata( |
8018 | 424 | {op1->inverse(), op2->inverse()}, false)); |
8019 | 424 | } catch (const std::exception &e) { |
8020 | | // Mostly for debugging purposes when using an inconsistent |
8021 | | // database |
8022 | 0 | if (getenv("PROJ_IGNORE_INSTANTIATION_ERRORS")) { |
8023 | 0 | fprintf(stderr, "Ignoring invalid operation: %s\n", e.what()); |
8024 | 0 | } else { |
8025 | 0 | throw; |
8026 | 0 | } |
8027 | 0 | } |
8028 | 424 | } |
8029 | | |
8030 | 18.7k | std::vector<operation::CoordinateOperationNNPtr> list; |
8031 | 18.7k | for (const auto &op : listTmp) { |
8032 | 11.4k | if (!discardIfMissingGrid || |
8033 | 11.4k | !d->rejectOpDueToMissingGrid(op, considerKnownGridsAsAvailable)) { |
8034 | 1.27k | list.emplace_back(op); |
8035 | 1.27k | } |
8036 | 11.4k | } |
8037 | | |
8038 | 18.7k | return list; |
8039 | 18.7k | } |
8040 | | |
8041 | | // --------------------------------------------------------------------------- |
8042 | | |
8043 | | //! @cond Doxygen_Suppress |
8044 | | |
8045 | | struct TrfmInfo { |
8046 | | std::string situation{}; |
8047 | | std::string table_name{}; |
8048 | | std::string auth_name{}; |
8049 | | std::string code{}; |
8050 | | std::string name{}; |
8051 | | double west = 0; |
8052 | | double south = 0; |
8053 | | double east = 0; |
8054 | | double north = 0; |
8055 | | }; |
8056 | | |
8057 | | // --------------------------------------------------------------------------- |
8058 | | |
8059 | | std::vector<operation::CoordinateOperationNNPtr> |
8060 | | AuthorityFactory::createBetweenGeodeticCRSWithDatumBasedIntermediates( |
8061 | | const crs::CRSNNPtr &sourceCRS, const std::string &sourceCRSAuthName, |
8062 | | const std::string &sourceCRSCode, const crs::CRSNNPtr &targetCRS, |
8063 | | const std::string &targetCRSAuthName, const std::string &targetCRSCode, |
8064 | | bool usePROJAlternativeGridNames, bool discardIfMissingGrid, |
8065 | | bool considerKnownGridsAsAvailable, bool discardSuperseded, |
8066 | | const std::vector<std::string> &allowedAuthorities, |
8067 | | const metadata::ExtentPtr &intersectingExtent1, |
8068 | 558 | const metadata::ExtentPtr &intersectingExtent2) const { |
8069 | | |
8070 | 558 | std::vector<operation::CoordinateOperationNNPtr> listTmp; |
8071 | | |
8072 | 558 | if (sourceCRSAuthName == targetCRSAuthName && |
8073 | 558 | sourceCRSCode == targetCRSCode) { |
8074 | 0 | return listTmp; |
8075 | 0 | } |
8076 | 558 | const auto sourceGeodCRS = |
8077 | 558 | dynamic_cast<crs::GeodeticCRS *>(sourceCRS.get()); |
8078 | 558 | const auto targetGeodCRS = |
8079 | 558 | dynamic_cast<crs::GeodeticCRS *>(targetCRS.get()); |
8080 | 558 | if (!sourceGeodCRS || !targetGeodCRS) { |
8081 | 0 | return listTmp; |
8082 | 0 | } |
8083 | | |
8084 | 558 | const bool NAD83_CSRS_to_NAD83_CSRS = |
8085 | 558 | starts_with(sourceGeodCRS->nameStr(), "NAD83(CSRS)") && |
8086 | 558 | starts_with(targetGeodCRS->nameStr(), "NAD83(CSRS)"); |
8087 | | |
8088 | 558 | const auto GetListCRSWithSameDatum = [this](const crs::GeodeticCRS *crs, |
8089 | 558 | const std::string &crsAuthName, |
8090 | 1.11k | const std::string &crsCode) { |
8091 | | // Find all geodetic CRS that share the same datum as the CRS |
8092 | 1.11k | SQLResultSet listCRS; |
8093 | | |
8094 | 1.11k | const common::IdentifiedObject *obj = crs->datum().get(); |
8095 | 1.11k | if (obj == nullptr) |
8096 | 322 | obj = crs->datumEnsemble().get(); |
8097 | 1.11k | assert(obj != nullptr); |
8098 | 1.11k | const auto &ids = obj->identifiers(); |
8099 | 1.11k | std::string datumAuthName; |
8100 | 1.11k | std::string datumCode; |
8101 | 1.11k | if (!ids.empty()) { |
8102 | 1.11k | const auto &id = ids.front(); |
8103 | 1.11k | datumAuthName = *(id->codeSpace()); |
8104 | 1.11k | datumCode = id->code(); |
8105 | 1.11k | } else { |
8106 | 0 | const auto res = |
8107 | 0 | d->run("SELECT datum_auth_name, datum_code FROM " |
8108 | 0 | "geodetic_crs WHERE auth_name = ? AND code = ?", |
8109 | 0 | {crsAuthName, crsCode}); |
8110 | 0 | if (res.size() != 1) { |
8111 | 0 | return listCRS; |
8112 | 0 | } |
8113 | 0 | const auto &row = res.front(); |
8114 | 0 | datumAuthName = row[0]; |
8115 | 0 | datumCode = row[1]; |
8116 | 0 | } |
8117 | | |
8118 | 1.11k | listCRS = |
8119 | 1.11k | d->run("SELECT auth_name, code FROM geodetic_crs WHERE " |
8120 | 1.11k | "datum_auth_name = ? AND datum_code = ? AND deprecated = 0", |
8121 | 1.11k | {datumAuthName, datumCode}); |
8122 | 1.11k | if (listCRS.empty()) { |
8123 | | // Can happen if the CRS is deprecated |
8124 | 1 | listCRS.emplace_back(SQLRow{crsAuthName, crsCode}); |
8125 | 1 | } |
8126 | 1.11k | return listCRS; |
8127 | 1.11k | }; |
8128 | | |
8129 | 558 | const SQLResultSet listSourceCRS = GetListCRSWithSameDatum( |
8130 | 558 | sourceGeodCRS, sourceCRSAuthName, sourceCRSCode); |
8131 | 558 | const SQLResultSet listTargetCRS = GetListCRSWithSameDatum( |
8132 | 558 | targetGeodCRS, targetCRSAuthName, targetCRSCode); |
8133 | 558 | if (listSourceCRS.empty() || listTargetCRS.empty()) { |
8134 | | // would happen only if we had CRS objects in the database without a |
8135 | | // link to a datum. |
8136 | 0 | return listTmp; |
8137 | 0 | } |
8138 | | |
8139 | 558 | ListOfParams params; |
8140 | 558 | const auto BuildSQLPart = [this, NAD83_CSRS_to_NAD83_CSRS, |
8141 | 558 | &allowedAuthorities, ¶ms, &listSourceCRS, |
8142 | 558 | &listTargetCRS](bool isSourceCRS, |
8143 | 2.23k | bool selectOnTarget) { |
8144 | 2.23k | std::string situation; |
8145 | 2.23k | if (isSourceCRS) |
8146 | 1.11k | situation = "src"; |
8147 | 1.11k | else |
8148 | 1.11k | situation = "tgt"; |
8149 | 2.23k | if (selectOnTarget) |
8150 | 1.11k | situation += "_is_tgt"; |
8151 | 1.11k | else |
8152 | 1.11k | situation += "_is_src"; |
8153 | 2.23k | const std::string prefix1(selectOnTarget ? "source" : "target"); |
8154 | 2.23k | const std::string prefix2(selectOnTarget ? "target" : "source"); |
8155 | 2.23k | std::string sql("SELECT '"); |
8156 | 2.23k | sql += situation; |
8157 | 2.23k | sql += "' as situation, v.table_name, v.auth_name, " |
8158 | 2.23k | "v.code, v.name, gcrs.datum_auth_name, gcrs.datum_code, " |
8159 | 2.23k | "a.west_lon, a.south_lat, a.east_lon, a.north_lat " |
8160 | 2.23k | "FROM coordinate_operation_view v " |
8161 | 2.23k | "JOIN geodetic_crs gcrs on gcrs.auth_name = "; |
8162 | 2.23k | sql += prefix1; |
8163 | 2.23k | sql += "_crs_auth_name AND gcrs.code = "; |
8164 | 2.23k | sql += prefix1; |
8165 | 2.23k | sql += "_crs_code " |
8166 | | |
8167 | 2.23k | "LEFT JOIN usage u ON " |
8168 | 2.23k | "u.object_table_name = v.table_name AND " |
8169 | 2.23k | "u.object_auth_name = v.auth_name AND " |
8170 | 2.23k | "u.object_code = v.code " |
8171 | 2.23k | "LEFT JOIN extent a " |
8172 | 2.23k | "ON a.auth_name = u.extent_auth_name AND " |
8173 | 2.23k | "a.code = u.extent_code " |
8174 | 2.23k | "WHERE v.deprecated = 0 AND ("; |
8175 | | |
8176 | 2.23k | std::string cond; |
8177 | | |
8178 | 2.23k | const auto &list = isSourceCRS ? listSourceCRS : listTargetCRS; |
8179 | 13.2k | for (const auto &row : list) { |
8180 | 13.2k | if (!cond.empty()) |
8181 | 11.0k | cond += " OR "; |
8182 | 13.2k | cond += '('; |
8183 | 13.2k | cond += prefix2; |
8184 | 13.2k | cond += "_crs_auth_name = ? AND "; |
8185 | 13.2k | cond += prefix2; |
8186 | 13.2k | cond += "_crs_code = ?)"; |
8187 | 13.2k | params.emplace_back(row[0]); |
8188 | 13.2k | params.emplace_back(row[1]); |
8189 | 13.2k | } |
8190 | | |
8191 | 2.23k | sql += cond; |
8192 | 2.23k | sql += ") "; |
8193 | | |
8194 | 2.23k | if (!allowedAuthorities.empty()) { |
8195 | 2.13k | sql += "AND v.auth_name IN ("; |
8196 | 8.54k | for (size_t i = 0; i < allowedAuthorities.size(); i++) { |
8197 | 6.40k | if (i > 0) |
8198 | 4.27k | sql += ','; |
8199 | 6.40k | sql += '?'; |
8200 | 6.40k | } |
8201 | 2.13k | sql += ") "; |
8202 | 6.40k | for (const auto &allowedAuthority : allowedAuthorities) { |
8203 | 6.40k | params.emplace_back(allowedAuthority); |
8204 | 6.40k | } |
8205 | 2.13k | } |
8206 | 2.23k | if (d->hasAuthorityRestriction()) { |
8207 | 0 | sql += "AND v.auth_name = ? "; |
8208 | 0 | params.emplace_back(d->authority()); |
8209 | 0 | } |
8210 | 2.23k | if (NAD83_CSRS_to_NAD83_CSRS) { |
8211 | | // Make sure that NAD83(CSRS)[x] to NAD83(CSRS)[y) doesn't go |
8212 | | // through NAD83 generic. Cf |
8213 | | // https://github.com/OSGeo/PROJ/issues/4464 |
8214 | 0 | sql += "AND gcrs.name NOT IN ('NAD83', 'WGS 84') "; |
8215 | 0 | } |
8216 | | |
8217 | 2.23k | return sql; |
8218 | 2.23k | }; |
8219 | | |
8220 | 558 | std::string sql(BuildSQLPart(true, true)); |
8221 | 558 | sql += "UNION ALL "; |
8222 | 558 | sql += BuildSQLPart(false, true); |
8223 | 558 | sql += "UNION ALL "; |
8224 | 558 | sql += BuildSQLPart(true, false); |
8225 | 558 | sql += "UNION ALL "; |
8226 | 558 | sql += BuildSQLPart(false, false); |
8227 | | // fprintf(stderr, "sql : %s\n", sql.c_str()); |
8228 | | |
8229 | | // Find all operations that have as source/target CRS a CRS that |
8230 | | // share the same datum as the source or targetCRS |
8231 | 558 | const auto res = d->run(sql, params); |
8232 | | |
8233 | 558 | std::map<std::string, std::list<TrfmInfo>> mapIntermDatumOfSource; |
8234 | 558 | std::map<std::string, std::list<TrfmInfo>> mapIntermDatumOfTarget; |
8235 | | |
8236 | 438k | for (const auto &row : res) { |
8237 | 438k | try { |
8238 | 438k | TrfmInfo trfm; |
8239 | 438k | trfm.situation = row[0]; |
8240 | 438k | trfm.table_name = row[1]; |
8241 | 438k | trfm.auth_name = row[2]; |
8242 | 438k | trfm.code = row[3]; |
8243 | 438k | trfm.name = row[4]; |
8244 | 438k | const auto &datum_auth_name = row[5]; |
8245 | 438k | const auto &datum_code = row[6]; |
8246 | 438k | trfm.west = c_locale_stod(row[7]); |
8247 | 438k | trfm.south = c_locale_stod(row[8]); |
8248 | 438k | trfm.east = c_locale_stod(row[9]); |
8249 | 438k | trfm.north = c_locale_stod(row[10]); |
8250 | 438k | const std::string key = |
8251 | 438k | std::string(datum_auth_name).append(":").append(datum_code); |
8252 | 438k | if (trfm.situation == "src_is_tgt" || |
8253 | 438k | trfm.situation == "src_is_src") |
8254 | 412k | mapIntermDatumOfSource[key].emplace_back(std::move(trfm)); |
8255 | 26.3k | else |
8256 | 26.3k | mapIntermDatumOfTarget[key].emplace_back(std::move(trfm)); |
8257 | 438k | } catch (const std::exception &) { |
8258 | 0 | } |
8259 | 438k | } |
8260 | | |
8261 | 558 | std::vector<const metadata::GeographicBoundingBox *> extraBbox; |
8262 | 1.11k | for (const auto &extent : {intersectingExtent1, intersectingExtent2}) { |
8263 | 1.11k | if (extent) { |
8264 | 634 | const auto &geogExtent = extent->geographicElements(); |
8265 | 634 | if (geogExtent.size() == 1) { |
8266 | 634 | auto bbox = |
8267 | 634 | dynamic_cast<const metadata::GeographicBoundingBox *>( |
8268 | 634 | geogExtent[0].get()); |
8269 | 634 | if (bbox) { |
8270 | 634 | const double south_lat = bbox->southBoundLatitude(); |
8271 | 634 | const double west_lon = bbox->westBoundLongitude(); |
8272 | 634 | const double north_lat = bbox->northBoundLatitude(); |
8273 | 634 | const double east_lon = bbox->eastBoundLongitude(); |
8274 | 634 | if (south_lat != -90.0 || west_lon != -180.0 || |
8275 | 634 | north_lat != 90.0 || east_lon != 180.0) { |
8276 | 329 | extraBbox.emplace_back(bbox); |
8277 | 329 | } |
8278 | 634 | } |
8279 | 634 | } |
8280 | 634 | } |
8281 | 1.11k | } |
8282 | | |
8283 | 558 | std::map<std::string, operation::CoordinateOperationPtr> oMapTrfmKeyToOp; |
8284 | 558 | std::list<std::pair<TrfmInfo, TrfmInfo>> candidates; |
8285 | 558 | std::map<std::string, TrfmInfo> setOfTransformations; |
8286 | | |
8287 | 33.3k | const auto MakeKey = [](const TrfmInfo &trfm) { |
8288 | 33.3k | return trfm.table_name + '_' + trfm.auth_name + '_' + trfm.code; |
8289 | 33.3k | }; |
8290 | | |
8291 | | // Find transformations that share a pivot datum, and do bbox filtering |
8292 | 156k | for (const auto &kvSource : mapIntermDatumOfSource) { |
8293 | 156k | const auto &listTrmfSource = kvSource.second; |
8294 | 156k | auto iter = mapIntermDatumOfTarget.find(kvSource.first); |
8295 | 156k | if (iter == mapIntermDatumOfTarget.end()) |
8296 | 154k | continue; |
8297 | | |
8298 | 2.11k | const auto &listTrfmTarget = iter->second; |
8299 | 14.9k | for (const auto &trfmSource : listTrmfSource) { |
8300 | 14.9k | auto bbox1 = metadata::GeographicBoundingBox::create( |
8301 | 14.9k | trfmSource.west, trfmSource.south, trfmSource.east, |
8302 | 14.9k | trfmSource.north); |
8303 | 14.9k | bool okBbox1 = true; |
8304 | 14.9k | for (const auto bbox : extraBbox) |
8305 | 8.88k | okBbox1 &= bbox->intersects(bbox1); |
8306 | 14.9k | if (!okBbox1) |
8307 | 4.57k | continue; |
8308 | | |
8309 | 10.4k | const std::string key1 = MakeKey(trfmSource); |
8310 | | |
8311 | 23.2k | for (const auto &trfmTarget : listTrfmTarget) { |
8312 | 23.2k | auto bbox2 = metadata::GeographicBoundingBox::create( |
8313 | 23.2k | trfmTarget.west, trfmTarget.south, trfmTarget.east, |
8314 | 23.2k | trfmTarget.north); |
8315 | 23.2k | if (!bbox1->intersects(bbox2)) |
8316 | 14.8k | continue; |
8317 | 8.37k | bool okBbox2 = true; |
8318 | 8.37k | for (const auto bbox : extraBbox) |
8319 | 3.74k | okBbox2 &= bbox->intersects(bbox2); |
8320 | 8.37k | if (!okBbox2) |
8321 | 624 | continue; |
8322 | | |
8323 | 7.74k | operation::CoordinateOperationPtr op1; |
8324 | 7.74k | if (oMapTrfmKeyToOp.find(key1) == oMapTrfmKeyToOp.end()) { |
8325 | 5.34k | auto op1NN = d->createFactory(trfmSource.auth_name) |
8326 | 5.34k | ->createCoordinateOperation( |
8327 | 5.34k | trfmSource.code, true, |
8328 | 5.34k | usePROJAlternativeGridNames, |
8329 | 5.34k | trfmSource.table_name); |
8330 | 5.34k | op1 = op1NN.as_nullable(); |
8331 | 5.34k | if (useIrrelevantPivot(op1NN, sourceCRSAuthName, |
8332 | 5.34k | sourceCRSCode, targetCRSAuthName, |
8333 | 5.34k | targetCRSCode)) { |
8334 | 18 | op1.reset(); |
8335 | 18 | } |
8336 | 5.34k | oMapTrfmKeyToOp[key1] = op1; |
8337 | 5.34k | } else { |
8338 | 2.40k | op1 = oMapTrfmKeyToOp[key1]; |
8339 | 2.40k | } |
8340 | 7.74k | if (op1 == nullptr) |
8341 | 18 | continue; |
8342 | | |
8343 | 7.72k | const std::string key2 = MakeKey(trfmTarget); |
8344 | | |
8345 | 7.72k | operation::CoordinateOperationPtr op2; |
8346 | 7.72k | if (oMapTrfmKeyToOp.find(key2) == oMapTrfmKeyToOp.end()) { |
8347 | 3.13k | auto op2NN = d->createFactory(trfmTarget.auth_name) |
8348 | 3.13k | ->createCoordinateOperation( |
8349 | 3.13k | trfmTarget.code, true, |
8350 | 3.13k | usePROJAlternativeGridNames, |
8351 | 3.13k | trfmTarget.table_name); |
8352 | 3.13k | op2 = op2NN.as_nullable(); |
8353 | 3.13k | if (useIrrelevantPivot(op2NN, sourceCRSAuthName, |
8354 | 3.13k | sourceCRSCode, targetCRSAuthName, |
8355 | 3.13k | targetCRSCode)) { |
8356 | 13 | op2.reset(); |
8357 | 13 | } |
8358 | 3.13k | oMapTrfmKeyToOp[key2] = op2; |
8359 | 4.59k | } else { |
8360 | 4.59k | op2 = oMapTrfmKeyToOp[key2]; |
8361 | 4.59k | } |
8362 | 7.72k | if (op2 == nullptr) |
8363 | 113 | continue; |
8364 | | |
8365 | 7.61k | candidates.emplace_back( |
8366 | 7.61k | std::pair<TrfmInfo, TrfmInfo>(trfmSource, trfmTarget)); |
8367 | 7.61k | setOfTransformations[key1] = trfmSource; |
8368 | 7.61k | setOfTransformations[key2] = trfmTarget; |
8369 | 7.61k | } |
8370 | 10.4k | } |
8371 | 2.11k | } |
8372 | | |
8373 | 558 | std::set<std::string> setSuperseded; |
8374 | 558 | if (discardSuperseded && !setOfTransformations.empty()) { |
8375 | 330 | std::string findSupersededSql( |
8376 | 330 | "SELECT superseded_table_name, " |
8377 | 330 | "superseded_auth_name, superseded_code, " |
8378 | 330 | "replacement_auth_name, replacement_code " |
8379 | 330 | "FROM supersession WHERE same_source_target_crs = 1 AND ("); |
8380 | 330 | bool findSupersededFirstWhere = true; |
8381 | 330 | ListOfParams findSupersededParams; |
8382 | | |
8383 | 330 | const auto keyMapSupersession = [](const std::string &table_name, |
8384 | 330 | const std::string &auth_name, |
8385 | 9.08k | const std::string &code) { |
8386 | 9.08k | return table_name + auth_name + code; |
8387 | 9.08k | }; |
8388 | | |
8389 | 330 | std::set<std::pair<std::string, std::string>> setTransf; |
8390 | 8.34k | for (const auto &kv : setOfTransformations) { |
8391 | 8.34k | const auto &table = kv.second.table_name; |
8392 | 8.34k | const auto &auth_name = kv.second.auth_name; |
8393 | 8.34k | const auto &code = kv.second.code; |
8394 | | |
8395 | 8.34k | if (!findSupersededFirstWhere) |
8396 | 8.01k | findSupersededSql += " OR "; |
8397 | 8.34k | findSupersededFirstWhere = false; |
8398 | 8.34k | findSupersededSql += |
8399 | 8.34k | "(superseded_table_name = ? AND replacement_table_name = " |
8400 | 8.34k | "superseded_table_name AND superseded_auth_name = ? AND " |
8401 | 8.34k | "superseded_code = ?)"; |
8402 | 8.34k | findSupersededParams.push_back(table); |
8403 | 8.34k | findSupersededParams.push_back(auth_name); |
8404 | 8.34k | findSupersededParams.push_back(code); |
8405 | | |
8406 | 8.34k | setTransf.insert( |
8407 | 8.34k | std::pair<std::string, std::string>(auth_name, code)); |
8408 | 8.34k | } |
8409 | 330 | findSupersededSql += ')'; |
8410 | | |
8411 | 330 | std::map<std::string, std::vector<std::pair<std::string, std::string>>> |
8412 | 330 | mapSupersession; |
8413 | | |
8414 | 330 | const auto resSuperseded = |
8415 | 330 | d->run(findSupersededSql, findSupersededParams); |
8416 | 742 | for (const auto &row : resSuperseded) { |
8417 | 742 | const auto &superseded_table_name = row[0]; |
8418 | 742 | const auto &superseded_auth_name = row[1]; |
8419 | 742 | const auto &superseded_code = row[2]; |
8420 | 742 | const auto &replacement_auth_name = row[3]; |
8421 | 742 | const auto &replacement_code = row[4]; |
8422 | 742 | mapSupersession[keyMapSupersession(superseded_table_name, |
8423 | 742 | superseded_auth_name, |
8424 | 742 | superseded_code)] |
8425 | 742 | .push_back(std::pair<std::string, std::string>( |
8426 | 742 | replacement_auth_name, replacement_code)); |
8427 | 742 | } |
8428 | | |
8429 | 8.34k | for (const auto &kv : setOfTransformations) { |
8430 | 8.34k | const auto &table = kv.second.table_name; |
8431 | 8.34k | const auto &auth_name = kv.second.auth_name; |
8432 | 8.34k | const auto &code = kv.second.code; |
8433 | | |
8434 | 8.34k | const auto iter = mapSupersession.find( |
8435 | 8.34k | keyMapSupersession(table, auth_name, code)); |
8436 | 8.34k | if (iter != mapSupersession.end()) { |
8437 | 742 | bool foundReplacement = false; |
8438 | 742 | for (const auto &replacement : iter->second) { |
8439 | 742 | const auto &replacement_auth_name = replacement.first; |
8440 | 742 | const auto &replacement_code = replacement.second; |
8441 | 742 | if (setTransf.find(std::pair<std::string, std::string>( |
8442 | 742 | replacement_auth_name, replacement_code)) != |
8443 | 742 | setTransf.end()) { |
8444 | | // Skip transformations that are superseded by others |
8445 | | // that got |
8446 | | // returned in the result set. |
8447 | 742 | foundReplacement = true; |
8448 | 742 | break; |
8449 | 742 | } |
8450 | 742 | } |
8451 | 742 | if (foundReplacement) { |
8452 | 742 | setSuperseded.insert(kv.first); |
8453 | 742 | } |
8454 | 742 | } |
8455 | 8.34k | } |
8456 | 330 | } |
8457 | | |
8458 | 558 | std::string sourceDatumPubDate; |
8459 | 558 | const auto sourceDatum = sourceGeodCRS->datumNonNull(d->context()); |
8460 | 558 | if (sourceDatum->publicationDate().has_value()) { |
8461 | 184 | sourceDatumPubDate = sourceDatum->publicationDate()->toString(); |
8462 | 184 | } |
8463 | | |
8464 | 558 | std::string targetDatumPubDate; |
8465 | 558 | const auto targetDatum = targetGeodCRS->datumNonNull(d->context()); |
8466 | 558 | if (targetDatum->publicationDate().has_value()) { |
8467 | 501 | targetDatumPubDate = targetDatum->publicationDate()->toString(); |
8468 | 501 | } |
8469 | | |
8470 | 558 | const std::string mostAncientDatumPubDate = |
8471 | 558 | (!targetDatumPubDate.empty() && |
8472 | 558 | (sourceDatumPubDate.empty() || |
8473 | 501 | targetDatumPubDate < sourceDatumPubDate)) |
8474 | 558 | ? targetDatumPubDate |
8475 | 558 | : sourceDatumPubDate; |
8476 | | |
8477 | 558 | auto opFactory = operation::CoordinateOperationFactory::create(); |
8478 | 7.61k | for (const auto &pair : candidates) { |
8479 | 7.61k | const auto &trfmSource = pair.first; |
8480 | 7.61k | const auto &trfmTarget = pair.second; |
8481 | 7.61k | const std::string key1 = MakeKey(trfmSource); |
8482 | 7.61k | const std::string key2 = MakeKey(trfmTarget); |
8483 | 7.61k | if (setSuperseded.find(key1) != setSuperseded.end() || |
8484 | 7.61k | setSuperseded.find(key2) != setSuperseded.end()) { |
8485 | 817 | continue; |
8486 | 817 | } |
8487 | 6.79k | auto op1 = oMapTrfmKeyToOp[key1]; |
8488 | 6.79k | auto op2 = oMapTrfmKeyToOp[key2]; |
8489 | 6.79k | auto op1NN = NN_NO_CHECK(op1); |
8490 | 6.79k | auto op2NN = NN_NO_CHECK(op2); |
8491 | 6.79k | if (trfmSource.situation == "src_is_tgt") |
8492 | 5.97k | op1NN = op1NN->inverse(); |
8493 | 6.79k | if (trfmTarget.situation == "tgt_is_src") |
8494 | 2.63k | op2NN = op2NN->inverse(); |
8495 | | |
8496 | 6.79k | const auto &op1Source = op1NN->sourceCRS(); |
8497 | 6.79k | const auto &op1Target = op1NN->targetCRS(); |
8498 | 6.79k | const auto &op2Source = op2NN->sourceCRS(); |
8499 | 6.79k | const auto &op2Target = op2NN->targetCRS(); |
8500 | 6.79k | if (!(op1Source && op1Target && op2Source && op2Target)) { |
8501 | 0 | continue; |
8502 | 0 | } |
8503 | | |
8504 | | // Skip operations using a datum that is older than the source or |
8505 | | // target datum (e.g to avoid ED50 to WGS84 to go through NTF) |
8506 | 6.79k | if (!mostAncientDatumPubDate.empty()) { |
8507 | 5.59k | const auto isOlderCRS = [this, &mostAncientDatumPubDate]( |
8508 | 22.3k | const crs::CRSPtr &crs) { |
8509 | 22.3k | const auto geogCRS = |
8510 | 22.3k | dynamic_cast<const crs::GeodeticCRS *>(crs.get()); |
8511 | 22.3k | if (geogCRS) { |
8512 | 22.3k | const auto datum = geogCRS->datumNonNull(d->context()); |
8513 | | // Hum, theoretically we'd want to check |
8514 | | // datum->publicationDate()->toString() < |
8515 | | // mostAncientDatumPubDate but that would exclude doing |
8516 | | // IG05/12 Intermediate CRS to ITRF2014 through ITRF2008, |
8517 | | // since IG05/12 Intermediate CRS has been published later |
8518 | | // than ITRF2008. So use a cut of date for ancient vs |
8519 | | // "modern" era. |
8520 | 22.3k | constexpr const char *CUT_OFF_DATE = "1900-01-01"; |
8521 | 22.3k | if (datum->publicationDate().has_value() && |
8522 | 22.3k | datum->publicationDate()->toString() < CUT_OFF_DATE && |
8523 | 22.3k | mostAncientDatumPubDate > CUT_OFF_DATE) { |
8524 | 0 | return true; |
8525 | 0 | } |
8526 | 22.3k | } |
8527 | 22.3k | return false; |
8528 | 22.3k | }; |
8529 | | |
8530 | 5.59k | if (isOlderCRS(op1Source) || isOlderCRS(op1Target) || |
8531 | 5.59k | isOlderCRS(op2Source) || isOlderCRS(op2Target)) |
8532 | 0 | continue; |
8533 | 5.59k | } |
8534 | | |
8535 | 6.79k | std::vector<operation::CoordinateOperationNNPtr> steps; |
8536 | | |
8537 | 6.79k | if (!sourceCRS->isEquivalentTo( |
8538 | 6.79k | op1Source.get(), util::IComparable::Criterion::EQUIVALENT)) { |
8539 | 3.75k | auto opFirst = |
8540 | 3.75k | opFactory->createOperation(sourceCRS, NN_NO_CHECK(op1Source)); |
8541 | 3.75k | assert(opFirst); |
8542 | 3.75k | steps.emplace_back(NN_NO_CHECK(opFirst)); |
8543 | 3.75k | } |
8544 | | |
8545 | 6.79k | steps.emplace_back(op1NN); |
8546 | | |
8547 | 6.79k | if (!op1Target->isEquivalentTo( |
8548 | 6.79k | op2Source.get(), util::IComparable::Criterion::EQUIVALENT)) { |
8549 | 2.42k | auto opMiddle = opFactory->createOperation(NN_NO_CHECK(op1Target), |
8550 | 2.42k | NN_NO_CHECK(op2Source)); |
8551 | 2.42k | assert(opMiddle); |
8552 | 2.42k | steps.emplace_back(NN_NO_CHECK(opMiddle)); |
8553 | 2.42k | } |
8554 | | |
8555 | 6.79k | steps.emplace_back(op2NN); |
8556 | | |
8557 | 6.79k | if (!op2Target->isEquivalentTo( |
8558 | 6.79k | targetCRS.get(), util::IComparable::Criterion::EQUIVALENT)) { |
8559 | 4.52k | auto opLast = |
8560 | 4.52k | opFactory->createOperation(NN_NO_CHECK(op2Target), targetCRS); |
8561 | 4.52k | assert(opLast); |
8562 | 4.52k | steps.emplace_back(NN_NO_CHECK(opLast)); |
8563 | 4.52k | } |
8564 | | |
8565 | 6.79k | listTmp.emplace_back( |
8566 | 6.79k | operation::ConcatenatedOperation::createComputeMetadata(steps, |
8567 | 6.79k | false)); |
8568 | 6.79k | } |
8569 | | |
8570 | 558 | std::vector<operation::CoordinateOperationNNPtr> list; |
8571 | 6.79k | for (const auto &op : listTmp) { |
8572 | 6.79k | if (!discardIfMissingGrid || |
8573 | 6.79k | !d->rejectOpDueToMissingGrid(op, considerKnownGridsAsAvailable)) { |
8574 | 1.58k | list.emplace_back(op); |
8575 | 1.58k | } |
8576 | 6.79k | } |
8577 | | |
8578 | 558 | return list; |
8579 | 558 | } |
8580 | | |
8581 | | //! @endcond |
8582 | | |
8583 | | // --------------------------------------------------------------------------- |
8584 | | |
8585 | | /** \brief Returns the authority name associated to this factory. |
8586 | | * @return name. |
8587 | | */ |
8588 | 129k | const std::string &AuthorityFactory::getAuthority() PROJ_PURE_DEFN { |
8589 | 129k | return d->authority(); |
8590 | 129k | } |
8591 | | |
8592 | | // --------------------------------------------------------------------------- |
8593 | | |
8594 | | /** \brief Returns the set of authority codes of the given object type. |
8595 | | * |
8596 | | * @param type Object type. |
8597 | | * @param allowDeprecated whether we should return deprecated objects as well. |
8598 | | * @return the set of authority codes for spatial reference objects of the given |
8599 | | * type |
8600 | | * @throw FactoryException in case of error. |
8601 | | */ |
8602 | | std::set<std::string> |
8603 | | AuthorityFactory::getAuthorityCodes(const ObjectType &type, |
8604 | 0 | bool allowDeprecated) const { |
8605 | 0 | std::string sql; |
8606 | 0 | switch (type) { |
8607 | 0 | case ObjectType::PRIME_MERIDIAN: |
8608 | 0 | sql = "SELECT code FROM prime_meridian WHERE "; |
8609 | 0 | break; |
8610 | 0 | case ObjectType::ELLIPSOID: |
8611 | 0 | sql = "SELECT code FROM ellipsoid WHERE "; |
8612 | 0 | break; |
8613 | 0 | case ObjectType::DATUM: |
8614 | 0 | sql = "SELECT code FROM object_view WHERE table_name IN " |
8615 | 0 | "('geodetic_datum', 'vertical_datum', 'engineering_datum') AND "; |
8616 | 0 | break; |
8617 | 0 | case ObjectType::GEODETIC_REFERENCE_FRAME: |
8618 | 0 | sql = "SELECT code FROM geodetic_datum WHERE "; |
8619 | 0 | break; |
8620 | 0 | case ObjectType::DYNAMIC_GEODETIC_REFERENCE_FRAME: |
8621 | 0 | sql = "SELECT code FROM geodetic_datum WHERE " |
8622 | 0 | "frame_reference_epoch IS NOT NULL AND "; |
8623 | 0 | break; |
8624 | 0 | case ObjectType::VERTICAL_REFERENCE_FRAME: |
8625 | 0 | sql = "SELECT code FROM vertical_datum WHERE "; |
8626 | 0 | break; |
8627 | 0 | case ObjectType::DYNAMIC_VERTICAL_REFERENCE_FRAME: |
8628 | 0 | sql = "SELECT code FROM vertical_datum WHERE " |
8629 | 0 | "frame_reference_epoch IS NOT NULL AND "; |
8630 | 0 | break; |
8631 | 0 | case ObjectType::ENGINEERING_DATUM: |
8632 | 0 | sql = "SELECT code FROM engineering_datum WHERE "; |
8633 | 0 | break; |
8634 | 0 | case ObjectType::CRS: |
8635 | 0 | sql = "SELECT code FROM crs_view WHERE "; |
8636 | 0 | break; |
8637 | 0 | case ObjectType::GEODETIC_CRS: |
8638 | 0 | sql = "SELECT code FROM geodetic_crs WHERE "; |
8639 | 0 | break; |
8640 | 0 | case ObjectType::GEOCENTRIC_CRS: |
8641 | 0 | sql = "SELECT code FROM geodetic_crs WHERE type " |
8642 | 0 | "= " GEOCENTRIC_SINGLE_QUOTED " AND "; |
8643 | 0 | break; |
8644 | 0 | case ObjectType::GEOGRAPHIC_CRS: |
8645 | 0 | sql = "SELECT code FROM geodetic_crs WHERE type IN " |
8646 | 0 | "(" GEOG_2D_SINGLE_QUOTED "," GEOG_3D_SINGLE_QUOTED ") AND "; |
8647 | 0 | break; |
8648 | 0 | case ObjectType::GEOGRAPHIC_2D_CRS: |
8649 | 0 | sql = |
8650 | 0 | "SELECT code FROM geodetic_crs WHERE type = " GEOG_2D_SINGLE_QUOTED |
8651 | 0 | " AND "; |
8652 | 0 | break; |
8653 | 0 | case ObjectType::GEOGRAPHIC_3D_CRS: |
8654 | 0 | sql = |
8655 | 0 | "SELECT code FROM geodetic_crs WHERE type = " GEOG_3D_SINGLE_QUOTED |
8656 | 0 | " AND "; |
8657 | 0 | break; |
8658 | 0 | case ObjectType::VERTICAL_CRS: |
8659 | 0 | sql = "SELECT code FROM vertical_crs WHERE "; |
8660 | 0 | break; |
8661 | 0 | case ObjectType::PROJECTED_CRS: |
8662 | 0 | sql = "SELECT code FROM projected_crs WHERE "; |
8663 | 0 | break; |
8664 | 0 | case ObjectType::COMPOUND_CRS: |
8665 | 0 | sql = "SELECT code FROM compound_crs WHERE "; |
8666 | 0 | break; |
8667 | 0 | case ObjectType::ENGINEERING_CRS: |
8668 | 0 | sql = "SELECT code FROM engineering_crs WHERE "; |
8669 | 0 | break; |
8670 | 0 | case ObjectType::COORDINATE_OPERATION: |
8671 | 0 | sql = |
8672 | 0 | "SELECT code FROM coordinate_operation_with_conversion_view WHERE "; |
8673 | 0 | break; |
8674 | 0 | case ObjectType::CONVERSION: |
8675 | 0 | sql = "SELECT code FROM conversion WHERE "; |
8676 | 0 | break; |
8677 | 0 | case ObjectType::TRANSFORMATION: |
8678 | 0 | sql = "SELECT code FROM coordinate_operation_view WHERE table_name != " |
8679 | 0 | "'concatenated_operation' AND "; |
8680 | 0 | break; |
8681 | 0 | case ObjectType::CONCATENATED_OPERATION: |
8682 | 0 | sql = "SELECT code FROM concatenated_operation WHERE "; |
8683 | 0 | break; |
8684 | 0 | case ObjectType::DATUM_ENSEMBLE: |
8685 | 0 | sql = "SELECT code FROM object_view WHERE table_name IN " |
8686 | 0 | "('geodetic_datum', 'vertical_datum') AND " |
8687 | 0 | "type = 'ensemble' AND "; |
8688 | 0 | break; |
8689 | 0 | } |
8690 | | |
8691 | 0 | sql += "auth_name = ?"; |
8692 | 0 | if (!allowDeprecated) { |
8693 | 0 | sql += " AND deprecated = 0"; |
8694 | 0 | } |
8695 | |
|
8696 | 0 | auto res = d->run(sql, {d->authority()}); |
8697 | 0 | std::set<std::string> set; |
8698 | 0 | for (const auto &row : res) { |
8699 | 0 | set.insert(row[0]); |
8700 | 0 | } |
8701 | 0 | return set; |
8702 | 0 | } |
8703 | | |
8704 | | // --------------------------------------------------------------------------- |
8705 | | |
8706 | | /** \brief Gets a description of the object corresponding to a code. |
8707 | | * |
8708 | | * \note In case of several objects of different types with the same code, |
8709 | | * one of them will be arbitrarily selected. But if a CRS object is found, it |
8710 | | * will be selected. |
8711 | | * |
8712 | | * @param code Object code allocated by authority. (e.g. "4326") |
8713 | | * @return description. |
8714 | | * @throw NoSuchAuthorityCodeException if there is no matching object. |
8715 | | * @throw FactoryException in case of other errors. |
8716 | | */ |
8717 | | std::string |
8718 | 0 | AuthorityFactory::getDescriptionText(const std::string &code) const { |
8719 | 0 | auto sql = "SELECT name, table_name FROM object_view WHERE auth_name = ? " |
8720 | 0 | "AND code = ? ORDER BY table_name"; |
8721 | 0 | auto sqlRes = d->runWithCodeParam(sql, code); |
8722 | 0 | if (sqlRes.empty()) { |
8723 | 0 | throw NoSuchAuthorityCodeException("object not found", d->authority(), |
8724 | 0 | code); |
8725 | 0 | } |
8726 | 0 | std::string text; |
8727 | 0 | for (const auto &row : sqlRes) { |
8728 | 0 | const auto &tableName = row[1]; |
8729 | 0 | if (tableName == "geodetic_crs" || tableName == "projected_crs" || |
8730 | 0 | tableName == "vertical_crs" || tableName == "compound_crs" || |
8731 | 0 | tableName == "engineering_crs") { |
8732 | 0 | return row[0]; |
8733 | 0 | } else if (text.empty()) { |
8734 | 0 | text = row[0]; |
8735 | 0 | } |
8736 | 0 | } |
8737 | 0 | return text; |
8738 | 0 | } |
8739 | | |
8740 | | // --------------------------------------------------------------------------- |
8741 | | |
8742 | | /** \brief Return a list of information on CRS objects |
8743 | | * |
8744 | | * This is functionally equivalent of listing the codes from an authority, |
8745 | | * instantiating |
8746 | | * a CRS object for each of them and getting the information from this CRS |
8747 | | * object, but this implementation has much less overhead. |
8748 | | * |
8749 | | * @throw FactoryException in case of error. |
8750 | | */ |
8751 | 0 | std::list<AuthorityFactory::CRSInfo> AuthorityFactory::getCRSInfoList() const { |
8752 | |
|
8753 | 0 | const auto getSqlArea = [](const char *table_name) { |
8754 | 0 | std::string sql("LEFT JOIN usage u ON u.object_table_name = '"); |
8755 | 0 | sql += table_name; |
8756 | 0 | sql += "' AND " |
8757 | 0 | "u.object_auth_name = c.auth_name AND " |
8758 | 0 | "u.object_code = c.code " |
8759 | 0 | "LEFT JOIN extent a " |
8760 | 0 | "ON a.auth_name = u.extent_auth_name AND " |
8761 | 0 | "a.code = u.extent_code "; |
8762 | 0 | return sql; |
8763 | 0 | }; |
8764 | |
|
8765 | 0 | const auto getJoinCelestialBody = [](const char *crs_alias) { |
8766 | 0 | std::string sql("LEFT JOIN geodetic_datum gd ON gd.auth_name = "); |
8767 | 0 | sql += crs_alias; |
8768 | 0 | sql += ".datum_auth_name AND gd.code = "; |
8769 | 0 | sql += crs_alias; |
8770 | 0 | sql += ".datum_code " |
8771 | 0 | "LEFT JOIN ellipsoid e ON e.auth_name = gd.ellipsoid_auth_name " |
8772 | 0 | "AND e.code = gd.ellipsoid_code " |
8773 | 0 | "LEFT JOIN celestial_body cb ON " |
8774 | 0 | "cb.auth_name = e.celestial_body_auth_name " |
8775 | 0 | "AND cb.code = e.celestial_body_code "; |
8776 | 0 | return sql; |
8777 | 0 | }; |
8778 | |
|
8779 | 0 | std::string sql = "SELECT * FROM (" |
8780 | 0 | "SELECT c.auth_name, c.code, c.name, c.type, " |
8781 | 0 | "c.deprecated, " |
8782 | 0 | "a.west_lon, a.south_lat, a.east_lon, a.north_lat, " |
8783 | 0 | "a.description, NULL, cb.name FROM geodetic_crs c "; |
8784 | 0 | sql += getSqlArea("geodetic_crs"); |
8785 | 0 | sql += getJoinCelestialBody("c"); |
8786 | 0 | ListOfParams params; |
8787 | 0 | if (d->hasAuthorityRestriction()) { |
8788 | 0 | sql += "WHERE c.auth_name = ? "; |
8789 | 0 | params.emplace_back(d->authority()); |
8790 | 0 | } |
8791 | 0 | sql += "UNION ALL SELECT c.auth_name, c.code, c.name, 'projected', " |
8792 | 0 | "c.deprecated, " |
8793 | 0 | "a.west_lon, a.south_lat, a.east_lon, a.north_lat, " |
8794 | 0 | "a.description, cm.name, cb.name AS conversion_method_name FROM " |
8795 | 0 | "projected_crs c " |
8796 | 0 | "LEFT JOIN conversion_table conv ON " |
8797 | 0 | "c.conversion_auth_name = conv.auth_name AND " |
8798 | 0 | "c.conversion_code = conv.code " |
8799 | 0 | "LEFT JOIN conversion_method cm ON " |
8800 | 0 | "conv.method_auth_name = cm.auth_name AND " |
8801 | 0 | "conv.method_code = cm.code " |
8802 | 0 | "LEFT JOIN geodetic_crs gcrs ON " |
8803 | 0 | "gcrs.auth_name = c.geodetic_crs_auth_name " |
8804 | 0 | "AND gcrs.code = c.geodetic_crs_code "; |
8805 | 0 | sql += getSqlArea("projected_crs"); |
8806 | 0 | sql += getJoinCelestialBody("gcrs"); |
8807 | 0 | if (d->hasAuthorityRestriction()) { |
8808 | 0 | sql += "WHERE c.auth_name = ? "; |
8809 | 0 | params.emplace_back(d->authority()); |
8810 | 0 | } |
8811 | | // FIXME: we can't handle non-EARTH vertical CRS for now |
8812 | 0 | sql += "UNION ALL SELECT c.auth_name, c.code, c.name, 'vertical', " |
8813 | 0 | "c.deprecated, " |
8814 | 0 | "a.west_lon, a.south_lat, a.east_lon, a.north_lat, " |
8815 | 0 | "a.description, NULL, 'Earth' FROM vertical_crs c "; |
8816 | 0 | sql += getSqlArea("vertical_crs"); |
8817 | 0 | if (d->hasAuthorityRestriction()) { |
8818 | 0 | sql += "WHERE c.auth_name = ? "; |
8819 | 0 | params.emplace_back(d->authority()); |
8820 | 0 | } |
8821 | | // FIXME: we can't handle non-EARTH compound CRS for now |
8822 | 0 | sql += "UNION ALL SELECT c.auth_name, c.code, c.name, 'compound', " |
8823 | 0 | "c.deprecated, " |
8824 | 0 | "a.west_lon, a.south_lat, a.east_lon, a.north_lat, " |
8825 | 0 | "a.description, NULL, 'Earth' FROM compound_crs c "; |
8826 | 0 | sql += getSqlArea("compound_crs"); |
8827 | 0 | if (d->hasAuthorityRestriction()) { |
8828 | 0 | sql += "WHERE c.auth_name = ? "; |
8829 | 0 | params.emplace_back(d->authority()); |
8830 | 0 | } |
8831 | | // FIXME: we can't handle non-EARTH compound CRS for now |
8832 | 0 | sql += "UNION ALL SELECT c.auth_name, c.code, c.name, 'engineering', " |
8833 | 0 | "c.deprecated, " |
8834 | 0 | "a.west_lon, a.south_lat, a.east_lon, a.north_lat, " |
8835 | 0 | "a.description, NULL, 'Earth' FROM engineering_crs c "; |
8836 | 0 | sql += getSqlArea("engineering_crs"); |
8837 | 0 | if (d->hasAuthorityRestriction()) { |
8838 | 0 | sql += "WHERE c.auth_name = ? "; |
8839 | 0 | params.emplace_back(d->authority()); |
8840 | 0 | } |
8841 | 0 | sql += ") r ORDER BY auth_name, code"; |
8842 | 0 | auto sqlRes = d->run(sql, params); |
8843 | 0 | std::list<AuthorityFactory::CRSInfo> res; |
8844 | 0 | for (const auto &row : sqlRes) { |
8845 | 0 | AuthorityFactory::CRSInfo info; |
8846 | 0 | info.authName = row[0]; |
8847 | 0 | info.code = row[1]; |
8848 | 0 | info.name = row[2]; |
8849 | 0 | const auto &type = row[3]; |
8850 | 0 | if (type == GEOG_2D) { |
8851 | 0 | info.type = AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS; |
8852 | 0 | } else if (type == GEOG_3D) { |
8853 | 0 | info.type = AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS; |
8854 | 0 | } else if (type == GEOCENTRIC) { |
8855 | 0 | info.type = AuthorityFactory::ObjectType::GEOCENTRIC_CRS; |
8856 | 0 | } else if (type == OTHER) { |
8857 | 0 | info.type = AuthorityFactory::ObjectType::GEODETIC_CRS; |
8858 | 0 | } else if (type == PROJECTED) { |
8859 | 0 | info.type = AuthorityFactory::ObjectType::PROJECTED_CRS; |
8860 | 0 | } else if (type == VERTICAL) { |
8861 | 0 | info.type = AuthorityFactory::ObjectType::VERTICAL_CRS; |
8862 | 0 | } else if (type == COMPOUND) { |
8863 | 0 | info.type = AuthorityFactory::ObjectType::COMPOUND_CRS; |
8864 | 0 | } else if (type == ENGINEERING) { |
8865 | 0 | info.type = AuthorityFactory::ObjectType::ENGINEERING_CRS; |
8866 | 0 | } |
8867 | 0 | info.deprecated = row[4] == "1"; |
8868 | 0 | if (row[5].empty()) { |
8869 | 0 | info.bbox_valid = false; |
8870 | 0 | } else { |
8871 | 0 | info.bbox_valid = true; |
8872 | 0 | info.west_lon_degree = c_locale_stod(row[5]); |
8873 | 0 | info.south_lat_degree = c_locale_stod(row[6]); |
8874 | 0 | info.east_lon_degree = c_locale_stod(row[7]); |
8875 | 0 | info.north_lat_degree = c_locale_stod(row[8]); |
8876 | 0 | } |
8877 | 0 | info.areaName = row[9]; |
8878 | 0 | info.projectionMethodName = row[10]; |
8879 | 0 | info.celestialBodyName = row[11]; |
8880 | 0 | res.emplace_back(info); |
8881 | 0 | } |
8882 | 0 | return res; |
8883 | 0 | } |
8884 | | |
8885 | | // --------------------------------------------------------------------------- |
8886 | | |
8887 | | //! @cond Doxygen_Suppress |
8888 | | AuthorityFactory::UnitInfo::UnitInfo() |
8889 | 0 | : authName{}, code{}, name{}, category{}, convFactor{}, projShortName{}, |
8890 | 0 | deprecated{} {} |
8891 | | //! @endcond |
8892 | | |
8893 | | // --------------------------------------------------------------------------- |
8894 | | |
8895 | | //! @cond Doxygen_Suppress |
8896 | 0 | AuthorityFactory::CelestialBodyInfo::CelestialBodyInfo() : authName{}, name{} {} |
8897 | | //! @endcond |
8898 | | |
8899 | | // --------------------------------------------------------------------------- |
8900 | | |
8901 | | /** \brief Return the list of units. |
8902 | | * @throw FactoryException in case of error. |
8903 | | * |
8904 | | * @since 7.1 |
8905 | | */ |
8906 | 0 | std::list<AuthorityFactory::UnitInfo> AuthorityFactory::getUnitList() const { |
8907 | 0 | std::string sql = "SELECT auth_name, code, name, type, conv_factor, " |
8908 | 0 | "proj_short_name, deprecated FROM unit_of_measure"; |
8909 | 0 | ListOfParams params; |
8910 | 0 | if (d->hasAuthorityRestriction()) { |
8911 | 0 | sql += " WHERE auth_name = ?"; |
8912 | 0 | params.emplace_back(d->authority()); |
8913 | 0 | } |
8914 | 0 | sql += " ORDER BY auth_name, code"; |
8915 | |
|
8916 | 0 | auto sqlRes = d->run(sql, params); |
8917 | 0 | std::list<AuthorityFactory::UnitInfo> res; |
8918 | 0 | for (const auto &row : sqlRes) { |
8919 | 0 | AuthorityFactory::UnitInfo info; |
8920 | 0 | info.authName = row[0]; |
8921 | 0 | info.code = row[1]; |
8922 | 0 | info.name = row[2]; |
8923 | 0 | const std::string &raw_category(row[3]); |
8924 | 0 | if (raw_category == "length") { |
8925 | 0 | info.category = info.name.find(" per ") != std::string::npos |
8926 | 0 | ? "linear_per_time" |
8927 | 0 | : "linear"; |
8928 | 0 | } else if (raw_category == "angle") { |
8929 | 0 | info.category = info.name.find(" per ") != std::string::npos |
8930 | 0 | ? "angular_per_time" |
8931 | 0 | : "angular"; |
8932 | 0 | } else if (raw_category == "scale") { |
8933 | 0 | info.category = |
8934 | 0 | info.name.find(" per year") != std::string::npos || |
8935 | 0 | info.name.find(" per second") != std::string::npos |
8936 | 0 | ? "scale_per_time" |
8937 | 0 | : "scale"; |
8938 | 0 | } else { |
8939 | 0 | info.category = raw_category; |
8940 | 0 | } |
8941 | 0 | info.convFactor = row[4].empty() ? 0 : c_locale_stod(row[4]); |
8942 | 0 | info.projShortName = row[5]; |
8943 | 0 | info.deprecated = row[6] == "1"; |
8944 | 0 | res.emplace_back(info); |
8945 | 0 | } |
8946 | 0 | return res; |
8947 | 0 | } |
8948 | | |
8949 | | // --------------------------------------------------------------------------- |
8950 | | |
8951 | | /** \brief Return the list of celestial bodies. |
8952 | | * @throw FactoryException in case of error. |
8953 | | * |
8954 | | * @since 8.1 |
8955 | | */ |
8956 | | std::list<AuthorityFactory::CelestialBodyInfo> |
8957 | 0 | AuthorityFactory::getCelestialBodyList() const { |
8958 | 0 | std::string sql = "SELECT auth_name, name FROM celestial_body"; |
8959 | 0 | ListOfParams params; |
8960 | 0 | if (d->hasAuthorityRestriction()) { |
8961 | 0 | sql += " WHERE auth_name = ?"; |
8962 | 0 | params.emplace_back(d->authority()); |
8963 | 0 | } |
8964 | 0 | sql += " ORDER BY auth_name, name"; |
8965 | |
|
8966 | 0 | auto sqlRes = d->run(sql, params); |
8967 | 0 | std::list<AuthorityFactory::CelestialBodyInfo> res; |
8968 | 0 | for (const auto &row : sqlRes) { |
8969 | 0 | AuthorityFactory::CelestialBodyInfo info; |
8970 | 0 | info.authName = row[0]; |
8971 | 0 | info.name = row[1]; |
8972 | 0 | res.emplace_back(info); |
8973 | 0 | } |
8974 | 0 | return res; |
8975 | 0 | } |
8976 | | |
8977 | | // --------------------------------------------------------------------------- |
8978 | | |
8979 | | /** \brief Gets the official name from a possibly alias name. |
8980 | | * |
8981 | | * @param aliasedName Alias name. |
8982 | | * @param tableName Table name/category. Can help in case of ambiguities. |
8983 | | * Or empty otherwise. |
8984 | | * @param source Source of the alias. Can help in case of ambiguities. |
8985 | | * Or empty otherwise. |
8986 | | * @param tryEquivalentNameSpelling whether the comparison of aliasedName with |
8987 | | * the alt_name column of the alias_name table should be done with using |
8988 | | * metadata::Identifier::isEquivalentName() rather than strict string |
8989 | | * comparison; |
8990 | | * @param outTableName Table name in which the official name has been found. |
8991 | | * @param outAuthName Authority name of the official name that has been found. |
8992 | | * @param outCode Code of the official name that has been found. |
8993 | | * @return official name (or empty if not found). |
8994 | | * @throw FactoryException in case of error. |
8995 | | */ |
8996 | | std::string AuthorityFactory::getOfficialNameFromAlias( |
8997 | | const std::string &aliasedName, const std::string &tableName, |
8998 | | const std::string &source, bool tryEquivalentNameSpelling, |
8999 | | std::string &outTableName, std::string &outAuthName, |
9000 | 2.87k | std::string &outCode) const { |
9001 | | |
9002 | 2.87k | if (tryEquivalentNameSpelling) { |
9003 | 0 | std::string sql( |
9004 | 0 | "SELECT table_name, auth_name, code, alt_name FROM alias_name"); |
9005 | 0 | ListOfParams params; |
9006 | 0 | if (!tableName.empty()) { |
9007 | 0 | sql += " WHERE table_name = ?"; |
9008 | 0 | params.push_back(tableName); |
9009 | 0 | } |
9010 | 0 | if (!source.empty()) { |
9011 | 0 | if (!tableName.empty()) { |
9012 | 0 | sql += " AND "; |
9013 | 0 | } else { |
9014 | 0 | sql += " WHERE "; |
9015 | 0 | } |
9016 | 0 | sql += "source = ?"; |
9017 | 0 | params.push_back(source); |
9018 | 0 | } |
9019 | 0 | auto res = d->run(sql, params); |
9020 | 0 | if (res.empty()) { |
9021 | 0 | return std::string(); |
9022 | 0 | } |
9023 | 0 | for (const auto &row : res) { |
9024 | 0 | const auto &alt_name = row[3]; |
9025 | 0 | if (metadata::Identifier::isEquivalentName(alt_name.c_str(), |
9026 | 0 | aliasedName.c_str())) { |
9027 | 0 | outTableName = row[0]; |
9028 | 0 | outAuthName = row[1]; |
9029 | 0 | outCode = row[2]; |
9030 | 0 | sql = "SELECT name FROM \""; |
9031 | 0 | sql += replaceAll(outTableName, "\"", "\"\""); |
9032 | 0 | sql += "\" WHERE auth_name = ? AND code = ?"; |
9033 | 0 | res = d->run(sql, {outAuthName, outCode}); |
9034 | 0 | if (res.empty()) { // shouldn't happen normally |
9035 | 0 | return std::string(); |
9036 | 0 | } |
9037 | 0 | return res.front()[0]; |
9038 | 0 | } |
9039 | 0 | } |
9040 | 0 | return std::string(); |
9041 | 2.87k | } else { |
9042 | 2.87k | std::string sql( |
9043 | 2.87k | "SELECT table_name, auth_name, code FROM alias_name WHERE " |
9044 | 2.87k | "alt_name = ?"); |
9045 | 2.87k | ListOfParams params{aliasedName}; |
9046 | 2.87k | if (!tableName.empty()) { |
9047 | 2.87k | sql += " AND table_name = ?"; |
9048 | 2.87k | params.push_back(tableName); |
9049 | 2.87k | } |
9050 | 2.87k | if (!source.empty()) { |
9051 | 2.87k | if (source == "ESRI") { |
9052 | 2.87k | sql += " AND source IN ('ESRI', 'ESRI_OLD')"; |
9053 | 2.87k | } else { |
9054 | 0 | sql += " AND source = ?"; |
9055 | 0 | params.push_back(source); |
9056 | 0 | } |
9057 | 2.87k | } |
9058 | 2.87k | auto res = d->run(sql, params); |
9059 | 2.87k | if (res.empty()) { |
9060 | 1.90k | return std::string(); |
9061 | 1.90k | } |
9062 | | |
9063 | 978 | params.clear(); |
9064 | 978 | sql.clear(); |
9065 | 978 | bool first = true; |
9066 | 978 | for (const auto &row : res) { |
9067 | 978 | if (!first) |
9068 | 0 | sql += " UNION ALL "; |
9069 | 978 | first = false; |
9070 | 978 | outTableName = row[0]; |
9071 | 978 | outAuthName = row[1]; |
9072 | 978 | outCode = row[2]; |
9073 | 978 | sql += "SELECT name, ? AS table_name, auth_name, code, deprecated " |
9074 | 978 | "FROM \""; |
9075 | 978 | sql += replaceAll(outTableName, "\"", "\"\""); |
9076 | 978 | sql += "\" WHERE auth_name = ? AND code = ?"; |
9077 | 978 | params.emplace_back(outTableName); |
9078 | 978 | params.emplace_back(outAuthName); |
9079 | 978 | params.emplace_back(outCode); |
9080 | 978 | } |
9081 | 978 | sql = "SELECT name, table_name, auth_name, code FROM (" + sql + |
9082 | 978 | ") x ORDER BY deprecated LIMIT 1"; |
9083 | 978 | res = d->run(sql, params); |
9084 | 978 | if (res.empty()) { // shouldn't happen normally |
9085 | 0 | return std::string(); |
9086 | 0 | } |
9087 | 978 | const auto &row = res.front(); |
9088 | 978 | outTableName = row[1]; |
9089 | 978 | outAuthName = row[2]; |
9090 | 978 | outCode = row[3]; |
9091 | 978 | return row[0]; |
9092 | 978 | } |
9093 | 2.87k | } |
9094 | | |
9095 | | // --------------------------------------------------------------------------- |
9096 | | |
9097 | | /** \brief Return a list of objects, identified by their name |
9098 | | * |
9099 | | * @param searchedName Searched name. Must be at least 2 character long. |
9100 | | * @param allowedObjectTypes List of object types into which to search. If |
9101 | | * empty, all object types will be searched. |
9102 | | * @param approximateMatch Whether approximate name identification is allowed. |
9103 | | * @param limitResultCount Maximum number of results to return. |
9104 | | * Or 0 for unlimited. |
9105 | | * @return list of matched objects. |
9106 | | * @throw FactoryException in case of error. |
9107 | | */ |
9108 | | std::list<common::IdentifiedObjectNNPtr> |
9109 | | AuthorityFactory::createObjectsFromName( |
9110 | | const std::string &searchedName, |
9111 | | const std::vector<ObjectType> &allowedObjectTypes, bool approximateMatch, |
9112 | 39.8k | size_t limitResultCount) const { |
9113 | 39.8k | std::list<common::IdentifiedObjectNNPtr> res; |
9114 | 39.8k | const auto resTmp(createObjectsFromNameEx( |
9115 | 39.8k | searchedName, allowedObjectTypes, approximateMatch, limitResultCount)); |
9116 | 39.8k | for (const auto &pair : resTmp) { |
9117 | 20.3k | res.emplace_back(pair.first); |
9118 | 20.3k | } |
9119 | 39.8k | return res; |
9120 | 39.8k | } |
9121 | | |
9122 | | // --------------------------------------------------------------------------- |
9123 | | |
9124 | | //! @cond Doxygen_Suppress |
9125 | | |
9126 | | /** \brief Return a list of objects, identifier by their name, with the name |
9127 | | * on which the match occurred. |
9128 | | * |
9129 | | * The name on which the match occurred might be different from the object name, |
9130 | | * if the match has been done on an alias name of that object. |
9131 | | * |
9132 | | * @param searchedName Searched name. Must be at least 2 character long. |
9133 | | * @param allowedObjectTypes List of object types into which to search. If |
9134 | | * empty, all object types will be searched. |
9135 | | * @param approximateMatch Whether approximate name identification is allowed. |
9136 | | * @param limitResultCount Maximum number of results to return. |
9137 | | * Or 0 for unlimited. |
9138 | | * @return list of matched objects. |
9139 | | * @throw FactoryException in case of error. |
9140 | | */ |
9141 | | std::list<AuthorityFactory::PairObjectName> |
9142 | | AuthorityFactory::createObjectsFromNameEx( |
9143 | | const std::string &searchedName, |
9144 | | const std::vector<ObjectType> &allowedObjectTypes, bool approximateMatch, |
9145 | 39.8k | size_t limitResultCount) const { |
9146 | 39.8k | std::string searchedNameWithoutDeprecated(searchedName); |
9147 | 39.8k | bool deprecated = false; |
9148 | 39.8k | if (ends_with(searchedNameWithoutDeprecated, " (deprecated)")) { |
9149 | 0 | deprecated = true; |
9150 | 0 | searchedNameWithoutDeprecated.resize( |
9151 | 0 | searchedNameWithoutDeprecated.size() - strlen(" (deprecated)")); |
9152 | 0 | } |
9153 | | |
9154 | 39.8k | const std::string canonicalizedSearchedName( |
9155 | 39.8k | metadata::Identifier::canonicalizeName(searchedNameWithoutDeprecated)); |
9156 | 39.8k | if (canonicalizedSearchedName.size() <= 1) { |
9157 | 1.79k | return {}; |
9158 | 1.79k | } |
9159 | | |
9160 | 38.0k | std::string sql( |
9161 | 38.0k | "SELECT table_name, auth_name, code, name, deprecated, is_alias " |
9162 | 38.0k | "FROM ("); |
9163 | | |
9164 | 38.0k | const auto getTableAndTypeConstraints = [&allowedObjectTypes, |
9165 | 38.0k | &searchedName]() { |
9166 | 38.0k | typedef std::pair<std::string, std::string> TableType; |
9167 | 38.0k | std::list<TableType> res; |
9168 | | // Hide ESRI D_ vertical datums |
9169 | 38.0k | const bool startsWithDUnderscore = starts_with(searchedName, "D_"); |
9170 | 38.0k | if (allowedObjectTypes.empty()) { |
9171 | 0 | for (const auto &tableName : |
9172 | 0 | {"prime_meridian", "ellipsoid", "geodetic_datum", |
9173 | 0 | "vertical_datum", "engineering_datum", "geodetic_crs", |
9174 | 0 | "projected_crs", "vertical_crs", "compound_crs", |
9175 | 0 | "engineering_crs", "conversion", "helmert_transformation", |
9176 | 0 | "grid_transformation", "other_transformation", |
9177 | 0 | "concatenated_operation"}) { |
9178 | 0 | if (!(startsWithDUnderscore && |
9179 | 0 | strcmp(tableName, "vertical_datum") == 0)) { |
9180 | 0 | res.emplace_back(TableType(tableName, std::string())); |
9181 | 0 | } |
9182 | 0 | } |
9183 | 38.0k | } else { |
9184 | 46.3k | for (const auto type : allowedObjectTypes) { |
9185 | 46.3k | switch (type) { |
9186 | 0 | case ObjectType::PRIME_MERIDIAN: |
9187 | 0 | res.emplace_back( |
9188 | 0 | TableType("prime_meridian", std::string())); |
9189 | 0 | break; |
9190 | 3.39k | case ObjectType::ELLIPSOID: |
9191 | 3.39k | res.emplace_back(TableType("ellipsoid", std::string())); |
9192 | 3.39k | break; |
9193 | 2.78k | case ObjectType::DATUM: |
9194 | 2.78k | res.emplace_back( |
9195 | 2.78k | TableType("geodetic_datum", std::string())); |
9196 | 2.78k | if (!startsWithDUnderscore) { |
9197 | 2.76k | res.emplace_back( |
9198 | 2.76k | TableType("vertical_datum", std::string())); |
9199 | 2.76k | res.emplace_back( |
9200 | 2.76k | TableType("engineering_datum", std::string())); |
9201 | 2.76k | } |
9202 | 2.78k | break; |
9203 | 10.0k | case ObjectType::GEODETIC_REFERENCE_FRAME: |
9204 | 10.0k | res.emplace_back( |
9205 | 10.0k | TableType("geodetic_datum", std::string())); |
9206 | 10.0k | break; |
9207 | 0 | case ObjectType::DYNAMIC_GEODETIC_REFERENCE_FRAME: |
9208 | 0 | res.emplace_back( |
9209 | 0 | TableType("geodetic_datum", "frame_reference_epoch")); |
9210 | 0 | break; |
9211 | 69 | case ObjectType::VERTICAL_REFERENCE_FRAME: |
9212 | 69 | res.emplace_back( |
9213 | 69 | TableType("vertical_datum", std::string())); |
9214 | 69 | break; |
9215 | 0 | case ObjectType::DYNAMIC_VERTICAL_REFERENCE_FRAME: |
9216 | 0 | res.emplace_back( |
9217 | 0 | TableType("vertical_datum", "frame_reference_epoch")); |
9218 | 0 | break; |
9219 | 0 | case ObjectType::ENGINEERING_DATUM: |
9220 | 0 | res.emplace_back( |
9221 | 0 | TableType("engineering_datum", std::string())); |
9222 | 0 | break; |
9223 | 3.84k | case ObjectType::CRS: |
9224 | 3.84k | res.emplace_back(TableType("geodetic_crs", std::string())); |
9225 | 3.84k | res.emplace_back(TableType("projected_crs", std::string())); |
9226 | 3.84k | res.emplace_back(TableType("vertical_crs", std::string())); |
9227 | 3.84k | res.emplace_back(TableType("compound_crs", std::string())); |
9228 | 3.84k | res.emplace_back( |
9229 | 3.84k | TableType("engineering_crs", std::string())); |
9230 | 3.84k | break; |
9231 | 0 | case ObjectType::GEODETIC_CRS: |
9232 | 0 | res.emplace_back(TableType("geodetic_crs", std::string())); |
9233 | 0 | break; |
9234 | 0 | case ObjectType::GEOCENTRIC_CRS: |
9235 | 0 | res.emplace_back(TableType("geodetic_crs", GEOCENTRIC)); |
9236 | 0 | break; |
9237 | 0 | case ObjectType::GEOGRAPHIC_CRS: |
9238 | 0 | res.emplace_back(TableType("geodetic_crs", GEOG_2D)); |
9239 | 0 | res.emplace_back(TableType("geodetic_crs", GEOG_3D)); |
9240 | 0 | break; |
9241 | 6.14k | case ObjectType::GEOGRAPHIC_2D_CRS: |
9242 | 6.14k | res.emplace_back(TableType("geodetic_crs", GEOG_2D)); |
9243 | 6.14k | break; |
9244 | 14.1k | case ObjectType::GEOGRAPHIC_3D_CRS: |
9245 | 14.1k | res.emplace_back(TableType("geodetic_crs", GEOG_3D)); |
9246 | 14.1k | break; |
9247 | 151 | case ObjectType::PROJECTED_CRS: |
9248 | 151 | res.emplace_back(TableType("projected_crs", std::string())); |
9249 | 151 | break; |
9250 | 159 | case ObjectType::VERTICAL_CRS: |
9251 | 159 | res.emplace_back(TableType("vertical_crs", std::string())); |
9252 | 159 | break; |
9253 | 97 | case ObjectType::COMPOUND_CRS: |
9254 | 97 | res.emplace_back(TableType("compound_crs", std::string())); |
9255 | 97 | break; |
9256 | 0 | case ObjectType::ENGINEERING_CRS: |
9257 | 0 | res.emplace_back( |
9258 | 0 | TableType("engineering_crs", std::string())); |
9259 | 0 | break; |
9260 | 2.78k | case ObjectType::COORDINATE_OPERATION: |
9261 | 2.78k | res.emplace_back(TableType("conversion", std::string())); |
9262 | 2.78k | res.emplace_back( |
9263 | 2.78k | TableType("helmert_transformation", std::string())); |
9264 | 2.78k | res.emplace_back( |
9265 | 2.78k | TableType("grid_transformation", std::string())); |
9266 | 2.78k | res.emplace_back( |
9267 | 2.78k | TableType("other_transformation", std::string())); |
9268 | 2.78k | res.emplace_back( |
9269 | 2.78k | TableType("concatenated_operation", std::string())); |
9270 | 2.78k | break; |
9271 | 0 | case ObjectType::CONVERSION: |
9272 | 0 | res.emplace_back(TableType("conversion", std::string())); |
9273 | 0 | break; |
9274 | 0 | case ObjectType::TRANSFORMATION: |
9275 | 0 | res.emplace_back( |
9276 | 0 | TableType("helmert_transformation", std::string())); |
9277 | 0 | res.emplace_back( |
9278 | 0 | TableType("grid_transformation", std::string())); |
9279 | 0 | res.emplace_back( |
9280 | 0 | TableType("other_transformation", std::string())); |
9281 | 0 | break; |
9282 | 0 | case ObjectType::CONCATENATED_OPERATION: |
9283 | 0 | res.emplace_back( |
9284 | 0 | TableType("concatenated_operation", std::string())); |
9285 | 0 | break; |
9286 | 2.78k | case ObjectType::DATUM_ENSEMBLE: |
9287 | 2.78k | res.emplace_back(TableType("geodetic_datum", "ensemble")); |
9288 | 2.78k | res.emplace_back(TableType("vertical_datum", "ensemble")); |
9289 | 2.78k | break; |
9290 | 46.3k | } |
9291 | 46.3k | } |
9292 | 38.0k | } |
9293 | 38.0k | return res; |
9294 | 38.0k | }; |
9295 | | |
9296 | 38.0k | bool datumEnsembleAllowed = false; |
9297 | 38.0k | if (allowedObjectTypes.empty()) { |
9298 | 0 | datumEnsembleAllowed = true; |
9299 | 38.0k | } else { |
9300 | 43.6k | for (const auto type : allowedObjectTypes) { |
9301 | 43.6k | if (type == ObjectType::DATUM_ENSEMBLE) { |
9302 | 2.78k | datumEnsembleAllowed = true; |
9303 | 2.78k | break; |
9304 | 2.78k | } |
9305 | 43.6k | } |
9306 | 38.0k | } |
9307 | | |
9308 | 38.0k | const auto listTableNameType = getTableAndTypeConstraints(); |
9309 | 38.0k | bool first = true; |
9310 | 38.0k | ListOfParams params; |
9311 | 81.2k | for (const auto &tableNameTypePair : listTableNameType) { |
9312 | 81.2k | if (!first) { |
9313 | 43.1k | sql += " UNION "; |
9314 | 43.1k | } |
9315 | 81.2k | first = false; |
9316 | 81.2k | sql += "SELECT '"; |
9317 | 81.2k | sql += tableNameTypePair.first; |
9318 | 81.2k | sql += "' AS table_name, auth_name, code, name, deprecated, " |
9319 | 81.2k | "0 AS is_alias FROM "; |
9320 | 81.2k | sql += tableNameTypePair.first; |
9321 | 81.2k | sql += " WHERE 1 = 1 "; |
9322 | 81.2k | if (!tableNameTypePair.second.empty()) { |
9323 | 25.8k | if (tableNameTypePair.second == "frame_reference_epoch") { |
9324 | 0 | sql += "AND frame_reference_epoch IS NOT NULL "; |
9325 | 25.8k | } else if (tableNameTypePair.second == "ensemble") { |
9326 | 5.56k | sql += "AND ensemble_accuracy IS NOT NULL "; |
9327 | 20.2k | } else { |
9328 | 20.2k | sql += "AND type = '"; |
9329 | 20.2k | sql += tableNameTypePair.second; |
9330 | 20.2k | sql += "' "; |
9331 | 20.2k | } |
9332 | 25.8k | } |
9333 | 81.2k | if (deprecated) { |
9334 | 0 | sql += "AND deprecated = 1 "; |
9335 | 0 | } |
9336 | 81.2k | if (!approximateMatch) { |
9337 | 63.8k | sql += "AND name = ? COLLATE NOCASE "; |
9338 | 63.8k | params.push_back(searchedNameWithoutDeprecated); |
9339 | 63.8k | } |
9340 | 81.2k | if (d->hasAuthorityRestriction()) { |
9341 | 15.1k | sql += "AND auth_name = ? "; |
9342 | 15.1k | params.emplace_back(d->authority()); |
9343 | 15.1k | } |
9344 | | |
9345 | 81.2k | sql += " UNION SELECT '"; |
9346 | 81.2k | sql += tableNameTypePair.first; |
9347 | 81.2k | sql += "' AS table_name, " |
9348 | 81.2k | "ov.auth_name AS auth_name, " |
9349 | 81.2k | "ov.code AS code, a.alt_name AS name, " |
9350 | 81.2k | "ov.deprecated AS deprecated, 1 as is_alias FROM "; |
9351 | 81.2k | sql += tableNameTypePair.first; |
9352 | 81.2k | sql += " ov " |
9353 | 81.2k | "JOIN alias_name a ON " |
9354 | 81.2k | "ov.auth_name = a.auth_name AND ov.code = a.code WHERE " |
9355 | 81.2k | "a.table_name = '"; |
9356 | 81.2k | sql += tableNameTypePair.first; |
9357 | 81.2k | sql += "' "; |
9358 | 81.2k | if (!tableNameTypePair.second.empty()) { |
9359 | 25.8k | if (tableNameTypePair.second == "frame_reference_epoch") { |
9360 | 0 | sql += "AND ov.frame_reference_epoch IS NOT NULL "; |
9361 | 25.8k | } else if (tableNameTypePair.second == "ensemble") { |
9362 | 5.56k | sql += "AND ov.ensemble_accuracy IS NOT NULL "; |
9363 | 20.2k | } else { |
9364 | 20.2k | sql += "AND ov.type = '"; |
9365 | 20.2k | sql += tableNameTypePair.second; |
9366 | 20.2k | sql += "' "; |
9367 | 20.2k | } |
9368 | 25.8k | } |
9369 | 81.2k | if (deprecated) { |
9370 | 0 | sql += "AND ov.deprecated = 1 "; |
9371 | 0 | } |
9372 | 81.2k | if (!approximateMatch) { |
9373 | 63.8k | sql += "AND a.alt_name = ? COLLATE NOCASE "; |
9374 | 63.8k | params.push_back(searchedNameWithoutDeprecated); |
9375 | 63.8k | } |
9376 | 81.2k | if (d->hasAuthorityRestriction()) { |
9377 | 15.1k | sql += "AND ov.auth_name = ? "; |
9378 | 15.1k | params.emplace_back(d->authority()); |
9379 | 15.1k | } |
9380 | 81.2k | } |
9381 | | |
9382 | 38.0k | sql += ") ORDER BY deprecated, is_alias, length(name), name"; |
9383 | 38.0k | if (limitResultCount > 0 && |
9384 | 38.0k | limitResultCount < |
9385 | 22.8k | static_cast<size_t>(std::numeric_limits<int>::max()) && |
9386 | 38.0k | !approximateMatch) { |
9387 | 19.8k | sql += " LIMIT "; |
9388 | 19.8k | sql += toString(static_cast<int>(limitResultCount)); |
9389 | 19.8k | } |
9390 | | |
9391 | 38.0k | std::list<PairObjectName> res; |
9392 | 38.0k | std::set<std::pair<std::string, std::string>> setIdentified; |
9393 | | |
9394 | | // Querying geodetic datum is a super hot path when importing from WKT1 |
9395 | | // so cache results. |
9396 | 38.0k | if (allowedObjectTypes.size() == 1 && |
9397 | 38.0k | allowedObjectTypes[0] == ObjectType::GEODETIC_REFERENCE_FRAME && |
9398 | 38.0k | approximateMatch && d->authority().empty()) { |
9399 | 112 | auto &mapCanonicalizeGRFName = |
9400 | 112 | d->context()->getPrivate()->getMapCanonicalizeGRFName(); |
9401 | 112 | if (mapCanonicalizeGRFName.empty()) { |
9402 | 68 | auto sqlRes = d->run(sql, params); |
9403 | 164k | for (const auto &row : sqlRes) { |
9404 | 164k | const auto &name = row[3]; |
9405 | 164k | const auto &deprecatedStr = row[4]; |
9406 | 164k | const auto canonicalizedName( |
9407 | 164k | metadata::Identifier::canonicalizeName(name)); |
9408 | 164k | auto &v = mapCanonicalizeGRFName[canonicalizedName]; |
9409 | 164k | if (deprecatedStr == "0" || v.empty() || v.front()[4] == "1") { |
9410 | 158k | v.push_back(row); |
9411 | 158k | } |
9412 | 164k | } |
9413 | 68 | } |
9414 | 112 | auto iter = mapCanonicalizeGRFName.find(canonicalizedSearchedName); |
9415 | 112 | if (iter != mapCanonicalizeGRFName.end()) { |
9416 | 13 | const auto &listOfRow = iter->second; |
9417 | 13 | for (const auto &row : listOfRow) { |
9418 | 13 | const auto &auth_name = row[1]; |
9419 | 13 | const auto &code = row[2]; |
9420 | 13 | auto key = std::pair<std::string, std::string>(auth_name, code); |
9421 | 13 | if (setIdentified.find(key) != setIdentified.end()) { |
9422 | 0 | continue; |
9423 | 0 | } |
9424 | 13 | setIdentified.insert(std::move(key)); |
9425 | 13 | auto factory = d->createFactory(auth_name); |
9426 | 13 | const auto &name = row[3]; |
9427 | 13 | res.emplace_back( |
9428 | 13 | PairObjectName(factory->createGeodeticDatum(code), name)); |
9429 | 13 | if (limitResultCount > 0 && res.size() == limitResultCount) { |
9430 | 13 | break; |
9431 | 13 | } |
9432 | 13 | } |
9433 | 99 | } else { |
9434 | 137k | for (const auto &pair : mapCanonicalizeGRFName) { |
9435 | 137k | const auto &listOfRow = pair.second; |
9436 | 149k | for (const auto &row : listOfRow) { |
9437 | 149k | const auto &name = row[3]; |
9438 | 149k | bool match = ci_find(name, searchedNameWithoutDeprecated) != |
9439 | 149k | std::string::npos; |
9440 | 149k | if (!match) { |
9441 | 149k | const auto &canonicalizedName(pair.first); |
9442 | 149k | match = ci_find(canonicalizedName, |
9443 | 149k | canonicalizedSearchedName) != |
9444 | 149k | std::string::npos; |
9445 | 149k | } |
9446 | 149k | if (!match) { |
9447 | 149k | continue; |
9448 | 149k | } |
9449 | | |
9450 | 46 | const auto &auth_name = row[1]; |
9451 | 46 | const auto &code = row[2]; |
9452 | 46 | auto key = |
9453 | 46 | std::pair<std::string, std::string>(auth_name, code); |
9454 | 46 | if (setIdentified.find(key) != setIdentified.end()) { |
9455 | 0 | continue; |
9456 | 0 | } |
9457 | 46 | setIdentified.insert(std::move(key)); |
9458 | 46 | auto factory = d->createFactory(auth_name); |
9459 | 46 | res.emplace_back(PairObjectName( |
9460 | 46 | factory->createGeodeticDatum(code), name)); |
9461 | 46 | if (limitResultCount > 0 && |
9462 | 46 | res.size() == limitResultCount) { |
9463 | 46 | break; |
9464 | 46 | } |
9465 | 46 | } |
9466 | 137k | if (limitResultCount > 0 && res.size() == limitResultCount) { |
9467 | 46 | break; |
9468 | 46 | } |
9469 | 137k | } |
9470 | 99 | } |
9471 | 37.9k | } else { |
9472 | 37.9k | auto sqlRes = d->run(sql, params); |
9473 | 37.9k | bool isFirst = true; |
9474 | 37.9k | bool firstIsDeprecated = false; |
9475 | 37.9k | size_t countExactMatch = 0; |
9476 | 37.9k | size_t countExactMatchOnAlias = 0; |
9477 | 37.9k | std::size_t hashCodeFirstMatch = 0; |
9478 | 38.3M | for (const auto &row : sqlRes) { |
9479 | 38.3M | const auto &name = row[3]; |
9480 | 38.3M | if (approximateMatch) { |
9481 | 38.2M | bool match = ci_find(name, searchedNameWithoutDeprecated) != |
9482 | 38.2M | std::string::npos; |
9483 | 38.2M | if (!match) { |
9484 | 38.2M | const auto canonicalizedName( |
9485 | 38.2M | metadata::Identifier::canonicalizeName(name)); |
9486 | 38.2M | match = |
9487 | 38.2M | ci_find(canonicalizedName, canonicalizedSearchedName) != |
9488 | 38.2M | std::string::npos; |
9489 | 38.2M | } |
9490 | 38.2M | if (!match) { |
9491 | 38.2M | continue; |
9492 | 38.2M | } |
9493 | 38.2M | } |
9494 | 21.3k | const auto &table_name = row[0]; |
9495 | 21.3k | const auto &auth_name = row[1]; |
9496 | 21.3k | const auto &code = row[2]; |
9497 | 21.3k | auto key = std::pair<std::string, std::string>(auth_name, code); |
9498 | 21.3k | if (setIdentified.find(key) != setIdentified.end()) { |
9499 | 876 | continue; |
9500 | 876 | } |
9501 | 20.4k | setIdentified.insert(std::move(key)); |
9502 | 20.4k | const auto &deprecatedStr = row[4]; |
9503 | 20.4k | if (isFirst) { |
9504 | 12.0k | firstIsDeprecated = deprecatedStr == "1"; |
9505 | 12.0k | isFirst = false; |
9506 | 12.0k | } |
9507 | 20.4k | if (deprecatedStr == "1" && !res.empty() && !firstIsDeprecated) { |
9508 | 87 | break; |
9509 | 87 | } |
9510 | 20.3k | auto factory = d->createFactory(auth_name); |
9511 | 20.3k | auto getObject = [&factory, datumEnsembleAllowed]( |
9512 | 20.3k | const std::string &l_table_name, |
9513 | 20.3k | const std::string &l_code) |
9514 | 20.3k | -> common::IdentifiedObjectNNPtr { |
9515 | 20.3k | if (l_table_name == "prime_meridian") { |
9516 | 0 | return factory->createPrimeMeridian(l_code); |
9517 | 20.3k | } else if (l_table_name == "ellipsoid") { |
9518 | 234 | return factory->createEllipsoid(l_code); |
9519 | 20.1k | } else if (l_table_name == "geodetic_datum") { |
9520 | 392 | if (datumEnsembleAllowed) { |
9521 | 392 | datum::GeodeticReferenceFramePtr datum; |
9522 | 392 | datum::DatumEnsemblePtr datumEnsemble; |
9523 | 392 | constexpr bool turnEnsembleAsDatum = false; |
9524 | 392 | factory->createGeodeticDatumOrEnsemble( |
9525 | 392 | l_code, datum, datumEnsemble, turnEnsembleAsDatum); |
9526 | 392 | if (datum) { |
9527 | 392 | return NN_NO_CHECK(datum); |
9528 | 392 | } |
9529 | 0 | assert(datumEnsemble); |
9530 | 0 | return NN_NO_CHECK(datumEnsemble); |
9531 | 392 | } |
9532 | 0 | return factory->createGeodeticDatum(l_code); |
9533 | 19.7k | } else if (l_table_name == "vertical_datum") { |
9534 | 175 | if (datumEnsembleAllowed) { |
9535 | 175 | datum::VerticalReferenceFramePtr datum; |
9536 | 175 | datum::DatumEnsemblePtr datumEnsemble; |
9537 | 175 | constexpr bool turnEnsembleAsDatum = false; |
9538 | 175 | factory->createVerticalDatumOrEnsemble( |
9539 | 175 | l_code, datum, datumEnsemble, turnEnsembleAsDatum); |
9540 | 175 | if (datum) { |
9541 | 172 | return NN_NO_CHECK(datum); |
9542 | 172 | } |
9543 | 3 | assert(datumEnsemble); |
9544 | 3 | return NN_NO_CHECK(datumEnsemble); |
9545 | 175 | } |
9546 | 0 | return factory->createVerticalDatum(l_code); |
9547 | 19.5k | } else if (l_table_name == "engineering_datum") { |
9548 | 6 | return factory->createEngineeringDatum(l_code); |
9549 | 19.5k | } else if (l_table_name == "geodetic_crs") { |
9550 | 14.1k | return factory->createGeodeticCRS(l_code); |
9551 | 14.1k | } else if (l_table_name == "projected_crs") { |
9552 | 2.73k | return factory->createProjectedCRS(l_code); |
9553 | 2.73k | } else if (l_table_name == "vertical_crs") { |
9554 | 761 | return factory->createVerticalCRS(l_code); |
9555 | 1.89k | } else if (l_table_name == "compound_crs") { |
9556 | 244 | return factory->createCompoundCRS(l_code); |
9557 | 1.64k | } else if (l_table_name == "engineering_crs") { |
9558 | 9 | return factory->createEngineeringCRS(l_code); |
9559 | 1.63k | } else if (l_table_name == "conversion") { |
9560 | 502 | return factory->createConversion(l_code); |
9561 | 1.13k | } else if (l_table_name == "grid_transformation" || |
9562 | 1.13k | l_table_name == "helmert_transformation" || |
9563 | 1.13k | l_table_name == "other_transformation" || |
9564 | 1.13k | l_table_name == "concatenated_operation") { |
9565 | 1.13k | return factory->createCoordinateOperation(l_code, true); |
9566 | 1.13k | } |
9567 | 0 | throw std::runtime_error("Unsupported table_name"); |
9568 | 20.3k | }; |
9569 | 20.3k | const auto obj = getObject(table_name, code); |
9570 | 20.3k | if (metadata::Identifier::isEquivalentName( |
9571 | 20.3k | obj->nameStr().c_str(), searchedName.c_str(), false)) { |
9572 | 10.4k | countExactMatch++; |
9573 | 10.4k | } else if (metadata::Identifier::isEquivalentName( |
9574 | 9.88k | name.c_str(), searchedName.c_str(), false)) { |
9575 | 542 | countExactMatchOnAlias++; |
9576 | 542 | } |
9577 | | |
9578 | 20.3k | const auto objPtr = obj.get(); |
9579 | 20.3k | if (res.empty()) { |
9580 | 12.0k | hashCodeFirstMatch = typeid(*objPtr).hash_code(); |
9581 | 12.0k | } else if (hashCodeFirstMatch != typeid(*objPtr).hash_code()) { |
9582 | 6.31k | hashCodeFirstMatch = 0; |
9583 | 6.31k | } |
9584 | | |
9585 | 20.3k | res.emplace_back(PairObjectName(obj, name)); |
9586 | 20.3k | if (limitResultCount > 0 && res.size() == limitResultCount) { |
9587 | 875 | break; |
9588 | 875 | } |
9589 | 20.3k | } |
9590 | | |
9591 | | // If we found several objects that are an exact match, and all objects |
9592 | | // have the same type, and we are not in approximate mode, only keep the |
9593 | | // objects with the exact name match. |
9594 | 37.9k | if ((countExactMatch + countExactMatchOnAlias) >= 1 && |
9595 | 37.9k | hashCodeFirstMatch != 0 && !approximateMatch) { |
9596 | 10.7k | std::list<PairObjectName> resTmp; |
9597 | 10.7k | bool biggerDifferencesAllowed = (countExactMatch == 0); |
9598 | 10.9k | for (const auto &pair : res) { |
9599 | 10.9k | if (metadata::Identifier::isEquivalentName( |
9600 | 10.9k | pair.first->nameStr().c_str(), searchedName.c_str(), |
9601 | 10.9k | biggerDifferencesAllowed) || |
9602 | 10.9k | (countExactMatch == 0 && |
9603 | 519 | metadata::Identifier::isEquivalentName( |
9604 | 427 | pair.second.c_str(), searchedName.c_str(), |
9605 | 10.8k | biggerDifferencesAllowed))) { |
9606 | 10.8k | resTmp.emplace_back(pair); |
9607 | 10.8k | } |
9608 | 10.9k | } |
9609 | 10.7k | res = std::move(resTmp); |
9610 | 10.7k | } |
9611 | 37.9k | } |
9612 | | |
9613 | 38.0k | auto sortLambda = [](const PairObjectName &a, const PairObjectName &b) { |
9614 | 15.4k | const auto &aName = a.first->nameStr(); |
9615 | 15.4k | const auto &bName = b.first->nameStr(); |
9616 | | |
9617 | 15.4k | if (aName.size() < bName.size()) { |
9618 | 533 | return true; |
9619 | 533 | } |
9620 | 14.8k | if (aName.size() > bName.size()) { |
9621 | 7.59k | return false; |
9622 | 7.59k | } |
9623 | | |
9624 | 7.29k | const auto &aIds = a.first->identifiers(); |
9625 | 7.29k | const auto &bIds = b.first->identifiers(); |
9626 | 7.29k | if (aIds.size() < bIds.size()) { |
9627 | 0 | return true; |
9628 | 0 | } |
9629 | 7.29k | if (aIds.size() > bIds.size()) { |
9630 | 0 | return false; |
9631 | 0 | } |
9632 | 7.29k | for (size_t idx = 0; idx < aIds.size(); idx++) { |
9633 | 7.29k | const auto &aCodeSpace = *aIds[idx]->codeSpace(); |
9634 | 7.29k | const auto &bCodeSpace = *bIds[idx]->codeSpace(); |
9635 | 7.29k | const auto codeSpaceComparison = aCodeSpace.compare(bCodeSpace); |
9636 | 7.29k | if (codeSpaceComparison < 0) { |
9637 | 684 | return true; |
9638 | 684 | } |
9639 | 6.61k | if (codeSpaceComparison > 0) { |
9640 | 743 | return false; |
9641 | 743 | } |
9642 | 5.86k | const auto &aCode = aIds[idx]->code(); |
9643 | 5.86k | const auto &bCode = bIds[idx]->code(); |
9644 | 5.86k | const auto codeComparison = aCode.compare(bCode); |
9645 | 5.86k | if (codeComparison < 0) { |
9646 | 1.70k | return true; |
9647 | 1.70k | } |
9648 | 4.16k | if (codeComparison > 0) { |
9649 | 4.16k | return false; |
9650 | 4.16k | } |
9651 | 4.16k | } |
9652 | 0 | return strcmp(typeid(a.first.get()).name(), |
9653 | 0 | typeid(b.first.get()).name()) < 0; |
9654 | 7.29k | }; |
9655 | | |
9656 | 38.0k | res.sort(sortLambda); |
9657 | | |
9658 | 38.0k | return res; |
9659 | 39.8k | } |
9660 | | //! @endcond |
9661 | | |
9662 | | // --------------------------------------------------------------------------- |
9663 | | |
9664 | | /** \brief Return a list of area of use from their name |
9665 | | * |
9666 | | * @param name Searched name. |
9667 | | * @param approximateMatch Whether approximate name identification is allowed. |
9668 | | * @return list of (auth_name, code) of matched objects. |
9669 | | * @throw FactoryException in case of error. |
9670 | | */ |
9671 | | std::list<std::pair<std::string, std::string>> |
9672 | | AuthorityFactory::listAreaOfUseFromName(const std::string &name, |
9673 | 0 | bool approximateMatch) const { |
9674 | 0 | std::string sql( |
9675 | 0 | "SELECT auth_name, code FROM extent WHERE deprecated = 0 AND "); |
9676 | 0 | ListOfParams params; |
9677 | 0 | if (d->hasAuthorityRestriction()) { |
9678 | 0 | sql += " auth_name = ? AND "; |
9679 | 0 | params.emplace_back(d->authority()); |
9680 | 0 | } |
9681 | 0 | sql += "name LIKE ?"; |
9682 | 0 | if (!approximateMatch) { |
9683 | 0 | params.push_back(name); |
9684 | 0 | } else { |
9685 | 0 | params.push_back('%' + name + '%'); |
9686 | 0 | } |
9687 | 0 | auto sqlRes = d->run(sql, params); |
9688 | 0 | std::list<std::pair<std::string, std::string>> res; |
9689 | 0 | for (const auto &row : sqlRes) { |
9690 | 0 | res.emplace_back(row[0], row[1]); |
9691 | 0 | } |
9692 | 0 | return res; |
9693 | 0 | } |
9694 | | |
9695 | | // --------------------------------------------------------------------------- |
9696 | | |
9697 | | //! @cond Doxygen_Suppress |
9698 | | std::list<datum::EllipsoidNNPtr> AuthorityFactory::createEllipsoidFromExisting( |
9699 | 0 | const datum::EllipsoidNNPtr &ellipsoid) const { |
9700 | 0 | std::string sql( |
9701 | 0 | "SELECT auth_name, code FROM ellipsoid WHERE " |
9702 | 0 | "abs(semi_major_axis - ?) < 1e-10 * abs(semi_major_axis) AND " |
9703 | 0 | "((semi_minor_axis IS NOT NULL AND " |
9704 | 0 | "abs(semi_minor_axis - ?) < 1e-10 * abs(semi_minor_axis)) OR " |
9705 | 0 | "((inv_flattening IS NOT NULL AND " |
9706 | 0 | "abs(inv_flattening - ?) < 1e-10 * abs(inv_flattening))))"); |
9707 | 0 | ListOfParams params{ellipsoid->semiMajorAxis().getSIValue(), |
9708 | 0 | ellipsoid->computeSemiMinorAxis().getSIValue(), |
9709 | 0 | ellipsoid->computedInverseFlattening()}; |
9710 | 0 | auto sqlRes = d->run(sql, params); |
9711 | 0 | std::list<datum::EllipsoidNNPtr> res; |
9712 | 0 | for (const auto &row : sqlRes) { |
9713 | 0 | const auto &auth_name = row[0]; |
9714 | 0 | const auto &code = row[1]; |
9715 | 0 | res.emplace_back(d->createFactory(auth_name)->createEllipsoid(code)); |
9716 | 0 | } |
9717 | 0 | return res; |
9718 | 0 | } |
9719 | | //! @endcond |
9720 | | |
9721 | | // --------------------------------------------------------------------------- |
9722 | | |
9723 | | //! @cond Doxygen_Suppress |
9724 | | std::list<crs::GeodeticCRSNNPtr> AuthorityFactory::createGeodeticCRSFromDatum( |
9725 | | const std::string &datum_auth_name, const std::string &datum_code, |
9726 | 15.7k | const std::string &geodetic_crs_type) const { |
9727 | 15.7k | std::string sql( |
9728 | 15.7k | "SELECT auth_name, code FROM geodetic_crs WHERE " |
9729 | 15.7k | "datum_auth_name = ? AND datum_code = ? AND deprecated = 0"); |
9730 | 15.7k | ListOfParams params{datum_auth_name, datum_code}; |
9731 | 15.7k | if (d->hasAuthorityRestriction()) { |
9732 | 1.78k | sql += " AND auth_name = ?"; |
9733 | 1.78k | params.emplace_back(d->authority()); |
9734 | 1.78k | } |
9735 | 15.7k | if (!geodetic_crs_type.empty()) { |
9736 | 0 | sql += " AND type = ?"; |
9737 | 0 | params.emplace_back(geodetic_crs_type); |
9738 | 0 | } |
9739 | 15.7k | sql += " ORDER BY auth_name, code"; |
9740 | 15.7k | auto sqlRes = d->run(sql, params); |
9741 | 15.7k | std::list<crs::GeodeticCRSNNPtr> res; |
9742 | 89.8k | for (const auto &row : sqlRes) { |
9743 | 89.8k | const auto &auth_name = row[0]; |
9744 | 89.8k | const auto &code = row[1]; |
9745 | 89.8k | res.emplace_back(d->createFactory(auth_name)->createGeodeticCRS(code)); |
9746 | 89.8k | } |
9747 | 15.7k | return res; |
9748 | 15.7k | } |
9749 | | //! @endcond |
9750 | | |
9751 | | // --------------------------------------------------------------------------- |
9752 | | |
9753 | | //! @cond Doxygen_Suppress |
9754 | | std::list<crs::GeodeticCRSNNPtr> AuthorityFactory::createGeodeticCRSFromDatum( |
9755 | | const datum::GeodeticReferenceFrameNNPtr &datum, |
9756 | | const std::string &preferredAuthName, |
9757 | 25.7k | const std::string &geodetic_crs_type) const { |
9758 | 25.7k | std::list<crs::GeodeticCRSNNPtr> candidates; |
9759 | 25.7k | const auto &ids = datum->identifiers(); |
9760 | 25.7k | const auto &datumName = datum->nameStr(); |
9761 | 25.7k | if (!ids.empty()) { |
9762 | 15.7k | for (const auto &id : ids) { |
9763 | 15.7k | const auto &authName = *(id->codeSpace()); |
9764 | 15.7k | const auto &code = id->code(); |
9765 | 15.7k | if (!authName.empty()) { |
9766 | 15.7k | const auto tmpFactory = |
9767 | 15.7k | (preferredAuthName == authName) |
9768 | 15.7k | ? create(databaseContext(), authName) |
9769 | 15.7k | : NN_NO_CHECK(d->getSharedFromThis()); |
9770 | 15.7k | auto l_candidates = tmpFactory->createGeodeticCRSFromDatum( |
9771 | 15.7k | authName, code, geodetic_crs_type); |
9772 | 89.8k | for (const auto &candidate : l_candidates) { |
9773 | 89.8k | candidates.emplace_back(candidate); |
9774 | 89.8k | } |
9775 | 15.7k | } |
9776 | 15.7k | } |
9777 | 15.7k | } else if (datumName != "unknown" && datumName != "unnamed") { |
9778 | 10.0k | auto matches = createObjectsFromName( |
9779 | 10.0k | datumName, |
9780 | 10.0k | {io::AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME}, false, |
9781 | 10.0k | 2); |
9782 | 10.0k | if (matches.size() == 1) { |
9783 | 0 | const auto &match = matches.front(); |
9784 | 0 | if (datum->_isEquivalentTo(match.get(), |
9785 | 0 | util::IComparable::Criterion::EQUIVALENT, |
9786 | 0 | databaseContext().as_nullable()) && |
9787 | 0 | !match->identifiers().empty()) { |
9788 | 0 | return createGeodeticCRSFromDatum( |
9789 | 0 | util::nn_static_pointer_cast<datum::GeodeticReferenceFrame>( |
9790 | 0 | match), |
9791 | 0 | preferredAuthName, geodetic_crs_type); |
9792 | 0 | } |
9793 | 0 | } |
9794 | 10.0k | } |
9795 | 25.7k | return candidates; |
9796 | 25.7k | } |
9797 | | //! @endcond |
9798 | | |
9799 | | // --------------------------------------------------------------------------- |
9800 | | |
9801 | | //! @cond Doxygen_Suppress |
9802 | | std::list<crs::VerticalCRSNNPtr> AuthorityFactory::createVerticalCRSFromDatum( |
9803 | 60 | const std::string &datum_auth_name, const std::string &datum_code) const { |
9804 | 60 | std::string sql( |
9805 | 60 | "SELECT auth_name, code FROM vertical_crs WHERE " |
9806 | 60 | "datum_auth_name = ? AND datum_code = ? AND deprecated = 0"); |
9807 | 60 | ListOfParams params{datum_auth_name, datum_code}; |
9808 | 60 | if (d->hasAuthorityRestriction()) { |
9809 | 0 | sql += " AND auth_name = ?"; |
9810 | 0 | params.emplace_back(d->authority()); |
9811 | 0 | } |
9812 | 60 | auto sqlRes = d->run(sql, params); |
9813 | 60 | std::list<crs::VerticalCRSNNPtr> res; |
9814 | 102 | for (const auto &row : sqlRes) { |
9815 | 102 | const auto &auth_name = row[0]; |
9816 | 102 | const auto &code = row[1]; |
9817 | 102 | res.emplace_back(d->createFactory(auth_name)->createVerticalCRS(code)); |
9818 | 102 | } |
9819 | 60 | return res; |
9820 | 60 | } |
9821 | | //! @endcond |
9822 | | |
9823 | | // --------------------------------------------------------------------------- |
9824 | | |
9825 | | //! @cond Doxygen_Suppress |
9826 | | std::list<crs::GeodeticCRSNNPtr> |
9827 | | AuthorityFactory::createGeodeticCRSFromEllipsoid( |
9828 | | const std::string &ellipsoid_auth_name, const std::string &ellipsoid_code, |
9829 | 0 | const std::string &geodetic_crs_type) const { |
9830 | 0 | std::string sql( |
9831 | 0 | "SELECT geodetic_crs.auth_name, geodetic_crs.code FROM geodetic_crs " |
9832 | 0 | "JOIN geodetic_datum ON " |
9833 | 0 | "geodetic_crs.datum_auth_name = geodetic_datum.auth_name AND " |
9834 | 0 | "geodetic_crs.datum_code = geodetic_datum.code WHERE " |
9835 | 0 | "geodetic_datum.ellipsoid_auth_name = ? AND " |
9836 | 0 | "geodetic_datum.ellipsoid_code = ? AND " |
9837 | 0 | "geodetic_datum.deprecated = 0 AND " |
9838 | 0 | "geodetic_crs.deprecated = 0"); |
9839 | 0 | ListOfParams params{ellipsoid_auth_name, ellipsoid_code}; |
9840 | 0 | if (d->hasAuthorityRestriction()) { |
9841 | 0 | sql += " AND geodetic_crs.auth_name = ?"; |
9842 | 0 | params.emplace_back(d->authority()); |
9843 | 0 | } |
9844 | 0 | if (!geodetic_crs_type.empty()) { |
9845 | 0 | sql += " AND geodetic_crs.type = ?"; |
9846 | 0 | params.emplace_back(geodetic_crs_type); |
9847 | 0 | } |
9848 | 0 | auto sqlRes = d->run(sql, params); |
9849 | 0 | std::list<crs::GeodeticCRSNNPtr> res; |
9850 | 0 | for (const auto &row : sqlRes) { |
9851 | 0 | const auto &auth_name = row[0]; |
9852 | 0 | const auto &code = row[1]; |
9853 | 0 | res.emplace_back(d->createFactory(auth_name)->createGeodeticCRS(code)); |
9854 | 0 | } |
9855 | 0 | return res; |
9856 | 0 | } |
9857 | | //! @endcond |
9858 | | |
9859 | | // --------------------------------------------------------------------------- |
9860 | | |
9861 | | //! @cond Doxygen_Suppress |
9862 | | static std::string buildSqlLookForAuthNameCode( |
9863 | | const std::list<std::pair<crs::CRSNNPtr, int>> &list, ListOfParams ¶ms, |
9864 | 0 | const char *prefixField) { |
9865 | 0 | std::string sql("("); |
9866 | |
|
9867 | 0 | std::set<std::string> authorities; |
9868 | 0 | for (const auto &crs : list) { |
9869 | 0 | auto boundCRS = dynamic_cast<crs::BoundCRS *>(crs.first.get()); |
9870 | 0 | const auto &ids = boundCRS ? boundCRS->baseCRS()->identifiers() |
9871 | 0 | : crs.first->identifiers(); |
9872 | 0 | if (!ids.empty()) { |
9873 | 0 | authorities.insert(*(ids[0]->codeSpace())); |
9874 | 0 | } |
9875 | 0 | } |
9876 | 0 | bool firstAuth = true; |
9877 | 0 | for (const auto &auth_name : authorities) { |
9878 | 0 | if (!firstAuth) { |
9879 | 0 | sql += " OR "; |
9880 | 0 | } |
9881 | 0 | firstAuth = false; |
9882 | 0 | sql += "( "; |
9883 | 0 | sql += prefixField; |
9884 | 0 | sql += "auth_name = ? AND "; |
9885 | 0 | sql += prefixField; |
9886 | 0 | sql += "code IN ("; |
9887 | 0 | params.emplace_back(auth_name); |
9888 | 0 | bool firstGeodCRSForAuth = true; |
9889 | 0 | for (const auto &crs : list) { |
9890 | 0 | auto boundCRS = dynamic_cast<crs::BoundCRS *>(crs.first.get()); |
9891 | 0 | const auto &ids = boundCRS ? boundCRS->baseCRS()->identifiers() |
9892 | 0 | : crs.first->identifiers(); |
9893 | 0 | if (!ids.empty() && *(ids[0]->codeSpace()) == auth_name) { |
9894 | 0 | if (!firstGeodCRSForAuth) { |
9895 | 0 | sql += ','; |
9896 | 0 | } |
9897 | 0 | firstGeodCRSForAuth = false; |
9898 | 0 | sql += '?'; |
9899 | 0 | params.emplace_back(ids[0]->code()); |
9900 | 0 | } |
9901 | 0 | } |
9902 | 0 | sql += "))"; |
9903 | 0 | } |
9904 | 0 | sql += ')'; |
9905 | 0 | return sql; |
9906 | 0 | } |
9907 | | //! @endcond |
9908 | | |
9909 | | // --------------------------------------------------------------------------- |
9910 | | |
9911 | | //! @cond Doxygen_Suppress |
9912 | | std::list<crs::ProjectedCRSNNPtr> |
9913 | | AuthorityFactory::createProjectedCRSFromExisting( |
9914 | 0 | const crs::ProjectedCRSNNPtr &crs) const { |
9915 | 0 | std::list<crs::ProjectedCRSNNPtr> res; |
9916 | |
|
9917 | 0 | const auto &conv = crs->derivingConversionRef(); |
9918 | 0 | const auto &method = conv->method(); |
9919 | 0 | const auto methodEPSGCode = method->getEPSGCode(); |
9920 | 0 | if (methodEPSGCode == 0) { |
9921 | 0 | return res; |
9922 | 0 | } |
9923 | | |
9924 | 0 | auto lockedThisFactory(d->getSharedFromThis()); |
9925 | 0 | assert(lockedThisFactory); |
9926 | 0 | const auto &baseCRS(crs->baseCRS()); |
9927 | 0 | auto candidatesGeodCRS = baseCRS->crs::CRS::identify(lockedThisFactory); |
9928 | 0 | auto geogCRS = dynamic_cast<const crs::GeographicCRS *>(baseCRS.get()); |
9929 | 0 | if (geogCRS) { |
9930 | 0 | const auto axisOrder = geogCRS->coordinateSystem()->axisOrder(); |
9931 | 0 | if (axisOrder == cs::EllipsoidalCS::AxisOrder::LONG_EAST_LAT_NORTH || |
9932 | 0 | axisOrder == cs::EllipsoidalCS::AxisOrder::LAT_NORTH_LONG_EAST) { |
9933 | 0 | const auto &unit = |
9934 | 0 | geogCRS->coordinateSystem()->axisList()[0]->unit(); |
9935 | 0 | auto otherOrderGeogCRS = crs::GeographicCRS::create( |
9936 | 0 | util::PropertyMap().set(common::IdentifiedObject::NAME_KEY, |
9937 | 0 | geogCRS->nameStr()), |
9938 | 0 | geogCRS->datum(), geogCRS->datumEnsemble(), |
9939 | 0 | axisOrder == cs::EllipsoidalCS::AxisOrder::LONG_EAST_LAT_NORTH |
9940 | 0 | ? cs::EllipsoidalCS::createLatitudeLongitude(unit) |
9941 | 0 | : cs::EllipsoidalCS::createLongitudeLatitude(unit)); |
9942 | 0 | auto otherCandidatesGeodCRS = |
9943 | 0 | otherOrderGeogCRS->crs::CRS::identify(lockedThisFactory); |
9944 | 0 | candidatesGeodCRS.insert(candidatesGeodCRS.end(), |
9945 | 0 | otherCandidatesGeodCRS.begin(), |
9946 | 0 | otherCandidatesGeodCRS.end()); |
9947 | 0 | } |
9948 | 0 | } |
9949 | |
|
9950 | 0 | std::string sql("SELECT projected_crs.auth_name, projected_crs.code, " |
9951 | 0 | "projected_crs.name FROM projected_crs " |
9952 | 0 | "JOIN conversion_table conv ON " |
9953 | 0 | "projected_crs.conversion_auth_name = conv.auth_name AND " |
9954 | 0 | "projected_crs.conversion_code = conv.code WHERE " |
9955 | 0 | "projected_crs.deprecated = 0 AND "); |
9956 | 0 | ListOfParams params; |
9957 | 0 | if (!candidatesGeodCRS.empty()) { |
9958 | 0 | sql += buildSqlLookForAuthNameCode(candidatesGeodCRS, params, |
9959 | 0 | "projected_crs.geodetic_crs_"); |
9960 | 0 | sql += " AND "; |
9961 | 0 | } |
9962 | 0 | sql += "conv.method_auth_name = 'EPSG' AND " |
9963 | 0 | "conv.method_code = ?"; |
9964 | 0 | params.emplace_back(toString(methodEPSGCode)); |
9965 | 0 | if (d->hasAuthorityRestriction()) { |
9966 | 0 | sql += " AND projected_crs.auth_name = ?"; |
9967 | 0 | params.emplace_back(d->authority()); |
9968 | 0 | } |
9969 | |
|
9970 | 0 | int iParam = 0; |
9971 | 0 | bool hasLat1stStd = false; |
9972 | 0 | double lat1stStd = 0; |
9973 | 0 | int iParamLat1stStd = 0; |
9974 | 0 | bool hasLat2ndStd = false; |
9975 | 0 | double lat2ndStd = 0; |
9976 | 0 | int iParamLat2ndStd = 0; |
9977 | 0 | for (const auto &genOpParamvalue : conv->parameterValues()) { |
9978 | 0 | iParam++; |
9979 | 0 | auto opParamvalue = |
9980 | 0 | dynamic_cast<const operation::OperationParameterValue *>( |
9981 | 0 | genOpParamvalue.get()); |
9982 | 0 | if (!opParamvalue) { |
9983 | 0 | break; |
9984 | 0 | } |
9985 | 0 | const auto paramEPSGCode = opParamvalue->parameter()->getEPSGCode(); |
9986 | 0 | const auto ¶meterValue = opParamvalue->parameterValue(); |
9987 | 0 | if (!(paramEPSGCode > 0 && |
9988 | 0 | parameterValue->type() == |
9989 | 0 | operation::ParameterValue::Type::MEASURE)) { |
9990 | 0 | break; |
9991 | 0 | } |
9992 | 0 | const auto &measure = parameterValue->value(); |
9993 | 0 | const auto &unit = measure.unit(); |
9994 | 0 | if (unit == common::UnitOfMeasure::DEGREE && |
9995 | 0 | baseCRS->coordinateSystem()->axisList()[0]->unit() == unit) { |
9996 | 0 | if (methodEPSGCode == |
9997 | 0 | EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP) { |
9998 | | // Special case for standard parallels of LCC_2SP. See below |
9999 | 0 | if (paramEPSGCode == |
10000 | 0 | EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL) { |
10001 | 0 | hasLat1stStd = true; |
10002 | 0 | lat1stStd = measure.value(); |
10003 | 0 | iParamLat1stStd = iParam; |
10004 | 0 | continue; |
10005 | 0 | } else if (paramEPSGCode == |
10006 | 0 | EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL) { |
10007 | 0 | hasLat2ndStd = true; |
10008 | 0 | lat2ndStd = measure.value(); |
10009 | 0 | iParamLat2ndStd = iParam; |
10010 | 0 | continue; |
10011 | 0 | } |
10012 | 0 | } |
10013 | 0 | const auto iParamAsStr(toString(iParam)); |
10014 | 0 | sql += " AND conv.param"; |
10015 | 0 | sql += iParamAsStr; |
10016 | 0 | sql += "_code = ? AND conv.param"; |
10017 | 0 | sql += iParamAsStr; |
10018 | 0 | sql += "_auth_name = 'EPSG' AND conv.param"; |
10019 | 0 | sql += iParamAsStr; |
10020 | 0 | sql += "_value BETWEEN ? AND ?"; |
10021 | | // As angles might be expressed with the odd unit EPSG:9110 |
10022 | | // "sexagesimal DMS", we have to provide a broad range |
10023 | 0 | params.emplace_back(toString(paramEPSGCode)); |
10024 | 0 | params.emplace_back(measure.value() - 1); |
10025 | 0 | params.emplace_back(measure.value() + 1); |
10026 | 0 | } |
10027 | 0 | } |
10028 | | |
10029 | | // Special case for standard parallels of LCC_2SP: they can be switched |
10030 | 0 | if (methodEPSGCode == EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP && |
10031 | 0 | hasLat1stStd && hasLat2ndStd) { |
10032 | 0 | const auto iParam1AsStr(toString(iParamLat1stStd)); |
10033 | 0 | const auto iParam2AsStr(toString(iParamLat2ndStd)); |
10034 | 0 | sql += " AND conv.param"; |
10035 | 0 | sql += iParam1AsStr; |
10036 | 0 | sql += "_code = ? AND conv.param"; |
10037 | 0 | sql += iParam1AsStr; |
10038 | 0 | sql += "_auth_name = 'EPSG' AND conv.param"; |
10039 | 0 | sql += iParam2AsStr; |
10040 | 0 | sql += "_code = ? AND conv.param"; |
10041 | 0 | sql += iParam2AsStr; |
10042 | 0 | sql += "_auth_name = 'EPSG' AND (("; |
10043 | 0 | params.emplace_back( |
10044 | 0 | toString(EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL)); |
10045 | 0 | params.emplace_back( |
10046 | 0 | toString(EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL)); |
10047 | 0 | double val1 = lat1stStd; |
10048 | 0 | double val2 = lat2ndStd; |
10049 | 0 | for (int i = 0; i < 2; i++) { |
10050 | 0 | if (i == 1) { |
10051 | 0 | sql += ") OR ("; |
10052 | 0 | std::swap(val1, val2); |
10053 | 0 | } |
10054 | 0 | sql += "conv.param"; |
10055 | 0 | sql += iParam1AsStr; |
10056 | 0 | sql += "_value BETWEEN ? AND ? AND conv.param"; |
10057 | 0 | sql += iParam2AsStr; |
10058 | 0 | sql += "_value BETWEEN ? AND ?"; |
10059 | 0 | params.emplace_back(val1 - 1); |
10060 | 0 | params.emplace_back(val1 + 1); |
10061 | 0 | params.emplace_back(val2 - 1); |
10062 | 0 | params.emplace_back(val2 + 1); |
10063 | 0 | } |
10064 | 0 | sql += "))"; |
10065 | 0 | } |
10066 | 0 | auto sqlRes = d->run(sql, params); |
10067 | |
|
10068 | 0 | for (const auto &row : sqlRes) { |
10069 | 0 | const auto &name = row[2]; |
10070 | 0 | if (metadata::Identifier::isEquivalentName(crs->nameStr().c_str(), |
10071 | 0 | name.c_str())) { |
10072 | 0 | const auto &auth_name = row[0]; |
10073 | 0 | const auto &code = row[1]; |
10074 | 0 | res.emplace_back( |
10075 | 0 | d->createFactory(auth_name)->createProjectedCRS(code)); |
10076 | 0 | } |
10077 | 0 | } |
10078 | 0 | if (!res.empty()) { |
10079 | 0 | return res; |
10080 | 0 | } |
10081 | | |
10082 | 0 | params.clear(); |
10083 | |
|
10084 | 0 | sql = "SELECT auth_name, code FROM projected_crs WHERE " |
10085 | 0 | "deprecated = 0 AND conversion_auth_name IS NULL AND "; |
10086 | 0 | if (!candidatesGeodCRS.empty()) { |
10087 | 0 | sql += buildSqlLookForAuthNameCode(candidatesGeodCRS, params, |
10088 | 0 | "geodetic_crs_"); |
10089 | 0 | sql += " AND "; |
10090 | 0 | } |
10091 | |
|
10092 | 0 | const auto escapeLikeStr = [](const std::string &str) { |
10093 | 0 | return replaceAll(replaceAll(replaceAll(str, "\\", "\\\\"), "_", "\\_"), |
10094 | 0 | "%", "\\%"); |
10095 | 0 | }; |
10096 | |
|
10097 | 0 | const auto ellpsSemiMajorStr = |
10098 | 0 | toString(baseCRS->ellipsoid()->semiMajorAxis().getSIValue(), 10); |
10099 | |
|
10100 | 0 | sql += "(text_definition LIKE ? ESCAPE '\\'"; |
10101 | | |
10102 | | // WKT2 definition |
10103 | 0 | { |
10104 | 0 | std::string patternVal("%"); |
10105 | |
|
10106 | 0 | patternVal += ','; |
10107 | 0 | patternVal += ellpsSemiMajorStr; |
10108 | 0 | patternVal += '%'; |
10109 | |
|
10110 | 0 | patternVal += escapeLikeStr(method->nameStr()); |
10111 | 0 | patternVal += '%'; |
10112 | |
|
10113 | 0 | params.emplace_back(patternVal); |
10114 | 0 | } |
10115 | |
|
10116 | 0 | const auto *mapping = getMapping(method.get()); |
10117 | 0 | if (mapping && mapping->proj_name_main) { |
10118 | 0 | sql += " OR (text_definition LIKE ? AND (text_definition LIKE ?"; |
10119 | |
|
10120 | 0 | std::string patternVal("%"); |
10121 | 0 | patternVal += "proj="; |
10122 | 0 | patternVal += mapping->proj_name_main; |
10123 | 0 | patternVal += '%'; |
10124 | 0 | params.emplace_back(patternVal); |
10125 | | |
10126 | | // could be a= or R= |
10127 | 0 | patternVal = "%="; |
10128 | 0 | patternVal += ellpsSemiMajorStr; |
10129 | 0 | patternVal += '%'; |
10130 | 0 | params.emplace_back(patternVal); |
10131 | |
|
10132 | 0 | std::string projEllpsName; |
10133 | 0 | std::string ellpsName; |
10134 | 0 | if (baseCRS->ellipsoid()->lookForProjWellKnownEllps(projEllpsName, |
10135 | 0 | ellpsName)) { |
10136 | 0 | sql += " OR text_definition LIKE ?"; |
10137 | | // Could be ellps= or datum= |
10138 | 0 | patternVal = "%="; |
10139 | 0 | patternVal += projEllpsName; |
10140 | 0 | patternVal += '%'; |
10141 | 0 | params.emplace_back(patternVal); |
10142 | 0 | } |
10143 | |
|
10144 | 0 | sql += "))"; |
10145 | 0 | } |
10146 | | |
10147 | | // WKT1_GDAL definition |
10148 | 0 | const char *wkt1GDALMethodName = conv->getWKT1GDALMethodName(); |
10149 | 0 | if (wkt1GDALMethodName) { |
10150 | 0 | sql += " OR text_definition LIKE ? ESCAPE '\\'"; |
10151 | 0 | std::string patternVal("%"); |
10152 | |
|
10153 | 0 | patternVal += ','; |
10154 | 0 | patternVal += ellpsSemiMajorStr; |
10155 | 0 | patternVal += '%'; |
10156 | |
|
10157 | 0 | patternVal += escapeLikeStr(wkt1GDALMethodName); |
10158 | 0 | patternVal += '%'; |
10159 | |
|
10160 | 0 | params.emplace_back(patternVal); |
10161 | 0 | } |
10162 | | |
10163 | | // WKT1_ESRI definition |
10164 | 0 | const char *esriMethodName = conv->getESRIMethodName(); |
10165 | 0 | if (esriMethodName) { |
10166 | 0 | sql += " OR text_definition LIKE ? ESCAPE '\\'"; |
10167 | 0 | std::string patternVal("%"); |
10168 | |
|
10169 | 0 | patternVal += ','; |
10170 | 0 | patternVal += ellpsSemiMajorStr; |
10171 | 0 | patternVal += '%'; |
10172 | |
|
10173 | 0 | patternVal += escapeLikeStr(esriMethodName); |
10174 | 0 | patternVal += '%'; |
10175 | |
|
10176 | 0 | auto fe = |
10177 | 0 | &conv->parameterValueMeasure(EPSG_CODE_PARAMETER_FALSE_EASTING); |
10178 | 0 | if (*fe == Measure()) { |
10179 | 0 | fe = &conv->parameterValueMeasure( |
10180 | 0 | EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN); |
10181 | 0 | } |
10182 | 0 | if (!(*fe == Measure())) { |
10183 | 0 | patternVal += "PARAMETER[\"False\\_Easting\","; |
10184 | 0 | patternVal += |
10185 | 0 | toString(fe->convertToUnit( |
10186 | 0 | crs->coordinateSystem()->axisList()[0]->unit()), |
10187 | 0 | 10); |
10188 | 0 | patternVal += '%'; |
10189 | 0 | } |
10190 | |
|
10191 | 0 | auto lat = &conv->parameterValueMeasure( |
10192 | 0 | EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN); |
10193 | 0 | if (*lat == Measure()) { |
10194 | 0 | lat = &conv->parameterValueMeasure( |
10195 | 0 | EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN); |
10196 | 0 | } |
10197 | 0 | if (!(*lat == Measure())) { |
10198 | 0 | patternVal += "PARAMETER[\"Latitude\\_Of\\_Origin\","; |
10199 | 0 | const auto &angularUnit = |
10200 | 0 | dynamic_cast<crs::GeographicCRS *>(crs->baseCRS().get()) |
10201 | 0 | ? crs->baseCRS()->coordinateSystem()->axisList()[0]->unit() |
10202 | 0 | : UnitOfMeasure::DEGREE; |
10203 | 0 | patternVal += toString(lat->convertToUnit(angularUnit), 10); |
10204 | 0 | patternVal += '%'; |
10205 | 0 | } |
10206 | |
|
10207 | 0 | params.emplace_back(patternVal); |
10208 | 0 | } |
10209 | 0 | sql += ")"; |
10210 | 0 | if (d->hasAuthorityRestriction()) { |
10211 | 0 | sql += " AND auth_name = ?"; |
10212 | 0 | params.emplace_back(d->authority()); |
10213 | 0 | } |
10214 | |
|
10215 | 0 | auto sqlRes2 = d->run(sql, params); |
10216 | |
|
10217 | 0 | if (sqlRes.size() <= 200) { |
10218 | 0 | for (const auto &row : sqlRes) { |
10219 | 0 | const auto &auth_name = row[0]; |
10220 | 0 | const auto &code = row[1]; |
10221 | 0 | res.emplace_back( |
10222 | 0 | d->createFactory(auth_name)->createProjectedCRS(code)); |
10223 | 0 | } |
10224 | 0 | } |
10225 | 0 | if (sqlRes2.size() <= 200) { |
10226 | 0 | for (const auto &row : sqlRes2) { |
10227 | 0 | const auto &auth_name = row[0]; |
10228 | 0 | const auto &code = row[1]; |
10229 | 0 | res.emplace_back( |
10230 | 0 | d->createFactory(auth_name)->createProjectedCRS(code)); |
10231 | 0 | } |
10232 | 0 | } |
10233 | |
|
10234 | 0 | return res; |
10235 | 0 | } |
10236 | | |
10237 | | // --------------------------------------------------------------------------- |
10238 | | |
10239 | | std::list<crs::CompoundCRSNNPtr> |
10240 | | AuthorityFactory::createCompoundCRSFromExisting( |
10241 | 0 | const crs::CompoundCRSNNPtr &crs) const { |
10242 | 0 | std::list<crs::CompoundCRSNNPtr> res; |
10243 | |
|
10244 | 0 | auto lockedThisFactory(d->getSharedFromThis()); |
10245 | 0 | assert(lockedThisFactory); |
10246 | |
|
10247 | 0 | const auto &components = crs->componentReferenceSystems(); |
10248 | 0 | if (components.size() != 2) { |
10249 | 0 | return res; |
10250 | 0 | } |
10251 | 0 | auto candidatesHorizCRS = components[0]->identify(lockedThisFactory); |
10252 | 0 | auto candidatesVertCRS = components[1]->identify(lockedThisFactory); |
10253 | 0 | if (candidatesHorizCRS.empty() && candidatesVertCRS.empty()) { |
10254 | 0 | return res; |
10255 | 0 | } |
10256 | | |
10257 | 0 | std::string sql("SELECT auth_name, code FROM compound_crs WHERE " |
10258 | 0 | "deprecated = 0 AND "); |
10259 | 0 | ListOfParams params; |
10260 | 0 | bool addAnd = false; |
10261 | 0 | if (!candidatesHorizCRS.empty()) { |
10262 | 0 | sql += buildSqlLookForAuthNameCode(candidatesHorizCRS, params, |
10263 | 0 | "horiz_crs_"); |
10264 | 0 | addAnd = true; |
10265 | 0 | } |
10266 | 0 | if (!candidatesVertCRS.empty()) { |
10267 | 0 | if (addAnd) { |
10268 | 0 | sql += " AND "; |
10269 | 0 | } |
10270 | 0 | sql += buildSqlLookForAuthNameCode(candidatesVertCRS, params, |
10271 | 0 | "vertical_crs_"); |
10272 | 0 | addAnd = true; |
10273 | 0 | } |
10274 | 0 | if (d->hasAuthorityRestriction()) { |
10275 | 0 | if (addAnd) { |
10276 | 0 | sql += " AND "; |
10277 | 0 | } |
10278 | 0 | sql += "auth_name = ?"; |
10279 | 0 | params.emplace_back(d->authority()); |
10280 | 0 | } |
10281 | |
|
10282 | 0 | auto sqlRes = d->run(sql, params); |
10283 | 0 | for (const auto &row : sqlRes) { |
10284 | 0 | const auto &auth_name = row[0]; |
10285 | 0 | const auto &code = row[1]; |
10286 | 0 | res.emplace_back(d->createFactory(auth_name)->createCompoundCRS(code)); |
10287 | 0 | } |
10288 | 0 | return res; |
10289 | 0 | } |
10290 | | |
10291 | | // --------------------------------------------------------------------------- |
10292 | | |
10293 | | std::vector<operation::CoordinateOperationNNPtr> |
10294 | | AuthorityFactory::getTransformationsForGeoid( |
10295 | 100 | const std::string &geoidName, bool usePROJAlternativeGridNames) const { |
10296 | 100 | std::vector<operation::CoordinateOperationNNPtr> res; |
10297 | | |
10298 | 100 | const std::string sql("SELECT operation_auth_name, operation_code FROM " |
10299 | 100 | "geoid_model WHERE name = ?"); |
10300 | 100 | auto sqlRes = d->run(sql, {geoidName}); |
10301 | 100 | for (const auto &row : sqlRes) { |
10302 | 0 | const auto &auth_name = row[0]; |
10303 | 0 | const auto &code = row[1]; |
10304 | 0 | res.emplace_back(d->createFactory(auth_name)->createCoordinateOperation( |
10305 | 0 | code, usePROJAlternativeGridNames)); |
10306 | 0 | } |
10307 | | |
10308 | 100 | return res; |
10309 | 100 | } |
10310 | | |
10311 | | // --------------------------------------------------------------------------- |
10312 | | |
10313 | | std::vector<operation::PointMotionOperationNNPtr> |
10314 | | AuthorityFactory::getPointMotionOperationsFor( |
10315 | 9 | const crs::GeodeticCRSNNPtr &crs, bool usePROJAlternativeGridNames) const { |
10316 | 9 | std::vector<operation::PointMotionOperationNNPtr> res; |
10317 | 9 | const auto crsList = |
10318 | 9 | createGeodeticCRSFromDatum(crs->datumNonNull(d->context()), |
10319 | 9 | /* preferredAuthName = */ std::string(), |
10320 | 9 | /* geodetic_crs_type = */ std::string()); |
10321 | 9 | if (crsList.empty()) |
10322 | 1 | return res; |
10323 | 8 | std::string sql("SELECT auth_name, code FROM coordinate_operation_view " |
10324 | 8 | "WHERE source_crs_auth_name = target_crs_auth_name AND " |
10325 | 8 | "source_crs_code = target_crs_code AND deprecated = 0 AND " |
10326 | 8 | "("); |
10327 | 8 | bool addOr = false; |
10328 | 8 | ListOfParams params; |
10329 | 27 | for (const auto &candidateCrs : crsList) { |
10330 | 27 | if (addOr) |
10331 | 19 | sql += " OR "; |
10332 | 27 | addOr = true; |
10333 | 27 | sql += "(source_crs_auth_name = ? AND source_crs_code = ?)"; |
10334 | 27 | const auto &ids = candidateCrs->identifiers(); |
10335 | 27 | params.emplace_back(*(ids[0]->codeSpace())); |
10336 | 27 | params.emplace_back(ids[0]->code()); |
10337 | 27 | } |
10338 | 8 | sql += ")"; |
10339 | 8 | if (d->hasAuthorityRestriction()) { |
10340 | 0 | sql += " AND auth_name = ?"; |
10341 | 0 | params.emplace_back(d->authority()); |
10342 | 0 | } |
10343 | | |
10344 | 8 | auto sqlRes = d->run(sql, params); |
10345 | 8 | for (const auto &row : sqlRes) { |
10346 | 1 | const auto &auth_name = row[0]; |
10347 | 1 | const auto &code = row[1]; |
10348 | 1 | auto pmo = |
10349 | 1 | util::nn_dynamic_pointer_cast<operation::PointMotionOperation>( |
10350 | 1 | d->createFactory(auth_name)->createCoordinateOperation( |
10351 | 1 | code, usePROJAlternativeGridNames)); |
10352 | 1 | if (pmo) { |
10353 | 1 | res.emplace_back(NN_NO_CHECK(pmo)); |
10354 | 1 | } |
10355 | 1 | } |
10356 | 8 | return res; |
10357 | 9 | } |
10358 | | |
10359 | | //! @endcond |
10360 | | |
10361 | | // --------------------------------------------------------------------------- |
10362 | | |
10363 | | //! @cond Doxygen_Suppress |
10364 | 1.00k | FactoryException::FactoryException(const char *message) : Exception(message) {} |
10365 | | |
10366 | | // --------------------------------------------------------------------------- |
10367 | | |
10368 | | FactoryException::FactoryException(const std::string &message) |
10369 | 322 | : Exception(message) {} |
10370 | | |
10371 | | // --------------------------------------------------------------------------- |
10372 | | |
10373 | 1.33k | FactoryException::~FactoryException() = default; |
10374 | | |
10375 | | // --------------------------------------------------------------------------- |
10376 | | |
10377 | 0 | FactoryException::FactoryException(const FactoryException &) = default; |
10378 | | //! @endcond |
10379 | | |
10380 | | // --------------------------------------------------------------------------- |
10381 | | |
10382 | | //! @cond Doxygen_Suppress |
10383 | | |
10384 | | struct NoSuchAuthorityCodeException::Private { |
10385 | | std::string authority_; |
10386 | | std::string code_; |
10387 | | |
10388 | | Private(const std::string &authority, const std::string &code) |
10389 | 322 | : authority_(authority), code_(code) {} |
10390 | | }; |
10391 | | |
10392 | | // --------------------------------------------------------------------------- |
10393 | | |
10394 | | NoSuchAuthorityCodeException::NoSuchAuthorityCodeException( |
10395 | | const std::string &message, const std::string &authority, |
10396 | | const std::string &code) |
10397 | 322 | : FactoryException(message), d(std::make_unique<Private>(authority, code)) { |
10398 | 322 | } |
10399 | | |
10400 | | // --------------------------------------------------------------------------- |
10401 | | |
10402 | 322 | NoSuchAuthorityCodeException::~NoSuchAuthorityCodeException() = default; |
10403 | | |
10404 | | // --------------------------------------------------------------------------- |
10405 | | |
10406 | | NoSuchAuthorityCodeException::NoSuchAuthorityCodeException( |
10407 | | const NoSuchAuthorityCodeException &other) |
10408 | 0 | : FactoryException(other), d(std::make_unique<Private>(*(other.d))) {} |
10409 | | //! @endcond |
10410 | | |
10411 | | // --------------------------------------------------------------------------- |
10412 | | |
10413 | | /** \brief Returns authority name. */ |
10414 | 72 | const std::string &NoSuchAuthorityCodeException::getAuthority() const { |
10415 | 72 | return d->authority_; |
10416 | 72 | } |
10417 | | |
10418 | | // --------------------------------------------------------------------------- |
10419 | | |
10420 | | /** \brief Returns authority code. */ |
10421 | 72 | const std::string &NoSuchAuthorityCodeException::getAuthorityCode() const { |
10422 | 72 | return d->code_; |
10423 | 72 | } |
10424 | | |
10425 | | // --------------------------------------------------------------------------- |
10426 | | |
10427 | | } // namespace io |
10428 | | NS_PROJ_END |
10429 | | |
10430 | | // --------------------------------------------------------------------------- |
10431 | | |
10432 | 9.80k | void pj_clear_sqlite_cache() { NS_PROJ::io::SQLiteHandleCache::get().clear(); } |