petern48 commented on code in PR #503:
URL: https://github.com/apache/sedona-db/pull/503#discussion_r2678830318


##########
c/sedona-geos/src/st_line_merge.rs:
##########
@@ -0,0 +1,177 @@
+// 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::{error::Result, DataFusionError, ScalarValue};
+use datafusion_expr::ColumnarValue;
+use geos::Geom;
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{datatypes::WKB_GEOMETRY, matchers::ArgMatcher};
+
+use crate::executor::GeosExecutor;
+
+pub fn st_line_merge_impl() -> ScalarKernelRef {
+    Arc::new(STLineMerge {})
+}
+
+#[derive(Debug)]
+struct STLineMerge {}
+
+impl SedonaScalarKernel for STLineMerge {
+    fn return_type(
+        &self,
+        args: &[sedona_schema::datatypes::SedonaType],
+    ) -> 
datafusion_common::Result<Option<sedona_schema::datatypes::SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![
+                ArgMatcher::is_geometry(),
+                ArgMatcher::optional(ArgMatcher::is_boolean()),
+            ],
+            WKB_GEOMETRY,
+        );
+        matcher.match_args(args)
+    }
+
+    fn invoke_batch(
+        &self,
+        arg_types: &[sedona_schema::datatypes::SedonaType],
+        args: &[datafusion_expr::ColumnarValue],
+    ) -> datafusion_common::Result<datafusion_expr::ColumnarValue> {
+        let executor = GeosExecutor::new(arg_types, args);
+        let mut builder = BinaryBuilder::with_capacity(
+            executor.num_iterations(),
+            WKB_MIN_PROBABLE_BYTES * executor.num_iterations(),
+        );
+
+        let directed = match args.get(1) {
+            Some(ColumnarValue::Scalar(ScalarValue::Boolean(Some(opt_bool)))) 
=> *opt_bool,
+            _ => false,
+        };
+
+        executor.execute_wkb_void(|maybe_wkb| {
+            match maybe_wkb {
+                Some(wkb) => {
+                    invoke_scalar(&wkb, &mut builder, directed)?;
+                    builder.append_value([]);
+                }
+                None => builder.append_null(),
+            }
+
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(
+    geos_geom: &geos::Geometry,
+    writer: &mut impl std::io::Write,
+    directed: bool,
+) -> Result<()> {
+    let result = if directed {
+        geos_geom.line_merge_directed()
+    } else {
+        geos_geom.line_merge()
+    };
+
+    let geom =
+        result.map_err(|e| DataFusionError::Execution(format!("Failed to merge 
lines: {e}")))?;
+
+    let wkb = geom
+        .to_wkb()
+        .map_err(|e| DataFusionError::Execution(format!("Failed to convert 
result to WKB: {e}")))?;
+
+    writer
+        .write_all(wkb.as_ref())
+        .map_err(|e| DataFusionError::Execution(format!("Failed to write 
result WKB: {e}")))?;

Review Comment:
   ```suggestion
       write_geos_geometry(&geom, writer)?;
   ```
   
   https://github.com/apache/sedona-db/pull/476 recently introduced this helper 
method that is faster than doing these two calls



##########
c/sedona-geos/src/st_line_merge.rs:
##########
@@ -0,0 +1,177 @@
+// 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::{error::Result, DataFusionError, ScalarValue};
+use datafusion_expr::ColumnarValue;
+use geos::Geom;
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_geometry::wkb_factory::WKB_MIN_PROBABLE_BYTES;
+use sedona_schema::{datatypes::WKB_GEOMETRY, matchers::ArgMatcher};
+
+use crate::executor::GeosExecutor;

Review Comment:
   ```suggestion
   use crate::executor::GeosExecutor;
   use crate::geos_to_wkb::write_geos_geometry;
   ```
   Here's the import for my other suggestion.



##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -1797,6 +1797,58 @@ def test_st_isring_non_linestring_error(eng, geom):
         eng.assert_query_result(f"SELECT 
ST_IsRing(ST_GeomFromText('{geom}'))", None)
 
 
[email protected]("eng", [SedonaDB, PostGIS])
[email protected](
+    ("geom", "expected"),
+    [
+        (None, None),
+        ("MULTILINESTRING ((0 0, 1 0), (1 0, 1 1))", "LINESTRING (0 0, 1 0, 1 
1)"),
+        (
+            "MULTILINESTRING ((0 0, 1 0), (1 1, 1 0))",
+            "LINESTRING (0 0, 1 0, 1 1)",
+        ),  # opposite direction
+        (
+            "MULTILINESTRING ((0 0, 1 0), (8 8, 9 9))",
+            "MULTILINESTRING ((0 0, 1 0), (8 8, 9 9))",
+        ),
+        # Note that the behaviour on non-multilinestring geometry is not 
documented.
+        # But, we test such cases here as well to detect if there's any 
difference.
+        ("POINT (0 0)", "GEOMETRYCOLLECTION EMPTY"),
+        ("LINESTRING (0 0, 1 0)", "LINESTRING (0 0, 1 0)"),
+        ("POLYGON ((0 0, 0 1, 1 0, 0 0))", "LINESTRING (0 0, 0 1, 1 0, 0 0)"),

Review Comment:
   interesting. The [docs](https://postgis.net/docs/ST_LineMerge.html) say 
"Other geometry types return an empty GeometryCollection" in the note. Though 
that doesn't seem to be the case for POLYGON or LINESTRING input 🤷.
   
   Could we test some empty geometries, for both of these tests? Those can 
often catch weird edge cases.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to