From a9ef3a229c6fef5ef8a05ba521a0237f2ffa6aa6 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Dec 2018 16:23:07 +0100 Subject: Coordinate operation search: add a authority_to_authority_preference table to restrict and prioritize searches --- src/c_api.cpp | 10 +++- src/coordinateoperation.cpp | 100 +++++++++++++++++++++++++------- src/crs.cpp | 135 ++++++++++++++++++++++++++------------------ src/factory.cpp | 62 ++++++++++++++++---- 4 files changed, 219 insertions(+), 88 deletions(-) (limited to 'src') diff --git a/src/c_api.cpp b/src/c_api.cpp index fed91750..e1f34012 100644 --- a/src/c_api.cpp +++ b/src/c_api.cpp @@ -5354,9 +5354,17 @@ struct PJ_OPERATION_FACTORY_CONTEXT { * The returned object must be unreferenced with * proj_operation_factory_context_unref() after use. * + * If authority is NULL or the empty string, then coordinate + * operations from any authority will be searched, with the restrictions set + * in the authority_to_authority_preference database table. + * If authority is set to "any", then coordinate + * operations from any authority will be searched + * If authority is a non-empty string different of "any", + * then coordinate operatiosn will be searched only in that authority namespace. + * * @param ctx Context, or NULL for default context. * @param authority Name of authority to which to restrict the search of - * canidate operations. Or NULL to allow any authority. + * candidate operations. * @return Object that must be unreferenced with * proj_operation_factory_context_unref(), or NULL in * case of error. diff --git a/src/coordinateoperation.cpp b/src/coordinateoperation.cpp index 04f9bc9a..d187f2cc 100644 --- a/src/coordinateoperation.cpp +++ b/src/coordinateoperation.cpp @@ -8937,6 +8937,14 @@ CoordinateOperationContext::getIntermediateCRS() const { * If a non null authorityFactory is provided, the resulting context should * not be used simultaneously by more than one thread. * + * If authorityFactory->getAuthority() is the empty string, then coordinate + * operations from any authority will be searched, with the restrictions set + * in the authority_to_authority_preference database table. + * If authorityFactory->getAuthority() is set to "any", then coordinate + * operations from any authority will be searched + * If authorityFactory->getAuthority() is a non-empty string different of "any", + * then coordinate operatiosn will be searched only in that authority namespace. + * * @param authorityFactory Authority factory, or null if no database lookup * is allowed. * Use io::authorityFactory::create(context, std::string()) to allow all @@ -9663,6 +9671,8 @@ findOpsInRegistryDirect(const crs::CRSNNPtr &sourceCRS, const CoordinateOperationContextNNPtr &context) { const auto &authFactory = context->getAuthorityFactory(); assert(authFactory); + const auto &authFactoryName = authFactory->getAuthority(); + for (const auto &idSrc : sourceCRS->identifiers()) { const auto &srcAuthName = *(idSrc->codeSpace()); const auto &srcCode = idSrc->code(); @@ -9671,17 +9681,39 @@ findOpsInRegistryDirect(const crs::CRSNNPtr &sourceCRS, const auto &targetAuthName = *(idTarget->codeSpace()); const auto &targetCode = idTarget->code(); if (!targetAuthName.empty()) { - auto res = - authFactory->createFromCoordinateReferenceSystemCodes( - srcAuthName, srcCode, targetAuthName, targetCode, - context->getUsePROJAlternativeGridNames(), - context->getGridAvailabilityUse() == - CoordinateOperationContext:: - GridAvailabilityUse:: - DISCARD_OPERATION_IF_MISSING_GRID, - context->getDiscardSuperseded()); - if (!res.empty()) { - return res; + std::vector authorities; + if (authFactoryName == "any") { + authorities.emplace_back(); + } + if (authFactoryName.empty()) { + authorities = authFactory->databaseContext() + ->getAllowedAuthorities( + srcAuthName, targetAuthName); + if (authorities.empty()) { + authorities.emplace_back(); + } + } else { + authorities.emplace_back(authFactoryName); + } + for (const auto &authority : authorities) { + const auto tmpAuthFactory = + io::AuthorityFactory::create( + authFactory->databaseContext(), + authority == "any" ? std::string() : authority); + auto res = + tmpAuthFactory + ->createFromCoordinateReferenceSystemCodes( + srcAuthName, srcCode, targetAuthName, + targetCode, + context->getUsePROJAlternativeGridNames(), + context->getGridAvailabilityUse() == + CoordinateOperationContext:: + GridAvailabilityUse:: + DISCARD_OPERATION_IF_MISSING_GRID, + context->getDiscardSuperseded()); + if (!res.empty()) { + return res; + } } } } @@ -9706,6 +9738,8 @@ static std::vector findsOpsInRegistryWithIntermediate( const auto &authFactory = context->getAuthorityFactory(); assert(authFactory); + const auto &authFactoryName = authFactory->getAuthority(); + for (const auto &idSrc : sourceCRS->identifiers()) { const auto &srcAuthName = *(idSrc->codeSpace()); const auto &srcCode = idSrc->code(); @@ -9714,16 +9748,40 @@ static std::vector findsOpsInRegistryWithIntermediate( const auto &targetAuthName = *(idTarget->codeSpace()); const auto &targetCode = idTarget->code(); if (!targetAuthName.empty()) { - auto res = authFactory->createFromCRSCodesWithIntermediates( - srcAuthName, srcCode, targetAuthName, targetCode, - context->getUsePROJAlternativeGridNames(), - context->getGridAvailabilityUse() == - CoordinateOperationContext::GridAvailabilityUse:: - DISCARD_OPERATION_IF_MISSING_GRID, - context->getDiscardSuperseded(), - context->getIntermediateCRS()); - if (!res.empty()) { - return res; + std::vector authorities; + if (authFactoryName == "any") { + authorities.emplace_back(); + } + if (authFactoryName.empty()) { + authorities = authFactory->databaseContext() + ->getAllowedAuthorities( + srcAuthName, targetAuthName); + if (authorities.empty()) { + authorities.emplace_back(); + } + } else { + authorities.emplace_back(authFactoryName); + } + for (const auto &authority : authorities) { + const auto tmpAuthFactory = + io::AuthorityFactory::create( + authFactory->databaseContext(), + authority == "any" ? std::string() : authority); + + auto res = + tmpAuthFactory->createFromCRSCodesWithIntermediates( + srcAuthName, srcCode, targetAuthName, + targetCode, + context->getUsePROJAlternativeGridNames(), + context->getGridAvailabilityUse() == + CoordinateOperationContext:: + GridAvailabilityUse:: + DISCARD_OPERATION_IF_MISSING_GRID, + context->getDiscardSuperseded(), + context->getIntermediateCRS()); + if (!res.empty()) { + return res; + } } } } diff --git a/src/crs.cpp b/src/crs.cpp index 546cfb0a..6212f561 100644 --- a/src/crs.cpp +++ b/src/crs.cpp @@ -409,74 +409,97 @@ CRSNNPtr CRS::createBoundCRSToWGS84IfPossible( } else { geodCRS = geogCRS; } - auto l_domains = domains(); + + if (!dbContext) { + return thisAsCRS; + } + + const auto &l_domains = domains(); metadata::ExtentPtr extent; if (!l_domains.empty()) { extent = l_domains[0]->domainOfValidity(); } - try { - auto authFactory = dbContext - ? io::AuthorityFactory::create( - NN_NO_CHECK(dbContext), std::string()) - .as_nullable() - : nullptr; - auto ctxt = operation::CoordinateOperationContext::create(authFactory, - extent, 0.0); - // ctxt->setSpatialCriterion( - // operation::CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); - auto list = - operation::CoordinateOperationFactory::create()->createOperations( - NN_NO_CHECK(geodCRS), hubCRS, ctxt); - for (const auto &op : list) { - auto transf = - util::nn_dynamic_pointer_cast(op); - if (transf) { - try { - transf->getTOWGS84Parameters(); - } catch (const std::exception &) { - continue; - } - return util::nn_static_pointer_cast( - BoundCRS::create(thisAsCRS, hubCRS, NN_NO_CHECK(transf))); - } else { - auto concatenated = - dynamic_cast( - op.get()); - if (concatenated) { - // Case for EPSG:4807 / "NTF (Paris)" that is made of a - // longitude rotation followed by a Helmert - // The prime meridian shift will be accounted elsewhere - const auto &subops = concatenated->operations(); - if (subops.size() == 2) { - auto firstOpIsTransformation = - dynamic_cast( - subops[0].get()); - auto firstOpIsConversion = - dynamic_cast( - subops[0].get()); - if ((firstOpIsTransformation && - firstOpIsTransformation->isLongitudeRotation()) || - (dynamic_cast(thisAsCRS.get()) && - firstOpIsConversion)) { - transf = util::nn_dynamic_pointer_cast< - operation::Transformation>(subops[1]); - if (transf) { - try { - transf->getTOWGS84Parameters(); - } catch (const std::exception &) { - continue; + std::string crs_authority; + const auto &l_identifiers = identifiers(); + // If the object has an authority, restrict the transformations to + // come from that codespace too. This avoids for example EPSG:4269 + // (NAD83) to use a (dubious) ESRI transformation. + if (!l_identifiers.empty()) { + crs_authority = *(l_identifiers[0]->codeSpace()); + } + + auto authorities = dbContext->getAllowedAuthorities(crs_authority, "EPSG"); + if (authorities.empty()) { + authorities.emplace_back(); + } + for (const auto &authority : authorities) { + try { + + auto authFactory = io::AuthorityFactory::create( + NN_NO_CHECK(dbContext), + authority == "any" ? std::string() : authority); + auto ctxt = operation::CoordinateOperationContext::create( + authFactory, extent, 0.0); + // ctxt->setSpatialCriterion( + // operation::CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); + auto list = + operation::CoordinateOperationFactory::create() + ->createOperations(NN_NO_CHECK(geodCRS), hubCRS, ctxt); + for (const auto &op : list) { + auto transf = + util::nn_dynamic_pointer_cast( + op); + if (transf && !starts_with(transf->nameStr(), "Null geo")) { + try { + transf->getTOWGS84Parameters(); + } catch (const std::exception &) { + continue; + } + return util::nn_static_pointer_cast(BoundCRS::create( + thisAsCRS, hubCRS, NN_NO_CHECK(transf))); + } else { + auto concatenated = + dynamic_cast( + op.get()); + if (concatenated) { + // Case for EPSG:4807 / "NTF (Paris)" that is made of a + // longitude rotation followed by a Helmert + // The prime meridian shift will be accounted elsewhere + const auto &subops = concatenated->operations(); + if (subops.size() == 2) { + auto firstOpIsTransformation = + dynamic_cast( + subops[0].get()); + auto firstOpIsConversion = + dynamic_cast( + subops[0].get()); + if ((firstOpIsTransformation && + firstOpIsTransformation + ->isLongitudeRotation()) || + (dynamic_cast(thisAsCRS.get()) && + firstOpIsConversion)) { + transf = util::nn_dynamic_pointer_cast< + operation::Transformation>(subops[1]); + if (transf && + !starts_with(transf->nameStr(), + "Null geo")) { + try { + transf->getTOWGS84Parameters(); + } catch (const std::exception &) { + continue; + } + return util::nn_static_pointer_cast( + BoundCRS::create(thisAsCRS, hubCRS, + NN_NO_CHECK(transf))); } - return util::nn_static_pointer_cast( - BoundCRS::create(thisAsCRS, hubCRS, - NN_NO_CHECK(transf))); } } } } } + } catch (const std::exception &) { } - } catch (const std::exception &) { } return thisAsCRS; } diff --git a/src/factory.cpp b/src/factory.cpp index e24cee58..20701def 100644 --- a/src/factory.cpp +++ b/src/factory.cpp @@ -880,6 +880,44 @@ std::string DatabaseContext::getTextDefinition(const std::string &tableName, return res[0][0]; } +// --------------------------------------------------------------------------- + +/** \brief Return the allowed authorities when researching transformations + * between different authorities. + * + * @throw FactoryException + */ +std::vector DatabaseContext::getAllowedAuthorities( + const std::string &sourceAuthName, + const std::string &targetAuthName) const { + auto res = d->run( + "SELECT allowed_authorities FROM authority_to_authority_preference " + "WHERE source_auth_name = ? AND target_auth_name = ?", + {sourceAuthName, targetAuthName}); + if (res.empty()) { + res = d->run( + "SELECT allowed_authorities FROM authority_to_authority_preference " + "WHERE source_auth_name = ? AND target_auth_name = 'any'", + {sourceAuthName}); + } + if (res.empty()) { + res = d->run( + "SELECT allowed_authorities FROM authority_to_authority_preference " + "WHERE source_auth_name = 'any' AND target_auth_name = ?", + {targetAuthName}); + } + if (res.empty()) { + res = d->run( + "SELECT allowed_authorities FROM authority_to_authority_preference " + "WHERE source_auth_name = 'any' AND target_auth_name = 'any'", + {}); + } + if (res.empty()) { + return std::vector(); + } + return split(res[0][0], ','); +} + //! @endcond // --------------------------------------------------------------------------- @@ -947,6 +985,10 @@ struct AuthorityFactory::Private { SQLResultSet runWithCodeParam(const char *sql, const std::string &code); + bool hasAuthorityRestriction() const { + return !authority_.empty() && authority_ != "any"; + } + private: DatabaseContextNNPtr context_; std::string authority_; @@ -3097,7 +3139,7 @@ AuthorityFactory::createFromCoordinateReferenceSystemCodes( "= ? AND auth_name = ? AND code = ? AND deprecated != 1"); auto params = std::vector{sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode}; - if (!getAuthority().empty()) { + if (d->hasAuthorityRestriction()) { sql += " AND conversion_auth_name = ?"; params.emplace_back(getAuthority()); } @@ -3134,7 +3176,7 @@ AuthorityFactory::createFromCoordinateReferenceSystemCodes( } params = {sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode}; - if (!getAuthority().empty()) { + if (d->hasAuthorityRestriction()) { sql += " AND cov.auth_name = ?"; params.emplace_back(getAuthority()); } @@ -3361,7 +3403,7 @@ AuthorityFactory::createFromCRSCodesWithIntermediates( "AND v1.deprecated = 0 AND v2.deprecated = 0 " "AND intersects_bbox(south_lat1, west_lon1, north_lat1, east_lon1, " "south_lat2, west_lon2, north_lat2, east_lon2) == 1 "); - if (!getAuthority().empty()) { + if (d->hasAuthorityRestriction()) { additionalWhere += "AND v1.auth_name = ? AND v2.auth_name = ? "; params.emplace_back(getAuthority()); params.emplace_back(getAuthority()); @@ -3852,7 +3894,7 @@ AuthorityFactory::createObjectsFromName( sql += "name LIKE ? AND "; params.push_back(searchedNameWithoutDeprecated); } - if (!getAuthority().empty()) { + if (d->hasAuthorityRestriction()) { sql += " auth_name = ? AND "; params.emplace_back(getAuthority()); } @@ -4152,7 +4194,7 @@ AuthorityFactory::listAreaOfUseFromName(const std::string &name, std::string sql( "SELECT auth_name, code FROM area WHERE deprecated = 0 AND "); std::vector params; - if (!getAuthority().empty()) { + if (d->hasAuthorityRestriction()) { sql += " auth_name = ? AND "; params.emplace_back(getAuthority()); } @@ -4206,7 +4248,7 @@ std::list AuthorityFactory::createGeodeticCRSFromDatum( "SELECT auth_name, code FROM geodetic_crs WHERE " "datum_auth_name = ? AND datum_code = ? AND deprecated = 0"); std::vector params{datum_auth_name, datum_code}; - if (!getAuthority().empty()) { + if (d->hasAuthorityRestriction()) { sql += " AND auth_name = ?"; params.emplace_back(getAuthority()); } @@ -4242,7 +4284,7 @@ AuthorityFactory::createGeodeticCRSFromEllipsoid( "geodetic_datum.deprecated = 0 AND " "geodetic_crs.deprecated = 0"); std::vector params{ellipsoid_auth_name, ellipsoid_code}; - if (!getAuthority().empty()) { + if (d->hasAuthorityRestriction()) { sql += " AND geodetic_crs.auth_name = ?"; params.emplace_back(getAuthority()); } @@ -4363,7 +4405,7 @@ AuthorityFactory::createProjectedCRSFromExisting( sql += "conversion.method_auth_name = 'EPSG' AND " "conversion.method_code = ?"; params.emplace_back(toString(methodEPSGCode)); - if (!getAuthority().empty()) { + if (d->hasAuthorityRestriction()) { sql += " AND projected_crs.auth_name = ?"; params.emplace_back(getAuthority()); } @@ -4533,7 +4575,7 @@ AuthorityFactory::createProjectedCRSFromExisting( params.emplace_back(patternVal); } sql += ")"; - if (!getAuthority().empty()) { + if (d->hasAuthorityRestriction()) { sql += " AND auth_name = ?"; params.emplace_back(getAuthority()); } @@ -4597,7 +4639,7 @@ AuthorityFactory::createCompoundCRSFromExisting( "vertical_crs_"); addAnd = true; } - if (!getAuthority().empty()) { + if (d->hasAuthorityRestriction()) { if (addAnd) { sql += " AND "; } -- cgit v1.2.3 From 6afbfc737384a4f58f2d5f8bc3bde69dacf9b355 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Dec 2018 16:32:02 +0100 Subject: Fine tune axis denomination when exporting to WKT1_GDAL --- src/coordinatesystem.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/coordinatesystem.cpp b/src/coordinatesystem.cpp index f1220878..2305e6c4 100644 --- a/src/coordinatesystem.cpp +++ b/src/coordinatesystem.cpp @@ -325,7 +325,13 @@ void CoordinateSystemAxis::_exportToWKT(io::WKTFormatter *formatter, int order, axisDesignation = tolower(axisName.substr(0, 1)) + axisName.substr(1); } else { - axisDesignation = axisName; + if (axisName == "Geodetic latitude") { + axisDesignation = "Latitude"; + } else if (axisName == "Geodetic longitude") { + axisDesignation = "Longitude"; + } else { + axisDesignation = axisName; + } } } -- cgit v1.2.3 From 4022e2093a6773458c2453e42089c987da6efbf9 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Dec 2018 19:40:13 +0100 Subject: Fix special handling of Azimuth parameter of Krovak --- src/coordinateoperation.cpp | 4 +++- src/io.cpp | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/coordinateoperation.cpp b/src/coordinateoperation.cpp index d187f2cc..ced0ab9f 100644 --- a/src/coordinateoperation.cpp +++ b/src/coordinateoperation.cpp @@ -5177,7 +5177,9 @@ void Conversion::_exportToPROJString( double latitudePseudoStandardParallel = parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL, common::UnitOfMeasure::DEGREE); - if (std::fabs(colatitude - 30.28813972222222) > 1e-8) { + // 30deg 17' 17.30311'' = 30.28813975277777776 + // 30deg 17' 17.303'' = 30.288139722222223 as used in GDAL WKT1 + if (std::fabs(colatitude - 30.2881397) > 1e-7) { throw io::FormattingException( std::string("Unsupported value for ") + EPSG_NAME_PARAMETER_COLATITUDE_CONE_AXIS); diff --git a/src/io.cpp b/src/io.cpp index f396f1df..ec35bdc5 100644 --- a/src/io.cpp +++ b/src/io.cpp @@ -6674,7 +6674,7 @@ CRSNNPtr PROJStringParser::Private::buildProjectedCRS( } else if (step.name == "krovak") { if (param->epsg_code == EPSG_CODE_PARAMETER_COLATITUDE_CONE_AXIS) { - value = 30.2881397222222; + value = 30.28813975277777776; } else if ( param->epsg_code == EPSG_CODE_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL) { -- cgit v1.2.3 From f06045c2f0145ec2290913fa144cd690e70736fd Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Dec 2018 21:28:16 +0100 Subject: Add API to retrieve non-deprecated equivalent of an object --- src/c_api.cpp | 30 ++++++++++++++++++++++++++++++ src/crs.cpp | 34 ++++++++++++++++++++++++++++++++++ src/factory.cpp | 32 ++++++++++++++++++++++++++++++++ src/proj.h | 3 +++ 4 files changed, 99 insertions(+) (limited to 'src') diff --git a/src/c_api.cpp b/src/c_api.cpp index e1f34012..78ca1c24 100644 --- a/src/c_api.cpp +++ b/src/c_api.cpp @@ -791,6 +791,36 @@ int proj_obj_is_deprecated(const PJ_OBJ *obj) { // --------------------------------------------------------------------------- +/** \brief Return a list of non-deprecated objects related to the passed one + * + * @param ctx Context, or NULL for default context. + * @param obj Object (of type CRS for now) for which non-deprecated objects + * must be searched. Must not be NULL + * @return a result set that must be unreferenced with + * proj_obj_list_unref(), or NULL in case of error. + */ +PJ_OBJ_LIST *proj_obj_get_non_deprecated(PJ_CONTEXT *ctx, const PJ_OBJ *obj) { + assert(obj); + SANITIZE_CTX(ctx); + auto crs = dynamic_cast(obj->obj.get()); + if (!crs) { + return nullptr; + } + try { + std::vector objects; + auto res = crs->getNonDeprecated(getDBcontext(ctx)); + for (const auto &resObj : res) { + objects.push_back(resObj); + } + return new PJ_OBJ_LIST(std::move(objects)); + } catch (const std::exception &e) { + proj_log_error(ctx, __FUNCTION__, e.what()); + } + return nullptr; +} + +// --------------------------------------------------------------------------- + /** \brief Return whether two objects are equivalent. * * @param obj Object (must not be NULL) diff --git a/src/crs.cpp b/src/crs.cpp index 6212f561..81e9a300 100644 --- a/src/crs.cpp +++ b/src/crs.cpp @@ -603,6 +603,40 @@ CRS::identify(const io::AuthorityFactoryPtr &authorityFactory) const { // --------------------------------------------------------------------------- +/** \brief Return CRSs that are non-deprecated substitutes for the current CRS. + */ +std::list +CRS::getNonDeprecated(const io::DatabaseContextNNPtr &dbContext) const { + std::list res; + const auto &l_identifiers = identifiers(); + if (l_identifiers.empty()) { + return res; + } + const char *tableName = nullptr; + if (dynamic_cast(this)) { + tableName = "geodetic_crs"; + } else if (dynamic_cast(this)) { + tableName = "projected_crs"; + } else if (dynamic_cast(this)) { + tableName = "vertical_crs"; + } else if (dynamic_cast(this)) { + tableName = "compound_crs"; + } + if (!tableName) { + return res; + } + const auto &id = l_identifiers[0]; + auto tmpRes = + dbContext->getNonDeprecated(tableName, *(id->codeSpace()), id->code()); + for (const auto &pair : tmpRes) { + res.emplace_back(io::AuthorityFactory::create(dbContext, pair.first) + ->createCoordinateReferenceSystem(pair.second)); + } + return res; +} + +// --------------------------------------------------------------------------- + //! @cond Doxygen_Suppress std::list> diff --git a/src/factory.cpp b/src/factory.cpp index 20701def..d56fb7b6 100644 --- a/src/factory.cpp +++ b/src/factory.cpp @@ -918,6 +918,38 @@ std::vector DatabaseContext::getAllowedAuthorities( return split(res[0][0], ','); } +// --------------------------------------------------------------------------- + +std::list> +DatabaseContext::getNonDeprecated(const std::string &tableName, + const std::string &authName, + const std::string &code) const { + auto sqlRes = + d->run("SELECT replacement_auth_name, replacement_code, source " + "FROM deprecation " + "WHERE table_name = ? AND deprecated_auth_name = ? " + "AND deprecated_code = ?", + {tableName, authName, code}); + std::list> res; + for (const auto &row : sqlRes) { + const auto &source = row[2]; + if (source == "PROJ") { + const auto &replacement_auth_name = row[0]; + const auto &replacement_code = row[1]; + res.emplace_back(replacement_auth_name, replacement_code); + } + } + if (!res.empty()) { + return res; + } + for (const auto &row : sqlRes) { + const auto &replacement_auth_name = row[0]; + const auto &replacement_code = row[1]; + res.emplace_back(replacement_auth_name, replacement_code); + } + return res; +} + //! @endcond // --------------------------------------------------------------------------- diff --git a/src/proj.h b/src/proj.h index c41a2770..cce371d4 100644 --- a/src/proj.h +++ b/src/proj.h @@ -572,6 +572,9 @@ PJ_OBJ_TYPE PROJ_DLL proj_obj_get_type(const PJ_OBJ *obj); int PROJ_DLL proj_obj_is_deprecated(const PJ_OBJ *obj); +PJ_OBJ_LIST PROJ_DLL *proj_obj_get_non_deprecated(PJ_CONTEXT *ctx, + const PJ_OBJ *obj); + /** Comparison criterion. */ typedef enum { -- cgit v1.2.3 From 67ca5c199dfe62fc0738a808f3142af2e77eafd7 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Dec 2018 22:10:57 +0100 Subject: projinfo: display deprecation info --- src/projinfo.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'src') diff --git a/src/projinfo.cpp b/src/projinfo.cpp index ddcc09da..ba19b8d2 100644 --- a/src/projinfo.cpp +++ b/src/projinfo.cpp @@ -37,6 +37,7 @@ #include "projects.h" +#include #include #include #include @@ -45,6 +46,7 @@ #include "proj/internal/internal.hpp" // for split +using namespace NS_PROJ::common; using namespace NS_PROJ::crs; using namespace NS_PROJ::io; using namespace NS_PROJ::metadata; @@ -201,6 +203,30 @@ static BaseObjectNNPtr buildObject(DatabaseContextPtr dbContext, static void outputObject(DatabaseContextPtr dbContext, BaseObjectNNPtr obj, const OutputOptions &outputOpt) { + + auto identified = dynamic_cast(obj.get()); + if (!outputOpt.quiet && identified && identified->isDeprecated()) { + std::cout << "Warning: object is deprecated" << std::endl; + auto crs = dynamic_cast(obj.get()); + if (crs && dbContext) { + try { + auto list = crs->getNonDeprecated(NN_NO_CHECK(dbContext)); + if (!list.empty()) { + std::cout << "Alternative non-deprecated CRS:" << std::endl; + } + for (const auto &altCRS : list) { + const auto &ids = altCRS->identifiers(); + if (!ids.empty()) { + std::cout << " " << *(ids[0]->codeSpace()) << ":" + << ids[0]->code() << std::endl; + } + } + } catch (const std::exception &) { + } + } + std::cout << std::endl; + } + auto projStringExportable = nn_dynamic_pointer_cast(obj); bool alreadyOutputed = false; -- cgit v1.2.3 From cae698abe380b3823c3f08151c25097031ae091f Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 6 Dec 2018 22:51:27 +0100 Subject: Speed-up createBoundCRSToWGS84IfPossible() --- src/c_api.cpp | 26 +++++++++++++++++++++++--- src/crs.cpp | 6 ++++-- src/proj_experimental.h | 3 ++- src/projinfo.cpp | 26 +++++++++++++++----------- 4 files changed, 44 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/c_api.cpp b/src/c_api.cpp index 78ca1c24..03a0c0bd 100644 --- a/src/c_api.cpp +++ b/src/c_api.cpp @@ -1319,11 +1319,19 @@ PJ_OBJ *proj_obj_crs_create_bound_crs(PJ_CONTEXT *ctx, const PJ_OBJ *base_crs, * * @param ctx PROJ context, or NULL for default context * @param crs Objet of type CRS (must not be NULL) + * @param options null-terminated list of options, or NULL. Currently + * supported options are: + *
    + *
  • ALLOW_INTERMEDIATE_CRS=YES/NO. Defaults to NO. When set to YES, + * intermediate CRS may be considered when computing the possible + * tranformations. Slower.
  • + *
* @return Object that must be unreferenced with proj_obj_unref(), or NULL * in case of error. */ PJ_OBJ *proj_obj_crs_create_bound_crs_to_WGS84(PJ_CONTEXT *ctx, - const PJ_OBJ *crs) { + const PJ_OBJ *crs, + const char *const *options) { SANITIZE_CTX(ctx); assert(crs); auto l_crs = dynamic_cast(crs->obj.get()); @@ -1333,8 +1341,20 @@ PJ_OBJ *proj_obj_crs_create_bound_crs_to_WGS84(PJ_CONTEXT *ctx, } auto dbContext = getDBcontextNoException(ctx, __FUNCTION__); try { - return PJ_OBJ::create( - l_crs->createBoundCRSToWGS84IfPossible(dbContext)); + bool allowIntermediateCRS = false; + for (auto iter = options; iter && iter[0]; ++iter) { + const char *value; + if ((value = getOptionValue(*iter, "ALLOW_INTERMEDIATE_CRS="))) { + allowIntermediateCRS = ci_equal(value, "YES"); + } else { + std::string msg("Unknown option :"); + msg += *iter; + proj_log_error(ctx, __FUNCTION__, msg.c_str()); + return nullptr; + } + } + return PJ_OBJ::create(l_crs->createBoundCRSToWGS84IfPossible( + dbContext, allowIntermediateCRS)); } catch (const std::exception &e) { proj_log_error(ctx, __FUNCTION__, e.what()); return nullptr; diff --git a/src/crs.cpp b/src/crs.cpp index 81e9a300..639fc3a9 100644 --- a/src/crs.cpp +++ b/src/crs.cpp @@ -375,8 +375,9 @@ VerticalCRSPtr CRS::extractVerticalCRS() const { * * @return a CRS. */ -CRSNNPtr CRS::createBoundCRSToWGS84IfPossible( - const io::DatabaseContextPtr &dbContext) const { +CRSNNPtr +CRS::createBoundCRSToWGS84IfPossible(const io::DatabaseContextPtr &dbContext, + bool allowIntermediateCRS) const { auto thisAsCRS = NN_NO_CHECK( std::static_pointer_cast(shared_from_this().as_nullable())); auto boundCRS = util::nn_dynamic_pointer_cast(thisAsCRS); @@ -441,6 +442,7 @@ CRSNNPtr CRS::createBoundCRSToWGS84IfPossible( authority == "any" ? std::string() : authority); auto ctxt = operation::CoordinateOperationContext::create( authFactory, extent, 0.0); + ctxt->setAllowUseIntermediateCRS(allowIntermediateCRS); // ctxt->setSpatialCriterion( // operation::CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = diff --git a/src/proj_experimental.h b/src/proj_experimental.h index b8c37054..9af7c389 100644 --- a/src/proj_experimental.h +++ b/src/proj_experimental.h @@ -244,7 +244,8 @@ PJ_OBJ PROJ_DLL *proj_obj_crs_create_bound_crs(PJ_CONTEXT *ctx, const PJ_OBJ *transformation); PJ_OBJ PROJ_DLL *proj_obj_crs_create_bound_crs_to_WGS84(PJ_CONTEXT *ctx, - const PJ_OBJ *crs); + const PJ_OBJ *crs, + const char *const *options); /* BEGIN: Generated by scripts/create_c_api_projections.py*/ PJ_OBJ PROJ_DLL *proj_obj_create_conversion_utm( diff --git a/src/projinfo.cpp b/src/projinfo.cpp index ba19b8d2..d6fa37bc 100644 --- a/src/projinfo.cpp +++ b/src/projinfo.cpp @@ -136,7 +136,8 @@ static std::string c_ify_string(const std::string &str) { static BaseObjectNNPtr buildObject(DatabaseContextPtr dbContext, const std::string &user_string, bool kindIsCRS, const std::string &context, - bool buildBoundCRSToWGS84) { + bool buildBoundCRSToWGS84, + bool allowPivots) { BaseObjectPtr obj; std::string l_user_string(user_string); @@ -192,7 +193,8 @@ static BaseObjectNNPtr buildObject(DatabaseContextPtr dbContext, if (buildBoundCRSToWGS84) { auto crs = std::dynamic_pointer_cast(obj); if (crs) { - obj = crs->createBoundCRSToWGS84IfPossible(dbContext).as_nullable(); + obj = crs->createBoundCRSToWGS84IfPossible(dbContext, allowPivots) + .as_nullable(); } } @@ -202,7 +204,7 @@ static BaseObjectNNPtr buildObject(DatabaseContextPtr dbContext, // --------------------------------------------------------------------------- static void outputObject(DatabaseContextPtr dbContext, BaseObjectNNPtr obj, - const OutputOptions &outputOpt) { + bool allowPivots, const OutputOptions &outputOpt) { auto identified = dynamic_cast(obj.get()); if (!outputOpt.quiet && identified && identified->isDeprecated()) { @@ -263,7 +265,8 @@ static void outputObject(DatabaseContextPtr dbContext, BaseObjectNNPtr obj, if (crs) { objToExport = nn_dynamic_pointer_cast( - crs->createBoundCRSToWGS84IfPossible(dbContext)); + crs->createBoundCRSToWGS84IfPossible(dbContext, + allowPivots)); } if (!objToExport) { objToExport = projStringExportable; @@ -398,7 +401,8 @@ static void outputObject(DatabaseContextPtr dbContext, BaseObjectNNPtr obj, std::shared_ptr objToExport; if (crs) { objToExport = nn_dynamic_pointer_cast( - crs->createBoundCRSToWGS84IfPossible(dbContext)); + crs->createBoundCRSToWGS84IfPossible(dbContext, + allowPivots)); } if (!objToExport) { objToExport = wktExportable; @@ -506,7 +510,7 @@ static void outputOperations( const std::string &authority, bool usePROJGridAlternatives, bool showSuperseded, const OutputOptions &outputOpt, bool summary) { auto sourceObj = - buildObject(dbContext, sourceCRSStr, true, "source CRS", false); + buildObject(dbContext, sourceCRSStr, true, "source CRS", false, false); auto sourceCRS = nn_dynamic_pointer_cast(sourceObj); if (!sourceCRS) { std::cerr << "source CRS string is not a CRS" << std::endl; @@ -514,7 +518,7 @@ static void outputOperations( } auto targetObj = - buildObject(dbContext, targetCRSStr, true, "target CRS", false); + buildObject(dbContext, targetCRSStr, true, "target CRS", false, false); auto targetCRS = nn_dynamic_pointer_cast(targetObj); if (!targetCRS) { std::cerr << "target CRS string is not a CRS" << std::endl; @@ -545,7 +549,7 @@ static void outputOperations( std::exit(1); } if (outputOpt.quiet && !list.empty()) { - outputObject(dbContext, list[0], outputOpt); + outputObject(dbContext, list[0], allowPivots, outputOpt); return; } if (summary) { @@ -571,7 +575,7 @@ static void outputOperations( } outputOperationSummary(op); std::cout << std::endl; - outputObject(dbContext, op, outputOpt); + outputObject(dbContext, op, allowPivots, outputOpt); } } } @@ -906,7 +910,7 @@ int main(int argc, char **argv) { if (!user_string.empty()) { auto obj(buildObject(dbContext, user_string, kindIsCRS, "input string", - buildBoundCRSToWGS84)); + buildBoundCRSToWGS84, allowPivots)); if (guessDialect) { auto dialect = WKTParser().guessDialect(user_string); std::cout << "Guessed WKT dialect: "; @@ -923,7 +927,7 @@ int main(int argc, char **argv) { } std::cout << std::endl; } - outputObject(dbContext, obj, outputOpt); + outputObject(dbContext, obj, allowPivots, outputOpt); if (identify) { auto crs = dynamic_cast(obj.get()); if (crs) { -- cgit v1.2.3 From 263b259b276edd075b0abcd6aad0e923230c2d15 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Fri, 7 Dec 2018 02:22:20 +0100 Subject: Various speed optimizations --- src/common.cpp | 80 ++-- src/coordinateoperation.cpp | 10 +- src/crs.cpp | 19 +- src/factory.cpp | 915 ++++++++++++++++++++++++++------------------ src/internal.cpp | 33 ++ src/io.cpp | 23 +- src/metadata.cpp | 70 ++-- src/util.cpp | 104 +++-- 8 files changed, 733 insertions(+), 521 deletions(-) (limited to 'src') diff --git a/src/common.cpp b/src/common.cpp index 94bc8678..2a9d17c7 100644 --- a/src/common.cpp +++ b/src/common.cpp @@ -650,23 +650,20 @@ bool IdentifiedObject::isDeprecated() PROJ_CONST_DEFN { void IdentifiedObject::Private::setName( const PropertyMap &properties) // throw(InvalidValueTypeException) { - auto oIter = properties.find(NAME_KEY); - if (oIter == properties.end()) { + const auto pVal = properties.get(NAME_KEY); + if (!pVal) { return; } - if (auto genVal = - util::nn_dynamic_pointer_cast(oIter->second)) { + if (const auto genVal = dynamic_cast(pVal->get())) { if (genVal->type() == BoxedValue::Type::STRING) { - name = Identifier::create( - std::string(), PropertyMap().set(Identifier::DESCRIPTION_KEY, - genVal->stringValue())); + name = Identifier::createFromDescription(genVal->stringValue()); } else { throw InvalidValueTypeException("Invalid value type for " + NAME_KEY); } } else { if (auto identifier = - util::nn_dynamic_pointer_cast(oIter->second)) { + util::nn_dynamic_pointer_cast(*pVal)) { name = NN_NO_CHECK(identifier); } else { throw InvalidValueTypeException("Invalid value type for " + @@ -680,23 +677,21 @@ void IdentifiedObject::Private::setName( void IdentifiedObject::Private::setIdentifiers( const PropertyMap &properties) // throw(InvalidValueTypeException) { - auto oIter = properties.find(IDENTIFIERS_KEY); - if (oIter == properties.end()) { + auto pVal = properties.get(IDENTIFIERS_KEY); + if (!pVal) { - oIter = properties.find(Identifier::CODE_KEY); - if (oIter != properties.end()) { + pVal = properties.get(Identifier::CODE_KEY); + if (pVal) { identifiers.push_back( Identifier::create(std::string(), properties)); } return; } - if (auto identifier = - util::nn_dynamic_pointer_cast(oIter->second)) { + if (auto identifier = util::nn_dynamic_pointer_cast(*pVal)) { identifiers.clear(); identifiers.push_back(NN_NO_CHECK(identifier)); } else { - if (auto array = util::nn_dynamic_pointer_cast( - oIter->second)) { + if (auto array = dynamic_cast(pVal->get())) { identifiers.clear(); for (const auto &val : *array) { identifier = util::nn_dynamic_pointer_cast(val); @@ -719,17 +714,16 @@ void IdentifiedObject::Private::setIdentifiers( void IdentifiedObject::Private::setAliases( const PropertyMap &properties) // throw(InvalidValueTypeException) { - auto oIter = properties.find(ALIAS_KEY); - if (oIter == properties.end()) { + const auto pVal = properties.get(ALIAS_KEY); + if (!pVal) { return; } - if (auto l_name = - util::nn_dynamic_pointer_cast(oIter->second)) { + if (auto l_name = util::nn_dynamic_pointer_cast(*pVal)) { aliases.clear(); aliases.push_back(NN_NO_CHECK(l_name)); } else { - if (auto array = util::nn_dynamic_pointer_cast( - oIter->second)) { + if (const auto array = + dynamic_cast(pVal->get())) { aliases.clear(); for (const auto &val : *array) { l_name = util::nn_dynamic_pointer_cast(val); @@ -737,7 +731,7 @@ void IdentifiedObject::Private::setAliases( aliases.push_back(NN_NO_CHECK(l_name)); } else { if (auto genVal = - util::nn_dynamic_pointer_cast(val)) { + dynamic_cast(val.get())) { if (genVal->type() == BoxedValue::Type::STRING) { aliases.push_back(NameFactory::createLocalName( nullptr, genVal->stringValue())); @@ -777,10 +771,10 @@ void IdentifiedObject::setProperties( properties.getStringValue(REMARKS_KEY, d->remarks); { - auto oIter = properties.find(DEPRECATED_KEY); - if (oIter != properties.end()) { - if (auto genVal = - util::nn_dynamic_pointer_cast(oIter->second)) { + const auto pVal = properties.get(DEPRECATED_KEY); + if (pVal) { + if (const auto genVal = + dynamic_cast(pVal->get())) { if (genVal->type() == BoxedValue::Type::BOOLEAN) { d->isDeprecated = genVal->booleanValue(); } else { @@ -930,8 +924,8 @@ void ObjectDomain::_exportToWKT(WKTFormatter *formatter) const { formatter->endNode(); } if (d->domainOfValidity_->geographicElements().size() == 1) { - auto bbox = util::nn_dynamic_pointer_cast( - d->domainOfValidity_->geographicElements()[0]); + const auto bbox = dynamic_cast( + d->domainOfValidity_->geographicElements()[0].get()); if (bbox) { formatter->startNode(WKTConstants::BBOX, false); formatter->add(bbox->southBoundLatitude()); @@ -1029,19 +1023,13 @@ void ObjectUsage::setProperties( IdentifiedObject::setProperties(properties); optional scope; - { - std::string temp; - if (properties.getStringValue(SCOPE_KEY, temp)) { - scope = temp; - } - } + properties.getStringValue(SCOPE_KEY, scope); ExtentPtr domainOfValidity; { - auto oIter = properties.find(DOMAIN_OF_VALIDITY_KEY); - if (oIter != properties.end()) { - domainOfValidity = - util::nn_dynamic_pointer_cast(oIter->second); + const auto pVal = properties.get(DOMAIN_OF_VALIDITY_KEY); + if (pVal) { + domainOfValidity = util::nn_dynamic_pointer_cast(*pVal); if (!domainOfValidity) { throw InvalidValueTypeException("Invalid value type for " + DOMAIN_OF_VALIDITY_KEY); @@ -1054,14 +1042,14 @@ void ObjectUsage::setProperties( } { - auto oIter = properties.find(OBJECT_DOMAIN_KEY); - if (oIter != properties.end()) { - if (auto objectDomain = util::nn_dynamic_pointer_cast( - oIter->second)) { + const auto pVal = properties.get(OBJECT_DOMAIN_KEY); + if (pVal) { + if (auto objectDomain = + util::nn_dynamic_pointer_cast(*pVal)) { d->domains_.emplace_back(NN_NO_CHECK(objectDomain)); - } else if (auto array = - util::nn_dynamic_pointer_cast( - oIter->second)) { + } else if (const auto array = + dynamic_cast( + pVal->get())) { for (const auto &val : *array) { objectDomain = util::nn_dynamic_pointer_cast(val); diff --git a/src/coordinateoperation.cpp b/src/coordinateoperation.cpp index ced0ab9f..8f75864e 100644 --- a/src/coordinateoperation.cpp +++ b/src/coordinateoperation.cpp @@ -2055,8 +2055,7 @@ static util::PropertyMap createMethodMapNameEPSGCode(int code) { static util::PropertyMap getUTMConversionProperty(const util::PropertyMap &properties, int zone, bool north) { - if (properties.find(common::IdentifiedObject::NAME_KEY) == - properties.end()) { + if (!properties.get(common::IdentifiedObject::NAME_KEY)) { std::string conversionName("UTM zone "); conversionName += toString(zone); conversionName += (north ? 'N' : 'S'); @@ -2073,8 +2072,7 @@ getUTMConversionProperty(const util::PropertyMap &properties, int zone, static util::PropertyMap addDefaultNameIfNeeded(const util::PropertyMap &properties, const std::string &defaultName) { - if (properties.find(common::IdentifiedObject::NAME_KEY) == - properties.end()) { + if (!properties.get(common::IdentifiedObject::NAME_KEY)) { return util::PropertyMap(properties) .set(common::IdentifiedObject::NAME_KEY, defaultName); } else { @@ -9579,6 +9577,10 @@ struct FilterAndSort { // cppcheck-suppress functionStatic void removeDuplicateOps() { + if (res.size() <= 1) { + return; + } + // When going from EPSG:4807 (NTF Paris) to EPSG:4171 (RGC93), we get // EPSG:7811, NTF (Paris) to RGF93 (2), 1 m // and unknown id, NTF (Paris) to NTF (1) + Inverse of RGF93 to NTF (2), diff --git a/src/crs.cpp b/src/crs.cpp index 639fc3a9..572fae5d 100644 --- a/src/crs.cpp +++ b/src/crs.cpp @@ -92,10 +92,10 @@ struct CRS::Private { bool implicitCS_ = false; void setImplicitCS(const util::PropertyMap &properties) { - auto oIter = properties.find("IMPLICIT_CS"); - if (oIter != properties.end()) { - if (auto genVal = util::nn_dynamic_pointer_cast( - oIter->second)) { + const auto pVal = properties.get("IMPLICIT_CS"); + if (pVal) { + if (const auto genVal = + dynamic_cast(pVal->get())) { if (genVal->type() == util::BoxedValue::Type::BOOLEAN && genVal->booleanValue()) { implicitCS_ = true; @@ -3226,8 +3226,7 @@ CompoundCRSNNPtr CompoundCRS::create(const util::PropertyMap &properties, auto compoundCRS(CompoundCRS::nn_make_shared(components)); compoundCRS->assignSelf(compoundCRS); compoundCRS->setProperties(properties); - if (properties.find(common::IdentifiedObject::NAME_KEY) == - properties.end()) { + if (!properties.get(common::IdentifiedObject::NAME_KEY)) { std::string name; for (const auto &crs : components) { if (!name.empty()) { @@ -4518,10 +4517,10 @@ EngineeringCRS::create(const util::PropertyMap &properties, crs->assignSelf(crs); crs->setProperties(properties); - auto oIter = properties.find("FORCE_OUTPUT_CS"); - if (oIter != properties.end()) { - if (auto genVal = util::nn_dynamic_pointer_cast( - oIter->second)) { + const auto pVal = properties.get("FORCE_OUTPUT_CS"); + if (pVal) { + if (const auto genVal = + dynamic_cast(pVal->get())) { if (genVal->type() == util::BoxedValue::Type::BOOLEAN && genVal->booleanValue()) { crs->d->forceOutputCS_ = true; diff --git a/src/factory.cpp b/src/factory.cpp index d56fb7b6..39679082 100644 --- a/src/factory.cpp +++ b/src/factory.cpp @@ -108,7 +108,8 @@ struct SQLValues { // --------------------------------------------------------------------------- using SQLRow = std::vector; -using SQLResultSet = std::vector; +using SQLResultSet = std::list; +using ListOfParams = std::list; // --------------------------------------------------------------------------- @@ -124,9 +125,8 @@ struct DatabaseContext::Private { PJ_CONTEXT *pjCtxt() const { return pjCtxt_; } void setPjCtxt(PJ_CONTEXT *ctxt) { pjCtxt_ = ctxt; } - SQLResultSet - run(const std::string &sql, - const std::vector ¶meters = std::vector()); + SQLResultSet run(const std::string &sql, + const ListOfParams ¶meters = ListOfParams()); std::vector getDatabaseStructure(); @@ -160,6 +160,48 @@ struct DatabaseContext::Private { return mapCanonicalizeGRFName_; } + // cppcheck-suppress functionStatic + common::UnitOfMeasurePtr getUOMFromCache(const std::string &code); + // cppcheck-suppress functionStatic + void cache(const std::string &code, const common::UnitOfMeasureNNPtr &uom); + + // cppcheck-suppress functionStatic + crs::CRSPtr getCRSFromCache(const std::string &code); + // cppcheck-suppress functionStatic + void cache(const std::string &code, const crs::CRSNNPtr &crs); + + datum::GeodeticReferenceFramePtr + // cppcheck-suppress functionStatic + getGeodeticDatumFromCache(const std::string &code); + // cppcheck-suppress functionStatic + void cache(const std::string &code, + const datum::GeodeticReferenceFrameNNPtr &datum); + + datum::PrimeMeridianPtr + // cppcheck-suppress functionStatic + getPrimeMeridianFromCache(const std::string &code); + // cppcheck-suppress functionStatic + void cache(const std::string &code, const datum::PrimeMeridianNNPtr &pm); + + // cppcheck-suppress functionStatic + cs::CoordinateSystemPtr + getCoordinateSystemFromCache(const std::string &code); + // cppcheck-suppress functionStatic + void cache(const std::string &code, const cs::CoordinateSystemNNPtr &cs); + + // cppcheck-suppress functionStatic + metadata::ExtentPtr getExtentFromCache(const std::string &code); + // cppcheck-suppress functionStatic + void cache(const std::string &code, const metadata::ExtentNNPtr &extent); + + // cppcheck-suppress functionStatic + bool getCRSToCRSCoordOpFromCache( + const std::string &code, + std::vector &list); + // cppcheck-suppress functionStatic + void cache(const std::string &code, + const std::vector &list); + private: friend class DatabaseContext; @@ -173,6 +215,25 @@ struct DatabaseContext::Private { std::string lastMetadataValue_{}; std::map> mapCanonicalizeGRFName_{}; + using LRUCacheOfObjects = lru11::Cache; + + static constexpr size_t CACHE_SIZE = 128; + LRUCacheOfObjects cacheUOM_{CACHE_SIZE}; + LRUCacheOfObjects cacheCRS_{CACHE_SIZE}; + LRUCacheOfObjects cacheGeodeticDatum_{CACHE_SIZE}; + LRUCacheOfObjects cachePrimeMeridian_{CACHE_SIZE}; + LRUCacheOfObjects cacheCS_{CACHE_SIZE}; + LRUCacheOfObjects cacheExtent_{CACHE_SIZE}; + lru11::Cache> + cacheCRSToCrsCoordOp_{CACHE_SIZE}; + + static void insertIntoCache(LRUCacheOfObjects &cache, + const std::string &code, + const util::BaseObjectPtr &obj); + + static void getFromCache(LRUCacheOfObjects &cache, const std::string &code, + util::BaseObjectPtr &obj); + void closeDB(); // cppcheck-suppress functionStatic @@ -240,6 +301,133 @@ void DatabaseContext::Private::closeDB() { // --------------------------------------------------------------------------- +void DatabaseContext::Private::insertIntoCache(LRUCacheOfObjects &cache, + const std::string &code, + const util::BaseObjectPtr &obj) { + cache.insert(code, obj); +} + +// --------------------------------------------------------------------------- + +void DatabaseContext::Private::getFromCache(LRUCacheOfObjects &cache, + const std::string &code, + util::BaseObjectPtr &obj) { + cache.tryGet(code, obj); +} + +// --------------------------------------------------------------------------- + +bool DatabaseContext::Private::getCRSToCRSCoordOpFromCache( + const std::string &code, + std::vector &list) { + return cacheCRSToCrsCoordOp_.tryGet(code, list); +} + +// --------------------------------------------------------------------------- + +void DatabaseContext::Private::cache( + const std::string &code, + const std::vector &list) { + cacheCRSToCrsCoordOp_.insert(code, list); +} + +// --------------------------------------------------------------------------- + +crs::CRSPtr DatabaseContext::Private::getCRSFromCache(const std::string &code) { + util::BaseObjectPtr obj; + getFromCache(cacheCRS_, code, obj); + return std::static_pointer_cast(obj); +} + +// --------------------------------------------------------------------------- + +void DatabaseContext::Private::cache(const std::string &code, + const crs::CRSNNPtr &crs) { + insertIntoCache(cacheCRS_, code, crs.as_nullable()); +} + +// --------------------------------------------------------------------------- + +common::UnitOfMeasurePtr +DatabaseContext::Private::getUOMFromCache(const std::string &code) { + util::BaseObjectPtr obj; + getFromCache(cacheUOM_, code, obj); + return std::static_pointer_cast(obj); +} + +// --------------------------------------------------------------------------- + +void DatabaseContext::Private::cache(const std::string &code, + const common::UnitOfMeasureNNPtr &uom) { + insertIntoCache(cacheUOM_, code, uom.as_nullable()); +} + +// --------------------------------------------------------------------------- + +datum::GeodeticReferenceFramePtr +DatabaseContext::Private::getGeodeticDatumFromCache(const std::string &code) { + util::BaseObjectPtr obj; + getFromCache(cacheGeodeticDatum_, code, obj); + return std::static_pointer_cast(obj); +} + +// --------------------------------------------------------------------------- + +void DatabaseContext::Private::cache( + const std::string &code, const datum::GeodeticReferenceFrameNNPtr &datum) { + insertIntoCache(cacheGeodeticDatum_, code, datum.as_nullable()); +} + +// --------------------------------------------------------------------------- + +datum::PrimeMeridianPtr +DatabaseContext::Private::getPrimeMeridianFromCache(const std::string &code) { + util::BaseObjectPtr obj; + getFromCache(cachePrimeMeridian_, code, obj); + return std::static_pointer_cast(obj); +} + +// --------------------------------------------------------------------------- + +void DatabaseContext::Private::cache(const std::string &code, + const datum::PrimeMeridianNNPtr &pm) { + insertIntoCache(cachePrimeMeridian_, code, pm.as_nullable()); +} + +// --------------------------------------------------------------------------- + +cs::CoordinateSystemPtr DatabaseContext::Private::getCoordinateSystemFromCache( + const std::string &code) { + util::BaseObjectPtr obj; + getFromCache(cacheCS_, code, obj); + return std::static_pointer_cast(obj); +} + +// --------------------------------------------------------------------------- + +void DatabaseContext::Private::cache(const std::string &code, + const cs::CoordinateSystemNNPtr &cs) { + insertIntoCache(cacheCS_, code, cs.as_nullable()); +} + +// --------------------------------------------------------------------------- + +metadata::ExtentPtr +DatabaseContext::Private::getExtentFromCache(const std::string &code) { + util::BaseObjectPtr obj; + getFromCache(cacheExtent_, code, obj); + return std::static_pointer_cast(obj); +} + +// --------------------------------------------------------------------------- + +void DatabaseContext::Private::cache(const std::string &code, + const metadata::ExtentNNPtr &extent) { + insertIntoCache(cacheExtent_, code, extent.as_nullable()); +} + +// --------------------------------------------------------------------------- + #ifdef ENABLE_CUSTOM_LOCKLESS_VFS typedef int (*ClosePtr)(sqlite3_file *); @@ -564,9 +752,8 @@ void DatabaseContext::Private::registerFunctions() { // --------------------------------------------------------------------------- -SQLResultSet -DatabaseContext::Private::run(const std::string &sql, - const std::vector ¶meters) { +SQLResultSet DatabaseContext::Private::run(const std::string &sql, + const ListOfParams ¶meters) { sqlite3_stmt *stmt = nullptr; auto iter = mapSqlToStatement_.find(sql); @@ -603,13 +790,15 @@ DatabaseContext::Private::run(const std::string &sql, while (true) { int ret = sqlite3_step(stmt); if (ret == SQLITE_ROW) { - SQLRow row; + SQLRow row(column_count); for (int i = 0; i < column_count; i++) { const char *txt = reinterpret_cast( sqlite3_column_text(stmt, i)); - row.emplace_back(txt ? txt : std::string()); + if (txt) { + row[i] = txt; + } } - result.emplace_back(row); + result.emplace_back(std::move(row)); } else if (ret == SQLITE_DONE) { break; } else { @@ -722,7 +911,7 @@ const char *DatabaseContext::getMetadata(const char *key) const { if (res.empty()) { return nullptr; } - d->lastMetadataValue_ = res[0][0]; + d->lastMetadataValue_ = res.front()[0]; return d->lastMetadataValue_.c_str(); } @@ -761,9 +950,10 @@ bool DatabaseContext::lookForGridAlternative(const std::string &officialName, if (res.empty()) { return false; } - projFilename = res[0][0]; - projFormat = res[0][1]; - inverse = res[0][2] == "1"; + const auto &row = res.front(); + projFilename = row[0]; + projFormat = row[1]; + inverse = row[2] == "1"; return true; } @@ -807,10 +997,11 @@ bool DatabaseContext::lookForGridInfo(const std::string &projFilename, if (res.empty()) { return false; } - packageName = std::move(res[0][0]); - url = res[0][1].empty() ? std::move(res[0][2]) : std::move(res[0][1]); - openLicense = (res[0][3].empty() ? res[0][4] : res[0][3]) == "1"; - directDownload = (res[0][5].empty() ? res[0][6] : res[0][5]) == "1"; + const auto &row = res.front(); + packageName = std::move(row[0]); + url = row[1].empty() ? std::move(row[2]) : std::move(row[1]); + openLicense = (row[3].empty() ? row[4] : row[3]) == "1"; + directDownload = (row[5].empty() ? row[6] : row[5]) == "1"; return true; } @@ -848,13 +1039,14 @@ DatabaseContext::getAliasFromOfficialName(const std::string &officialName, if (res.empty()) { return std::string(); } + const auto &row = res.front(); res = d->run("SELECT alt_name FROM alias_name WHERE table_name = ? AND " "auth_name = ? AND code = ? AND source = ?", - {tableName, res[0][0], res[0][1], source}); + {tableName, row[0], row[1], source}); if (res.empty()) { return std::string(); } - return res[0][0]; + return res.front()[0]; } // --------------------------------------------------------------------------- @@ -877,7 +1069,7 @@ std::string DatabaseContext::getTextDefinition(const std::string &tableName, if (res.empty()) { return std::string(); } - return res[0][0]; + return res.front()[0]; } // --------------------------------------------------------------------------- @@ -915,7 +1107,7 @@ std::vector DatabaseContext::getAllowedAuthorities( if (res.empty()) { return std::vector(); } - return split(res[0][0], ','); + return split(res.front()[0], ','); } // --------------------------------------------------------------------------- @@ -974,24 +1166,12 @@ struct AuthorityFactory::Private { // cppcheck-suppress functionStatic AuthorityFactoryPtr getSharedFromThis() { return thisFactory_.lock(); } - AuthorityFactoryNNPtr createFactory(const std::string &auth_name); - - // cppcheck-suppress functionStatic - common::UnitOfMeasurePtr getUOMFromCache(const std::string &code); - // cppcheck-suppress functionStatic - void cache(const std::string &code, const common::UnitOfMeasureNNPtr &uom); - - // cppcheck-suppress functionStatic - crs::CRSPtr getCRSFromCache(const std::string &code); - // cppcheck-suppress functionStatic - void cache(const std::string &code, const crs::CRSNNPtr &crs); - - datum::GeodeticReferenceFramePtr - // cppcheck-suppress functionStatic - getGeodeticDatumFromCache(const std::string &code); - // cppcheck-suppress functionStatic - void cache(const std::string &code, - const datum::GeodeticReferenceFrameNNPtr &datum); + inline AuthorityFactoryNNPtr createFactory(const std::string &auth_name) { + if (auth_name == authority_) { + return NN_NO_CHECK(thisFactory_.lock()); + } + return AuthorityFactory::create(context_, auth_name); + } bool rejectOpDueToMissingGrid(const operation::CoordinateOperationNNPtr &op, bool discardIfMissingGrid); @@ -1008,9 +1188,8 @@ struct AuthorityFactory::Private { const std::string &area_of_use_auth_name, const std::string &area_of_use_code); - SQLResultSet - run(const std::string &sql, - const std::vector ¶meters = std::vector()); + SQLResultSet run(const std::string &sql, + const ListOfParams ¶meters = ListOfParams()); SQLResultSet runWithCodeParam(const std::string &sql, const std::string &code); @@ -1025,56 +1204,12 @@ struct AuthorityFactory::Private { DatabaseContextNNPtr context_; std::string authority_; std::weak_ptr thisFactory_{}; - std::weak_ptr parentFactory_{}; - std::map mapFactory_{}; - lru11::Cache cacheUOM_{}; - lru11::Cache cacheCRS_{}; - lru11::Cache cacheGeodeticDatum_{}; - - static void - insertIntoCache(lru11::Cache &cache, - const std::string &code, const util::BaseObjectPtr &obj); - - static void - getFromCache(lru11::Cache &cache, - const std::string &code, util::BaseObjectPtr &obj); }; // --------------------------------------------------------------------------- -AuthorityFactoryNNPtr -AuthorityFactory::Private::createFactory(const std::string &auth_name) { - - // If we are a child factory, then create new factory on the parent - auto parentFactoryLocked(parentFactory_.lock()); - if (parentFactoryLocked) { - return parentFactoryLocked->d->createFactory(auth_name); - } - - // If asked for a factory with our name, return ourselves. - auto lockedThisFactory(thisFactory_.lock()); - assert(lockedThisFactory); - if (auth_name == lockedThisFactory->getAuthority()) { - return NN_NO_CHECK(lockedThisFactory); - } - - // Find if there is already a child factory with the passed name. - auto iter = mapFactory_.find(auth_name); - if (iter == mapFactory_.end()) { - auto newFactory = AuthorityFactory::create(context_, auth_name); - newFactory->d->parentFactory_ = thisFactory_; - mapFactory_.insert(std::pair( - auth_name, newFactory)); - return newFactory; - } - return iter->second; -} - -// --------------------------------------------------------------------------- - -SQLResultSet -AuthorityFactory::Private::run(const std::string &sql, - const std::vector ¶meters) { +SQLResultSet AuthorityFactory::Private::run(const std::string &sql, + const ListOfParams ¶meters) { return context()->getPrivate()->run(sql, parameters); } @@ -1110,8 +1245,10 @@ util::PropertyMap AuthorityFactory::Private::createProperties( auto props = util::PropertyMap() .set(metadata::Identifier::CODESPACE_KEY, authority()) .set(metadata::Identifier::CODE_KEY, code) - .set(common::IdentifiedObject::NAME_KEY, name) - .set(common::IdentifiedObject::DEPRECATED_KEY, deprecated); + .set(common::IdentifiedObject::NAME_KEY, name); + if (deprecated) { + props.set(common::IdentifiedObject::DEPRECATED_KEY, true); + } if (extent) { props.set( common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY, @@ -1136,70 +1273,6 @@ util::PropertyMap AuthorityFactory::Private::createProperties( // --------------------------------------------------------------------------- -void AuthorityFactory::Private::insertIntoCache( - lru11::Cache &cache, - const std::string &code, const util::BaseObjectPtr &obj) { - cache.insert(code, obj); -} - -// --------------------------------------------------------------------------- - -void AuthorityFactory::Private::getFromCache( - lru11::Cache &cache, - const std::string &code, util::BaseObjectPtr &obj) { - cache.tryGet(code, obj); -} - -// --------------------------------------------------------------------------- - -crs::CRSPtr -AuthorityFactory::Private::getCRSFromCache(const std::string &code) { - util::BaseObjectPtr obj; - getFromCache(cacheCRS_, code, obj); - return std::static_pointer_cast(obj); -} - -// --------------------------------------------------------------------------- - -void AuthorityFactory::Private::cache(const std::string &code, - const crs::CRSNNPtr &crs) { - insertIntoCache(cacheCRS_, code, crs.as_nullable()); -} - -// --------------------------------------------------------------------------- - -common::UnitOfMeasurePtr -AuthorityFactory::Private::getUOMFromCache(const std::string &code) { - util::BaseObjectPtr obj; - getFromCache(cacheUOM_, code, obj); - return std::static_pointer_cast(obj); -} - -// --------------------------------------------------------------------------- - -void AuthorityFactory::Private::cache(const std::string &code, - const common::UnitOfMeasureNNPtr &uom) { - insertIntoCache(cacheUOM_, code, uom.as_nullable()); -} - -// --------------------------------------------------------------------------- - -datum::GeodeticReferenceFramePtr -AuthorityFactory::Private::getGeodeticDatumFromCache(const std::string &code) { - util::BaseObjectPtr obj; - getFromCache(cacheGeodeticDatum_, code, obj); - return std::static_pointer_cast(obj); -} - -// --------------------------------------------------------------------------- - -void AuthorityFactory::Private::cache( - const std::string &code, const datum::GeodeticReferenceFrameNNPtr &datum) { - insertIntoCache(cacheGeodeticDatum_, code, datum.as_nullable()); -} - -// --------------------------------------------------------------------------- - bool AuthorityFactory::Private::rejectOpDueToMissingGrid( const operation::CoordinateOperationNNPtr &op, bool discardIfMissingGrid) { if (discardIfMissingGrid) { @@ -1244,6 +1317,7 @@ AuthorityFactory::AuthorityFactory(const DatabaseContextNNPtr &context, AuthorityFactoryNNPtr AuthorityFactory::create(const DatabaseContextNNPtr &context, const std::string &authorityName) { + auto factory = AuthorityFactory::nn_make_shared( context, authorityName); factory->d->setThis(factory); @@ -1284,7 +1358,7 @@ AuthorityFactory::createObject(const std::string &code) const { "SELECT table_name FROM object_view WHERE auth_name = ? AND code = ?", code); if (res.empty()) { - throw NoSuchAuthorityCodeException("not found", getAuthority(), code); + throw NoSuchAuthorityCodeException("not found", d->authority(), code); } if (res.size() != 1) { std::string msg( @@ -1298,7 +1372,7 @@ AuthorityFactory::createObject(const std::string &code) const { } throw FactoryException(msg); } - const auto &table_name = res[0][0]; + const auto &table_name = res.front()[0]; if (table_name == "area") { return util::nn_static_pointer_cast( createExtent(code)); @@ -1350,7 +1424,7 @@ AuthorityFactory::createObject(const std::string &code) const { return util::nn_static_pointer_cast( createCoordinateOperation(code, false)); } - throw FactoryException("unimplemented factory for " + res[0][0]); + throw FactoryException("unimplemented factory for " + res.front()[0]); } // --------------------------------------------------------------------------- @@ -1376,15 +1450,22 @@ static FactoryException buildFactoryException(const char *type, metadata::ExtentNNPtr AuthorityFactory::createExtent(const std::string &code) const { + const auto cacheKey(d->authority() + code); + { + auto extent = d->context()->d->getExtentFromCache(cacheKey); + if (extent) { + return NN_NO_CHECK(extent); + } + } auto sql = "SELECT name, south_lat, north_lat, west_lon, east_lon, " "deprecated FROM area WHERE auth_name = ? AND code = ?"; auto res = d->runWithCodeParam(sql, code); if (res.empty()) { - throw NoSuchAuthorityCodeException("area not found", getAuthority(), + throw NoSuchAuthorityCodeException("area not found", d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); const auto &name = row[0]; double south_lat = c_locale_stod(row[1]); double north_lat = c_locale_stod(row[2]); @@ -1393,11 +1474,13 @@ AuthorityFactory::createExtent(const std::string &code) const { auto bbox = metadata::GeographicBoundingBox::create( west_lon, south_lat, east_lon, north_lat); - return metadata::Extent::create( + auto extent = metadata::Extent::create( util::optional(name), std::vector{bbox}, std::vector(), std::vector()); + d->context()->d->cache(code, extent); + return extent; } catch (const std::exception &ex) { throw buildFactoryException("area", code, ex); @@ -1416,8 +1499,9 @@ AuthorityFactory::createExtent(const std::string &code) const { UnitOfMeasureNNPtr AuthorityFactory::createUnitOfMeasure(const std::string &code) const { + const auto cacheKey(d->authority() + code); { - auto uom = d->getUOMFromCache(code); + auto uom = d->context()->d->getUOMFromCache(cacheKey); if (uom) { return NN_NO_CHECK(uom); } @@ -1428,10 +1512,10 @@ AuthorityFactory::createUnitOfMeasure(const std::string &code) const { code); if (res.empty()) { throw NoSuchAuthorityCodeException("unit of measure not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); const auto &name = (row[0] == "degree (supplier to define representation)") ? UnitOfMeasure::DEGREE.name() @@ -1460,8 +1544,8 @@ AuthorityFactory::createUnitOfMeasure(const std::string &code) const { else if (type_str == "time") unitType = UnitOfMeasure::Type::TIME; auto uom = util::nn_make_shared( - name, conv_factor, unitType, getAuthority(), code); - d->cache(code, uom); + name, conv_factor, unitType, d->authority(), code); + d->context()->d->cache(cacheKey, uom); return uom; } catch (const std::exception &ex) { throw buildFactoryException("unit of measure", code, ex); @@ -1471,14 +1555,12 @@ AuthorityFactory::createUnitOfMeasure(const std::string &code) const { // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress -static void normalizeMeasure(const std::string &uom_code, - const std::string &value, - std::string &normalized_uom_code, - double &normalized_value) { - normalized_uom_code = uom_code; - normalized_value = c_locale_stod(value); +static double normalizeMeasure(const std::string &uom_code, + const std::string &value, + std::string &normalized_uom_code) { if (uom_code == "9110") // DDD.MMSSsss..... { + double normalized_value = c_locale_stod(value); std::ostringstream buffer; buffer.imbue(std::locale::classic()); constexpr size_t precision = 12; @@ -1496,6 +1578,10 @@ static void normalizeMeasure(const std::string &uom_code, (c_locale_stod(seconds) / std::pow(10, seconds.size() - 2)) / 3600.); normalized_uom_code = common::UnitOfMeasure::DEGREE.code(); + return normalized_value; + } else { + normalized_uom_code = uom_code; + return c_locale_stod(value); } } //! @endcond @@ -1512,6 +1598,13 @@ static void normalizeMeasure(const std::string &uom_code, datum::PrimeMeridianNNPtr AuthorityFactory::createPrimeMeridian(const std::string &code) const { + const auto cacheKey(d->authority() + code); + { + auto pm = d->context()->d->getPrimeMeridianFromCache(cacheKey); + if (pm) { + return NN_NO_CHECK(pm); + } + } auto res = d->runWithCodeParam( "SELECT name, longitude, uom_auth_name, uom_code, deprecated FROM " "prime_meridian WHERE " @@ -1519,10 +1612,10 @@ AuthorityFactory::createPrimeMeridian(const std::string &code) const { code); if (res.empty()) { throw NoSuchAuthorityCodeException("prime meridian not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); const auto &name = row[0]; const auto &longitude = row[1]; const auto &uom_auth_name = row[2]; @@ -1530,14 +1623,15 @@ AuthorityFactory::createPrimeMeridian(const std::string &code) const { const bool deprecated = row[4] == "1"; std::string normalized_uom_code(uom_code); - double normalized_value(c_locale_stod(longitude)); - normalizeMeasure(uom_code, longitude, normalized_uom_code, - normalized_value); + const double normalized_value = + normalizeMeasure(uom_code, longitude, normalized_uom_code); auto uom = d->createUnitOfMeasure(uom_auth_name, normalized_uom_code); auto props = d->createProperties(code, name, deprecated, nullptr); - return datum::PrimeMeridian::create( + auto pm = datum::PrimeMeridian::create( props, common::Angle(normalized_value, uom)); + d->context()->d->cache(cacheKey, pm); + return pm; } catch (const std::exception &ex) { throw buildFactoryException("prime meridian", code, ex); } @@ -1566,7 +1660,7 @@ AuthorityFactory::identifyBodyFromSemiMajorAxis(double semi_major_axis, if (res.size() > 1) { throw FactoryException("more than one match found"); } - return res[0][0]; + return res.front()[0]; } // --------------------------------------------------------------------------- @@ -1593,10 +1687,10 @@ AuthorityFactory::createEllipsoid(const std::string &code) const { code); if (res.empty()) { throw NoSuchAuthorityCodeException("ellipsoid not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); const auto &name = row[0]; const auto &semi_major_axis_str = row[1]; double semi_major_axis = c_locale_stod(semi_major_axis_str); @@ -1637,8 +1731,9 @@ AuthorityFactory::createEllipsoid(const std::string &code) const { datum::GeodeticReferenceFrameNNPtr AuthorityFactory::createGeodeticDatum(const std::string &code) const { + const auto cacheKey(d->authority() + code); { - auto datum = d->getGeodeticDatumFromCache(code); + auto datum = d->context()->d->getGeodeticDatumFromCache(cacheKey); if (datum) { return NN_NO_CHECK(datum); } @@ -1651,10 +1746,10 @@ AuthorityFactory::createGeodeticDatum(const std::string &code) const { code); if (res.empty()) { throw NoSuchAuthorityCodeException("geodetic datum not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); const auto &name = row[0]; const auto &ellipsoid_auth_name = row[1]; const auto &ellipsoid_code = row[2]; @@ -1672,7 +1767,7 @@ AuthorityFactory::createGeodeticDatum(const std::string &code) const { auto anchor = util::optional(); auto datum = datum::GeodeticReferenceFrame::create(props, ellipsoid, anchor, pm); - d->cache(code, datum); + d->context()->d->cache(cacheKey, datum); return datum; } catch (const std::exception &ex) { throw buildFactoryException("geodetic reference frame", code, ex); @@ -1697,10 +1792,10 @@ AuthorityFactory::createVerticalDatum(const std::string &code) const { code); if (res.empty()) { throw NoSuchAuthorityCodeException("vertical datum not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); const auto &name = row[0]; const auto &area_of_use_auth_name = row[1]; const auto &area_of_use_code = row[2]; @@ -1730,12 +1825,12 @@ datum::DatumNNPtr AuthorityFactory::createDatum(const std::string &code) const { "auth_name = ? AND code = ? " "UNION ALL SELECT 'vertical_datum' FROM vertical_datum WHERE " "auth_name = ? AND code = ?", - {getAuthority(), code, getAuthority(), code}); + {d->authority(), code, d->authority(), code}); if (res.empty()) { - throw NoSuchAuthorityCodeException("datum not found", getAuthority(), + throw NoSuchAuthorityCodeException("datum not found", d->authority(), code); } - if (res[0][0] == "geodetic_datum") { + if (res.front()[0] == "geodetic_datum") { return createGeodeticDatum(code); } return createVerticalDatum(code); @@ -1774,6 +1869,13 @@ static cs::MeridianPtr createMeridian(const std::string &val) { cs::CoordinateSystemNNPtr AuthorityFactory::createCoordinateSystem(const std::string &code) const { + const auto cacheKey(d->authority() + code); + { + auto cs = d->context()->d->getCoordinateSystemFromCache(cacheKey); + if (cs) { + return NN_NO_CHECK(cs); + } + } auto res = d->runWithCodeParam( "SELECT axis.name, abbrev, orientation, uom_auth_name, uom_code, " "cs.type FROM " @@ -1785,10 +1887,10 @@ AuthorityFactory::createCoordinateSystem(const std::string &code) const { code); if (res.empty()) { throw NoSuchAuthorityCodeException("coordinate system not found", - getAuthority(), code); + d->authority(), code); } - const auto &csType = res[0][5]; + const auto &csType = res.front()[5]; std::vector axisList; for (const auto &row : res) { const auto &name = row[0]; @@ -1829,32 +1931,41 @@ AuthorityFactory::createCoordinateSystem(const std::string &code) const { axisList.emplace_back(cs::CoordinateSystemAxis::create( props, abbrev, *direction, uom, meridian)); } + + const auto cacheAndRet = [this, + &cacheKey](const cs::CoordinateSystemNNPtr &cs) { + d->context()->d->cache(cacheKey, cs); + return cs; + }; + auto props = util::PropertyMap() - .set(metadata::Identifier::CODESPACE_KEY, getAuthority()) + .set(metadata::Identifier::CODESPACE_KEY, d->authority()) .set(metadata::Identifier::CODE_KEY, code); if (csType == "ellipsoidal") { if (axisList.size() == 2) { - return cs::EllipsoidalCS::create(props, axisList[0], axisList[1]); + return cacheAndRet( + cs::EllipsoidalCS::create(props, axisList[0], axisList[1])); } if (axisList.size() == 3) { - return cs::EllipsoidalCS::create(props, axisList[0], axisList[1], - axisList[2]); + return cacheAndRet(cs::EllipsoidalCS::create( + props, axisList[0], axisList[1], axisList[2])); } throw FactoryException("invalid number of axis for EllipsoidalCS"); } if (csType == "Cartesian") { if (axisList.size() == 2) { - return cs::CartesianCS::create(props, axisList[0], axisList[1]); + return cacheAndRet( + cs::CartesianCS::create(props, axisList[0], axisList[1])); } if (axisList.size() == 3) { - return cs::CartesianCS::create(props, axisList[0], axisList[1], - axisList[2]); + return cacheAndRet(cs::CartesianCS::create( + props, axisList[0], axisList[1], axisList[2])); } throw FactoryException("invalid number of axis for CartesianCS"); } if (csType == "vertical") { if (axisList.size() == 1) { - return cs::VerticalCS::create(props, axisList[0]); + return cacheAndRet(cs::VerticalCS::create(props, axisList[0])); } throw FactoryException("invalid number of axis for VerticalCS"); } @@ -1920,8 +2031,9 @@ cloneWithProps(const crs::GeodeticCRSNNPtr &geodCRS, crs::GeodeticCRSNNPtr AuthorityFactory::createGeodeticCRS(const std::string &code, bool geographicOnly) const { - auto crs = - std::dynamic_pointer_cast(d->getCRSFromCache(code)); + const auto cacheKey(d->authority() + code); + auto crs = std::dynamic_pointer_cast( + d->context()->d->getCRSFromCache(cacheKey)); if (crs) { return NN_NO_CHECK(crs); } @@ -1936,10 +2048,10 @@ AuthorityFactory::createGeodeticCRS(const std::string &code, auto res = d->runWithCodeParam(sql, code); if (res.empty()) { throw NoSuchAuthorityCodeException("geodeticCRS not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); const auto &name = row[0]; const auto &type = row[1]; const auto &cs_auth_name = row[2]; @@ -1991,14 +2103,14 @@ AuthorityFactory::createGeodeticCRS(const std::string &code, ellipsoidalCS) { auto crsRet = crs::GeographicCRS::create( props, datum, NN_NO_CHECK(ellipsoidalCS)); - d->cache(code, crsRet); + d->context()->d->cache(cacheKey, crsRet); return crsRet; } auto geocentricCS = util::nn_dynamic_pointer_cast(cs); if (type == "geocentric" && geocentricCS) { auto crsRet = crs::GeodeticCRS::create(props, datum, NN_NO_CHECK(geocentricCS)); - d->cache(code, crsRet); + d->context()->d->cache(cacheKey, crsRet); return crsRet; } throw FactoryException("unsupported (type, CS type) for geodeticCRS: " + @@ -2028,10 +2140,10 @@ AuthorityFactory::createVerticalCRS(const std::string &code) const { code); if (res.empty()) { throw NoSuchAuthorityCodeException("verticalCRS not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); const auto &name = row[0]; const auto &cs_auth_name = row[1]; const auto &cs_code = row[2]; @@ -2072,28 +2184,41 @@ AuthorityFactory::createVerticalCRS(const std::string &code) const { operation::ConversionNNPtr AuthorityFactory::createConversion(const std::string &code) const { - std::ostringstream buffer; - buffer.imbue(std::locale::classic()); - buffer << "SELECT name, area_of_use_auth_name, area_of_use_code, " - "method_auth_name, method_code, method_name"; - constexpr int N_MAX_PARAMS = 7; - for (int i = 1; i <= N_MAX_PARAMS; ++i) { - buffer << ", param" << i << "_auth_name"; - buffer << ", param" << i << "_code"; - buffer << ", param" << i << "_name"; - buffer << ", param" << i << "_value"; - buffer << ", param" << i << "_uom_auth_name"; - buffer << ", param" << i << "_uom_code"; - } - buffer << ", deprecated FROM conversion WHERE auth_name = ? AND code = ?"; - - auto res = d->runWithCodeParam(buffer.str(), code); + + static const char *sql = + "SELECT name, area_of_use_auth_name, area_of_use_code, " + "method_auth_name, method_code, method_name, " + + "param1_auth_name, param1_code, param1_name, param1_value, " + "param1_uom_auth_name, param1_uom_code, " + + "param2_auth_name, param2_code, param2_name, param2_value, " + "param2_uom_auth_name, param2_uom_code, " + + "param3_auth_name, param3_code, param3_name, param3_value, " + "param3_uom_auth_name, param3_uom_code, " + + "param4_auth_name, param4_code, param4_name, param4_value, " + "param4_uom_auth_name, param4_uom_code, " + + "param5_auth_name, param5_code, param5_name, param5_value, " + "param5_uom_auth_name, param5_uom_code, " + + "param6_auth_name, param6_code, param6_name, param6_value, " + "param6_uom_auth_name, param6_uom_code, " + + "param7_auth_name, param7_code, param7_name, param7_value, " + "param7_uom_auth_name, param7_uom_code, " + + "deprecated FROM conversion WHERE auth_name = ? AND code = ?"; + + auto res = d->runWithCodeParam(sql, code); if (res.empty()) { throw NoSuchAuthorityCodeException("conversion not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); size_t idx = 0; const auto &name = row[idx++]; const auto &area_of_use_auth_name = row[idx++]; @@ -2104,6 +2229,7 @@ AuthorityFactory::createConversion(const std::string &code) const { const size_t base_param_idx = idx; std::vector parameters; std::vector values; + constexpr int N_MAX_PARAMS = 7; for (int i = 0; i < N_MAX_PARAMS; ++i) { const auto ¶m_auth_name = row[base_param_idx + i * 6 + 0]; if (param_auth_name.empty()) { @@ -2120,9 +2246,8 @@ AuthorityFactory::createConversion(const std::string &code) const { .set(metadata::Identifier::CODE_KEY, param_code) .set(common::IdentifiedObject::NAME_KEY, param_name))); std::string normalized_uom_code(param_uom_code); - double normalized_value(c_locale_stod(param_value)); - normalizeMeasure(param_uom_code, param_value, normalized_uom_code, - normalized_value); + const double normalized_value = normalizeMeasure( + param_uom_code, param_value, normalized_uom_code); auto uom = d->createUnitOfMeasure(param_uom_auth_name, normalized_uom_code); values.emplace_back(operation::ParameterValue::create( @@ -2169,10 +2294,10 @@ AuthorityFactory::createProjectedCRS(const std::string &code) const { code); if (res.empty()) { throw NoSuchAuthorityCodeException("projectedCRS not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); const auto &name = row[0]; const auto &cs_auth_name = row[1]; const auto &cs_code = row[2]; @@ -2268,10 +2393,10 @@ AuthorityFactory::createCompoundCRS(const std::string &code) const { code); if (res.empty()) { throw NoSuchAuthorityCodeException("compoundCRS not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); const auto &name = row[0]; const auto &horiz_crs_auth_name = row[1]; const auto &horiz_crs_code = row[2]; @@ -2314,17 +2439,18 @@ crs::CRSNNPtr AuthorityFactory::createCoordinateReferenceSystem( crs::CRSNNPtr AuthorityFactory::createCoordinateReferenceSystem(const std::string &code, bool allowCompound) const { - auto crs = d->getCRSFromCache(code); + const auto cacheKey(d->authority() + code); + auto crs = d->context()->d->getCRSFromCache(cacheKey); if (crs) { return NN_NO_CHECK(crs); } auto res = d->runWithCodeParam( "SELECT type FROM crs_view WHERE auth_name = ? AND code = ?", code); if (res.empty()) { - throw NoSuchAuthorityCodeException("crs not found", getAuthority(), + throw NoSuchAuthorityCodeException("crs not found", d->authority(), code); } - const auto &type = res[0][0]; + const auto &type = res.front()[0]; if (type == "geographic 2D" || type == "geographic 3D" || type == "geocentric") { return createGeodeticCRS(code); @@ -2389,28 +2515,33 @@ static operation::ParameterValueNNPtr createAngle(const std::string &value, operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( const std::string &code, bool usePROJAlternativeGridNames) const { - return createCoordinateOperation(code, true, usePROJAlternativeGridNames); + return createCoordinateOperation(code, true, usePROJAlternativeGridNames, + std::string()); } operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( const std::string &code, bool allowConcatenated, - bool usePROJAlternativeGridNames) const { - auto res = d->runWithCodeParam( - "SELECT type FROM coordinate_operation_with_conversion_view " - "WHERE auth_name = ? AND code = ?", - code); - if (res.empty()) { - throw NoSuchAuthorityCodeException("coordinate operation not found", - getAuthority(), code); + bool usePROJAlternativeGridNames, const std::string &typeIn) const { + std::string type(typeIn); + if (type.empty()) { + auto res = d->runWithCodeParam( + "SELECT type FROM coordinate_operation_with_conversion_view " + "WHERE auth_name = ? AND code = ?", + code); + if (res.empty()) { + throw NoSuchAuthorityCodeException("coordinate operation not found", + d->authority(), code); + } + type = res.front()[0]; } - const auto type = res[0][0]; + if (type == "conversion") { return createConversion(code); } if (type == "helmert_transformation") { - res = d->runWithCodeParam( + auto res = d->runWithCodeParam( "SELECT name, method_auth_name, method_code, method_name, " "source_crs_auth_name, source_crs_code, target_crs_auth_name, " "target_crs_code, area_of_use_auth_name, area_of_use_code, " @@ -2430,10 +2561,10 @@ operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( if (res.empty()) { // shouldn't happen if foreign keys are OK throw NoSuchAuthorityCodeException( - "helmert_transformation not found", getAuthority(), code); + "helmert_transformation not found", d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); size_t idx = 0; const auto &name = row[idx++]; const auto &method_auth_name = row[idx++]; @@ -2647,7 +2778,7 @@ operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( } if (type == "grid_transformation") { - res = d->runWithCodeParam( + auto res = d->runWithCodeParam( "SELECT name, method_auth_name, method_code, method_name, " "source_crs_auth_name, source_crs_code, target_crs_auth_name, " "target_crs_code, area_of_use_auth_name, area_of_use_code, " @@ -2662,10 +2793,10 @@ operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( if (res.empty()) { // shouldn't happen if foreign keys are OK throw NoSuchAuthorityCodeException("grid_transformation not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); size_t idx = 0; const auto &name = row[idx++]; const auto &method_auth_name = row[idx++]; @@ -2778,14 +2909,14 @@ operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( buffer << ", deprecated FROM other_transformation WHERE auth_name = ? " "AND code = ?"; - res = d->runWithCodeParam(buffer.str(), code); + auto res = d->runWithCodeParam(buffer.str(), code); if (res.empty()) { // shouldn't happen if foreign keys are OK throw NoSuchAuthorityCodeException("other_transformation not found", - getAuthority(), code); + d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); size_t idx = 0; const auto &name = row[idx++]; const auto &method_auth_name = row[idx++]; @@ -2820,9 +2951,8 @@ operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( .set(metadata::Identifier::CODE_KEY, param_code) .set(common::IdentifiedObject::NAME_KEY, param_name))); std::string normalized_uom_code(param_uom_code); - double normalized_value(c_locale_stod(param_value)); - normalizeMeasure(param_uom_code, param_value, - normalized_uom_code, normalized_value); + const double normalized_value = normalizeMeasure( + param_uom_code, param_value, normalized_uom_code); auto uom = d->createUnitOfMeasure(param_uom_auth_name, normalized_uom_code); values.emplace_back(operation::ParameterValue::create( @@ -2892,7 +3022,7 @@ operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( } if (allowConcatenated && type == "concatenated_operation") { - res = d->runWithCodeParam( + auto res = d->runWithCodeParam( "SELECT name, source_crs_auth_name, source_crs_code, " "target_crs_auth_name, target_crs_code, " "area_of_use_auth_name, area_of_use_code, accuracy, " @@ -2903,10 +3033,10 @@ operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( if (res.empty()) { // shouldn't happen if foreign keys are OK throw NoSuchAuthorityCodeException( - "concatenated_operation not found", getAuthority(), code); + "concatenated_operation not found", d->authority(), code); } try { - const auto &row = res[0]; + const auto &row = res.front(); size_t idx = 0; const auto &name = row[idx++]; const auto &source_crs_auth_name = row[idx++]; @@ -2929,17 +3059,20 @@ operation::CoordinateOperationNNPtr AuthorityFactory::createCoordinateOperation( operations.push_back( d->createFactory(step1_auth_name) ->createCoordinateOperation(step1_code, false, - usePROJAlternativeGridNames)); + usePROJAlternativeGridNames, + std::string())); operations.push_back( d->createFactory(step2_auth_name) ->createCoordinateOperation(step2_code, false, - usePROJAlternativeGridNames)); + usePROJAlternativeGridNames, + std::string())); if (!step3_auth_name.empty()) { operations.push_back( d->createFactory(step3_auth_name) - ->createCoordinateOperation( - step3_code, false, usePROJAlternativeGridNames)); + ->createCoordinateOperation(step3_code, false, + usePROJAlternativeGridNames, + std::string())); } // In case the operation is a conversion (we hope this is the @@ -3119,7 +3252,7 @@ std::vector AuthorityFactory::createFromCoordinateReferenceSystemCodes( const std::string &sourceCRSCode, const std::string &targetCRSCode) const { return createFromCoordinateReferenceSystemCodes( - getAuthority(), sourceCRSCode, getAuthority(), targetCRSCode, false, + d->authority(), sourceCRSCode, d->authority(), targetCRSCode, false, false, false); } @@ -3162,29 +3295,45 @@ AuthorityFactory::createFromCoordinateReferenceSystemCodes( const std::string &targetCRSAuthName, const std::string &targetCRSCode, bool usePROJAlternativeGridNames, bool discardIfMissingGrid, bool discardSuperseded) const { + + auto cacheKey(d->authority()); + cacheKey += sourceCRSAuthName; + cacheKey += sourceCRSCode; + cacheKey += targetCRSAuthName; + cacheKey += targetCRSCode; + cacheKey += (usePROJAlternativeGridNames ? '1' : '0'); + cacheKey += (discardIfMissingGrid ? '1' : '0'); + cacheKey += (discardSuperseded ? '1' : '0'); + std::vector list; - // Look-up first for conversion which is the most precise. - std::string sql( - "SELECT conversion_auth_name, conversion_code FROM " - "projected_crs WHERE geodetic_crs_auth_name = ? AND geodetic_crs_code " - "= ? AND auth_name = ? AND code = ? AND deprecated != 1"); - auto params = std::vector{sourceCRSAuthName, sourceCRSCode, - targetCRSAuthName, targetCRSCode}; - if (d->hasAuthorityRestriction()) { - sql += " AND conversion_auth_name = ?"; - params.emplace_back(getAuthority()); + if (d->context()->d->getCRSToCRSCoordOpFromCache(cacheKey, list)) { + return list; } + + // Look-up first for conversion which is the most precise. + std::string sql("SELECT conversion_auth_name, " + "geodetic_crs_auth_name, geodetic_crs_code FROM " + "projected_crs WHERE auth_name = ? AND code = ?"); + auto params = ListOfParams{targetCRSAuthName, targetCRSCode}; auto res = d->run(sql, params); if (!res.empty()) { - auto targetCRS = d->createFactory(targetCRSAuthName) - ->createProjectedCRS(targetCRSCode); - auto conv = targetCRS->derivingConversion(); - list.emplace_back(conv); - return list; + const auto &row = res.front(); + bool ok = row[1] == sourceCRSAuthName && row[2] == sourceCRSCode; + if (ok && d->hasAuthorityRestriction()) { + ok = row[0] == d->authority(); + } + if (ok) { + auto targetCRS = d->createFactory(targetCRSAuthName) + ->createProjectedCRS(targetCRSCode); + auto conv = targetCRS->derivingConversion(); + list.emplace_back(conv); + d->context()->d->cache(cacheKey, list); + return list; + } } if (discardSuperseded) { - sql = "SELECT cov.auth_name, cov.code, " + sql = "SELECT cov.auth_name, cov.code, cov.table_name, " "ss.replacement_auth_name, ss.replacement_code FROM " "coordinate_operation_view cov JOIN area " "ON cov.area_of_use_auth_name = area.auth_name AND " @@ -3196,21 +3345,21 @@ AuthorityFactory::createFromCoordinateReferenceSystemCodes( "ss.superseded_table_name = ss.replacement_table_name " "WHERE source_crs_auth_name = ? AND source_crs_code = ? AND " "target_crs_auth_name = ? AND target_crs_code = ? AND " - "cov.deprecated != 1"; + "cov.deprecated = 0"; } else { - sql = "SELECT cov.auth_name, cov.code FROM " + sql = "SELECT cov.auth_name, cov.code, cov.table_name FROM " "coordinate_operation_view cov JOIN area " "ON cov.area_of_use_auth_name = area.auth_name AND " "cov.area_of_use_code = area.code " "WHERE source_crs_auth_name = ? AND source_crs_code = ? AND " "target_crs_auth_name = ? AND target_crs_code = ? AND " - "cov.deprecated != 1"; + "cov.deprecated = 0"; } params = {sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode}; if (d->hasAuthorityRestriction()) { sql += " AND cov.auth_name = ?"; - params.emplace_back(getAuthority()); + params.emplace_back(d->authority()); } sql += " ORDER BY pseudo_area_from_swne(south_lat, west_lon, north_lat, " "east_lon) DESC, " @@ -3227,8 +3376,8 @@ AuthorityFactory::createFromCoordinateReferenceSystemCodes( } for (const auto &row : res) { if (discardSuperseded) { - const auto &replacement_auth_name = row[2]; - const auto &replacement_code = row[3]; + const auto &replacement_auth_name = row[3]; + const auto &replacement_code = row[4]; if (!replacement_auth_name.empty() && setTransf.find(std::pair( replacement_auth_name, replacement_code)) != @@ -3241,12 +3390,14 @@ AuthorityFactory::createFromCoordinateReferenceSystemCodes( const auto &auth_name = row[0]; const auto &code = row[1]; + const auto &table_name = row[2]; auto op = d->createFactory(auth_name)->createCoordinateOperation( - code, true, usePROJAlternativeGridNames); + code, true, usePROJAlternativeGridNames, table_name); if (!d->rejectOpDueToMissingGrid(op, discardIfMissingGrid)) { list.emplace_back(op); } } + d->context()->d->cache(cacheKey, list); return list; } @@ -3364,8 +3515,10 @@ AuthorityFactory::createFromCRSCodesWithIntermediates( discardSuperseded ? - "SELECT v1.auth_name AS auth_name1, v1.code AS code1, " + "SELECT v1.table_name as table1, " + "v1.auth_name AS auth_name1, v1.code AS code1, " "v1.accuracy AS accuracy1, " + "v2.table_name as table2, " "v2.auth_name AS auth_name2, v2.code AS code2, " "v2.accuracy as accuracy2, " "a1.south_lat AS south_lat1, " @@ -3384,8 +3537,10 @@ AuthorityFactory::createFromCRSCodesWithIntermediates( "JOIN coordinate_operation_view v2 " : - "SELECT v1.auth_name AS auth_name1, v1.code AS code1, " + "SELECT v1.table_name as table1, " + "v1.auth_name AS auth_name1, v1.code AS code1, " "v1.accuracy AS accuracy1, " + "v2.table_name as table2, " "v2.auth_name AS auth_name2, v2.code AS code2, " "v2.accuracy as accuracy2, " "a1.south_lat AS south_lat1, " @@ -3428,8 +3583,8 @@ AuthorityFactory::createFromCRSCodesWithIntermediates( joinArea + "WHERE v1.source_crs_auth_name = ? AND v1.source_crs_code = ? " "AND v2.target_crs_auth_name = ? AND v2.target_crs_code = ? "); - auto params = std::vector{sourceCRSAuthName, sourceCRSCode, - targetCRSAuthName, targetCRSCode}; + auto params = ListOfParams{sourceCRSAuthName, sourceCRSCode, + targetCRSAuthName, targetCRSCode}; std::string additionalWhere( "AND v1.deprecated = 0 AND v2.deprecated = 0 " @@ -3437,8 +3592,8 @@ AuthorityFactory::createFromCRSCodesWithIntermediates( "south_lat2, west_lon2, north_lat2, east_lon2) == 1 "); if (d->hasAuthorityRestriction()) { additionalWhere += "AND v1.auth_name = ? AND v2.auth_name = ? "; - params.emplace_back(getAuthority()); - params.emplace_back(getAuthority()); + params.emplace_back(d->authority()); + params.emplace_back(d->authority()); } std::string intermediateWhere = buildIntermediateWhere(intermediateCRSAuthCodes, "target", "source"); @@ -3455,11 +3610,13 @@ AuthorityFactory::createFromCRSCodesWithIntermediates( std::set> setTransf1; std::set> setTransf2; for (const auto &row : resultSet) { - const auto &auth_name1 = row[0]; - const auto &code1 = row[1]; - // const auto &accuracy1 = row[2]; - const auto &auth_name2 = row[3]; - const auto &code2 = row[4]; + // table1 + const auto &auth_name1 = row[1]; + const auto &code1 = row[2]; + // accuracy1 + // table2 + const auto &auth_name2 = row[5]; + const auto &code2 = row[6]; setTransf1.insert( std::pair(auth_name1, code1)); setTransf2.insert( @@ -3467,10 +3624,10 @@ AuthorityFactory::createFromCRSCodesWithIntermediates( } SQLResultSet filteredResultSet; for (const auto &row : resultSet) { - const auto &replacement_auth_name1 = row[14]; - const auto &replacement_code1 = row[15]; - const auto &replacement_auth_name2 = row[16]; - const auto &replacement_code2 = row[17]; + const auto &replacement_auth_name1 = row[16]; + const auto &replacement_code1 = row[17]; + const auto &replacement_auth_name2 = row[18]; + const auto &replacement_code2 = row[19]; if (!replacement_auth_name1.empty() && setTransf1.find(std::pair( replacement_auth_name1, replacement_code1)) != @@ -3496,22 +3653,24 @@ AuthorityFactory::createFromCRSCodesWithIntermediates( res = filterOutSuperseded(std::move(res)); } for (const auto &row : res) { - const auto &auth_name1 = row[0]; - const auto &code1 = row[1]; - // const auto &accuracy1 = row[2]; - const auto &auth_name2 = row[3]; - const auto &code2 = row[4]; - // const auto &accuracy2 = row[5]; + const auto &table1 = row[0]; + const auto &auth_name1 = row[1]; + const auto &code1 = row[2]; + // const auto &accuracy1 = row[3]; + const auto &table2 = row[4]; + const auto &auth_name2 = row[5]; + const auto &code2 = row[6]; + // const auto &accuracy2 = row[7]; auto op1 = d->createFactory(auth_name1) - ->createCoordinateOperation(code1, true, - usePROJAlternativeGridNames); + ->createCoordinateOperation( + code1, true, usePROJAlternativeGridNames, table1); if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } auto op2 = d->createFactory(auth_name2) - ->createCoordinateOperation(code2, true, - usePROJAlternativeGridNames); + ->createCoordinateOperation( + code2, true, usePROJAlternativeGridNames, table2); if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; @@ -3535,22 +3694,24 @@ AuthorityFactory::createFromCRSCodesWithIntermediates( res = filterOutSuperseded(std::move(res)); } for (const auto &row : res) { - const auto &auth_name1 = row[0]; - const auto &code1 = row[1]; - // const auto &accuracy1 = row[2]; - const auto &auth_name2 = row[3]; - const auto &code2 = row[4]; - // const auto &accuracy2 = row[5]; + const auto &table1 = row[0]; + const auto &auth_name1 = row[1]; + const auto &code1 = row[2]; + // const auto &accuracy1 = row[3]; + const auto &table2 = row[4]; + const auto &auth_name2 = row[5]; + const auto &code2 = row[6]; + // const auto &accuracy2 = row[7]; auto op1 = d->createFactory(auth_name1) - ->createCoordinateOperation(code1, true, - usePROJAlternativeGridNames); + ->createCoordinateOperation( + code1, true, usePROJAlternativeGridNames, table1); if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } auto op2 = d->createFactory(auth_name2) - ->createCoordinateOperation(code2, true, - usePROJAlternativeGridNames); + ->createCoordinateOperation( + code2, true, usePROJAlternativeGridNames, table2); if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; @@ -3574,22 +3735,24 @@ AuthorityFactory::createFromCRSCodesWithIntermediates( res = filterOutSuperseded(std::move(res)); } for (const auto &row : res) { - const auto &auth_name1 = row[0]; - const auto &code1 = row[1]; - // const auto &accuracy1 = row[2]; - const auto &auth_name2 = row[3]; - const auto &code2 = row[4]; - // const auto &accuracy2 = row[5]; + const auto &table1 = row[0]; + const auto &auth_name1 = row[1]; + const auto &code1 = row[2]; + // const auto &accuracy1 = row[3]; + const auto &table2 = row[4]; + const auto &auth_name2 = row[5]; + const auto &code2 = row[6]; + // const auto &accuracy2 = row[7]; auto op1 = d->createFactory(auth_name1) - ->createCoordinateOperation(code1, true, - usePROJAlternativeGridNames); + ->createCoordinateOperation( + code1, true, usePROJAlternativeGridNames, table1); if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } auto op2 = d->createFactory(auth_name2) - ->createCoordinateOperation(code2, true, - usePROJAlternativeGridNames); + ->createCoordinateOperation( + code2, true, usePROJAlternativeGridNames, table2); if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; @@ -3613,22 +3776,24 @@ AuthorityFactory::createFromCRSCodesWithIntermediates( res = filterOutSuperseded(std::move(res)); } for (const auto &row : res) { - const auto &auth_name1 = row[0]; - const auto &code1 = row[1]; - // const auto &accuracy1 = row[2]; - const auto &auth_name2 = row[3]; - const auto &code2 = row[4]; - // const auto &accuracy2 = row[5]; + const auto &table1 = row[0]; + const auto &auth_name1 = row[1]; + const auto &code1 = row[2]; + // const auto &accuracy1 = row[3]; + const auto &table2 = row[4]; + const auto &auth_name2 = row[5]; + const auto &code2 = row[6]; + // const auto &accuracy2 = row[7]; auto op1 = d->createFactory(auth_name1) - ->createCoordinateOperation(code1, true, - usePROJAlternativeGridNames); + ->createCoordinateOperation( + code1, true, usePROJAlternativeGridNames, table1); if (useIrrelevantPivot(op1, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; } auto op2 = d->createFactory(auth_name2) - ->createCoordinateOperation(code2, true, - usePROJAlternativeGridNames); + ->createCoordinateOperation( + code2, true, usePROJAlternativeGridNames, table2); if (useIrrelevantPivot(op2, sourceCRSAuthName, sourceCRSCode, targetCRSAuthName, targetCRSCode)) { continue; @@ -3735,10 +3900,10 @@ AuthorityFactory::getAuthorityCodes(const ObjectType &type, sql += "auth_name = ?"; if (!allowDeprecated) { - sql += " AND deprecated != 1"; + sql += " AND deprecated = 0"; } - auto res = d->run(sql, {getAuthority()}); + auto res = d->run(sql, {d->authority()}); std::set set; for (const auto &row : res) { set.insert(row[0]); @@ -3764,10 +3929,10 @@ AuthorityFactory::getDescriptionText(const std::string &code) const { "? ORDER BY table_name"; auto res = d->runWithCodeParam(sql, code); if (res.empty()) { - throw NoSuchAuthorityCodeException("object not found", getAuthority(), + throw NoSuchAuthorityCodeException("object not found", d->authority(), code); } - return res[0][0]; + return res.front()[0]; } // --------------------------------------------------------------------------- @@ -3798,7 +3963,7 @@ std::string AuthorityFactory::getOfficialNameFromAlias( if (tryEquivalentNameSpelling) { std::string sql( "SELECT table_name, auth_name, code, alt_name FROM alias_name"); - std::vector params; + ListOfParams params; if (!tableName.empty()) { sql += " WHERE table_name = ?"; params.push_back(tableName); @@ -3830,7 +3995,7 @@ std::string AuthorityFactory::getOfficialNameFromAlias( if (res.empty()) { // shouldn't happen normally return std::string(); } - return res[0][0]; + return res.front()[0]; } } return std::string(); @@ -3838,7 +4003,7 @@ std::string AuthorityFactory::getOfficialNameFromAlias( std::string sql( "SELECT table_name, auth_name, code FROM alias_name WHERE " "alt_name = ?"); - std::vector params{aliasedName}; + ListOfParams params{aliasedName}; if (!tableName.empty()) { sql += " AND table_name = ?"; params.push_back(tableName); @@ -3851,9 +4016,10 @@ std::string AuthorityFactory::getOfficialNameFromAlias( if (res.empty()) { return std::string(); } - outTableName = res[0][0]; - outAuthName = res[0][1]; - outCode = res[0][2]; + const auto &row = res.front(); + outTableName = row[0]; + outAuthName = row[1]; + outCode = row[2]; sql = "SELECT name FROM \""; sql += replaceAll(outTableName, "\"", "\"\""); sql += "\" WHERE auth_name = ? AND code = ?"; @@ -3861,7 +4027,7 @@ std::string AuthorityFactory::getOfficialNameFromAlias( if (res.empty()) { // shouldn't happen normally return std::string(); } - return res[0][0]; + return res.front()[0]; } } @@ -3921,14 +4087,14 @@ AuthorityFactory::createObjectsFromName( std::string sql( "SELECT table_name, auth_name, code, name FROM object_view WHERE " "deprecated = ? AND "); - std::vector params{deprecated ? 1.0 : 0.0}; + ListOfParams params{deprecated ? 1.0 : 0.0}; if (!approximateMatch) { sql += "name LIKE ? AND "; params.push_back(searchedNameWithoutDeprecated); } if (d->hasAuthorityRestriction()) { sql += " auth_name = ? AND "; - params.emplace_back(getAuthority()); + params.emplace_back(d->authority()); } if (allowedObjectTypes.empty()) { @@ -4045,7 +4211,7 @@ AuthorityFactory::createObjectsFromName( // so cache results. if (allowedObjectTypes.size() == 1 && allowedObjectTypes[0] == ObjectType::GEODETIC_REFERENCE_FRAME && - approximateMatch && getAuthority().empty()) { + approximateMatch && d->authority().empty()) { auto &mapCanonicalizeGRFName = d->context()->getPrivate()->getMapCanonicalizeGRFName(); if (mapCanonicalizeGRFName.empty()) { @@ -4225,10 +4391,10 @@ AuthorityFactory::listAreaOfUseFromName(const std::string &name, bool approximateMatch) const { std::string sql( "SELECT auth_name, code FROM area WHERE deprecated = 0 AND "); - std::vector params; + ListOfParams params; if (d->hasAuthorityRestriction()) { sql += " auth_name = ? AND "; - params.emplace_back(getAuthority()); + params.emplace_back(d->authority()); } sql += "name LIKE ?"; if (!approximateMatch) { @@ -4256,10 +4422,9 @@ std::list AuthorityFactory::createEllipsoidFromExisting( "abs(semi_minor_axis - ?) < 1e-10 * abs(semi_minor_axis)) OR " "((inv_flattening IS NOT NULL AND " "abs(inv_flattening - ?) < 1e-10 * abs(inv_flattening))))"); - std::vector params{ - ellipsoid->semiMajorAxis().getSIValue(), - ellipsoid->computeSemiMinorAxis().getSIValue(), - ellipsoid->computedInverseFlattening()}; + ListOfParams params{ellipsoid->semiMajorAxis().getSIValue(), + ellipsoid->computeSemiMinorAxis().getSIValue(), + ellipsoid->computedInverseFlattening()}; auto sqlRes = d->run(sql, params); std::list res; for (const auto &row : sqlRes) { @@ -4279,10 +4444,10 @@ std::list AuthorityFactory::createGeodeticCRSFromDatum( std::string sql( "SELECT auth_name, code FROM geodetic_crs WHERE " "datum_auth_name = ? AND datum_code = ? AND deprecated = 0"); - std::vector params{datum_auth_name, datum_code}; + ListOfParams params{datum_auth_name, datum_code}; if (d->hasAuthorityRestriction()) { sql += " AND auth_name = ?"; - params.emplace_back(getAuthority()); + params.emplace_back(d->authority()); } if (!geodetic_crs_type.empty()) { sql += " AND type = ?"; @@ -4315,10 +4480,10 @@ AuthorityFactory::createGeodeticCRSFromEllipsoid( "geodetic_datum.ellipsoid_code = ? AND " "geodetic_datum.deprecated = 0 AND " "geodetic_crs.deprecated = 0"); - std::vector params{ellipsoid_auth_name, ellipsoid_code}; + ListOfParams params{ellipsoid_auth_name, ellipsoid_code}; if (d->hasAuthorityRestriction()) { sql += " AND geodetic_crs.auth_name = ?"; - params.emplace_back(getAuthority()); + params.emplace_back(d->authority()); } if (!geodetic_crs_type.empty()) { sql += " AND geodetic_crs.type = ?"; @@ -4339,8 +4504,8 @@ AuthorityFactory::createGeodeticCRSFromEllipsoid( //! @cond Doxygen_Suppress static std::string buildSqlLookForAuthNameCode( - const std::list> &list, - std::vector ¶ms, const char *prefixField) { + const std::list> &list, ListOfParams ¶ms, + const char *prefixField) { std::string sql("("); std::set authorities; @@ -4428,7 +4593,7 @@ AuthorityFactory::createProjectedCRSFromExisting( "projected_crs.conversion_auth_name = conversion.auth_name AND " "projected_crs.conversion_code = conversion.code WHERE " "projected_crs.deprecated = 0 AND "); - std::vector params; + ListOfParams params; if (!candidatesGeodCRS.empty()) { sql += buildSqlLookForAuthNameCode(candidatesGeodCRS, params, "projected_crs.geodetic_crs_"); @@ -4439,7 +4604,7 @@ AuthorityFactory::createProjectedCRSFromExisting( params.emplace_back(toString(methodEPSGCode)); if (d->hasAuthorityRestriction()) { sql += " AND projected_crs.auth_name = ?"; - params.emplace_back(getAuthority()); + params.emplace_back(d->authority()); } int iParam = 1; @@ -4609,7 +4774,7 @@ AuthorityFactory::createProjectedCRSFromExisting( sql += ")"; if (d->hasAuthorityRestriction()) { sql += " AND auth_name = ?"; - params.emplace_back(getAuthority()); + params.emplace_back(d->authority()); } auto sqlRes2 = d->run(sql, params); @@ -4656,7 +4821,7 @@ AuthorityFactory::createCompoundCRSFromExisting( std::string sql("SELECT auth_name, code FROM compound_crs WHERE " "deprecated = 0 AND "); - std::vector params; + ListOfParams params; bool addAnd = false; if (!candidatesHorizCRS.empty()) { sql += buildSqlLookForAuthNameCode(candidatesHorizCRS, params, @@ -4676,7 +4841,7 @@ AuthorityFactory::createCompoundCRSFromExisting( sql += " AND "; } sql += "auth_name = ?"; - params.emplace_back(getAuthority()); + params.emplace_back(d->authority()); } auto sqlRes = d->run(sql, params); diff --git a/src/internal.cpp b/src/internal.cpp index 4bec1bf9..ecb724c2 100644 --- a/src/internal.cpp +++ b/src/internal.cpp @@ -32,6 +32,7 @@ #include "proj/internal/internal.hpp" +#include #include #ifdef _MSC_VER #include @@ -237,6 +238,38 @@ bool ends_with(const std::string &str, const std::string &suffix) noexcept { // --------------------------------------------------------------------------- double c_locale_stod(const std::string &s) { + + const auto s_size = s.size(); + // Fast path + if (s_size > 0 && s_size < 15) { + std::int64_t acc = 0; + std::int64_t div = 1; + bool afterDot = false; + size_t i = 0; + if (s[0] == '-') { + ++i; + div = -1; + } else if (s[0] == '+') { + ++i; + } + for (; i < s_size; ++i) { + const auto ch = s[i]; + if (ch >= '0' && ch <= '9') { + acc = acc * 10 + ch - '0'; + if (afterDot) { + div *= 10; + } + } else if (ch == '.') { + afterDot = true; + } else { + div = 0; + } + } + if (div) { + return static_cast(acc) / div; + } + } + std::istringstream iss(s); iss.imbue(std::locale::classic()); double d; diff --git a/src/io.cpp b/src/io.cpp index ec35bdc5..b5da2b8c 100644 --- a/src/io.cpp +++ b/src/io.cpp @@ -490,7 +490,7 @@ static std::string normalizeSerializedString(const std::string &in) { return in; } #else -static std::string normalizeSerializedString(const std::string &in) { +static inline std::string normalizeSerializedString(const std::string &in) { return in; } #endif @@ -499,11 +499,19 @@ static std::string normalizeSerializedString(const std::string &in) { void WKTFormatter::add(double number, int precision) { d->startNewChild(); - std::string val( - normalizeSerializedString(internal::toString(number, precision))); - d->result_ += val; - if (d->params_.useESRIDialect_ && val.find('.') == std::string::npos) { - d->result_ += ".0"; + if (number == 0.0) { + if (d->params_.useESRIDialect_) { + d->result_ += "0.0"; + } else { + d->result_ += '0'; + } + } else { + std::string val( + normalizeSerializedString(internal::toString(number, precision))); + d->result_ += val; + if (d->params_.useESRIDialect_ && val.find('.') == std::string::npos) { + d->result_ += ".0"; + } } } @@ -1963,8 +1971,7 @@ GeodeticReferenceFrameNNPtr WKTParser::Private::buildGeodeticReferenceFrame( foundDatumName = true; properties.set(IdentifiedObject::NAME_KEY, refDatum->nameStr()); - if (properties.find(Identifier::CODESPACE_KEY) == - properties.end() && + if (!properties.get(Identifier::CODESPACE_KEY) && refDatum->identifiers().size() == 1) { const auto &id = refDatum->identifiers()[0]; auto identifiers = ArrayOfBaseObject::create(); diff --git a/src/metadata.cpp b/src/metadata.cpp index af8dc1fe..fac2ae6b 100644 --- a/src/metadata.cpp +++ b/src/metadata.cpp @@ -858,6 +858,8 @@ struct Identifier::Private { optional description_{}; optional uri_{}; + Private() = default; + Private(const std::string &codeIn, const PropertyMap &properties) : code_(codeIn) { setProperties(properties); @@ -874,10 +876,9 @@ void Identifier::Private::setProperties( const PropertyMap &properties) // throw(InvalidValueTypeException) { { - auto oIter = properties.find(AUTHORITY_KEY); - if (oIter != properties.end()) { - if (auto genVal = - dynamic_cast(oIter->second.get())) { + const auto pVal = properties.get(AUTHORITY_KEY); + if (pVal) { + if (auto genVal = dynamic_cast(pVal->get())) { if (genVal->type() == BoxedValue::Type::STRING) { authority_ = Citation(genVal->stringValue()); } else { @@ -886,7 +887,7 @@ void Identifier::Private::setProperties( } } else { if (auto citation = - dynamic_cast(oIter->second.get())) { + dynamic_cast(pVal->get())) { authority_ = *citation; } else { throw InvalidValueTypeException("Invalid value type for " + @@ -897,10 +898,9 @@ void Identifier::Private::setProperties( } { - auto oIter = properties.find(CODE_KEY); - if (oIter != properties.end()) { - if (auto genVal = - dynamic_cast(oIter->second.get())) { + const auto pVal = properties.get(CODE_KEY); + if (pVal) { + if (auto genVal = dynamic_cast(pVal->get())) { if (genVal->type() == BoxedValue::Type::INTEGER) { code_ = toString(genVal->integerValue()); } else if (genVal->type() == BoxedValue::Type::STRING) { @@ -916,45 +916,30 @@ void Identifier::Private::setProperties( } } - { - std::string temp; - if (properties.getStringValue(CODESPACE_KEY, temp)) { - codeSpace_ = temp; - } - } - - { - std::string temp; - if (properties.getStringValue(VERSION_KEY, temp)) { - version_ = temp; - } - } - - { - std::string temp; - if (properties.getStringValue(DESCRIPTION_KEY, temp)) { - description_ = temp; - } - } - - { - std::string temp; - if (properties.getStringValue(URI_KEY, temp)) { - uri_ = temp; - } - } + properties.getStringValue(CODESPACE_KEY, codeSpace_); + properties.getStringValue(VERSION_KEY, version_); + properties.getStringValue(DESCRIPTION_KEY, description_); + properties.getStringValue(URI_KEY, uri_); } //! @endcond // --------------------------------------------------------------------------- -Identifier::Identifier(const std::string &codeIn, const PropertyMap &properties) +Identifier::Identifier(const std::string &codeIn, + const util::PropertyMap &properties) : d(internal::make_unique(codeIn, properties)) {} // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress + +// --------------------------------------------------------------------------- + +Identifier::Identifier() : d(internal::make_unique()) {} + +// --------------------------------------------------------------------------- + Identifier::Identifier(const Identifier &other) : d(internal::make_unique(*(other.d))) {} @@ -979,6 +964,17 @@ IdentifierNNPtr Identifier::create(const std::string &codeIn, // --------------------------------------------------------------------------- +//! @cond Doxygen_Suppress +IdentifierNNPtr +Identifier::createFromDescription(const std::string &descriptionIn) { + auto id = Identifier::nn_make_shared(); + id->d->description_ = descriptionIn; + return id; +} +//! @endcond + +// --------------------------------------------------------------------------- + /** \brief Return a citation for the organization responsible for definition and * maintenance of the code. * diff --git a/src/util.cpp b/src/util.cpp index b3a5149d..ac6357a2 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -239,7 +239,18 @@ ArrayOfBaseObjectNNPtr ArrayOfBaseObject::create() { //! @cond Doxygen_Suppress struct PropertyMap::Private { - std::map map_{}; + std::list> list_{}; + + // cppcheck-suppress functionStatic + void set(const std::string &key, const BoxedValueNNPtr &val) { + for (auto &pair : list_) { + if (pair.first == key) { + pair.second = val; + return; + } + } + list_.emplace_back(key, val); + } }; //! @endcond @@ -263,15 +274,13 @@ PropertyMap::~PropertyMap() = default; // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress -std::map::iterator -PropertyMap::find(const std::string &key) const { - return d->map_.find(key); -} - -// --------------------------------------------------------------------------- - -std::map::iterator PropertyMap::end() const { - return d->map_.end(); +const BaseObjectNNPtr *PropertyMap::get(const std::string &key) const { + for (const auto &pair : d->list_) { + if (pair.first == key) { + return &(pair.second); + } + } + return nullptr; } //! @endcond @@ -280,26 +289,13 @@ std::map::iterator PropertyMap::end() const { /** \brief Set a BaseObjectNNPtr as the value of a key. */ PropertyMap &PropertyMap::set(const std::string &key, const BaseObjectNNPtr &val) { - auto iter = d->map_.find(key); - if (iter != d->map_.end()) { - iter->second = val; - } else { - d->map_.insert(std::pair(key, val)); - } - return *this; -} - -// --------------------------------------------------------------------------- - -/** \brief Set a BoxedValue as the value of a key. */ -PropertyMap &PropertyMap::set(const std::string &key, const BoxedValue &val) { - auto iter = d->map_.find(key); - if (iter != d->map_.end()) { - iter->second = util::nn_make_shared(val); - } else { - d->map_.insert(std::pair( - key, util::nn_make_shared(val))); + for (auto &pair : d->list_) { + if (pair.first == key) { + pair.second = val; + return *this; + } } + d->list_.emplace_back(key, val); return *this; } @@ -307,28 +303,32 @@ PropertyMap &PropertyMap::set(const std::string &key, const BoxedValue &val) { /** \brief Set a string as the value of a key. */ PropertyMap &PropertyMap::set(const std::string &key, const std::string &val) { - return set(key, BoxedValue(val)); + d->set(key, util::nn_make_shared(val)); + return *this; } // --------------------------------------------------------------------------- /** \brief Set a string as the value of a key. */ PropertyMap &PropertyMap::set(const std::string &key, const char *val) { - return set(key, BoxedValue(val)); + d->set(key, util::nn_make_shared(val)); + return *this; } // --------------------------------------------------------------------------- /** \brief Set a integer as the value of a key. */ PropertyMap &PropertyMap::set(const std::string &key, int val) { - return set(key, BoxedValue(val)); + d->set(key, util::nn_make_shared(val)); + return *this; } // --------------------------------------------------------------------------- /** \brief Set a boolean as the value of a key. */ PropertyMap &PropertyMap::set(const std::string &key, bool val) { - return set(key, BoxedValue(val)); + d->set(key, util::nn_make_shared(val)); + return *this; } // --------------------------------------------------------------------------- @@ -350,16 +350,38 @@ bool PropertyMap::getStringValue( const std::string &key, std::string &outVal) const // throw(InvalidValueTypeException) { - auto oIter = d->map_.find(key); - if (oIter == d->map_.end()) { - return false; + for (const auto &pair : d->list_) { + if (pair.first == key) { + auto genVal = dynamic_cast(pair.second.get()); + if (genVal && genVal->type() == BoxedValue::Type::STRING) { + outVal = genVal->stringValue(); + return true; + } + throw InvalidValueTypeException("Invalid value type for " + key); + } } - auto genVal = dynamic_cast(oIter->second.get()); - if (genVal && genVal->type() == BoxedValue::Type::STRING) { - outVal = genVal->stringValue(); - return true; + return false; +} +//! @endcond + +// --------------------------------------------------------------------------- + +//! @cond Doxygen_Suppress +bool PropertyMap::getStringValue( + const std::string &key, + optional &outVal) const // throw(InvalidValueTypeException) +{ + for (const auto &pair : d->list_) { + if (pair.first == key) { + auto genVal = dynamic_cast(pair.second.get()); + if (genVal && genVal->type() == BoxedValue::Type::STRING) { + outVal = genVal->stringValue(); + return true; + } + throw InvalidValueTypeException("Invalid value type for " + key); + } } - throw InvalidValueTypeException("Invalid value type for " + key); + return false; } //! @endcond -- cgit v1.2.3 From 29b522b4b80b43fe03cb1a955789676eec8051e7 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Fri, 7 Dec 2018 18:22:53 +0100 Subject: Experimental C API: add proj_obj_query_geodetic_crs_from_datum() (for GDAL Idrisi driver) --- src/c_api.cpp | 36 ++++++++++++++++++++++++++++++++++++ src/proj_experimental.h | 7 +++++++ 2 files changed, 43 insertions(+) (limited to 'src') diff --git a/src/c_api.cpp b/src/c_api.cpp index 03a0c0bd..9d66071b 100644 --- a/src/c_api.cpp +++ b/src/c_api.cpp @@ -522,6 +522,42 @@ PJ_OBJ *proj_obj_create_from_database(PJ_CONTEXT *ctx, const char *auth_name, // --------------------------------------------------------------------------- +/** \brief Return GeodeticCRS that use the specified datum. + * + * @param ctx Context, or NULL for default context. + * @param crs_auth_name CRS authority name, or NULL. + * @param datum_auth_name Datum authority name (must not be NULL) + * @param datum_code Datum code (must not be NULL) + * @param crs_type "geographic 2D", "geographic 3D", "geocentric" or NULL + * @return a result set that must be unreferenced with + * proj_obj_list_unref(), or NULL in case of error. + */ +PJ_OBJ_LIST *proj_obj_query_geodetic_crs_from_datum(PJ_CONTEXT *ctx, + const char *crs_auth_name, + const char *datum_auth_name, + const char *datum_code, + const char *crs_type) { + assert(datum_auth_name); + assert(datum_code); + SANITIZE_CTX(ctx); + try { + auto factory = AuthorityFactory::create( + getDBcontext(ctx), crs_auth_name ? crs_auth_name : ""); + auto res = factory->createGeodeticCRSFromDatum( + datum_auth_name, datum_code, crs_type ? crs_type : ""); + std::vector objects; + for (const auto &obj : res) { + objects.push_back(obj); + } + return new PJ_OBJ_LIST(std::move(objects)); + } catch (const std::exception &e) { + proj_log_error(ctx, __FUNCTION__, e.what()); + } + return nullptr; +} + +// --------------------------------------------------------------------------- + /** \brief Drops a reference on an object. * * This method should be called one and exactly one for each function diff --git a/src/proj_experimental.h b/src/proj_experimental.h index 9af7c389..698b235b 100644 --- a/src/proj_experimental.h +++ b/src/proj_experimental.h @@ -123,6 +123,13 @@ PJ_OBJ PROJ_DLL *proj_obj_create_ellipsoidal_2D_cs(PJ_CONTEXT *ctx, const char* unit_name, double unit_conv_factor); +PJ_OBJ_LIST PROJ_DLL *proj_obj_query_geodetic_crs_from_datum( + PJ_CONTEXT *ctx, + const char *crs_auth_name, + const char *datum_auth_name, + const char *datum_code, + const char *crs_type); + PJ_OBJ PROJ_DLL *proj_obj_create_geographic_crs( PJ_CONTEXT *ctx, const char *crs_name, -- cgit v1.2.3