Skip to content

feat(function): add S2 and H3 geospatial cell functions - #24

Open
fengttt wants to merge 10 commits into
mainfrom
feature/s2h3-funcs
Open

fengttt wants to merge 10 commits into
mainfrom
feature/s2h3-funcs

Conversation

@fengttt

@fengttt fengttt commented Jun 21, 2026

Copy link
Copy Markdown
Owner

Implements the S2_* and H3_* SQL functions described in docs/design/s2h3_funcs.md.

Functions

S2 (via github.com/golang/geo/s2, already a dependency):
s2_cellid(POINT), s2_cellid_level, s2_cellid_center, s2_cellid_area, s2_cellid_parent, s2_cellid_edgeneighbours, s2_cellid_allneighbours, s2_cellid_areneighbours

H3 (via github.com/uber/h3-go/v4, newly added — cgo-backed, bundles the H3 C library):
h3_h3index(POINT[, res]), h3_h3index_resolution, h3_h3index_center, h3_h3index_boundary, h3_h3index_parent[, res], h3_h3index_neighbours, h3_h3index_areneighbours

A CellId / H3Index is BIGINT UNSIGNED (uint64). A POINT argument carries (longitude, latitude). Neighbour lists return a JSON array of uint64 encoded with bytejson's native uint64 type code so the full 64-bit id is preserved (above 2^53 a JSON float would lose precision). Both British and American spellings of "neighbour(s)" are accepted.

Decisions vs. the design note

  • s2_cellid_parent returns a CellId, not a POINT (the note's "returns POINT" contradicted its own description and the symmetric h3_h3index_parent).
  • h3_h3index(POINT) defaults to resolution 15 and gained an optional explicit-resolution overload — H3 needs a resolution to pick a cell, unlike S2 where a point maps to a unique leaf cell.
  • s2_cellid_area returns square metres rather than S2's native unit-sphere steradians, so it is directly usable and comparable to H3.

Files

  • pkg/sql/plan/function/func_s2h3.go (new — implementations + helpers)
  • pkg/sql/plan/function/function_id.go, function_id_test.go, list_builtIn.go (ids + registration)
  • go.mod / go.sum (h3-go/v4)
  • docs/design/s2h3_funcs.md (appended implementation details)
  • test/distributed/cases/geo/geo_s2h3.{sql,result} (BVT)

Testing

  • Full mo-service build + link clean.
  • Test_funids ID-registration unit test passes.
  • BVT geo_s2h3.sql: 34/34 statements pass (100%), covering every function, the stored BIGINT UNSIGNED column path, and invalid-input error cases.

Note

h3-go/v4 is cgo-backed and bundles the H3 C library — worth a look for CI / musl builds.

🤖 Generated with Claude Code

Implement the S2_* and H3_* SQL functions described in
docs/design/s2h3_funcs.md.

S2 (github.com/golang/geo/s2, already a dependency):
  s2_cellid(POINT), s2_cellid_level, s2_cellid_center,
  s2_cellid_area, s2_cellid_parent, s2_cellid_edgeneighbours,
  s2_cellid_allneighbours, s2_cellid_areneighbours

H3 (github.com/uber/h3-go/v4, newly added):
  h3_h3index(POINT[, res]), h3_h3index_resolution,
  h3_h3index_center, h3_h3index_boundary, h3_h3index_parent[ , res],
  h3_h3index_neighbours, h3_h3index_areneighbours

A CellId / H3Index is BIGINT UNSIGNED (uint64). Neighbour lists return
a JSON array of uint64 encoded with bytejson's native uint64 type code
so the full 64-bit id is preserved. Both British and American spellings
of "neighbour(s)" are accepted.

Decisions vs. the design note (see doc):
- s2_cellid_parent returns a CellId, not a POINT (spec typo).
- h3_h3index(POINT) defaults to resolution 15 and gained an optional
  explicit-resolution overload (H3 needs a resolution to pick a cell).
- s2_cellid_area returns square metres rather than S2 steradians.

BVT: test/distributed/cases/geo/geo_s2h3.sql (34 statements, all pass).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Resolve Copilot and self-review comments:

- docs: fix spec typos flagged by Copilot (S2_CellId_Parent return type
  POINT->CellId, EdegNeighbours->EdgeNeighbours, "bounday"->"boundary",
  "return"->"returns", jsonb->JSON); document the lon/lat degree range
  contract and the "evaluated at the first cell's level" are-neighbours
  semantics.
- func_s2h3.go: guard NaN/Inf in validLatLng (the range checks alone let
  NaN through); give a domain error ("H3Index at resolution 0 has no
  parent") instead of leaking the h3 library message.
- BVT: expand geo_s2h3.sql from 34 to 58 statements — NULL inputs
  (scalar + vectorized), GEOMETRY32/POINT32 overloads, boundary
  resolutions/levels, neighbour symmetry and cross-level cases, and the
  remaining error paths.
- Add func_s2h3_test.go: Go unit tests for validLatLng (incl. NaN/Inf),
  uint64ListToJSON precision (>2^53), and s2/h3 validity helpers.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
ST_Point(x, y) builds a POINT geometry from numeric coordinates (x = X /
longitude, y = Y / latitude, matching WKT POINT(x y) order), returning a
plain GEOMETRY (SRID 0). ST_Point32(x, y) is the float32 GEOMETRY32 variant.
They are the numeric counterparts of ST_PointFromText('POINT(x y)') and pair
naturally with the new S2_*/H3_* functions, which take a POINT argument.

- Non-finite coordinates raise an error; a NULL ordinate yields NULL.
- Function ids ST_POINT=534, ST_POINT32=535.
- BVT: test/distributed/cases/geo/geo_stpoint.sql (16 stmts, all pass).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Replace the geometry-specific bindNumVal guard from the previous commit
with the correct, general fix. The root problem is that buildValueScan
binds every VALUES item with a DefaultBinder carrying the destination
column type, and that type is pushed down to nested literals. That target
type is only meaningful for a bare literal value, not for the literal
arguments of a function call: st_point(116.3975, 39.9087) bound the float
args against the GEOMETRY column type, breaking overload resolution
("bad value [GEOMETRY GEOMETRY]") — and the same class of bug could affect
any column type, not just geometry.

Now a compound value expression (function/operator) is bound with a
binder that has no column type, so its literal arguments bind by their own
type; the result is cast to the column type afterward (funcCastFor*Type /
forceCastExpr2). A bare literal value still binds against the column type
as before. bindNumVal is reverted to its original behavior.

Regression: geo, dml/insert, dml/update, dml/replace, expression and
operator BVT suites all pass 100%; geo_stpoint.result is unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous commit bound every non-bare-literal VALUES expression without
the column type, which regressed inserts where the column type is
legitimately needed by a nested literal: a negative literal like
-999.995 (a UnaryExpr) and a cast like 123.45::int (a CastExpr) lost the
destination decimal/precision and failed dtype/decimal and pg_cast BVT.

Narrow the rule to actual function calls (*tree.FuncExpr), matching the
real problem: st_point(116.3975, 39.9087) must bind its float arguments by
their own types, not the GEOMETRY column type. Unary/cast/other value
expressions keep binding against the column type as before.

Verified locally: dtype/decimal, pg_cast (the CI failures), plus geo,
dml/insert, dml/update, expression, operator all pass 100%. Remaining
local dtype/function failures are pre-existing stage/datalink/wasm
environment cases (green in CI), unrelated to this change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nstructors

Two correctness fixes from PR review (XuPeng-SH):

1. h3_h3index_areneighbours: h3-go v4.5.0's IsNeighbor returns a
   resolution-mismatch error for two valid cells at different resolutions,
   contradicting the documented "cross-resolution returns false" semantics.
   Detect differing resolutions before IsNeighbor and return false, matching
   the S2 cross-level behavior. Added an H3 ancestor/descendant regression.

2. INSERT ... VALUES binder only used the function-call binder when the
   top-level node was exactly *tree.FuncExpr, so wrapped constructors —
   (st_point(...)) and cast(st_point(...) as point) — still bound their
   arguments against the destination column type and could fail overload
   resolution. Unwrap ParenExpr/CastExpr before deciding. Added regression
   cases for parenthesized and cast-wrapped constructors into point/point32.
   A cast wrapping a bare literal (123.45::int) is unaffected.

Also added American-spelling alias coverage (s2_cellid_allneighbors,
s2_cellid_edgeneighbors, h3_h3index_neighbors, *_areneighbors).

Verified: geo, dtype/decimal and pg_cast (the prior CI failures) all 100%.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts:
#	pkg/sql/plan/function/function_id.go
#	pkg/sql/plan/function/function_id_test.go

This branch had an error being deployed

1 failed deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant