You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@sedona.apache.org by "yutannihilation (via GitHub)" <gi...@apache.org> on 2025/10/26 14:55:33 UTC

[PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

yutannihilation opened a new pull request, #245:
URL: https://github.com/apache/sedona-db/pull/245

   As many people are adding geos-related functions, I pick this to avoid collision.
   
   At first, I thought this can be implemented via `geo_traits::CoordTrait`. But, I read the implementation of `ST_Point` and felt it's preferable to handle the raw bytes of WKB for performance. While I'm not good at performance, I'm trying to implement it. The remaining tasks are:
   
   - [ ] Handle big endian
   - [ ] Add Python tests
   - [ ] Add benchmark


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

Posted by "yutannihilation (via GitHub)" <gi...@apache.org>.
yutannihilation commented on PR #245:
URL: https://github.com/apache/sedona-db/pull/245#issuecomment-3455898023

   Thanks for reviewing!
   
   Sorry, this was unexpected, but I just found [the document](https://postgis.net/docs/en/ST_StartPoint.html) has this small note
   
   > Enhanced: 3.2.0 returns a point for all geometries. Prior behavior returns NULLs if input was not a LineString.
   
   and this is the actual behavior (while the example on the document returns `t`...)
   
   ```
   postgres=# SELECT ST_StartPoint('POINT(0 1)'::geometry) IS NULL AS is_null;
    is_null 
   ---------
    f
   (1 row)
   ```
   
   Probably I need some time to update the implementation.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on PR #245:
URL: https://github.com/apache/sedona-db/pull/245#issuecomment-3449140793

   > As many people are adding geos-related functions, I pick this to avoid collision.
   
   Thank you!
   
   > At first, I thought this can be implemented via geo_traits::CoordTrait. But, I read the implementation of ST_Point and felt it's preferable to handle the raw bytes of WKB for performance.
   
   I think using `GeoTraits` or the `Wkb` object directly would be roughly equivalent in terms of performance and would be a whole lot easier to write. While we do care about performance, we also care about bug surface area and maintainability. There are some functions were we work with WKB bytes directly but all of them had simpler implementations first that we benchmarked to ensure that the complexity had measurable benefit.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

Posted by "yutannihilation (via GitHub)" <gi...@apache.org>.
yutannihilation commented on PR #245:
URL: https://github.com/apache/sedona-db/pull/245#issuecomment-3452084760

   It seems I still have troubles on running Python tests on my Windows, so I don't run these Python tests yet. I'll try on macOS tomorrow. Anyway, I believe this pull request is ready for review now.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #245:
URL: https://github.com/apache/sedona-db/pull/245#discussion_r2470522993


##########
rust/sedona-functions/src/st_start_point.rs:
##########
@@ -0,0 +1,276 @@
+// 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 arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::{
+    scalar_doc_sections::DOC_SECTION_OTHER, ColumnarValue, Documentation, Volatility,
+};
+use geo_traits::{
+    CoordTrait, GeometryCollectionTrait, GeometryTrait, LineStringTrait, MultiLineStringTrait,
+    MultiPointTrait, MultiPolygonTrait, PointTrait, PolygonTrait,
+};
+use sedona_common::sedona_internal_err;
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::{
+    error::SedonaGeometryError,
+    wkb_factory::{write_wkb_coord_trait, write_wkb_point_header, WKB_MIN_PROBABLE_BYTES},
+};
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::{io::Write, sync::Arc};
+
+use crate::executor::WkbExecutor;
+
+/// ST_StartPoint() scalar UDF
+///
+/// Native implementation to get the start point of a geometry
+pub fn st_start_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_startpoint",
+        vec![Arc::new(STStartOrEndPoint::new(true))],
+        Volatility::Immutable,
+        Some(st_start_point_doc()),
+    )
+}
+
+fn st_start_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the start point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_StartPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_StartPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+/// ST_EndPoint() scalar UDF
+///
+/// Native implementation to get the end point of a geometry
+pub fn st_end_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_endpoint",
+        vec![Arc::new(STStartOrEndPoint::new(false))],
+        Volatility::Immutable,
+        Some(st_end_point_doc()),
+    )
+}
+
+fn st_end_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the end point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_EndPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_EndPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+#[derive(Debug)]
+struct STStartOrEndPoint {
+    from_start: bool,
+}
+
+impl STStartOrEndPoint {
+    fn new(from_start: bool) -> Self {
+        STStartOrEndPoint { from_start }
+    }
+}
+
+impl SedonaScalarKernel for STStartOrEndPoint {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![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(),
+        );
+
+        executor.execute_wkb_void(|maybe_wkb| {
+            if let Some(wkb) = maybe_wkb {
+                if let Some(coord) = extract_first_geometry(&wkb, self.from_start) {
+                    if write_wkb_start_point(&mut builder, coord).is_err() {
+                        return sedona_internal_err!("Failed to write WKB point header");
+                    };
+                    builder.append_value([]);
+                    return Ok(());
+                }
+            }
+
+            builder.append_null();
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn write_wkb_start_point(
+    buf: &mut impl Write,
+    coord: impl CoordTrait<T = f64>,
+) -> Result<(), SedonaGeometryError> {
+    write_wkb_point_header(buf, coord.dim())?;
+    write_wkb_coord_trait(buf, &coord)
+}
+
+// - ST_StartPoint returns result for all types of geometries
+// - ST_EndPoint returns result only for LINESTRING
+fn extract_first_geometry<'a>(

Review Comment:
   Optional nit:
   
   ```suggestion
   fn extract_start_or_end_coord<'a>(
   
   ```



##########
rust/sedona-functions/src/st_start_point.rs:
##########
@@ -0,0 +1,276 @@
+// 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 arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::{
+    scalar_doc_sections::DOC_SECTION_OTHER, ColumnarValue, Documentation, Volatility,
+};
+use geo_traits::{
+    CoordTrait, GeometryCollectionTrait, GeometryTrait, LineStringTrait, MultiLineStringTrait,
+    MultiPointTrait, MultiPolygonTrait, PointTrait, PolygonTrait,
+};
+use sedona_common::sedona_internal_err;
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::{
+    error::SedonaGeometryError,
+    wkb_factory::{write_wkb_coord_trait, write_wkb_point_header, WKB_MIN_PROBABLE_BYTES},
+};
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::{io::Write, sync::Arc};
+
+use crate::executor::WkbExecutor;
+
+/// ST_StartPoint() scalar UDF
+///
+/// Native implementation to get the start point of a geometry
+pub fn st_start_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_startpoint",
+        vec![Arc::new(STStartOrEndPoint::new(true))],
+        Volatility::Immutable,
+        Some(st_start_point_doc()),
+    )
+}
+
+fn st_start_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the start point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_StartPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_StartPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+/// ST_EndPoint() scalar UDF
+///
+/// Native implementation to get the end point of a geometry
+pub fn st_end_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_endpoint",
+        vec![Arc::new(STStartOrEndPoint::new(false))],
+        Volatility::Immutable,
+        Some(st_end_point_doc()),
+    )
+}
+
+fn st_end_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the end point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_EndPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_EndPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+#[derive(Debug)]
+struct STStartOrEndPoint {
+    from_start: bool,
+}
+
+impl STStartOrEndPoint {
+    fn new(from_start: bool) -> Self {
+        STStartOrEndPoint { from_start }
+    }
+}
+
+impl SedonaScalarKernel for STStartOrEndPoint {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![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(),
+        );
+
+        executor.execute_wkb_void(|maybe_wkb| {
+            if let Some(wkb) = maybe_wkb {
+                if let Some(coord) = extract_first_geometry(&wkb, self.from_start) {
+                    if write_wkb_start_point(&mut builder, coord).is_err() {
+                        return sedona_internal_err!("Failed to write WKB point header");
+                    };
+                    builder.append_value([]);
+                    return Ok(());
+                }
+            }
+
+            builder.append_null();
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn write_wkb_start_point(
+    buf: &mut impl Write,
+    coord: impl CoordTrait<T = f64>,
+) -> Result<(), SedonaGeometryError> {
+    write_wkb_point_header(buf, coord.dim())?;
+    write_wkb_coord_trait(buf, &coord)
+}
+
+// - ST_StartPoint returns result for all types of geometries
+// - ST_EndPoint returns result only for LINESTRING
+fn extract_first_geometry<'a>(
+    wkb: &'a wkb::reader::Wkb<'a>,
+    from_start: bool,
+) -> Option<wkb::reader::Coord<'a>> {
+    match (wkb.as_type(), from_start) {
+        (geo_traits::GeometryType::Point(point), true) => point.coord(),
+        (geo_traits::GeometryType::LineString(line_string), true) => line_string.coord(0),
+        (geo_traits::GeometryType::LineString(line_string), false) => {
+            line_string.coord(line_string.num_coords() - 1)
+        }
+        (geo_traits::GeometryType::Polygon(polygon), true) => match polygon.exterior() {
+            Some(ring) => ring.coord(0),
+            None => None,
+        },
+        (geo_traits::GeometryType::MultiPoint(multi_point), true) => match multi_point.point(0) {
+            Some(point) => point.coord(),
+            None => None,
+        },
+        (geo_traits::GeometryType::MultiLineString(multi_line_string), true) => {
+            match multi_line_string.line_string(0) {
+                Some(line_string) => line_string.coord(0),
+                None => None,
+            }
+        }
+        (geo_traits::GeometryType::MultiPolygon(multi_polygon), true) => {
+            match multi_polygon.polygon(0) {
+                Some(polygon) => match polygon.exterior() {
+                    Some(ring) => ring.coord(0),
+                    None => None,
+                },
+                None => None,
+            }
+        }
+        (geo_traits::GeometryType::GeometryCollection(geometry_collection), true) => {
+            match geometry_collection.geometry(0) {
+                Some(geometry) => extract_first_geometry(geometry, from_start),
+                None => None,
+            }
+        }
+        (geo_traits::GeometryType::Rect(_), true) => None,
+        (geo_traits::GeometryType::Triangle(_), true) => None,
+        (geo_traits::GeometryType::Line(_), true) => None,
+        _ => None,
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use datafusion_expr::ScalarUDF;
+    use rstest::rstest;
+    use sedona_schema::datatypes::WKB_VIEW_GEOMETRY;
+    use sedona_testing::{
+        compare::assert_array_equal, create::create_array, testers::ScalarUdfTester,
+    };
+
+    use super::*;
+
+    #[test]
+    fn udf_metadata() {
+        let st_start_point_udf: ScalarUDF = st_start_point_udf().into();
+        assert_eq!(st_start_point_udf.name(), "st_startpoint");
+        assert!(st_start_point_udf.documentation().is_some());
+
+        let st_end_point_udf: ScalarUDF = st_end_point_udf().into();
+        assert_eq!(st_end_point_udf.name(), "st_endpoint");
+        assert!(st_end_point_udf.documentation().is_some());
+    }
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let tester_start_point =
+            ScalarUdfTester::new(st_start_point_udf().into(), vec![sedona_type.clone()]);
+        let tester_end_point =
+            ScalarUdfTester::new(st_end_point_udf().into(), vec![sedona_type.clone()]);
+
+        let input = create_array(
+            &[
+                Some("LINESTRING (1 2, 3 4, 5 6)"),

Review Comment:
   For full test coverage of your implementation I think we would need to test empty geometries here as well.



##########
rust/sedona-functions/src/st_start_point.rs:
##########
@@ -0,0 +1,276 @@
+// 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 arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::{
+    scalar_doc_sections::DOC_SECTION_OTHER, ColumnarValue, Documentation, Volatility,
+};
+use geo_traits::{
+    CoordTrait, GeometryCollectionTrait, GeometryTrait, LineStringTrait, MultiLineStringTrait,
+    MultiPointTrait, MultiPolygonTrait, PointTrait, PolygonTrait,
+};
+use sedona_common::sedona_internal_err;
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::{
+    error::SedonaGeometryError,
+    wkb_factory::{write_wkb_coord_trait, write_wkb_point_header, WKB_MIN_PROBABLE_BYTES},
+};
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::{io::Write, sync::Arc};
+
+use crate::executor::WkbExecutor;
+
+/// ST_StartPoint() scalar UDF
+///
+/// Native implementation to get the start point of a geometry
+pub fn st_start_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_startpoint",
+        vec![Arc::new(STStartOrEndPoint::new(true))],
+        Volatility::Immutable,
+        Some(st_start_point_doc()),
+    )
+}
+
+fn st_start_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the start point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_StartPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_StartPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+/// ST_EndPoint() scalar UDF
+///
+/// Native implementation to get the end point of a geometry
+pub fn st_end_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_endpoint",
+        vec![Arc::new(STStartOrEndPoint::new(false))],
+        Volatility::Immutable,
+        Some(st_end_point_doc()),
+    )
+}
+
+fn st_end_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the end point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_EndPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_EndPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+#[derive(Debug)]
+struct STStartOrEndPoint {
+    from_start: bool,
+}
+
+impl STStartOrEndPoint {
+    fn new(from_start: bool) -> Self {
+        STStartOrEndPoint { from_start }
+    }
+}
+
+impl SedonaScalarKernel for STStartOrEndPoint {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![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(),
+        );
+
+        executor.execute_wkb_void(|maybe_wkb| {
+            if let Some(wkb) = maybe_wkb {
+                if let Some(coord) = extract_first_geometry(&wkb, self.from_start) {
+                    if write_wkb_start_point(&mut builder, coord).is_err() {
+                        return sedona_internal_err!("Failed to write WKB point header");
+                    };
+                    builder.append_value([]);
+                    return Ok(());
+                }
+            }
+
+            builder.append_null();
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn write_wkb_start_point(

Review Comment:
   Optional nit:
   
   ```suggestion
   fn write_wkb_coord(
   
   ```



##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -1016,6 +1016,55 @@ def test_st_pointm(eng, x, y, m, expected):
     )
 
 
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+    ("geometry", "expected"),
+    [
+        ("LINESTRING (1 2, 3 4, 5 6)", "POINT (1 2)"),

Review Comment:
   I think it would be good to verify that we have the same behaviour as PostGIS for empties as well:
   
   ```suggestion
           (None, None),
           ("POINT EMPTY", None),
           ("LINESTRING EMPTY", None),
           ("POLYGON EMPTY", None),
           ("MULTIPOINT EMPTY", None),
           ("MULTILINESTRING EMPTY", None),
           ("MULTIPOLYGON EMPTY", None),
           ("GEOMETRYCOLLECTION EMPTY", None),
           ("LINESTRING (1 2, 3 4, 5 6)", "POINT (1 2)"),
   ```



##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -1016,6 +1016,55 @@ def test_st_pointm(eng, x, y, m, expected):
     )
 
 
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+    ("geometry", "expected"),
+    [
+        ("LINESTRING (1 2, 3 4, 5 6)", "POINT (1 2)"),
+        ("LINESTRING Z (1 2 3, 3 4 5, 5 6 7)", "POINT Z (1 2 3)"),
+        ("LINESTRING M (1 2 3, 3 4 5, 5 6 7)", "POINT M (1 2 3)"),
+        ("LINESTRING ZM (1 2 3 4, 3 4 5 6, 5 6 7 8)", "POINT ZM (1 2 3 4)"),
+        ("POINT (1 2)", "POINT (1 2)"),
+        ("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "POINT (0 0)"),
+        ("MULTIPOINT (0 0, 10 0, 10 10, 0 10, 0 0)", "POINT (0 0)"),
+        ("MULTILINESTRING ((1 2, 3 4), (5 6, 7 8))", "POINT (1 2)"),
+        ("MULTIPOLYGON (((0 0, 10 0, 10 10, 0 10, 0 0)))", "POINT (0 0)"),
+        ("GEOMETRYCOLLECTION (POINT (1 2), LINESTRING (3 4, 5 6))", "POINT (1 2)"),
+        (
+            "GEOMETRYCOLLECTION (GEOMETRYCOLLECTION (GEOMETRYCOLLECTION (POINT (1 2), LINESTRING (3 4, 5 6))))",
+            "POINT (1 2)",
+        ),
+    ],
+)
+def test_st_start_point(eng, geometry, expected):
+    eng = eng.create_or_skip()
+    eng.assert_query_result(
+        f"SELECT ST_StartPoint({geom_or_null(geometry)})",
+        expected,
+    )
+
+
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+    ("geometry", "expected"),
+    [
+        ("LINESTRING (1 2, 3 4, 5 6)", "POINT (5 6)"),

Review Comment:
   NULL and empties would be good to test here, too.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

Posted by "martin-g (via GitHub)" <gi...@apache.org>.
martin-g commented on code in PR #245:
URL: https://github.com/apache/sedona-db/pull/245#discussion_r2470125577


##########
rust/sedona-functions/src/st_start_point.rs:
##########
@@ -0,0 +1,276 @@
+// 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 arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::{
+    scalar_doc_sections::DOC_SECTION_OTHER, ColumnarValue, Documentation, Volatility,
+};
+use geo_traits::{
+    CoordTrait, GeometryCollectionTrait, GeometryTrait, LineStringTrait, MultiLineStringTrait,
+    MultiPointTrait, MultiPolygonTrait, PointTrait, PolygonTrait,
+};
+use sedona_common::sedona_internal_err;
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::{
+    error::SedonaGeometryError,
+    wkb_factory::{write_wkb_coord_trait, write_wkb_point_header, WKB_MIN_PROBABLE_BYTES},
+};
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::{io::Write, sync::Arc};
+
+use crate::executor::WkbExecutor;
+
+/// ST_StartPoint() scalar UDF
+///
+/// Native implementation to get the start point of a geometry
+pub fn st_start_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_startpoint",
+        vec![Arc::new(STStartOrEndPoint::new(true))],
+        Volatility::Immutable,
+        Some(st_start_point_doc()),
+    )
+}
+
+fn st_start_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the start point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",

Review Comment:
   According to https://github.com/apache/sedona-db/pull/245/files#diff-6675d3a4b31524e6b409c5e557bdecd20adb0615fba805d77ba4b52a61c4dae5R142-R143 this is correct for the end point, not for the start one.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot merged PR #245:
URL: https://github.com/apache/sedona-db/pull/245


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

Posted by "yutannihilation (via GitHub)" <gi...@apache.org>.
yutannihilation commented on PR #245:
URL: https://github.com/apache/sedona-db/pull/245#issuecomment-3456354194

   Benchmark result:
   
   ```
   --------------------------------------------------------------------------------------------------------- benchmark: 6 tests --------------------------------------------------------------------------------------------------------
   Name (time in ms)                                                     Min                 Max                Mean            StdDev              Median               IQR            Outliers       OPS            Rounds  Iterations
   -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
   test_st_start_point[segments_large-SedonaDBSingleThread]           1.9418 (1.0)        2.3150 (1.0)        2.0126 (1.0)      0.0812 (1.0)        1.9881 (1.0)      0.0475 (1.0)           2;2  496.8624 (1.0)          26           1
   test_st_start_point[collections_simple-DuckDBSingleThread]         6.3318 (3.26)       7.5675 (3.27)       6.7992 (3.38)     0.4783 (5.89)       6.6988 (3.37)     0.6017 (12.66)         1;0  147.0758 (0.30)          5           1
   test_st_start_point[segments_large-DuckDBSingleThread]             7.6638 (3.95)       8.6637 (3.74)       7.9898 (3.97)     0.3350 (4.12)       7.8963 (3.97)     0.2996 (6.30)          1;1  125.1591 (0.25)          7           1
   test_st_start_point[collections_simple-SedonaDBSingleThread]      10.4538 (5.38)      11.3186 (4.89)      10.6016 (5.27)     0.2383 (2.93)      10.5149 (5.29)     0.0893 (1.88)          2;3   94.3255 (0.19)         20           1
   test_st_start_point[segments_large-PostGISSingleThread]          240.1957 (123.70)   243.3285 (105.11)   241.3920 (119.94)   1.1893 (14.64)    241.1900 (121.32)   1.3549 (28.50)         2;0    4.1426 (0.01)          5           1
   test_st_start_point[collections_simple-PostGISSingleThread]      352.2113 (181.39)   357.8562 (154.58)   355.9990 (176.88)   2.3396 (28.80)    357.1065 (179.63)   3.0995 (65.20)         1;0    2.8090 (0.01)          5           1
   -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
   
   Legend:
     Outliers: 1 Standard Deviation from Mean; 1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd Quartile.
     OPS: Operations Per Second, computed as 1 / Mean
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

Posted by "yutannihilation (via GitHub)" <gi...@apache.org>.
yutannihilation commented on code in PR #245:
URL: https://github.com/apache/sedona-db/pull/245#discussion_r2469410764


##########
rust/sedona-functions/src/st_start_point.rs:
##########
@@ -0,0 +1,248 @@
+// 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 arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::{
+    scalar_doc_sections::DOC_SECTION_OTHER, ColumnarValue, Documentation, Volatility,
+};
+use geo_traits::{CoordTrait, GeometryTrait, LineStringTrait};
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::{
+    error::SedonaGeometryError,
+    wkb_factory::{write_wkb_coord, write_wkb_point_header, WKB_MIN_PROBABLE_BYTES},
+};
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::{io::Write, sync::Arc};
+
+use crate::executor::WkbExecutor;
+
+/// ST_StartPoint() scalar UDF
+///
+/// Native implementation to get the start point of a geometry
+pub fn st_start_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_start_point",
+        vec![Arc::new(STStartOrEndPoint::new(true))],
+        Volatility::Immutable,
+        Some(st_start_point_doc()),
+    )
+}
+
+fn st_start_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the start point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_StartPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_StartPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+/// ST_EndPoint() scalar UDF
+///
+/// Native implementation to get the end point of a geometry
+pub fn st_end_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_end_point",
+        vec![Arc::new(STStartOrEndPoint::new(false))],
+        Volatility::Immutable,
+        Some(st_end_point_doc()),
+    )
+}
+
+fn st_end_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the end point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_EndPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_EndPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+#[derive(Debug)]
+struct STStartOrEndPoint {
+    from_start: bool,
+}
+
+impl STStartOrEndPoint {
+    fn new(from_start: bool) -> Self {
+        STStartOrEndPoint { from_start }
+    }
+}
+
+impl SedonaScalarKernel for STStartOrEndPoint {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![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(),
+        );
+
+        executor.execute_wkb_void(|maybe_wkb| {
+            if let Some(wkb) = maybe_wkb {
+                if let geo_traits::GeometryType::LineString(line_string) = wkb.as_type() {
+                    let maybe_coord = if self.from_start {
+                        line_string.coord(0)
+                    } else {
+                        line_string.coord(line_string.num_coords() - 1)
+                    };
+
+                    if let Some(coord) = maybe_coord {
+                        write_wkb_start_point(&mut builder, coord).map_err(|_| {
+                            datafusion_common::DataFusionError::Internal(
+                                "Failed to write WKB point header".to_string(),
+                            )
+                        })?;
+                        builder.append_value([]);
+                        return Ok(());
+                    }
+                }
+            }
+
+            builder.append_null();
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn write_wkb_start_point(
+    buf: &mut impl Write,
+    coords: impl CoordTrait<T = f64>,
+) -> Result<(), SedonaGeometryError> {
+    let dim = coords.dim();
+    write_wkb_point_header(buf, dim)?;
+
+    match dim.size() {
+        2 => {
+            let coords_tuple = coords.x_y();
+            write_wkb_coord(buf, coords_tuple)
+        }
+        3 => {
+            let coords_tuple = (coords.x(), coords.y(), coords.nth_or_panic(2));
+            write_wkb_coord(buf, coords_tuple)
+        }
+        4 => {
+            let coords_tuple = (
+                coords.x(),
+                coords.y(),
+                coords.nth_or_panic(2),
+                coords.nth_or_panic(3),
+            );
+            write_wkb_coord(buf, coords_tuple)
+        }
+        _ => Err(SedonaGeometryError::Invalid(
+            "Unsupported number of dimensions".to_string(),
+        )),
+    }

Review Comment:
   Thanks, moved the implementation to wkb_factory now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

Posted by "yutannihilation (via GitHub)" <gi...@apache.org>.
yutannihilation commented on PR #245:
URL: https://github.com/apache/sedona-db/pull/245#issuecomment-3451846790

   Thanks for the hint! Now I figured out how to do it with geo-traits and the functions in wkb_factory.rs.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

Posted by "yutannihilation (via GitHub)" <gi...@apache.org>.
yutannihilation commented on PR #245:
URL: https://github.com/apache/sedona-db/pull/245#issuecomment-3458722555

   Thanks for the great review! Adding tests about empty geometry actually helped me to find a bug in handling LINESTRING :) I think I addressed all the comments now.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(sql): Implement ST_StartPoint() and ST_EndPoint() [sedona-db]

Posted by "paleolimbot (via GitHub)" <gi...@apache.org>.
paleolimbot commented on code in PR #245:
URL: https://github.com/apache/sedona-db/pull/245#discussion_r2467813686


##########
rust/sedona-functions/src/st_start_point.rs:
##########
@@ -0,0 +1,248 @@
+// 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 arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::{
+    scalar_doc_sections::DOC_SECTION_OTHER, ColumnarValue, Documentation, Volatility,
+};
+use geo_traits::{CoordTrait, GeometryTrait, LineStringTrait};
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::{
+    error::SedonaGeometryError,
+    wkb_factory::{write_wkb_coord, write_wkb_point_header, WKB_MIN_PROBABLE_BYTES},
+};
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::{io::Write, sync::Arc};
+
+use crate::executor::WkbExecutor;
+
+/// ST_StartPoint() scalar UDF
+///
+/// Native implementation to get the start point of a geometry
+pub fn st_start_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_start_point",
+        vec![Arc::new(STStartOrEndPoint::new(true))],
+        Volatility::Immutable,
+        Some(st_start_point_doc()),
+    )
+}
+
+fn st_start_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the start point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_StartPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_StartPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+/// ST_EndPoint() scalar UDF
+///
+/// Native implementation to get the end point of a geometry
+pub fn st_end_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_end_point",
+        vec![Arc::new(STStartOrEndPoint::new(false))],
+        Volatility::Immutable,
+        Some(st_end_point_doc()),
+    )
+}
+
+fn st_end_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the end point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_EndPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_EndPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+#[derive(Debug)]
+struct STStartOrEndPoint {
+    from_start: bool,
+}
+
+impl STStartOrEndPoint {
+    fn new(from_start: bool) -> Self {
+        STStartOrEndPoint { from_start }
+    }
+}
+
+impl SedonaScalarKernel for STStartOrEndPoint {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![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(),
+        );
+
+        executor.execute_wkb_void(|maybe_wkb| {
+            if let Some(wkb) = maybe_wkb {
+                if let geo_traits::GeometryType::LineString(line_string) = wkb.as_type() {
+                    let maybe_coord = if self.from_start {
+                        line_string.coord(0)
+                    } else {
+                        line_string.coord(line_string.num_coords() - 1)
+                    };
+
+                    if let Some(coord) = maybe_coord {
+                        write_wkb_start_point(&mut builder, coord).map_err(|_| {
+                            datafusion_common::DataFusionError::Internal(
+                                "Failed to write WKB point header".to_string(),
+                            )

Review Comment:
   ```suggestion
                               sedona_internal_err!("Failed to write WKB point header")
   
   ```



##########
rust/sedona-functions/src/st_start_point.rs:
##########
@@ -0,0 +1,248 @@
+// 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 arrow_array::builder::BinaryBuilder;
+use datafusion_common::error::Result;
+use datafusion_expr::{
+    scalar_doc_sections::DOC_SECTION_OTHER, ColumnarValue, Documentation, Volatility,
+};
+use geo_traits::{CoordTrait, GeometryTrait, LineStringTrait};
+use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF};
+use sedona_geometry::{
+    error::SedonaGeometryError,
+    wkb_factory::{write_wkb_coord, write_wkb_point_header, WKB_MIN_PROBABLE_BYTES},
+};
+use sedona_schema::{
+    datatypes::{SedonaType, WKB_GEOMETRY},
+    matchers::ArgMatcher,
+};
+use std::{io::Write, sync::Arc};
+
+use crate::executor::WkbExecutor;
+
+/// ST_StartPoint() scalar UDF
+///
+/// Native implementation to get the start point of a geometry
+pub fn st_start_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_start_point",
+        vec![Arc::new(STStartOrEndPoint::new(true))],
+        Volatility::Immutable,
+        Some(st_start_point_doc()),
+    )
+}
+
+fn st_start_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the start point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_StartPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_StartPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+/// ST_EndPoint() scalar UDF
+///
+/// Native implementation to get the end point of a geometry
+pub fn st_end_point_udf() -> SedonaScalarUDF {
+    SedonaScalarUDF::new(
+        "st_end_point",
+        vec![Arc::new(STStartOrEndPoint::new(false))],
+        Volatility::Immutable,
+        Some(st_end_point_doc()),
+    )
+}
+
+fn st_end_point_doc() -> Documentation {
+    Documentation::builder(
+        DOC_SECTION_OTHER,
+        "Returns the end point of a LINESTRING geometry. Returns NULL if the geometry is not a LINESTRING.",
+        "ST_EndPoint (geom: Geometry)",
+    )
+    .with_argument("geom", "geometry: Input geometry")
+    .with_sql_example("SELECT ST_EndPoint(ST_GeomFromWKT('LINESTRING(0 1, 2 3, 4 5)'))")
+    .build()
+}
+
+#[derive(Debug)]
+struct STStartOrEndPoint {
+    from_start: bool,
+}
+
+impl STStartOrEndPoint {
+    fn new(from_start: bool) -> Self {
+        STStartOrEndPoint { from_start }
+    }
+}
+
+impl SedonaScalarKernel for STStartOrEndPoint {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(vec![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(),
+        );
+
+        executor.execute_wkb_void(|maybe_wkb| {
+            if let Some(wkb) = maybe_wkb {
+                if let geo_traits::GeometryType::LineString(line_string) = wkb.as_type() {
+                    let maybe_coord = if self.from_start {
+                        line_string.coord(0)
+                    } else {
+                        line_string.coord(line_string.num_coords() - 1)
+                    };
+
+                    if let Some(coord) = maybe_coord {
+                        write_wkb_start_point(&mut builder, coord).map_err(|_| {
+                            datafusion_common::DataFusionError::Internal(
+                                "Failed to write WKB point header".to_string(),
+                            )
+                        })?;
+                        builder.append_value([]);
+                        return Ok(());
+                    }
+                }
+            }
+
+            builder.append_null();
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn write_wkb_start_point(
+    buf: &mut impl Write,
+    coords: impl CoordTrait<T = f64>,
+) -> Result<(), SedonaGeometryError> {
+    let dim = coords.dim();
+    write_wkb_point_header(buf, dim)?;
+
+    match dim.size() {
+        2 => {
+            let coords_tuple = coords.x_y();
+            write_wkb_coord(buf, coords_tuple)
+        }
+        3 => {
+            let coords_tuple = (coords.x(), coords.y(), coords.nth_or_panic(2));
+            write_wkb_coord(buf, coords_tuple)
+        }
+        4 => {
+            let coords_tuple = (
+                coords.x(),
+                coords.y(),
+                coords.nth_or_panic(2),
+                coords.nth_or_panic(3),
+            );
+            write_wkb_coord(buf, coords_tuple)
+        }
+        _ => Err(SedonaGeometryError::Invalid(
+            "Unsupported number of dimensions".to_string(),
+        )),
+    }

Review Comment:
   This would fit nicely as `wkb_factory::write_wkb_coord_trait()` (I'm sure we'll need it again!)



##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -1015,6 +1015,45 @@ def test_st_pointm(eng, x, y, m, expected):
         expected,
     )
 
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+    ("geometry", "expected"),
+    [
+        ("LINESTRING (1 2, 3 4, 5 6)",                "POINT (1 2)"       ),
+        ("LINESTRING Z (1 2 3, 3 4 5, 5 6 7)",        "POINT Z (1 2 3)"   ),
+        ("LINESTRING M (1 2 3, 3 4 5, 5 6 7)",        "POINT M (1 2 3)"   ),
+        ("LINESTRING ZM (1 2 3 4, 3 4 5 6, 5 6 7 8)", "POINT ZM (1 2 3 4)"),
+        ("POINT (1 2)",                               None                ),
+        ("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))",   None                ),
+        ("MULTILINESTRING ((1 2, 3 4), (5 6, 7 8))",  None                ),                ),

Review Comment:
   ```suggestion
           ("MULTILINESTRING ((1 2, 3 4), (5 6, 7 8))",  None                ),
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@sedona.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org