Repository navigation
Add UTM and MGRS coordinate functions - #108939
Conversation
Add four geographic coordinate-conversion functions: - `geoToUTM(longitude, latitude[, zone])` converts WGS84 coordinates to Universal Transverse Mercator, returning a named tuple `(easting, northing, zone, band)`. - `utmToGeo(easting, northing, zone, is_north)` is the inverse. - `geoToMGRS(longitude, latitude[, precision])` encodes a point as a Military Grid Reference System string such as `31UDQ4825111935`. - `mgrsToGeo(mgrs)` decodes an MGRS string to the centre of the referenced grid square (consistent with `geohashDecode`, and stable for round-tripping). The conversion uses the truncated transverse Mercator series on the WGS84 ellipsoid with no external dependency, applying the standard Norway and Svalbard zone exceptions. The shared math lives in `UTMCoordinates`. Validated against the independent Python `utm` and `mgrs` libraries across both hemispheres, the equator, and the Norway/Svalbard zones: easting and northing agree to sub-millimetre, and all zone numbers, latitude bands and MGRS strings match. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [27734f5] Summary: ✅
AI ReviewSummaryThis PR adds PR Metadata
Missing context / blind spots
Final VerdictStatus: Minimum required action: update the PR description and changelog entry to use |
| ``` | ||
|
|
||
| ```text | ||
| ┌─coord──────────────────────────────────┐ |
The `arm_tidy` build flagged `cppcoreguidelines-init-variables` and `readability-use-std-min-max` in `UTMCoordinates.cpp`: initialize `zone`, and replace the manual clamps with `std::clamp` and `std::min`. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- `mgrsToGeo`: reject MGRS strings with more than five digits per coordinate (previously `per` was unbounded, so an over-long string such as `31UDQ482511193512` decoded to a sub-metre cell the encoder can never produce). Now throws `BAD_ARGUMENTS`, with a regression query. - Fix the stale "south-west corner" wording in the `mgrsToGeo` `FunctionDocumentation` and the `mgrsDecode` declaration comment in `UTMCoordinates.h` to say "centre", matching the actual behaviour and the documentation page. - Docs: named tuples now render as multi-line JSON in pretty formats, so show the tuple results inline instead of in misaligned boxes.
Address a second round of review comments: - `mgrsToGeo`: reject 100km square column letters beyond the eight valid columns for the zone (e.g. `31UQD...`), which previously decoded to an easting far outside the zone and a longitude outside `[-180, 180]`. - `mgrsToGeo`: reject the even zones `32`, `34`, `36` in the `X` band, which do not exist there (e.g. `32XAA`), matching the reference implementations. - `geoToUTM`: make the Svalbard exception upper bound inclusive so that `geoToUTM(6, 84)` returns zone 31, consistent with the documented latitude domain `[-80, 84]`. - `geoToMGRS`: throw `ARGUMENT_OUT_OF_BOUND` for `precision` outside `[0, 5]` instead of silently clamping, following the avoid-fallback principle and symmetric with the `mgrsToGeo` digit-count check. Verified the new rejections and the latitude-84 zone against the Python `utm` and `mgrs` libraries; added regression queries for each case. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `SELECT '-- error handling';` label statement produces output when the test harness runs the full file, but the earlier reference was generated by stripping everything from that line onward, so the harness reported a diff. Regenerate the reference keeping the label and dropping only the `serverError`-annotated queries (which produce no output). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
From review: - `mgrsToGeo`: reject squares whose decoded latitude does not fall within the declared latitude band. A row letter that does not occur in the band (e.g. `1LAB`) previously decoded, after the northing roll-over, to a point a full ~2000km cycle away in another band. The 1 degree tolerance admits cells that straddle a band boundary (a 100km cell reaches at most ~0.5 degrees past it), which a 200k-point encode/decode sweep confirmed never over-rejects. - Tests: the Norway and Svalbard zone-exception checks used points that the normal 6 degree formula already maps to the same zone, so they did not exercise the exceptions. Use `geoToUTM(4, 60)` (normal 31 -> 32) and `geoToUTM(20, 78)` (normal 34 -> 33), and add a `1LAB` regression. Behaviour verified against the Python `mgrs` library, which rejects `1LAB`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`mgrsToGeo` advertises `FixedString` input, but `FixedString(N)` null-pads
values shorter than `N`, and those trailing `\0` bytes reached `mgrsDecode`
and failed as odd/non-digit location data. For example
`mgrsToGeo(toFixedString('31UDQ4825111935', 20))` threw instead of decoding.
Trim the trailing `\0` padding for the `ColumnFixedString` specialization
(via `if constexpr`) before decoding; `String` input is unaffected. Added a
regression query comparing the `FixedString` and `String` decodes.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
From review: - `mgrsToGeo`: bound the zone designator to one or two digits. The parser previously consumed an unbounded digit prefix, so `031UDQ...` was accepted as zone 31 and a very long prefix could overflow `std::stoi`. - `utmToGeo`: reject `is_north` values other than `0` or `1` instead of treating every nonzero value as north, matching the documented contract and the strict validation used elsewhere in these functions. Added regression queries for both. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Keep the acronym capitalisation consistent between the forward and reverse functions: the reverse functions now spell the acronym in upper case (`UTMToGeo`, `MGRSToGeo`) to match `geoToUTM` and `geoToMGRS`. Updates the function names, syntax strings, documentation and tests. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Reviewed and synced the PR after the
CI is still scheduling (Fast test / builds in progress, no failures so far). No code changes were needed. |
|
Status update (continue-pr pass): The latest AI Review " Verified now:
Replied to and resolved the new CI: no failures (75 green, 74 still in progress). |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 440/506 (86.96%) · Uncovered code |
|
Status update (continue-pr pass): The sole CI red is
Reran the failed job (the flake is timing-dependent — it only fires when the reconnect task happens to log during the upgrade-check window), so the rerun may go green on its own. The AI Review No code changes and no re-merge needed (merge-base ~today, |
|
Status update (continue-pr pass): CI is now fully green. The Independently re-verified the two remaining loose ends:
No code changes needed. The PR is effectively ready — only a human approval is outstanding. |
…e check
The upgrade check (`tests/docker_scripts/upgrade_runner.sh`) scans the
post-upgrade server log for `<Error>` lines and fails on anything not in its
allow-list. It intermittently fails with:
<Error> PostgreSQLConnectionPool: Connection error: connection to server at "192.0.2.1", port 5432 failed: timeout expired
<Error> void DB::DatabasePostgreSQL::removeOutdatedTables(): Code: 614. DB::Exception: Try 2. Connection to `192.0.2.1:5432` failed ...
These come from a leftover `DatabasePostgreSQL` engine created by
`04210_show_remote_databases_in_system_tables`, which points at the RFC 5737
documentation IP `192.0.2.1` (intentionally unreachable). The stress phase runs
the stateless tests under a global time limit and can interrupt that test
between its `CREATE DATABASE ... ENGINE = PostgreSQL('192.0.2.1:5432', ...)` and
the final `DROP DATABASE`, leaving the database in metadata. After the upgrade
restart, `DatabasePostgreSQL::startup` unconditionally activates the
`PostgreSQLCleanerTask`, whose `removeOutdatedTables` tries to connect and the
connection pool logs `<Error>` for each retry.
This is the same class of benign background-reconnection-after-restart noise
already allow-listed for Kafka (`rdk:FAIL`/`StorageKafka2`), Azure DNS, and
NuRaft. Add two regex filters in the secondary pipe that require the PostgreSQL
connection-pool / cleaner-task context together with the connection-failure
symptom, so real PostgreSQL regressions (auth, protocol, query errors) are not
masked.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108939&sha=27734f50667a6b77ca59b768e605b4d843acde3c&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29
Related: ClickHouse#108939
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
I tried out the functions with some examples - the usability seems good to me |
…e check
The upgrade check (`tests/docker_scripts/upgrade_runner.sh`) scans the
post-upgrade server log for `<Error>` lines and fails on anything not in its
allow-list. It intermittently fails with:
<Error> PostgreSQLConnectionPool: Connection error: connection to server at "192.0.2.1", port 5432 failed: timeout expired
<Error> void DB::DatabasePostgreSQL::removeOutdatedTables(): Code: 614. DB::Exception: Try 2. Connection to `192.0.2.1:5432` failed ...
These come from a leftover `DatabasePostgreSQL` engine created by
`04210_show_remote_databases_in_system_tables`, which points at the RFC 5737
documentation IP `192.0.2.1` (intentionally unreachable). The stress phase runs
the stateless tests under a global time limit and can interrupt that test
between its `CREATE DATABASE ... ENGINE = PostgreSQL('192.0.2.1:5432', ...)` and
the final `DROP DATABASE`, leaving the database in metadata. After the upgrade
restart, `DatabasePostgreSQL::startup` unconditionally activates the
`PostgreSQLCleanerTask`, whose `removeOutdatedTables` tries to connect and the
connection pool logs `<Error>` for each retry.
This is the same class of benign background-reconnection-after-restart noise
already allow-listed for Kafka (`rdk:FAIL`/`StorageKafka2`), Azure DNS, and
NuRaft. Add two regex filters in the secondary pipe that require the PostgreSQL
connection-pool / cleaner-task context together with the connection-failure
symptom, so real PostgreSQL regressions (auth, protocol, query errors) are not
masked.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108939&sha=27734f50667a6b77ca59b768e605b4d843acde3c&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29
Related: ClickHouse#108939
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add UTM and MGRS coordinate functions
Description
Add four geographic coordinate-conversion functions for the UTM (Universal Transverse Mercator) and MGRS (Military Grid Reference System) coordinate systems:
geoToUTM(longitude, latitude[, zone])— converts WGS84 coordinates to UTM, returning a named tuple(easting, northing, zone, band).UTMToGeo(easting, northing, zone, is_north)— the inverse ofgeoToUTM.geoToMGRS(longitude, latitude[, precision])— encodes a point as an MGRS string such as31UDQ4825111935.MGRSToGeo(mgrs)— decodes an MGRS string to the centre of the referenced grid square.Motivation. UTM and MGRS are widely used in surveying, GIS, GPS and mapping to work with planar coordinates in metres. ClickHouse already has
geohashEncode/geohashDecode,H3,S2and great-circle distance, but no projected-coordinate conversion, so users currently round-trip through external tools.Implementation. The conversion uses the truncated transverse Mercator series on the WGS84 ellipsoid with no new external dependency, applying the standard Norway and Svalbard zone exceptions. The shared math lives in
UTMCoordinates; the zone is auto-selected from the longitude unless an explicitzoneis given.MGRSToGeoreturns the centre of the grid square (consistent withgeohashDecodeand stable for round-tripping).The results were validated against the independent Python
utmandmgrslibraries across both hemispheres, the equator, and the Norway/Svalbard zones: easting and northing agree to sub-millimetre, and all zone numbers, latitude bands and MGRS strings match.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added functions
geoToUTM,UTMToGeo,geoToMGRSandMGRSToGeofor converting between WGS84 geographic coordinates and the UTM and MGRS coordinate systems.Documentation entry for user-facing changes
docs/en/sql-reference/functions/geo/coordinates.md.