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

[PR] Add st num interior rings [sedona-db]

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

   (no comment)


-- 
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] Add st num interior rings [sedona-db]

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

   @petern48 my mkdocs.yml is 


-- 
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(c/sedona-geos): Add ST_NumInteriorRings [sedona-db]

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

   > Merged. Thanks for sticking through it @LakshmiSowmya04!
   Thank you so much for helping me and encouraging me, even with the small things. I really appreciate it a lot. @petern48 


-- 
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] Add st num interior rings [sedona-db]

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


##########
c/sedona-geos/src/st_numinteriorrings.rs:
##########
@@ -0,0 +1,131 @@
+// 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::Int32Builder;
+use arrow_schema::DataType;
+use datafusion_common::{error::Result, DataFusionError};
+use datafusion_expr::ColumnarValue;
+use geos::Geom;
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+use crate::executor::GeosExecutor;
+
+/// ST_NumInteriorRings() implementation using the geos crate
+pub fn st_num_interior_rings_impl() -> ScalarKernelRef {
+    Arc::new(STNumInteriorRings {})
+}
+
+#[derive(Debug)]
+struct STNumInteriorRings {}
+
+impl SedonaScalarKernel for STNumInteriorRings {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Int32),
+        );
+
+        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 = Int32Builder::with_capacity(executor.num_iterations());
+
+        // single-geometry executor path
+        executor.execute_wkb_void(|geom| {
+            match geom {
+                Some(g) => {
+                    let n = invoke_scalar(&g)?;
+                    builder.append_value(n);
+                }
+                None => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(geos_geom: &geos::Geometry) -> Result<i32> {
+    // geos::Geometry provides get_num_interior_rings() -> GResult<usize>
+    let count = geos_geom.get_num_interior_rings().map_err(|e| {
+        DataFusionError::Execution(format!("Failed to get num interior rings: {e}"))
+    })?;
+
+    // safe to cast to i32 for SQL integer return
+    Ok(count as i32)
+}
+
+#[cfg(test)]
+mod tests {
+    use arrow_array::{create_array as arrow_array, ArrayRef};
+    use datafusion_common::ScalarValue;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::{WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::compare::assert_array_equal;
+    use sedona_testing::create::create_array;
+    use sedona_testing::testers::ScalarUdfTester;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let udf = SedonaScalarUDF::from_kernel("st_numinteriorrings", st_num_interior_rings_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type.clone()]);
+        tester.assert_return_type(DataType::Int32);
+
+        // scalar-scalar: polygon with two interior rings -> 2
+        let result = tester
+            .invoke_scalar_scalar(
+                "POLYGON((0 0,10 0,10 6,0 6,0 0),(1 1,2 1,2 5,1 5,1 1),(8 5,8 4,9 4,9 5,8 5))", // returns 2
+                "POLYGON((0 0,10 0,10 6,0 6,0 0))", // second arg ignored, only single-arg UDF tester will pass one value, but keep pattern consistent
+            )
+            .unwrap();
+
+        // Note: Above tester.invoke_scalar_scalar in your testing harness for single-arg UDFs
+        // may accept two parameters; if not, use invoke_scalar("WKT") variant available in the tester.
+        tester.assert_scalar_result_equals(result, 2_i32);
+
+        // Nulls -> Null
+        let result = tester
+            .invoke_scalar_scalar(ScalarValue::Null, ScalarValue::Null)
+            .unwrap();
+        assert!(result.is_null());
+
+        // array-array style: mix of polygon, non-polygon and null
+        let lhs = create_array(
+            &[
+                Some("POLYGON((0 0,10 0,10 6,0 6,0 0),(1 1,2 1,2 5,1 5,1 1))"), //returns 1
+                Some("POINT (5 5)"), //returns 0 only out circle is there
+                None,
+            ],
+            &WKB_GEOMETRY,
+        );
+
+        let expected: ArrayRef = arrow_array!(Int32, [Some(1), Some(0), None]);
+        assert_array_equal(&tester.invoke_array_array(lhs).unwrap(), &expected);

Review Comment:
   Similar issue here I can quickly see in the following error in the [failed cargo test CI](https://github.com/apache/sedona-db/actions/runs/19710765299/job/56470443347?pr=369)
   ```
   error[E0061]: this method takes 2 arguments but 1 argument was supplied
      --> c/sedona-geos/src/st_numinteriorrings.rs:129:36
       |
   129 |         assert_array_equal(&tester.invoke_array_array(lhs).unwrap(), &expected);
   ```
   
   This means we gave `invoke_array_array()` one argument, but it's a method that takes two. When you see an error like this, your IDE probably shows red swiggly lines showing you aren't calling that method properly. You can see the definition [here](https://github.com/apache/sedona-db/blob/90f29892315b593dc4b6efd98e6b337ce5a271a4/rust/sedona-testing/src/testers.rs#L407) (you should be able to figure this out by `Ctrl + click`-ing this on VsCode), it takes two arguments. Similar to above, we only want to pass in one argument, so we actually want to use a different method.
   
   Look around in that [same file](https://github.com/apache/sedona-db/blob/90f29892315b593dc4b6efd98e6b337ce5a271a4/rust/sedona-testing/src/testers.rs#L407C12-L407C30) that `invoke_array_array` is in, and look for a similar function you can use that only takes one (array) argument as input instead of two. Your IDE should stop showing red swiggly lines when you're passing in the right number of arguments to the function.



-- 
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] Add st num interior rings [sedona-db]

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


##########
c/sedona-geos/src/st_numinteriorrings.rs:
##########
@@ -0,0 +1,131 @@
+// 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::Int32Builder;
+use arrow_schema::DataType;
+use datafusion_common::{error::Result, DataFusionError};
+use datafusion_expr::ColumnarValue;
+use geos::Geom;
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+use crate::executor::GeosExecutor;
+
+/// ST_NumInteriorRings() implementation using the geos crate
+pub fn st_num_interior_rings_impl() -> ScalarKernelRef {
+    Arc::new(STNumInteriorRings {})
+}
+
+#[derive(Debug)]
+struct STNumInteriorRings {}
+
+impl SedonaScalarKernel for STNumInteriorRings {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Int32),
+        );
+
+        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 = Int32Builder::with_capacity(executor.num_iterations());
+
+        // single-geometry executor path
+        executor.execute_wkb_void(|geom| {
+            match geom {
+                Some(g) => {
+                    let n = invoke_scalar(&g)?;
+                    builder.append_value(n);
+                }
+                None => builder.append_null(),
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(geos_geom: &geos::Geometry) -> Result<i32> {
+    // geos::Geometry provides get_num_interior_rings() -> GResult<usize>
+    let count = geos_geom.get_num_interior_rings().map_err(|e| {
+        DataFusionError::Execution(format!("Failed to get num interior rings: {e}"))
+    })?;
+
+    // safe to cast to i32 for SQL integer return
+    Ok(count as i32)
+}
+
+#[cfg(test)]
+mod tests {
+    use arrow_array::{create_array as arrow_array, ArrayRef};
+    use datafusion_common::ScalarValue;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::{WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::compare::assert_array_equal;
+    use sedona_testing::create::create_array;
+    use sedona_testing::testers::ScalarUdfTester;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let udf = SedonaScalarUDF::from_kernel("st_numinteriorrings", st_num_interior_rings_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type.clone()]);
+        tester.assert_return_type(DataType::Int32);
+
+        // scalar-scalar: polygon with two interior rings -> 2
+        let result = tester
+            .invoke_scalar_scalar(
+                "POLYGON((0 0,10 0,10 6,0 6,0 0),(1 1,2 1,2 5,1 5,1 1),(8 5,8 4,9 4,9 5,8 5))", // returns 2
+                "POLYGON((0 0,10 0,10 6,0 6,0 0))", // second arg ignored, only single-arg UDF tester will pass one value, but keep pattern consistent
+            )
+            .unwrap();

Review Comment:
   To help point you in the right direction, We have other methods that we could use here instead of [.invoke_scalar_scalar()](https://github.com/apache/sedona-db/blob/90f29892315b593dc4b6efd98e6b337ce5a271a4/rust/sedona-testing/src/testers.rs#L310). That method is meant for passing in two arguments to the SQL function. For ST_NumInteriorRings, we just want to pass in one.
   
   Currently, this is like calling the function like this:
   ```
   ST_NumInteriorRings(
        POLYGON((0 0,10 0,10 6,0 6,0 0),(1 1,2 1,2 5,1 5,1 1),(8 5,8 4,9 4,9 5,8 5))
        POLYGON((0 0,10 0,10 6,0 6,0 0))
   )
   ```
   whereas we should just call it with the first arg. (notice how you currently have a comment saying the second arg is ignore.
   ST_NumInteriorRings(
        POLYGON((0 0,10 0,10 6,0 6,0 0),(1 1,2 1,2 5,1 5,1 1),(8 5,8 4,9 4,9 5,8 5))
   )
   
   We should instead just use a different method than `invoke_scalar_scalar` that only takes one argument.
   
   Try taking a look at the rust tests in `st_area.rs` to model your tests after:
   https://github.com/apache/sedona-db/blob/90f29892315b593dc4b6efd98e6b337ce5a271a4/c/sedona-geos/src/st_area.rs#L87-L106
   
   Similar to ST_NumInteriorRings, ST_Area takes a single geometry as input and returns a number.



-- 
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] Add st num interior rings [sedona-db]

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


##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -2698,3 +2698,49 @@ def test_st_snap(eng, input, reference, tolerance, expected):
 def test_st_zmflag(eng, geom, expected):
     eng = eng.create_or_skip()
     eng.assert_query_result(f"SELECT ST_ZmFlag({geom_or_null(geom)})", expected)
+
+
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+    ("geom", "expected"),
+    [
+        # input -> #output postgis returned
+        (None, None),  # none
+        ("POINT (1 2)", None),  # none
+        ("LINESTRING (0 0, 1 1, 2 2)", None),  # non-polygon -> NULL
+        ("POLYGON EMPTY", 0),  # empty polygon has no interior rings
+        ("POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))", 0),  # simple polygon, no holes
+        # example query - SELECT ST_NumInteriorRings(ST_GeomFromText('POLYGON((0 0,4 0,4 4,0 4,0 0))')) AS num_rings;
+        (
+            "POLYGON (\
+                (0 0,6 0,6 6,0 6,0 0),\
+                (2 2,4 2,4 4,2 4,2 2))",

Review Comment:
   ```suggestion
               "POLYGON ((0 0,6 0,6 6,0 6,0 0), (2 2,4 2,4 4,2 4,2 2))"
   ```
   
   It's slightly more convenient to write geometries on a single line. It makes it easier to copy-paste for testing on the PostGIS container I mentioned above. I suggest doing this with your other python tests to help you debug easier.



-- 
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] Add st num interior rings [sedona-db]

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


##########
c/sedona-geos/src/st_numinteriorrings.rs:
##########
@@ -0,0 +1,174 @@
+// 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 crate::executor::GeosExecutor;
+use arrow_array::builder::Int32Builder;
+use arrow_schema::DataType;
+use datafusion_common::{error::Result, DataFusionError};
+use datafusion_expr::ColumnarValue;
+use geos::{Geom, Geometry, GeometryTypes};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+pub fn st_num_interior_rings_impl() -> ScalarKernelRef {
+    Arc::new(STNumInteriorRings {})
+}
+
+#[derive(Debug)]
+struct STNumInteriorRings {}
+
+impl SedonaScalarKernel for STNumInteriorRings {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Int32),
+        );
+
+        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 = Int32Builder::with_capacity(executor.num_iterations());
+        executor.execute_wkb_void(|maybe_geom| {
+            match maybe_geom {
+                None => builder.append_null(),
+                Some(geom) => {
+                    let res = invoke_scalar(&geom)?;
+                    match res {
+                        Some(n) => builder.append_value(n),
+                        // non-polygon / unsupported -> NULL (matches PostGIS + py tests)

Review Comment:
   ```suggestion
   ```
   Just clean up. It's not wrong. I just don't think it's necessary to say it passes the postgis python tests. There's already comments below explaining the non-polygon case.



-- 
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] Add st num interior rings [sedona-db]

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

   Could you also modify your PR description to say "closes <issue link>". GitHub has a feature to auto-close the issue once the PR is merged when you put that.
   
   "closes https://github.com/apache/sedona-db/issues/290"


-- 
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(c/sedona-geos): Add ST_NumInteriorRings [sedona-db]

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


-- 
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] Add st num interior rings [sedona-db]

Posted by "LakshmiSowmya04 (via GitHub)" <gi...@apache.org>.
LakshmiSowmya04 closed pull request #369: Add st num interior rings
URL: https://github.com/apache/sedona-db/pull/369


-- 
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] Add st num interior rings [sedona-db]

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


##########
c/sedona-geos/src/st_numinteriorrings.rs:
##########
@@ -0,0 +1,174 @@
+// 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 crate::executor::GeosExecutor;
+use arrow_array::builder::Int32Builder;
+use arrow_schema::DataType;
+use datafusion_common::{error::Result, DataFusionError};
+use datafusion_expr::ColumnarValue;
+use geos::{Geom, Geometry, GeometryTypes};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+pub fn st_num_interior_rings_impl() -> ScalarKernelRef {
+    Arc::new(STNumInteriorRings {})
+}
+
+#[derive(Debug)]
+struct STNumInteriorRings {}
+
+impl SedonaScalarKernel for STNumInteriorRings {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Int32),
+        );
+
+        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 = Int32Builder::with_capacity(executor.num_iterations());
+        executor.execute_wkb_void(|maybe_geom| {
+            match maybe_geom {
+                None => builder.append_null(),
+                Some(geom) => {
+                    let res = invoke_scalar(&geom)?;
+                    match res {
+                        Some(n) => builder.append_value(n),
+                        // non-polygon / unsupported -> NULL (matches PostGIS + py tests)

Review Comment:
   ```suggestion
   ```



##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -2698,3 +2698,45 @@ def test_st_snap(eng, input, reference, tolerance, expected):
 def test_st_zmflag(eng, geom, expected):
     eng = eng.create_or_skip()
     eng.assert_query_result(f"SELECT ST_ZmFlag({geom_or_null(geom)})", expected)
+
+
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+    ("geom", "expected"),
+    [
+        (None, None),
+        ("POINT (1 2)", None),
+        ("LINESTRING (0 0, 1 1, 2 2)", None),
+        ("POLYGON EMPTY", 0),
+        ("POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))", 0),
+        (
+            "POLYGON ((0 0,6 0,6 6,0 6,0 0),(2 2,4 2,4 4,2 4,2 2))",
+            1,
+        ),
+        (
+            "POLYGON ("
+            "(0 0,10 0,10 6,0 6,0 0),"
+            "(1 1,2 1,2 5,1 5,1 1),"
+            "(8 5,8 4,9 4,9 5,8 5)"
+            ")",

Review Comment:
   ```suggestion
               "POLYGON ((0 0,10 0,10 6,0 6,0 0), (1 1,2 1,2 5,1 5,1 1),(8 5,8 4,9 4,9 5,8 5))",
   ```
   Again, I slightly prefer to have these all on one line for the ease of copy-pasting. There's one more multiline case that's right below this to fix.



##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -2698,3 +2698,45 @@ def test_st_snap(eng, input, reference, tolerance, expected):
 def test_st_zmflag(eng, geom, expected):
     eng = eng.create_or_skip()
     eng.assert_query_result(f"SELECT ST_ZmFlag({geom_or_null(geom)})", expected)
+
+
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+    ("geom", "expected"),
+    [
+        (None, None),
+        ("POINT (1 2)", None),
+        ("LINESTRING (0 0, 1 1, 2 2)", None),
+        ("POLYGON EMPTY", 0),

Review Comment:
   Great job with the tests so far 👏. I'd like the Python tests to be a bit more comprehensive because it's very possible we implement ways to speed up ST_NumInteriorRings in the future. When we do, so it's important that we have good tests to make sure we don't introduce bugs.
   
   Here are the tests I'd like to have:
   - None (done)
   - Polygon with one ring (zero interior rings) (done)
   - Polygon with more rings (done)
   - Empty geom for each geometry type (not done)
   - One of each geometry type (not done)
     - All 7 of the geometry types are: `POINT`, `LINESTRING`, `POLYGON`, `MULTIPOINT`, `MULTILINESTRING`, `MULTIPOLYGON`, `GEOMETRYCOLLECTION`. You have most of these, but not quite all of them
   
   You cover most of these (indicated by "done"), but not the last two bullets. Could you add cases for the last two bullets? Here's an example of how it's done for another function. You can use similar (or even the same) test cases, except your "expected" value will be different than the True/False values in that function.
   
   https://github.com/apache/sedona-db/blob/16d232be0f28441b85801936b270fa43f7edceb4/python/sedonadb/tests/functions/test_functions.py#L1276-L1290
   
   optional: It's also nice to group the tests by bullet (e.g. all empty cases together), for readability.



##########
c/sedona-geos/src/st_numinteriorrings.rs:
##########
@@ -0,0 +1,174 @@
+// 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 crate::executor::GeosExecutor;
+use arrow_array::builder::Int32Builder;
+use arrow_schema::DataType;
+use datafusion_common::{error::Result, DataFusionError};
+use datafusion_expr::ColumnarValue;
+use geos::{Geom, Geometry, GeometryTypes};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+pub fn st_num_interior_rings_impl() -> ScalarKernelRef {
+    Arc::new(STNumInteriorRings {})
+}
+
+#[derive(Debug)]
+struct STNumInteriorRings {}
+
+impl SedonaScalarKernel for STNumInteriorRings {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Int32),
+        );
+
+        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 = Int32Builder::with_capacity(executor.num_iterations());
+        executor.execute_wkb_void(|maybe_geom| {
+            match maybe_geom {
+                None => builder.append_null(),
+                Some(geom) => {
+                    let res = invoke_scalar(&geom)?;
+                    match res {
+                        Some(n) => builder.append_value(n),
+                        // non-polygon / unsupported -> NULL (matches PostGIS + py tests)
+                        None => builder.append_null(),
+                    }
+                }
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(geom: &Geometry) -> Result<Option<i32>> {
+    match geom.geometry_type() {
+        GeometryTypes::Polygon => {
+            let is_empty = geom.is_empty().map_err(|e| {
+                DataFusionError::Execution(format!("Failed to check if geometry is empty: {e}"))
+            })?;
+
+            if is_empty {
+                // empty polygon has no interior rings
+                Ok(Some(0))
+            } else {
+                let count = geom.get_num_interior_rings().map_err(|e| {
+                    DataFusionError::Execution(format!("Failed to get num interior rings: {e}"))
+                })?;
+                Ok(Some(count as i32))
+            }
+        }
+        // non-polygon -> NULL
+        _ => Ok(None),
+    }
+}
+#[cfg(test)]
+mod tests {
+    use std::sync::Arc;
+
+    use arrow_array::{ArrayRef, Int32Array};
+    use arrow_schema::DataType;
+    use datafusion_common::ScalarValue;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::compare::assert_array_equal;
+    use sedona_testing::testers::ScalarUdfTester;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let udf = SedonaScalarUDF::from_kernel("st_numinteriorrings", st_num_interior_rings_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type]);
+        tester.assert_return_type(DataType::Int32);
+
+        // Polygon with 2 interior rings -> 2
+        let result = tester
+            .invoke_scalar(
+                "POLYGON(
+                    (0 0,10 0,10 6,0 6,0 0),
+                    (1 1,2 1,2 5,1 5,1 1),
+                    (8 5,8 4,9 4,9 5,8 5)
+                )",
+            )
+            .unwrap();
+        tester.assert_scalar_result_equals(result, 2_i32);
+
+        // NULL -> NULL
+        let result = tester.invoke_scalar(ScalarValue::Null).unwrap();
+        assert!(result.is_null());
+
+        let input_wkt = vec![
+            None,
+            Some("POINT (1 2)"),
+            Some("LINESTRING (0 0, 1 1, 2 2)"),
+            Some("POLYGON EMPTY"),
+            Some("POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))"),
+            Some("POLYGON ((0 0,6 0,6 6,0 6,0 0),(2 2,4 2,4 4,2 4,2 2))"),
+            Some(
+                "POLYGON (
+                    (0 0,10 0,10 6,0 6,0 0),
+                    (1 1,2 1,2 5,1 5,1 1),
+                    (8 5,8 4,9 4,9 5,8 5)
+                )",
+            ),

Review Comment:
   For copy-paste ease (and conciseness), I prefer to collapse these rust ones to a single line too. Two more cases below this and one more at the beginning of the function



-- 
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] Add st num interior rings [sedona-db]

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


##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -2698,3 +2698,50 @@ def test_st_snap(eng, input, reference, tolerance, expected):
 def test_st_zmflag(eng, geom, expected):
     eng = eng.create_or_skip()
     eng.assert_query_result(f"SELECT ST_ZmFlag({geom_or_null(geom)})", expected)
+
+
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+    ("geom", "expected"),
+    [
+        (None, None),
+        ("POINT EMPTY", None),
+        ("LINESTRING EMPTY", None),
+        ("POLYGON EMPTY", 0),
+        ("MULTIPOINT EMPTY", None),
+        ("MULTILINESTRING EMPTY", None),
+        ("MULTIPOLYGON EMPTY", None),
+        ("GEOMETRYCOLLECTION EMPTY", None),
+        ("POINT (1 2)", None),
+        ("LINESTRING (0 0, 1 1, 2 2)", None),
+        ("POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))", 0),
+        ("MULTIPOINT ((0 0), (1 1))", None),
+        ("MULTILINESTRING ((0 0, 0 1, 1 1, 0 0),(0 0, 1 1))", None),
+        ("GEOMETRYCOLLECTION (LINESTRING (0 0, 0 1, 1 1, 0 0))", None),
+        (
+            "POLYGON ((0 0,6 0,6 6,0 6,0 0),(2 2,4 2,4 4,2 4,2 2))",
+            1,
+        ),
+        (
+            "POLYGON ((0 0,10 0,10 6,0 6,0 0), (1 1,2 1,2 5,1 5,1 1),(8 5,8 4,9 4,9 5,8 5))",
+            2,
+        ),
+        (
+            "MULTIPOLYGON ("
+            "((0 0, 5 0, 5 5, 0 5, 0 0), (1 1, 2 1, 2 2, 1 2, 1 1)),"
+            "((10 10, 14 10, 14 14, 10 14, 10 10))"
+            ")",

Review Comment:
   ```suggestion
               "MULTIPOLYGON (((0 0, 5 0, 5 5, 0 5, 0 0), (1 1, 2 1, 2 2, 1 2, 1 1)),((10 10, 14 10, 14 14, 10 14, 10 10)))",
   ```



##########
c/sedona-geos/src/st_numinteriorrings.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::sync::Arc;
+
+use crate::executor::GeosExecutor;
+use arrow_array::builder::Int32Builder;
+use arrow_schema::DataType;
+use datafusion_common::{error::Result, DataFusionError};
+use datafusion_expr::ColumnarValue;
+use geos::{Geom, Geometry, GeometryTypes};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+pub fn st_num_interior_rings_impl() -> ScalarKernelRef {
+    Arc::new(STNumInteriorRings {})
+}
+
+#[derive(Debug)]
+struct STNumInteriorRings {}
+
+impl SedonaScalarKernel for STNumInteriorRings {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Int32),
+        );
+
+        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 = Int32Builder::with_capacity(executor.num_iterations());
+        executor.execute_wkb_void(|maybe_geom| {
+            match maybe_geom {
+                None => builder.append_null(),
+                Some(geom) => {
+                    let res = invoke_scalar(&geom)?;
+                    match res {
+                        Some(n) => builder.append_value(n),
+                        None => builder.append_null(),
+                    }
+                }
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(geom: &Geometry) -> Result<Option<i32>> {
+    match geom.geometry_type() {
+        GeometryTypes::Polygon => {
+            let is_empty = geom.is_empty().map_err(|e| {
+                DataFusionError::Execution(format!("Failed to check if geometry is empty: {e}"))
+            })?;
+
+            if is_empty {
+                Ok(Some(0))
+            } else {
+                let count = geom.get_num_interior_rings().map_err(|e| {
+                    DataFusionError::Execution(format!("Failed to get num interior rings: {e}"))
+                })?;
+                Ok(Some(count as i32))
+            }
+        }
+        _ => Ok(None),
+    }
+}
+#[cfg(test)]
+mod tests {
+    use std::sync::Arc;
+
+    use arrow_array::{ArrayRef, Int32Array};
+    use arrow_schema::DataType;
+    use datafusion_common::ScalarValue;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::compare::assert_array_equal;
+    use sedona_testing::testers::ScalarUdfTester;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let udf = SedonaScalarUDF::from_kernel("st_numinteriorrings", st_num_interior_rings_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type]);
+        tester.assert_return_type(DataType::Int32);
+
+        // Polygon with 2 interior rings -> 2
+        let result = tester
+            .invoke_scalar(
+                "POLYGON(
+                    (0 0,10 0,10 6,0 6,0 0),
+                    (1 1,2 1,2 5,1 5,1 1),
+                    (8 5,8 4,9 4,9 5,8 5)
+                )",
+            )
+            .unwrap();
+        tester.assert_scalar_result_equals(result, 2_i32);
+
+        let result = tester.invoke_scalar(ScalarValue::Null).unwrap();
+        assert!(result.is_null());
+
+        let input_wkt = vec![
+            None,
+            Some("POINT (1 2)"),
+            Some("LINESTRING (0 0, 1 1, 2 2)"),
+            Some("POLYGON EMPTY"),
+            Some("POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))"),
+            Some("POLYGON ((0 0,6 0,6 6,0 6,0 0),(2 2,4 2,4 4,2 4,2 2))"),
+            Some(
+                "POLYGON (
+                    (0 0,10 0,10 6,0 6,0 0),
+                    (1 1,2 1,2 5,1 5,1 1),
+                    (8 5,8 4,9 4,9 5,8 5)
+                )",
+            ),
+            Some(
+                "MULTIPOLYGON (
+                    ((0 0,5 0,5 5,0 5,0 0),(1 1,2 1,2 2,1 2,1 1)),
+                    ((10 10,14 10,14 14,10 14,10 10))
+                )",

Review Comment:
   ```suggestion
                   "MULTIPOLYGON (((0 0,5 0,5 5,0 5,0 0),(1 1,2 1,2 2,1 2,1 1)),((10 10,14 10,14 14,10 14,10 10)))",
   ```



##########
c/sedona-geos/src/st_numinteriorrings.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::sync::Arc;
+
+use crate::executor::GeosExecutor;
+use arrow_array::builder::Int32Builder;
+use arrow_schema::DataType;
+use datafusion_common::{error::Result, DataFusionError};
+use datafusion_expr::ColumnarValue;
+use geos::{Geom, Geometry, GeometryTypes};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+pub fn st_num_interior_rings_impl() -> ScalarKernelRef {
+    Arc::new(STNumInteriorRings {})
+}
+
+#[derive(Debug)]
+struct STNumInteriorRings {}
+
+impl SedonaScalarKernel for STNumInteriorRings {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Int32),
+        );
+
+        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 = Int32Builder::with_capacity(executor.num_iterations());
+        executor.execute_wkb_void(|maybe_geom| {
+            match maybe_geom {
+                None => builder.append_null(),
+                Some(geom) => {
+                    let res = invoke_scalar(&geom)?;
+                    match res {
+                        Some(n) => builder.append_value(n),
+                        None => builder.append_null(),
+                    }
+                }
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(geom: &Geometry) -> Result<Option<i32>> {
+    match geom.geometry_type() {
+        GeometryTypes::Polygon => {
+            let is_empty = geom.is_empty().map_err(|e| {
+                DataFusionError::Execution(format!("Failed to check if geometry is empty: {e}"))
+            })?;
+
+            if is_empty {
+                Ok(Some(0))
+            } else {
+                let count = geom.get_num_interior_rings().map_err(|e| {
+                    DataFusionError::Execution(format!("Failed to get num interior rings: {e}"))
+                })?;
+                Ok(Some(count as i32))
+            }
+        }
+        _ => Ok(None),
+    }
+}
+#[cfg(test)]
+mod tests {
+    use std::sync::Arc;
+
+    use arrow_array::{ArrayRef, Int32Array};
+    use arrow_schema::DataType;
+    use datafusion_common::ScalarValue;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::compare::assert_array_equal;
+    use sedona_testing::testers::ScalarUdfTester;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let udf = SedonaScalarUDF::from_kernel("st_numinteriorrings", st_num_interior_rings_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type]);
+        tester.assert_return_type(DataType::Int32);
+
+        // Polygon with 2 interior rings -> 2
+        let result = tester
+            .invoke_scalar(
+                "POLYGON(
+                    (0 0,10 0,10 6,0 6,0 0),
+                    (1 1,2 1,2 5,1 5,1 1),
+                    (8 5,8 4,9 4,9 5,8 5)
+                )",

Review Comment:
   ```suggestion
                   "POLYGON((0 0,10 0,10 6,0 6,0 0),(1 1,2 1,2 5,1 5,1 1),(8 5,8 4,9 4,9 5,8 5))",
   ```



##########
c/sedona-geos/src/st_numinteriorrings.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::sync::Arc;
+
+use crate::executor::GeosExecutor;
+use arrow_array::builder::Int32Builder;
+use arrow_schema::DataType;
+use datafusion_common::{error::Result, DataFusionError};
+use datafusion_expr::ColumnarValue;
+use geos::{Geom, Geometry, GeometryTypes};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+pub fn st_num_interior_rings_impl() -> ScalarKernelRef {
+    Arc::new(STNumInteriorRings {})
+}
+
+#[derive(Debug)]
+struct STNumInteriorRings {}
+
+impl SedonaScalarKernel for STNumInteriorRings {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Int32),
+        );
+
+        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 = Int32Builder::with_capacity(executor.num_iterations());
+        executor.execute_wkb_void(|maybe_geom| {
+            match maybe_geom {
+                None => builder.append_null(),
+                Some(geom) => {
+                    let res = invoke_scalar(&geom)?;
+                    match res {
+                        Some(n) => builder.append_value(n),
+                        None => builder.append_null(),
+                    }
+                }
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(geom: &Geometry) -> Result<Option<i32>> {
+    match geom.geometry_type() {
+        GeometryTypes::Polygon => {
+            let is_empty = geom.is_empty().map_err(|e| {
+                DataFusionError::Execution(format!("Failed to check if geometry is empty: {e}"))
+            })?;
+
+            if is_empty {
+                Ok(Some(0))
+            } else {
+                let count = geom.get_num_interior_rings().map_err(|e| {
+                    DataFusionError::Execution(format!("Failed to get num interior rings: {e}"))
+                })?;
+                Ok(Some(count as i32))
+            }
+        }
+        _ => Ok(None),
+    }
+}
+#[cfg(test)]
+mod tests {
+    use std::sync::Arc;
+
+    use arrow_array::{ArrayRef, Int32Array};
+    use arrow_schema::DataType;
+    use datafusion_common::ScalarValue;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::compare::assert_array_equal;
+    use sedona_testing::testers::ScalarUdfTester;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let udf = SedonaScalarUDF::from_kernel("st_numinteriorrings", st_num_interior_rings_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type]);
+        tester.assert_return_type(DataType::Int32);
+
+        // Polygon with 2 interior rings -> 2
+        let result = tester
+            .invoke_scalar(
+                "POLYGON(
+                    (0 0,10 0,10 6,0 6,0 0),
+                    (1 1,2 1,2 5,1 5,1 1),
+                    (8 5,8 4,9 4,9 5,8 5)
+                )",

Review Comment:
   nit: There are a few more multiline geometries to collapse to one line. I made a suggestion for each one, if you want to handle that before we merge.



##########
c/sedona-geos/src/st_numinteriorrings.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::sync::Arc;
+
+use crate::executor::GeosExecutor;
+use arrow_array::builder::Int32Builder;
+use arrow_schema::DataType;
+use datafusion_common::{error::Result, DataFusionError};
+use datafusion_expr::ColumnarValue;
+use geos::{Geom, Geometry, GeometryTypes};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+pub fn st_num_interior_rings_impl() -> ScalarKernelRef {
+    Arc::new(STNumInteriorRings {})
+}
+
+#[derive(Debug)]
+struct STNumInteriorRings {}
+
+impl SedonaScalarKernel for STNumInteriorRings {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Int32),
+        );
+
+        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 = Int32Builder::with_capacity(executor.num_iterations());
+        executor.execute_wkb_void(|maybe_geom| {
+            match maybe_geom {
+                None => builder.append_null(),
+                Some(geom) => {
+                    let res = invoke_scalar(&geom)?;
+                    match res {
+                        Some(n) => builder.append_value(n),
+                        None => builder.append_null(),
+                    }
+                }
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(geom: &Geometry) -> Result<Option<i32>> {
+    match geom.geometry_type() {
+        GeometryTypes::Polygon => {
+            let is_empty = geom.is_empty().map_err(|e| {
+                DataFusionError::Execution(format!("Failed to check if geometry is empty: {e}"))
+            })?;
+
+            if is_empty {
+                Ok(Some(0))
+            } else {
+                let count = geom.get_num_interior_rings().map_err(|e| {
+                    DataFusionError::Execution(format!("Failed to get num interior rings: {e}"))
+                })?;
+                Ok(Some(count as i32))
+            }
+        }
+        _ => Ok(None),
+    }
+}
+#[cfg(test)]
+mod tests {
+    use std::sync::Arc;
+
+    use arrow_array::{ArrayRef, Int32Array};
+    use arrow_schema::DataType;
+    use datafusion_common::ScalarValue;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::compare::assert_array_equal;
+    use sedona_testing::testers::ScalarUdfTester;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let udf = SedonaScalarUDF::from_kernel("st_numinteriorrings", st_num_interior_rings_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type]);
+        tester.assert_return_type(DataType::Int32);
+
+        // Polygon with 2 interior rings -> 2
+        let result = tester
+            .invoke_scalar(
+                "POLYGON(
+                    (0 0,10 0,10 6,0 6,0 0),
+                    (1 1,2 1,2 5,1 5,1 1),
+                    (8 5,8 4,9 4,9 5,8 5)
+                )",
+            )
+            .unwrap();
+        tester.assert_scalar_result_equals(result, 2_i32);
+
+        let result = tester.invoke_scalar(ScalarValue::Null).unwrap();
+        assert!(result.is_null());
+
+        let input_wkt = vec![
+            None,
+            Some("POINT (1 2)"),
+            Some("LINESTRING (0 0, 1 1, 2 2)"),
+            Some("POLYGON EMPTY"),
+            Some("POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))"),
+            Some("POLYGON ((0 0,6 0,6 6,0 6,0 0),(2 2,4 2,4 4,2 4,2 2))"),
+            Some(
+                "POLYGON (
+                    (0 0,10 0,10 6,0 6,0 0),
+                    (1 1,2 1,2 5,1 5,1 1),
+                    (8 5,8 4,9 4,9 5,8 5)
+                )",

Review Comment:
   ```suggestion
                   "POLYGON ((0 0,10 0,10 6,0 6,0 0),(1 1,2 1,2 5,1 5,1 1),(8 5,8 4,9 4,9 5,8 5))",
   ```



##########
c/sedona-geos/src/st_numinteriorrings.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::sync::Arc;
+
+use crate::executor::GeosExecutor;
+use arrow_array::builder::Int32Builder;
+use arrow_schema::DataType;
+use datafusion_common::{error::Result, DataFusionError};
+use datafusion_expr::ColumnarValue;
+use geos::{Geom, Geometry, GeometryTypes};
+use sedona_expr::scalar_udf::{ScalarKernelRef, SedonaScalarKernel};
+use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher};
+
+pub fn st_num_interior_rings_impl() -> ScalarKernelRef {
+    Arc::new(STNumInteriorRings {})
+}
+
+#[derive(Debug)]
+struct STNumInteriorRings {}
+
+impl SedonaScalarKernel for STNumInteriorRings {
+    fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> {
+        let matcher = ArgMatcher::new(
+            vec![ArgMatcher::is_geometry()],
+            SedonaType::Arrow(DataType::Int32),
+        );
+
+        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 = Int32Builder::with_capacity(executor.num_iterations());
+        executor.execute_wkb_void(|maybe_geom| {
+            match maybe_geom {
+                None => builder.append_null(),
+                Some(geom) => {
+                    let res = invoke_scalar(&geom)?;
+                    match res {
+                        Some(n) => builder.append_value(n),
+                        None => builder.append_null(),
+                    }
+                }
+            }
+            Ok(())
+        })?;
+
+        executor.finish(Arc::new(builder.finish()))
+    }
+}
+
+fn invoke_scalar(geom: &Geometry) -> Result<Option<i32>> {
+    match geom.geometry_type() {
+        GeometryTypes::Polygon => {
+            let is_empty = geom.is_empty().map_err(|e| {
+                DataFusionError::Execution(format!("Failed to check if geometry is empty: {e}"))
+            })?;
+
+            if is_empty {
+                Ok(Some(0))
+            } else {
+                let count = geom.get_num_interior_rings().map_err(|e| {
+                    DataFusionError::Execution(format!("Failed to get num interior rings: {e}"))
+                })?;
+                Ok(Some(count as i32))
+            }
+        }
+        _ => Ok(None),
+    }
+}
+#[cfg(test)]
+mod tests {
+    use std::sync::Arc;
+
+    use arrow_array::{ArrayRef, Int32Array};
+    use arrow_schema::DataType;
+    use datafusion_common::ScalarValue;
+    use rstest::rstest;
+    use sedona_expr::scalar_udf::SedonaScalarUDF;
+    use sedona_schema::datatypes::{SedonaType, WKB_GEOMETRY, WKB_VIEW_GEOMETRY};
+    use sedona_testing::compare::assert_array_equal;
+    use sedona_testing::testers::ScalarUdfTester;
+
+    use super::*;
+
+    #[rstest]
+    fn udf(#[values(WKB_GEOMETRY, WKB_VIEW_GEOMETRY)] sedona_type: SedonaType) {
+        let udf = SedonaScalarUDF::from_kernel("st_numinteriorrings", st_num_interior_rings_impl());
+        let tester = ScalarUdfTester::new(udf.into(), vec![sedona_type]);
+        tester.assert_return_type(DataType::Int32);
+
+        // Polygon with 2 interior rings -> 2
+        let result = tester
+            .invoke_scalar(
+                "POLYGON(
+                    (0 0,10 0,10 6,0 6,0 0),
+                    (1 1,2 1,2 5,1 5,1 1),
+                    (8 5,8 4,9 4,9 5,8 5)
+                )",
+            )
+            .unwrap();
+        tester.assert_scalar_result_equals(result, 2_i32);
+
+        let result = tester.invoke_scalar(ScalarValue::Null).unwrap();
+        assert!(result.is_null());
+
+        let input_wkt = vec![
+            None,
+            Some("POINT (1 2)"),
+            Some("LINESTRING (0 0, 1 1, 2 2)"),
+            Some("POLYGON EMPTY"),
+            Some("POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))"),
+            Some("POLYGON ((0 0,6 0,6 6,0 6,0 0),(2 2,4 2,4 4,2 4,2 2))"),
+            Some(
+                "POLYGON (
+                    (0 0,10 0,10 6,0 6,0 0),
+                    (1 1,2 1,2 5,1 5,1 1),
+                    (8 5,8 4,9 4,9 5,8 5)
+                )",
+            ),
+            Some(
+                "MULTIPOLYGON (
+                    ((0 0,5 0,5 5,0 5,0 0),(1 1,2 1,2 2,1 2,1 1)),
+                    ((10 10,14 10,14 14,10 14,10 10))
+                )",
+            ),
+            Some(
+                "GEOMETRYCOLLECTION (
+                    POINT (1 2),
+                    POLYGON ((0 0,3 0,3 3,0 3,0 0))
+                )",

Review Comment:
   ```suggestion
                   "GEOMETRYCOLLECTION (POINT (1 2),POLYGON ((0 0,3 0,3 3,0 3,0 0)))",
   ```



-- 
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(c/sedona-geos): Add ST_NumInteriorRings [sedona-db]

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

   Merged. Thanks for sticking through it @LakshmiSowmya04!


-- 
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] Add st num interior rings [sedona-db]

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

   Nice, looks like you're making good progress. Fixing some of the rust issues. Now we need to fix the python tests.
   
   Here's a useful tip to help with your local development: Here's how you can execute queries on PostGIS Docker container
   
   1. Start the postgis docker container (for you knowledge it runs this [compose.yml](https://github.com/apache/sedona-db/blob/16d232be0f28441b85801936b270fa43f7edceb4/compose.yml#L4) file.
   ```
   docker compose up -d
   
   # output:
   [+] Running 1/1
    ✔ Container sedona-db-postgis-1  Running0.0s
   ```
   
   2. Assuming it spun up properly, Now you can exec into that to enter the Postgres / PostGIS shell using the container name. It's usually the same for everyone `sedona-db-postgis-1`.
   ```
   docker exec -it sedona-db-postgis-1 psql -U postgres
   
   # output:
   psql (18.0 (Debian 18.0-1.pgdg13+3))
   Type "help" for help.
   
   postgres=# 
   ```
   
   Now you can execute queries locally against PostGIS (which is a correct solution we model SedonaDB after).
   ```
   postgres=# SELECT ST_NumInteriorRings(ST_GeomFromText('POLYGON ((0 0,6 0,6 6,0 6,0 0), (2 2,4 2,4 4,2 4,2 2))'));
   
   -- output:
    st_numinteriorrings 
   ---------------------
                      1
   ```
   
   To help with testing you can copy-paste the geometries you're using in your tests to replace that Polygon in my example query. Based on the error in the [last Python CI run](https://github.com/apache/sedona-db/actions/runs/19741057767/job/56564766173?pr=369), it looks like at least one of the geometries is formatted improperly. You can use PostGIS to iterate and fix it faster.
   
   ```
   FAILED sedonadb/tests/functions/test_functions.py::test_st_numinteriorrings_basic[POLYGON (                (0 0,10 0,10 6,0 6,0 0)                (1 1,2 1,2 5,1 5,1 1),                (8 5,8 4,9 4,9 5,8 5))-2-SedonaDB] - pyarrow.lib.ArrowInvalid: External error: Internal error: WKT parse error: Missing closing parenthesis for type.
   ```
   
   You can see which polygon is problematic there in the error message. What I would do, is spin up the postgis container, and try running the SQL query I wrote above on each of the polygons in your tests. You're probably missing a parentheses somewhere or have an extra 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] Add st num interior rings [sedona-db]

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


##########
python/sedonadb/tests/functions/test_functions.py:
##########
@@ -2698,3 +2698,49 @@ def test_st_snap(eng, input, reference, tolerance, expected):
 def test_st_zmflag(eng, geom, expected):
     eng = eng.create_or_skip()
     eng.assert_query_result(f"SELECT ST_ZmFlag({geom_or_null(geom)})", expected)
+
+
+@pytest.mark.parametrize("eng", [SedonaDB, PostGIS])
+@pytest.mark.parametrize(
+    ("geom", "expected"),
+    [
+        # input -> #output postgis returned
+        (None, None),  # none
+        ("POINT (1 2)", None),  # none
+        ("LINESTRING (0 0, 1 1, 2 2)", None),  # non-polygon -> NULL
+        ("POLYGON EMPTY", 0),  # empty polygon has no interior rings
+        ("POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0))", 0),  # simple polygon, no holes
+        # example query - SELECT ST_NumInteriorRings(ST_GeomFromText('POLYGON((0 0,4 0,4 4,0 4,0 0))')) AS num_rings;
+        (
+            "POLYGON (\
+                (0 0,6 0,6 6,0 6,0 0),\
+                (2 2,4 2,4 4,2 4,2 2))",

Review Comment:
   ```suggestion
               "POLYGON ((0 0,6 0,6 6,0 6,0 0), (2 2,4 2,4 4,2 4,2 2))"
   ```
   
   It's slightly more convenient to write geometries on a single line. It makes it easier to copy-paste for testing on the PostGIS container I mentioned above. I suggest doing this with your other python tests to help you debug easier. This way, you also won't have to worry about backslashes and issues with multiline python strings.



-- 
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