paleolimbot commented on code in PR #286: URL: https://github.com/apache/sedona-db/pull/286#discussion_r2515508535
########## c/sedona-geos/src/st_polygonize.rs: ########## @@ -0,0 +1,459 @@ +// 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::wkb_to_geos::GEOSWkbFactory; +use arrow_array::{cast::AsArray, types::UInt64Type, Array, ArrayRef}; +use arrow_schema::{DataType, Field, FieldRef}; +use datafusion_common::{cast::as_binary_array, error::Result, DataFusionError, ScalarValue}; +use datafusion_expr::{Accumulator, ColumnarValue}; +use geo_traits::Dimensions; +use geos::Geom; +use sedona_expr::aggregate_udf::{SedonaAccumulator, SedonaAccumulatorRef}; +use sedona_geometry::wkb_factory::write_wkb_geometrycollection_header; +use sedona_schema::{ + datatypes::{SedonaType, WKB_GEOMETRY}, + matchers::ArgMatcher, +}; +use wkb::reader::read_wkb; + +/// ST_Polygonize() aggregate implementation using GEOS +pub fn st_polygonize_impl() -> SedonaAccumulatorRef { + Arc::new(STPolygonize {}) +} + +#[derive(Debug)] +struct STPolygonize {} + +impl SedonaAccumulator for STPolygonize { + fn return_type(&self, args: &[SedonaType]) -> Result<Option<SedonaType>> { + let matcher = ArgMatcher::new(vec![ArgMatcher::is_geometry()], WKB_GEOMETRY); + matcher.match_args(args) + } + + fn accumulator( + &self, + args: &[SedonaType], + _output_type: &SedonaType, + ) -> Result<Box<dyn Accumulator>> { + Ok(Box::new(PolygonizeAccumulator::new(args[0].clone()))) + } + + fn state_fields(&self, _args: &[SedonaType]) -> Result<Vec<FieldRef>> { + Ok(vec![ + Arc::new(Field::new("count", DataType::UInt64, false)), + Arc::new(Field::new("item", DataType::Binary, true)), + ]) + } +} + +#[derive(Debug)] +struct PolygonizeAccumulator { + input_type: SedonaType, + item: Option<Vec<u8>>, + count: usize, +} + +const WKB_HEADER_SIZE: usize = 1 + 4 + 4; + +impl PolygonizeAccumulator { + pub fn new(input_type: SedonaType) -> Self { + let mut item = Vec::new(); + write_wkb_geometrycollection_header(&mut item, Dimensions::Xy, 0) + .expect("Failed to write initial GeometryCollection header"); + + Self { + input_type, + item: Some(item), + count: 0, + } + } + + fn make_wkb_result(&mut self) -> Result<Option<Vec<u8>>> { + if self.count == 0 { + return Ok(None); + } + + let collection_wkb = self.item.as_mut().unwrap(); + let mut header = Vec::new(); + write_wkb_geometrycollection_header(&mut header, Dimensions::Xy, self.count) + .map_err(|e| DataFusionError::Execution(format!("Failed to write header: {e}")))?; + collection_wkb[0..WKB_HEADER_SIZE].copy_from_slice(&header); + + let wkb = read_wkb(collection_wkb) + .map_err(|e| DataFusionError::Execution(format!("Failed to read WKB: {e}")))?; + + let factory = GEOSWkbFactory::new(); + let collection = factory.create(&wkb).map_err(|e| { + DataFusionError::Execution(format!("Failed to create geometry from WKB: {e}")) + })?; + + let num_geoms = collection.get_num_geometries().map_err(|e| { + DataFusionError::Execution(format!("Failed to get number of geometries: {e}")) + })?; + + let mut geos_geoms = Vec::with_capacity(num_geoms); + for i in 0..num_geoms { + let geom = collection.get_geometry_n(i).map_err(|e| { + DataFusionError::Execution(format!("Failed to get geometry {}: {e}", i)) + })?; + // Clone is necessary: get_geometry_n() returns ConstGeometry<'_> which doesn't + // implement Borrow<Geometry>. The GEOS polygonize() function signature requires + // T: Borrow<Geometry>, so we must clone to get owned Geometry instances. + geos_geoms.push(geom.clone()); Review Comment: This is OK! A heap allocation per output item is better than a heap allocation per input item 🙂 -- 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]
