petern48 commented on code in PR #270: URL: https://github.com/apache/sedona-db/pull/270#discussion_r2483798385
########## rust/sedona-functions/src/st_numgeometries.rs: ########## @@ -0,0 +1,182 @@ +// 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::UInt32Builder; +use arrow_schema::DataType; +use datafusion_common::error::{DataFusionError, Result}; +use datafusion_expr::{scalar_doc_sections::DOC_SECTION_OTHER, Documentation, Volatility}; +use sedona_common::sedona_internal_err; +use sedona_expr::scalar_udf::{SedonaScalarKernel, SedonaScalarUDF}; +use sedona_geometry::types::GeometryTypeId; +use sedona_geometry::wkb_header::WkbHeader; +use sedona_schema::{datatypes::SedonaType, matchers::ArgMatcher}; + +use crate::executor::WkbBytesExecutor; + +pub fn st_numgeometries_udf() -> SedonaScalarUDF { + SedonaScalarUDF::new( + "st_numgeometries", + vec![Arc::new(STNumGeometries {})], + Volatility::Immutable, + Some(st_numgeometries_doc()), + ) +} + +fn st_numgeometries_doc() -> Documentation { + Documentation::builder( + DOC_SECTION_OTHER, + "Return the number of geometries in the geometry collection", + "ST_NumGeometries (A: Geometry)", + ) + .with_argument("geom", "geometry: Input geometry") + .with_sql_example("SELECT ST_NumGeometries(ST_GeomFromWKT('GEOMETRYCOLLECTION(POINT(0 0), LINESTRING(0 0, 1 1))'))") + .build() +} + +#[derive(Debug)] +struct STNumGeometries {} + +impl SedonaScalarKernel for STNumGeometries { + fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> { + let matcher = ArgMatcher::new( + vec![ArgMatcher::is_geometry()], + SedonaType::Arrow(DataType::UInt32), + ); + + matcher.match_args(args) + } + + fn invoke_batch( + &self, + arg_types: &[SedonaType], + args: &[datafusion_expr::ColumnarValue], + ) -> Result<datafusion_expr::ColumnarValue> { + let executor = WkbBytesExecutor::new(arg_types, args); + let mut builder = UInt32Builder::with_capacity(executor.num_iterations()); + + executor.execute_wkb_void(|maybe_item| { + match maybe_item { + Some(item) => { + builder.append_value(invoke_scalar(item)?); + } + None => builder.append_null(), + } + Ok(()) + })?; + + executor.finish(Arc::new(builder.finish())) + } +} + +fn invoke_scalar(buf: &[u8]) -> Result<u32> { + let header = WkbHeader::try_new(buf).map_err(|e| DataFusionError::External(Box::new(e)))?; + + let size = header.size(); + if size == 0 { + return Ok(0); + } + + let geometry_type = header + .geometry_type_id() + .map_err(|e| DataFusionError::External(Box::new(e)))?; + match geometry_type { + GeometryTypeId::Point => { + // If POINT EMPTY (represented as POINT (NaN, NaN)), return 0 + let first_xy = header.first_xy(); + if first_xy.0.is_nan() && first_xy.1.is_nan() { Review Comment: I was also thinking about pulling out this logic into a new `is_empty` function, since there are other places we'd want this (e.g ST_IsEmpty). I was thinking about something like one of these in `sedona-geometry` A new method in WkbHeader: ```rust // WkbHeader pub fn is_empty(&self) -> Result<bool>, SedonaGeometryError> { ``` OR a new function in sedona_geometry::is_empty.rs that takes a `WkbHeader` ```rust // proposed function pub fn is_geometry_empty_header( header: WkbHeader, ) -> Result<bool, SedonaGeometryError> { // The Existing function pub fn is_geometry_empty<G: GeometryTrait<T = f64>>( geometry: &G, ) -> Result<bool, SedonaGeometryError> { ``` The former is cleaner imo, but I wasn't sure if you'd agree that it makes sense for `WkbHeader` to have that method. -- 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]
