You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sedona.apache.org by pa...@apache.org on 2026/10/14 20:07:38 UTC
(sedona-db) branch main updated: feat(rust/sedona-functions): add geometry distance-line functions (#1367)
This is an automated email from the ASF dual-hosted git repository.
paleolimbot pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/sedona-db.git
The following commit(s) were added to refs/heads/main by this push:
new 6df9b07ee feat(rust/sedona-functions): add geometry distance-line functions (#1367)
6df9b07ee is described below
commit 6df9b07ee843a34e79fd74baeff90fccb9b87d5f
Author: Dewey Dunnington <de...@dunnington.ca>
AuthorDate: Wed Oct 14 15:07:33 2026 -0500
feat(rust/sedona-functions): add geometry distance-line functions (#1367)
---
c/sedona-geos/src/lib.rs | 1 +
c/sedona-geos/src/register.rs | 2 +
c/sedona-geos/src/st_closest_point.rs | 291 ++++++++++++++++++++
docs/reference/sql/st_closestpoint.qmd | 7 +
.../{st_closestpoint.qmd => st_longestline.qmd} | 17 +-
.../{st_closestpoint.qmd => st_shortestline.qmd} | 13 +-
python/sedonadb/tests/functions/test_distance.py | 295 +++++++++++++++++++++
rust/sedona-functions/src/lib.rs | 1 +
rust/sedona-functions/src/register.rs | 1 +
rust/sedona-functions/src/st_longest_line.rs | 168 ++++++++++++
rust/sedona-functions/src/st_max_distance.rs | 37 ++-
11 files changed, 820 insertions(+), 13 deletions(-)
diff --git a/c/sedona-geos/src/lib.rs b/c/sedona-geos/src/lib.rs
index b77236e74..e7ad71dd1 100644
--- a/c/sedona-geos/src/lib.rs
+++ b/c/sedona-geos/src/lib.rs
@@ -27,6 +27,7 @@ mod st_boundary;
mod st_buffer;
mod st_buildarea;
mod st_centroid;
+mod st_closest_point;
mod st_concavehull;
mod st_convexhull;
mod st_delaunaytriangles;
diff --git a/c/sedona-geos/src/register.rs b/c/sedona-geos/src/register.rs
index 90ee56ba9..c94c55621 100644
--- a/c/sedona-geos/src/register.rs
+++ b/c/sedona-geos/src/register.rs
@@ -46,6 +46,8 @@ pub fn scalar_kernels() -> Vec<(&'static str, Vec<ScalarKernelRef>)> {
"st_buffer" => crate::st_buffer::st_buffer_impl,
"st_buffer" => crate::st_buffer::st_buffer_style_impl,
"st_centroid" => crate::st_centroid::st_centroid_impl,
+ "st_closestpoint" => crate::st_closest_point::st_closest_point_impl,
+ "st_shortestline" => crate::st_closest_point::st_shortest_line_impl,
"st_concavehull" => crate::st_concavehull::st_concave_hull_allow_holes_impl,
"st_concavehull" => crate::st_concavehull::st_concave_hull_impl,
"st_contains" => crate::binary_predicates::st_contains_impl,
diff --git a/c/sedona-geos/src/st_closest_point.rs b/c/sedona-geos/src/st_closest_point.rs
new file mode 100644
index 000000000..81f86ece2
--- /dev/null
+++ b/c/sedona-geos/src/st_closest_point.rs
@@ -0,0 +1,291 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::sync::Arc;
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::{DataFusionError, Result};
+use datafusion_expr::ColumnarValue;
+use geos::{CoordSeq, Geom, Geometry};
+use sedona_expr::{
+ item_crs::ItemCrsKernel,
+ scalar_udf::{ScalarKernelRef, SedonaScalarKernel},
+};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{
+ datatypes::{SedonaType, WKB_GEOMETRY},
+ matchers::ArgMatcher,
+};
+
+use crate::executor::GeosExecutor;
+use crate::geos_to_wkb::write_geos_geometry;
+
+/// ST_ClosestPoint() implementation using GEOS.
+pub fn st_closest_point_impl() -> Vec<ScalarKernelRef> {
+ ItemCrsKernel::wrap_impl(STClosestPoint {})
+}
+
+/// ST_ShortestLine() implementation using GEOS.
+pub fn st_shortest_line_impl() -> Vec<ScalarKernelRef> {
+ ItemCrsKernel::wrap_impl(STShortestLine {})
+}
+
+#[derive(Debug)]
+struct STClosestPoint {}
+
+impl SedonaScalarKernel for STClosestPoint {
+ fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+ let matcher = ArgMatcher::new(
+ vec![ArgMatcher::is_geometry(), ArgMatcher::is_geometry()],
+ WKB_GEOMETRY,
+ );
+
+ matcher.match_args(args)
+ }
+
+ fn invoke_batch(
+ &self,
+ arg_types: &[SedonaType],
+ args: &[ColumnarValue],
+ ) -> Result<ColumnarValue> {
+ let executor = GeosExecutor::new(arg_types, args);
+ let mut builder = BinaryBuilder::with_capacity(
+ executor.num_iterations(),
+ WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+ );
+
+ executor.execute_wkb_wkb_void(|geom1, geom2| {
+ match (geom1, geom2) {
+ (Some(geom1), Some(geom2)) => match invoke_closest_point(geom1, geom2)? {
+ Some(point) => {
+ write_geos_geometry(&point, &mut builder)?;
+ builder.append_value([]);
+ }
+ None => builder.append_null(),
+ },
+ _ => builder.append_null(),
+ }
+ Ok(())
+ })?;
+
+ executor.finish(Arc::new(builder.finish()))
+ }
+}
+
+fn nearest_points(geom1: &geos::Geometry, geom2: &geos::Geometry) -> Result<Option<CoordSeq>> {
+ let geom1_empty = geom1
+ .is_empty()
+ .map_err(|e| DataFusionError::Execution(format!("Failed to check empty geometry: {e}")))?;
+ let geom2_empty = geom2
+ .is_empty()
+ .map_err(|e| DataFusionError::Execution(format!("Failed to check empty geometry: {e}")))?;
+ if geom1_empty || geom2_empty {
+ return Ok(None);
+ }
+
+ let nearest = geom1.nearest_points(geom2).map_err(|e| {
+ DataFusionError::Execution(format!("Failed to calculate nearest points: {e}"))
+ })?;
+ Ok(Some(nearest))
+}
+
+fn invoke_closest_point(
+ geom1: &geos::Geometry,
+ geom2: &geos::Geometry,
+) -> Result<Option<Geometry>> {
+ let Some(nearest) = nearest_points(geom1, geom2)? else {
+ return Ok(None);
+ };
+ let x = nearest.get_x(0).map_err(|e| {
+ DataFusionError::Execution(format!("Failed to read closest point x coordinate: {e}"))
+ })?;
+ let y = nearest.get_y(0).map_err(|e| {
+ DataFusionError::Execution(format!("Failed to read closest point y coordinate: {e}"))
+ })?;
+ let point_coords = CoordSeq::new_from_vec(&[[x, y]]).map_err(|e| {
+ DataFusionError::Execution(format!("Failed to create closest point coordinates: {e}"))
+ })?;
+ let point = Geometry::create_point(point_coords).map_err(|e| {
+ DataFusionError::Execution(format!("Failed to create closest point geometry: {e}"))
+ })?;
+
+ Ok(Some(point))
+}
+
+#[derive(Debug)]
+struct STShortestLine {}
+
+impl SedonaScalarKernel for STShortestLine {
+ fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+ let matcher = ArgMatcher::new(
+ vec![ArgMatcher::is_geometry(), ArgMatcher::is_geometry()],
+ WKB_GEOMETRY,
+ );
+
+ matcher.match_args(args)
+ }
+
+ fn invoke_batch(
+ &self,
+ arg_types: &[SedonaType],
+ args: &[ColumnarValue],
+ ) -> Result<ColumnarValue> {
+ let executor = GeosExecutor::new(arg_types, args);
+ let mut builder = BinaryBuilder::with_capacity(
+ executor.num_iterations(),
+ WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+ );
+
+ executor.execute_wkb_wkb_void(|geom1, geom2| {
+ match (geom1, geom2) {
+ (Some(geom1), Some(geom2)) => match nearest_points(geom1, geom2)? {
+ Some(nearest) => {
+ let line = Geometry::create_line_string(nearest).map_err(|e| {
+ DataFusionError::Execution(format!(
+ "Failed to create shortest line geometry: {e}"
+ ))
+ })?;
+ write_geos_geometry(&line, &mut builder)?;
+ builder.append_value([]);
+ }
+ None => builder.append_null(),
+ },
+ _ => builder.append_null(),
+ }
+ Ok(())
+ })?;
+
+ executor.finish(Arc::new(builder.finish()))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use datafusion_common::ScalarValue;
+ use rstest::rstest;
+ use sedona_expr::scalar_udf::SedonaScalarUDF;
+ use sedona_schema::datatypes::{
+ SedonaType, WKB_GEOMETRY, WKB_GEOMETRY_ITEM_CRS, WKB_VIEW_GEOMETRY,
+ };
+ use sedona_testing::{
+ compare::assert_array_equal, create::create_array, testers::ScalarUdfTester,
+ };
+
+ use super::*;
+
+ #[rstest]
+ fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+ let udf = SedonaScalarUDF::from_impl("st_closestpoint", st_closest_point_impl());
+ let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type.clone(), sedona_type]);
+ tester.assert_return_type(WKB_GEOMETRY);
+
+ let result = tester
+ .invoke_scalar_scalar("LINESTRING (0 0, 10 10)", "POINT (5 0)")
+ .unwrap();
+ tester.assert_scalar_result_equals(result, "POINT (2.5 2.5)");
+
+ let result = tester
+ .invoke_scalar_scalar(ScalarValue::Null, ScalarValue::Null)
+ .unwrap();
+ assert!(result.is_null());
+
+ let geom1 = create_array(
+ &[
+ Some("POINT (5 0)"),
+ Some("POINT EMPTY"),
+ Some("POINT (0 0)"),
+ None,
+ ],
+ &WKB_GEOMETRY,
+ );
+ let geom2 = create_array(
+ &[
+ Some("LINESTRING (0 0, 10 10)"),
+ Some("POINT (0 0)"),
+ Some("POINT EMPTY"),
+ Some("POINT (0 0)"),
+ ],
+ &WKB_GEOMETRY,
+ );
+ let expected = create_array(&[Some("POINT (5 0)"), None, None, None], &WKB_GEOMETRY);
+ assert_array_equal(&tester.invoke_array_array(geom1, geom2).unwrap(), &expected);
+ }
+
+ #[test]
+ fn udf_invoke_item_crs() {
+ let sedona_type = WKB_GEOMETRY_ITEM_CRS.clone();
+ let udf = SedonaScalarUDF::from_impl("st_closestpoint", st_closest_point_impl());
+ let tester =
+ ScalarUdfTester::new(udf.into(), vec![sedona_type.clone(), sedona_type.clone()]);
+ tester.assert_return_type(sedona_type);
+
+ let result = tester
+ .invoke_scalar_scalar("LINESTRING (0 0, 10 10)", "POINT (5 0)")
+ .unwrap();
+ tester.assert_scalar_result_equals(result, "POINT (2.5 2.5)");
+ }
+
+ #[rstest]
+ fn shortest_line_udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+ let udf = SedonaScalarUDF::from_impl("st_shortestline", st_shortest_line_impl());
+ let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type.clone(), sedona_type]);
+ tester.assert_return_type(WKB_GEOMETRY);
+
+ let result = tester
+ .invoke_scalar_scalar("LINESTRING (0 0, 10 10)", "POINT (5 0)")
+ .unwrap();
+ tester.assert_scalar_result_equals(result, "LINESTRING (2.5 2.5, 5 0)");
+
+ let geom1 = create_array(
+ &[
+ Some("POINT (5 0)"),
+ Some("POINT EMPTY"),
+ Some("POINT (0 0)"),
+ None,
+ ],
+ &WKB_GEOMETRY,
+ );
+ let geom2 = create_array(
+ &[
+ Some("LINESTRING (0 0, 10 10)"),
+ Some("POINT (0 0)"),
+ Some("POINT EMPTY"),
+ Some("POINT (0 0)"),
+ ],
+ &WKB_GEOMETRY,
+ );
+ let expected = create_array(
+ &[Some("LINESTRING (5 0, 2.5 2.5)"), None, None, None],
+ &WKB_GEOMETRY,
+ );
+ assert_array_equal(&tester.invoke_array_array(geom1, geom2).unwrap(), &expected);
+ }
+
+ #[test]
+ fn shortest_line_udf_invoke_item_crs() {
+ let sedona_type = WKB_GEOMETRY_ITEM_CRS.clone();
+ let udf = SedonaScalarUDF::from_impl("st_shortestline", st_shortest_line_impl());
+ let tester =
+ ScalarUdfTester::new(udf.into(), vec![sedona_type.clone(), sedona_type.clone()]);
+ tester.assert_return_type(sedona_type);
+
+ let result = tester
+ .invoke_scalar_scalar("LINESTRING (0 0, 10 10)", "POINT (5 0)")
+ .unwrap();
+ tester.assert_scalar_result_equals(result, "LINESTRING (2.5 2.5, 5 0)");
+ }
+}
diff --git a/docs/reference/sql/st_closestpoint.qmd b/docs/reference/sql/st_closestpoint.qmd
index 8377a1be5..bf1e01746 100644
--- a/docs/reference/sql/st_closestpoint.qmd
+++ b/docs/reference/sql/st_closestpoint.qmd
@@ -27,6 +27,13 @@ kernels:
## Examples
+```sql
+SELECT ST_ClosestPoint(
+ ST_GeomFromText('LINESTRING(0 0, 10 10)'),
+ ST_Point(5, 0)
+);
+```
+
```sql
SELECT ST_ClosestPoint(
ST_GeogFromText('LINESTRING(0 0, 10 10)'),
diff --git a/docs/reference/sql/st_closestpoint.qmd b/docs/reference/sql/st_longestline.qmd
similarity index 74%
copy from docs/reference/sql/st_closestpoint.qmd
copy to docs/reference/sql/st_longestline.qmd
index 8377a1be5..9d8ed9246 100644
--- a/docs/reference/sql/st_closestpoint.qmd
+++ b/docs/reference/sql/st_longestline.qmd
@@ -16,8 +16,8 @@
# specific language governing permissions and limitations
# under the License.
-title: ST_ClosestPoint
-description: Returns the 2-dimensional point on geom1 that is closest to geom2.
+title: ST_LongestLine
+description: Returns the 2-dimensional longest line between the vertices of two geometries or geographies.
kernels:
- returns: geometry
args: [geometry, geometry]
@@ -28,8 +28,15 @@ kernels:
## Examples
```sql
-SELECT ST_ClosestPoint(
- ST_GeogFromText('LINESTRING(0 0, 10 10)'),
- ST_GeogPoint(5, 0)
+SELECT ST_LongestLine(
+ ST_GeomFromText('LINESTRING(0 0, 0 1)'),
+ ST_Point(1, 0)
+);
+```
+
+```sql
+SELECT ST_LongestLine(
+ ST_GeogFromText('LINESTRING(0 0, 0 1)'),
+ ST_GeogPoint(1, 0)
);
```
diff --git a/docs/reference/sql/st_closestpoint.qmd b/docs/reference/sql/st_shortestline.qmd
similarity index 80%
copy from docs/reference/sql/st_closestpoint.qmd
copy to docs/reference/sql/st_shortestline.qmd
index 8377a1be5..43422ed3d 100644
--- a/docs/reference/sql/st_closestpoint.qmd
+++ b/docs/reference/sql/st_shortestline.qmd
@@ -16,8 +16,8 @@
# specific language governing permissions and limitations
# under the License.
-title: ST_ClosestPoint
-description: Returns the 2-dimensional point on geom1 that is closest to geom2.
+title: ST_ShortestLine
+description: Returns the 2-dimensional shortest line between two geometries or geographies.
kernels:
- returns: geometry
args: [geometry, geometry]
@@ -28,7 +28,14 @@ kernels:
## Examples
```sql
-SELECT ST_ClosestPoint(
+SELECT ST_ShortestLine(
+ ST_GeomFromText('LINESTRING(0 0, 10 10)'),
+ ST_Point(5, 0)
+);
+```
+
+```sql
+SELECT ST_ShortestLine(
ST_GeogFromText('LINESTRING(0 0, 10 10)'),
ST_GeogPoint(5, 0)
);
diff --git a/python/sedonadb/tests/functions/test_distance.py b/python/sedonadb/tests/functions/test_distance.py
index 35603aa71..6d90d29b8 100644
--- a/python/sedonadb/tests/functions/test_distance.py
+++ b/python/sedonadb/tests/functions/test_distance.py
@@ -18,6 +18,301 @@ import pytest
from sedonadb.testing import geom_or_null, PostGIS, SedonaDB
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+ ("geom1", "geom2", "expected"),
+ [
+ # NULL and empty geometries
+ (None, None, None),
+ ("POINT (0 0)", None, None),
+ (None, "POINT (0 0)", None),
+ ("POINT EMPTY", "POINT (0 0)", None),
+ ("POINT (0 0)", "POINT EMPTY", None),
+ ("GEOMETRYCOLLECTION EMPTY", "POINT (0 0)", None),
+ # Point x Point
+ ("POINT (0 0)", "POINT (0 0)", "POINT (0 0)"),
+ ("POINT (0 0)", "POINT (3 4)", "POINT (0 0)"),
+ # Argument order is significant: the result lies on geom1
+ (
+ "POINT (5 0)",
+ "LINESTRING (0 0, 10 10)",
+ "POINT (5 0)",
+ ),
+ (
+ "LINESTRING (0 0, 10 10)",
+ "POINT (5 0)",
+ "POINT (2.5 2.5)",
+ ),
+ # LineString x LineString, both disjoint and intersecting
+ (
+ "LINESTRING (0 0, 10 0)",
+ "LINESTRING (2 2, 8 2)",
+ "POINT (2 0)",
+ ),
+ (
+ "LINESTRING (0 0, 10 10)",
+ "LINESTRING (0 10, 10 0)",
+ "POINT (5 5)",
+ ),
+ # Point and Polygon
+ (
+ "POINT (0.25 0.25)",
+ "POLYGON ((0 0, 2 0, 0 2, 0 0))",
+ "POINT (0.25 0.25)",
+ ),
+ (
+ "POINT (-1 0)",
+ "POLYGON ((0 0, 2 0, 0 2, 0 0))",
+ "POINT (-1 0)",
+ ),
+ (
+ "POLYGON ((0 0, 2 0, 0 2, 0 0))",
+ "POINT (-1 0)",
+ "POINT (0 0)",
+ ),
+ (
+ "POLYGON ((0 0, 2 0, 0 2, 0 0))",
+ "POINT (0.25 0.25)",
+ "POINT (0.25 0.25)",
+ ),
+ # Polygon x Polygon, both disjoint and intersecting
+ (
+ "POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))",
+ "POLYGON ((2 0, 3 0, 3 1, 2 1, 2 0))",
+ "POINT (1 0)",
+ ),
+ (
+ "POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))",
+ "POLYGON ((1 1, 3 1, 3 3, 1 3, 1 1))",
+ "POINT (1 1)",
+ ),
+ # Multi-geometries and collections
+ (
+ "MULTIPOINT ((0 0), (5 5))",
+ "POINT (4 5)",
+ "POINT (5 5)",
+ ),
+ (
+ "MULTILINESTRING ((0 0, 0 1), (5 0, 5 1))",
+ "POINT (4 0.5)",
+ "POINT (5 0.5)",
+ ),
+ (
+ "MULTIPOLYGON (((0 0, 1 0, 1 1, 0 1, 0 0)), ((5 0, 6 0, 6 1, 5 1, 5 0)))",
+ "POINT (4 0.5)",
+ "POINT (5 0.5)",
+ ),
+ (
+ "GEOMETRYCOLLECTION (POINT (0 0), LINESTRING (5 0, 5 1))",
+ "POINT (4 0.5)",
+ "POINT (5 0.5)",
+ ),
+ # ST_ClosestPoint is two-dimensional and ignores Z
+ (
+ "LINESTRING Z (0 0 10, 10 10 20)",
+ "POINT Z (5 0 100)",
+ "POINT (2.5 2.5)",
+ ),
+ ],
+)
+def test_st_closestpoint(eng, geom1, geom2, expected):
+ eng = eng.create_or_skip()
+ eng.assert_query_result(
+ f"SELECT ST_ClosestPoint({geom_or_null(geom1)}, {geom_or_null(geom2)})",
+ expected,
+ )
+
+
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+ ("geom1", "geom2", "expected"),
+ [
+ # NULL and empty geometries
+ (None, None, None),
+ ("POINT (0 0)", None, None),
+ (None, "POINT (0 0)", None),
+ ("POINT EMPTY", "POINT (0 0)", None),
+ ("POINT (0 0)", "POINT EMPTY", None),
+ ("GEOMETRYCOLLECTION EMPTY", "POINT (0 0)", None),
+ # Point x Point
+ ("POINT (0 0)", "POINT (0 0)", "LINESTRING (0 0, 0 0)"),
+ ("POINT (0 0)", "POINT (3 4)", "LINESTRING (0 0, 3 4)"),
+ # Argument order determines line direction
+ (
+ "POINT (5 0)",
+ "LINESTRING (0 0, 10 10)",
+ "LINESTRING (5 0, 2.5 2.5)",
+ ),
+ (
+ "LINESTRING (0 0, 10 10)",
+ "POINT (5 0)",
+ "LINESTRING (2.5 2.5, 5 0)",
+ ),
+ # LineString x LineString, both disjoint and intersecting
+ (
+ "LINESTRING (0 0, 1 0)",
+ "LINESTRING (3 2, 4 2)",
+ "LINESTRING (1 0, 3 2)",
+ ),
+ (
+ "LINESTRING (0 0, 10 10)",
+ "LINESTRING (0 10, 10 0)",
+ "LINESTRING (5 5, 5 5)",
+ ),
+ # Point and Polygon, including containment and argument order
+ (
+ "POINT (0.25 0.25)",
+ "POLYGON ((0 0, 2 0, 0 2, 0 0))",
+ "LINESTRING (0.25 0.25, 0.25 0.25)",
+ ),
+ (
+ "POINT (-1 0)",
+ "POLYGON ((0 0, 2 0, 0 2, 0 0))",
+ "LINESTRING (-1 0, 0 0)",
+ ),
+ (
+ "POLYGON ((0 0, 2 0, 0 2, 0 0))",
+ "POINT (-1 0)",
+ "LINESTRING (0 0, -1 0)",
+ ),
+ # Polygon x Polygon, both disjoint and intersecting
+ (
+ "POLYGON ((0 0, 1 0, 0 1, 0 0))",
+ "POLYGON ((3 2, 4 2, 3 3, 3 2))",
+ "LINESTRING (1 0, 3 2)",
+ ),
+ (
+ "POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))",
+ "POLYGON ((1 1, 3 1, 3 3, 1 3, 1 1))",
+ "LINESTRING (1 1, 1 1)",
+ ),
+ # Multi-geometries and collections
+ (
+ "MULTIPOINT ((0 0), (5 5))",
+ "POINT (4 5)",
+ "LINESTRING (5 5, 4 5)",
+ ),
+ (
+ "MULTILINESTRING ((0 0, 0 1), (5 0, 5 1))",
+ "POINT (4 0.5)",
+ "LINESTRING (5 0.5, 4 0.5)",
+ ),
+ (
+ "MULTIPOLYGON (((0 0, 1 0, 1 1, 0 1, 0 0)), ((5 0, 6 0, 6 1, 5 1, 5 0)))",
+ "POINT (4 0.5)",
+ "LINESTRING (5 0.5, 4 0.5)",
+ ),
+ (
+ "GEOMETRYCOLLECTION (POINT (0 0), LINESTRING (5 0, 5 1))",
+ "POINT (4 0.5)",
+ "LINESTRING (5 0.5, 4 0.5)",
+ ),
+ # ST_ShortestLine is two-dimensional and ignores Z
+ (
+ "LINESTRING Z (0 0 10, 10 10 20)",
+ "POINT Z (5 0 100)",
+ "LINESTRING (2.5 2.5, 5 0)",
+ ),
+ ],
+)
+def test_st_shortestline(eng, geom1, geom2, expected):
+ eng = eng.create_or_skip()
+ eng.assert_query_result(
+ f"SELECT ST_ShortestLine({geom_or_null(geom1)}, {geom_or_null(geom2)})",
+ expected,
+ )
+
+
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+ ("geom1", "geom2", "expected"),
+ [
+ # NULL and empty geometries
+ (None, None, None),
+ ("POINT (0 0)", None, None),
+ (None, "POINT (0 0)", None),
+ ("POINT EMPTY", "POINT (0 0)", None),
+ ("POINT (0 0)", "POINT EMPTY", None),
+ ("GEOMETRYCOLLECTION EMPTY", "POINT (0 0)", None),
+ # Point x Point
+ ("POINT (0 0)", "POINT (0 0)", "LINESTRING (0 0, 0 0)"),
+ ("POINT (0 0)", "POINT (3 4)", "LINESTRING (0 0, 3 4)"),
+ # Point x LineString and argument order
+ (
+ "POINT (0 0)",
+ "LINESTRING (1 0, 3 4)",
+ "LINESTRING (0 0, 3 4)",
+ ),
+ (
+ "LINESTRING (1 0, 3 4)",
+ "POINT (0 0)",
+ "LINESTRING (3 4, 0 0)",
+ ),
+ # LineString x LineString
+ (
+ "LINESTRING (0 0, 0 1)",
+ "LINESTRING (2 0, 4 3)",
+ "LINESTRING (0 0, 4 3)",
+ ),
+ # Point x Polygon, inside and outside
+ (
+ "POINT (0.5 0.2)",
+ "POLYGON ((0 0, 2 0, 0 2, 0 0))",
+ "LINESTRING (0.5 0.2, 0 2)",
+ ),
+ (
+ "POINT (-1 0)",
+ "POLYGON ((0 0, 2 0, 0 2, 0 0))",
+ "LINESTRING (-1 0, 2 0)",
+ ),
+ # Polygon x Polygon, including overlap
+ (
+ "POLYGON ((0 0, 1 0, 0 1, 0 0))",
+ "POLYGON ((10 10, 12 10, 10 13, 10 10))",
+ "LINESTRING (0 0, 10 13)",
+ ),
+ (
+ "POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))",
+ "POLYGON ((1 1, 4 1, 4 4, 1 4, 1 1))",
+ "LINESTRING (0 0, 4 4)",
+ ),
+ # Multi-geometries and collections
+ (
+ "MULTIPOINT ((0 0), (5 5))",
+ "POINT (4 5)",
+ "LINESTRING (0 0, 4 5)",
+ ),
+ (
+ "MULTILINESTRING ((0 0, 0 1), (5 0, 5 1))",
+ "POINT (-2 -1)",
+ "LINESTRING (5 1, -2 -1)",
+ ),
+ (
+ "MULTIPOLYGON (((0 0, 1 0, 1 1, 0 1, 0 0)), ((5 0, 6 0, 6 1, 5 1, 5 0)))",
+ "POINT (-2 -1)",
+ "LINESTRING (6 1, -2 -1)",
+ ),
+ (
+ "GEOMETRYCOLLECTION (POINT (0 0), LINESTRING (5 0, 5 1))",
+ "POINT (-2 -1)",
+ "LINESTRING (5 1, -2 -1)",
+ ),
+ # ST_LongestLine is two-dimensional and ignores Z
+ (
+ "LINESTRING Z (0 0 10, 10 10 20)",
+ "POINT Z (5 0 100)",
+ "LINESTRING (10 10, 5 0)",
+ ),
+ ],
+)
+def test_st_longestline(eng, geom1, geom2, expected):
+ eng = eng.create_or_skip()
+ eng.assert_query_result(
+ f"SELECT ST_LongestLine({geom_or_null(geom1)}, {geom_or_null(geom2)})",
+ expected,
+ )
+
+
@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
@pytest.mark.parametrize(
("geom1", "geom2", "expected"),
diff --git a/rust/sedona-functions/src/lib.rs b/rust/sedona-functions/src/lib.rs
index c848aa01d..8f670ccf1 100644
--- a/rust/sedona-functions/src/lib.rs
+++ b/rust/sedona-functions/src/lib.rs
@@ -48,6 +48,7 @@ mod st_iscollection;
mod st_isempty;
mod st_knn;
mod st_linesubstring;
+mod st_longest_line;
mod st_makeenvelope;
mod st_makeline;
mod st_max_distance;
diff --git a/rust/sedona-functions/src/register.rs b/rust/sedona-functions/src/register.rs
index 41eb3cbb7..49ce8a0a1 100644
--- a/rust/sedona-functions/src/register.rs
+++ b/rust/sedona-functions/src/register.rs
@@ -121,6 +121,7 @@ pub fn default_function_set() -> FunctionSet {
crate::st_xyzm::st_z_udf,
crate::st_zmflag::st_zmflag_udf,
crate::st_linesubstring::st_line_substring_udf,
+ crate::st_longest_line::st_longest_line_udf,
crate::st_max_distance::st_max_distance_udf
);
diff --git a/rust/sedona-functions/src/st_longest_line.rs b/rust/sedona-functions/src/st_longest_line.rs
new file mode 100644
index 000000000..8aff90b02
--- /dev/null
+++ b/rust/sedona-functions/src/st_longest_line.rs
@@ -0,0 +1,168 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::{io::Write, sync::Arc};
+
+use arrow_array::builder::BinaryBuilder;
+use datafusion_common::{DataFusionError, Result};
+use datafusion_expr::{ColumnarValue, Volatility};
+use geo_traits::Dimensions;
+use sedona_expr::{
+ item_crs::ItemCrsKernel,
+ scalar_udf::{SedonaScalarKernel, SedonaScalarUDF},
+};
+use sedona_geometry::wkb_factory::{WKB_MIN_PROBABLE_BYTES, write_wkb_linestring_header};
+use sedona_schema::{
+ datatypes::{SedonaType, WKB_GEOMETRY},
+ matchers::ArgMatcher,
+};
+
+use crate::{executor::WkbExecutor, st_max_distance::farthest_coords};
+
+/// ST_LongestLine() scalar UDF.
+pub fn st_longest_line_udf() -> SedonaScalarUDF {
+ SedonaScalarUDF::new(
+ "st_longestline",
+ ItemCrsKernel::wrap_impl(STLongestLine {}),
+ Volatility::Immutable,
+ )
+}
+
+#[derive(Debug)]
+struct STLongestLine {}
+
+impl SedonaScalarKernel for STLongestLine {
+ fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+ let matcher = ArgMatcher::new(
+ vec![ArgMatcher::is_geometry(), ArgMatcher::is_geometry()],
+ WKB_GEOMETRY,
+ );
+ matcher.match_args(args)
+ }
+
+ fn invoke_batch(
+ &self,
+ arg_types: &[SedonaType],
+ args: &[ColumnarValue],
+ ) -> Result<ColumnarValue> {
+ let executor = WkbExecutor::new(arg_types, args);
+ let mut builder = BinaryBuilder::with_capacity(
+ executor.num_iterations(),
+ WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+ );
+ let mut lhs_coords = Vec::new();
+ let mut rhs_coords = Vec::new();
+
+ executor.execute_wkb_wkb_void(|lhs, rhs| {
+ match (lhs, rhs) {
+ (Some(lhs), Some(rhs)) => {
+ match farthest_coords(lhs, rhs, &mut lhs_coords, &mut rhs_coords) {
+ Some((a, b)) => {
+ write_wkb_linestring_header(&mut builder, Dimensions::Xy, 2)
+ .map_err(|e| DataFusionError::External(Box::new(e)))?;
+ for ordinate in [a.0, a.1, b.0, b.1] {
+ builder.write_all(&ordinate.to_le_bytes())?;
+ }
+ builder.append_value([]);
+ }
+ None => builder.append_null(),
+ }
+ }
+ _ => builder.append_null(),
+ }
+ Ok(())
+ })?;
+
+ executor.finish(Arc::new(builder.finish()))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use datafusion_common::ScalarValue;
+ use rstest::rstest;
+ use sedona_schema::datatypes::{
+ WKB_GEOMETRY, WKB_GEOMETRY_ITEM_CRS, WKB_LARGE_GEOMETRY, WKB_VIEW_GEOMETRY,
+ };
+ use sedona_testing::{
+ compare::assert_array_equal, create::create_array, testers::ScalarUdfTester,
+ };
+
+ use super::*;
+
+ #[rstest]
+ fn udf(#[values(WKB_GEOMETRY, WKB_LARGE_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+ let tester = ScalarUdfTester::new(
+ st_longest_line_udf().into(),
+ vec![sedona_type.clone(), sedona_type],
+ );
+ tester.assert_return_type(WKB_GEOMETRY);
+
+ let result = tester
+ .invoke_scalar_scalar("LINESTRING (0 0, 0 1)", "POINT (1 0)")
+ .unwrap();
+ tester.assert_scalar_result_equals(result, "LINESTRING (0 1, 1 0)");
+
+ let result = tester
+ .invoke_scalar_scalar(ScalarValue::Null, ScalarValue::Null)
+ .unwrap();
+ assert!(result.is_null());
+
+ let lhs = create_array(
+ &[Some("POINT (0 0)"), Some("POINT EMPTY"), None],
+ &WKB_GEOMETRY,
+ );
+ let rhs = create_array(
+ &[
+ Some("LINESTRING (0 0, 0 2)"),
+ Some("POINT (0 0)"),
+ Some("POINT (0 0)"),
+ ],
+ &WKB_GEOMETRY,
+ );
+ let expected = create_array(&[Some("LINESTRING (0 0, 0 2)"), None, None], &WKB_GEOMETRY);
+ assert_array_equal(&tester.invoke_array_array(lhs, rhs).unwrap(), &expected);
+ }
+
+ #[test]
+ fn udf_invoke_item_crs() {
+ let sedona_type = WKB_GEOMETRY_ITEM_CRS.clone();
+ let tester = ScalarUdfTester::new(
+ st_longest_line_udf().into(),
+ vec![sedona_type.clone(), sedona_type.clone()],
+ );
+ tester.assert_return_type(sedona_type);
+
+ let result = tester
+ .invoke_scalar_scalar("POINT (0 0)", "POINT (3 4)")
+ .unwrap();
+ tester.assert_scalar_result_equals(result, "LINESTRING (0 0, 3 4)");
+ }
+
+ #[test]
+ fn selects_longest_line_without_distance_overflow() {
+ let tester = ScalarUdfTester::new(
+ st_longest_line_udf().into(),
+ vec![WKB_GEOMETRY, WKB_GEOMETRY],
+ );
+
+ let result = tester
+ .invoke_scalar_scalar("MULTIPOINT ((1e200 0), (0 0))", "POINT (2e200 0)")
+ .unwrap();
+ tester.assert_scalar_result_equals(result, "LINESTRING (0 0, 2e200 0)");
+ }
+}
diff --git a/rust/sedona-functions/src/st_max_distance.rs b/rust/sedona-functions/src/st_max_distance.rs
index b68a50de5..2498d8bd5 100644
--- a/rust/sedona-functions/src/st_max_distance.rs
+++ b/rust/sedona-functions/src/st_max_distance.rs
@@ -88,6 +88,18 @@ fn invoke_scalar(
lhs_coords: &mut Vec<(f64, f64)>,
rhs_coords: &mut Vec<(f64, f64)>,
) -> Option<f64> {
+ let (a, b) = farthest_coords(lhs, rhs, lhs_coords, rhs_coords)?;
+ let dx = a.0 - b.0;
+ let dy = a.1 - b.1;
+ Some(dx.hypot(dy))
+}
+
+pub(crate) fn farthest_coords(
+ lhs: &Wkb,
+ rhs: &Wkb,
+ lhs_coords: &mut Vec<(f64, f64)>,
+ rhs_coords: &mut Vec<(f64, f64)>,
+) -> Option<((f64, f64), (f64, f64))> {
lhs_coords.clear();
rhs_coords.clear();
@@ -98,19 +110,21 @@ fn invoke_scalar(
return None;
}
- let mut max_dist_sq = f64::NEG_INFINITY;
+ let mut farthest = None;
+ let mut max_distance = f64::NEG_INFINITY;
for a in lhs_coords {
for b in &*rhs_coords {
let dx = a.0 - b.0;
let dy = a.1 - b.1;
- let d2 = dx * dx + dy * dy;
- if d2 > max_dist_sq {
- max_dist_sq = d2;
+ let distance = dx.hypot(dy);
+ if distance > max_distance {
+ max_distance = distance;
+ farthest = Some((*a, *b));
}
}
}
- Some(max_dist_sq.max(0.0).sqrt())
+ farthest
}
fn collect_coords(geom: &impl GeometryTrait<T = f64>, coords: &mut Vec<(f64, f64)>) {
@@ -259,4 +273,17 @@ mod tests {
.unwrap();
tester.assert_scalar_result_equals(result, 5.0);
}
+
+ #[test]
+ fn distance_does_not_overflow_for_large_coordinates() {
+ let tester = ScalarUdfTester::new(
+ st_max_distance_udf().into(),
+ vec![WKB_GEOMETRY, WKB_GEOMETRY],
+ );
+
+ let result = tester
+ .invoke_scalar_scalar("MULTIPOINT ((1e200 0), (0 0))", "POINT (2e200 0)")
+ .unwrap();
+ tester.assert_scalar_result_equals(result, 2e200);
+ }
}